static int read_audio_mux_element(struct LATMContext *latmctx,

                                  GetBitContext *gb)

{

    int err;

    uint8_t use_same_mux = get_bits(gb, 1);

    if (!use_same_mux) {

        if ((err = read_stream_mux_config(latmctx, gb)) < 0)

            return err;

    } else if (!latmctx->aac_ctx.avctx->extradata) {

        av_log(latmctx->aac_ctx.avctx, AV_LOG_DEBUG,

               "no decoder config found\n");

        return AVERROR(EAGAIN);

    }

    if (latmctx->audio_mux_version_A == 0) {

        int mux_slot_length_bytes = read_payload_length_info(latmctx, gb);

        if (mux_slot_length_bytes * 8 > get_bits_left(gb)) {

            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR, "incomplete frame\n");

            return AVERROR_INVALIDDATA;

        } else if (mux_slot_length_bytes * 8 + 256 < get_bits_left(gb)) {

            av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,

                   "frame length mismatch %d << %d\n",

                   mux_slot_length_bytes * 8, get_bits_left(gb));

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static int vpc_has_zero_init(BlockDriverState *bs)

{

    BDRVVPCState *s = bs->opaque;

    VHDFooter *footer =  (VHDFooter *) s->footer_buf;

    if (cpu_to_be32(footer->type) == VHD_FIXED) {

        return bdrv_has_zero_init(bs->file);

    } else {

        return 1;

    }

}


static int mpeg_decode_postinit(AVCodecContext *avctx)

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    uint8_t old_permutation[64];

    int ret;

    if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {

        // MPEG-1 aspect

        avctx->sample_aspect_ratio = av_d2q(1.0 / ff_mpeg1_aspect[s->aspect_ratio_info], 255);

    } else { // MPEG-2

        // MPEG-2 aspect

        if (s->aspect_ratio_info > 1) {

            AVRational dar =

                av_mul_q(av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],

                                  (AVRational) { s1->pan_scan.width,

                                                 s1->pan_scan.height }),

                         (AVRational) { s->width, s->height });

            /* We ignore the spec here and guess a bit as reality does not

             * match the spec, see for example res_change_ffmpeg_aspect.ts

             * and sequence-display-aspect.mpg.

             * issue1613, 621, 562 */

            if ((s1->pan_scan.width == 0) || (s1->pan_scan.height == 0) ||

                (av_cmp_q(dar, (AVRational) { 4, 3 }) &&

                 av_cmp_q(dar, (AVRational) { 16, 9 }))) {

                s->avctx->sample_aspect_ratio =

                    av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],

                             (AVRational) { s->width, s->height });

            } else {

                s->avctx->sample_aspect_ratio =

                    av_div_q(ff_mpeg2_aspect[s->aspect_ratio_info],

                             (AVRational) { s1->pan_scan.width, s1->pan_scan.height });

// issue1613 4/3 16/9 -> 16/9

// res_change_ffmpeg_aspect.ts 4/3 225/44 ->4/3

// widescreen-issue562.mpg 4/3 16/9 -> 16/9

//                s->avctx->sample_aspect_ratio = av_mul_q(s->avctx->sample_aspect_ratio, (AVRational) {s->width, s->height});

                ff_dlog(avctx, "aspect A %d/%d\n",

                        ff_mpeg2_aspect[s->aspect_ratio_info].num,

                        ff_mpeg2_aspect[s->aspect_ratio_info].den);

                ff_dlog(avctx, "aspect B %d/%d\n", s->avctx->sample_aspect_ratio.num,

                        s->avctx->sample_aspect_ratio.den);

            }

        } else {

            s->avctx->sample_aspect_ratio =

                ff_mpeg2_aspect[s->aspect_ratio_info];

        }

    } // MPEG-2

    if (av_image_check_sar(s->width, s->height,

                           avctx->sample_aspect_ratio) < 0) {

        av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",

                avctx->sample_aspect_ratio.num,

                avctx->sample_aspect_ratio.den);

        avctx->sample_aspect_ratio = (AVRational){ 0, 1 };

    }

    if ((s1->mpeg_enc_ctx_allocated == 0)                   ||

        avctx->coded_width       != s->width                ||

        avctx->coded_height      != s->height               ||

        s1->save_width           != s->width                ||

        s1->save_height          != s->height               ||

        av_cmp_q(s1->save_aspect, s->avctx->sample_aspect_ratio) ||

        (s1->save_progressive_seq != s->progressive_sequence && FFALIGN(s->height, 16) != FFALIGN(s->height, 32)) ||

        0) {

        if (s1->mpeg_enc_ctx_allocated) {

            ParseContext pc = s->parse_context;

            s->parse_context.buffer = 0;

            ff_mpv_common_end(s);

            s->parse_context = pc;

            s1->mpeg_enc_ctx_allocated = 0;

        }

        ret = ff_set_dimensions(avctx, s->width, s->height);

        if (ret < 0)

            return ret;

        if (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO && s->bit_rate) {

            avctx->rc_max_rate = s->bit_rate;

        } else if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO && s->bit_rate &&

                   (s->bit_rate != 0x3FFFF*400 || s->vbv_delay != 0xFFFF)) {

            avctx->bit_rate = s->bit_rate;

        }

        s1->save_aspect          = s->avctx->sample_aspect_ratio;

        s1->save_width           = s->width;

        s1->save_height          = s->height;

        s1->save_progressive_seq = s->progressive_sequence;

        /* low_delay may be forced, in this case we will have B-frames

         * that behave like P-frames. */

        avctx->has_b_frames = !s->low_delay;

        if (avctx->codec_id == AV_CODEC_ID_MPEG1VIDEO) {

            // MPEG-1 fps

            avctx->framerate = ff_mpeg12_frame_rate_tab[s->frame_rate_index];

            avctx->ticks_per_frame     = 1;

            avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;

        } else { // MPEG-2

            // MPEG-2 fps

            av_reduce(&s->avctx->framerate.num,

                      &s->avctx->framerate.den,

                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].num * s1->frame_rate_ext.num,

                      ff_mpeg12_frame_rate_tab[s->frame_rate_index].den * s1->frame_rate_ext.den,

                      1 << 30);

            avctx->ticks_per_frame = 2;

            switch (s->chroma_format) {

            case 1: avctx->chroma_sample_location = AVCHROMA_LOC_LEFT; break;

            case 2:

            case 3: avctx->chroma_sample_location = AVCHROMA_LOC_TOPLEFT; break;

            default: av_assert0(0);

            }

        } // MPEG-2

        avctx->pix_fmt = mpeg_get_pixelformat(avctx);

        setup_hwaccel_for_pixfmt(avctx);

        /* Quantization matrices may need reordering

         * if DCT permutation is changed. */

        memcpy(old_permutation, s->idsp.idct_permutation, 64 * sizeof(uint8_t));

        ff_mpv_idct_init(s);

        if ((ret = ff_mpv_common_init(s)) < 0)

            return ret;

        quant_matrix_rebuild(s->intra_matrix,        old_permutation, s->idsp.idct_permutation);

        quant_matrix_rebuild(s->inter_matrix,        old_permutation, s->idsp.idct_permutation);

        quant_matrix_rebuild(s->chroma_intra_matrix, old_permutation, s->idsp.idct_permutation);

        quant_matrix_rebuild(s->chroma_inter_matrix, old_permutation, s->idsp.idct_permutation);

        s1->mpeg_enc_ctx_allocated = 1;

    }

    return 0;

}


static void mxf_write_index_table_segment(AVFormatContext *s)

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    int i, j, temporal_reordering = 0;

    int key_index = mxf->last_key_index;

    av_log(s, AV_LOG_DEBUG, "edit units count %d\n", mxf->edit_units_count);

    if (!mxf->edit_units_count && !mxf->edit_unit_byte_count)

        return;

    avio_write(pb, index_table_segment_key, 16);

    if (mxf->edit_unit_byte_count) {

        klv_encode_ber_length(pb, 80);

    } else {

        klv_encode_ber_length(pb, 85 + 12+(s->nb_streams+1)*6 +

                              12+mxf->edit_units_count*(11+mxf->slice_count*4));

    }

    // instance id

    mxf_write_local_tag(pb, 16, 0x3C0A);

    mxf_write_uuid(pb, IndexTableSegment, 0);

    // index edit rate

    mxf_write_local_tag(pb, 8, 0x3F0B);

    avio_wb32(pb, mxf->time_base.den);

    avio_wb32(pb, mxf->time_base.num);

    // index start position

    mxf_write_local_tag(pb, 8, 0x3F0C);

    avio_wb64(pb, mxf->last_indexed_edit_unit);

    // index duration

    mxf_write_local_tag(pb, 8, 0x3F0D);

    if (mxf->edit_unit_byte_count)

        avio_wb64(pb, 0); // index table covers whole container

    else

        avio_wb64(pb, mxf->edit_units_count);

    // edit unit byte count

    mxf_write_local_tag(pb, 4, 0x3F05);

    avio_wb32(pb, mxf->edit_unit_byte_count);

    // index sid

    mxf_write_local_tag(pb, 4, 0x3F06);

    avio_wb32(pb, 2);

    // body sid

    mxf_write_local_tag(pb, 4, 0x3F07);

    avio_wb32(pb, 1);

    if (!mxf->edit_unit_byte_count) {

        // real slice count - 1

        mxf_write_local_tag(pb, 1, 0x3F08);

        avio_w8(pb, mxf->slice_count);

        // delta entry array

        mxf_write_local_tag(pb, 8 + (s->nb_streams+1)*6, 0x3F09);

        avio_wb32(pb, s->nb_streams+1); // num of entries

        avio_wb32(pb, 6);               // size of one entry

        // write system item delta entry

        avio_w8(pb, 0);

        avio_w8(pb, 0); // slice entry

        avio_wb32(pb, 0); // element delta

        for (i = 0; i < s->nb_streams; i++) {

            AVStream *st = s->streams[i];

            MXFStreamContext *sc = st->priv_data;

            avio_w8(pb, sc->temporal_reordering);

            if (sc->temporal_reordering)

                temporal_reordering = 1;

            if (i == 0) { // video track

                avio_w8(pb, 0); // slice number

                avio_wb32(pb, KAG_SIZE); // system item size including klv fill

            } else { // audio track

                unsigned audio_frame_size = sc->aic.samples[0]*sc->aic.sample_size;

                audio_frame_size += klv_fill_size(audio_frame_size);

                avio_w8(pb, 1);

                avio_wb32(pb, (i-1)*audio_frame_size); // element delta

            }

        }

        mxf_write_local_tag(pb, 8 + mxf->edit_units_count*(11+mxf->slice_count*4), 0x3F0A);

        avio_wb32(pb, mxf->edit_units_count);  // num of entries

        avio_wb32(pb, 11+mxf->slice_count*4);  // size of one entry

        for (i = 0; i < mxf->edit_units_count; i++) {

            int temporal_offset = 0;

            if (!(mxf->index_entries[i].flags & 0x33)) { // I frame

                mxf->last_key_index = key_index;

                key_index = i;

            }

            if (temporal_reordering) {

                int pic_num_in_gop = i - key_index;

                if (pic_num_in_gop != mxf->index_entries[i].temporal_ref) {

                    for (j = key_index; j < mxf->edit_units_count; j++) {

                        if (pic_num_in_gop == mxf->index_entries[j].temporal_ref)

                            break;

                    }

                    if (j == mxf->edit_units_count)

                        av_log(s, AV_LOG_WARNING, "missing frames\n");

                    temporal_offset = j - key_index - pic_num_in_gop;

                }

            }

            avio_w8(pb, temporal_offset);

            if ((mxf->index_entries[i].flags & 0x30) == 0x30) { // back and forward prediction

                avio_w8(pb, mxf->last_key_index - i);

            } else {

                avio_w8(pb, key_index - i); // key frame offset

                if ((mxf->index_entries[i].flags & 0x20) == 0x20) // only forward

                    mxf->last_key_index = key_index;

            }

            if (!(mxf->index_entries[i].flags & 0x33) && // I frame

                mxf->index_entries[i].flags & 0x40 && !temporal_offset)

                mxf->index_entries[i].flags |= 0x80; // random access

            avio_w8(pb, mxf->index_entries[i].flags);

            // stream offset

            avio_wb64(pb, mxf->index_entries[i].offset);

            if (s->nb_streams > 1)

                avio_wb32(pb, mxf->index_entries[i].slice_offset);

        }

        mxf->last_key_index = key_index - mxf->edit_units_count;

        mxf->last_indexed_edit_unit += mxf->edit_units_count;

        mxf->edit_units_count = 0;

    }

}


static int vaapi_h264_decode_slice(AVCodecContext *avctx,

                                   const uint8_t  *buffer,

                                   uint32_t        size)

{

    H264Context * const h = avctx->priv_data;

    H264SliceContext *sl  = &h->slice_ctx[0];

    VASliceParameterBufferH264 *slice_param;

    ff_dlog(avctx, "vaapi_h264_decode_slice(): buffer %p, size %d\n",

            buffer, size);

    /* Fill in VASliceParameterBufferH264. */

    slice_param = (VASliceParameterBufferH264 *)ff_vaapi_alloc_slice(avctx->hwaccel_context, buffer, size);

    if (!slice_param)

        return -1;

    slice_param->slice_data_bit_offset          = get_bits_count(&sl->gb);

    slice_param->first_mb_in_slice              = (sl->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + sl->mb_x;

    slice_param->slice_type                     = ff_h264_get_slice_type(sl);

    slice_param->direct_spatial_mv_pred_flag    = sl->slice_type == AV_PICTURE_TYPE_B ? sl->direct_spatial_mv_pred : 0;

    slice_param->num_ref_idx_l0_active_minus1   = sl->list_count > 0 ? sl->ref_count[0] - 1 : 0;

    slice_param->num_ref_idx_l1_active_minus1   = sl->list_count > 1 ? sl->ref_count[1] - 1 : 0;

    slice_param->cabac_init_idc                 = sl->cabac_init_idc;

    slice_param->slice_qp_delta                 = sl->qscale - h->pps.init_qp;

    slice_param->disable_deblocking_filter_idc  = sl->deblocking_filter < 2 ? !sl->deblocking_filter : sl->deblocking_filter;

    slice_param->slice_alpha_c0_offset_div2     = sl->slice_alpha_c0_offset / 2;

    slice_param->slice_beta_offset_div2         = sl->slice_beta_offset     / 2;

    slice_param->luma_log2_weight_denom         = sl->pwt.luma_log2_weight_denom;

    slice_param->chroma_log2_weight_denom       = sl->pwt.chroma_log2_weight_denom;

    fill_vaapi_RefPicList(slice_param->RefPicList0, sl->ref_list[0], sl->list_count > 0 ? sl->ref_count[0] : 0);

    fill_vaapi_RefPicList(slice_param->RefPicList1, sl->ref_list[1], sl->list_count > 1 ? sl->ref_count[1] : 0);

    fill_vaapi_plain_pred_weight_table(h, 0,

                                       &slice_param->luma_weight_l0_flag,   slice_param->luma_weight_l0,   slice_param->luma_offset_l0,

                                       &slice_param->chroma_weight_l0_flag, slice_param->chroma_weight_l0, slice_param->chroma_offset_l0);

    fill_vaapi_plain_pred_weight_table(h, 1,

                                       &slice_param->luma_weight_l1_flag,   slice_param->luma_weight_l1,   slice_param->luma_offset_l1,

                                       &slice_param->chroma_weight_l1_flag, slice_param->chroma_weight_l1, slice_param->chroma_offset_l1);

    return 0;

}


static void adaptive_quantization(MpegEncContext *s, double q){

    int i;

    const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);

    const float dark_masking= s->avctx->dark_masking / (128.0*128.0);

    const float temp_cplx_masking= s->avctx->temporal_cplx_masking;

    const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;

    const float p_masking = s->avctx->p_masking;

    float bits_sum= 0.0;

    float cplx_sum= 0.0;

    float cplx_tab[s->mb_num];

    float bits_tab[s->mb_num];

    const int qmin= 2; //s->avctx->mb_qmin;

    const int qmax= 31; //s->avctx->mb_qmax;

    Picture * const pic= &s->current_picture;

    for(i=0; i<s->mb_num; i++){

        float temp_cplx= sqrt(pic->mc_mb_var[i]);

        float spat_cplx= sqrt(pic->mb_var[i]);

        const int lumi= pic->mb_mean[i];

        float bits, cplx, factor;

        if(spat_cplx < q/3) spat_cplx= q/3; //FIXME finetune

        if(temp_cplx < q/3) temp_cplx= q/3; //FIXME finetune

        if((s->mb_type[i]&MB_TYPE_INTRA)){//FIXME hq mode

            cplx= spat_cplx;

            factor= 1.0 + p_masking;

        }else{

            cplx= temp_cplx;

            factor= pow(temp_cplx, - temp_cplx_masking);

        }

        factor*=pow(spat_cplx, - spatial_cplx_masking);

        if(lumi>127)

            factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking);

        else

            factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking);

        if(factor<0.00001) factor= 0.00001;

        bits= cplx*factor;

        cplx_sum+= cplx;

        bits_sum+= bits;

        cplx_tab[i]= cplx;

        bits_tab[i]= bits;

    }

    /* handle qmin/qmax cliping */

    if(s->flags&CODEC_FLAG_NORMALIZE_AQP){

        for(i=0; i<s->mb_num; i++){

            float newq= q*cplx_tab[i]/bits_tab[i];

            newq*= bits_sum/cplx_sum;

            if     (newq > qmax){

                bits_sum -= bits_tab[i];

                cplx_sum -= cplx_tab[i]*q/qmax;

            }

            else if(newq < qmin){

                bits_sum -= bits_tab[i];

                cplx_sum -= cplx_tab[i]*q/qmin;

            }

        }

    }

    for(i=0; i<s->mb_num; i++){

        float newq= q*cplx_tab[i]/bits_tab[i];

        int intq;

        if(s->flags&CODEC_FLAG_NORMALIZE_AQP){

            newq*= bits_sum/cplx_sum;

        }

        if(i && ABS(pic->qscale_table[i-1] - newq)<0.75)

            intq= pic->qscale_table[i-1];

        else

            intq= (int)(newq + 0.5);

        if     (intq > qmax) intq= qmax;

        else if(intq < qmin) intq= qmin;

//if(i%s->mb_width==0) printf("\n");

//printf("%2d%3d ", intq, ff_sqrt(s->mc_mb_var[i]));

        pic->qscale_table[i]= intq;

    }

}


static int flashsv2_prime(FlashSVContext *s, uint8_t *src,

                          int size, int unp_size)

{

    z_stream zs;

    int zret; // Zlib return code

    zs.zalloc = NULL;

    zs.zfree  = NULL;

    zs.opaque = NULL;

    s->zstream.next_in   = src;

    s->zstream.avail_in  = size;

    s->zstream.next_out  = s->tmpblock;

    s->zstream.avail_out = s->block_size * 3;

    inflate(&s->zstream, Z_SYNC_FLUSH);

    deflateInit(&zs, 0);

    zs.next_in   = s->tmpblock;

    zs.avail_in  = s->block_size * 3 - s->zstream.avail_out;

    zs.next_out  = s->deflate_block;

    zs.avail_out = s->deflate_block_size;

    deflate(&zs, Z_SYNC_FLUSH);

    deflateEnd(&zs);

    if ((zret = inflateReset(&s->zstream)) != Z_OK) {

        av_log(s->avctx, AV_LOG_ERROR, "Inflate reset error: %d\n", zret);

        return AVERROR_UNKNOWN;

    }

    s->zstream.next_in   = s->deflate_block;

    s->zstream.avail_in  = s->deflate_block_size - zs.avail_out;

    s->zstream.next_out  = s->tmpblock;

    s->zstream.avail_out = s->block_size * 3;

    inflate(&s->zstream, Z_SYNC_FLUSH);

    return 0;

}


int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)

{

    MpegEncContext *s = &ctx->m;

    int mb_num_bits      = av_log2(s->mb_num - 1) + 1;

    int header_extension = 0, mb_num, len;

    /* is there enough space left for a video packet + header */

    if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)

        return -1;

    for (len = 0; len < 32; len++)

        if (get_bits1(&s->gb))

            break;

    if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {

        av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");

        return -1;

    }

    if (ctx->shape != RECT_SHAPE) {

        header_extension = get_bits1(&s->gb);

        // FIXME more stuff here

    }

    mb_num = get_bits(&s->gb, mb_num_bits);

    if (mb_num >= s->mb_num) {

        av_log(s->avctx, AV_LOG_ERROR,

               "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);

        return -1;

    }

    s->mb_x = mb_num % s->mb_width;

    s->mb_y = mb_num / s->mb_width;

    if (ctx->shape != BIN_ONLY_SHAPE) {

        int qscale = get_bits(&s->gb, s->quant_precision);

        if (qscale)

            s->chroma_qscale = s->qscale = qscale;

    }

    if (ctx->shape == RECT_SHAPE)

        header_extension = get_bits1(&s->gb);

    if (header_extension) {

        int time_incr = 0;

        while (get_bits1(&s->gb) != 0)

            time_incr++;

        check_marker(s->avctx, &s->gb, "before time_increment in video packed header");

        skip_bits(&s->gb, ctx->time_increment_bits);      /* time_increment */

        check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");

        skip_bits(&s->gb, 2); /* vop coding type */

        // FIXME not rect stuff here

        if (ctx->shape != BIN_ONLY_SHAPE) {

            skip_bits(&s->gb, 3); /* intra dc vlc threshold */

            // FIXME don't just ignore everything

            if (s->pict_type == AV_PICTURE_TYPE_S &&

                ctx->vol_sprite_usage == GMC_SPRITE) {

                if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)

                    return AVERROR_INVALIDDATA;

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

            }

            // FIXME reduced res stuff here

            if (s->pict_type != AV_PICTURE_TYPE_I) {

                int f_code = get_bits(&s->gb, 3);       /* fcode_for */

                if (f_code == 0)

                    av_log(s->avctx, AV_LOG_ERROR,

                           "Error, video packet header damaged (f_code=0)\n");

            }

            if (s->pict_type == AV_PICTURE_TYPE_B) {

                int b_code = get_bits(&s->gb, 3);

                if (b_code == 0)

                    av_log(s->avctx, AV_LOG_ERROR,

                           "Error, video packet header damaged (b_code=0)\n");

            }

        }

    }

    if (ctx->new_pred)

        decode_new_pred(ctx, &s->gb);

    return 0;

}


static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,

                   uint8_t *properties)

{

    int compno;

    if (s->buf_end - s->buf < 1)

        return AVERROR(EINVAL);

    compno              = bytestream_get_byte(&s->buf);

    properties[compno] |= HAD_QCC;

    return get_qcx(s, n - 1, q + compno);

}


static int mkv_write_tracks(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *dyn_cp, *pb = s->pb;

    ebml_master tracks;

    int i, ret, default_stream_exists = 0;

    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));

    if (ret < 0)

        return ret;

    ret = start_ebml_master_crc32(pb, &dyn_cp, &tracks, MATROSKA_ID_TRACKS, 0);

    if (ret < 0)

        return ret;

    for (i = 0; i < s->nb_streams; i++) {

        AVStream *st = s->streams[i];

        default_stream_exists |= st->disposition & AV_DISPOSITION_DEFAULT;

    }

    for (i = 0; i < s->nb_streams; i++) {

        ret = mkv_write_track(s, mkv, i, dyn_cp, default_stream_exists);

        if (ret < 0)

            return ret;

    }

    end_ebml_master_crc32(pb, &dyn_cp, mkv, tracks);

    return 0;

}


static void v9fs_stat(void *opaque)

{

    int32_t fid;

    V9fsStat v9stat;

    ssize_t err = 0;

    size_t offset = 7;

    struct stat stbuf;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "d", &fid);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (err < 0) {

        goto out;

    }

    err = stat_to_v9stat(pdu, &fidp->path, &stbuf, &v9stat);

    if (err < 0) {

        goto out;

    }

    offset += pdu_marshal(pdu, offset, "wS", 0, &v9stat);

    err = offset;

    v9fs_stat_free(&v9stat);

out:

    put_fid(pdu, fidp);

out_nofid:

    trace_v9fs_stat_return(pdu->tag, pdu->id, v9stat.mode,

                           v9stat.atime, v9stat.mtime, v9stat.length);

    complete_pdu(s, pdu, err);

}


static int mjpeg_decode_scan(MJpegDecodeContext *s, int nb_components, int Ah, int Al){

    int i, mb_x, mb_y;

    uint8_t* data[MAX_COMPONENTS];

    int linesize[MAX_COMPONENTS];

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

        int c = s->comp_index[i];

        data[c] = s->picture.data[c];

        linesize[c]=s->linesize[c];

        s->coefs_finished[c] |= 1;

        if(s->flipped) {

            //picture should be flipped upside-down for this codec

            assert(!(s->avctx->flags & CODEC_FLAG_EMU_EDGE));

            data[c] += (linesize[c] * (s->v_scount[i] * (8 * s->mb_height -((s->height/s->v_max)&7)) - 1 ));

            linesize[c] *= -1;

        }

    }

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

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

            if (s->restart_interval && !s->restart_count)

                s->restart_count = s->restart_interval;

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

                uint8_t *ptr;

                int n, h, v, x, y, c, j;

                n = s->nb_blocks[i];

                c = s->comp_index[i];

                h = s->h_scount[i];

                v = s->v_scount[i];

                x = 0;

                y = 0;

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

                    ptr = data[c] +

                        (((linesize[c] * (v * mb_y + y) * 8) +

                        (h * mb_x + x) * 8) >> s->avctx->lowres);

                    if(s->interlaced && s->bottom_field)

                        ptr += linesize[c] >> 1;

                    if(!s->progressive) {

                        s->dsp.clear_block(s->block);

                        if(decode_block(s, s->block, i,

                                     s->dc_index[i], s->ac_index[i],

                                     s->quant_matrixes[ s->quant_index[c] ]) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

                            return -1;

                        }

                        s->dsp.idct_put(ptr, linesize[c], s->block);

                    } else {

                        int block_idx = s->block_stride[c] * (v * mb_y + y) + (h * mb_x + x);

                        DCTELEM *block = s->blocks[c][block_idx];

                        if(Ah)

                            block[0] += get_bits1(&s->gb) * s->quant_matrixes[ s->quant_index[c] ][0] << Al;

                        else if(decode_dc_progressive(s, block, i, s->dc_index[i], s->quant_matrixes[ s->quant_index[c] ], Al) < 0) {

                            av_log(s->avctx, AV_LOG_ERROR, "error y=%d x=%d\n", mb_y, mb_x);

                            return -1;

                        }

                    }

//                    av_log(s->avctx, AV_LOG_DEBUG, "mb: %d %d processed\n", mb_y, mb_x);

//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d %d %d %d %d \n", mb_x, mb_y, x, y, c, s->bottom_field, (v * mb_y + y) * 8, (h * mb_x + x) * 8);

                    if (++x == h) {

                        x = 0;

                        y++;

                    }

                }

            }

            if (s->restart_interval && !--s->restart_count) {

                align_get_bits(&s->gb);

                skip_bits(&s->gb, 16); /* skip RSTn */

                for (i=0; i<nb_components; i++) /* reset dc */

                    s->last_dc[i] = 1024;

            }

        }

    }

    return 0;

}


static double eval_expr(Parser *p, AVExpr *e)

{

    switch (e->type) {

        case e_value:  return e->value;

        case e_const:  return e->value * p->const_values[e->a.const_index];

        case e_func0:  return e->value * e->a.func0(eval_expr(p, e->param[0]));

        case e_func1:  return e->value * e->a.func1(p->opaque, eval_expr(p, e->param[0]));

        case e_func2:  return e->value * e->a.func2(p->opaque, eval_expr(p, e->param[0]), eval_expr(p, e->param[1]));

        case e_squish: return 1/(1+exp(4*eval_expr(p, e->param[0])));

        case e_gauss: { double d = eval_expr(p, e->param[0]); return exp(-d*d/2)/sqrt(2*M_PI); }

        case e_ld:     return e->value * p->var[av_clip(eval_expr(p, e->param[0]), 0, VARS-1)];

        case e_isnan:  return e->value * !!isnan(eval_expr(p, e->param[0]));

        case e_floor:  return e->value * floor(eval_expr(p, e->param[0]));

        case e_ceil :  return e->value * ceil (eval_expr(p, e->param[0]));

        case e_trunc:  return e->value * trunc(eval_expr(p, e->param[0]));

        case e_sqrt:   return e->value * sqrt (eval_expr(p, e->param[0]));

        case e_not:    return e->value * (eval_expr(p, e->param[0]) == 0);

        case e_if:     return e->value * ( eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0);

        case e_ifnot:  return e->value * (!eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) : 0);

        case e_random:{

            int idx= av_clip(eval_expr(p, e->param[0]), 0, VARS-1);

            uint64_t r= isnan(p->var[idx]) ? 0 : p->var[idx];

            r= r*1664525+1013904223;

            p->var[idx]= r;

            return e->value * (r * (1.0/UINT64_MAX));

        }

        case e_while: {

            double d = NAN;

            while (eval_expr(p, e->param[0]))

                d=eval_expr(p, e->param[1]);

            return d;

        }

        case e_taylor: {

            double t = 1, d = 0, v;

            double x = eval_expr(p, e->param[1]);

            int id = e->param[2] ? av_clip(eval_expr(p, e->param[2]), 0, VARS-1) : 0;

            int i;

            double var0 = p->var[id];

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

                double ld = d;

                p->var[id] = i;

                v = eval_expr(p, e->param[0]);

                d += t*v;

                if(ld==d && v)

                    break;

                t *= x / (i+1);

            }

            p->var[id] = var0;

            return d;

        }

        case e_root: {

            int i;

            double low = -1, high = -1, v, low_v = -DBL_MAX, high_v = DBL_MAX;

            double var0 = p->var[0];

            double x_max = eval_expr(p, e->param[1]);

            for(i=-1; i<1024; i++) {

                if(i<255) {

                    p->var[0] = av_reverse[i&255]*x_max/255;

                } else {

                    p->var[0] = x_max*pow(0.9, i-255);

                    if (i&1) p->var[0] *= -1;

                    if (i&2) p->var[0] += low;

                    else     p->var[0] += high;

                }

                v = eval_expr(p, e->param[0]);

                if (v<=0 && v>low_v) {

                    low    = p->var[0];

                    low_v  = v;

                }

                if (v>=0 && v<high_v) {

                    high   = p->var[0];

                    high_v = v;

                }

                if (low>=0 && high>=0){

                    while (1) {

                        p->var[0] = (low+high)*0.5;

                        if (low == p->var[0] || high == p->var[0])

                            break;

                        v = eval_expr(p, e->param[0]);

                        if (v<=0) low = p->var[0];

                        if (v>=0) high= p->var[0];

                        if (isnan(v)) {

                            low = high = v;

                            break;

                        }

                    }

                    break;

                }

            }

            p->var[0] = var0;

            return -low_v<high_v ? low : high;

        }

        default: {

            double d = eval_expr(p, e->param[0]);

            double d2 = eval_expr(p, e->param[1]);

            switch (e->type) {

                case e_mod: return e->value * (d - floor(d/d2)*d2);

                case e_gcd: return e->value * av_gcd(d,d2);

                case e_max: return e->value * (d >  d2 ?   d : d2);

                case e_min: return e->value * (d <  d2 ?   d : d2);

                case e_eq:  return e->value * (d == d2 ? 1.0 : 0.0);

                case e_gt:  return e->value * (d >  d2 ? 1.0 : 0.0);

                case e_gte: return e->value * (d >= d2 ? 1.0 : 0.0);

                case e_pow: return e->value * pow(d, d2);

                case e_mul: return e->value * (d * d2);

                case e_div: return e->value * (d / d2);

                case e_add: return e->value * (d + d2);

                case e_last:return e->value * d2;

                case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);

                case e_hypot:return e->value * (sqrt(d*d + d2*d2));

            }

        }

    }

    return NAN;

}


static int deband_16_coupling_c(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)

{

    DebandContext *s = ctx->priv;

    ThreadData *td = arg;

    AVFrame *in = td->in;

    AVFrame *out = td->out;

    const int start = (s->planeheight[0] *  jobnr   ) / nb_jobs;

    const int end   = (s->planeheight[0] * (jobnr+1)) / nb_jobs;

    int x, y, p, z;

    for (y = start; y < end; y++) {

        const int pos = y * s->planewidth[0];

        for (x = 0; x < s->planewidth[p]; x++) {

            const int x_pos = s->x_pos[pos + x];

            const int y_pos = s->y_pos[pos + x];

            int avg[4], cmp[4] = { 0 }, src[4];

            for (p = 0; p < s->nb_components; p++) {

                const uint16_t *src_ptr = (const uint16_t *)in->data[p];

                const int src_linesize = in->linesize[p] / 2;

                const int thr = s->thr[p];

                const int w = s->planewidth[p] - 1;

                const int h = s->planeheight[p] - 1;

                const int ref0 = src_ptr[av_clip(y +  y_pos, 0, h) * src_linesize + av_clip(x +  x_pos, 0, w)];

                const int ref1 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x +  x_pos, 0, w)];

                const int ref2 = src_ptr[av_clip(y + -y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)];

                const int ref3 = src_ptr[av_clip(y +  y_pos, 0, h) * src_linesize + av_clip(x + -x_pos, 0, w)];

                const int src0 = src_ptr[y * src_linesize + x];

                src[p] = src0;

                avg[p] = get_avg(ref0, ref1, ref2, ref3);

                if (s->blur) {

                    cmp[p] = FFABS(src0 - avg[p]) < thr;

                } else {

                    cmp[p] = (FFABS(src0 - ref0) < thr) &&

                             (FFABS(src0 - ref1) < thr) &&

                             (FFABS(src0 - ref2) < thr) &&

                             (FFABS(src0 - ref3) < thr);

                }

            }

            for (z = 0; z < s->nb_components; z++)

                if (!cmp[z])

                    break;

            if (z == s->nb_components) {

                for (p = 0; p < s->nb_components; p++) {

                    const int dst_linesize = out->linesize[p] / 2;

                    uint16_t *dst = (uint16_t *)out->data[p] + y * dst_linesize + x;

                    dst[0] = avg[p];

                }

            } else {

                for (p = 0; p < s->nb_components; p++) {

                    const int dst_linesize = out->linesize[p] / 2;

                    uint16_t *dst = (uint16_t *)out->data[p] + y * dst_linesize + x;

                    dst[0] = src[p];

                }

            }

        }

    }

    return 0;

}


static int tiff_decode_tag(TiffContext *s)

{

    unsigned tag, type, count, off, value = 0;

    int i, j, k, pos, start;

    int ret;

    uint32_t *pal;

    double *dp;

    tag   = tget_short(&s->gb, s->le);

    type  = tget_short(&s->gb, s->le);

    count = tget_long(&s->gb, s->le);

    off   = tget_long(&s->gb, s->le);

    start = bytestream2_tell(&s->gb);

    if (type == 0 || type >= FF_ARRAY_ELEMS(type_sizes)) {

        av_log(s->avctx, AV_LOG_DEBUG, "Unknown tiff type (%u) encountered\n",

               type);

        return 0;

    }

    if (count == 1) {

        switch (type) {

        case TIFF_BYTE:

        case TIFF_SHORT:

            bytestream2_seek(&s->gb, -4, SEEK_CUR);

            value = tget(&s->gb, type, s->le);

            break;

        case TIFF_LONG:

            value = off;

            break;

        case TIFF_STRING:

            if (count <= 4) {

                bytestream2_seek(&s->gb, -4, SEEK_CUR);

                break;

            }

        default:

            value = UINT_MAX;

            bytestream2_seek(&s->gb, off, SEEK_SET);

        }

    } else {

        if (count <= 4 && type_sizes[type] * count <= 4) {

            bytestream2_seek(&s->gb, -4, SEEK_CUR);

        } else {

            bytestream2_seek(&s->gb, off, SEEK_SET);

        }

    }

    switch (tag) {

    case TIFF_WIDTH:

        s->width = value;

        break;

    case TIFF_HEIGHT:

        s->height = value;

        break;

    case TIFF_BPP:

        s->bppcount = count;

        if (count > 4) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "This format is not supported (bpp=%d, %d components)\n",

                   s->bpp, count);

            return AVERROR_INVALIDDATA;

        }

        if (count == 1)

            s->bpp = value;

        else {

            switch (type) {

            case TIFF_BYTE:

                s->bpp = (off & 0xFF) + ((off >> 8) & 0xFF) +

                         ((off >> 16) & 0xFF) + ((off >> 24) & 0xFF);

                break;

            case TIFF_SHORT:

            case TIFF_LONG:

                s->bpp = 0;

                if (bytestream2_get_bytes_left(&s->gb) < type_sizes[type] * count)

                    return AVERROR_INVALIDDATA;

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

                    s->bpp += tget(&s->gb, type, s->le);

                break;

            default:

                s->bpp = -1;

            }

        }

        break;

    case TIFF_SAMPLES_PER_PIXEL:

        if (count != 1) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Samples per pixel requires a single value, many provided\n");

            return AVERROR_INVALIDDATA;

        }

        if (value > 4U) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Samples per pixel %d is too large\n", value);

            return AVERROR_INVALIDDATA;

        }

        if (s->bppcount == 1)

            s->bpp *= value;

        s->bppcount = value;

        break;

    case TIFF_COMPR:

        s->compr = value;

        s->predictor = 0;

        switch (s->compr) {

        case TIFF_RAW:

        case TIFF_PACKBITS:

        case TIFF_LZW:

        case TIFF_CCITT_RLE:

            break;

        case TIFF_G3:

        case TIFF_G4:

            s->fax_opts = 0;

            break;

        case TIFF_DEFLATE:

        case TIFF_ADOBE_DEFLATE:

#if CONFIG_ZLIB

            break;

#else

            av_log(s->avctx, AV_LOG_ERROR, "Deflate: ZLib not compiled in\n");

            return AVERROR(ENOSYS);

#endif

        case TIFF_JPEG:

        case TIFF_NEWJPEG:

            av_log(s->avctx, AV_LOG_ERROR,

                   "JPEG compression is not supported\n");

            return AVERROR_PATCHWELCOME;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Unknown compression method %i\n",

                   s->compr);

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_ROWSPERSTRIP:

        if (type == TIFF_LONG && value == UINT_MAX)

            value = s->height;

        if (value < 1) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Incorrect value of rows per strip\n");

            return AVERROR_INVALIDDATA;

        }

        s->rps = value;

        break;

    case TIFF_STRIP_OFFS:

        if (count == 1) {

            s->strippos = 0;

            s->stripoff = value;

        } else

            s->strippos = off;

        s->strips = count;

        if (s->strips == 1)

            s->rps = s->height;

        s->sot = type;

        if (s->strippos > bytestream2_size(&s->gb)) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Tag referencing position outside the image\n");

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_STRIP_SIZE:

        if (count == 1) {

            s->stripsizesoff = 0;

            s->stripsize = value;

            s->strips = 1;

        } else {

            s->stripsizesoff = off;

        }

        s->strips = count;

        s->sstype = type;

        if (s->stripsizesoff > bytestream2_size(&s->gb)) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Tag referencing position outside the image\n");

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_TILE_BYTE_COUNTS:

    case TIFF_TILE_LENGTH:

    case TIFF_TILE_OFFSETS:

    case TIFF_TILE_WIDTH:

        av_log(s->avctx, AV_LOG_ERROR, "Tiled images are not supported\n");

        return AVERROR_PATCHWELCOME;

        break;

    case TIFF_PREDICTOR:

        s->predictor = value;

        break;

    case TIFF_INVERT:

        switch (value) {

        case 0:

            s->invert = 1;

            break;

        case 1:

            s->invert = 0;

            break;

        case 2:

        case 3:

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Color mode %d is not supported\n",

                   value);

            return AVERROR_INVALIDDATA;

        }

        break;

    case TIFF_FILL_ORDER:

        if (value < 1 || value > 2) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Unknown FillOrder value %d, trying default one\n", value);

            value = 1;

        }

        s->fill_order = value - 1;

        break;

    case TIFF_PAL:

        pal = (uint32_t *) s->palette;

        off = type_sizes[type];

        if (count / 3 > 256 || bytestream2_get_bytes_left(&s->gb) < count / 3 * off * 3)

            return AVERROR_INVALIDDATA;

        off = (type_sizes[type] - 1) << 3;

        for (k = 2; k >= 0; k--) {

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

                if (k == 2)

                    pal[i] = 0xFFU << 24;

                j =  (tget(&s->gb, type, s->le) >> off) << (k * 8);

                pal[i] |= j;

            }

        }

        s->palette_is_set = 1;

        break;

    case TIFF_PLANAR:

        if (value == 2) {

            av_log(s->avctx, AV_LOG_ERROR, "Planar format is not supported\n");

            return AVERROR_PATCHWELCOME;

        }

        break;

    case TIFF_T4OPTIONS:

        if (s->compr == TIFF_G3)

            s->fax_opts = value;

        break;

    case TIFF_T6OPTIONS:

        if (s->compr == TIFF_G4)

            s->fax_opts = value;

        break;

#define ADD_METADATA(count, name, sep)\

    if ((ret = add_metadata(count, type, name, sep, s)) < 0) {\

        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");\

        return ret;\

    }

    case TIFF_MODEL_PIXEL_SCALE:

        ADD_METADATA(count, "ModelPixelScaleTag", NULL);

        break;

    case TIFF_MODEL_TRANSFORMATION:

        ADD_METADATA(count, "ModelTransformationTag", NULL);

        break;

    case TIFF_MODEL_TIEPOINT:

        ADD_METADATA(count, "ModelTiepointTag", NULL);

        break;

    case TIFF_GEO_KEY_DIRECTORY:

        ADD_METADATA(1, "GeoTIFF_Version", NULL);

        ADD_METADATA(2, "GeoTIFF_Key_Revision", ".");

        s->geotag_count   = tget_short(&s->gb, s->le);

        if (s->geotag_count > count / 4 - 1) {

            s->geotag_count = count / 4 - 1;

            av_log(s->avctx, AV_LOG_WARNING, "GeoTIFF key directory buffer shorter than specified\n");

        }

        if (bytestream2_get_bytes_left(&s->gb) < s->geotag_count * sizeof(int16_t) * 4) {

            s->geotag_count = 0;

            return -1;

        }

        s->geotags = av_mallocz(sizeof(TiffGeoTag) * s->geotag_count);

        if (!s->geotags) {

            av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

            s->geotag_count = 0;

            return AVERROR(ENOMEM);

        }

        for (i = 0; i < s->geotag_count; i++) {

            s->geotags[i].key    = tget_short(&s->gb, s->le);

            s->geotags[i].type   = tget_short(&s->gb, s->le);

            s->geotags[i].count  = tget_short(&s->gb, s->le);

            if (!s->geotags[i].type)

                s->geotags[i].val  = get_geokey_val(s->geotags[i].key, tget_short(&s->gb, s->le));

            else

                s->geotags[i].offset = tget_short(&s->gb, s->le);

        }

        break;

    case TIFF_GEO_DOUBLE_PARAMS:

        if (count >= INT_MAX / sizeof(int64_t))

            return AVERROR_INVALIDDATA;

        if (bytestream2_get_bytes_left(&s->gb) < count * sizeof(int64_t))

            return AVERROR_INVALIDDATA;

        dp = av_malloc(count * sizeof(double));

        if (!dp) {

            av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

            return AVERROR(ENOMEM);

        }

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

            dp[i] = tget_double(&s->gb, s->le);

        for (i = 0; i < s->geotag_count; i++) {

            if (s->geotags[i].type == TIFF_GEO_DOUBLE_PARAMS) {

                if (s->geotags[i].count == 0

                    || s->geotags[i].offset + s->geotags[i].count > count) {

                    av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);

                } else {

                    char *ap = doubles2str(&dp[s->geotags[i].offset], s->geotags[i].count, ", ");

                    if (!ap) {

                        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

                        av_freep(&dp);

                        return AVERROR(ENOMEM);

                    }

                    s->geotags[i].val = ap;

                }

            }

        }

        av_freep(&dp);

        break;

    case TIFF_GEO_ASCII_PARAMS:

        pos = bytestream2_tell(&s->gb);

        for (i = 0; i < s->geotag_count; i++) {

            if (s->geotags[i].type == TIFF_GEO_ASCII_PARAMS) {

                if (s->geotags[i].count == 0

                    || s->geotags[i].offset +  s->geotags[i].count > count) {

                    av_log(s->avctx, AV_LOG_WARNING, "Invalid GeoTIFF key %d\n", s->geotags[i].key);

                } else {

                    char *ap;

                    bytestream2_seek(&s->gb, pos + s->geotags[i].offset, SEEK_SET);

                    if (bytestream2_get_bytes_left(&s->gb) < s->geotags[i].count)

                        return AVERROR_INVALIDDATA;

                    ap = av_malloc(s->geotags[i].count);

                    if (!ap) {

                        av_log(s->avctx, AV_LOG_ERROR, "Error allocating temporary buffer\n");

                        return AVERROR(ENOMEM);

                    }

                    bytestream2_get_bufferu(&s->gb, ap, s->geotags[i].count);

                    ap[s->geotags[i].count - 1] = '\0'; //replace the "|" delimiter with a 0 byte

                    s->geotags[i].val = ap;

                }

            }

        }

        break;

    case TIFF_ARTIST:

        ADD_METADATA(count, "artist", NULL);

        break;

    case TIFF_COPYRIGHT:

        ADD_METADATA(count, "copyright", NULL);

        break;

    case TIFF_DATE:

        ADD_METADATA(count, "date", NULL);

        break;

    case TIFF_DOCUMENT_NAME:

        ADD_METADATA(count, "document_name", NULL);

        break;

    case TIFF_HOST_COMPUTER:

        ADD_METADATA(count, "computer", NULL);

        break;

    case TIFF_IMAGE_DESCRIPTION:

        ADD_METADATA(count, "description", NULL);

        break;

    case TIFF_MAKE:

        ADD_METADATA(count, "make", NULL);

        break;

    case TIFF_MODEL:

        ADD_METADATA(count, "model", NULL);

        break;

    case TIFF_PAGE_NAME:

        ADD_METADATA(count, "page_name", NULL);

        break;

    case TIFF_PAGE_NUMBER:

        ADD_METADATA(count, "page_number", " / ");

        break;

    case TIFF_SOFTWARE_NAME:

        ADD_METADATA(count, "software", NULL);

        break;

    default:

        av_log(s->avctx, AV_LOG_DEBUG, "Unknown or unsupported tag %d/0X%0X\n",

               tag, tag);

    }

    bytestream2_seek(&s->gb, start, SEEK_SET);

    return 0;

}


static void FUNC(put_hevc_epel_bi_w_v)(uint8_t *_dst, ptrdiff_t _dststride, uint8_t *_src, ptrdiff_t _srcstride,

                                       int16_t *src2,

                                       int height, int denom, int wx0, int wx1,

                                       int ox0, int ox1, intptr_t mx, intptr_t my, int width)

{

    int x, y;

    pixel *src = (pixel *)_src;

    ptrdiff_t srcstride  = _srcstride / sizeof(pixel);

    const int8_t *filter = ff_hevc_epel_filters[my - 1];

    pixel *dst          = (pixel *)_dst;

    ptrdiff_t dststride = _dststride / sizeof(pixel);

    int shift = 14 + 1 - BIT_DEPTH;

    int log2Wd = denom + shift - 1;

    ox0     = ox0 * (1 << (BIT_DEPTH - 8));

    ox1     = ox1 * (1 << (BIT_DEPTH - 8));

    for (y = 0; y < height; y++) {

        for (x = 0; x < width; x++)

            dst[x] = av_clip_pixel(((EPEL_FILTER(src, srcstride) >> (BIT_DEPTH - 8)) * wx1 + src2[x] * wx0 +

                                    ((ox0 + ox1 + 1) << log2Wd)) >> (log2Wd + 1));

        src  += srcstride;

        dst  += dststride;

        src2 += MAX_PB_SIZE;

    }

}


DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)

{

    const char *buf;

    const char *file = NULL;

    char devname[128];

    const char *serial;

    const char *mediastr = "";

    BlockInterfaceType type;

    enum { MEDIA_DISK, MEDIA_CDROM } media;

    int bus_id, unit_id;

    int cyls, heads, secs, translation;

    BlockDriver *drv = NULL;

    int max_devs;

    int index;

    int ro = 0;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    const char *devaddr;

    DriveInfo *dinfo;

    BlockIOLimit io_limits;

    int snapshot = 0;

    bool copy_on_read;

    int ret;

    translation = BIOS_ATA_TRANSLATION_AUTO;

    media = MEDIA_DISK;

    /* extract parameters */

    bus_id  = qemu_opt_get_number(opts, "bus", 0);

    unit_id = qemu_opt_get_number(opts, "unit", -1);

    index   = qemu_opt_get_number(opts, "index", -1);

    cyls  = qemu_opt_get_number(opts, "cyls", 0);

    heads = qemu_opt_get_number(opts, "heads", 0);

    secs  = qemu_opt_get_number(opts, "secs", 0);

    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);

    ro = qemu_opt_get_bool(opts, "readonly", 0);

    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);

    file = qemu_opt_get(opts, "file");

    serial = qemu_opt_get(opts, "serial");

    if ((buf = qemu_opt_get(opts, "if")) != NULL) {

        pstrcpy(devname, sizeof(devname), buf);

        for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)

            ;

        if (type == IF_COUNT) {

            error_report("unsupported bus type '%s'", buf);

            return NULL;

	}

    } else {

        type = default_to_scsi ? IF_SCSI : IF_IDE;

        pstrcpy(devname, sizeof(devname), if_name[type]);

    }

    max_devs = if_max_devs[type];

    if (cyls || heads || secs) {

        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {

            error_report("invalid physical cyls number");

	    return NULL;

	}

        if (heads < 1 || (type == IF_IDE && heads > 16)) {

            error_report("invalid physical heads number");

	    return NULL;

	}

        if (secs < 1 || (type == IF_IDE && secs > 63)) {

            error_report("invalid physical secs number");

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {

        if (!cyls) {

            error_report("'%s' trans must be used with cyls, heads and secs",

                         buf);

            return NULL;

        }

        if (!strcmp(buf, "none"))

            translation = BIOS_ATA_TRANSLATION_NONE;

        else if (!strcmp(buf, "lba"))

            translation = BIOS_ATA_TRANSLATION_LBA;

        else if (!strcmp(buf, "auto"))

            translation = BIOS_ATA_TRANSLATION_AUTO;

	else {

            error_report("'%s' invalid translation type", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "media")) != NULL) {

        if (!strcmp(buf, "disk")) {

	    media = MEDIA_DISK;

	} else if (!strcmp(buf, "cdrom")) {

            if (cyls || secs || heads) {

                error_report("CHS can't be set with media=%s", buf);

	        return NULL;

            }

	    media = MEDIA_CDROM;

	} else {

	    error_report("'%s' invalid media", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {

        if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) {

            error_report("invalid cache option");

            return NULL;

        }

    }

#ifdef CONFIG_LINUX_AIO

    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {

        if (!strcmp(buf, "native")) {

            bdrv_flags |= BDRV_O_NATIVE_AIO;

        } else if (!strcmp(buf, "threads")) {

            /* this is the default */

        } else {

           error_report("invalid aio option");

           return NULL;

        }

    }

#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {

       if (strcmp(buf, "?") == 0) {

           error_printf("Supported formats:");

           bdrv_iterate_format(bdrv_format_print, NULL);

           error_printf("\n");

           return NULL;

        }

        drv = bdrv_find_whitelisted_format(buf);

        if (!drv) {

            error_report("'%s' invalid format", buf);

            return NULL;

        }

    }

    /* disk I/O throttling */

    io_limits.bps[BLOCK_IO_LIMIT_TOTAL]  =

                           qemu_opt_get_number(opts, "bps", 0);

    io_limits.bps[BLOCK_IO_LIMIT_READ]   =

                           qemu_opt_get_number(opts, "bps_rd", 0);

    io_limits.bps[BLOCK_IO_LIMIT_WRITE]  =

                           qemu_opt_get_number(opts, "bps_wr", 0);

    io_limits.iops[BLOCK_IO_LIMIT_TOTAL] =

                           qemu_opt_get_number(opts, "iops", 0);

    io_limits.iops[BLOCK_IO_LIMIT_READ]  =

                           qemu_opt_get_number(opts, "iops_rd", 0);

    io_limits.iops[BLOCK_IO_LIMIT_WRITE] =

                           qemu_opt_get_number(opts, "iops_wr", 0);

    if (!do_check_io_limits(&io_limits)) {

        error_report("bps(iops) and bps_rd/bps_wr(iops_rd/iops_wr) "

                     "cannot be used at the same time");

        return NULL;

    }

    on_write_error = BLOCK_ERR_STOP_ENOSPC;

    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {

            error_report("werror is not supported by this bus type");

            return NULL;

        }

        on_write_error = parse_block_error_action(buf, 0);

        if (on_write_error < 0) {

            return NULL;

        }

    }

    on_read_error = BLOCK_ERR_REPORT;

    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {

        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {

            error_report("rerror is not supported by this bus type");

            return NULL;

        }

        on_read_error = parse_block_error_action(buf, 1);

        if (on_read_error < 0) {

            return NULL;

        }

    }

    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {

        if (type != IF_VIRTIO) {

            error_report("addr is not supported by this bus type");

            return NULL;

        }

    }

    /* compute bus and unit according index */

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            error_report("index cannot be used with bus and unit");

            return NULL;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    /* if user doesn't specify a unit_id,

     * try to find the first free

     */

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get(type, bus_id, unit_id) != NULL) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {

        error_report("unit %d too big (max is %d)",

                     unit_id, max_devs - 1);

        return NULL;

    }

    /*

     * catch multiple definitions

     */

    if (drive_get(type, bus_id, unit_id) != NULL) {

        error_report("drive with bus=%d, unit=%d (index=%d) exists",

                     bus_id, unit_id, index);

        return NULL;

    }

    /* init */

    dinfo = g_malloc0(sizeof(*dinfo));

    if ((buf = qemu_opts_id(opts)) != NULL) {

        dinfo->id = g_strdup(buf);

    } else {

        /* no id supplied -> create one */

        dinfo->id = g_malloc0(32);

        if (type == IF_IDE || type == IF_SCSI)

            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

        if (max_devs)

            snprintf(dinfo->id, 32, "%s%i%s%i",

                     devname, bus_id, mediastr, unit_id);

        else

            snprintf(dinfo->id, 32, "%s%s%i",

                     devname, mediastr, unit_id);

    }

    dinfo->bdrv = bdrv_new(dinfo->id);

    dinfo->devaddr = devaddr;

    dinfo->type = type;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->opts = opts;

    dinfo->refcount = 1;

    if (serial) {

        pstrcpy(dinfo->serial, sizeof(dinfo->serial), serial);

    }

    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

    /* disk I/O throttling */

    bdrv_set_io_limits(dinfo->bdrv, &io_limits);

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        switch(media) {

	case MEDIA_DISK:

            if (cyls != 0) {

                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);

                bdrv_set_translation_hint(dinfo->bdrv, translation);

            }

	    break;

	case MEDIA_CDROM:

            dinfo->media_cd = 1;

	    break;

	}

        break;

    case IF_SD:

    case IF_FLOPPY:

    case IF_PFLASH:

    case IF_MTD:

        break;

    case IF_VIRTIO:

        /* add virtio block device */

        opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);

        if (arch_type == QEMU_ARCH_S390X) {

            qemu_opt_set(opts, "driver", "virtio-blk-s390");

        } else {

            qemu_opt_set(opts, "driver", "virtio-blk-pci");

        }

        qemu_opt_set(opts, "drive", dinfo->id);

        if (devaddr)

            qemu_opt_set(opts, "addr", devaddr);

        break;

    default:

        abort();

    }

    if (!file || !*file) {

        return dinfo;

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    if (copy_on_read) {

        bdrv_flags |= BDRV_O_COPY_ON_READ;

    }

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        bdrv_flags |= BDRV_O_INCOMING;

    }

    if (media == MEDIA_CDROM) {

        /* CDROM is fine for any interface, don't check.  */

        ro = 1;

    } else if (ro == 1) {

        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&

            type != IF_NONE && type != IF_PFLASH) {

            error_report("readonly not supported by this bus type");

            goto err;

        }

    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

    ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv);

    if (ret < 0) {

        error_report("could not open disk image %s: %s",

                     file, strerror(-ret));

        goto err;

    }

    if (bdrv_key_required(dinfo->bdrv))

        autostart = 0;

    return dinfo;

err:

    bdrv_delete(dinfo->bdrv);

    g_free(dinfo->id);

    QTAILQ_REMOVE(&drives, dinfo, next);

    g_free(dinfo);

    return NULL;

}


bool vhost_net_query(VHostNetState *net, VirtIODevice *dev)

{

    return false;

}


static int init_input(AVFormatContext *s, const char *filename)
{
    int ret;
    AVProbeData pd = {filename, NULL, 0};
    if (s->pb) {
        s->flags |= AVFMT_FLAG_CUSTOM_IO;
        if (!s->iformat)
            return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
        else if (s->iformat->flags & AVFMT_NOFILE)
            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "
                                      "will be ignored with AVFMT_NOFILE format.\n");
    }
    if ( (s->iformat && s->iformat->flags & AVFMT_NOFILE) ||
        (!s->iformat && (s->iformat = av_probe_input_format(&pd, 0))))
    if ((ret = avio_open(&s->pb, filename, AVIO_FLAG_READ)) < 0)
        return ret;
    if (s->iformat)
    return av_probe_input_buffer(s->pb, &s->iformat, filename, s, 0, 0);
}


void *etraxfs_eth_init(NICInfo *nd, CPUState *env,

		       qemu_irq *irq, target_phys_addr_t base, int phyaddr)

{

	struct etraxfs_dma_client *dma = NULL;

	struct fs_eth *eth = NULL;

	qemu_check_nic_model(nd, "fseth");

	dma = qemu_mallocz(sizeof *dma * 2);

	eth = qemu_mallocz(sizeof *eth);

	dma[0].client.push = eth_tx_push;

	dma[0].client.opaque = eth;

	dma[1].client.opaque = eth;

	dma[1].client.pull = NULL;

	eth->env = env;

	eth->irq = irq;

	eth->dma_out = dma;

	eth->dma_in = dma + 1;

	/* Connect the phy.  */

	eth->phyaddr = phyaddr & 0x1f;

	tdk_init(&eth->phy);

	mdio_attach(&eth->mdio_bus, &eth->phy, eth->phyaddr);

	eth->ethregs = cpu_register_io_memory(0, eth_read, eth_write, eth);

	cpu_register_physical_memory (base, 0x5c, eth->ethregs);

	eth->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

				       eth_receive, eth_can_receive, eth);

	eth->vc->opaque = eth;

	eth->vc->link_status_changed = eth_set_link;

	return dma;

}


static int gif_read_extension(GifState *s)

{

    ByteIOContext *f = s->f;

    int ext_code, ext_len, i, gce_flags, gce_transparent_index;

    /* extension */

    ext_code = get_byte(f);

    ext_len = get_byte(f);

#ifdef DEBUG

    printf("gif: ext_code=0x%x len=%d\n", ext_code, ext_len);

#endif

    switch(ext_code) {

    case 0xf9:

        if (ext_len != 4)

            goto discard_ext;

        s->transparent_color_index = -1;

        gce_flags = get_byte(f);

        s->gce_delay = get_le16(f);

        gce_transparent_index = get_byte(f);

        if (gce_flags & 0x01)

            s->transparent_color_index = gce_transparent_index;

        else

            s->transparent_color_index = -1;

        s->gce_disposal = (gce_flags >> 2) & 0x7;

#ifdef DEBUG

        printf("gif: gce_flags=%x delay=%d tcolor=%d disposal=%d\n",

               gce_flags, s->gce_delay,

               s->transparent_color_index, s->gce_disposal);

#endif

        ext_len = get_byte(f);

        break;

    }

    /* NOTE: many extension blocks can come after */

 discard_ext:

    while (ext_len != 0) {

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

            get_byte(f);

        ext_len = get_byte(f);

#ifdef DEBUG

        printf("gif: ext_len1=%d\n", ext_len);

#endif

    }

    return 0;

}


altivec_packIntArrayToCharArray(int *val, uint8_t* dest, int dstW) {

  register int i;

  vector unsigned int altivec_vectorShiftInt19 =

    vec_add(vec_splat_u32(10),vec_splat_u32(9));

  if ((unsigned long)dest % 16) {

    /* badly aligned store, we force store alignement */

    /* and will handle load misalignement on val w/ vec_perm */

    vector unsigned char perm1;

    vector signed int v1;

    for (i = 0 ; (i < dstW) &&

	   (((unsigned long)dest + i) % 16) ; i++) {

      int t = val[i] >> 19;

      dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t);

    }

    perm1 = vec_lvsl(i << 2, val);

    v1 = vec_ld(i << 2, val);

    for ( ; i < (dstW - 15); i+=16) {

      int offset = i << 2;

      vector signed int v2 = vec_ld(offset + 16, val);

      vector signed int v3 = vec_ld(offset + 32, val);

      vector signed int v4 = vec_ld(offset + 48, val);

      vector signed int v5 = vec_ld(offset + 64, val);

      vector signed int v12 = vec_perm(v1,v2,perm1);

      vector signed int v23 = vec_perm(v2,v3,perm1);

      vector signed int v34 = vec_perm(v3,v4,perm1);

      vector signed int v45 = vec_perm(v4,v5,perm1);

      vector signed int vA = vec_sra(v12, altivec_vectorShiftInt19);

      vector signed int vB = vec_sra(v23, altivec_vectorShiftInt19);

      vector signed int vC = vec_sra(v34, altivec_vectorShiftInt19);

      vector signed int vD = vec_sra(v45, altivec_vectorShiftInt19);

      vector unsigned short vs1 = vec_packsu(vA, vB);

      vector unsigned short vs2 = vec_packsu(vC, vD);

      vector unsigned char vf = vec_packsu(vs1, vs2);

      vec_st(vf, i, dest);

      v1 = v5;

    }

  } else { // dest is properly aligned, great

    for (i = 0; i < (dstW - 15); i+=16) {

      int offset = i << 2;

      vector signed int v1 = vec_ld(offset, val);

      vector signed int v2 = vec_ld(offset + 16, val);

      vector signed int v3 = vec_ld(offset + 32, val);

      vector signed int v4 = vec_ld(offset + 48, val);

      vector signed int v5 = vec_sra(v1, altivec_vectorShiftInt19);

      vector signed int v6 = vec_sra(v2, altivec_vectorShiftInt19);

      vector signed int v7 = vec_sra(v3, altivec_vectorShiftInt19);

      vector signed int v8 = vec_sra(v4, altivec_vectorShiftInt19);

      vector unsigned short vs1 = vec_packsu(v5, v6);

      vector unsigned short vs2 = vec_packsu(v7, v8);

      vector unsigned char vf = vec_packsu(vs1, vs2);

      vec_st(vf, i, dest);

    }

  }

  for ( ; i < dstW ; i++) {

    int t = val[i] >> 19;

    dest[i] = (t < 0) ? 0 : ((t > 255) ? 255 : t);

  }

}


static void virtio_pci_realize(PCIDevice *pci_dev, Error **errp)

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(pci_dev);

    VirtioPCIClass *k = VIRTIO_PCI_GET_CLASS(pci_dev);

    /*

     * virtio pci bar layout used by default.

     * subclasses can re-arrange things if needed.

     *

     *   region 0   --  virtio legacy io bar

     *   region 1   --  msi-x bar

     *   region 4+5 --  virtio modern memory (64bit) bar

     *

     */

    proxy->legacy_io_bar  = 0;

    proxy->msix_bar       = 1;

    proxy->modern_io_bar  = 2;

    proxy->modern_mem_bar = 4;

    proxy->common.offset = 0x0;

    proxy->common.size = 0x1000;

    proxy->common.type = VIRTIO_PCI_CAP_COMMON_CFG;

    proxy->isr.offset = 0x1000;

    proxy->isr.size = 0x1000;

    proxy->isr.type = VIRTIO_PCI_CAP_ISR_CFG;

    proxy->device.offset = 0x2000;

    proxy->device.size = 0x1000;

    proxy->device.type = VIRTIO_PCI_CAP_DEVICE_CFG;

    proxy->notify.offset = 0x3000;

    proxy->notify.size =

        QEMU_VIRTIO_PCI_QUEUE_MEM_MULT * VIRTIO_QUEUE_MAX;

    proxy->notify.type = VIRTIO_PCI_CAP_NOTIFY_CFG;

    proxy->notify_pio.offset = 0x0;

    proxy->notify_pio.size = 0x4;

    proxy->notify_pio.type = VIRTIO_PCI_CAP_NOTIFY_CFG;

    /* subclasses can enforce modern, so do this unconditionally */

    memory_region_init(&proxy->modern_bar, OBJECT(proxy), "virtio-pci",

                       2 * QEMU_VIRTIO_PCI_QUEUE_MEM_MULT *

                       VIRTIO_QUEUE_MAX);

    memory_region_init_alias(&proxy->modern_cfg,

                             OBJECT(proxy),

                             "virtio-pci-cfg",

                             &proxy->modern_bar,

                             0,

                             memory_region_size(&proxy->modern_bar));

    address_space_init(&proxy->modern_as, &proxy->modern_cfg, "virtio-pci-cfg-as");

    if (!(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_PCIE)

        && !(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_MODERN)

        && pci_bus_is_express(pci_dev->bus)

        && !pci_bus_is_root(pci_dev->bus)) {

        int pos;

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

        pos = pcie_endpoint_cap_init(pci_dev, 0);

        assert(pos > 0);

        pos = pci_add_capability(pci_dev, PCI_CAP_ID_PM, 0, PCI_PM_SIZEOF);

        assert(pos > 0);

        /*

         * Indicates that this function complies with revision 1.2 of the

         * PCI Power Management Interface Specification.

         */

        pci_set_word(pci_dev->config + pos + PCI_PM_PMC, 0x3);

    }

    virtio_pci_bus_new(&proxy->bus, sizeof(proxy->bus), proxy);

    if (k->realize) {

        k->realize(proxy, errp);

    }

}


static HTTPContext *find_rtp_session_with_url(const char *url,

                                              const char *session_id)

{

    HTTPContext *rtp_c;

    char path1[1024];

    const char *path;

    char buf[1024];

    int s;

    rtp_c = find_rtp_session(session_id);

    if (!rtp_c)

        return NULL;

    /* find which url is asked */

    url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);

    path = path1;

    if (*path == '/')

        path++;

    if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;

    for(s=0; s<rtp_c->stream->nb_streams; ++s) {

      snprintf(buf, sizeof(buf), "%s/streamid=%d",

        rtp_c->stream->filename, s);

      if(!strncmp(path, buf, sizeof(buf))) {

    // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?

        return rtp_c;

      }

    }

    return NULL;

}


static void write_header(FFV1Context *f)

{

    uint8_t state[CONTEXT_SIZE];

    int i, j;

    RangeCoder *const c = &f->slice_context[0]->c;

    memset(state, 128, sizeof(state));

    if (f->version < 2) {

        put_symbol(c, state, f->version, 0);

        put_symbol(c, state, f->ac, 0);

        if (f->ac > 1) {

            for (i = 1; i < 256; i++)

                put_symbol(c, state,

                           f->state_transition[i] - c->one_state[i], 1);

        }

        put_symbol(c, state, f->colorspace, 0); // YUV cs type

        if (f->version > 0)

            put_symbol(c, state, f->bits_per_raw_sample, 0);

        put_rac(c, state, f->chroma_planes);

        put_symbol(c, state, f->chroma_h_shift, 0);

        put_symbol(c, state, f->chroma_v_shift, 0);

        put_rac(c, state, f->transparency);

        write_quant_tables(c, f->quant_table);

    } else if (f->version < 3) {

        put_symbol(c, state, f->slice_count, 0);

        for (i = 0; i < f->slice_count; i++) {

            FFV1Context *fs = f->slice_context[i];

            put_symbol(c, state,

                       (fs->slice_x      + 1) * f->num_h_slices / f->width, 0);

            put_symbol(c, state,

                       (fs->slice_y      + 1) * f->num_v_slices / f->height, 0);

            put_symbol(c, state,

                       (fs->slice_width  + 1) * f->num_h_slices / f->width - 1,

                       0);

            put_symbol(c, state,

                       (fs->slice_height + 1) * f->num_v_slices / f->height - 1,

                       0);

            for (j = 0; j < f->plane_count; j++) {

                put_symbol(c, state, f->plane[j].quant_table_index, 0);

                av_assert0(f->plane[j].quant_table_index == f->avctx->context_model);

            }

        }

    }

}


static void __attribute__((constructor)) init_main_loop(void)

{

    init_clocks();

    init_timer_alarm();

    qemu_clock_enable(vm_clock, false);

}


static unsigned tget_long(const uint8_t **p, int le)

{

    unsigned v = le ? AV_RL32(*p) : AV_RB32(*p);

    *p += 4;

    return v;

}