static av_cold int decode_init(WMAProDecodeCtx *s, AVCodecContext *avctx)

{

    uint8_t *edata_ptr = avctx->extradata;

    unsigned int channel_mask;

    int i, bits;

    int log2_max_num_subframes;

    int num_possible_block_sizes;

    if (avctx->codec_id == AV_CODEC_ID_XMA1 || avctx->codec_id == AV_CODEC_ID_XMA2)

        avctx->block_align = 2048;

    if (!avctx->block_align) {

        av_log(avctx, AV_LOG_ERROR, "block_align is not set\n");

        return AVERROR(EINVAL);

    }

    s->avctx = avctx;

    s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);

    if (!s->fdsp)

        return AVERROR(ENOMEM);

    init_put_bits(&s->pb, s->frame_data, MAX_FRAMESIZE);

    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;

    /** dump the extradata */

    av_log(avctx, AV_LOG_DEBUG, "extradata:\n");

    for (i = 0; i < avctx->extradata_size; i++)

        av_log(avctx, AV_LOG_DEBUG, "[%x] ", avctx->extradata[i]);

    av_log(avctx, AV_LOG_DEBUG, "\n");

    if (avctx->codec_id == AV_CODEC_ID_XMA2 && (!avctx->extradata || avctx->extradata_size >= 6)) {

        s->decode_flags    = 0x10d6;

        channel_mask       = avctx->extradata ? AV_RL32(edata_ptr+2) : 0;

        s->bits_per_sample = 16;

     } else if (avctx->codec_id == AV_CODEC_ID_XMA1) {

        s->decode_flags    = 0x10d6;

        s->bits_per_sample = 16;

        channel_mask       = 0;

     } else if (avctx->codec_id == AV_CODEC_ID_WMAPRO && avctx->extradata_size >= 18) {

        s->decode_flags    = AV_RL16(edata_ptr+14);

        channel_mask       = AV_RL32(edata_ptr+2);

        s->bits_per_sample = AV_RL16(edata_ptr);

        if (s->bits_per_sample > 32 || s->bits_per_sample < 1) {

            avpriv_request_sample(avctx, "bits per sample is %d", s->bits_per_sample);

            return AVERROR_PATCHWELCOME;

        }

    } else {

        avpriv_request_sample(avctx, "Unknown extradata size");

        return AVERROR_PATCHWELCOME;

    }

    if (avctx->codec_id != AV_CODEC_ID_WMAPRO && avctx->channels > 2) {

        s->nb_channels = 2;

    } else {

        s->nb_channels = avctx->channels;

    }

    /** generic init */

    s->log2_frame_size = av_log2(avctx->block_align) + 4;

    if (s->log2_frame_size > 25) {

        avpriv_request_sample(avctx, "Large block align");

        return AVERROR_PATCHWELCOME;

    }

    /** frame info */

    if (avctx->codec_id != AV_CODEC_ID_WMAPRO)

        s->skip_frame = 0;

    else

        s->skip_frame = 1; /* skip first frame */

    s->packet_loss = 1;

    s->len_prefix  = (s->decode_flags & 0x40);

    /** get frame len */

    if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {

        bits = ff_wma_get_frame_len_bits(avctx->sample_rate, 3, s->decode_flags);

        if (bits > WMAPRO_BLOCK_MAX_BITS) {

            avpriv_request_sample(avctx, "14-bit block sizes");

            return AVERROR_PATCHWELCOME;

        }

        s->samples_per_frame = 1 << bits;

    } else {

        s->samples_per_frame = 512;

    }

    /** subframe info */

    log2_max_num_subframes       = ((s->decode_flags & 0x38) >> 3);

    s->max_num_subframes         = 1 << log2_max_num_subframes;

    if (s->max_num_subframes == 16 || s->max_num_subframes == 4)

        s->max_subframe_len_bit = 1;

    s->subframe_len_bits = av_log2(log2_max_num_subframes) + 1;

    num_possible_block_sizes     = log2_max_num_subframes + 1;

    s->min_samples_per_subframe  = s->samples_per_frame / s->max_num_subframes;

    s->dynamic_range_compression = (s->decode_flags & 0x80);

    if (s->max_num_subframes > MAX_SUBFRAMES) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of subframes %"PRId8"\n",

               s->max_num_subframes);

        return AVERROR_INVALIDDATA;

    }

    if (s->min_samples_per_subframe < WMAPRO_BLOCK_MIN_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "min_samples_per_subframe of %d too small\n",

               s->min_samples_per_subframe);

        return AVERROR_INVALIDDATA;

    }

    if (s->avctx->sample_rate <= 0) {

        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->nb_channels <= 0) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of channels %d\n",

               s->nb_channels);

        return AVERROR_INVALIDDATA;

    } else if (s->nb_channels > WMAPRO_MAX_CHANNELS) {

        avpriv_request_sample(avctx,

                              "More than %d channels", WMAPRO_MAX_CHANNELS);

        return AVERROR_PATCHWELCOME;

    }

    /** init previous block len */

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

        s->channel[i].prev_block_len = s->samples_per_frame;

    /** extract lfe channel position */

    s->lfe_channel = -1;

    if (channel_mask & 8) {

        unsigned int mask;

        for (mask = 1; mask < 16; mask <<= 1) {

            if (channel_mask & mask)

                ++s->lfe_channel;

        }

    }

    INIT_VLC_STATIC(&sf_vlc, SCALEVLCBITS, HUFF_SCALE_SIZE,

                    scale_huffbits, 1, 1,

                    scale_huffcodes, 2, 2, 616);

    INIT_VLC_STATIC(&sf_rl_vlc, VLCBITS, HUFF_SCALE_RL_SIZE,

                    scale_rl_huffbits, 1, 1,

                    scale_rl_huffcodes, 4, 4, 1406);

    INIT_VLC_STATIC(&coef_vlc[0], VLCBITS, HUFF_COEF0_SIZE,

                    coef0_huffbits, 1, 1,

                    coef0_huffcodes, 4, 4, 2108);

    INIT_VLC_STATIC(&coef_vlc[1], VLCBITS, HUFF_COEF1_SIZE,

                    coef1_huffbits, 1, 1,

                    coef1_huffcodes, 4, 4, 3912);

    INIT_VLC_STATIC(&vec4_vlc, VLCBITS, HUFF_VEC4_SIZE,

                    vec4_huffbits, 1, 1,

                    vec4_huffcodes, 2, 2, 604);

    INIT_VLC_STATIC(&vec2_vlc, VLCBITS, HUFF_VEC2_SIZE,

                    vec2_huffbits, 1, 1,

                    vec2_huffcodes, 2, 2, 562);

    INIT_VLC_STATIC(&vec1_vlc, VLCBITS, HUFF_VEC1_SIZE,

                    vec1_huffbits, 1, 1,

                    vec1_huffcodes, 2, 2, 562);

    /** calculate number of scale factor bands and their offsets

        for every possible block size */

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

        int subframe_len = s->samples_per_frame >> i;

        int x;

        int band = 1;

        int rate = get_rate(avctx);

        s->sfb_offsets[i][0] = 0;

        for (x = 0; x < MAX_BANDS-1 && s->sfb_offsets[i][band - 1] < subframe_len; x++) {

            int offset = (subframe_len * 2 * critical_freq[x]) / rate + 2;

            offset &= ~3;

            if (offset > s->sfb_offsets[i][band - 1])

                s->sfb_offsets[i][band++] = offset;

            if (offset >= subframe_len)

                break;

        }

        s->sfb_offsets[i][band - 1] = subframe_len;

        s->num_sfb[i]               = band - 1;

        if (s->num_sfb[i] <= 0) {

            av_log(avctx, AV_LOG_ERROR, "num_sfb invalid\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /** Scale factors can be shared between blocks of different size

        as every block has a different scale factor band layout.

        The matrix sf_offsets is needed to find the correct scale factor.

     */

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

        int b;

        for (b = 0; b < s->num_sfb[i]; b++) {

            int x;

            int offset = ((s->sfb_offsets[i][b]

                           + s->sfb_offsets[i][b + 1] - 1) << i) >> 1;

            for (x = 0; x < num_possible_block_sizes; x++) {

                int v = 0;

                while (s->sfb_offsets[x][v + 1] << x < offset) {

                    v++;

                    av_assert0(v < MAX_BANDS);

                }

                s->sf_offsets[i][x][b] = v;

            }

        }

    }

    /** init MDCT, FIXME: only init needed sizes */

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

        ff_mdct_init(&s->mdct_ctx[i], WMAPRO_BLOCK_MIN_BITS+1+i, 1,

                     1.0 / (1 << (WMAPRO_BLOCK_MIN_BITS + i - 1))

                     / (1 << (s->bits_per_sample - 1)));

    /** init MDCT windows: simple sine window */

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

        const int win_idx = WMAPRO_BLOCK_MAX_BITS - i;

        ff_init_ff_sine_windows(win_idx);

        s->windows[WMAPRO_BLOCK_SIZES - i - 1] = ff_sine_windows[win_idx];

    }

    /** calculate subwoofer cutoff values */

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

        int block_size = s->samples_per_frame >> i;

        int cutoff = (440*block_size + 3LL * (s->avctx->sample_rate >> 1) - 1)

                     / s->avctx->sample_rate;

        s->subwoofer_cutoffs[i] = av_clip(cutoff, 4, block_size);

    }

    /** calculate sine values for the decorrelation matrix */

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

        sin64[i] = sin(i*M_PI / 64.0);

    if (avctx->debug & FF_DEBUG_BITSTREAM)

        dump_context(s);

    avctx->channel_layout = channel_mask;

    return 0;

}


static uint16_t qvirtio_pci_get_queue_size(QVirtioDevice *d)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    return qpci_io_readw(dev->pdev, dev->addr + VIRTIO_PCI_QUEUE_NUM);

}


int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,

    const void *buf, int count)

{

    int ret;

    ret = bdrv_pwrite(bs, offset, buf, count);

    if (ret < 0) {

        return ret;

    }

    /* No flush needed for cache=writethrough, it uses O_DSYNC */

    if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {

        bdrv_flush(bs);

    }

    return 0;

}


static void dnxhd_decode_dct_block_8(const DNXHDContext *ctx,

                                     RowContext *row, int n)

{

    dnxhd_decode_dct_block(ctx, row, n, 4, 32, 6);

}


int ff_h264_decode_slice_header(H264Context *h, H264SliceContext *sl)

{

    unsigned int first_mb_in_slice;

    unsigned int pps_id;

    int ret;

    unsigned int slice_type, tmp, i, j;

    int last_pic_structure, last_pic_droppable;

    int must_reinit;

    int needs_reinit = 0;

    int field_pic_flag, bottom_field_flag;

    int first_slice = sl == h->slice_ctx && !h->current_slice;

    int frame_num, picture_structure, droppable;

    PPS *pps;

    h->qpel_put = h->h264qpel.put_h264_qpel_pixels_tab;

    h->qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab;

    first_mb_in_slice = get_ue_golomb_long(&sl->gb);

    if (first_mb_in_slice == 0) { // FIXME better field boundary detection

        if (h->current_slice) {

            if (h->cur_pic_ptr && FIELD_PICTURE(h) && h->first_field) {

                ff_h264_field_end(h, sl, 1);

                h->current_slice = 0;

            } else if (h->cur_pic_ptr && !FIELD_PICTURE(h) && !h->first_field && h->nal_unit_type  == NAL_IDR_SLICE) {

                av_log(h, AV_LOG_WARNING, "Broken frame packetizing\n");

                ff_h264_field_end(h, sl, 1);

                h->current_slice = 0;

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);

                h->cur_pic_ptr = NULL;

            } else

                return AVERROR_INVALIDDATA;

        }

        if (!h->first_field) {

            if (h->cur_pic_ptr && !h->droppable) {

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                          h->picture_structure == PICT_BOTTOM_FIELD);

            }

            h->cur_pic_ptr = NULL;

        }

    }

    slice_type = get_ue_golomb_31(&sl->gb);

    if (slice_type > 9) {

        av_log(h->avctx, AV_LOG_ERROR,

               "slice type %d too large at %d\n",

               slice_type, first_mb_in_slice);

        return AVERROR_INVALIDDATA;

    }

    if (slice_type > 4) {

        slice_type -= 5;

        sl->slice_type_fixed = 1;

    } else

        sl->slice_type_fixed = 0;

    slice_type = golomb_to_pict_type[slice_type];

    sl->slice_type     = slice_type;

    sl->slice_type_nos = slice_type & 3;

    if (h->nal_unit_type  == NAL_IDR_SLICE &&

        sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");

        return AVERROR_INVALIDDATA;

    }

    if (

        (h->avctx->skip_frame >= AVDISCARD_NONREF && !h->nal_ref_idc) ||

        (h->avctx->skip_frame >= AVDISCARD_BIDIR  && sl->slice_type_nos == AV_PICTURE_TYPE_B) ||

        (h->avctx->skip_frame >= AVDISCARD_NONINTRA && sl->slice_type_nos != AV_PICTURE_TYPE_I) ||

        (h->avctx->skip_frame >= AVDISCARD_NONKEY && h->nal_unit_type != NAL_IDR_SLICE) ||

         h->avctx->skip_frame >= AVDISCARD_ALL) {

         return SLICE_SKIPED;

     }

    // to make a few old functions happy, it's wrong though

    h->pict_type = sl->slice_type;

    pps_id = get_ue_golomb(&sl->gb);

    if (pps_id >= MAX_PPS_COUNT) {

        av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (!h->pps_buffers[pps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing PPS %u referenced\n",

               pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (h->au_pps_id >= 0 && pps_id != h->au_pps_id) {

        av_log(h->avctx, AV_LOG_ERROR,

               "PPS change from %d to %d forbidden\n",

               h->au_pps_id, pps_id);

        return AVERROR_INVALIDDATA;

    }

    pps = h->pps_buffers[pps_id];

    if (!h->sps_buffers[pps->sps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing SPS %u referenced\n",

               h->pps.sps_id);

        return AVERROR_INVALIDDATA;

    }

    if (first_slice)

        h->pps = *h->pps_buffers[pps_id];

    if (pps->sps_id != h->sps.sps_id ||

        pps->sps_id != h->current_sps_id ||

        h->sps_buffers[pps->sps_id]->new) {

        if (!first_slice) {

            av_log(h->avctx, AV_LOG_ERROR,

               "SPS changed in the middle of the frame\n");

            return AVERROR_INVALIDDATA;

        }

        h->sps = *h->sps_buffers[h->pps.sps_id];

        if (h->mb_width  != h->sps.mb_width ||

            h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) ||

            h->cur_bit_depth_luma    != h->sps.bit_depth_luma ||

            h->cur_chroma_format_idc != h->sps.chroma_format_idc

        )

            needs_reinit = 1;

        if (h->bit_depth_luma    != h->sps.bit_depth_luma ||

            h->chroma_format_idc != h->sps.chroma_format_idc) {

            h->bit_depth_luma    = h->sps.bit_depth_luma;

            h->chroma_format_idc = h->sps.chroma_format_idc;

            needs_reinit         = 1;

        }

        if ((ret = ff_h264_set_parameter_from_sps(h)) < 0)

            return ret;

    }

    h->avctx->profile = ff_h264_get_profile(&h->sps);

    h->avctx->level   = h->sps.level_idc;

    h->avctx->refs    = h->sps.ref_frame_count;

    must_reinit = (h->context_initialized &&

                    (   16*h->sps.mb_width != h->avctx->coded_width

                     || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height

                     || h->cur_bit_depth_luma    != h->sps.bit_depth_luma

                     || h->cur_chroma_format_idc != h->sps.chroma_format_idc

                     || h->mb_width  != h->sps.mb_width

                     || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag)

                    ));

    if (h->avctx->pix_fmt == AV_PIX_FMT_NONE

        || (non_j_pixfmt(h->avctx->pix_fmt) != non_j_pixfmt(get_pixel_format(h, 0))))

        must_reinit = 1;

    if (first_slice && av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio))

        must_reinit = 1;

    h->mb_width  = h->sps.mb_width;

    h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);

    h->mb_num    = h->mb_width * h->mb_height;

    h->mb_stride = h->mb_width + 1;

    h->b_stride = h->mb_width * 4;

    h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p

    h->width  = 16 * h->mb_width;

    h->height = 16 * h->mb_height;

    ret = init_dimensions(h);

    if (ret < 0)

        return ret;

    if (h->sps.video_signal_type_present_flag) {

        h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG

                                                    : AVCOL_RANGE_MPEG;

        if (h->sps.colour_description_present_flag) {

            if (h->avctx->colorspace != h->sps.colorspace)

                needs_reinit = 1;

            h->avctx->color_primaries = h->sps.color_primaries;

            h->avctx->color_trc       = h->sps.color_trc;

            h->avctx->colorspace      = h->sps.colorspace;

        }

    }

    if (h->context_initialized &&

        (must_reinit || needs_reinit)) {

        if (sl != h->slice_ctx) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "changing width %d -> %d / height %d -> %d on "

                   "slice %d\n",

                   h->width, h->avctx->coded_width,

                   h->height, h->avctx->coded_height,

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

        av_assert1(first_slice);

        ff_h264_flush_change(h);

        if ((ret = get_pixel_format(h, 1)) < 0)

            return ret;

        h->avctx->pix_fmt = ret;

        av_log(h->avctx, AV_LOG_INFO, "Reinit context to %dx%d, "

               "pix_fmt: %s\n", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt));

        if ((ret = h264_slice_header_init(h, 1)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "h264_slice_header_init() failed\n");

            return ret;

        }

    }

    if (!h->context_initialized) {

        if (sl != h->slice_ctx) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Cannot (re-)initialize context during parallel decoding.\n");

            return AVERROR_PATCHWELCOME;

        }

        if ((ret = get_pixel_format(h, 1)) < 0)

            return ret;

        h->avctx->pix_fmt = ret;

        if ((ret = h264_slice_header_init(h, 0)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "h264_slice_header_init() failed\n");

            return ret;

        }

    }

    if (first_slice && h->dequant_coeff_pps != pps_id) {

        h->dequant_coeff_pps = pps_id;

        ff_h264_init_dequant_tables(h);

    }

    frame_num = get_bits(&sl->gb, h->sps.log2_max_frame_num);

    if (!first_slice) {

        if (h->frame_num != frame_num) {

            av_log(h->avctx, AV_LOG_ERROR, "Frame num change from %d to %d\n",

                   h->frame_num, frame_num);

            return AVERROR_INVALIDDATA;

        }

    }

    sl->mb_mbaff       = 0;

    h->mb_aff_frame    = 0;

    last_pic_structure = h->picture_structure;

    last_pic_droppable = h->droppable;

    droppable          = h->nal_ref_idc == 0;

    if (h->sps.frame_mbs_only_flag) {

        picture_structure = PICT_FRAME;

    } else {

        if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) {

            av_log(h->avctx, AV_LOG_ERROR, "This stream was generated by a broken encoder, invalid 8x8 inference\n");

            return -1;

        }

        field_pic_flag = get_bits1(&sl->gb);

        if (field_pic_flag) {

            bottom_field_flag = get_bits1(&sl->gb);

            picture_structure = PICT_TOP_FIELD + bottom_field_flag;

        } else {

            picture_structure = PICT_FRAME;

            h->mb_aff_frame      = h->sps.mb_aff;

        }

    }

    if (h->current_slice) {

        if (last_pic_structure != picture_structure ||

            last_pic_droppable != droppable) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Changing field mode (%d -> %d) between slices is not allowed\n",

                   last_pic_structure, h->picture_structure);

            return AVERROR_INVALIDDATA;

        } else if (!h->cur_pic_ptr) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "unset cur_pic_ptr on slice %d\n",

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

    }

    h->picture_structure = picture_structure;

    h->droppable         = droppable;

    h->frame_num         = frame_num;

    sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;

    if (h->current_slice == 0) {

        /* Shorten frame num gaps so we don't have to allocate reference

         * frames just to throw them away */

        if (h->frame_num != h->prev_frame_num) {

            int unwrap_prev_frame_num = h->prev_frame_num;

            int max_frame_num         = 1 << h->sps.log2_max_frame_num;

            if (unwrap_prev_frame_num > h->frame_num)

                unwrap_prev_frame_num -= max_frame_num;

            if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) {

                unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1;

                if (unwrap_prev_frame_num < 0)

                    unwrap_prev_frame_num += max_frame_num;

                h->prev_frame_num = unwrap_prev_frame_num;

            }

        }

        /* See if we have a decoded first field looking for a pair...

         * Here, we're using that to see if we should mark previously

         * decode frames as "finished".

         * We have to do that before the "dummy" in-between frame allocation,

         * since that can modify h->cur_pic_ptr. */

        if (h->first_field) {

            assert(h->cur_pic_ptr);

            assert(h->cur_pic_ptr->f.buf[0]);

            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);

            /* Mark old field/frame as completed */

            if (h->cur_pic_ptr->tf.owner == h->avctx) {

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                          last_pic_structure == PICT_BOTTOM_FIELD);

            }

            /* figure out if we have a complementary field pair */

            if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {

                /* Previous field is unmatched. Don't display it, but let it

                 * remain for reference if marked as such. */

                if (last_pic_structure != PICT_FRAME) {

                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                              last_pic_structure == PICT_TOP_FIELD);

                }

            } else {

                if (h->cur_pic_ptr->frame_num != h->frame_num) {

                    /* This and previous field were reference, but had

                     * different frame_nums. Consider this field first in

                     * pair. Throw away previous field except for reference

                     * purposes. */

                    if (last_pic_structure != PICT_FRAME) {

                        ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                                  last_pic_structure == PICT_TOP_FIELD);

                    }

                } else {

                    /* Second field in complementary pair */

                    if (!((last_pic_structure   == PICT_TOP_FIELD &&

                           h->picture_structure == PICT_BOTTOM_FIELD) ||

                          (last_pic_structure   == PICT_BOTTOM_FIELD &&

                           h->picture_structure == PICT_TOP_FIELD))) {

                        av_log(h->avctx, AV_LOG_ERROR,

                               "Invalid field mode combination %d/%d\n",

                               last_pic_structure, h->picture_structure);

                        h->picture_structure = last_pic_structure;

                        h->droppable         = last_pic_droppable;

                        return AVERROR_INVALIDDATA;

                    } else if (last_pic_droppable != h->droppable) {

                        avpriv_request_sample(h->avctx,

                                              "Found reference and non-reference fields in the same frame, which");

                        h->picture_structure = last_pic_structure;

                        h->droppable         = last_pic_droppable;

                        return AVERROR_PATCHWELCOME;

                    }

                }

            }

        }

        while (h->frame_num != h->prev_frame_num && !h->first_field &&

               h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) {

            H264Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL;

            av_log(h->avctx, AV_LOG_DEBUG, "Frame num gap %d %d\n",

                   h->frame_num, h->prev_frame_num);

            if (!h->sps.gaps_in_frame_num_allowed_flag)

                for(i=0; i<FF_ARRAY_ELEMS(h->last_pocs); i++)

                    h->last_pocs[i] = INT_MIN;

            ret = h264_frame_start(h);

            if (ret < 0) {

                h->first_field = 0;

                return ret;

            }

            h->prev_frame_num++;

            h->prev_frame_num        %= 1 << h->sps.log2_max_frame_num;

            h->cur_pic_ptr->frame_num = h->prev_frame_num;

            h->cur_pic_ptr->invalid_gap = !h->sps.gaps_in_frame_num_allowed_flag;

            ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0);

            ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1);

            ret = ff_generate_sliding_window_mmcos(h, 1);

            if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

                return ret;

            ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);

            if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

                return ret;

            /* Error concealment: If a ref is missing, copy the previous ref

             * in its place.

             * FIXME: Avoiding a memcpy would be nice, but ref handling makes

             * many assumptions about there being no actual duplicates.

             * FIXME: This does not copy padding for out-of-frame motion

             * vectors.  Given we are concealing a lost frame, this probably

             * is not noticeable by comparison, but it should be fixed. */

            if (h->short_ref_count) {

                if (prev) {

                    av_image_copy(h->short_ref[0]->f.data,

                                  h->short_ref[0]->f.linesize,

                                  (const uint8_t **)prev->f.data,

                                  prev->f.linesize,

                                  h->avctx->pix_fmt,

                                  h->mb_width  * 16,

                                  h->mb_height * 16);

                    h->short_ref[0]->poc = prev->poc + 2;

                }

                h->short_ref[0]->frame_num = h->prev_frame_num;

            }

        }

        /* See if we have a decoded first field looking for a pair...

         * We're using that to see whether to continue decoding in that

         * frame, or to allocate a new one. */

        if (h->first_field) {

            assert(h->cur_pic_ptr);

            assert(h->cur_pic_ptr->f.buf[0]);

            assert(h->cur_pic_ptr->reference != DELAYED_PIC_REF);

            /* figure out if we have a complementary field pair */

            if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) {

                /* Previous field is unmatched. Don't display it, but let it

                 * remain for reference if marked as such. */

                h->missing_fields ++;

                h->cur_pic_ptr = NULL;

                h->first_field = FIELD_PICTURE(h);

            } else {

                h->missing_fields = 0;

                if (h->cur_pic_ptr->frame_num != h->frame_num) {

                    ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                              h->picture_structure==PICT_BOTTOM_FIELD);

                    /* This and the previous field had different frame_nums.

                     * Consider this field first in pair. Throw away previous

                     * one except for reference purposes. */

                    h->first_field = 1;

                    h->cur_pic_ptr = NULL;

                } else {

                    /* Second field in complementary pair */

                    h->first_field = 0;

                }

            }

        } else {

            /* Frame or first field in a potentially complementary pair */

            h->first_field = FIELD_PICTURE(h);

        }

        if (!FIELD_PICTURE(h) || h->first_field) {

            if (h264_frame_start(h) < 0) {

                h->first_field = 0;

                return AVERROR_INVALIDDATA;

            }

        } else {

            release_unused_pictures(h, 0);

        }

        /* Some macroblocks can be accessed before they're available in case

        * of lost slices, MBAFF or threading. */

        if (FIELD_PICTURE(h)) {

            for(i = (h->picture_structure == PICT_BOTTOM_FIELD); i<h->mb_height; i++)

                memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table));

        } else {

            memset(h->slice_table, -1,

                (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table));

        }

        h->last_slice_type = -1;

    }

    h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup

    av_assert1(h->mb_num == h->mb_width * h->mb_height);

    if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||

        first_mb_in_slice >= h->mb_num) {

        av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");

        return AVERROR_INVALIDDATA;

    }

    sl->resync_mb_x = sl->mb_x =  first_mb_in_slice % h->mb_width;

    sl->resync_mb_y = sl->mb_y = (first_mb_in_slice / h->mb_width) <<

                                 FIELD_OR_MBAFF_PICTURE(h);

    if (h->picture_structure == PICT_BOTTOM_FIELD)

        sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;

    av_assert1(sl->mb_y < h->mb_height);

    if (h->picture_structure == PICT_FRAME) {

        h->curr_pic_num = h->frame_num;

        h->max_pic_num  = 1 << h->sps.log2_max_frame_num;

    } else {

        h->curr_pic_num = 2 * h->frame_num + 1;

        h->max_pic_num  = 1 << (h->sps.log2_max_frame_num + 1);

    }

    if (h->nal_unit_type == NAL_IDR_SLICE)

        get_ue_golomb(&sl->gb); /* idr_pic_id */

    if (h->sps.poc_type == 0) {

        h->poc_lsb = get_bits(&sl->gb, h->sps.log2_max_poc_lsb);

        if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)

            h->delta_poc_bottom = get_se_golomb(&sl->gb);

    }

    if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) {

        h->delta_poc[0] = get_se_golomb(&sl->gb);

        if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME)

            h->delta_poc[1] = get_se_golomb(&sl->gb);

    }

    ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc);

    if (h->pps.redundant_pic_cnt_present)

        sl->redundant_pic_count = get_ue_golomb(&sl->gb);

    ret = ff_set_ref_count(h, sl);

    if (ret < 0)

        return ret;

    if (slice_type != AV_PICTURE_TYPE_I &&

        (h->current_slice == 0 ||

         slice_type != h->last_slice_type ||

         memcmp(h->last_ref_count, sl->ref_count, sizeof(sl->ref_count)))) {

        ff_h264_fill_default_ref_list(h, sl);

    }

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

       ret = ff_h264_decode_ref_pic_list_reordering(h, sl);

       if (ret < 0) {

           sl->ref_count[1] = sl->ref_count[0] = 0;

           return ret;

       }

    }

    if ((h->pps.weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||

        (h->pps.weighted_bipred_idc == 1 &&

         sl->slice_type_nos == AV_PICTURE_TYPE_B))

        ff_pred_weight_table(h, sl);

    else if (h->pps.weighted_bipred_idc == 2 &&

             sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        implicit_weight_table(h, sl, -1);

    } else {

        sl->use_weight = 0;

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

            sl->luma_weight_flag[i]   = 0;

            sl->chroma_weight_flag[i] = 0;

        }

    }

    // If frame-mt is enabled, only update mmco tables for the first slice

    // in a field. Subsequent slices can temporarily clobber h->mmco_index

    // or h->mmco, which will cause ref list mix-ups and decoding errors

    // further down the line. This may break decoding if the first slice is

    // corrupt, thus we only do this if frame-mt is enabled.

    if (h->nal_ref_idc) {

        ret = ff_h264_decode_ref_pic_marking(h, &sl->gb,

                                             !(h->avctx->active_thread_type & FF_THREAD_FRAME) ||

                                             h->current_slice == 0);

        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

            return AVERROR_INVALIDDATA;

    }

    if (FRAME_MBAFF(h)) {

        ff_h264_fill_mbaff_ref_list(h, sl);

        if (h->pps.weighted_bipred_idc == 2 && sl->slice_type_nos == AV_PICTURE_TYPE_B) {

            implicit_weight_table(h, sl, 0);

            implicit_weight_table(h, sl, 1);

        }

    }

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)

        ff_h264_direct_dist_scale_factor(h, sl);

    ff_h264_direct_ref_list_init(h, sl);

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->cabac_init_idc = tmp;

    }

    sl->last_qscale_diff = 0;

    tmp = h->pps.init_qp + get_se_golomb(&sl->gb);

    if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) {

        av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);

        return AVERROR_INVALIDDATA;

    }

    sl->qscale       = tmp;

    sl->chroma_qp[0] = get_chroma_qp(h, 0, sl->qscale);

    sl->chroma_qp[1] = get_chroma_qp(h, 1, sl->qscale);

    // FIXME qscale / qp ... stuff

    if (sl->slice_type == AV_PICTURE_TYPE_SP)

        get_bits1(&sl->gb); /* sp_for_switch_flag */

    if (sl->slice_type == AV_PICTURE_TYPE_SP ||

        sl->slice_type == AV_PICTURE_TYPE_SI)

        get_se_golomb(&sl->gb); /* slice_qs_delta */

    sl->deblocking_filter     = 1;

    sl->slice_alpha_c0_offset = 0;

    sl->slice_beta_offset     = 0;

    if (h->pps.deblocking_filter_parameters_present) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "deblocking_filter_idc %u out of range\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->deblocking_filter = tmp;

        if (sl->deblocking_filter < 2)

            sl->deblocking_filter ^= 1;  // 1<->0

        if (sl->deblocking_filter) {

            sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;

            sl->slice_beta_offset     = get_se_golomb(&sl->gb) * 2;

            if (sl->slice_alpha_c0_offset >  12 ||

                sl->slice_alpha_c0_offset < -12 ||

                sl->slice_beta_offset >  12     ||

                sl->slice_beta_offset < -12) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "deblocking filter parameters %d %d out of range\n",

                       sl->slice_alpha_c0_offset, sl->slice_beta_offset);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&

         h->nal_unit_type != NAL_IDR_SLICE) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&

         sl->slice_type_nos != AV_PICTURE_TYPE_I) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&

         sl->slice_type_nos == AV_PICTURE_TYPE_B) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&

         h->nal_ref_idc == 0))

        sl->deblocking_filter = 0;

    if (sl->deblocking_filter == 1 && h->max_contexts > 1) {

        if (h->avctx->flags2 & CODEC_FLAG2_FAST) {

            /* Cheat slightly for speed:

             * Do not bother to deblock across slices. */

            sl->deblocking_filter = 2;

        } else {

            h->max_contexts = 1;

            if (!h->single_decode_warning) {

                av_log(h->avctx, AV_LOG_INFO,

                       "Cannot parallelize slice decoding with deblocking filter type 1, decoding such frames in sequential order\n"

                       "To parallelize slice decoding you need video encoded with disable_deblocking_filter_idc set to 2 (deblock only edges that do not cross slices).\n"

                       "Setting the flags2 libavcodec option to +fast (-flags2 +fast) will disable deblocking across slices and enable parallel slice decoding "

                       "but will generate non-standard-compliant output.\n");

                h->single_decode_warning = 1;

            }

            if (sl != h->slice_ctx) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "Deblocking switched inside frame.\n");

                return SLICE_SINGLETHREAD;

            }

        }

    }

    sl->qp_thresh = 15 -

                   FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -

                   FFMAX3(0,

                          h->pps.chroma_qp_index_offset[0],

                          h->pps.chroma_qp_index_offset[1]) +

                   6 * (h->sps.bit_depth_luma - 8);

    h->last_slice_type = slice_type;

    memcpy(h->last_ref_count, sl->ref_count, sizeof(h->last_ref_count));

    sl->slice_num       = ++h->current_slice;

    if (sl->slice_num)

        h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;

    if (   h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y

        && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y

        && sl->slice_num >= MAX_SLICES) {

        //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case

        av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);

    }

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

        int id_list[16];

        int *ref2frm = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];

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

            id_list[i] = 60;

            if (j < sl->list_count && i < sl->ref_count[j] &&

                sl->ref_list[j][i].parent->f.buf[0]) {

                int k;

                AVBuffer *buf = sl->ref_list[j][i].parent->f.buf[0]->buffer;

                for (k = 0; k < h->short_ref_count; k++)

                    if (h->short_ref[k]->f.buf[0]->buffer == buf) {

                        id_list[i] = k;

                        break;

                    }

                for (k = 0; k < h->long_ref_count; k++)

                    if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) {

                        id_list[i] = h->short_ref_count + k;

                        break;

                    }

            }

        }

        ref2frm[0] =

        ref2frm[1] = -1;

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

            ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);

        ref2frm[18 + 0] =

        ref2frm[18 + 1] = -1;

        for (i = 16; i < 48; i++)

            ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +

                             (sl->ref_list[j][i].reference & 3);

    }

    h->au_pps_id = pps_id;

    h->sps.new =

    h->sps_buffers[h->pps.sps_id]->new = 0;

    h->current_sps_id = h->pps.sps_id;

    if (h->avctx->debug & FF_DEBUG_PICT_INFO) {

        av_log(h->avctx, AV_LOG_DEBUG,

               "slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",

               sl->slice_num,

               (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),

               first_mb_in_slice,

               av_get_picture_type_char(sl->slice_type),

               sl->slice_type_fixed ? " fix" : "",

               h->nal_unit_type == NAL_IDR_SLICE ? " IDR" : "",

               pps_id, h->frame_num,

               h->cur_pic_ptr->field_poc[0],

               h->cur_pic_ptr->field_poc[1],

               sl->ref_count[0], sl->ref_count[1],

               sl->qscale,

               sl->deblocking_filter,

               sl->slice_alpha_c0_offset, sl->slice_beta_offset,

               sl->use_weight,

               sl->use_weight == 1 && sl->use_weight_chroma ? "c" : "",

               sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");

    }

    return 0;

}


static int wv_get_value(WavpackFrameContext *ctx, GetBitContext *gb,

                        int channel, int *last)

{

    int t, t2;

    int sign, base, add, ret;

    WvChannel *c = &ctx->ch[channel];

    *last = 0;

    if ((ctx->ch[0].median[0] < 2U) && (ctx->ch[1].median[0] < 2U) &&

        !ctx->zero && !ctx->one) {

        if (ctx->zeroes) {

            ctx->zeroes--;

            if (ctx->zeroes) {

                c->slow_level -= LEVEL_DECAY(c->slow_level);

                return 0;

        } else {

            t = get_unary_0_33(gb);

            if (t >= 2) {

                if (get_bits_left(gb) < t - 1)

                t = get_bits(gb, t - 1) | (1 << (t-1));

            } else {

                if (get_bits_left(gb) < 0)

            ctx->zeroes = t;

            if (ctx->zeroes) {

                memset(ctx->ch[0].median, 0, sizeof(ctx->ch[0].median));

                memset(ctx->ch[1].median, 0, sizeof(ctx->ch[1].median));

                c->slow_level -= LEVEL_DECAY(c->slow_level);

                return 0;

    if (ctx->zero) {

        t = 0;

        ctx->zero = 0;

    } else {

        t = get_unary_0_33(gb);

        if (get_bits_left(gb) < 0)

        if (t == 16) {

            t2 = get_unary_0_33(gb);

            if (t2 < 2) {

                if (get_bits_left(gb) < 0)

                t += t2;

            } else {

                if (get_bits_left(gb) < t2 - 1)

                t += get_bits(gb, t2 - 1) | (1 << (t2 - 1));

        if (ctx->one) {

            ctx->one = t & 1;

            t = (t >> 1) + 1;

        } else {

            ctx->one = t & 1;

            t >>= 1;

        ctx->zero = !ctx->one;

    if (ctx->hybrid && !channel)

        update_error_limit(ctx);

    if (!t) {

        base = 0;

        add  = GET_MED(0) - 1;

        DEC_MED(0);

    } else if (t == 1) {

        base = GET_MED(0);

        add  = GET_MED(1) - 1;

        INC_MED(0);

        DEC_MED(1);

    } else if (t == 2) {

        base = GET_MED(0) + GET_MED(1);

        add  = GET_MED(2) - 1;

        INC_MED(0);

        INC_MED(1);

        DEC_MED(2);

    } else {

        base = GET_MED(0) + GET_MED(1) + GET_MED(2) * (t - 2);

        add  = GET_MED(2) - 1;

        INC_MED(0);

        INC_MED(1);

        INC_MED(2);

    if (!c->error_limit) {

        ret = base + get_tail(gb, add);

        if (get_bits_left(gb) <= 0)

    } else {

        int mid = (base * 2 + add + 1) >> 1;

        while (add > c->error_limit) {

            if (get_bits_left(gb) <= 0)

            if (get_bits1(gb)) {

                add -= (mid - base);

                base = mid;

            } else

                add = mid - base - 1;

            mid = (base * 2 + add + 1) >> 1;

        ret = mid;

    sign = get_bits1(gb);

    if (ctx->hybrid_bitrate)

        c->slow_level += wp_log2(ret) - LEVEL_DECAY(c->slow_level);

    return sign ? ~ret : ret;

error:

    *last = 1;

    return 0;


static pxa2xx_timer_info *pxa2xx_timer_init(target_phys_addr_t base,

                qemu_irq *irqs)

{

    int i;

    int iomemtype;

    pxa2xx_timer_info *s;

    s = (pxa2xx_timer_info *) qemu_mallocz(sizeof(pxa2xx_timer_info));

    s->base = base;

    s->irq_enabled = 0;

    s->oldclock = 0;

    s->clock = 0;

    s->lastload = qemu_get_clock(vm_clock);

    s->reset3 = 0;

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

        s->timer[i].value = 0;

        s->timer[i].irq = irqs[i];

        s->timer[i].info = s;

        s->timer[i].num = i;

        s->timer[i].level = 0;

        s->timer[i].qtimer = qemu_new_timer(vm_clock,

                        pxa2xx_timer_tick, &s->timer[i]);

    }

    iomemtype = cpu_register_io_memory(0, pxa2xx_timer_readfn,

                    pxa2xx_timer_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    register_savevm("pxa2xx_timer", 0, 0,

                    pxa2xx_timer_save, pxa2xx_timer_load, s);

    return s;

}


static void http_write_packet(void *opaque,

                              unsigned char *buf, int size)

{

    HTTPContext *c = opaque;

    if (c->buffer_ptr == c->buffer_end || !c->buffer_ptr)

        c->buffer_ptr = c->buffer_end = c->buffer;

    if (c->buffer_end - c->buffer + size > IOBUFFER_MAX_SIZE)

        abort();

    memcpy(c->buffer_end, buf, size);

    c->buffer_end += size;

}


void net_rx_pkt_attach_iovec_ex(struct NetRxPkt *pkt,

                                const struct iovec *iov, int iovcnt,

                                size_t iovoff, bool strip_vlan,

                                uint16_t vet)

{

    uint16_t tci = 0;

    uint16_t ploff = iovoff;

    assert(pkt);

    pkt->vlan_stripped = false;

    if (strip_vlan) {

        pkt->vlan_stripped = eth_strip_vlan_ex(iov, iovcnt, iovoff, vet,

                                               pkt->ehdr_buf,

                                               &ploff, &tci);

    }

    pkt->tci = tci;

    net_rx_pkt_pull_data(pkt, iov, iovcnt, ploff);

}


static int http_read_stream(URLContext *h, uint8_t *buf, int size)

{

    HTTPContext *s = h->priv_data;

    int err, new_location;

    if (!s->hd)

        return AVERROR_EOF;

    if (s->end_chunked_post && !s->end_header) {

        err = http_read_header(h, &new_location);

        if (err < 0)

            return err;

    }

    if (s->chunksize >= 0) {

        if (!s->chunksize) {

            char line[32];

            for (;;) {

                do {

                    if ((err = http_get_line(s, line, sizeof(line))) < 0)

                        return err;

                } while (!*line);    /* skip CR LF from last chunk */

                s->chunksize = strtoll(line, NULL, 16);

                av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",

                        s->chunksize);

                if (!s->chunksize)

                    return 0;

                break;

            }

        }

        size = FFMIN(size, s->chunksize);

    }

#if CONFIG_ZLIB

    if (s->compressed)

        return http_buf_read_compressed(h, buf, size);

#endif /* CONFIG_ZLIB */

    return http_buf_read(h, buf, size);

}


static int lag_read_prob_header(lag_rac *rac, GetBitContext *gb)

{

    int i, j, scale_factor;

    unsigned prob, cumulative_target;

    unsigned cumul_prob = 0;

    unsigned scaled_cumul_prob = 0;

    rac->prob[0] = 0;

    rac->prob[257] = UINT_MAX;

    /* Read probabilities from bitstream */

    for (i = 1; i < 257; i++) {

        if (lag_decode_prob(gb, &rac->prob[i]) < 0) {

            av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability encountered.\n");

            return -1;

        }

        if ((uint64_t)cumul_prob + rac->prob[i] > UINT_MAX) {

            av_log(rac->avctx, AV_LOG_ERROR, "Integer overflow encountered in cumulative probability calculation.\n");

            return -1;

        }

        cumul_prob += rac->prob[i];

        if (!rac->prob[i]) {

            if (lag_decode_prob(gb, &prob)) {

                av_log(rac->avctx, AV_LOG_ERROR, "Invalid probability run encountered.\n");

                return -1;

            }

            if (prob > 256 - i)

                prob = 256 - i;

            for (j = 0; j < prob; j++)

                rac->prob[++i] = 0;

        }

    }

    if (!cumul_prob) {

        av_log(rac->avctx, AV_LOG_ERROR, "All probabilities are 0!\n");

        return -1;

    }

    /* Scale probabilities so cumulative probability is an even power of 2. */

    scale_factor = av_log2(cumul_prob);

    if (cumul_prob & (cumul_prob - 1)) {

        uint64_t mul = softfloat_reciprocal(cumul_prob);

        for (i = 1; i <= 128; i++) {

            rac->prob[i] = softfloat_mul(rac->prob[i], mul);

            scaled_cumul_prob += rac->prob[i];

        }

        if (scaled_cumul_prob <= 0) {

            av_log(rac->avctx, AV_LOG_ERROR, "Scaled probabilities invalid\n");

            return AVERROR_INVALIDDATA;

        }

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

            rac->prob[i] = softfloat_mul(rac->prob[i], mul);

            scaled_cumul_prob += rac->prob[i];

        }

        scale_factor++;

        cumulative_target = 1 << scale_factor;

        if (scaled_cumul_prob > cumulative_target) {

            av_log(rac->avctx, AV_LOG_ERROR,

                   "Scaled probabilities are larger than target!\n");

            return -1;

        }

        scaled_cumul_prob = cumulative_target - scaled_cumul_prob;

        for (i = 1; scaled_cumul_prob; i = (i & 0x7f) + 1) {

            if (rac->prob[i]) {

                rac->prob[i]++;

                scaled_cumul_prob--;

            }

            /* Comment from reference source:

             * if (b & 0x80 == 0) {     // order of operations is 'wrong'; it has been left this way

             *                          // since the compression change is negligible and fixing it

             *                          // breaks backwards compatibility

             *      b =- (signed int)b;

             *      b &= 0xFF;

             * } else {

             *      b++;

             *      b &= 0x7f;

             * }

             */

        }

    }

    rac->scale = scale_factor;

    /* Fill probability array with cumulative probability for each symbol. */

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

        rac->prob[i] += rac->prob[i - 1];

    return 0;

}


static int ata_passthrough_12_xfer_size(SCSIDevice *dev, uint8_t *buf)

{

    int length = buf[2] & 0x3;

    int xfer;

    int unit = ata_passthrough_xfer_unit(dev, buf);

    switch (length) {

    case 0:

    case 3: /* USB-specific.  */

        xfer = 0;

        break;

    case 1:

        xfer = buf[3];

        break;

    case 2:

        xfer = buf[4];

        break;

    }

    return xfer * unit;

}


static inline void downmix_2f_2r_to_stereo(float *samples)

{

    int i;

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

        samples[i] += samples[i + 512];

        samples[i + 256] = samples[i + 768];

        samples[i + 512] = samples[i + 768] = 0;

    }

}


static int video_read_header(AVFormatContext *s,

                             AVFormatParameters *ap)

{

    AVStream *st;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR_NOMEM;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = s->iformat->value;

    st->need_parsing = 1;

    /* for mjpeg, specify frame rate */

    /* for mpeg4 specify it too (most mpeg4 streams dont have the fixed_vop_rate set ...)*/

    if (ap && ap->time_base.num) {

        av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);

    } else if ( st->codec->codec_id == CODEC_ID_MJPEG ||

                st->codec->codec_id == CODEC_ID_MPEG4 ||

                st->codec->codec_id == CODEC_ID_H264) {

        av_set_pts_info(st, 64, 1, 25);

    }

    return 0;

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    static int counter = 0;

    int i;

    init_get_bits(&gb, buf, buf_size * 8);

    if (s->theora && get_bits1(&gb))

    {

#if 1

        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");

        return -1;

#else

        int ptype = get_bits(&gb, 7);

        skip_bits(&gb, 6*8); /* "theora" */

        switch(ptype)

        {

            case 1:

                theora_decode_comments(avctx, gb);

                break;

            case 2:

                theora_decode_tables(avctx, gb);

                    init_dequantizer(s);

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype);

        }

        return buf_size;

#endif

    }

    s->keyframe = !get_bits1(&gb);

    if (!s->theora)

        skip_bits(&gb, 1);

    s->last_quality_index = s->quality_index;

    s->quality_index = get_bits(&gb, 6);

    if (s->theora >= 0x030200)

        skip_bits1(&gb);

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",

            s->keyframe?"key":"", counter, s->quality_index);

    counter++;

    if (s->quality_index != s->last_quality_index) {

        init_dequantizer(s);

        init_loop_filter(s);

    }

    if (s->keyframe) {

        if (!s->theora)

        {

            skip_bits(&gb, 4); /* width code */

            skip_bits(&gb, 4); /* height code */

            if (s->version)

            {

                s->version = get_bits(&gb, 5);

                if (counter == 1)

                    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);

            }

        }

        if (s->version || s->theora)

        {

                if (get_bits1(&gb))

                    av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");

            skip_bits(&gb, 2); /* reserved? */

        }

        if (s->last_frame.data[0] == s->golden_frame.data[0]) {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */

        } else {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            if (s->last_frame.data[0])

                avctx->release_buffer(avctx, &s->last_frame);

        }

        s->golden_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

        /* golden frame is also the current frame */

        memcpy(&s->current_frame, &s->golden_frame, sizeof(AVFrame));

        /* time to figure out pixel addresses? */

        if (!s->pixel_addresses_inited)

        {

            if (!s->flipped_image)

                vp3_calculate_pixel_addresses(s);

            else

                theora_calculate_pixel_addresses(s);

        }

    } else {

        /* allocate a new current frame */

        s->current_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->current_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

    }

    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame

    s->current_frame.qstride= 0;

    {START_TIMER

    init_frame(s, &gb);

    STOP_TIMER("init_frame")}

#if KEYFRAMES_ONLY

if (!s->keyframe) {

    memcpy(s->current_frame.data[0], s->golden_frame.data[0],

        s->current_frame.linesize[0] * s->height);

    memcpy(s->current_frame.data[1], s->golden_frame.data[1],

        s->current_frame.linesize[1] * s->height / 2);

    memcpy(s->current_frame.data[2], s->golden_frame.data[2],

        s->current_frame.linesize[2] * s->height / 2);

} else {

#endif

    {START_TIMER

    if (unpack_superblocks(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");

        return -1;

    }

    STOP_TIMER("unpack_superblocks")}

    {START_TIMER

    if (unpack_modes(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");

        return -1;

    }

    STOP_TIMER("unpack_modes")}

    {START_TIMER

    if (unpack_vectors(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");

        return -1;

    }

    STOP_TIMER("unpack_vectors")}

    {START_TIMER

    if (unpack_dct_coeffs(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");

        return -1;

    }

    STOP_TIMER("unpack_dct_coeffs")}

    {START_TIMER

    reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);

    if ((avctx->flags & CODEC_FLAG_GRAY) == 0) {

        reverse_dc_prediction(s, s->u_fragment_start,

            s->fragment_width / 2, s->fragment_height / 2);

        reverse_dc_prediction(s, s->v_fragment_start,

            s->fragment_width / 2, s->fragment_height / 2);

    }

    STOP_TIMER("reverse_dc_prediction")}

    {START_TIMER

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

        render_slice(s, i);

    STOP_TIMER("render_fragments")}

    {START_TIMER

    apply_loop_filter(s);

    STOP_TIMER("apply_loop_filter")}

#if KEYFRAMES_ONLY

}

#endif

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data= s->current_frame;

    /* release the last frame, if it is allocated and if it is not the

     * golden frame */

    if ((s->last_frame.data[0]) &&

        (s->last_frame.data[0] != s->golden_frame.data[0]))

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames (last = current) */

    memcpy(&s->last_frame, &s->current_frame, sizeof(AVFrame));

    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */

    return buf_size;

}


static inline int host_to_target_errno(int err)

{

    if(host_to_target_errno_table[err])

        return host_to_target_errno_table[err];

    return err;

}


void backup_start(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *target, int64_t speed,

                  MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,

                  bool compress,

                  BlockdevOnError on_source_error,

                  BlockdevOnError on_target_error,

                  int creation_flags,

                  BlockCompletionFunc *cb, void *opaque,

                  BlockJobTxn *txn, Error **errp)

{

    int64_t len;

    BlockDriverInfo bdi;

    BackupBlockJob *job = NULL;

    int ret;

    assert(bs);

    assert(target);

    if (bs == target) {

        error_setg(errp, "Source and target cannot be the same");

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(bs));

        return;

    }

    if (!bdrv_is_inserted(target)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(target));

        return;

    }

    if (compress && target->drv->bdrv_co_pwritev_compressed == NULL) {

        error_setg(errp, "Compression is not supported for this drive %s",

                   bdrv_get_device_name(target));

        return;

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        return;

    }

    if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {

        return;

    }

    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {

        if (!sync_bitmap) {

            error_setg(errp, "must provide a valid bitmap name for "

                             "\"incremental\" sync mode");

            return;

        }

        /* Create a new bitmap, and freeze/disable this one. */

        if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {

            return;

        }

    } else if (sync_bitmap) {

        error_setg(errp,

                   "a sync_bitmap was provided to backup_run, "

                   "but received an incompatible sync_mode (%s)",

                   MirrorSyncMode_lookup[sync_mode]);

        return;

    }

    len = bdrv_getlength(bs);

    if (len < 0) {

        error_setg_errno(errp, -len, "unable to get length for '%s'",

                         bdrv_get_device_name(bs));

        goto error;

    }

    job = block_job_create(job_id, &backup_job_driver, bs, speed,

                           creation_flags, cb, opaque, errp);

    if (!job) {

        goto error;

    }

    job->target = blk_new();

    blk_insert_bs(job->target, target);

    job->on_source_error = on_source_error;

    job->on_target_error = on_target_error;

    job->sync_mode = sync_mode;

    job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?

                       sync_bitmap : NULL;

    job->compress = compress;

    /* If there is no backing file on the target, we cannot rely on COW if our

     * backup cluster size is smaller than the target cluster size. Even for

     * targets with a backing file, try to avoid COW if possible. */

    ret = bdrv_get_info(target, &bdi);

    if (ret < 0 && !target->backing) {

        error_setg_errno(errp, -ret,

            "Couldn't determine the cluster size of the target image, "

            "which has no backing file");

        error_append_hint(errp,

            "Aborting, since this may create an unusable destination image\n");

        goto error;

    } else if (ret < 0 && target->backing) {

        /* Not fatal; just trudge on ahead. */

        job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;

    } else {

        job->cluster_size = MAX(BACKUP_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);

    }

    block_job_add_bdrv(&job->common, target);

    job->common.len = len;

    job->common.co = qemu_coroutine_create(backup_run, job);

    block_job_txn_add_job(txn, &job->common);

    qemu_coroutine_enter(job->common.co);

    return;

 error:

    if (sync_bitmap) {

        bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);

    }

    if (job) {

        blk_unref(job->target);

        block_job_unref(&job->common);

    }

}


static void restart_co_req(void *opaque)

{

    Coroutine *co = opaque;

    qemu_coroutine_enter(co, NULL);

}


static void nbd_coroutine_start(NBDClientSession *s,

                                NBDRequest *request)

{

    /* Poor man semaphore.  The free_sema is locked when no other request

     * can be accepted, and unlocked after receiving one reply.  */

    if (s->in_flight == MAX_NBD_REQUESTS) {

        qemu_co_queue_wait(&s->free_sema, NULL);

        assert(s->in_flight < MAX_NBD_REQUESTS);

    }

    s->in_flight++;

    /* s->recv_coroutine[i] is set as soon as we get the send_lock.  */

}


void ff_h264_direct_dist_scale_factor(H264Context *const h)

{

    const int poc  = h->cur_pic_ptr->field_poc[h->picture_structure == PICT_BOTTOM_FIELD];

    const int poc1 = h->ref_list[1][0].poc;

    int i, field;

    if (FRAME_MBAFF(h))

        for (field = 0; field < 2; field++) {

            const int poc  = h->cur_pic_ptr->field_poc[field];

            const int poc1 = h->ref_list[1][0].field_poc[field];

            for (i = 0; i < 2 * h->ref_count[0]; i++)

                h->dist_scale_factor_field[field][i ^ field] =

                    get_scale_factor(h, poc, poc1, i + 16);

        }

    for (i = 0; i < h->ref_count[0]; i++)

        h->dist_scale_factor[i] = get_scale_factor(h, poc, poc1, i);

}


static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,

    QDict *options, int flags, BlockDriver *drv)

{

    int ret, open_flags;

    const char *filename;

    assert(drv != NULL);

    assert(bs->file == NULL);

    assert(options != NULL && bs->options != options);

    trace_bdrv_open_common(bs, filename, flags, drv->format_name);

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {

        return -ENOTSUP;

    }

    /* bdrv_open() with directly using a protocol as drv. This layer is already

     * opened, so assign it to bs (while file becomes a closed BlockDriverState)

     * and return immediately. */

    if (file != NULL && drv->bdrv_file_open) {

        bdrv_swap(file, bs);

        return 0;

    }

    bs->open_flags = flags;

    bs->buffer_alignment = 512;

    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */

    if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {

        bdrv_enable_copy_on_read(bs);

    }

    if (file != NULL) {

        filename = file->filename;

    } else {

        filename = qdict_get_try_str(options, "filename");

    }

    if (filename != NULL) {

        pstrcpy(bs->filename, sizeof(bs->filename), filename);

    } else {

        bs->filename[0] = '\0';

    }

    bs->drv = drv;

    bs->opaque = g_malloc0(drv->instance_size);

    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);

    open_flags = bdrv_open_flags(bs, flags);

    bs->read_only = !(open_flags & BDRV_O_RDWR);

    /* Open the image, either directly or using a protocol */

    if (drv->bdrv_file_open) {

        assert(file == NULL);

        assert(drv->bdrv_parse_filename || filename != NULL);

        ret = drv->bdrv_file_open(bs, options, open_flags);

    } else {

        if (file == NULL) {

            qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "

                          "block driver for the protocol level",

                          drv->format_name);

            ret = -EINVAL;

            goto free_and_fail;

        }

        assert(file != NULL);

        bs->file = file;

        ret = drv->bdrv_open(bs, options, open_flags);

    }

    if (ret < 0) {

        goto free_and_fail;

    }

    ret = refresh_total_sectors(bs, bs->total_sectors);

    if (ret < 0) {

        goto free_and_fail;

    }

#ifndef _WIN32

    if (bs->is_temporary) {

        assert(filename != NULL);

        unlink(filename);

    }

#endif

    return 0;

free_and_fail:

    bs->file = NULL;

    g_free(bs->opaque);

    bs->opaque = NULL;

    bs->drv = NULL;

    return ret;

}


static int qcow2_open(BlockDriverState *bs, int flags)

{

    BDRVQcowState *s = bs->opaque;

    int len, i, ret = 0;

    QCowHeader header;

    uint64_t ext_end;

    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));

    if (ret < 0) {

        goto fail;

    }

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC) {

        ret = -EINVAL;

        goto fail;

    }

    if (header.version < 2 || header.version > 3) {

        report_unsupported(bs, "QCOW version %d", header.version);

        ret = -ENOTSUP;

        goto fail;

    }

    s->qcow_version = header.version;

    /* Initialise version 3 header fields */

    if (header.version == 2) {

        header.incompatible_features    = 0;

        header.compatible_features      = 0;

        header.autoclear_features       = 0;

        header.refcount_order           = 4;

        header.header_length            = 72;

    } else {

        be64_to_cpus(&header.incompatible_features);

        be64_to_cpus(&header.compatible_features);

        be64_to_cpus(&header.autoclear_features);

        be32_to_cpus(&header.refcount_order);

        be32_to_cpus(&header.header_length);

    }

    if (header.header_length > sizeof(header)) {

        s->unknown_header_fields_size = header.header_length - sizeof(header);

        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);

        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,

                         s->unknown_header_fields_size);

        if (ret < 0) {

            goto fail;

        }

    }

    if (header.backing_file_offset) {

        ext_end = header.backing_file_offset;

    } else {

        ext_end = 1 << header.cluster_bits;

    }

    /* Handle feature bits */

    s->incompatible_features    = header.incompatible_features;

    s->compatible_features      = header.compatible_features;

    s->autoclear_features       = header.autoclear_features;

    if (s->incompatible_features != 0) {

        void *feature_table = NULL;

        qcow2_read_extensions(bs, header.header_length, ext_end,

                              &feature_table);

        report_unsupported_feature(bs, feature_table,

                                   s->incompatible_features);

        ret = -ENOTSUP;

        goto fail;

    }

    /* Check support for various header values */

    if (header.refcount_order != 4) {

        report_unsupported(bs, "%d bit reference counts",

                           1 << header.refcount_order);

        ret = -ENOTSUP;

        goto fail;

    }

    if (header.cluster_bits < MIN_CLUSTER_BITS ||

        header.cluster_bits > MAX_CLUSTER_BITS) {

        ret = -EINVAL;

        goto fail;

    }

    if (header.crypt_method > QCOW_CRYPT_AES) {

        ret = -EINVAL;

        goto fail;

    }

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header) {

        bs->encrypted = 1;

    }

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    /* read the level 1 table */

    s->l1_size = header.l1_size;

    s->l1_vm_state_index = size_to_l1(s, header.size);

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index) {

        ret = -EINVAL;

        goto fail;

    }

    s->l1_table_offset = header.l1_table_offset;

    if (s->l1_size > 0) {

        s->l1_table = g_malloc0(

            align_offset(s->l1_size * sizeof(uint64_t), 512));

        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,

                         s->l1_size * sizeof(uint64_t));

        if (ret < 0) {

            goto fail;

        }

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

            be64_to_cpus(&s->l1_table[i]);

        }

    }

    /* alloc L2 table/refcount block cache */

    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);

    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);

    s->cluster_cache = g_malloc(s->cluster_size);

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size

                                  + 512);

    s->cluster_cache_offset = -1;

    s->flags = flags;

    ret = qcow2_refcount_init(bs);

    if (ret != 0) {

        goto fail;

    }

    QLIST_INIT(&s->cluster_allocs);

    /* read qcow2 extensions */

    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {

        ret = -EINVAL;

        goto fail;

    }

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > 1023) {

            len = 1023;

        }

        ret = bdrv_pread(bs->file, header.backing_file_offset,

                         bs->backing_file, len);

        if (ret < 0) {

            goto fail;

        }

        bs->backing_file[len] = '\0';

    }

    ret = qcow2_read_snapshots(bs);

    if (ret < 0) {

        goto fail;

    }

    /* Clear unknown autoclear feature bits */

    if (!bs->read_only && s->autoclear_features != 0) {

        s->autoclear_features = 0;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            goto fail;

        }

    }

    /* Initialise locks */

    qemu_co_mutex_init(&s->lock);

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result);

    }

#endif

    return ret;

 fail:

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    qcow2_free_snapshots(bs);

    qcow2_refcount_close(bs);

    g_free(s->l1_table);

    if (s->l2_table_cache) {

        qcow2_cache_destroy(bs, s->l2_table_cache);

    }

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    return ret;

}


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

{

    PAFDemuxContext *p = s->priv_data;

    AVIOContext     *pb = s->pb;

    uint32_t        count, offset;

    int             size, i;

    if (p->current_frame >= p->nb_frames)

        return AVERROR_EOF;

    if (url_feof(pb))

        return AVERROR_EOF;

    if (p->got_audio) {

        if (av_new_packet(pkt, p->audio_size) < 0)

            return AVERROR(ENOMEM);

        memcpy(pkt->data, p->temp_audio_frame, p->audio_size);

        pkt->duration     = PAF_SOUND_SAMPLES * (p->audio_size / PAF_SOUND_FRAME_SIZE);

        pkt->flags       |= AV_PKT_FLAG_KEY;

        pkt->stream_index = 1;

        p->got_audio      = 0;

        return pkt->size;

    }

    count = (p->current_frame == 0) ? p->preload_count : p->blocks_count_table[p->current_frame - 1];

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

        if (p->current_frame_block >= p->frame_blks)

            return AVERROR_INVALIDDATA;

        offset = p->blocks_offset_table[p->current_frame_block] & ~(1U << 31);

        if (p->blocks_offset_table[p->current_frame_block] & (1U << 31)) {

            if (offset > p->audio_size - p->buffer_size)

                return AVERROR_INVALIDDATA;

            avio_read(pb, p->audio_frame + offset, p->buffer_size);

            if (offset == (p->max_audio_blks - 2) * p->buffer_size) {

                memcpy(p->temp_audio_frame, p->audio_frame, p->audio_size);

                p->got_audio = 1;

            }

        } else {

            if (offset > p->video_size - p->buffer_size)

                return AVERROR_INVALIDDATA;

            avio_read(pb, p->video_frame + offset, p->buffer_size);

        }

        p->current_frame_block++;

    }

    size = p->video_size - p->frames_offset_table[p->current_frame];

    if (size < 1)

        return AVERROR_INVALIDDATA;

    if (av_new_packet(pkt, size) < 0)

        return AVERROR(ENOMEM);

    pkt->stream_index = 0;

    pkt->duration     = 1;

    memcpy(pkt->data, p->video_frame + p->frames_offset_table[p->current_frame], size);

    if (pkt->data[0] & 0x20)

        pkt->flags   |= AV_PKT_FLAG_KEY;

    p->current_frame++;

    return pkt->size;

}


char *target_strerror(int err)

{

    return strerror(target_to_host_errno(err));


AVFormatContext *ff_rtp_chain_mux_open(AVFormatContext *s, AVStream *st,

                                       URLContext *handle, int packet_size)

{

    AVFormatContext *rtpctx;

    int ret;

    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);

    if (!rtp_format)

        return NULL;

    /* Allocate an AVFormatContext for each output stream */

    rtpctx = avformat_alloc_context();

    if (!rtpctx)

        return NULL;

    rtpctx->oformat = rtp_format;

    if (!av_new_stream(rtpctx, 0)) {

        av_free(rtpctx);

        return NULL;

    }

    /* Copy the max delay setting; the rtp muxer reads this. */

    rtpctx->max_delay = s->max_delay;

    /* Copy other stream parameters. */

    rtpctx->streams[0]->sample_aspect_ratio = st->sample_aspect_ratio;

    /* Set the synchronized start time. */

    rtpctx->start_time_realtime = s->start_time_realtime;

    /* Remove the local codec, link to the original codec

     * context instead, to give the rtp muxer access to

     * codec parameters. */

    av_free(rtpctx->streams[0]->codec);

    rtpctx->streams[0]->codec = st->codec;

    if (handle) {

        url_fdopen(&rtpctx->pb, handle);

    } else

        url_open_dyn_packet_buf(&rtpctx->pb, packet_size);

    ret = av_write_header(rtpctx);

    if (ret) {

        if (handle) {

            url_fclose(rtpctx->pb);

        } else {

            uint8_t *ptr;

            url_close_dyn_buf(rtpctx->pb, &ptr);

            av_free(ptr);

        }

        av_free(rtpctx->streams[0]);

        av_free(rtpctx);

        return NULL;

    }

    /* Copy the RTP AVStream timebase back to the original AVStream */

    st->time_base = rtpctx->streams[0]->time_base;

    return rtpctx;

}


static int pci_cirrus_vga_initfn(PCIDevice *dev)

{

     PCICirrusVGAState *d = DO_UPCAST(PCICirrusVGAState, dev, dev);

     CirrusVGAState *s = &d->cirrus_vga;

     PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(dev);

     int16_t device_id = pc->device_id;

     /* setup VGA */

     vga_common_init(&s->vga, OBJECT(dev), true);

     cirrus_init_common(s, OBJECT(dev), device_id, 1, pci_address_space(dev),

                        pci_address_space_io(dev));

     s->vga.con = graphic_console_init(DEVICE(dev), 0, s->vga.hw_ops, &s->vga);

     /* setup PCI */

    memory_region_init(&s->pci_bar, OBJECT(dev), "cirrus-pci-bar0", 0x2000000);

    /* XXX: add byte swapping apertures */

    memory_region_add_subregion(&s->pci_bar, 0, &s->cirrus_linear_io);

    memory_region_add_subregion(&s->pci_bar, 0x1000000,

                                &s->cirrus_linear_bitblt_io);

     /* setup memory space */

     /* memory #0 LFB */

     /* memory #1 memory-mapped I/O */

     /* XXX: s->vga.vram_size must be a power of two */

     pci_register_bar(&d->dev, 0, PCI_BASE_ADDRESS_MEM_PREFETCH, &s->pci_bar);

     if (device_id == CIRRUS_ID_CLGD5446) {

         pci_register_bar(&d->dev, 1, 0, &s->cirrus_mmio_io);

     return 0;


static void rm_read_audio_stream_info(AVFormatContext *s, AVStream *st,
                                      int read_all)
{
    RMContext *rm = s->priv_data;
    ByteIOContext *pb = &s->pb;
    char buf[256];
    uint32_t version;
    int i;
    /* ra type header */
    version = get_be32(pb); /* version */
    if (((version >> 16) & 0xff) == 3) {
        int64_t startpos = url_ftell(pb);
        /* very old version */
        for(i = 0; i < 14; i++)
            get_byte(pb);
        get_str8(pb, s->title, sizeof(s->title));
        get_str8(pb, s->author, sizeof(s->author));
        get_str8(pb, s->copyright, sizeof(s->copyright));
        get_str8(pb, s->comment, sizeof(s->comment));
        if ((startpos + (version & 0xffff)) >= url_ftell(pb) + 2) {
        // fourcc (should always be "lpcJ")
        get_byte(pb);
        get_str8(pb, buf, sizeof(buf));
        // Skip extra header crap (this should never happen)
        if ((startpos + (version & 0xffff)) > url_ftell(pb))
            url_fskip(pb, (version & 0xffff) + startpos - url_ftell(pb));
        st->codec->sample_rate = 8000;
        st->codec->channels = 1;
        st->codec->codec_type = CODEC_TYPE_AUDIO;
        st->codec->codec_id = CODEC_ID_RA_144;
    } else {
        int flavor, sub_packet_h, coded_framesize, sub_packet_size;
        /* old version (4) */
        get_be32(pb); /* .ra4 */
        get_be32(pb); /* data size */
        get_be16(pb); /* version2 */
        get_be32(pb); /* header size */
        flavor= get_be16(pb); /* add codec info / flavor */
        rm->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
        get_be32(pb); /* ??? */
        get_be32(pb); /* ??? */
        get_be32(pb); /* ??? */
        rm->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
        st->codec->block_align= get_be16(pb); /* frame size */
        rm->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
        get_be16(pb); /* ??? */
        if (((version >> 16) & 0xff) == 5) {
            get_be16(pb); get_be16(pb); get_be16(pb); }
        st->codec->sample_rate = get_be16(pb);
        get_be32(pb);
        st->codec->channels = get_be16(pb);
        if (((version >> 16) & 0xff) == 5) {
            get_be32(pb);
            buf[0] = get_byte(pb);
            buf[1] = get_byte(pb);
            buf[2] = get_byte(pb);
            buf[3] = get_byte(pb);
            buf[4] = 0;
        } else {
        get_str8(pb, buf, sizeof(buf)); /* desc */
        get_str8(pb, buf, sizeof(buf)); /* desc */
        st->codec->codec_type = CODEC_TYPE_AUDIO;
        if (!strcmp(buf, "dnet")) {
            st->codec->codec_id = CODEC_ID_AC3;
        } else if (!strcmp(buf, "28_8")) {
            st->codec->codec_id = CODEC_ID_RA_288;
            st->codec->extradata_size= 0;
            rm->audio_framesize = st->codec->block_align;
            st->codec->block_align = coded_framesize;
            rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
        } else if (!strcmp(buf, "cook")) {
            int codecdata_length, i;
            get_be16(pb); get_byte(pb);
            if (((version >> 16) & 0xff) == 5)
                get_byte(pb);
            codecdata_length = get_be32(pb);
            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
            st->codec->codec_id = CODEC_ID_COOK;
            st->codec->extradata_size= codecdata_length;
            st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
            for(i = 0; i < codecdata_length; i++)
                ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);
            rm->audio_framesize = st->codec->block_align;
            st->codec->block_align = rm->sub_packet_size;
            rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);
        } else {
            st->codec->codec_id = CODEC_ID_NONE;
            pstrcpy(st->codec->codec_name, sizeof(st->codec->codec_name),
                    buf);
        if (read_all) {
            get_byte(pb);
            get_byte(pb);
            get_byte(pb);
            get_str8(pb, s->title, sizeof(s->title));
            get_str8(pb, s->author, sizeof(s->author));
            get_str8(pb, s->copyright, sizeof(s->copyright));
            get_str8(pb, s->comment, sizeof(s->comment));


static int vc1test_write_header(AVFormatContext *s)

{

    AVCodecContext *avc = s->streams[0]->codec;

    AVIOContext *pb = s->pb;

    if (avc->codec_id != CODEC_ID_WMV3) {

        av_log(s, AV_LOG_ERROR, "Only WMV3 is accepted!\n");

        return -1;

    }

    avio_wl24(pb, 0); //frames count will be here

    avio_w8(pb, 0xC5);

    avio_wl32(pb, 4);

    avio_write(pb, avc->extradata, 4);

    avio_wl32(pb, avc->height);

    avio_wl32(pb, avc->width);

    avio_wl32(pb, 0xC);

    avio_wl24(pb, 0); // hrd_buffer

    avio_w8(pb, 0x80); // level|cbr|res1

    avio_wl32(pb, 0); // hrd_rate

    if (s->streams[0]->r_frame_rate.den && s->streams[0]->r_frame_rate.num == 1)

        avio_wl32(pb, s->streams[0]->r_frame_rate.den);

    else

        avio_wl32(pb, 0xFFFFFFFF); //variable framerate

    avpriv_set_pts_info(s->streams[0], 32, 1, 1000);

    return 0;

}


static int caca_write_trailer(AVFormatContext *s)

{

    CACAContext *c = s->priv_data;

    av_freep(&c->window_title);

    caca_free_dither(c->dither);

    caca_free_display(c->display);

    caca_free_canvas(c->canvas);

    return 0;

}


static void dec_null(DisasContext *dc)

{

    qemu_log ("unknown insn pc=%x opc=%x\n", dc->pc, dc->opcode);

    dc->abort_at_next_insn = 1;


int av_parse_cpu_flags(const char *s)

{

#define CPUFLAG_MMXEXT   (AV_CPU_FLAG_MMX      | AV_CPU_FLAG_MMXEXT | AV_CPU_FLAG_CMOV)

#define CPUFLAG_3DNOW    (AV_CPU_FLAG_3DNOW    | AV_CPU_FLAG_MMX)

#define CPUFLAG_3DNOWEXT (AV_CPU_FLAG_3DNOWEXT | CPUFLAG_3DNOW)

#define CPUFLAG_SSE      (AV_CPU_FLAG_SSE      | CPUFLAG_MMXEXT)

#define CPUFLAG_SSE2     (AV_CPU_FLAG_SSE2     | CPUFLAG_SSE)

#define CPUFLAG_SSE2SLOW (AV_CPU_FLAG_SSE2SLOW | CPUFLAG_SSE2)

#define CPUFLAG_SSE3     (AV_CPU_FLAG_SSE3     | CPUFLAG_SSE2)

#define CPUFLAG_SSE3SLOW (AV_CPU_FLAG_SSE3SLOW | CPUFLAG_SSE3)

#define CPUFLAG_SSSE3    (AV_CPU_FLAG_SSSE3    | CPUFLAG_SSE3)

#define CPUFLAG_SSE4     (AV_CPU_FLAG_SSE4     | CPUFLAG_SSSE3)

#define CPUFLAG_SSE42    (AV_CPU_FLAG_SSE42    | CPUFLAG_SSE4)

#define CPUFLAG_AVX      (AV_CPU_FLAG_AVX      | CPUFLAG_SSE42)

#define CPUFLAG_AVXSLOW  (AV_CPU_FLAG_AVXSLOW  | CPUFLAG_AVX)

#define CPUFLAG_XOP      (AV_CPU_FLAG_XOP      | CPUFLAG_AVX)

#define CPUFLAG_FMA3     (AV_CPU_FLAG_FMA3     | CPUFLAG_AVX)

#define CPUFLAG_FMA4     (AV_CPU_FLAG_FMA4     | CPUFLAG_AVX)

#define CPUFLAG_AVX2     (AV_CPU_FLAG_AVX2     | CPUFLAG_AVX)

#define CPUFLAG_BMI2     (AV_CPU_FLAG_BMI2     | AV_CPU_FLAG_BMI1)

    static const AVOption cpuflags_opts[] = {

        { "flags"   , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },

#if   ARCH_PPC

        { "altivec" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ALTIVEC  },    .unit = "flags" },

#elif ARCH_X86

        { "mmx"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX      },    .unit = "flags" },

        { "mmxext"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_MMXEXT       },    .unit = "flags" },

        { "sse"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE          },    .unit = "flags" },

        { "sse2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE2         },    .unit = "flags" },

        { "sse2slow", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE2SLOW     },    .unit = "flags" },

        { "sse3"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE3         },    .unit = "flags" },

        { "sse3slow", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE3SLOW     },    .unit = "flags" },

        { "ssse3"   , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSSE3        },    .unit = "flags" },

        { "atom"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ATOM     },    .unit = "flags" },

        { "sse4.1"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE4         },    .unit = "flags" },

        { "sse4.2"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_SSE42        },    .unit = "flags" },

        { "avx"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_AVX          },    .unit = "flags" },

        { "avxslow" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_AVXSLOW      },    .unit = "flags" },

        { "xop"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_XOP          },    .unit = "flags" },

        { "fma3"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_FMA3         },    .unit = "flags" },

        { "fma4"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_FMA4         },    .unit = "flags" },

        { "avx2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_AVX2         },    .unit = "flags" },

        { "bmi1"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_BMI1     },    .unit = "flags" },

        { "bmi2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_BMI2         },    .unit = "flags" },

        { "3dnow"   , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_3DNOW        },    .unit = "flags" },

        { "3dnowext", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPUFLAG_3DNOWEXT     },    .unit = "flags" },

        { "cmov",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_CMOV     },    .unit = "flags" },

#elif ARCH_ARM

        { "armv5te",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV5TE  },    .unit = "flags" },

        { "armv6",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV6    },    .unit = "flags" },

        { "armv6t2",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV6T2  },    .unit = "flags" },

        { "vfp",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFP      },    .unit = "flags" },

        { "vfpv3",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFPV3    },    .unit = "flags" },

        { "neon",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_NEON     },    .unit = "flags" },

#elif ARCH_AARCH64

        { "armv8",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV8    },    .unit = "flags" },

        { "neon",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_NEON     },    .unit = "flags" },

        { "vfp",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFP      },    .unit = "flags" },

#endif

        { NULL },

    };

    static const AVClass class = {

        .class_name = "cpuflags",

        .item_name  = av_default_item_name,

        .option     = cpuflags_opts,

        .version    = LIBAVUTIL_VERSION_INT,

    };

    int flags = 0, ret;

    const AVClass *pclass = &class;

    if ((ret = av_opt_eval_flags(&pclass, &cpuflags_opts[0], s, &flags)) < 0)

        return ret;

    return flags & INT_MAX;

}


void mpeg1_init_vlc(MpegEncContext *s)

{

    static int done = 0;

    if (!done) {

        init_vlc(&dc_lum_vlc, 9, 12,

                 vlc_dc_lum_bits, 1, 1,

                 vlc_dc_lum_code, 2, 2);

        init_vlc(&dc_chroma_vlc, 9, 12,

                 vlc_dc_chroma_bits, 1, 1,

                 vlc_dc_chroma_code, 2, 2);

        init_vlc(&mv_vlc, 9, 17,

                 &mbMotionVectorTable[0][1], 2, 1,

                 &mbMotionVectorTable[0][0], 2, 1);

        init_vlc(&mbincr_vlc, 9, 35,

                 &mbAddrIncrTable[0][1], 2, 1,

                 &mbAddrIncrTable[0][0], 2, 1);

        init_vlc(&mb_pat_vlc, 9, 63,

                 &mbPatTable[0][1], 2, 1,

                 &mbPatTable[0][0], 2, 1);

        init_vlc(&mb_ptype_vlc, 6, 32,

                 &table_mb_ptype[0][1], 2, 1,

                 &table_mb_ptype[0][0], 2, 1);

        init_vlc(&mb_btype_vlc, 6, 32,

                 &table_mb_btype[0][1], 2, 1,

                 &table_mb_btype[0][0], 2, 1);

        init_rl(&rl_mpeg1);

        init_rl(&rl_mpeg2);

        /* cannot use generic init because we must add the EOB code */

        init_vlc(&rl_mpeg1.vlc, 9, rl_mpeg1.n + 2,

                 &rl_mpeg1.table_vlc[0][1], 4, 2,

                 &rl_mpeg1.table_vlc[0][0], 4, 2);

        init_vlc(&rl_mpeg2.vlc, 9, rl_mpeg2.n + 2,

                 &rl_mpeg2.table_vlc[0][1], 4, 2,

                 &rl_mpeg2.table_vlc[0][0], 4, 2);

    }

}


static int encode_bitstream(FlashSVContext *s, const AVFrame *p, uint8_t *buf,

                            int buf_size, int block_width, int block_height,

                            uint8_t *previous_frame, int *I_frame)

{

    PutBitContext pb;

    int h_blocks, v_blocks, h_part, v_part, i, j;

    int buf_pos, res;

    int pred_blocks = 0;

    init_put_bits(&pb, buf, buf_size * 8);

    put_bits(&pb,  4, block_width / 16 - 1);

    put_bits(&pb, 12, s->image_width);

    put_bits(&pb,  4, block_height / 16 - 1);

    put_bits(&pb, 12, s->image_height);

    flush_put_bits(&pb);

    buf_pos = 4;

    h_blocks = s->image_width  / block_width;

    h_part   = s->image_width  % block_width;

    v_blocks = s->image_height / block_height;

    v_part   = s->image_height % block_height;

    /* loop over all block columns */

    for (j = 0; j < v_blocks + (v_part ? 1 : 0); j++) {

        int y_pos = j * block_height; // vertical position in frame

        int cur_blk_height = (j < v_blocks) ? block_height : v_part;

        /* loop over all block rows */

        for (i = 0; i < h_blocks + (h_part ? 1 : 0); i++) {

            int x_pos = i * block_width; // horizontal position in frame

            int cur_blk_width = (i < h_blocks) ? block_width : h_part;

            int ret = Z_OK;

            uint8_t *ptr = buf + buf_pos;

            /* copy the block to the temp buffer before compression

             * (if it differs from the previous frame's block) */

            res = copy_region_enc(p->data[0], s->tmpblock,

                                  s->image_height - (y_pos + cur_blk_height + 1),

                                  x_pos, cur_blk_height, cur_blk_width,

                                  p->linesize[0], previous_frame);

            if (res || *I_frame) {

                unsigned long zsize = 3 * block_width * block_height;

                ret = compress2(ptr + 2, &zsize, s->tmpblock,

                                3 * cur_blk_width * cur_blk_height, 9);

                //ret = deflateReset(&s->zstream);

                if (ret != Z_OK)

                    av_log(s->avctx, AV_LOG_ERROR,

                           "error while compressing block %dx%d\n", i, j);

                bytestream_put_be16(&ptr, zsize);

                buf_pos += zsize + 2;

                av_dlog(s->avctx, "buf_pos = %d\n", buf_pos);

            } else {

                pred_blocks++;

                bytestream_put_be16(&ptr, 0);

                buf_pos += 2;

            }

        }

    }

    if (pred_blocks)

        *I_frame = 0;

    else

        *I_frame = 1;

    return buf_pos;

}


static void usb_uas_task(UASDevice *uas, uas_ui *ui)

{

    uint16_t tag = be16_to_cpu(ui->hdr.tag);

    uint64_t lun64 = be64_to_cpu(ui->task.lun);

    SCSIDevice *dev = usb_uas_get_dev(uas, lun64);

    int lun = usb_uas_get_lun(lun64);

    UASRequest *req;

    uint16_t task_tag;

    req = usb_uas_find_request(uas, be16_to_cpu(ui->hdr.tag));

    if (req) {

        goto overlapped_tag;

    if (dev == NULL) {

        goto incorrect_lun;

    switch (ui->task.function) {

    case UAS_TMF_ABORT_TASK:

        task_tag = be16_to_cpu(ui->task.task_tag);

        trace_usb_uas_tmf_abort_task(uas->dev.addr, tag, task_tag);

        req = usb_uas_find_request(uas, task_tag);

        if (req && req->dev == dev) {

            scsi_req_cancel(req->req);

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);

        break;

    case UAS_TMF_LOGICAL_UNIT_RESET:

        trace_usb_uas_tmf_logical_unit_reset(uas->dev.addr, tag, lun);

        qdev_reset_all(&dev->qdev);

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_COMPLETE, 0);

        break;

    default:

        trace_usb_uas_tmf_unsupported(uas->dev.addr, tag, ui->task.function);

        usb_uas_queue_response(uas, tag, UAS_RC_TMF_NOT_SUPPORTED, 0);

        break;

    return;

invalid_tag:

    usb_uas_queue_response(uas, tag, UAS_RC_INVALID_INFO_UNIT, 0);

    return;

overlapped_tag:

    usb_uas_queue_response(uas, req->tag, UAS_RC_OVERLAPPED_TAG, 0);

    return;

incorrect_lun:

    usb_uas_queue_response(uas, tag, UAS_RC_INCORRECT_LUN, 0);


static int sch_handle_start_func_passthrough(SubchDev *sch)

{

    PMCW *p = &sch->curr_status.pmcw;

    SCSW *s = &sch->curr_status.scsw;

    int ret;

    ORB *orb = &sch->orb;

    if (!(s->ctrl & SCSW_ACTL_SUSP)) {

        assert(orb != NULL);

        p->intparm = orb->intparm;

    }

    /*

     * Only support prefetch enable mode.

     * Only support 64bit addressing idal.

     */

    if (!(orb->ctrl0 & ORB_CTRL0_MASK_PFCH) ||

        !(orb->ctrl0 & ORB_CTRL0_MASK_C64)) {

        return -EINVAL;

    }

    ret = s390_ccw_cmd_request(orb, s, sch->driver_data);

    switch (ret) {

    /* Currently we don't update control block and just return the cc code. */

    case 0:

        break;

    case -EBUSY:

        break;

    case -ENODEV:

        break;

    case -EACCES:

        /* Let's reflect an inaccessible host device by cc 3. */

        ret = -ENODEV;

        break;

    default:

       /*

        * All other return codes will trigger a program check,

        * or set cc to 1.

        */

       break;

    };

    return ret;

}


static int cmd_valid_while_locked(SDState *sd, SDRequest *req)

{

    /* Valid commands in locked state:

     * basic class (0)

     * lock card class (7)

     * CMD16

     * implicitly, the ACMD prefix CMD55

     * ACMD41 and ACMD42

     * Anything else provokes an "illegal command" response.

     */

    if (sd->card_status & APP_CMD) {

        return req->cmd == 41 || req->cmd == 42;

    }

    if (req->cmd == 16 || req->cmd == 55) {

        return 1;

    }

    return sd_cmd_class[req->cmd] == 0 || sd_cmd_class[req->cmd] == 7;

}


static int smc_decode_init(AVCodecContext *avctx)

{

    SmcContext *s = avctx->priv_data;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    dsputil_init(&s->dsp, avctx);

    s->frame.data[0] = NULL;

    return 0;

}


int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,

                             int track_index, int sample)

{

    MOVMuxContext *mov = s->priv_data;

    MOVTrack *trk = &mov->tracks[track_index];

    AVFormatContext *rtp_ctx = trk->rtp_ctx;

    uint8_t *buf = NULL;

    int size;

    AVIOContext *hintbuf = NULL;

    AVPacket hint_pkt;

    int ret = 0, count;

    if (!rtp_ctx)

        return AVERROR(ENOENT);

    if (!rtp_ctx->pb)

        return AVERROR(ENOMEM);

    sample_queue_push(&trk->sample_queue, pkt, sample);

    /* Feed the packet to the RTP muxer */

    ff_write_chained(rtp_ctx, 0, pkt, s);

    /* Fetch the output from the RTP muxer, open a new output buffer

     * for next time. */

    size = avio_close_dyn_buf(rtp_ctx->pb, &buf);

    if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,

                                       RTP_MAX_PACKET_SIZE)) < 0)

        goto done;

    if (size <= 0)

        goto done;

    /* Open a buffer for writing the hint */

    if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)

        goto done;

    av_init_packet(&hint_pkt);

    count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);

    av_freep(&buf);

    /* Write the hint data into the hint track */

    hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);

    hint_pkt.data = buf;

    hint_pkt.pts  = hint_pkt.dts;

    hint_pkt.stream_index = track_index;

    if (pkt->flags & AV_PKT_FLAG_KEY)

        hint_pkt.flags |= AV_PKT_FLAG_KEY;

    if (count > 0)

        ff_mov_write_packet(s, &hint_pkt);

done:

    av_free(buf);

    sample_queue_retain(&trk->sample_queue);

    return ret;

}