void mpv_decode_mb_internal(MpegEncContext *s, int16_t block[12][64],

                            int is_mpeg12)

{

    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    if(CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration){

        ff_xvmc_decode_mb(s);//xvmc uses pblocks

        return;

    }

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {

       /* print DCT coefficients */

       int i,j;

       av_log(s->avctx, AV_LOG_DEBUG, "DCT coeffs of MB at %dx%d:\n", s->mb_x, s->mb_y);

       for(i=0; i<6; i++){

           for(j=0; j<64; j++){

               av_log(s->avctx, AV_LOG_DEBUG, "%5d",

                      block[i][s->idsp.idct_permutation[j]]);

           }

           av_log(s->avctx, AV_LOG_DEBUG, "\n");

       }

    }

    s->current_picture.qscale_table[mb_xy] = s->qscale;

    /* update DC predictors for P macroblocks */

    if (!s->mb_intra) {

        if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {

            if(s->mbintra_table[mb_xy])

                ff_clean_intra_table_entries(s);

        } else {

            s->last_dc[0] =

            s->last_dc[1] =

            s->last_dc[2] = 128 << s->intra_dc_precision;

        }

    }

    else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))

        s->mbintra_table[mb_xy]=1;

    if ((s->avctx->flags & AV_CODEC_FLAG_PSNR) ||

        !(s->encoding && (s->intra_only || s->pict_type == AV_PICTURE_TYPE_B) &&

          s->avctx->mb_decision != FF_MB_DECISION_RD)) { // FIXME precalc

        uint8_t *dest_y, *dest_cb, *dest_cr;

        int dct_linesize, dct_offset;

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        const int linesize   = s->current_picture.f->linesize[0]; //not s->linesize as this would be wrong for field pics

        const int uvlinesize = s->current_picture.f->linesize[1];

        const int readable= s->pict_type != AV_PICTURE_TYPE_B || s->encoding || s->avctx->draw_horiz_band;

        const int block_size = 8;

        /* avoid copy if macroblock skipped in last frame too */

        /* skip only during decoding as we might trash the buffers during encoding a bit */

        if(!s->encoding){

            uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];

            if (s->mb_skipped) {

                s->mb_skipped= 0;

                assert(s->pict_type!=AV_PICTURE_TYPE_I);

                *mbskip_ptr = 1;

            } else if(!s->current_picture.reference) {

                *mbskip_ptr = 1;

            } else{

                *mbskip_ptr = 0; /* not skipped */

            }

        }

        dct_linesize = linesize << s->interlaced_dct;

        dct_offset   = s->interlaced_dct ? linesize : linesize * block_size;

        if(readable){

            dest_y=  s->dest[0];

            dest_cb= s->dest[1];

            dest_cr= s->dest[2];

        }else{

            dest_y = s->sc.b_scratchpad;

            dest_cb= s->sc.b_scratchpad+16*linesize;

            dest_cr= s->sc.b_scratchpad+32*linesize;

        }

        if (!s->mb_intra) {

            /* motion handling */

            /* decoding or more than one mb_type (MC was already done otherwise) */

            if(!s->encoding){

                if(HAVE_THREADS && s->avctx->active_thread_type&FF_THREAD_FRAME) {

                    if (s->mv_dir & MV_DIR_FORWARD) {

                        ff_thread_await_progress(&s->last_picture_ptr->tf,

                                                 lowest_referenced_row(s, 0),

                                                 0);

                    }

                    if (s->mv_dir & MV_DIR_BACKWARD) {

                        ff_thread_await_progress(&s->next_picture_ptr->tf,

                                                 lowest_referenced_row(s, 1),

                                                 0);

                    }

                }

                op_qpix= s->me.qpel_put;

                if ((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){

                    op_pix = s->hdsp.put_pixels_tab;

                }else{

                    op_pix = s->hdsp.put_no_rnd_pixels_tab;

                }

                if (s->mv_dir & MV_DIR_FORWARD) {

                    ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.f->data, op_pix, op_qpix);

                    op_pix = s->hdsp.avg_pixels_tab;

                    op_qpix= s->me.qpel_avg;

                }

                if (s->mv_dir & MV_DIR_BACKWARD) {

                    ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.f->data, op_pix, op_qpix);

                }

            }

            /* skip dequant / idct if we are really late ;) */

            if(s->avctx->skip_idct){

                if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B)

                   ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I)

                   || s->avctx->skip_idct >= AVDISCARD_ALL)

                    goto skip_idct;

            }

            /* add dct residue */

            if(s->encoding || !(   s->msmpeg4_version || s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO

                                || (s->codec_id==AV_CODEC_ID_MPEG4 && !s->mpeg_quant))){

                add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if (!CONFIG_GRAY || !(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {

                    if (s->chroma_y_shift){

                        add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_linesize >>= 1;

                        dct_offset >>=1;

                        add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            } else if(is_mpeg12 || (s->codec_id != AV_CODEC_ID_WMV2)){

                add_dct(s, block[0], 0, dest_y                          , dct_linesize);

                add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);

                add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);

                add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);

                if (!CONFIG_GRAY || !(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {

                    if(s->chroma_y_shift){//Chroma420

                        add_dct(s, block[4], 4, dest_cb, uvlinesize);

                        add_dct(s, block[5], 5, dest_cr, uvlinesize);

                    }else{

                        //chroma422

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;

                        add_dct(s, block[4], 4, dest_cb, dct_linesize);

                        add_dct(s, block[5], 5, dest_cr, dct_linesize);

                        add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);

                        add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);

                        if(!s->chroma_x_shift){//Chroma444

                            add_dct(s, block[8], 8, dest_cb+8, dct_linesize);

                            add_dct(s, block[9], 9, dest_cr+8, dct_linesize);

                            add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);

                            add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);

                        }

                    }

                }//fi gray

            }

            else if (CONFIG_WMV2_DECODER || CONFIG_WMV2_ENCODER) {

                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);

            }

        } else {

            /* dct only in intra block */

            if(s->encoding || !(s->codec_id==AV_CODEC_ID_MPEG1VIDEO || s->codec_id==AV_CODEC_ID_MPEG2VIDEO)){

                put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if (!CONFIG_GRAY || !(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {

                    if(s->chroma_y_shift){

                        put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_offset >>=1;

                        dct_linesize >>=1;

                        put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            }else{

                s->idsp.idct_put(dest_y,                           dct_linesize, block[0]);

                s->idsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);

                s->idsp.idct_put(dest_y + dct_offset,              dct_linesize, block[2]);

                s->idsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);

                if (!CONFIG_GRAY || !(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {

                    if(s->chroma_y_shift){

                        s->idsp.idct_put(dest_cb, uvlinesize, block[4]);

                        s->idsp.idct_put(dest_cr, uvlinesize, block[5]);

                    }else{

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset   = s->interlaced_dct ? uvlinesize : uvlinesize * 8;

                        s->idsp.idct_put(dest_cb,              dct_linesize, block[4]);

                        s->idsp.idct_put(dest_cr,              dct_linesize, block[5]);

                        s->idsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);

                        s->idsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);

                        if(!s->chroma_x_shift){//Chroma444

                            s->idsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);

                            s->idsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);

                            s->idsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);

                            s->idsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);

                        }

                    }

                }//gray

            }

        }

skip_idct:

        if(!readable){

            s->hdsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);

            s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);

            s->hdsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);

        }

    }

}


static void device_finalize(Object *obj)

{

    NamedGPIOList *ngl, *next;

    DeviceState *dev = DEVICE(obj);

    qemu_opts_del(dev->opts);

    QLIST_FOREACH_SAFE(ngl, &dev->gpios, node, next) {

        QLIST_REMOVE(ngl, node);

        qemu_free_irqs(ngl->in, ngl->num_in);

        g_free(ngl->name);

        g_free(ngl);

        /* ngl->out irqs are owned by the other end and should not be freed

         * here

         */

    }

}


static int vdi_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVVdiState *s = bs->opaque;

    VdiHeader header;

    size_t bmap_size;

    int ret;

    logout("\n");

    ret = bdrv_read(bs->file, 0, (uint8_t *)&header, 1);

    if (ret < 0) {

        goto fail;

    }

    vdi_header_to_cpu(&header);

#if defined(CONFIG_VDI_DEBUG)

    vdi_header_print(&header);

#endif

    if (header.disk_size % SECTOR_SIZE != 0) {

        /* 'VBoxManage convertfromraw' can create images with odd disk sizes.

           We accept them but round the disk size to the next multiple of

           SECTOR_SIZE. */

        logout("odd disk size %" PRIu64 " B, round up\n", header.disk_size);

        header.disk_size += SECTOR_SIZE - 1;

        header.disk_size &= ~(SECTOR_SIZE - 1);

    }

    if (header.signature != VDI_SIGNATURE) {

        error_setg(errp, "Image not in VDI format (bad signature %08x)", header.signature);

        ret = -EINVAL;

        goto fail;

    } else if (header.version != VDI_VERSION_1_1) {

        error_setg(errp, "unsupported VDI image (version %u.%u)",

                   header.version >> 16, header.version & 0xffff);

        ret = -ENOTSUP;

        goto fail;

    } else if (header.offset_bmap % SECTOR_SIZE != 0) {

        /* We only support block maps which start on a sector boundary. */

        error_setg(errp, "unsupported VDI image (unaligned block map offset "

                   "0x%x)", header.offset_bmap);

        ret = -ENOTSUP;

        goto fail;

    } else if (header.offset_data % SECTOR_SIZE != 0) {

        /* We only support data blocks which start on a sector boundary. */

        error_setg(errp, "unsupported VDI image (unaligned data offset 0x%x)",

                   header.offset_data);

        ret = -ENOTSUP;

        goto fail;

    } else if (header.sector_size != SECTOR_SIZE) {

        error_setg(errp, "unsupported VDI image (sector size %u is not %u)",

                   header.sector_size, SECTOR_SIZE);

        ret = -ENOTSUP;

        goto fail;

    } else if (header.block_size != 1 * MiB) {

        error_setg(errp, "unsupported VDI image (sector size %u is not %u)",

                   header.block_size, 1 * MiB);

        ret = -ENOTSUP;

        goto fail;

    } else if (header.disk_size >

               (uint64_t)header.blocks_in_image * header.block_size) {

        error_setg(errp, "unsupported VDI image (disk size %" PRIu64 ", "

                   "image bitmap has room for %" PRIu64 ")",

                   header.disk_size,

                   (uint64_t)header.blocks_in_image * header.block_size);

        ret = -ENOTSUP;

        goto fail;

    } else if (!uuid_is_null(header.uuid_link)) {

        error_setg(errp, "unsupported VDI image (non-NULL link UUID)");

        ret = -ENOTSUP;

        goto fail;

    } else if (!uuid_is_null(header.uuid_parent)) {

        error_setg(errp, "unsupported VDI image (non-NULL parent UUID)");

        ret = -ENOTSUP;

        goto fail;

    }

    bs->total_sectors = header.disk_size / SECTOR_SIZE;

    s->block_size = header.block_size;

    s->block_sectors = header.block_size / SECTOR_SIZE;

    s->bmap_sector = header.offset_bmap / SECTOR_SIZE;

    s->header = header;

    bmap_size = header.blocks_in_image * sizeof(uint32_t);

    bmap_size = (bmap_size + SECTOR_SIZE - 1) / SECTOR_SIZE;

    s->bmap = g_malloc(bmap_size * SECTOR_SIZE);

    ret = bdrv_read(bs->file, s->bmap_sector, (uint8_t *)s->bmap, bmap_size);

    if (ret < 0) {

        goto fail_free_bmap;

    }

    /* Disable migration when vdi images are used */

    error_set(&s->migration_blocker,

              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,

              "vdi", bs->device_name, "live migration");

    migrate_add_blocker(s->migration_blocker);

    return 0;

 fail_free_bmap:

    g_free(s->bmap);

 fail:

    return ret;

}


static void i440fx_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->no_hotplug = 1;

    k->init = i440fx_initfn;

    k->config_write = i440fx_write_config;

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_82441;

    k->revision = 0x02;

    k->class_id = PCI_CLASS_BRIDGE_HOST;

    dc->desc = "Host bridge";

    dc->no_user = 1;

    dc->vmsd = &vmstate_i440fx;

}


int yuv2rgb_c_init_tables (SwsContext *c, const int inv_table[4], int fullRange, int brightness, int contrast, int saturation)

{

    const int isRgb = isBGR(c->dstFormat);

    const int bpp = fmt_depth(c->dstFormat);

    int i;

    uint8_t table_Y[1024];

    uint32_t *table_32 = 0;

    uint16_t *table_16 = 0;

    uint8_t *table_8 = 0;

    uint8_t *table_332 = 0;

    uint8_t *table_121 = 0;

    uint8_t *table_1 = 0;

    int entry_size = 0;

    void *table_r = 0, *table_g = 0, *table_b = 0;

    void *table_start;

    int64_t crv =  inv_table[0];

    int64_t cbu =  inv_table[1];

    int64_t cgu = -inv_table[2];

    int64_t cgv = -inv_table[3];

    int64_t cy  = 1<<16;

    int64_t oy  = 0;

//printf("%lld %lld %lld %lld %lld\n", cy, crv, cbu, cgu, cgv);

    if(!fullRange){

	cy= (cy*255) / 219;

	oy= 16<<16;

    }else{

        crv= (crv*224) / 255;

        cbu= (cbu*224) / 255;

        cgu= (cgu*224) / 255;

        cgv= (cgv*224) / 255;

    }

    cy = (cy *contrast             )>>16;

    crv= (crv*contrast * saturation)>>32;

    cbu= (cbu*contrast * saturation)>>32;

    cgu= (cgu*contrast * saturation)>>32;

    cgv= (cgv*contrast * saturation)>>32;

//printf("%lld %lld %lld %lld %lld\n", cy, crv, cbu, cgu, cgv);

    oy -= 256*brightness;

    for (i = 0; i < 1024; i++) {

	int j;

	j= (cy*(((i - 384)<<16) - oy) + (1<<31))>>32;

	j = (j < 0) ? 0 : ((j > 255) ? 255 : j);

	table_Y[i] = j;

    }

    switch (bpp) {

    case 32:

	table_start= table_32 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint32_t));

	entry_size = sizeof (uint32_t);

	table_r = table_32 + 197;

	table_b = table_32 + 197 + 685;

	table_g = table_32 + 197 + 2*682;

	for (i = -197; i < 256+197; i++)

	    ((uint32_t *)table_r)[i] = table_Y[i+384] << (isRgb ? 16 : 0);

	for (i = -132; i < 256+132; i++)

	    ((uint32_t *)table_g)[i] = table_Y[i+384] << 8;

	for (i = -232; i < 256+232; i++)

	    ((uint32_t *)table_b)[i] = table_Y[i+384] << (isRgb ? 0 : 16);

	break;

    case 24:

	table_start= table_8 = av_malloc ((256 + 2*232) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_g = table_b = table_8 + 232;

	for (i = -232; i < 256+232; i++)

	    ((uint8_t * )table_b)[i] = table_Y[i+384];

	break;

    case 15:

    case 16:

	table_start= table_16 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint16_t));

	entry_size = sizeof (uint16_t);

	table_r = table_16 + 197;

	table_b = table_16 + 197 + 685;

	table_g = table_16 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = table_Y[i+384] >> 3;

	    if (isRgb)

		j <<= ((bpp==16) ? 11 : 10);

	    ((uint16_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = table_Y[i+384] >> ((bpp==16) ? 2 : 3);

	    ((uint16_t *)table_g)[i] = j << 5;

	}

	for (i = -232; i < 256+232; i++) {

	    int j = table_Y[i+384] >> 3;

	    if (!isRgb)

		j <<= ((bpp==16) ? 11 : 10);

	    ((uint16_t *)table_b)[i] = j;

	}

	break;

    case 8:

	table_start= table_332 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_332 + 197;

	table_b = table_332 + 197 + 685;

	table_g = table_332 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = (table_Y[i+384 - 16] + 18)/36;

	    if (isRgb)

		j <<= 5;

	    ((uint8_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = (table_Y[i+384 - 16] + 18)/36;

	    if (!isRgb)

		j <<= 1;

	    ((uint8_t *)table_g)[i] = j << 2;

	}

	for (i = -232; i < 256+232; i++) {

	    int j = (table_Y[i+384 - 37] + 43)/85;

	    if (!isRgb)

		j <<= 6;

	    ((uint8_t *)table_b)[i] = j;

	}

	break;

    case 4:

    case 4|128:

	table_start= table_121 = av_malloc ((197 + 2*682 + 256 + 132) * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_r = table_121 + 197;

	table_b = table_121 + 197 + 685;

	table_g = table_121 + 197 + 2*682;

	for (i = -197; i < 256+197; i++) {

	    int j = table_Y[i+384 - 110] >> 7;

	    if (isRgb)

		j <<= 3;

	    ((uint8_t *)table_r)[i] = j;

	}

	for (i = -132; i < 256+132; i++) {

	    int j = (table_Y[i+384 - 37]+ 43)/85;

	    ((uint8_t *)table_g)[i] = j << 1;

	}

	for (i = -232; i < 256+232; i++) {

	    int j =table_Y[i+384 - 110] >> 7;

	    if (!isRgb)

		j <<= 3;

	    ((uint8_t *)table_b)[i] = j;

	}

	break;

    case 1:

	table_start= table_1 = av_malloc (256*2 * sizeof (uint8_t));

	entry_size = sizeof (uint8_t);

	table_g = table_1;

	table_r = table_b = NULL;

	for (i = 0; i < 256+256; i++) {

	    int j = table_Y[i + 384 - 110]>>7;

	    ((uint8_t *)table_g)[i] = j;

	}

	break;

    default:

	table_start= NULL;

	av_log(c, AV_LOG_ERROR, "%ibpp not supported by yuv2rgb\n", bpp);

	//free mem?

	return -1;

    }

    for (i = 0; i < 256; i++) {

	c->table_rV[i] = (uint8_t *)table_r + entry_size * div_round (crv * (i-128), 76309);

	c->table_gU[i] = (uint8_t *)table_g + entry_size * div_round (cgu * (i-128), 76309);

	c->table_gV[i] = entry_size * div_round (cgv * (i-128), 76309);

	c->table_bU[i] = (uint8_t *)table_b + entry_size * div_round (cbu * (i-128), 76309);

    }

    av_free(c->yuvTable);

    c->yuvTable= table_start;

    return 0;

}


target_ulong helper_udiv(target_ulong a, target_ulong b)

{

    uint64_t x0;

    uint32_t x1;

    x0 = (a & 0xffffffff) | ((int64_t) (env->y) << 32);

    x1 = (b & 0xffffffff);

    if (x1 == 0) {

        raise_exception(TT_DIV_ZERO);

    }

    x0 = x0 / x1;

    if (x0 > 0xffffffff) {

        env->cc_src2 = 1;

        return 0xffffffff;

    } else {

        env->cc_src2 = 0;

        return x0;

    }

}


static direntry_t *create_short_filename(BDRVVVFATState *s,

                                         const char *filename,

                                         unsigned int directory_start)

{

    int i, j = 0;

    direntry_t *entry = array_get_next(&(s->directory));

    const gchar *p, *last_dot = NULL;

    gunichar c;

    bool lossy_conversion = false;

    char tail[11];

    if (!entry) {

        return NULL;

    }

    memset(entry->name, 0x20, sizeof(entry->name));

    /* copy filename and search last dot */

    for (p = filename; ; p = g_utf8_next_char(p)) {

        c = g_utf8_get_char(p);

        if (c == '\0') {

            break;

        } else if (c == '.') {

            if (j == 0) {

                /* '.' at start of filename */

                lossy_conversion = true;

            } else {

                if (last_dot) {

                    lossy_conversion = true;

                }

                last_dot = p;

            }

        } else if (!last_dot) {

            /* first part of the name; copy it */

            uint8_t v = to_valid_short_char(c);

            if (j < 8 && v) {

                entry->name[j++] = v;

            } else {

                lossy_conversion = true;

            }

        }

    }

    /* copy extension (if any) */

    if (last_dot) {

        j = 0;

        for (p = g_utf8_next_char(last_dot); ; p = g_utf8_next_char(p)) {

            c = g_utf8_get_char(p);

            if (c == '\0') {

                break;

            } else {

                /* extension; copy it */

                uint8_t v = to_valid_short_char(c);

                if (j < 3 && v) {

                    entry->name[8 + (j++)] = v;

                } else {

                    lossy_conversion = true;

                }

            }

        }

    }

    if (entry->name[0] == DIR_KANJI) {

        entry->name[0] = DIR_KANJI_FAKE;

    }

    /* numeric-tail generation */

    for (j = 0; j < 8; j++) {

        if (entry->name[j] == ' ') {

            break;

        }

    }

    for (i = lossy_conversion ? 1 : 0; i < 999999; i++) {

        direntry_t *entry1;

        if (i > 0) {

            int len = sprintf(tail, "~%d", i);

            memcpy(entry->name + MIN(j, 8 - len), tail, len);

        }

        for (entry1 = array_get(&(s->directory), directory_start);

             entry1 < entry; entry1++) {

            if (!is_long_name(entry1) &&

                !memcmp(entry1->name, entry->name, 11)) {

                break; /* found dupe */

            }

        }

        if (entry1 == entry) {

            /* no dupe found */

            return entry;

        }

    }

    return NULL;

}


void ff_print_debug_info(MpegEncContext *s, Picture *p)

{

    AVFrame *pict;

    if (s->avctx->hwaccel || !p || !p->mb_type)

        return;

    pict = &p->f;

    if (s->avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {

        int x,y;

        av_log(s->avctx,AV_LOG_DEBUG,"New frame, type: ");

        switch (pict->pict_type) {

        case AV_PICTURE_TYPE_I:

            av_log(s->avctx,AV_LOG_DEBUG,"I\n");

            break;

        case AV_PICTURE_TYPE_P:

            av_log(s->avctx,AV_LOG_DEBUG,"P\n");

            break;

        case AV_PICTURE_TYPE_B:

            av_log(s->avctx,AV_LOG_DEBUG,"B\n");

            break;

        case AV_PICTURE_TYPE_S:

            av_log(s->avctx,AV_LOG_DEBUG,"S\n");

            break;

        case AV_PICTURE_TYPE_SI:

            av_log(s->avctx,AV_LOG_DEBUG,"SI\n");

            break;

        case AV_PICTURE_TYPE_SP:

            av_log(s->avctx,AV_LOG_DEBUG,"SP\n");

            break;

        }

        for (y = 0; y < s->mb_height; y++) {

            for (x = 0; x < s->mb_width; x++) {

                if (s->avctx->debug & FF_DEBUG_SKIP) {

                    int count = s->mbskip_table[x + y * s->mb_stride];

                    if (count > 9)

                        count = 9;

                    av_log(s->avctx, AV_LOG_DEBUG, "%1d", count);

                }

                if (s->avctx->debug & FF_DEBUG_QP) {

                    av_log(s->avctx, AV_LOG_DEBUG, "%2d",

                           p->qscale_table[x + y * s->mb_stride]);

                }

                if (s->avctx->debug & FF_DEBUG_MB_TYPE) {

                    int mb_type = p->mb_type[x + y * s->mb_stride];

                    // Type & MV direction

                    if (IS_PCM(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "P");

                    else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "A");

                    else if (IS_INTRA4x4(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "i");

                    else if (IS_INTRA16x16(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "I");

                    else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "d");

                    else if (IS_DIRECT(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "D");

                    else if (IS_GMC(mb_type) && IS_SKIP(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "g");

                    else if (IS_GMC(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "G");

                    else if (IS_SKIP(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "S");

                    else if (!USES_LIST(mb_type, 1))

                        av_log(s->avctx, AV_LOG_DEBUG, ">");

                    else if (!USES_LIST(mb_type, 0))

                        av_log(s->avctx, AV_LOG_DEBUG, "<");

                    else {

                        assert(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));

                        av_log(s->avctx, AV_LOG_DEBUG, "X");

                    }

                    // segmentation

                    if (IS_8X8(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "+");

                    else if (IS_16X8(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "-");

                    else if (IS_8X16(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "|");

                    else if (IS_INTRA(mb_type) || IS_16X16(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, " ");

                    else

                        av_log(s->avctx, AV_LOG_DEBUG, "?");

                    if (IS_INTERLACED(mb_type))

                        av_log(s->avctx, AV_LOG_DEBUG, "=");

                    else

                        av_log(s->avctx, AV_LOG_DEBUG, " ");

                }

            }

            av_log(s->avctx, AV_LOG_DEBUG, "\n");

        }

    }

}


static int xan_huffman_decode(unsigned char *dest, const unsigned char *src,

    int dest_len)

{

    unsigned char byte = *src++;

    unsigned char ival = byte + 0x16;

    const unsigned char * ptr = src + byte*2;

    unsigned char val = ival;

    unsigned char *dest_end = dest + dest_len;

    GetBitContext gb;

    init_get_bits(&gb, ptr, 0); // FIXME: no src size available

    while ( val != 0x16 ) {

        val = src[val - 0x17 + get_bits1(&gb) * byte];

        if ( val < 0x16 ) {

            if (dest + 1 > dest_end)

                return 0;

            *dest++ = val;

            val = ival;

        }

    }

    return 0;

}


static int kvm_log_stop(CPUPhysMemoryClient *client,

                        target_phys_addr_t phys_addr, ram_addr_t size)

{

    return kvm_dirty_pages_log_change(phys_addr, size, false);

}


void MPV_common_end(MpegEncContext *s)

{

    int i;

    if (s->motion_val)

        free(s->motion_val);

    if (s->h263_pred) {

        free(s->dc_val[0]);

        free(s->ac_val[0]);

        free(s->coded_block);

        free(s->mbintra_table);

    }

    if (s->mbskip_table)

        free(s->mbskip_table);

    for(i=0;i<3;i++) {

        free(s->last_picture_base[i]);

        free(s->next_picture_base[i]);

        if (s->has_b_frames)

            free(s->aux_picture_base[i]);

    }

    s->context_initialized = 0;

}


static void blkdebug_refresh_filename(BlockDriverState *bs, QDict *options)

{

    BDRVBlkdebugState *s = bs->opaque;

    QDict *opts;

    const QDictEntry *e;

    bool force_json = false;

    for (e = qdict_first(options); e; e = qdict_next(options, e)) {

        if (strcmp(qdict_entry_key(e), "config") &&

            strcmp(qdict_entry_key(e), "x-image"))

        {

            force_json = true;

            break;

        }

    }

    if (force_json && !bs->file->bs->full_open_options) {

        /* The config file cannot be recreated, so creating a plain filename

         * is impossible */

        return;

    }

    if (!force_json && bs->file->bs->exact_filename[0]) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "blkdebug:%s:%s", s->config_file ?: "",

                 bs->file->bs->exact_filename);

    }

    opts = qdict_new();

    qdict_put_str(opts, "driver", "blkdebug");

    QINCREF(bs->file->bs->full_open_options);

    qdict_put(opts, "image", bs->file->bs->full_open_options);

    for (e = qdict_first(options); e; e = qdict_next(options, e)) {

        if (strcmp(qdict_entry_key(e), "x-image")) {

            qobject_incref(qdict_entry_value(e));

            qdict_put_obj(opts, qdict_entry_key(e), qdict_entry_value(e));

        }

    }

    bs->full_open_options = opts;

}


static inline int usb_bt_fifo_dequeue(struct usb_hci_in_fifo_s *fifo,

                USBPacket *p)

{

    int len;

    if (likely(!fifo->len))

        return USB_RET_STALL;

    len = MIN(p->len, fifo->fifo[fifo->start].len);

    memcpy(p->data, fifo->fifo[fifo->start].data, len);

    if (len == p->len) {

        fifo->fifo[fifo->start].len -= len;

        fifo->fifo[fifo->start].data += len;

    } else {

        fifo->start ++;

        fifo->start &= CFIFO_LEN_MASK;

        fifo->len --;

    }

    fifo->dstart += len;

    fifo->dlen -= len;

    if (fifo->dstart >= fifo->dsize) {

        fifo->dstart = 0;

        fifo->dsize = DFIFO_LEN_MASK + 1;

    }

    return len;

}


static int block_load(QEMUFile *f, void *opaque, int version_id)

{

    static int banner_printed;

    int len, flags;

    char device_name[256];

    int64_t addr;

    BlockDriverState *bs;

    uint8_t *buf;

    do {

        addr = qemu_get_be64(f);

        flags = addr & ~BDRV_SECTOR_MASK;

        addr >>= BDRV_SECTOR_BITS;

        if (flags & BLK_MIG_FLAG_DEVICE_BLOCK) {

            int ret;

            /* get device name */

            len = qemu_get_byte(f);

            qemu_get_buffer(f, (uint8_t *)device_name, len);

            device_name[len] = '\0';

            bs = bdrv_find(device_name);

            if (!bs) {

                fprintf(stderr, "Error unknown block device %s\n",

                        device_name);

                return -EINVAL;

            }

            buf = qemu_malloc(BLOCK_SIZE);

            qemu_get_buffer(f, buf, BLOCK_SIZE);

            ret = bdrv_write(bs, addr, buf, BDRV_SECTORS_PER_DIRTY_CHUNK);

            qemu_free(buf);

            if (ret < 0) {

                return ret;

            }

        } else if (flags & BLK_MIG_FLAG_PROGRESS) {

            if (!banner_printed) {

                printf("Receiving block device images\n");

                banner_printed = 1;

            }

            printf("Completed %d %%%c", (int)addr,

                   (addr == 100) ? '\n' : '\r');

            fflush(stdout);

        } else if (!(flags & BLK_MIG_FLAG_EOS)) {

            fprintf(stderr, "Unknown flags\n");

            return -EINVAL;

        }

        if (qemu_file_has_error(f)) {

            return -EIO;

        }

    } while (!(flags & BLK_MIG_FLAG_EOS));

    return 0;

}


static int alsa_init_in (HWVoiceIn *hw, struct audsettings *as)

{

    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;

    struct alsa_params_req req;

    struct alsa_params_obt obt;

    snd_pcm_t *handle;

    struct audsettings obt_as;

    req.fmt = aud_to_alsafmt (as->fmt, as->endianness);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.period_size = conf.period_size_in;

    req.buffer_size = conf.buffer_size_in;

    req.size_in_usec = conf.size_in_usec_in;

    req.override_mask =

        (conf.period_size_in_overridden ? 1 : 0) |

        (conf.buffer_size_in_overridden ? 2 : 0);

    if (alsa_open (1, &req, &obt, &handle)) {

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = obt.fmt;

    obt_as.endianness = obt.endianness;

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = obt.samples;

    alsa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!alsa->pcm_buf) {

        dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",

               hw->samples, 1 << hw->info.shift);

        alsa_anal_close1 (&handle);

        return -1;

    }

    alsa->handle = handle;

    return 0;

}


static uint32_t m5206_mbar_readb(void *opaque, target_phys_addr_t offset)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    offset &= 0x3ff;

    if (offset > 0x200) {

        hw_error("Bad MBAR read offset 0x%x", (int)offset);

    }

    if (m5206_mbar_width[offset >> 2] > 1) {

        uint16_t val;

        val = m5206_mbar_readw(opaque, offset & ~1);

        if ((offset & 1) == 0) {

            val >>= 8;

        }

        return val & 0xff;

    }

    return m5206_mbar_read(s, offset, 1);

}


static int vnc_zlib_stop(VncState *vs, int stream_id)

{

    z_streamp zstream = &vs->zlib_stream[stream_id];

    int previous_out;

    // switch back to normal output/zlib buffers

    vs->zlib = vs->output;

    vs->output = vs->zlib_tmp;

    // compress the zlib buffer

    // initialize the stream

    // XXX need one stream per session

    if (zstream->opaque != vs) {

        int err;

        VNC_DEBUG("VNC: initializing zlib stream %d\n", stream_id);

        VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);

        zstream->zalloc = Z_NULL;

        zstream->zfree = Z_NULL;

        err = deflateInit2(zstream, vs->tight_compression, Z_DEFLATED, MAX_WBITS,

                           MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);

        if (err != Z_OK) {

            fprintf(stderr, "VNC: error initializing zlib\n");

            return -1;

        }

        zstream->opaque = vs;

    }

    // XXX what to do if tight_compression changed in between?

    // reserve memory in output buffer

    buffer_reserve(&vs->output, vs->zlib.offset + 64);

    // set pointers

    zstream->next_in = vs->zlib.buffer;

    zstream->avail_in = vs->zlib.offset;

    zstream->next_out = vs->output.buffer + vs->output.offset;

    zstream->avail_out = vs->output.capacity - vs->output.offset;

    zstream->data_type = Z_BINARY;

    previous_out = zstream->total_out;

    // start encoding

    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {

        fprintf(stderr, "VNC: error during zlib compression\n");

        return -1;

    }

    vs->output.offset = vs->output.capacity - zstream->avail_out;

    return zstream->total_out - previous_out;

}


static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,

                      const uint8_t **poutbuf, int *poutbuf_size,

                      const uint8_t *buf, int buf_size)

{

    FLACParseContext *fpc = s->priv_data;

    FLACHeaderMarker *curr;

    int nb_headers;

    const uint8_t *read_end   = buf;

    const uint8_t *read_start = buf;

    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {

        FLACFrameInfo fi;

        if (frame_header_is_valid(avctx, buf, &fi)) {

            s->duration = fi.blocksize;

            if (!avctx->sample_rate)

                avctx->sample_rate = fi.samplerate;

            if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS){

                fpc->pc->pts = fi.frame_or_sample_num;

                if (!fi.is_var_size)

                  fpc->pc->pts *= fi.blocksize;

            }

        }

        *poutbuf      = buf;

        *poutbuf_size = buf_size;

        return buf_size;

    }

    fpc->avctx = avctx;

    if (fpc->best_header_valid)

        return get_best_header(fpc, poutbuf, poutbuf_size);

    /* If a best_header was found last call remove it with the buffer data. */

    if (fpc->best_header && fpc->best_header->best_child) {

        FLACHeaderMarker *temp;

        FLACHeaderMarker *best_child = fpc->best_header->best_child;

        /* Remove headers in list until the end of the best_header. */

        for (curr = fpc->headers; curr != best_child; curr = temp) {

            if (curr != fpc->best_header) {

                av_log(avctx, AV_LOG_DEBUG,

                       "dropping low score %i frame header from offset %i to %i\n",

                       curr->max_score, curr->offset, curr->next->offset);

            }

            temp = curr->next;

            av_freep(&curr->link_penalty);

            av_free(curr);

        }

        /* Release returned data from ring buffer. */

        av_fifo_drain(fpc->fifo_buf, best_child->offset);

        /* Fix the offset for the headers remaining to match the new buffer. */

        for (curr = best_child->next; curr; curr = curr->next)

            curr->offset -= best_child->offset;

        best_child->offset = 0;

        fpc->headers       = best_child;

        if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {

            fpc->best_header = best_child;

            return get_best_header(fpc, poutbuf, poutbuf_size);

        }

        fpc->best_header   = NULL;

    } else if (fpc->best_header) {

        /* No end frame no need to delete the buffer; probably eof */

        FLACHeaderMarker *temp;

        for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {

            temp = curr->next;

            av_freep(&curr->link_penalty);

            av_free(curr);

        }

        fpc->headers = fpc->best_header->next;

        av_freep(&fpc->best_header->link_penalty);

        av_freep(&fpc->best_header);

    }

    /* Find and score new headers.                                     */

    /* buf_size is to zero when padding, so check for this since we do */

    /* not want to try to read more input once we have found the end.  */

    /* Note that as (non-modified) parameters, buf can be non-NULL,    */

    /* while buf_size is 0.                                            */

    while ((buf && buf_size && read_end < buf + buf_size &&

            fpc->nb_headers_buffered < FLAC_MIN_HEADERS)

           || ((!buf || !buf_size) && !fpc->end_padded)) {

        int start_offset;

        /* Pad the end once if EOF, to check the final region for headers. */

        if (!buf || !buf_size) {

            fpc->end_padded      = 1;

            buf_size = MAX_FRAME_HEADER_SIZE;

            read_end = read_start + MAX_FRAME_HEADER_SIZE;

        } else {

            /* The maximum read size is the upper-bound of what the parser

               needs to have the required number of frames buffered */

            int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;

            read_end       = read_end + FFMIN(buf + buf_size - read_end,

                                              nb_desired * FLAC_AVG_FRAME_SIZE);

        }

        if (!av_fifo_space(fpc->fifo_buf) &&

            av_fifo_size(fpc->fifo_buf) / FLAC_AVG_FRAME_SIZE >

            fpc->nb_headers_buffered * 20) {

            /* There is less than one valid flac header buffered for 20 headers

             * buffered. Therefore the fifo is most likely filled with invalid

             * data and the input is not a flac file. */

            goto handle_error;

        }

        /* Fill the buffer. */

        if (   av_fifo_space(fpc->fifo_buf) < read_end - read_start

            && av_fifo_realloc2(fpc->fifo_buf, (read_end - read_start) + 2*av_fifo_size(fpc->fifo_buf)) < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "couldn't reallocate buffer of size %"PTRDIFF_SPECIFIER"\n",

                   (read_end - read_start) + av_fifo_size(fpc->fifo_buf));

            goto handle_error;

        }

        if (buf && buf_size) {

            av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,

                                  read_end - read_start, NULL);

        } else {

            int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };

            av_fifo_generic_write(fpc->fifo_buf, (void*) pad, sizeof(pad), NULL);

        }

        /* Tag headers and update sequences. */

        start_offset = av_fifo_size(fpc->fifo_buf) -

                       ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));

        start_offset = FFMAX(0, start_offset);

        nb_headers   = find_new_headers(fpc, start_offset);

        if (nb_headers < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "find_new_headers couldn't allocate FLAC header\n");

            goto handle_error;

        }

        fpc->nb_headers_buffered = nb_headers;

        /* Wait till FLAC_MIN_HEADERS to output a valid frame. */

        if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {

            if (buf && read_end < buf + buf_size) {

                read_start = read_end;

                continue;

            } else {

                goto handle_error;

            }

        }

        /* If headers found, update the scores since we have longer chains. */

        if (fpc->end_padded || fpc->nb_headers_found)

            score_sequences(fpc);

        /* restore the state pre-padding */

        if (fpc->end_padded) {

            int warp = fpc->fifo_buf->wptr - fpc->fifo_buf->buffer < MAX_FRAME_HEADER_SIZE;

            /* HACK: drain the tail of the fifo */

            fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;

            fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;

            if (warp) {

                fpc->fifo_buf->wptr += fpc->fifo_buf->end -

                    fpc->fifo_buf->buffer;

            }

            buf_size = 0;

            read_start = read_end = NULL;

        }

    }

    for (curr = fpc->headers; curr; curr = curr->next) {

        if (curr->max_score > 0 &&

            (!fpc->best_header || curr->max_score > fpc->best_header->max_score)) {

            fpc->best_header = curr;

        }

    }

    if (fpc->best_header) {

        fpc->best_header_valid = 1;

        if (fpc->best_header->offset > 0) {

            /* Output a junk frame. */

            av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",

                   fpc->best_header->offset);

            /* Set duration to 0. It is unknown or invalid in a junk frame. */

            s->duration = 0;

            *poutbuf_size     = fpc->best_header->offset;

            *poutbuf          = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,

                                                    &fpc->wrap_buf,

                                                    &fpc->wrap_buf_allocated_size);

            return buf_size ? (read_end - buf) : (fpc->best_header->offset -

                                           av_fifo_size(fpc->fifo_buf));

        }

        if (!buf_size)

            return get_best_header(fpc, poutbuf, poutbuf_size);

    }

handle_error:

    *poutbuf      = NULL;

    *poutbuf_size = 0;

    return buf_size ? read_end - buf : 0;

}


int ff_init_vlc_sparse(VLC *vlc, int nb_bits, int nb_codes,

             const void *bits, int bits_wrap, int bits_size,

             const void *codes, int codes_wrap, int codes_size,

             const void *symbols, int symbols_wrap, int symbols_size,

             int flags)

{

    VLCcode *buf;

    int i, j, ret;

    vlc->bits = nb_bits;

    if(flags & INIT_VLC_USE_NEW_STATIC){

        VLC dyn_vlc = *vlc;

        if (vlc->table_size)

            return 0;

        ret = ff_init_vlc_sparse(&dyn_vlc, nb_bits, nb_codes,

                                 bits, bits_wrap, bits_size,

                                 codes, codes_wrap, codes_size,

                                 symbols, symbols_wrap, symbols_size,

                                 flags & ~INIT_VLC_USE_NEW_STATIC);

        av_assert0(ret >= 0);

        av_assert0(dyn_vlc.table_size <= vlc->table_allocated);

        if(dyn_vlc.table_size < vlc->table_allocated)

            av_log(NULL, AV_LOG_ERROR, "needed %d had %d\n", dyn_vlc.table_size, vlc->table_allocated);

        memcpy(vlc->table, dyn_vlc.table, dyn_vlc.table_size * sizeof(*vlc->table));

        vlc->table_size = dyn_vlc.table_size;

        ff_free_vlc(&dyn_vlc);

        return 0;

    }else {

        vlc->table = NULL;

        vlc->table_allocated = 0;

        vlc->table_size = 0;

    }

    av_dlog(NULL, "build table nb_codes=%d\n", nb_codes);

    buf = av_malloc((nb_codes+1)*sizeof(VLCcode));

    av_assert0(symbols_size <= 2 || !symbols);

    j = 0;

#define COPY(condition)\

    for (i = 0; i < nb_codes; i++) {\

        GET_DATA(buf[j].bits, bits, i, bits_wrap, bits_size);\

        if (!(condition))\

            continue;\

        if (buf[j].bits > 3*nb_bits || buf[j].bits>32) {\

            av_log(NULL, AV_LOG_ERROR, "Too long VLC in init_vlc\n");\

            return -1;\

        }\

        GET_DATA(buf[j].code, codes, i, codes_wrap, codes_size);\

        if (buf[j].code >= (1LL<<buf[j].bits)) {\

            av_log(NULL, AV_LOG_ERROR, "Invalid code in init_vlc\n");\

            return -1;\

        }\

        if (flags & INIT_VLC_LE)\

            buf[j].code = bitswap_32(buf[j].code);\

        else\

            buf[j].code <<= 32 - buf[j].bits;\

        if (symbols)\

            GET_DATA(buf[j].symbol, symbols, i, symbols_wrap, symbols_size)\

        else\

            buf[j].symbol = i;\

        j++;\

    }

    COPY(buf[j].bits > nb_bits);

    // qsort is the slowest part of init_vlc, and could probably be improved or avoided

    qsort(buf, j, sizeof(VLCcode), compare_vlcspec);

    COPY(buf[j].bits && buf[j].bits <= nb_bits);

    nb_codes = j;

    ret = build_table(vlc, nb_bits, nb_codes, buf, flags);

    av_free(buf);

    if (ret < 0) {

        av_freep(&vlc->table);

        return -1;

    }

    return 0;

}


static void idr(H264Context *h){

    int i;

    ff_h264_remove_all_refs(h);

    h->prev_frame_num= 0;

    h->prev_frame_num_offset= 0;

    h->prev_poc_msb=

    h->prev_poc_lsb= 0;

    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)

        h->last_pocs[i] = INT_MIN;

}


static void cg3_initfn(Object *obj)

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    CG3State *s = CG3(obj);

    memory_region_init_ram(&s->rom, NULL, "cg3.prom", FCODE_MAX_ROM_SIZE,

                           &error_abort);

    memory_region_set_readonly(&s->rom, true);

    sysbus_init_mmio(sbd, &s->rom);

    memory_region_init_io(&s->reg, NULL, &cg3_reg_ops, s, "cg3.reg",

                          CG3_REG_SIZE);

    sysbus_init_mmio(sbd, &s->reg);

}


int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)

{

    int id, sr, ch, ba, tag, bps;

    id  = avctx->codec_id;

    sr  = avctx->sample_rate;

    ch  = avctx->channels;

    ba  = avctx->block_align;

    tag = avctx->codec_tag;

    bps = av_get_exact_bits_per_sample(avctx->codec_id);

    /* codecs with an exact constant bits per sample */

    if (bps > 0 && ch > 0 && frame_bytes > 0)

        return (frame_bytes * 8) / (bps * ch);

    bps = avctx->bits_per_coded_sample;

    /* codecs with a fixed packet duration */

    switch (id) {

    case CODEC_ID_ADPCM_ADX:    return   32;

    case CODEC_ID_ADPCM_IMA_QT: return   64;

    case CODEC_ID_ADPCM_EA_XAS: return  128;

    case CODEC_ID_AMR_NB:

    case CODEC_ID_GSM:

    case CODEC_ID_QCELP:

    case CODEC_ID_RA_144:

    case CODEC_ID_RA_288:       return  160;

    case CODEC_ID_IMC:          return  256;

    case CODEC_ID_AMR_WB:

    case CODEC_ID_GSM_MS:       return  320;

    case CODEC_ID_MP1:          return  384;

    case CODEC_ID_ATRAC1:       return  512;

    case CODEC_ID_ATRAC3:       return 1024;

    case CODEC_ID_MP2:

    case CODEC_ID_MUSEPACK7:    return 1152;

    case CODEC_ID_AC3:          return 1536;

    }

    if (sr > 0) {

        /* calc from sample rate */

        if (id == CODEC_ID_TTA)

            return 256 * sr / 245;

        if (ch > 0) {

            /* calc from sample rate and channels */

            if (id == CODEC_ID_BINKAUDIO_DCT)

                return (480 << (sr / 22050)) / ch;

        }

    }

    if (ba > 0) {

        /* calc from block_align */

        if (id == CODEC_ID_SIPR) {

            switch (ba) {

            case 20: return 160;

            case 19: return 144;

            case 29: return 288;

            case 37: return 480;

            }

        }

    }

    if (frame_bytes > 0) {

        /* calc from frame_bytes only */

        if (id == CODEC_ID_TRUESPEECH)

            return 240 * (frame_bytes / 32);

        if (id == CODEC_ID_NELLYMOSER)

            return 256 * (frame_bytes / 64);

        if (bps > 0) {

            /* calc from frame_bytes and bits_per_coded_sample */

            if (id == CODEC_ID_ADPCM_G726)

                return frame_bytes * 8 / bps;

        }

        if (ch > 0) {

            /* calc from frame_bytes and channels */

            switch (id) {

            case CODEC_ID_ADPCM_4XM:

            case CODEC_ID_ADPCM_IMA_ISS:

                return (frame_bytes - 4 * ch) * 2 / ch;

            case CODEC_ID_ADPCM_IMA_SMJPEG:

                return (frame_bytes - 4) * 2 / ch;

            case CODEC_ID_ADPCM_IMA_AMV:

                return (frame_bytes - 8) * 2 / ch;

            case CODEC_ID_ADPCM_XA:

                return (frame_bytes / 128) * 224 / ch;

            case CODEC_ID_INTERPLAY_DPCM:

                return (frame_bytes - 6 - ch) / ch;

            case CODEC_ID_ROQ_DPCM:

                return (frame_bytes - 8) / ch;

            case CODEC_ID_XAN_DPCM:

                return (frame_bytes - 2 * ch) / ch;

            case CODEC_ID_MACE3:

                return 3 * frame_bytes / ch;

            case CODEC_ID_MACE6:

                return 6 * frame_bytes / ch;

            case CODEC_ID_PCM_LXF:

                return 2 * (frame_bytes / (5 * ch));

            }

            if (tag) {

                /* calc from frame_bytes, channels, and codec_tag */

                if (id == CODEC_ID_SOL_DPCM) {

                    if (tag == 3)

                        return frame_bytes / ch;

                    else

                        return frame_bytes * 2 / ch;

                }

            }

            if (ba > 0) {

                /* calc from frame_bytes, channels, and block_align */

                int blocks = frame_bytes / ba;

                switch (avctx->codec_id) {

                case CODEC_ID_ADPCM_IMA_WAV:

                    return blocks * (1 + (ba - 4 * ch) / (4 * ch) * 8);

                case CODEC_ID_ADPCM_IMA_DK3:

                    return blocks * (((ba - 16) * 2 / 3 * 4) / ch);

                case CODEC_ID_ADPCM_IMA_DK4:

                    return blocks * (1 + (ba - 4 * ch) * 2 / ch);

                case CODEC_ID_ADPCM_MS:

                    return blocks * (2 + (ba - 7 * ch) * 2 / ch);

                }

            }

            if (bps > 0) {

                /* calc from frame_bytes, channels, and bits_per_coded_sample */

                switch (avctx->codec_id) {

                case CODEC_ID_PCM_DVD:

                    return 2 * (frame_bytes / ((bps * 2 / 8) * ch));

                case CODEC_ID_PCM_BLURAY:

                    return frame_bytes / ((FFALIGN(ch, 2) * bps) / 8);

                case CODEC_ID_S302M:

                    return 2 * (frame_bytes / ((bps + 4) / 4)) / ch;

                }

            }

        }

    }

    return 0;

}


static void parse_context_init(SchroParseUnitContext *parse_ctx,

                               const uint8_t *buf, int buf_size)

{

    parse_ctx->buf           = buf;

    parse_ctx->buf_size      = buf_size;

}


static int update_size(AVCodecContext *ctx, int w, int h)

{

    VP9Context *s = ctx->priv_data;

    uint8_t *p;

    if (s->above_partition_ctx && w == ctx->width && h == ctx->height)

        return 0;

    ctx->width  = w;

    ctx->height = h;

    s->sb_cols  = (w + 63) >> 6;

    s->sb_rows  = (h + 63) >> 6;

    s->cols     = (w + 7) >> 3;

    s->rows     = (h + 7) >> 3;

#define assign(var, type, n) var = (type) p; p += s->sb_cols * n * sizeof(*var)

    av_free(s->above_partition_ctx);

    p = av_malloc(s->sb_cols * (240 + sizeof(*s->lflvl) + 16 * sizeof(*s->above_mv_ctx) +

                                64 * s->sb_rows * (1 + sizeof(*s->mv[0]) * 2)));

    if (!p)

        return AVERROR(ENOMEM);

    assign(s->above_partition_ctx, uint8_t *,              8);

    assign(s->above_skip_ctx,      uint8_t *,              8);

    assign(s->above_txfm_ctx,      uint8_t *,              8);

    assign(s->above_mode_ctx,      uint8_t *,             16);

    assign(s->above_y_nnz_ctx,     uint8_t *,             16);

    assign(s->above_uv_nnz_ctx[0], uint8_t *,              8);

    assign(s->above_uv_nnz_ctx[1], uint8_t *,              8);

    assign(s->intra_pred_data[0],  uint8_t *,             64);

    assign(s->intra_pred_data[1],  uint8_t *,             32);

    assign(s->intra_pred_data[2],  uint8_t *,             32);

    assign(s->above_segpred_ctx,   uint8_t *,              8);

    assign(s->above_intra_ctx,     uint8_t *,              8);

    assign(s->above_comp_ctx,      uint8_t *,              8);

    assign(s->above_ref_ctx,       uint8_t *,              8);

    assign(s->above_filter_ctx,    uint8_t *,              8);

    assign(s->lflvl,               struct VP9Filter *,     1);

    assign(s->above_mv_ctx,        VP56mv(*)[2],          16);

    assign(s->segmentation_map,    uint8_t *,             64 * s->sb_rows);

    assign(s->mv[0],               struct VP9mvrefPair *, 64 * s->sb_rows);

    assign(s->mv[1],               struct VP9mvrefPair *, 64 * s->sb_rows);

#undef assign

    return 0;

}


static int smacker_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    SmackerContext *smk = s->priv_data;

    int flags;

    int ret;

    int i;

    int frame_size = 0;

    int palchange = 0;

    if (s->pb->eof_reached || smk->cur_frame >= smk->frames)

        return AVERROR_EOF;

    /* if we demuxed all streams, pass another frame */

    if(smk->curstream < 0) {

        avio_seek(s->pb, smk->nextpos, 0);

        frame_size = smk->frm_size[smk->cur_frame] & (~3);

        flags = smk->frm_flags[smk->cur_frame];

        /* handle palette change event */

        if(flags & SMACKER_PAL){

            int size, sz, t, off, j, pos;

            uint8_t *pal = smk->pal;

            uint8_t oldpal[768];

            memcpy(oldpal, pal, 768);

            size = avio_r8(s->pb);

            size = size * 4 - 1;

            frame_size -= size;

            frame_size--;

            sz = 0;

            pos = avio_tell(s->pb) + size;

            while(sz < 256){

                t = avio_r8(s->pb);

                if(t & 0x80){ /* skip palette entries */

                    sz += (t & 0x7F) + 1;

                    pal += ((t & 0x7F) + 1) * 3;

                } else if(t & 0x40){ /* copy with offset */

                    off = avio_r8(s->pb);

                    j = (t & 0x3F) + 1;

                    if (off + j > 0x100) {

                        av_log(s, AV_LOG_ERROR,

                               "Invalid palette update, offset=%d length=%d extends beyond palette size\n",

                               off, j);

                        return AVERROR_INVALIDDATA;

                    }

                    off *= 3;

                    while(j-- && sz < 256) {

                        *pal++ = oldpal[off + 0];

                        *pal++ = oldpal[off + 1];

                        *pal++ = oldpal[off + 2];

                        sz++;

                        off += 3;

                    }

                } else { /* new entries */

                    *pal++ = smk_pal[t];

                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];

                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];

                    sz++;

                }

            }

            avio_seek(s->pb, pos, 0);

            palchange |= 1;

        }

        flags >>= 1;

        smk->curstream = -1;

        /* if audio chunks are present, put them to stack and retrieve later */

        for(i = 0; i < 7; i++) {

            if(flags & 1) {

                uint32_t size;

                uint8_t *tmpbuf;

                size = avio_rl32(s->pb) - 4;

                if (!size || size > frame_size) {

                    av_log(s, AV_LOG_ERROR, "Invalid audio part size\n");

                    return AVERROR_INVALIDDATA;

                }

                frame_size -= size;

                frame_size -= 4;

                smk->curstream++;

                tmpbuf = av_realloc(smk->bufs[smk->curstream], size);

                if (!tmpbuf)

                    return AVERROR(ENOMEM);

                smk->bufs[smk->curstream] = tmpbuf;

                smk->buf_sizes[smk->curstream] = size;

                ret = avio_read(s->pb, smk->bufs[smk->curstream], size);

                if(ret != size)

                    return AVERROR(EIO);

                smk->stream_id[smk->curstream] = smk->indexes[i];

            }

            flags >>= 1;

        }

        if (frame_size < 0)

            return AVERROR_INVALIDDATA;

        if (av_new_packet(pkt, frame_size + 769))

            return AVERROR(ENOMEM);

        if(smk->frm_size[smk->cur_frame] & 1)

            palchange |= 2;

        pkt->data[0] = palchange;

        memcpy(pkt->data + 1, smk->pal, 768);

        ret = avio_read(s->pb, pkt->data + 769, frame_size);

        if(ret != frame_size)

            return AVERROR(EIO);

        pkt->stream_index = smk->videoindex;

        pkt->pts          = smk->cur_frame;

        pkt->size = ret + 769;

        smk->cur_frame++;

        smk->nextpos = avio_tell(s->pb);

    } else {

        if (smk->stream_id[smk->curstream] < 0)

            return AVERROR_INVALIDDATA;

        if (av_new_packet(pkt, smk->buf_sizes[smk->curstream]))

            return AVERROR(ENOMEM);

        memcpy(pkt->data, smk->bufs[smk->curstream], smk->buf_sizes[smk->curstream]);

        pkt->size = smk->buf_sizes[smk->curstream];

        pkt->stream_index = smk->stream_id[smk->curstream];

        pkt->pts = smk->aud_pts[smk->curstream];

        smk->aud_pts[smk->curstream] += AV_RL32(pkt->data);

        smk->curstream--;

    }

    return 0;

}


static void wm8750_audio_out_cb(void *opaque, int free_b)

{

    struct wm8750_s *s = (struct wm8750_s *) opaque;

    wm8750_out_flush(s);

    s->req_out = free_b;

    s->data_req(s->opaque, free_b >> 2, s->req_in >> 2);

}


static void unix_process_msgfd(CharDriverState *chr, struct msghdr *msg)
{
    TCPCharDriver *s = chr->opaque;
    struct cmsghdr *cmsg;
    for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) {
        int fd;
        if (cmsg->cmsg_len != CMSG_LEN(sizeof(int)) ||
            cmsg->cmsg_level != SOL_SOCKET ||
            cmsg->cmsg_type != SCM_RIGHTS)
            continue;
        fd = *((int *)CMSG_DATA(cmsg));
        if (fd < 0)
            continue;
#ifndef MSG_CMSG_CLOEXEC
        qemu_set_cloexec(fd);
#endif
        if (s->msgfd != -1)
            close(s->msgfd);
        s->msgfd = fd;
    }
}


void ga_channel_free(GAChannel *c)

{

    if (c->method == GA_CHANNEL_UNIX_LISTEN

        && c->listen_channel) {

        ga_channel_listen_close(c);

    }

    if (c->client_channel) {

        ga_channel_client_close(c);

    }

    g_free(c);

}


ram_addr_t qemu_ram_alloc_from_ptr(ram_addr_t size, void *host,

                                   MemoryRegion *mr, Error **errp)

{

    RAMBlock *new_block;

    ram_addr_t addr;

    Error *local_err = NULL;

    size = TARGET_PAGE_ALIGN(size);

    new_block = g_malloc0(sizeof(*new_block));

    new_block->mr = mr;

    new_block->used_length = size;

    new_block->max_length = max_size;

    new_block->fd = -1;

    new_block->host = host;

    if (host) {

        new_block->flags |= RAM_PREALLOC;

    }

    addr = ram_block_add(new_block, &local_err);

    if (local_err) {

        g_free(new_block);

        error_propagate(errp, local_err);

        return -1;

    }

    return addr;

}


void kvm_s390_io_interrupt(S390CPU *cpu, uint16_t subchannel_id,

                           uint16_t subchannel_nr, uint32_t io_int_parm,

                           uint32_t io_int_word)

{

    uint32_t type;

    if (io_int_word & IO_INT_WORD_AI) {

        type = KVM_S390_INT_IO(1, 0, 0, 0);

    } else {

        type = ((subchannel_id & 0xff00) << 24) |

            ((subchannel_id & 0x00060) << 22) | (subchannel_nr << 16);

    }

    kvm_s390_interrupt_internal(cpu, type,

                                ((uint32_t)subchannel_id << 16) | subchannel_nr,

                                ((uint64_t)io_int_parm << 32) | io_int_word, 1);

}


static void elcr_ioport_write(void *opaque, target_phys_addr_t addr,

                              uint64_t val, unsigned size)

{

    PICCommonState *s = opaque;

    s->elcr = val & s->elcr_mask;

}


void nonono(const char* file, int line, const char* msg) {

    fprintf(stderr, "Nonono! %s:%d %s\n", file, line, msg);

    exit(-5);

}


static void spitz_i2c_setup(PXA2xxState *cpu)

{

    /* Attach the CPU on one end of our I2C bus.  */

    i2c_bus *bus = pxa2xx_i2c_bus(cpu->i2c[0]);

#ifdef HAS_AUDIO

    DeviceState *wm;

    /* Attach a WM8750 to the bus */

    wm = i2c_create_slave(bus, "wm8750", 0);

    spitz_wm8750_addr(wm, 0, 0);

    pxa2xx_gpio_out_set(cpu->gpio, SPITZ_GPIO_WM,

                    qemu_allocate_irqs(spitz_wm8750_addr, wm, 1)[0]);

    /* .. and to the sound interface.  */

    cpu->i2s->opaque = wm;

    cpu->i2s->codec_out = wm8750_dac_dat;

    cpu->i2s->codec_in = wm8750_adc_dat;

    wm8750_data_req_set(wm, cpu->i2s->data_req, cpu->i2s);

#endif

}


static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)

{

    OutputStream *ost = ofilter->ost;

    AVCodecContext *codec  = ost->st->codec;

    AVFilterContext *last_filter = out->filter_ctx;

    int pad_idx = out->pad_idx;

    char *sample_fmts, *sample_rates, *channel_layouts;

    char name[255];

    int ret;

    snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);

    ret = avfilter_graph_create_filter(&ofilter->filter,

                                       avfilter_get_by_name("ffabuffersink"),

                                       name, NULL, NULL, fg->graph);

    if (ret < 0)

        return ret;

#define AUTO_INSERT_FILTER(opt_name, filter_name, arg) do {                 \

    AVFilterContext *filt_ctx;                                              \

                                                                            \

    av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \

           "similarly to -af " filter_name "=%s.\n", arg);                  \

                                                                            \

    ret = avfilter_graph_create_filter(&filt_ctx,                           \

                                       avfilter_get_by_name(filter_name),   \

                                       filter_name, arg, NULL, fg->graph);  \

    if (ret < 0)                                                            \

        return ret;                                                         \

                                                                            \

    ret = avfilter_link(last_filter, pad_idx, filt_ctx, 0);                 \

    if (ret < 0)                                                            \

        return ret;                                                         \

                                                                            \

    last_filter = filt_ctx;                                                 \

    pad_idx = 0;                                                            \

} while (0)

    if (ost->audio_channels_mapped) {

        int i;

        AVBPrint pan_buf;

        av_bprint_init(&pan_buf, 256, 8192);

        av_bprintf(&pan_buf, "0x%"PRIx64,

                   av_get_default_channel_layout(ost->audio_channels_mapped));

        for (i = 0; i < ost->audio_channels_mapped; i++)

            if (ost->audio_channels_map[i] != -1)

                av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);

        AUTO_INSERT_FILTER("-map_channel", "pan", pan_buf.str);

        av_bprint_finalize(&pan_buf, NULL);

    }

    if (codec->channels && !codec->channel_layout)

        codec->channel_layout = av_get_default_channel_layout(codec->channels);

    sample_fmts     = choose_sample_fmts(ost);

    sample_rates    = choose_sample_rates(ost);

    channel_layouts = choose_channel_layouts(ost);

    if (sample_fmts || sample_rates || channel_layouts) {

        AVFilterContext *format;

        char args[256];

        int len = 0;

        if (sample_fmts)

            len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",

                            sample_fmts);

        if (sample_rates)

            len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",

                            sample_rates);

        if (channel_layouts)

            len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",

                            channel_layouts);

        args[len - 1] = 0;

        av_freep(&sample_fmts);

        av_freep(&sample_rates);

        av_freep(&channel_layouts);

        snprintf(name, sizeof(name), "audio format for output stream %d:%d",

                 ost->file_index, ost->index);

        ret = avfilter_graph_create_filter(&format,

                                           avfilter_get_by_name("aformat"),

                                           name, args, NULL, fg->graph);

        if (ret < 0)

            return ret;

        ret = avfilter_link(last_filter, pad_idx, format, 0);

        if (ret < 0)

            return ret;

        last_filter = format;

        pad_idx = 0;

    }

    if (audio_volume != 256 && 0) {

        char args[256];

        snprintf(args, sizeof(args), "%f", audio_volume / 256.);

        AUTO_INSERT_FILTER("-vol", "volume", args);

    }

    if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)

        return ret;

    return 0;

}


void restore_boot_order(void *opaque)

{

    char *normal_boot_order = opaque;

    static int first = 1;

    /* Restore boot order and remove ourselves after the first boot */

    if (first) {

        first = 0;

        return;

    }

    qemu_boot_set(normal_boot_order);

    qemu_unregister_reset(restore_boot_order, normal_boot_order);

    g_free(normal_boot_order);

}


static int virtser_port_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    VirtIOSerialPort *port = DO_UPCAST(VirtIOSerialPort, dev, qdev);

    VirtIOSerialPortInfo *info = DO_UPCAST(VirtIOSerialPortInfo, qdev, base);

    VirtIOSerialBus *bus = DO_UPCAST(VirtIOSerialBus, qbus, qdev->parent_bus);

    int ret, max_nr_ports;

    bool plugging_port0;

    port->vser = bus->vser;

    port->bh = qemu_bh_new(flush_queued_data_bh, port);

    /*

     * Is the first console port we're seeing? If so, put it up at

     * location 0. This is done for backward compatibility (old

     * kernel, new qemu).

     */

    plugging_port0 = port->is_console && !find_port_by_id(port->vser, 0);

    if (find_port_by_id(port->vser, port->id)) {

        error_report("virtio-serial-bus: A port already exists at id %u\n",

                     port->id);

        return -1;

    }

    if (port->id == VIRTIO_CONSOLE_BAD_ID) {

        if (plugging_port0) {

            port->id = 0;

        } else {

            port->id = find_free_port_id(port->vser);

            if (port->id == VIRTIO_CONSOLE_BAD_ID) {

                error_report("virtio-serial-bus: Maximum port limit for this device reached\n");

                return -1;

            }

        }

    }

    max_nr_ports = tswap32(port->vser->config.max_nr_ports);

    if (port->id >= max_nr_ports) {

        error_report("virtio-serial-bus: Out-of-range port id specified, max. allowed: %u\n",

                     max_nr_ports - 1);

        return -1;

    }

    port->info = info;

    ret = info->init(port);

    if (ret) {

        return ret;

    }

    if (!use_multiport(port->vser)) {

        /*

         * Allow writes to guest in this case; we have no way of

         * knowing if a guest port is connected.

         */

        port->guest_connected = true;

    }

    port->elem.out_num = 0;

    QTAILQ_INSERT_TAIL(&port->vser->ports, port, next);

    port->ivq = port->vser->ivqs[port->id];

    port->ovq = port->vser->ovqs[port->id];

    add_port(port->vser, port->id);

    /* Send an update to the guest about this new port added */

    virtio_notify_config(&port->vser->vdev);

    return ret;

}


void block_job_pause(BlockJob *job)

{

    job->paused = true;

}


static void prop_get_fdt(Object *obj, Visitor *v, const char *name,

                         void *opaque, Error **errp)

{

    sPAPRDRConnector *drc = SPAPR_DR_CONNECTOR(obj);

    Error *err = NULL;

    int fdt_offset_next, fdt_offset, fdt_depth;

    void *fdt;

    if (!drc->fdt) {

        visit_type_null(v, NULL, errp);

        return;

    }

    fdt = drc->fdt;

    fdt_offset = drc->fdt_start_offset;

    fdt_depth = 0;

    do {

        const char *name = NULL;

        const struct fdt_property *prop = NULL;

        int prop_len = 0, name_len = 0;

        uint32_t tag;

        tag = fdt_next_tag(fdt, fdt_offset, &fdt_offset_next);

        switch (tag) {

        case FDT_BEGIN_NODE:

            fdt_depth++;

            name = fdt_get_name(fdt, fdt_offset, &name_len);

            visit_start_struct(v, name, NULL, 0, &err);

            if (err) {

                error_propagate(errp, err);

                return;

            }

            break;

        case FDT_END_NODE:

            /* shouldn't ever see an FDT_END_NODE before FDT_BEGIN_NODE */

            g_assert(fdt_depth > 0);

            visit_check_struct(v, &err);

            visit_end_struct(v);

            if (err) {

                error_propagate(errp, err);

                return;

            }

            fdt_depth--;

            break;

        case FDT_PROP: {

            int i;

            prop = fdt_get_property_by_offset(fdt, fdt_offset, &prop_len);

            name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));

            visit_start_list(v, name, &err);

            if (err) {

                error_propagate(errp, err);

                return;

            }

            for (i = 0; i < prop_len; i++) {

                visit_type_uint8(v, NULL, (uint8_t *)&prop->data[i], &err);

                if (err) {

                    error_propagate(errp, err);

                    return;

                }

            }

            visit_end_list(v);

            break;

        }

        default:

            error_setg(&error_abort, "device FDT in unexpected state: %d", tag);

        }

        fdt_offset = fdt_offset_next;

    } while (fdt_depth != 0);

}


int bdrv_pwrite(BlockDriverState *bs, int64_t offset,

                const void *buf, int bytes)

{

    QEMUIOVector qiov;

    struct iovec iov = {

        .iov_base   = (void *) buf,

        .iov_len    = bytes,

    };

    if (bytes < 0) {

        return -EINVAL;

    }

    qemu_iovec_init_external(&qiov, &iov, 1);

    return bdrv_pwritev(bs, offset, &qiov);

}


static int ppc_fixup_cpu(PowerPCCPU *cpu)

{

    CPUPPCState *env = &cpu->env;

    /* TCG doesn't (yet) emulate some groups of instructions that

     * are implemented on some otherwise supported CPUs (e.g. VSX

     * and decimal floating point instructions on POWER7).  We

     * remove unsupported instruction groups from the cpu state's

     * instruction masks and hope the guest can cope.  For at

     * least the pseries machine, the unavailability of these

     * instructions can be advertised to the guest via the device

     * tree. */

    if ((env->insns_flags & ~PPC_TCG_INSNS)

        || (env->insns_flags2 & ~PPC_TCG_INSNS2)) {

        fprintf(stderr, "Warning: Disabling some instructions which are not "

                "emulated by TCG (0x%" PRIx64 ", 0x%" PRIx64 ")\n",

                env->insns_flags & ~PPC_TCG_INSNS,

                env->insns_flags2 & ~PPC_TCG_INSNS2);

    }

    env->insns_flags &= PPC_TCG_INSNS;

    env->insns_flags2 &= PPC_TCG_INSNS2;

    return 0;

}


void main_loop_wait(int timeout)

{

    IOHandlerRecord *ioh;

    fd_set rfds, wfds, xfds;

    int ret, nfds;

    struct timeval tv;

    qemu_bh_update_timeout(&timeout);

    host_main_loop_wait(&timeout);

    /* poll any events */

    /* XXX: separate device handlers from system ones */

    nfds = -1;

    FD_ZERO(&rfds);

    FD_ZERO(&wfds);

    FD_ZERO(&xfds);

    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {

        if (ioh->deleted)

            continue;

        if (ioh->fd_read &&

            (!ioh->fd_read_poll ||

             ioh->fd_read_poll(ioh->opaque) != 0)) {

            FD_SET(ioh->fd, &rfds);

            if (ioh->fd > nfds)

                nfds = ioh->fd;

        }

        if (ioh->fd_write) {

            FD_SET(ioh->fd, &wfds);

            if (ioh->fd > nfds)

                nfds = ioh->fd;

        }

    }

    tv.tv_sec = timeout / 1000;

    tv.tv_usec = (timeout % 1000) * 1000;

    slirp_select_fill(&nfds, &rfds, &wfds, &xfds);

    qemu_mutex_unlock_iothread();

    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);

    qemu_mutex_lock_iothread();

    if (ret > 0) {

        IOHandlerRecord **pioh;

        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {

            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {

                ioh->fd_read(ioh->opaque);

            }

            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {

                ioh->fd_write(ioh->opaque);

            }

        }

	/* remove deleted IO handlers */

	pioh = &first_io_handler;

	while (*pioh) {

            ioh = *pioh;

            if (ioh->deleted) {

                *pioh = ioh->next;

                qemu_free(ioh);

            } else

                pioh = &ioh->next;

        }

    }

    slirp_select_poll(&rfds, &wfds, &xfds, (ret < 0));

    /* rearm timer, if not periodic */

    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {

        alarm_timer->flags &= ~ALARM_FLAG_EXPIRED;

        qemu_rearm_alarm_timer(alarm_timer);

    }

    /* vm time timers */

    if (vm_running) {

        if (!cur_cpu || likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))

            qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],

                qemu_get_clock(vm_clock));

    }

    /* real time timers */

    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],

                    qemu_get_clock(rt_clock));

    /* Check bottom-halves last in case any of the earlier events triggered

       them.  */

    qemu_bh_poll();

}


av_cold int ff_rate_control_init(MpegEncContext *s)

{

    RateControlContext *rcc = &s->rc_context;

    int i, res;

    static const char * const const_names[] = {

        "PI",

        "E",

        "iTex",

        "pTex",

        "tex",

        "mv",

        "fCode",

        "iCount",

        "mcVar",

        "var",

        "isI",

        "isP",

        "isB",

        "avgQP",

        "qComp",

#if 0

        "lastIQP",

        "lastPQP",

        "lastBQP",

        "nextNonBQP",

#endif

        "avgIITex",

        "avgPITex",

        "avgPPTex",

        "avgBPTex",

        "avgTex",

        NULL

    };

    static double (* const func1[])(void *, double) = {

        (void *)bits2qp,

        (void *)qp2bits,

        NULL

    };

    static const char * const func1_names[] = {

        "bits2qp",

        "qp2bits",

        NULL

    };

    emms_c();

    res = av_expr_parse(&rcc->rc_eq_eval,

                        s->rc_eq ? s->rc_eq : "tex^qComp",

                        const_names, func1_names, func1,

                        NULL, NULL, 0, s->avctx);

    if (res < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->rc_eq);

        return res;

    }

    for (i = 0; i < 5; i++) {

        rcc->pred[i].coeff = FF_QP2LAMBDA * 7.0;

        rcc->pred[i].count = 1.0;

        rcc->pred[i].decay = 0.4;

        rcc->i_cplx_sum [i] =

        rcc->p_cplx_sum [i] =

        rcc->mv_bits_sum[i] =

        rcc->qscale_sum [i] =

        rcc->frame_count[i] = 1; // 1 is better because of 1/0 and such

        rcc->last_qscale_for[i] = FF_QP2LAMBDA * 5;

    }

    rcc->buffer_index = s->avctx->rc_initial_buffer_occupancy;

    if (s->avctx->flags & CODEC_FLAG_PASS2) {

        int i;

        char *p;

        /* find number of pics */

        p = s->avctx->stats_in;

        for (i = -1; p; i++)

            p = strchr(p + 1, ';');

        i += s->max_b_frames;

        if (i <= 0 || i >= INT_MAX / sizeof(RateControlEntry))

            return -1;

        rcc->entry       = av_mallocz(i * sizeof(RateControlEntry));

        rcc->num_entries = i;

        /* init all to skipped p frames

         * (with b frames we might have a not encoded frame at the end FIXME) */

        for (i = 0; i < rcc->num_entries; i++) {

            RateControlEntry *rce = &rcc->entry[i];

            rce->pict_type  = rce->new_pict_type = AV_PICTURE_TYPE_P;

            rce->qscale     = rce->new_qscale    = FF_QP2LAMBDA * 2;

            rce->misc_bits  = s->mb_num + 10;

            rce->mb_var_sum = s->mb_num * 100;

        }

        /* read stats */

        p = s->avctx->stats_in;

        for (i = 0; i < rcc->num_entries - s->max_b_frames; i++) {

            RateControlEntry *rce;

            int picture_number;

            int e;

            char *next;

            next = strchr(p, ';');

            if (next) {

                (*next) = 0; // sscanf in unbelievably slow on looong strings // FIXME copy / do not write

                next++;

            }

            e = sscanf(p, " in:%d ", &picture_number);

            assert(picture_number >= 0);

            assert(picture_number < rcc->num_entries);

            rce = &rcc->entry[picture_number];

            e += sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d",

                        &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits,

                        &rce->mv_bits, &rce->misc_bits,

                        &rce->f_code, &rce->b_code,

                        &rce->mc_mb_var_sum, &rce->mb_var_sum,

                        &rce->i_count, &rce->skip_count, &rce->header_bits);

            if (e != 14) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "statistics are damaged at line %d, parser out=%d\n",

                       i, e);

                return -1;

            }

            p = next;

        }

        if (init_pass2(s) < 0)

            return -1;

        // FIXME maybe move to end

        if ((s->avctx->flags & CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {

#if CONFIG_LIBXVID

            return ff_xvid_rate_control_init(s);

#else

            av_log(s->avctx, AV_LOG_ERROR,

                   "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");

            return -1;

#endif

        }

    }

    if (!(s->avctx->flags & CODEC_FLAG_PASS2)) {

        rcc->short_term_qsum   = 0.001;

        rcc->short_term_qcount = 0.001;

        rcc->pass1_rc_eq_output_sum = 0.001;

        rcc->pass1_wanted_bits      = 0.001;

        if (s->avctx->qblur > 1.0) {

            av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");

            return -1;

        }

        /* init stuff with the user specified complexity */

        if (s->rc_initial_cplx) {

            for (i = 0; i < 60 * 30; i++) {

                double bits = s->rc_initial_cplx * (i / 10000.0 + 1.0) * s->mb_num;

                RateControlEntry rce;

                if (i % ((s->gop_size + 3) / 4) == 0)

                    rce.pict_type = AV_PICTURE_TYPE_I;

                else if (i % (s->max_b_frames + 1))

                    rce.pict_type = AV_PICTURE_TYPE_B;

                else

                    rce.pict_type = AV_PICTURE_TYPE_P;

                rce.new_pict_type = rce.pict_type;

                rce.mc_mb_var_sum = bits * s->mb_num / 100000;

                rce.mb_var_sum    = s->mb_num;

                rce.qscale    = FF_QP2LAMBDA * 2;

                rce.f_code    = 2;

                rce.b_code    = 1;

                rce.misc_bits = 1;

                if (s->pict_type == AV_PICTURE_TYPE_I) {

                    rce.i_count    = s->mb_num;

                    rce.i_tex_bits = bits;

                    rce.p_tex_bits = 0;

                    rce.mv_bits    = 0;

                } else {

                    rce.i_count    = 0; // FIXME we do know this approx

                    rce.i_tex_bits = 0;

                    rce.p_tex_bits = bits * 0.9;

                    rce.mv_bits    = bits * 0.1;

                }

                rcc->i_cplx_sum[rce.pict_type]  += rce.i_tex_bits * rce.qscale;

                rcc->p_cplx_sum[rce.pict_type]  += rce.p_tex_bits * rce.qscale;

                rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;

                rcc->frame_count[rce.pict_type]++;

                get_qscale(s, &rce, rcc->pass1_wanted_bits / rcc->pass1_rc_eq_output_sum, i);

                // FIXME misbehaves a little for variable fps

                rcc->pass1_wanted_bits += s->bit_rate / (1 / av_q2d(s->avctx->time_base));

            }

        }

    }

    return 0;

}


av_cold void ff_sws_init_swscale_x86(SwsContext *c)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_MMX_INLINE

    if (INLINE_MMX(cpu_flags))

        sws_init_swscale_mmx(c);

#endif

#if HAVE_MMXEXT_INLINE

    if (INLINE_MMXEXT(cpu_flags))

        sws_init_swscale_mmxext(c);

#endif

#define ASSIGN_SCALE_FUNC2(hscalefn, filtersize, opt1, opt2) do { \

    if (c->srcBpc == 8) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale8to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale8to19_ ## filtersize ## _ ## opt1; \

    } else if (c->srcBpc == 9) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale9to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale9to19_ ## filtersize ## _ ## opt1; \

    } else if (c->srcBpc == 10) { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale10to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale10to19_ ## filtersize ## _ ## opt1; \

    } else /* c->srcBpc == 16 */ { \

        hscalefn = c->dstBpc <= 10 ? ff_hscale16to15_ ## filtersize ## _ ## opt2 : \

                                     ff_hscale16to19_ ## filtersize ## _ ## opt1; \

    } \

} while (0)

#define ASSIGN_MMX_SCALE_FUNC(hscalefn, filtersize, opt1, opt2) \

    switch (filtersize) { \

    case 4:  ASSIGN_SCALE_FUNC2(hscalefn, 4, opt1, opt2); break; \

    case 8:  ASSIGN_SCALE_FUNC2(hscalefn, 8, opt1, opt2); break; \

    default: ASSIGN_SCALE_FUNC2(hscalefn, X, opt1, opt2); break; \

    }

#define ASSIGN_VSCALEX_FUNC(vscalefn, opt, do_16_case, condition_8bit) \

switch(c->dstBpc){ \

    case 16:                          do_16_case;                          break; \

    case 10: if (!isBE(c->dstFormat)) vscalefn = ff_yuv2planeX_10_ ## opt; break; \

    case 9:  if (!isBE(c->dstFormat)) vscalefn = ff_yuv2planeX_9_  ## opt; break; \

    default: if (condition_8bit)      vscalefn = ff_yuv2planeX_8_  ## opt; break; \

    }

#define ASSIGN_VSCALE_FUNC(vscalefn, opt1, opt2, opt2chk) \

    switch(c->dstBpc){ \

    case 16: if (!isBE(c->dstFormat))            vscalefn = ff_yuv2plane1_16_ ## opt1; break; \

    case 10: if (!isBE(c->dstFormat) && opt2chk) vscalefn = ff_yuv2plane1_10_ ## opt2; break; \

    case 9:  if (!isBE(c->dstFormat) && opt2chk) vscalefn = ff_yuv2plane1_9_  ## opt2;  break; \

    default:                                     vscalefn = ff_yuv2plane1_8_  ## opt1;  break; \

    }

#define case_rgb(x, X, opt) \

        case AV_PIX_FMT_ ## X: \

            c->lumToYV12 = ff_ ## x ## ToY_ ## opt; \

            if (!c->chrSrcHSubSample) \

                c->chrToYV12 = ff_ ## x ## ToUV_ ## opt; \

            break

#if ARCH_X86_32

    if (EXTERNAL_MMX(cpu_flags)) {

        ASSIGN_MMX_SCALE_FUNC(c->hyScale, c->hLumFilterSize, mmx, mmx);

        ASSIGN_MMX_SCALE_FUNC(c->hcScale, c->hChrFilterSize, mmx, mmx);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, mmx, mmxext, cpu_flags & AV_CPU_FLAG_MMXEXT);

        switch (c->srcFormat) {

        case AV_PIX_FMT_YA8:

            c->lumToYV12 = ff_yuyvToY_mmx;

            if (c->alpPixBuf)

                c->alpToYV12 = ff_uyvyToY_mmx;

            break;

        case AV_PIX_FMT_YUYV422:

            c->lumToYV12 = ff_yuyvToY_mmx;

            c->chrToYV12 = ff_yuyvToUV_mmx;

            break;

        case AV_PIX_FMT_UYVY422:

            c->lumToYV12 = ff_uyvyToY_mmx;

            c->chrToYV12 = ff_uyvyToUV_mmx;

            break;

        case AV_PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_mmx;

            break;

        case AV_PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_mmx;

            break;

        case_rgb(rgb24, RGB24, mmx);

        case_rgb(bgr24, BGR24, mmx);

        case_rgb(bgra,  BGRA,  mmx);

        case_rgb(rgba,  RGBA,  mmx);

        case_rgb(abgr,  ABGR,  mmx);

        case_rgb(argb,  ARGB,  mmx);

        default:

            break;

        }

    }

    if (EXTERNAL_MMXEXT(cpu_flags)) {

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, mmxext, , 1);

    }

#endif /* ARCH_X86_32 */

#define ASSIGN_SSE_SCALE_FUNC(hscalefn, filtersize, opt1, opt2) \

    switch (filtersize) { \

    case 4:  ASSIGN_SCALE_FUNC2(hscalefn, 4, opt1, opt2); break; \

    case 8:  ASSIGN_SCALE_FUNC2(hscalefn, 8, opt1, opt2); break; \

    default: if (filtersize & 4) ASSIGN_SCALE_FUNC2(hscalefn, X4, opt1, opt2); \

             else                ASSIGN_SCALE_FUNC2(hscalefn, X8, opt1, opt2); \

             break; \

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, sse2, sse2);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, sse2, sse2);

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, sse2, ,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, sse2, sse2, 1);

        switch (c->srcFormat) {

        case AV_PIX_FMT_YA8:

            c->lumToYV12 = ff_yuyvToY_sse2;

            if (c->alpPixBuf)

                c->alpToYV12 = ff_uyvyToY_sse2;

            break;

        case AV_PIX_FMT_YUYV422:

            c->lumToYV12 = ff_yuyvToY_sse2;

            c->chrToYV12 = ff_yuyvToUV_sse2;

            break;

        case AV_PIX_FMT_UYVY422:

            c->lumToYV12 = ff_uyvyToY_sse2;

            c->chrToYV12 = ff_uyvyToUV_sse2;

            break;

        case AV_PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_sse2;

            break;

        case AV_PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_sse2;

            break;

        case_rgb(rgb24, RGB24, sse2);

        case_rgb(bgr24, BGR24, sse2);

        case_rgb(bgra,  BGRA,  sse2);

        case_rgb(rgba,  RGBA,  sse2);

        case_rgb(abgr,  ABGR,  sse2);

        case_rgb(argb,  ARGB,  sse2);

        default:

            break;

        }

    }

    if (EXTERNAL_SSSE3(cpu_flags)) {

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, ssse3, ssse3);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, ssse3, ssse3);

        switch (c->srcFormat) {

        case_rgb(rgb24, RGB24, ssse3);

        case_rgb(bgr24, BGR24, ssse3);

        default:

            break;

        }

    }

    if (EXTERNAL_SSE4(cpu_flags)) {

        /* Xto15 don't need special sse4 functions */

        ASSIGN_SSE_SCALE_FUNC(c->hyScale, c->hLumFilterSize, sse4, ssse3);

        ASSIGN_SSE_SCALE_FUNC(c->hcScale, c->hChrFilterSize, sse4, ssse3);

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, sse4,

                            if (!isBE(c->dstFormat)) c->yuv2planeX = ff_yuv2planeX_16_sse4,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        if (c->dstBpc == 16 && !isBE(c->dstFormat))

            c->yuv2plane1 = ff_yuv2plane1_16_sse4;

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        ASSIGN_VSCALEX_FUNC(c->yuv2planeX, avx, ,

                            HAVE_ALIGNED_STACK || ARCH_X86_64);

        ASSIGN_VSCALE_FUNC(c->yuv2plane1, avx, avx, 1);

        switch (c->srcFormat) {

        case AV_PIX_FMT_YUYV422:

            c->chrToYV12 = ff_yuyvToUV_avx;

            break;

        case AV_PIX_FMT_UYVY422:

            c->chrToYV12 = ff_uyvyToUV_avx;

            break;

        case AV_PIX_FMT_NV12:

            c->chrToYV12 = ff_nv12ToUV_avx;

            break;

        case AV_PIX_FMT_NV21:

            c->chrToYV12 = ff_nv21ToUV_avx;

            break;

        case_rgb(rgb24, RGB24, avx);

        case_rgb(bgr24, BGR24, avx);

        case_rgb(bgra,  BGRA,  avx);

        case_rgb(rgba,  RGBA,  avx);

        case_rgb(abgr,  ABGR,  avx);

        case_rgb(argb,  ARGB,  avx);

        default:

            break;

        }

    }

}


static void libopus_write_header(AVCodecContext *avctx, int stream_count,

                                 int coupled_stream_count,

                                 const uint8_t *channel_mapping)

{

    uint8_t *p   = avctx->extradata;

    int channels = avctx->channels;

    bytestream_put_buffer(&p, "OpusHead", 8);

    bytestream_put_byte(&p, 1); /* Version */

    bytestream_put_byte(&p, channels);

    bytestream_put_le16(&p, avctx->delay); /* Lookahead samples at 48kHz */

    bytestream_put_le32(&p, avctx->sample_rate); /* Original sample rate */

    bytestream_put_le16(&p, 0); /* Gain of 0dB is recommended. */

    /* Channel mapping */

    if (channels > 2) {

        bytestream_put_byte(&p, channels <= 8 ? 1 : 255);

        bytestream_put_byte(&p, stream_count);

        bytestream_put_byte(&p, coupled_stream_count);

        bytestream_put_buffer(&p, channel_mapping, channels);

    } else {

        bytestream_put_byte(&p, 0);

    }

}


static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

#if 1

    int frame_duration = av_rescale(track->timescale, track->enc->time_base.num, track->enc->time_base.den);

    int nb_frames = ROUNDED_DIV(track->enc->time_base.den, track->enc->time_base.num);

    AVDictionaryEntry *t = NULL;

    if (nb_frames > 255) {

        av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);

        return AVERROR(EINVAL);

    }

    avio_wb32(pb, 0); /* size */

    ffio_wfourcc(pb, "tmcd");               /* Data format */

    avio_wb32(pb, 0);                       /* Reserved */

    avio_wb32(pb, 1);                       /* Data reference index */

    avio_wb32(pb, 0);                       /* Flags */

    avio_wb32(pb, track->timecode_flags);   /* Flags (timecode) */

    avio_wb32(pb, track->timescale);        /* Timescale */

    avio_wb32(pb, frame_duration);          /* Frame duration */

    avio_w8(pb, nb_frames);                 /* Number of frames */

    avio_w8(pb, 0);                         /* Reserved */

    if (track->st)

        t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);

    if (t && utf8len(t->value))

        mov_write_source_reference_tag(pb, track, t->value);

    else

        avio_wb16(pb, 0); /* zero size */

#else

    avio_wb32(pb, 0); /* size */

    ffio_wfourcc(pb, "tmcd");               /* Data format */

    avio_wb32(pb, 0);                       /* Reserved */

    avio_wb32(pb, 1);                       /* Data reference index */

    if (track->enc->extradata_size)

        avio_write(pb, track->enc->extradata, track->enc->extradata_size);

#endif

    return update_size(pb, pos);

}