void ff_aac_search_for_pred(AACEncContext *s, SingleChannelElement *sce)

{

    int sfb, i, count = 0, cost_coeffs = 0, cost_pred = 0;

    const int pmax = FFMIN(sce->ics.max_sfb, ff_aac_pred_sfb_max[s->samplerate_index]);

    float *O34  = &s->scoefs[128*0], *P34 = &s->scoefs[128*1];

    float *SENT = &s->scoefs[128*2], *S34 = &s->scoefs[128*3];

    float *QERR = &s->scoefs[128*4];

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        sce->ics.predictor_present = 0;

        return;

    }

    if (!sce->ics.predictor_initialized) {

        reset_all_predictors(sce->predictor_state);

        sce->ics.predictor_initialized = 1;

        memcpy(sce->prcoeffs, sce->coeffs, 1024*sizeof(float));

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

            sce->ics.predictor_reset_count[i] = i;

    }

    update_pred_resets(sce);

    memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));

    for (sfb = PRED_SFB_START; sfb < pmax; sfb++) {

        int cost1, cost2, cb_p;

        float dist1, dist2, dist_spec_err = 0.0f;

        const int cb_n = sce->band_type[sfb];

        const int start_coef = sce->ics.swb_offset[sfb];

        const int num_coeffs = sce->ics.swb_offset[sfb + 1] - start_coef;

        const FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[sfb];

        if (start_coef + num_coeffs > MAX_PREDICTORS ||

            (s->cur_channel && sce->band_type[sfb] >= INTENSITY_BT2) ||

            sce->band_type[sfb] == NOISE_BT)

            continue;

        /* Normal coefficients */

        abs_pow34_v(O34, &sce->coeffs[start_coef], num_coeffs);

        dist1 = quantize_and_encode_band_cost(s, NULL, &sce->coeffs[start_coef], NULL,

                                              O34, num_coeffs, sce->sf_idx[sfb],

                                              cb_n, s->lambda / band->threshold, INFINITY, &cost1, 0);

        cost_coeffs += cost1;

        /* Encoded coefficients - needed for #bits, band type and quant. error */

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

            SENT[i] = sce->coeffs[start_coef + i] - sce->prcoeffs[start_coef + i];

        abs_pow34_v(S34, SENT, num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, S34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        quantize_and_encode_band_cost(s, NULL, SENT, QERR, S34, num_coeffs,

                                      sce->sf_idx[sfb], cb_p, s->lambda / band->threshold, INFINITY,

                                      &cost2, 0);

        /* Reconstructed coefficients - needed for distortion measurements */

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

            sce->prcoeffs[start_coef + i] += QERR[i] != 0.0f ? (sce->prcoeffs[start_coef + i] - QERR[i]) : 0.0f;

        abs_pow34_v(P34, &sce->prcoeffs[start_coef], num_coeffs);

        if (cb_n < RESERVED_BT)

            cb_p = find_min_book(find_max_val(1, num_coeffs, P34), sce->sf_idx[sfb]);

        else

            cb_p = cb_n;

        dist2 = quantize_and_encode_band_cost(s, NULL, &sce->prcoeffs[start_coef], NULL,

                                              P34, num_coeffs, sce->sf_idx[sfb],

                                              cb_p, s->lambda / band->threshold, INFINITY, NULL, 0);

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

            dist_spec_err += (O34[i] - P34[i])*(O34[i] - P34[i]);

        dist_spec_err *= s->lambda / band->threshold;

        dist2 += dist_spec_err;

        if (dist2 <= dist1 && cb_p <= cb_n) {

            cost_pred += cost2;

            sce->ics.prediction_used[sfb] = 1;

            sce->band_alt[sfb]  = cb_n;

            sce->band_type[sfb] = cb_p;

            count++;

        } else {

            cost_pred += cost1;

            sce->band_alt[sfb] = cb_p;

        }

    }

    if (count && cost_coeffs < cost_pred) {

        count = 0;

        for (sfb = PRED_SFB_START; sfb < pmax; sfb++)

            RESTORE_PRED(sce, sfb);

        memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));

    }

    sce->ics.predictor_present = !!count;

}


static void new_subtitle_stream(AVFormatContext *oc, int file_idx)

{

    AVStream *st;

    OutputStream *ost;

    AVCodec *codec=NULL;

    AVCodecContext *subtitle_enc;

    enum CodecID codec_id = CODEC_ID_NONE;

    if(!subtitle_stream_copy){

        if (subtitle_codec_name) {

            codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,

                                         avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);

            codec = avcodec_find_encoder_by_name(subtitle_codec_name);

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);

            codec = avcodec_find_encoder(codec_id);

        }

    }

    ost = new_output_stream(oc, file_idx, codec);

    st  = ost->st;

    subtitle_enc = st->codec;

    ost->bitstream_filters = subtitle_bitstream_filters;

    subtitle_bitstream_filters= NULL;

    subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;

    if(subtitle_codec_tag)

        subtitle_enc->codec_tag= subtitle_codec_tag;

    if (oc->oformat->flags & AVFMT_GLOBALHEADER) {

        subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

    }

    if (subtitle_stream_copy) {

        st->stream_copy = 1;

    } else {

        subtitle_enc->codec_id = codec_id;

        set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);

    }

    if (subtitle_language) {

        av_dict_set(&st->metadata, "language", subtitle_language, 0);

        av_freep(&subtitle_language);

    }

    subtitle_disable = 0;

    av_freep(&subtitle_codec_name);

    subtitle_stream_copy = 0;

}


static int compile_kernel_file(GPUEnv *gpu_env, const char *build_options)

{

    cl_int status;

    char *temp, *source_str = NULL;

    size_t source_str_len = 0;

    int i, ret = 0;

    for (i = 0; i < gpu_env->kernel_code_count; i++) {

        if (!gpu_env->kernel_code[i].is_compiled)

            source_str_len += strlen(gpu_env->kernel_code[i].kernel_string);

    }

    if (!source_str_len) {

        return 0;

    }

    source_str = av_mallocz(source_str_len + 1);

    if (!source_str) {

        return AVERROR(ENOMEM);

    }

    temp = source_str;

    for (i = 0; i < gpu_env->kernel_code_count; i++) {

        if (!gpu_env->kernel_code[i].is_compiled) {

            memcpy(temp, gpu_env->kernel_code[i].kernel_string,

                        strlen(gpu_env->kernel_code[i].kernel_string));

            gpu_env->kernel_code[i].is_compiled = 1;

            temp += strlen(gpu_env->kernel_code[i].kernel_string);

        }

    }

    /* create a CL program using the kernel source */

    gpu_env->programs[gpu_env->program_count] = clCreateProgramWithSource(gpu_env->context,

                                                           1, (const char **)(&source_str),

                                                                   &source_str_len, &status);

    if(status != CL_SUCCESS) {

        av_log(&openclutils, AV_LOG_ERROR, "Could not create OpenCL program with source code: %s\n",

               opencl_errstr(status));

        ret = AVERROR_EXTERNAL;

        goto end;

    }

    if (!gpu_env->programs[gpu_env->program_count]) {

        av_log(&openclutils, AV_LOG_ERROR, "Created program is NULL\n");

        ret = AVERROR_EXTERNAL;

        goto end;

    }

    i = 0;

    if (gpu_env->usr_spec_dev_info.dev_idx >= 0)

        i = gpu_env->usr_spec_dev_info.dev_idx;

    /* create a cl program executable for all the devices specified */

    if (!gpu_env->is_user_created)

        status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &gpu_env->device_ids[i],

                                build_options, NULL, NULL);

    else

        status = clBuildProgram(gpu_env->programs[gpu_env->program_count], 1, &(gpu_env->device_id),

                                 build_options, NULL, NULL);

    if (status != CL_SUCCESS) {

        av_log(&openclutils, AV_LOG_ERROR, "Could not compile OpenCL kernel: %s\n", opencl_errstr(status));

        ret = AVERROR_EXTERNAL;

        goto end;

    }

    gpu_env->program_count++;

end:

    av_free(source_str);

    return ret;

}


static void read_ttag(AVFormatContext *s, int taglen, const char *key)

{

    char *q, dst[512];

    int len, dstlen = sizeof(dst) - 1;

    unsigned genre;

    dst[0] = 0;

    if (taglen < 1)

        return;

    taglen--; /* account for encoding type byte */

    switch (get_byte(s->pb)) { /* encoding type */

    case 0:  /* ISO-8859-1 (0 - 255 maps directly into unicode) */

        q = dst;

        while (taglen--) {

            uint8_t tmp;

            PUT_UTF8(get_byte(s->pb), tmp, if (q - dst < dstlen - 1) *q++ = tmp;)

        }

        *q = '\0';

        break;

    case 3:  /* UTF-8 */

        len = FFMIN(taglen, dstlen - 1);

        get_buffer(s->pb, dst, len);

        dst[len] = 0;

        break;

    }

    if (!strcmp(key, "genre")

        && (sscanf(dst, "(%d)", &genre) == 1 || sscanf(dst, "%d", &genre) == 1)

        && genre <= ID3v1_GENRE_MAX)

        av_strlcpy(dst, ff_id3v1_genre_str[genre], sizeof(dst));

    if (*dst)

        av_metadata_set(&s->metadata, key, dst);

}


static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)

{

    Jpeg2000CodingStyle *codsty = s->codsty;

    Jpeg2000QuantStyle *qntsty  = s->qntsty;

    uint8_t *properties         = s->properties;

    for (;;) {

        int len, ret = 0;

        uint16_t marker;

        int oldpos;

        if (bytestream2_get_bytes_left(&s->g) < 2) {

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

            break;

        }

        marker = bytestream2_get_be16u(&s->g);

        oldpos = bytestream2_tell(&s->g);

        if (marker == JPEG2000_SOD) {

            Jpeg2000Tile *tile = s->tile + s->curtileno;

            Jpeg2000TilePart *tp = tile->tile_part + tile->tp_idx;

            bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);

            bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);

            continue;

        }

        if (marker == JPEG2000_EOC)

            break;

        if (bytestream2_get_bytes_left(&s->g) < 2)

            return AVERROR(EINVAL);

        len = bytestream2_get_be16u(&s->g);

        switch (marker) {

        case JPEG2000_SIZ:

            ret = get_siz(s);

            if (!s->tile)

                s->numXtiles = s->numYtiles = 0;

            break;

        case JPEG2000_COC:

            ret = get_coc(s, codsty, properties);

            break;

        case JPEG2000_COD:

            ret = get_cod(s, codsty, properties);

            break;

        case JPEG2000_QCC:

            ret = get_qcc(s, len, qntsty, properties);

            break;

        case JPEG2000_QCD:

            ret = get_qcd(s, len, qntsty, properties);

            break;

        case JPEG2000_SOT:

            if (!(ret = get_sot(s, len))) {

                av_assert1(s->curtileno >= 0);

                codsty = s->tile[s->curtileno].codsty;

                qntsty = s->tile[s->curtileno].qntsty;

                properties = s->tile[s->curtileno].properties;

            }

            break;

        case JPEG2000_COM:

            // the comment is ignored

            bytestream2_skip(&s->g, len - 2);

            break;

        case JPEG2000_TLM:

            // Tile-part lengths

            ret = get_tlm(s, len);

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR,

                   "unsupported marker 0x%.4X at pos 0x%X\n",

                   marker, bytestream2_tell(&s->g) - 4);

            bytestream2_skip(&s->g, len - 2);

            break;

        }

        if (bytestream2_tell(&s->g) - oldpos != len || ret) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "error during processing marker segment %.4x\n", marker);

            return ret ? ret : -1;

        }

    }

    return 0;

}


static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)

{

    int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;

    int num_blocks = s->coded_fragment_list_index;

    for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {

        i = blocks_decoded = num_blocks_at_qpi = 0;

        bit = get_bits1(gb);

        do {

            run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;

            if (run_length == 34)

                run_length += get_bits(gb, 12);

            blocks_decoded += run_length;

            if (!bit)

                num_blocks_at_qpi += run_length;

            for (j = 0; j < run_length; i++) {

                if (i > s->coded_fragment_list_index)

                    return -1;

                if (s->all_fragments[s->coded_fragment_list[i]].qpi == qpi) {

                    s->all_fragments[s->coded_fragment_list[i]].qpi += bit;

                    j++;

                }

            }

            if (run_length == 4129)

                bit = get_bits1(gb);

            else

                bit ^= 1;

        } while (blocks_decoded < num_blocks);

        num_blocks -= num_blocks_at_qpi;

    }

    return 0;

}


static void v9fs_mkdir(void *opaque)
{
    V9fsPDU *pdu = opaque;
    size_t offset = 7;
    int32_t fid;
    struct stat stbuf;
    V9fsQID qid;
    V9fsString name;
    V9fsFidState *fidp;
    gid_t gid;
    int mode;
    int err = 0;
    v9fs_string_init(&name);
    err = pdu_unmarshal(pdu, offset, "dsdd", &fid, &name, &mode, &gid);
    if (err < 0) {
    trace_v9fs_mkdir(pdu->tag, pdu->id, fid, name.data, mode, gid);
    fidp = get_fid(pdu, fid);
    if (fidp == NULL) {
    err = v9fs_co_mkdir(pdu, fidp, &name, mode, fidp->uid, gid, &stbuf);
    if (err < 0) {
        goto out;
    stat_to_qid(&stbuf, &qid);
    err = pdu_marshal(pdu, offset, "Q", &qid);
    if (err < 0) {
        goto out;
    err += offset;
    trace_v9fs_mkdir_return(pdu->tag, pdu->id,
                            qid.type, qid.version, qid.path, err);
out:
    put_fid(pdu, fidp);
out_nofid:
    pdu_complete(pdu, err);
    v9fs_string_free(&name);


static void kvmppc_host_cpu_class_init(ObjectClass *oc, void *data)

{

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    uint32_t vmx = kvmppc_get_vmx();

    uint32_t dfp = kvmppc_get_dfp();

    /* Now fix up the class with information we can query from the host */

    if (vmx != -1) {

        /* Only override when we know what the host supports */

        alter_insns(&pcc->insns_flags, PPC_ALTIVEC, vmx > 0);

        alter_insns(&pcc->insns_flags2, PPC2_VSX, vmx > 1);

    }

    if (dfp != -1) {

        /* Only override when we know what the host supports */

        alter_insns(&pcc->insns_flags2, PPC2_DFP, dfp);

    }

    if (dcache_size != -1) {

        pcc->l1_dcache_size = dcache_size;

    }

    if (icache_size != -1) {

        pcc->l1_icache_size = icache_size;

    }

}


static BlockDriverAIOCB *raw_aio_writev(BlockDriverState *bs,

    int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

    BlockDriverCompletionFunc *cb, void *opaque)

{

    const uint8_t *first_buf;

    int first_buf_index = 0, i;

    /* This is probably being paranoid, but handle cases of zero size

       vectors. */

    for (i = 0; i < qiov->niov; i++) {

        if (qiov->iov[i].iov_len) {

            assert(qiov->iov[i].iov_len >= 512);

            first_buf_index = i;

            break;

        }

    }

    first_buf = qiov->iov[first_buf_index].iov_base;

    if (check_write_unsafe(bs, sector_num, first_buf, nb_sectors)) {

        RawScrubberBounce *b;

        int ret;

        /* write the first sector using sync I/O */

        ret = raw_write_scrubbed_bootsect(bs, first_buf);

        if (ret < 0) {

            return NULL;

        }

        /* adjust request to be everything but first sector */

        b = qemu_malloc(sizeof(*b));

        b->cb = cb;

        b->opaque = opaque;

        qemu_iovec_init(&b->qiov, qiov->nalloc);

        qemu_iovec_concat(&b->qiov, qiov, qiov->size);

        b->qiov.size -= 512;

        b->qiov.iov[first_buf_index].iov_base += 512;

        b->qiov.iov[first_buf_index].iov_len -= 512;

        return bdrv_aio_writev(bs->file, sector_num + 1, &b->qiov,

                               nb_sectors - 1, raw_aio_writev_scrubbed, b);

    }

    return bdrv_aio_writev(bs->file, sector_num, qiov, nb_sectors, cb, opaque);

}


void ppc_slb_invalidate_all (CPUPPCState *env)

{

    target_phys_addr_t sr_base;

    uint64_t tmp64;

    int n, do_invalidate;

    do_invalidate = 0;

    sr_base = env->spr[SPR_ASR];

    for (n = 0; n < env->slb_nr; n++) {

        tmp64 = ldq_phys(sr_base);

        if (slb_is_valid(tmp64)) {

            slb_invalidate(&tmp64);

            stq_phys(sr_base, tmp64);

            /* XXX: given the fact that segment size is 256 MB or 1TB,

             *      and we still don't have a tlb_flush_mask(env, n, mask)

             *      in Qemu, we just invalidate all TLBs

             */

            do_invalidate = 1;

        }

        sr_base += 12;

    }

    if (do_invalidate)

        tlb_flush(env, 1);

}


static int dirac_header(AVFormatContext *s, int idx)

{

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

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

    dirac_source_params source;

    GetBitContext gb;

    // already parsed the header

    if (st->codec->codec_id == AV_CODEC_ID_DIRAC)

        return 0;

    init_get_bits(&gb, os->buf + os->pstart + 13, (os->psize - 13) * 8);

    if (avpriv_dirac_parse_sequence_header(st->codec, &gb, &source) < 0)

        return -1;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = AV_CODEC_ID_DIRAC;

    // dirac in ogg always stores timestamps as though the video were interlaced

    avpriv_set_pts_info(st, 64, st->codec->framerate.den, 2*st->codec->framerate.num);

    return 1;

}


static int targa_encode_frame(AVCodecContext *avctx,

                              unsigned char *outbuf,

                              int buf_size, void *data){

    AVFrame *p = data;

    int bpp, picsize, datasize;

    uint8_t *out;

    if(avctx->width > 0xffff || avctx->height > 0xffff) {

        av_log(avctx, AV_LOG_ERROR, "image dimensions too large\n");

        return -1;

    }

    picsize = avpicture_get_size(avctx->pix_fmt, avctx->width, avctx->height);

    if(buf_size < picsize + 45) {

        av_log(avctx, AV_LOG_ERROR, "encoded frame too large\n");

        return -1;

    }

    p->pict_type= FF_I_TYPE;

    p->key_frame= 1;

    /* zero out the header and only set applicable fields */

    memset(outbuf, 0, 11);

    AV_WL16(outbuf+12, avctx->width);

    AV_WL16(outbuf+14, avctx->height);

    outbuf[17] = 0x20;           /* origin is top-left. no alpha */

    /* TODO: support alpha channel */

    switch(avctx->pix_fmt) {

    case PIX_FMT_GRAY8:

        outbuf[2] = 3;           /* uncompressed grayscale image */

        outbuf[16] = 8;          /* bpp */

        break;

    case PIX_FMT_RGB555:

        outbuf[2] = 2;           /* uncompresses true-color image */

        outbuf[16] = 16;         /* bpp */

        break;

    case PIX_FMT_BGR24:

        outbuf[2] = 2;           /* uncompressed true-color image */

        outbuf[16] = 24;         /* bpp */

        break;

    default:

        return -1;

    }

    bpp = outbuf[16] >> 3;

    out = outbuf + 18;  /* skip past the header we just output */

    /* try RLE compression */

    datasize = targa_encode_rle(out, picsize, p, bpp, avctx->width, avctx->height);

    /* if that worked well, mark the picture as RLE compressed */

    if(datasize >= 0)

        outbuf[2] |= 8;

    /* if RLE didn't make it smaller, go back to no compression */

    else datasize = targa_encode_normal(out, p, bpp, avctx->width, avctx->height);

    out += datasize;

    /* The standard recommends including this section, even if we don't use

     * any of the features it affords. TODO: take advantage of the pixel

     * aspect ratio and encoder ID fields available? */

    memcpy(out, "\0\0\0\0\0\0\0\0TRUEVISION-XFILE.", 26);

    return out + 26 - outbuf;

}


static void sdp_parse_fmtp(AVStream *st, const char *p)

{

    char attr[256];

    /* Vorbis setup headers can be up to 12KB and are sent base64

     * encoded, giving a 12KB * (4/3) = 16KB FMTP line. */

    char value[16384];

    int i;

    RTSPStream *rtsp_st = st->priv_data;

    AVCodecContext *codec = st->codec;

    RTPPayloadData *rtp_payload_data = &rtsp_st->rtp_payload_data;

    /* loop on each attribute */

    while(rtsp_next_attr_and_value(&p, attr, sizeof(attr), value, sizeof(value)))

    {

        /* grab the codec extra_data from the config parameter of the fmtp line */

        sdp_parse_fmtp_config(codec, rtsp_st->dynamic_protocol_context,

                              attr, value);

        /* Looking for a known attribute */

        for (i = 0; attr_names[i].str; ++i) {

            if (!strcasecmp(attr, attr_names[i].str)) {

                if (attr_names[i].type == ATTR_NAME_TYPE_INT)

                    *(int *)((char *)rtp_payload_data + attr_names[i].offset) = atoi(value);

                else if (attr_names[i].type == ATTR_NAME_TYPE_STR)

                    *(char **)((char *)rtp_payload_data + attr_names[i].offset) = av_strdup(value);

            }

        }

    }

}


static int h261_decode_gob(H261Context *h){

    MpegEncContext * const s = &h->s;

    int v;

    ff_set_qscale(s, s->qscale);

    /* check for empty gob */

    v= show_bits(&s->gb, 15);

    if(get_bits_count(&s->gb) + 15 > s->gb.size_in_bits){

        v>>= get_bits_count(&s->gb) + 15 - s->gb.size_in_bits;

    }

    if(v==0){

        h261_decode_mb_skipped(h, 0, 33);

        return 0;

    }

    /* decode mb's */

    while(h->current_mba <= MAX_MBA)

    {

        int ret;

        /* DCT & quantize */

        ret= h261_decode_mb(h, s->block);

        if(ret<0){

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

            if(ret==SLICE_END){

                MPV_decode_mb(s, s->block);

                if(h->loop_filter){

                    ff_h261_loop_filter(h);

                }

                h->loop_filter = 0;

                h261_decode_mb_skipped(h, h->current_mba-h->mba_diff, h->current_mba-1);

                h261_decode_mb_skipped(h, h->current_mba, 33);

                return 0;

            }else if(ret==SLICE_NOEND){

                av_log(s->avctx, AV_LOG_ERROR, "Slice mismatch at MB: %d\n", xy);

                return -1;

            }

            av_log(s->avctx, AV_LOG_ERROR, "Error at MB: %d\n", xy);

            return -1;

        }

        MPV_decode_mb(s, s->block);

        if(h->loop_filter){

            ff_h261_loop_filter(h);

        }

        h->loop_filter = 0;

        h261_decode_mb_skipped(h, h->current_mba-h->mba_diff, h->current_mba-1);

    }

    return -1;

}


static int parse_playlist(URLContext *h, const char *url)

{

    HLSContext *s = h->priv_data;

    AVIOContext *in;

    int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;

    int64_t duration = 0;

    char line[1024];

    const char *ptr;

    if ((ret = avio_open2(&in, url, AVIO_FLAG_READ,

                          &h->interrupt_callback, NULL)) < 0)

        return ret;

    read_chomp_line(in, line, sizeof(line));

    if (strcmp(line, "#EXTM3U"))

        return AVERROR_INVALIDDATA;

    free_segment_list(s);

    s->finished = 0;

    while (!in->eof_reached) {

        read_chomp_line(in, line, sizeof(line));

        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {

            struct variant_info info = {{0}};

            is_variant = 1;

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,

                               &info);

            bandwidth = atoi(info.bandwidth);

        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {

            s->target_duration = atoi(ptr) * AV_TIME_BASE;

        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {

            s->start_seq_no = atoi(ptr);

        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {

            s->finished = 1;

        } else if (av_strstart(line, "#EXTINF:", &ptr)) {

            is_segment = 1;

            duration = atof(ptr) * AV_TIME_BASE;

        } else if (av_strstart(line, "#", NULL)) {

            continue;

        } else if (line[0]) {

            if (is_segment) {

                struct segment *seg = av_malloc(sizeof(struct segment));

                if (!seg) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                seg->duration = duration;

                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);

                dynarray_add(&s->segments, &s->n_segments, seg);

                is_segment = 0;

            } else if (is_variant) {

                struct variant *var = av_malloc(sizeof(struct variant));

                if (!var) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                var->bandwidth = bandwidth;

                ff_make_absolute_url(var->url, sizeof(var->url), url, line);

                dynarray_add(&s->variants, &s->n_variants, var);

                is_variant = 0;

            }

        }

    }

    s->last_load_time = av_gettime_relative();

fail:

    avio_close(in);

    return ret;

}


static int dc1394_read_header(AVFormatContext *c, AVFormatParameters * ap)

{

    dc1394_data* dc1394 = c->priv_data;

    AVStream* vst;

    nodeid_t* camera_nodes;

    int res;

    struct dc1394_frame_format *fmt;

    struct dc1394_frame_rate *fps;

    for (fmt = dc1394_frame_formats; fmt->width; fmt++)

         if (fmt->pix_fmt == ap->pix_fmt && fmt->width == ap->width && fmt->height == ap->height)

             break;

    for (fps = dc1394_frame_rates; fps->frame_rate; fps++)

         if (fps->frame_rate == av_rescale(1000, ap->time_base.den, ap->time_base.num))

             break;

    /* create a video stream */

    vst = av_new_stream(c, 0);

    if (!vst)

        return -1;

    av_set_pts_info(vst, 64, 1, 1000);

    vst->codec->codec_type = CODEC_TYPE_VIDEO;

    vst->codec->codec_id = CODEC_ID_RAWVIDEO;

    vst->codec->time_base.den = fps->frame_rate;

    vst->codec->time_base.num = 1000;

    vst->codec->width = fmt->width;

    vst->codec->height = fmt->height;

    vst->codec->pix_fmt = fmt->pix_fmt;

    /* packet init */

    av_init_packet(&dc1394->packet);

    dc1394->packet.size = avpicture_get_size(fmt->pix_fmt, fmt->width, fmt->height);

    dc1394->packet.stream_index = vst->index;

    dc1394->packet.flags |= PKT_FLAG_KEY;

    dc1394->current_frame = 0;

    dc1394->fps = fps->frame_rate;

    vst->codec->bit_rate = av_rescale(dc1394->packet.size * 8, fps->frame_rate, 1000);

    /* Now lets prep the hardware */

    dc1394->handle = dc1394_create_handle(0); /* FIXME: gotta have ap->port */

    if (!dc1394->handle) {

        av_log(c, AV_LOG_ERROR, "Can't acquire dc1394 handle on port %d\n", 0 /* ap->port */);

        goto out;

    }

    camera_nodes = dc1394_get_camera_nodes(dc1394->handle, &res, 1);

    if (!camera_nodes || camera_nodes[ap->channel] == DC1394_NO_CAMERA) {

        av_log(c, AV_LOG_ERROR, "There's no IIDC camera on the channel %d\n", ap->channel);

        goto out_handle;

    }

    res = dc1394_dma_setup_capture(dc1394->handle, camera_nodes[ap->channel],

                                   0,

                                   FORMAT_VGA_NONCOMPRESSED,

                                   fmt->frame_size_id,

                                   SPEED_400,

                                   fps->frame_rate_id, 8, 1,

                                   c->filename,

                                   &dc1394->camera);

    dc1394_free_camera_nodes(camera_nodes);

    if (res != DC1394_SUCCESS) {

        av_log(c, AV_LOG_ERROR, "Can't prepare camera for the DMA capture\n");

        goto out_handle;

    }

    res = dc1394_start_iso_transmission(dc1394->handle, dc1394->camera.node);

    if (res != DC1394_SUCCESS) {

        av_log(c, AV_LOG_ERROR, "Can't start isochronous transmission\n");

        goto out_handle_dma;

    }

    return 0;

out_handle_dma:

    dc1394_dma_unlisten(dc1394->handle, &dc1394->camera);

    dc1394_dma_release_camera(dc1394->handle, &dc1394->camera);

out_handle:

    dc1394_destroy_handle(dc1394->handle);

out:

    return -1;

}


static void bdrv_aio_bh_cb(void *opaque)

{

    BlockDriverAIOCBSync *acb = opaque;

    if (!acb->is_write)

        qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);

    qemu_vfree(acb->bounce);

    acb->common.cb(acb->common.opaque, acb->ret);

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    qemu_aio_release(acb);

}


static int send_sub_rect_jpeg(VncState *vs, int x, int y, int w, int h,

                              int bg, int fg, int colors,

                              VncPalette *palette)

{

    int ret;

    if (colors == 0) {

        if (tight_detect_smooth_image(vs, w, h)) {

            int quality = tight_conf[vs->tight.quality].jpeg_quality;

            ret = send_jpeg_rect(vs, x, y, w, h, quality);

            ret = send_full_color_rect(vs, x, y, w, h);

        }

    } else if (colors == 1) {

        ret = send_solid_rect(vs);

    } else if (colors == 2) {

        ret = send_mono_rect(vs, x, y, w, h, bg, fg);

    } else if (colors <= 256) {

        if (colors > 96 &&

            tight_detect_smooth_image(vs, w, h)) {

            int quality = tight_conf[vs->tight.quality].jpeg_quality;

            ret = send_jpeg_rect(vs, x, y, w, h, quality);

            ret = send_palette_rect(vs, x, y, w, h, palette);

        }

    }

    return ret;

}


static uint64_t htonll(uint64_t v)

{

    union { uint32_t lv[2]; uint64_t llv; } u;

    u.lv[0] = htonl(v >> 32);

    u.lv[1] = htonl(v & 0xFFFFFFFFULL);

    return u.llv;

}


void op_addo (void)

{

    target_ulong tmp;

    tmp = T0;

    T0 += T1;

    if ((T0 >> 31) ^ (T1 >> 31) ^ (tmp >> 31)) {

        CALL_FROM_TB1(do_raise_exception_direct, EXCP_OVERFLOW);

    }

    RETURN();

}


static av_cold int adpcm_decode_init(AVCodecContext * avctx)

{

    ADPCMDecodeContext *c = avctx->priv_data;

    unsigned int max_channels = 2;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_EA_R1:

    case CODEC_ID_ADPCM_EA_R2:

    case CODEC_ID_ADPCM_EA_R3:

    case CODEC_ID_ADPCM_EA_XAS:

        max_channels = 6;

        break;

    }

    if(avctx->channels > max_channels){

        return -1;

    }

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_CT:

        c->status[0].step = c->status[1].step = 511;

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->bits_per_coded_sample != 4) {

            av_log(avctx, AV_LOG_ERROR, "Only 4-bit ADPCM IMA WAV files are supported\n");

            return -1;

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        if (avctx->extradata && avctx->extradata_size == 2 * 4) {

            c->status[0].predictor = AV_RL32(avctx->extradata);

            c->status[1].predictor = AV_RL32(avctx->extradata + 4);

        }

        break;

    default:

        break;

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    avcodec_get_frame_defaults(&c->frame);

    avctx->coded_frame = &c->frame;

    return 0;

}


static void test_qemu_strtol_max(void)

{

    const char *str = g_strdup_printf("%ld", LONG_MAX);

    char f = 'X';

    const char *endptr = &f;

    long res = 999;

    int err;

    err = qemu_strtol(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, LONG_MAX);

    g_assert(endptr == str + strlen(str));

}


static int build_vlc(AVCodecContext *avctx, VLC *vlc, const uint32_t *table)

{

    Node nodes[512];

    uint32_t bits[256];

    int16_t lens[256];

    uint8_t xlat[256];

    int cur_node, i, j, pos = 0;

    ff_free_vlc(vlc);

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

        nodes[i].count = table[i];

        nodes[i].sym   = i;

        nodes[i].n0    = -2;

        nodes[i].l     = i;

        nodes[i].r     = i;

    }

    cur_node = 256;

    j = 0;

    do {

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

            int new_node = j;

            int first_node = cur_node;

            int second_node = cur_node;

            int nd, st;

            nodes[cur_node].count = -1;

            do {

                int val = nodes[new_node].count;

                if (val && (val < nodes[first_node].count)) {

                    if (val >= nodes[second_node].count) {

                        first_node = new_node;

                    } else {

                        first_node = second_node;

                        second_node = new_node;

                    }

                }

                new_node += 1;

            } while (new_node != cur_node);

            if (first_node == cur_node)

                break;

            nd = nodes[second_node].count;

            st = nodes[first_node].count;

            nodes[second_node].count = 0;

            nodes[first_node].count  = 0;

            nodes[cur_node].count = nd + st;

            nodes[cur_node].sym = -1;

            nodes[cur_node].n0 = cur_node;

            nodes[cur_node].l = first_node;

            nodes[cur_node].r = second_node;

            cur_node++;

        }

        j++;

    } while (cur_node - 256 == j);

    get_tree_codes(bits, lens, xlat, nodes, cur_node - 1, 0, 0, &pos);

    return ff_init_vlc_sparse(vlc, 10, pos, lens, 2, 2, bits, 4, 4, xlat, 1, 1, 0);

}


static inline void dv_guess_qnos(EncBlockInfo* blks, int* qnos)

{

    int size[5];

    int i, j, k, a, prev, a2;

    EncBlockInfo* b;

    size[0] = size[1] = size[2] = size[3] = size[4] = 1<<24;

    do {

       b = blks;

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

          if (!qnos[i])

              continue;

          qnos[i]--;

          size[i] = 0;

          for (j=0; j<6; j++, b++) {

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

                if (b->area_q[a] != dv_quant_shifts[qnos[i] + dv_quant_offset[b->cno]][a]) {

                    b->bit_size[a] = 1; // 4 areas 4 bits for EOB :)

                    b->area_q[a]++;

                    prev= b->prev[a];

                    for (k= b->next[prev] ; k<mb_area_start[a+1]; k= b->next[k]) {

                       b->mb[k] >>= 1;

                       if (b->mb[k]) {

                           b->bit_size[a] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);

                           prev= k;

                       } else {

                           if(b->next[k] >= mb_area_start[a+1] && b->next[k]<64){

                                for(a2=a+1; b->next[k] >= mb_area_start[a2+1]; a2++)

                                    b->prev[a2] = prev;

                                assert(a2<4);

                                assert(b->mb[b->next[k]]);

                                b->bit_size[a2] += dv_rl2vlc_size(b->next[k] - prev - 1, b->mb[b->next[k]])

                                                  -dv_rl2vlc_size(b->next[k] -    k - 1, b->mb[b->next[k]]);

                                for(; (b->prev[a2]==k) && (a2<4); a2++)

                                        b->prev[a2] = prev;

                           }

                           b->next[prev] = b->next[k];

                       }

                    }

                    b->prev[a+1]= prev;

                }

                size[i] += b->bit_size[a];

             }

          }

          if(vs_total_ac_bits >= size[0] + size[1] + size[2] + size[3] + size[4])

                return;

       }

    } while (qnos[0]|qnos[1]|qnos[2]|qnos[3]|qnos[4]);

    for(a=2; a==2 || vs_total_ac_bits < size[0]; a+=a){

        b = blks;

        size[0] = 5*6*4; //EOB

        for (j=0; j<6*5; j++, b++) {

            prev= b->prev[0];

            for (k= b->next[prev]; k<64; k= b->next[k]) {

                if(b->mb[k] < a && b->mb[k] > -a){

                    b->next[prev] = b->next[k];

                }else{

                    size[0] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);

                    prev= k;

                }

            }

        }

    }

}


static int vtenc_cm_to_avpacket(

    AVCodecContext    *avctx,

    CMSampleBufferRef sample_buffer,

    AVPacket          *pkt,

    ExtraSEI          *sei)

{

    VTEncContext *vtctx = avctx->priv_data;

    int     status;

    bool    is_key_frame;

    bool    add_header;

    size_t  length_code_size;

    size_t  header_size = 0;

    size_t  in_buf_size;

    size_t  out_buf_size;

    size_t  sei_nalu_size = 0;

    int64_t dts_delta;

    int64_t time_base_num;

    int nalu_count;

    CMTime  pts;

    CMTime  dts;

    CMVideoFormatDescriptionRef vid_fmt;

    vtenc_get_frame_info(sample_buffer, &is_key_frame);

    status = get_length_code_size(avctx, sample_buffer, &length_code_size);

    if (status) return status;

    add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);

    if (add_header) {

        vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);

        if (!vid_fmt) {

            av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");

            return AVERROR_EXTERNAL;

        }

        int status = get_params_size(avctx, vid_fmt, &header_size);

        if (status) return status;

    }

    status = count_nalus(length_code_size, sample_buffer, &nalu_count);

    if(status)

        return status;

    if (sei) {

        sei_nalu_size = sizeof(start_code) + 3 + sei->size + 1;

    }

    in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);

    out_buf_size = header_size +

                   in_buf_size +

                   sei_nalu_size +

                   nalu_count * ((int)sizeof(start_code) - (int)length_code_size);

    status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);

    if (status < 0)

        return status;

    if (add_header) {

        status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);

        if(status) return status;

    }

    status = copy_replace_length_codes(

        avctx,

        length_code_size,

        sample_buffer,

        pkt->data + header_size,

        pkt->size - header_size - sei_nalu_size

    );

    if (status) {

        av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d", status);

        return status;

    }

    if (sei_nalu_size > 0) {

        uint8_t *sei_nalu = pkt->data + pkt->size - sei_nalu_size;

        memcpy(sei_nalu, start_code, sizeof(start_code));

        sei_nalu += sizeof(start_code);

        sei_nalu[0] = H264_NAL_SEI;

        sei_nalu[1] = SEI_TYPE_USER_DATA_REGISTERED;

        sei_nalu[2] = sei->size;

        sei_nalu += 3;

        memcpy(sei_nalu, sei->data, sei->size);

        sei_nalu += sei->size;

        sei_nalu[0] = 1; // RBSP

    }

    if (is_key_frame) {

        pkt->flags |= AV_PKT_FLAG_KEY;

    }

    pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);

    dts = CMSampleBufferGetDecodeTimeStamp      (sample_buffer);

    if (CMTIME_IS_INVALID(dts)) {

        if (!vtctx->has_b_frames) {

            dts = pts;

        } else {

            av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");

            return AVERROR_EXTERNAL;

        }

    }

    dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;

    time_base_num = avctx->time_base.num;

    pkt->pts = pts.value / time_base_num;

    pkt->dts = dts.value / time_base_num - dts_delta;

    pkt->size = out_buf_size;

    return 0;

}


AVFormatContext *avformat_alloc_context(void)

{

    AVFormatContext *ic;

    ic = av_malloc(sizeof(AVFormatContext));

    if (!ic) return ic;

    avformat_get_context_defaults(ic);

    ic->av_class = &av_format_context_class;

    return ic;

}


offset_t url_filesize(URLContext *h)

{

    offset_t pos, size;

    size= url_seek(h, 0, AVSEEK_SIZE);

    if(size<0){

        pos = url_seek(h, 0, SEEK_CUR);

        size = url_seek(h, -1, SEEK_END)+1;

        url_seek(h, pos, SEEK_SET);

    }

    return size;

}


static av_noinline void FUNC(hl_decode_mb)(const H264Context *h, H264SliceContext *sl)

{

    const int mb_x    = sl->mb_x;

    const int mb_y    = sl->mb_y;

    const int mb_xy   = sl->mb_xy;

    const int mb_type = h->cur_pic.mb_type[mb_xy];

    uint8_t *dest_y, *dest_cb, *dest_cr;

    int linesize, uvlinesize /*dct_offset*/;

    int i, j;

    const int *block_offset = &h->block_offset[0];

    const int transform_bypass = !SIMPLE && (sl->qscale == 0 && h->sps.transform_bypass);

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    const int block_h   = 16 >> h->chroma_y_shift;

    const int chroma422 = CHROMA422(h);

    dest_y  = h->cur_pic.f->data[0] + ((mb_x << PIXEL_SHIFT)     + mb_y * sl->linesize)  * 16;

    dest_cb = h->cur_pic.f->data[1] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * sl->uvlinesize * block_h;

    dest_cr = h->cur_pic.f->data[2] +  (mb_x << PIXEL_SHIFT) * 8 + mb_y * sl->uvlinesize * block_h;

    h->vdsp.prefetch(dest_y  + (sl->mb_x & 3) * 4 * sl->linesize   + (64 << PIXEL_SHIFT), sl->linesize,       4);

    h->vdsp.prefetch(dest_cb + (sl->mb_x & 7)     * sl->uvlinesize + (64 << PIXEL_SHIFT), dest_cr - dest_cb, 2);

    h->list_counts[mb_xy] = sl->list_count;

    if (!SIMPLE && MB_FIELD(sl)) {

        linesize     = sl->mb_linesize = sl->linesize * 2;

        uvlinesize   = sl->mb_uvlinesize = sl->uvlinesize * 2;

        block_offset = &h->block_offset[48];

        if (mb_y & 1) { // FIXME move out of this function?

            dest_y  -= sl->linesize * 15;

            dest_cb -= sl->uvlinesize * (block_h - 1);

            dest_cr -= sl->uvlinesize * (block_h - 1);

        }

        if (FRAME_MBAFF(h)) {

            int list;

            for (list = 0; list < sl->list_count; list++) {

                if (!USES_LIST(mb_type, list))

                    continue;

                if (IS_16X16(mb_type)) {

                    int8_t *ref = &sl->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (sl->mb_y & 1), 1);

                } else {

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

                        int ref = sl->ref_cache[list][scan8[i]];

                        if (ref >= 0)

                            fill_rectangle(&sl->ref_cache[list][scan8[i]], 2, 2,

                                           8, (16 + ref) ^ (sl->mb_y & 1), 1);

                    }

                }

            }

        }

    } else {

        linesize   = sl->mb_linesize   = sl->linesize;

        uvlinesize = sl->mb_uvlinesize = sl->uvlinesize;

        // dct_offset = s->linesize * 16;

    }

    if (!SIMPLE && IS_INTRA_PCM(mb_type)) {

        if (PIXEL_SHIFT) {

            const int bit_depth = h->sps.bit_depth_luma;

            int j;

            GetBitContext gb;

            init_get_bits(&gb, sl->intra_pcm_ptr,

                          ff_h264_mb_sizes[h->sps.chroma_format_idc] * bit_depth);

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

                uint16_t *tmp_y = (uint16_t *)(dest_y + i * linesize);

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

                    tmp_y[j] = get_bits(&gb, bit_depth);

            }

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

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

                            tmp_cb[j] = 1 << (bit_depth - 1);

                    }

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

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cr[j] = 1 << (bit_depth - 1);

                    }

                } else {

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

                        uint16_t *tmp_cb = (uint16_t *)(dest_cb + i * uvlinesize);

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

                            tmp_cb[j] = get_bits(&gb, bit_depth);

                    }

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

                        uint16_t *tmp_cr = (uint16_t *)(dest_cr + i * uvlinesize);

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

                            tmp_cr[j] = get_bits(&gb, bit_depth);

                    }

                }

            }

        } else {

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

                memcpy(dest_y + i * linesize, sl->intra_pcm_ptr + i * 16, 16);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {

                if (!h->sps.chroma_format_idc) {

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

                        memset(dest_cb + i * uvlinesize, 128, 8);

                        memset(dest_cr + i * uvlinesize, 128, 8);

                    }

                } else {

                    const uint8_t *src_cb = sl->intra_pcm_ptr + 256;

                    const uint8_t *src_cr = sl->intra_pcm_ptr + 256 + block_h * 8;

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

                        memcpy(dest_cb + i * uvlinesize, src_cb + i * 8, 8);

                        memcpy(dest_cr + i * uvlinesize, src_cr + i * 8, 8);

                    }

                }

            }

        }

    } else {

        if (IS_INTRA(mb_type)) {

            if (sl->deblocking_filter)

                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 1, 0, SIMPLE, PIXEL_SHIFT);

            if (SIMPLE || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) {

                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cb, uvlinesize);

                h->hpc.pred8x8[sl->chroma_pred_mode](dest_cr, uvlinesize);

            }

            hl_decode_mb_predict_luma(h, sl, mb_type, SIMPLE,

                                      transform_bypass, PIXEL_SHIFT,

                                      block_offset, linesize, dest_y, 0);

            if (sl->deblocking_filter)

                xchg_mb_border(h, sl, dest_y, dest_cb, dest_cr, linesize,

                               uvlinesize, 0, 0, SIMPLE, PIXEL_SHIFT);

        } else {

            if (chroma422) {

                FUNC(hl_motion_422)(h, sl, dest_y, dest_cb, dest_cr,

                              h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            } else {

                FUNC(hl_motion_420)(h, sl, dest_y, dest_cb, dest_cr,

                              h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                              h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                              h->h264dsp.weight_h264_pixels_tab,

                              h->h264dsp.biweight_h264_pixels_tab);

            }

        }

        hl_decode_mb_idct_luma(h, sl, mb_type, SIMPLE, transform_bypass,

                               PIXEL_SHIFT, block_offset, linesize, dest_y, 0);

        if ((SIMPLE || !CONFIG_GRAY || !(h->flags & AV_CODEC_FLAG_GRAY)) &&

            (sl->cbp & 0x30)) {

            uint8_t *dest[2] = { dest_cb, dest_cr };

            if (transform_bypass) {

                if (IS_INTRA(mb_type) && h->sps.profile_idc == 244 &&

                    (sl->chroma_pred_mode == VERT_PRED8x8 ||

                     sl->chroma_pred_mode == HOR_PRED8x8)) {

                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[0],

                                                            block_offset + 16,

                                                            sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                            uvlinesize);

                    h->hpc.pred8x8_add[sl->chroma_pred_mode](dest[1],

                                                            block_offset + 32,

                                                            sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                            uvlinesize);

                } else {

                    idct_add = h->h264dsp.h264_add_pixels4_clear;

                    for (j = 1; j < 3; j++) {

                        for (i = j * 16; i < j * 16 + 4; i++)

                            if (sl->non_zero_count_cache[scan8[i]] ||

                                dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))

                                idct_add(dest[j - 1] + block_offset[i],

                                         sl->mb + (i * 16 << PIXEL_SHIFT),

                                         uvlinesize);

                        if (chroma422) {

                            for (i = j * 16 + 4; i < j * 16 + 8; i++)

                                if (sl->non_zero_count_cache[scan8[i + 4]] ||

                                    dctcoef_get(sl->mb, PIXEL_SHIFT, i * 16))

                                    idct_add(dest[j - 1] + block_offset[i + 4],

                                             sl->mb + (i * 16 << PIXEL_SHIFT),

                                             uvlinesize);

                        }

                    }

                }

            } else {

                int qp[2];

                if (chroma422) {

                    qp[0] = sl->chroma_qp[0] + 3;

                    qp[1] = sl->chroma_qp[1] + 3;

                } else {

                    qp[0] = sl->chroma_qp[0];

                    qp[1] = sl->chroma_qp[1];

                }

                if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 0]])

                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 1 << PIXEL_SHIFT),

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 1 : 4][qp[0]][0]);

                if (sl->non_zero_count_cache[scan8[CHROMA_DC_BLOCK_INDEX + 1]])

                    h->h264dsp.h264_chroma_dc_dequant_idct(sl->mb + (16 * 16 * 2 << PIXEL_SHIFT),

                                                           h->dequant4_coeff[IS_INTRA(mb_type) ? 2 : 5][qp[1]][0]);

                h->h264dsp.h264_idct_add8(dest, block_offset,

                                          sl->mb, uvlinesize,

                                          sl->non_zero_count_cache);

            }

        }

    }

}


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

{

    RTPContext *s = h->priv_data;

    struct sockaddr_storage from;

    socklen_t from_len;

    int len, fd_max, n;

    fd_set rfds;

    struct timeval tv;

#if 0

    for(;;) {

        from_len = sizeof(from);

        len = recvfrom (s->rtp_fd, buf, size, 0,

                        (struct sockaddr *)&from, &from_len);

        if (len < 0) {

            if (ff_neterrno() == FF_NETERROR(EAGAIN) ||

                ff_neterrno() == FF_NETERROR(EINTR))

                continue;

            return AVERROR(EIO);

        }

        break;

    }

#else

    for(;;) {

        if (url_interrupt_cb())

            return AVERROR(EINTR);

        /* build fdset to listen to RTP and RTCP packets */

        FD_ZERO(&rfds);

        fd_max = s->rtp_fd;

        FD_SET(s->rtp_fd, &rfds);

        if (s->rtcp_fd > fd_max)

            fd_max = s->rtcp_fd;

        FD_SET(s->rtcp_fd, &rfds);

        tv.tv_sec = 0;

        tv.tv_usec = 100 * 1000;

        n = select(fd_max + 1, &rfds, NULL, NULL, &tv);

        if (n > 0) {

            /* first try RTCP */

            if (FD_ISSET(s->rtcp_fd, &rfds)) {

                from_len = sizeof(from);

                len = recvfrom (s->rtcp_fd, buf, size, 0,

                                (struct sockaddr *)&from, &from_len);

                if (len < 0) {

                    if (ff_neterrno() == FF_NETERROR(EAGAIN) ||

                        ff_neterrno() == FF_NETERROR(EINTR))

                        continue;

                    return AVERROR(EIO);

                }

                break;

            }

            /* then RTP */

            if (FD_ISSET(s->rtp_fd, &rfds)) {

                from_len = sizeof(from);

                len = recvfrom (s->rtp_fd, buf, size, 0,

                                (struct sockaddr *)&from, &from_len);

                if (len < 0) {

                    if (ff_neterrno() == FF_NETERROR(EAGAIN) ||

                        ff_neterrno() == FF_NETERROR(EINTR))

                        continue;

                    return AVERROR(EIO);

                }

                break;

            }

        } else if (n < 0) {

            if (ff_neterrno() == FF_NETERROR(EINTR))

                continue;

            return AVERROR(EIO);

        }

    }

#endif

    return len;

}


static int load_apply_palette(FFFrameSync *fs)

{

    AVFilterContext *ctx = fs->parent;

    AVFilterLink *inlink = ctx->inputs[0];

    PaletteUseContext *s = ctx->priv;

    AVFrame *master, *second, *out;

    int ret;

    // writable for error diffusal dithering

    ret = ff_framesync_dualinput_get_writable(fs, &master, &second);

    if (ret < 0)

        return ret;

    if (!master || !second) {

        ret = AVERROR_BUG;

        goto error;

    }

    if (!s->palette_loaded) {

        load_palette(s, second);

    }

    out = apply_palette(inlink, master);

    return ff_filter_frame(ctx->outputs[0], out);

error:

    av_frame_free(&master);

    av_frame_free(&second);

    return ret;

}


static void test_parse_invalid_path(void)

{

    g_test_trap_subprocess ("/logging/parse_invalid_path/subprocess", 0, 0);

    g_test_trap_assert_passed();

    g_test_trap_assert_stdout("");

    g_test_trap_assert_stderr("Bad logfile format: /tmp/qemu-%d%d.log\n");

}


void bdrv_iterate_format(void (*it)(void *opaque, const char *name),

                         void *opaque)

{

    BlockDriver *drv;

    int count = 0;

    const char **formats = NULL;

    QLIST_FOREACH(drv, &bdrv_drivers, list) {

        if (drv->format_name) {

            bool found = false;

            int i = count;

            while (formats && i && !found) {

                found = !strcmp(formats[--i], drv->format_name);

            }

            if (!found) {

                formats = g_realloc(formats, (count + 1) * sizeof(char *));

                formats[count++] = drv->format_name;

                it(opaque, drv->format_name);

            }

        }

    }

    g_free(formats);

}


static int ea_read_header(AVFormatContext *s,

                          AVFormatParameters *ap)

{

    EaDemuxContext *ea = s->priv_data;

    AVStream *st;

    if (!process_ea_header(s))

        return AVERROR(EIO);

    if (ea->video_codec) {

        /* initialize the video decoder stream */

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        ea->video_stream_index = st->index;

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id = ea->video_codec;

        st->codec->codec_tag = 0;  /* no fourcc */

        st->codec->time_base = ea->time_base;

        st->codec->width = ea->width;

        st->codec->height = ea->height;

    if (ea->audio_codec) {

        if (ea->num_channels <= 0) {

            av_log(s, AV_LOG_WARNING, "Unsupported number of channels: %d\n", ea->num_channels);

            ea->audio_codec = 0;

        if (ea->sample_rate <= 0) {

            av_log(s, AV_LOG_ERROR, "Unsupported sample rate: %d\n", ea->sample_rate);

            ea->audio_codec = 0;

        /* initialize the audio decoder stream */

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        avpriv_set_pts_info(st, 33, 1, ea->sample_rate);

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = ea->audio_codec;

        st->codec->codec_tag = 0;  /* no tag */

        st->codec->channels = ea->num_channels;

        st->codec->sample_rate = ea->sample_rate;

        st->codec->bits_per_coded_sample = ea->bytes * 8;

        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *

            st->codec->bits_per_coded_sample / 4;

        st->codec->block_align = st->codec->channels*st->codec->bits_per_coded_sample;

        ea->audio_stream_index = st->index;

        ea->audio_frame_counter = 0;


static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,

                            int buf_size, void *data)

{

    AC3EncodeContext *s = avctx->priv_data;

    const SampleType *samples = data;

    int ret;

    if (s->bit_alloc.sr_code == 1)

        adjust_frame_size(s);

    deinterleave_input_samples(s, samples);

    apply_mdct(s);

    compute_rematrixing_strategy(s);

    scale_coefficients(s);

    apply_rematrixing(s);

    process_exponents(s);

    ret = compute_bit_allocation(s);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");

        return ret;

    }

    quantize_mantissas(s);

    output_frame(s, frame);

    return s->frame_size;

}


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;

            if(rm->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            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");

                return -1;

            }

            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;

            if(rm->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);

        } else if (!strcmp(buf, "raac") || !strcmp(buf, "racp")) {

            int codecdata_length, i;

            get_be16(pb); get_byte(pb);

            if (((version >> 16) & 0xff) == 5)

                get_byte(pb);

            st->codec->codec_id = CODEC_ID_AAC;

            codecdata_length = get_be32(pb);

            if (codecdata_length >= 1) {

                st->codec->extradata_size = codecdata_length - 1;

                st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                get_byte(pb);

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

                    ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);

            }

        } 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 void term_init(void)

{

#if HAVE_TERMIOS_H

    if(!run_as_daemon){

    struct termios tty;

    tcgetattr (0, &tty);

    oldtty = tty;

    atexit(term_exit);

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP

                          |INLCR|IGNCR|ICRNL|IXON);

    tty.c_oflag |= OPOST;

    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);

    tty.c_cflag &= ~(CSIZE|PARENB);

    tty.c_cflag |= CS8;

    tty.c_cc[VMIN] = 1;

    tty.c_cc[VTIME] = 0;

    tcsetattr (0, TCSANOW, &tty);

    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */

    }

#endif

    avformat_network_deinit();

    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */

    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */

#ifdef SIGXCPU

    signal(SIGXCPU, sigterm_handler);

#endif

}


static int tcp_write_packet(AVFormatContext *s, RTSPStream *rtsp_st)

{

    RTSPState *rt = s->priv_data;

    AVFormatContext *rtpctx = rtsp_st->transport_priv;

    uint8_t *buf, *ptr;

    int size;

    uint8_t *interleave_header, *interleaved_packet;

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

    ptr = buf;

    while (size > 4) {

        uint32_t packet_len = AV_RB32(ptr);

        int id;

        /* The interleaving header is exactly 4 bytes, which happens to be

         * the same size as the packet length header from

         * ffio_open_dyn_packet_buf. So by writing the interleaving header

         * over these bytes, we get a consecutive interleaved packet

         * that can be written in one call. */

        interleaved_packet = interleave_header = ptr;

        ptr += 4;

        size -= 4;

        if (packet_len > size || packet_len < 2)

            break;

        if (RTP_PT_IS_RTCP(ptr[1]))

            id = rtsp_st->interleaved_max; /* RTCP */

        else

            id = rtsp_st->interleaved_min; /* RTP */

        interleave_header[0] = '$';

        interleave_header[1] = id;

        AV_WB16(interleave_header + 2, packet_len);

        ffurl_write(rt->rtsp_hd_out, interleaved_packet, 4 + packet_len);

        ptr += packet_len;

        size -= packet_len;

    }

    av_free(buf);

    ffio_open_dyn_packet_buf(&rtpctx->pb, RTSP_TCP_MAX_PACKET_SIZE);

    return 0;

}


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

{

    VirtIOBlock *s = opaque;

    if (version_id != 2)

        return -EINVAL;

    virtio_load(&s->vdev, f);

    while (qemu_get_sbyte(f)) {

        VirtIOBlockReq *req = virtio_blk_alloc_request(s);

        qemu_get_buffer(f, (unsigned char*)&req->elem, sizeof(req->elem));

        req->next = s->rq;

        s->rq = req;

        virtqueue_map_sg(req->elem.in_sg, req->elem.in_addr,

            req->elem.in_num, 1);

        virtqueue_map_sg(req->elem.out_sg, req->elem.out_addr,

            req->elem.out_num, 0);

    }

    return 0;

}


static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,

                               unsigned int epid)

{

    XHCISlot *slot;

    XHCIEPContext *epctx;

    int i;

    trace_usb_xhci_ep_disable(slotid, epid);

    assert(slotid >= 1 && slotid <= xhci->numslots);

    assert(epid >= 1 && epid <= 31);

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {

        DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);

        return CC_SUCCESS;

    }

    xhci_ep_nuke_xfers(xhci, slotid, epid, 0);

    epctx = slot->eps[epid-1];

    if (epctx->nr_pstreams) {

        xhci_free_streams(epctx);

    }

    for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {

        usb_packet_cleanup(&epctx->transfers[i].packet);

    }

    xhci_set_ep_state(xhci, epctx, NULL, EP_DISABLED);

    timer_free(epctx->kick_timer);

    g_free(epctx);

    slot->eps[epid-1] = NULL;

    return CC_SUCCESS;

}


static void parse_mb_skip(Wmv2Context *w)

{

    int mb_x, mb_y;

    MpegEncContext *const s = &w->s;

    uint32_t *const mb_type = s->current_picture_ptr->mb_type;

    w->skip_type = get_bits(&s->gb, 2);

    switch (w->skip_type) {

    case SKIP_TYPE_NONE:

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

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

                mb_type[mb_y * s->mb_stride + mb_x] =

                    MB_TYPE_16x16 | MB_TYPE_L0;

        break;

    case SKIP_TYPE_MPEG:

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

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

                mb_type[mb_y * s->mb_stride + mb_x] =

                    (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;

        break;

    case SKIP_TYPE_ROW:

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

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

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

                    mb_type[mb_y * s->mb_stride + mb_x] =

                        MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;

            } else {

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

                    mb_type[mb_y * s->mb_stride + mb_x] =

                        (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;

            }

        }

        break;

    case SKIP_TYPE_COL:

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

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

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

                    mb_type[mb_y * s->mb_stride + mb_x] =

                        MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;

            } else {

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

                    mb_type[mb_y * s->mb_stride + mb_x] =

                        (get_bits1(&s->gb) ? MB_TYPE_SKIP : 0) | MB_TYPE_16x16 | MB_TYPE_L0;

            }

        }

        break;

    }

}


static void qemu_chr_free_common(CharDriverState *chr)

{

    g_free(chr->filename);

    g_free(chr->label);

    if (chr->logfd != -1) {

        close(chr->logfd);

    qemu_mutex_destroy(&chr->chr_write_lock);

    g_free(chr);


void do_unassigned_access(target_phys_addr_t addr, int is_write, int is_exec,

                          int is_asi, int size)

{

    CPUState *saved_env;

    int fault_type;

    /* XXX: hack to restore env in all cases, even if not called from

       generated code */

    saved_env = env;

    env = cpu_single_env;

#ifdef DEBUG_UNASSIGNED

    if (is_asi)

        printf("Unassigned mem %s access of %d byte%s to " TARGET_FMT_plx

               " asi 0x%02x from " TARGET_FMT_lx "\n",

               is_exec ? "exec" : is_write ? "write" : "read", size,

               size == 1 ? "" : "s", addr, is_asi, env->pc);

    else

        printf("Unassigned mem %s access of %d byte%s to " TARGET_FMT_plx

               " from " TARGET_FMT_lx "\n",

               is_exec ? "exec" : is_write ? "write" : "read", size,

               size == 1 ? "" : "s", addr, env->pc);

#endif

    /* Don't overwrite translation and access faults */

    fault_type = (env->mmuregs[3] & 0x1c) >> 2;

    if ((fault_type > 4) || (fault_type == 0)) {

        env->mmuregs[3] = 0; /* Fault status register */

        if (is_asi)

            env->mmuregs[3] |= 1 << 16;

        if (env->psrs)

            env->mmuregs[3] |= 1 << 5;

        if (is_exec)

            env->mmuregs[3] |= 1 << 6;

        if (is_write)

            env->mmuregs[3] |= 1 << 7;

        env->mmuregs[3] |= (5 << 2) | 2;

        /* SuperSPARC will never place instruction fault addresses in the FAR */

        if (!is_exec) {

            env->mmuregs[4] = addr; /* Fault address register */

        }

    }

    /* overflow (same type fault was not read before another fault) */

    if (fault_type == ((env->mmuregs[3] & 0x1c)) >> 2) {

        env->mmuregs[3] |= 1;

    }

    if ((env->mmuregs[0] & MMU_E) && !(env->mmuregs[0] & MMU_NF)) {

        if (is_exec)

            raise_exception(TT_CODE_ACCESS);

        else

            raise_exception(TT_DATA_ACCESS);

    }

    /* flush neverland mappings created during no-fault mode,

       so the sequential MMU faults report proper fault types */

    if (env->mmuregs[0] & MMU_NF) {

        tlb_flush(env, 1);

    }

    env = saved_env;

}


int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
{
    int ret;
    BdrvTrackedRequest req;
    if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
        bdrv_is_sg(bs)) {
        return 0;
    }
    tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
    int current_gen = bs->write_gen;
    /* Wait until any previous flushes are completed */
    while (bs->flush_started_gen != bs->flushed_gen) {
        qemu_co_queue_wait(&bs->flush_queue);
    }
    bs->flush_started_gen = current_gen;
    /* Write back all layers by calling one driver function */
    if (bs->drv->bdrv_co_flush) {
        ret = bs->drv->bdrv_co_flush(bs);
        goto out;
    }
    /* Write back cached data to the OS even with cache=unsafe */
    BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
    if (bs->drv->bdrv_co_flush_to_os) {
        ret = bs->drv->bdrv_co_flush_to_os(bs);
        if (ret < 0) {
            goto out;
        }
    }
    /* But don't actually force it to the disk with cache=unsafe */
    if (bs->open_flags & BDRV_O_NO_FLUSH) {
        goto flush_parent;
    }
    /* Check if we really need to flush anything */
    if (bs->flushed_gen == current_gen) {
        goto flush_parent;
    }
    BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
    if (bs->drv->bdrv_co_flush_to_disk) {
        ret = bs->drv->bdrv_co_flush_to_disk(bs);
    } else if (bs->drv->bdrv_aio_flush) {
        BlockAIOCB *acb;
        CoroutineIOCompletion co = {
            .coroutine = qemu_coroutine_self(),
        };
        acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
        if (acb == NULL) {
            ret = -EIO;
        } else {
            qemu_coroutine_yield();
            ret = co.ret;
        }
    } else {
        /*
         * Some block drivers always operate in either writethrough or unsafe
         * mode and don't support bdrv_flush therefore. Usually qemu doesn't
         * know how the server works (because the behaviour is hardcoded or
         * depends on server-side configuration), so we can't ensure that
         * everything is safe on disk. Returning an error doesn't work because
         * that would break guests even if the server operates in writethrough
         * mode.
         *
         * Let's hope the user knows what he's doing.
         */
        ret = 0;
    }
    if (ret < 0) {
        goto out;
    }
    /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
     * in the case of cache=unsafe, so there are no useless flushes.
     */
flush_parent:
    ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
out:
    /* Notify any pending flushes that we have completed */
    bs->flushed_gen = current_gen;
    qemu_co_queue_restart_all(&bs->flush_queue);
    tracked_request_end(&req);
    return ret;
}


static int modify_current_stream(HTTPContext *c, char *rates)
{
    int i;
    FFStream *req = c->stream;
    int action_required = 0;
    for (i = 0; i < req->nb_streams; i++) {
        AVCodecContext *codec = &req->streams[i]->codec;
        switch(rates[i]) {
            case 0:
                c->switch_feed_streams[i] = req->feed_streams[i];
                break;
            case 1:
                c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
                break;
            case 2:
                /* Wants off or slow */
                c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
#ifdef WANTS_OFF
                /* This doesn't work well when it turns off the only stream! */
                c->switch_feed_streams[i] = -2;
                c->feed_streams[i] = -2;
#endif
                break;
        }
        if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
            action_required = 1;
    }
    return action_required;
}


static int cirrus_bitblt_cputovideo(CirrusVGAState * s)
{
    int w;
    if (blit_is_unsafe(s, true)) {
        return 0;
    }
    s->cirrus_blt_mode &= ~CIRRUS_BLTMODE_MEMSYSSRC;
    s->cirrus_srcptr = &s->cirrus_bltbuf[0];
    s->cirrus_srcptr_end = &s->cirrus_bltbuf[0];
    if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {
	if (s->cirrus_blt_mode & CIRRUS_BLTMODE_COLOREXPAND) {
	    s->cirrus_blt_srcpitch = 8;
	} else {
            /* XXX: check for 24 bpp */
	    s->cirrus_blt_srcpitch = 8 * 8 * s->cirrus_blt_pixelwidth;
	}
	s->cirrus_srccounter = s->cirrus_blt_srcpitch;
    } else {
	if (s->cirrus_blt_mode & CIRRUS_BLTMODE_COLOREXPAND) {
            w = s->cirrus_blt_width / s->cirrus_blt_pixelwidth;
            if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_DWORDGRANULARITY)
                s->cirrus_blt_srcpitch = ((w + 31) >> 5);
            else
                s->cirrus_blt_srcpitch = ((w + 7) >> 3);
	} else {
            /* always align input size to 32 bits */
	    s->cirrus_blt_srcpitch = (s->cirrus_blt_width + 3) & ~3;
	}
        s->cirrus_srccounter = s->cirrus_blt_srcpitch * s->cirrus_blt_height;
    }
    s->cirrus_srcptr = s->cirrus_bltbuf;
    s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;
    cirrus_update_memory_access(s);
    return 1;
}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VFIOAmdXgbeDeviceClass *vcxc =

        VFIO_AMD_XGBE_DEVICE_CLASS(klass);

    vcxc->parent_realize = dc->realize;

    dc->realize = amd_xgbe_realize;

    dc->desc = "VFIO AMD XGBE";

    dc->vmsd = &vfio_platform_amd_xgbe_vmstate;

}


static int hls_window(AVFormatContext *s, int last)

{

    HLSContext *hls = s->priv_data;

    HLSSegment *en;

    int target_duration = 0;

    int ret = 0;

    AVIOContext *out = NULL;

    AVIOContext *sub_out = NULL;

    char temp_filename[1024];

    int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);

    int version = 3;

    const char *proto = avio_find_protocol_name(s->filename);

    int use_rename = proto && !strcmp(proto, "file");

    static unsigned warned_non_file;

    char *key_uri = NULL;

    char *iv_string = NULL;

    AVDictionary *options = NULL;

    double prog_date_time = hls->initial_prog_date_time;

    int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);

    if (byterange_mode) {

        version = 4;

        sequence = 0;

    }

    if (hls->segment_type == SEGMENT_TYPE_FMP4) {

        version = 7;

    }

    if (!use_rename && !warned_non_file++)

        av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");

    set_http_options(s, &options, hls);

    snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);

    if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &options)) < 0)

        goto fail;

    for (en = hls->segments; en; en = en->next) {

        if (target_duration <= en->duration)

            target_duration = get_int_from_double(en->duration);

    }

    hls->discontinuity_set = 0;

    write_m3u8_head_block(hls, out, version, target_duration, sequence);

    if (hls->pl_type == PLAYLIST_TYPE_EVENT) {

        avio_printf(out, "#EXT-X-PLAYLIST-TYPE:EVENT\n");

    } else if (hls->pl_type == PLAYLIST_TYPE_VOD) {

        avio_printf(out, "#EXT-X-PLAYLIST-TYPE:VOD\n");

    }

    if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && hls->discontinuity_set==0 ){

        avio_printf(out, "#EXT-X-DISCONTINUITY\n");

        hls->discontinuity_set = 1;

    }

    for (en = hls->segments; en; en = en->next) {

        if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||

                                    av_strcasecmp(en->iv_string, iv_string))) {

            avio_printf(out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);

            if (*en->iv_string)

                avio_printf(out, ",IV=0x%s", en->iv_string);

            avio_printf(out, "\n");

            key_uri = en->key_uri;

            iv_string = en->iv_string;

        }

        if (en->discont) {

            avio_printf(out, "#EXT-X-DISCONTINUITY\n");

        }

        if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == hls->segments)) {

            avio_printf(out, "#EXT-X-MAP:URI=\"%s\"", hls->fmp4_init_filename);

            if (hls->flags & HLS_SINGLE_FILE) {

                avio_printf(out, ",BYTERANGE=\"%"PRId64"@%"PRId64"\"", en->size, en->pos);

            }

            avio_printf(out, "\n");

        } else {

            if (hls->flags & HLS_ROUND_DURATIONS)

                avio_printf(out, "#EXTINF:%ld,\n",  lrint(en->duration));

            else

                avio_printf(out, "#EXTINF:%f,\n", en->duration);

            if (byterange_mode)

                avio_printf(out, "#EXT-X-BYTERANGE:%"PRId64"@%"PRId64"\n",

                            en->size, en->pos);

        }

        if (hls->flags & HLS_PROGRAM_DATE_TIME) {

            time_t tt, wrongsecs;

            int milli;

            struct tm *tm, tmpbuf;

            char buf0[128], buf1[128];

            tt = (int64_t)prog_date_time;

            milli = av_clip(lrint(1000*(prog_date_time - tt)), 0, 999);

            tm = localtime_r(&tt, &tmpbuf);

            strftime(buf0, sizeof(buf0), "%Y-%m-%dT%H:%M:%S", tm);

            if (!strftime(buf1, sizeof(buf1), "%z", tm) || buf1[1]<'0' ||buf1[1]>'2') {

                int tz_min, dst = tm->tm_isdst;

                tm = gmtime_r(&tt, &tmpbuf);

                tm->tm_isdst = dst;

                wrongsecs = mktime(tm);

                tz_min = (abs(wrongsecs - tt) + 30) / 60;

                snprintf(buf1, sizeof(buf1),

                         "%c%02d%02d",

                         wrongsecs <= tt ? '+' : '-',

                         tz_min / 60,

                         tz_min % 60);

            }

            avio_printf(out, "#EXT-X-PROGRAM-DATE-TIME:%s.%03d%s\n", buf0, milli, buf1);

            prog_date_time += en->duration;

        }

        if (!((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == hls->segments))) {

            if (hls->baseurl)

                avio_printf(out, "%s", hls->baseurl);

            avio_printf(out, "%s\n", en->filename);

        }

    }

    if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)

        avio_printf(out, "#EXT-X-ENDLIST\n");

    if( hls->vtt_m3u8_name ) {

        if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)

            goto fail;

        write_m3u8_head_block(hls, sub_out, version, target_duration, sequence);

        for (en = hls->segments; en; en = en->next) {

            avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);

            if (byterange_mode)

                 avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",

                         en->size, en->pos);

            if (hls->baseurl)

                avio_printf(sub_out, "%s", hls->baseurl);

            avio_printf(sub_out, "%s\n", en->sub_filename);

        }

        if (last)

            avio_printf(sub_out, "#EXT-X-ENDLIST\n");

    }

fail:

    av_dict_free(&options);

    ff_format_io_close(s, &out);

    ff_format_io_close(s, &sub_out);

    if (ret >= 0 && use_rename)

        ff_rename(temp_filename, s->filename, s);

    return ret;

}


static inline void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,

                                    const uint8_t *src1, const uint8_t *src2,

                                    int width, uint32_t *unused)

{

    RENAME(nvXXtoUV)(dstU, dstV, src1, width);

}


void blk_eject(BlockBackend *blk, bool eject_flag)

{

    BlockDriverState *bs = blk_bs(blk);

    char *id;

    /* blk_eject is only called by qdevified devices */

    assert(!blk->legacy_dev);

    if (bs) {

        bdrv_eject(bs, eject_flag);

        id = blk_get_attached_dev_id(blk);

        qapi_event_send_device_tray_moved(blk_name(blk), id,

                                          eject_flag, &error_abort);

        g_free(id);

    }

}


static void megasas_scsi_realize(PCIDevice *dev, Error **errp)

{

    DeviceState *d = DEVICE(dev);

    MegasasState *s = MEGASAS(dev);

    MegasasBaseClass *b = MEGASAS_DEVICE_GET_CLASS(s);

    uint8_t *pci_conf;

    int i, bar_type;

    Error *err = NULL;

    int ret;

    pci_conf = dev->config;

    /* PCI latency timer = 0 */

    pci_conf[PCI_LATENCY_TIMER] = 0;

    /* Interrupt pin 1 */

    pci_conf[PCI_INTERRUPT_PIN] = 0x01;

    if (s->msi != ON_OFF_AUTO_OFF) {

        ret = msi_init(dev, 0x50, 1, true, false, &err);

        /* Any error other than -ENOTSUP(board's MSI support is broken)

         * is a programming error */

        assert(!ret || ret == -ENOTSUP);

        if (ret && s->msi == ON_OFF_AUTO_ON) {

            /* Can't satisfy user's explicit msi=on request, fail */

            error_append_hint(&err, "You have to use msi=auto (default) or "

                    "msi=off with this machine type.\n");

            error_propagate(errp, err);

            return;

        } else if (ret) {

            /* With msi=auto, we fall back to MSI off silently */

            s->msi = ON_OFF_AUTO_OFF;

            error_free(err);

        }

    }

    memory_region_init_io(&s->mmio_io, OBJECT(s), &megasas_mmio_ops, s,

                          "megasas-mmio", 0x4000);

    memory_region_init_io(&s->port_io, OBJECT(s), &megasas_port_ops, s,

                          "megasas-io", 256);

    memory_region_init_io(&s->queue_io, OBJECT(s), &megasas_queue_ops, s,

                          "megasas-queue", 0x40000);

    if (megasas_use_msix(s) &&

        msix_init(dev, 15, &s->mmio_io, b->mmio_bar, 0x2000,

                  &s->mmio_io, b->mmio_bar, 0x3800, 0x68)) {

        s->msix = ON_OFF_AUTO_OFF;

    }

    if (pci_is_express(dev)) {

        pcie_endpoint_cap_init(dev, 0xa0);

    }

    bar_type = PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64;

    pci_register_bar(dev, b->ioport_bar,

                     PCI_BASE_ADDRESS_SPACE_IO, &s->port_io);

    pci_register_bar(dev, b->mmio_bar, bar_type, &s->mmio_io);

    pci_register_bar(dev, 3, bar_type, &s->queue_io);

    if (megasas_use_msix(s)) {

        msix_vector_use(dev, 0);

    }

    s->fw_state = MFI_FWSTATE_READY;

    if (!s->sas_addr) {

        s->sas_addr = ((NAA_LOCALLY_ASSIGNED_ID << 24) |

                       IEEE_COMPANY_LOCALLY_ASSIGNED) << 36;

        s->sas_addr |= (pci_bus_num(dev->bus) << 16);

        s->sas_addr |= (PCI_SLOT(dev->devfn) << 8);

        s->sas_addr |= PCI_FUNC(dev->devfn);

    }

    if (!s->hba_serial) {

        s->hba_serial = g_strdup(MEGASAS_HBA_SERIAL);

    }

    if (s->fw_sge >= MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE) {

        s->fw_sge = MEGASAS_MAX_SGE - MFI_PASS_FRAME_SIZE;

    } else if (s->fw_sge >= 128 - MFI_PASS_FRAME_SIZE) {

        s->fw_sge = 128 - MFI_PASS_FRAME_SIZE;

    } else {

        s->fw_sge = 64 - MFI_PASS_FRAME_SIZE;

    }

    if (s->fw_cmds > MEGASAS_MAX_FRAMES) {

        s->fw_cmds = MEGASAS_MAX_FRAMES;

    }

    trace_megasas_init(s->fw_sge, s->fw_cmds,

                       megasas_is_jbod(s) ? "jbod" : "raid");

    if (megasas_is_jbod(s)) {

        s->fw_luns = MFI_MAX_SYS_PDS;

    } else {

        s->fw_luns = MFI_MAX_LD;

    }

    s->producer_pa = 0;

    s->consumer_pa = 0;

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

        s->frames[i].index = i;

        s->frames[i].context = -1;

        s->frames[i].pa = 0;

        s->frames[i].state = s;

    }

    scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),

                 &megasas_scsi_info, NULL);

    if (!d->hotplugged) {

        scsi_bus_legacy_handle_cmdline(&s->bus, errp);

    }

}


int kvm_arch_debug(struct kvm_debug_exit_arch *arch_info)

{

    int handle = 0;

    int n;

    if (arch_info->exception == 1) {

        if (arch_info->dr6 & (1 << 14)) {

            if (cpu_single_env->singlestep_enabled)

                handle = 1;

        } else {

            for (n = 0; n < 4; n++)

                if (arch_info->dr6 & (1 << n))

                    switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {

                    case 0x0:

                        handle = 1;

                        break;

                    case 0x1:

                        handle = 1;

                        cpu_single_env->watchpoint_hit = &hw_watchpoint;

                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;

                        hw_watchpoint.flags = BP_MEM_WRITE;

                        break;

                    case 0x3:

                        handle = 1;

                        cpu_single_env->watchpoint_hit = &hw_watchpoint;

                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;

                        hw_watchpoint.flags = BP_MEM_ACCESS;

                        break;

                    }

        }

    } else if (kvm_find_sw_breakpoint(cpu_single_env, arch_info->pc))

        handle = 1;

    if (!handle)

        kvm_update_guest_debug(cpu_single_env,

                        (arch_info->exception == 1) ?

                        KVM_GUESTDBG_INJECT_DB : KVM_GUESTDBG_INJECT_BP);

    return handle;

}


static int mpegts_read_packet(AVFormatContext *s,

                              AVPacket *pkt)

{

    MpegTSContext *ts = s->priv_data;

    int ret, i;

    ts->pkt = pkt;

    ret = handle_packets(ts, 0);

    if (ret < 0) {

        /* flush pes data left */

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

            if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {

                PESContext *pes = ts->pids[i]->u.pes_filter.opaque;

                if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {

                    new_pes_packet(pes, pkt);

                    pes->state = MPEGTS_SKIP;

                    ret = 0;

                    break;

                }

            }

        }

    }

    if (!ret && pkt->size < 0)

        ret = AVERROR(EINTR);

    return ret;

}


static int qemu_savevm_state(QEMUFile *f)

{

    SaveStateEntry *se;

    int len, ret;

    int64_t cur_pos, len_pos, total_len_pos;

    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);

    qemu_put_be32(f, QEMU_VM_FILE_VERSION);

    total_len_pos = qemu_ftell(f);

    qemu_put_be64(f, 0); /* total size */

    for(se = first_se; se != NULL; se = se->next) {

	if (se->save_state == NULL)

	    /* this one has a loader only, for backwards compatibility */

	    continue;

        /* ID string */

        len = strlen(se->idstr);

        qemu_put_byte(f, len);

        qemu_put_buffer(f, (uint8_t *)se->idstr, len);

        qemu_put_be32(f, se->instance_id);

        qemu_put_be32(f, se->version_id);

        /* record size: filled later */

        len_pos = qemu_ftell(f);

        qemu_put_be32(f, 0);

        se->save_state(f, se->opaque);

        /* fill record size */

        cur_pos = qemu_ftell(f);

        len = cur_pos - len_pos - 4;

        qemu_fseek(f, len_pos, SEEK_SET);

        qemu_put_be32(f, len);

        qemu_fseek(f, cur_pos, SEEK_SET);

    }

    cur_pos = qemu_ftell(f);

    qemu_fseek(f, total_len_pos, SEEK_SET);

    qemu_put_be64(f, cur_pos - total_len_pos - 8);

    qemu_fseek(f, cur_pos, SEEK_SET);

    ret = 0;

    return ret;

}


static void cmv_decode_inter(CmvContext * s, const uint8_t *buf, const uint8_t *buf_end){

    const uint8_t *raw = buf + (s->avctx->width*s->avctx->height/16);

    int x,y,i;

    i = 0;

    for(y=0; y<s->avctx->height/4; y++)

    for(x=0; x<s->avctx->width/4 && buf+i<buf_end; x++) {

        if (buf[i]==0xFF) {

            unsigned char *dst = s->frame.data[0] + (y*4)*s->frame.linesize[0] + x*4;

            if (raw+16<buf_end && *raw==0xFF) { /* intra */

                raw++;

                memcpy(dst, raw, 4);

                memcpy(dst+s->frame.linesize[0], raw+4, 4);

                memcpy(dst+2*s->frame.linesize[0], raw+8, 4);

                memcpy(dst+3*s->frame.linesize[0], raw+12, 4);

                raw+=16;

            }else if(raw<buf_end) {  /* inter using second-last frame as reference */

                int xoffset = (*raw & 0xF) - 7;

                int yoffset = ((*raw >> 4)) - 7;

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

                    cmv_motcomp(s->frame.data[0], s->frame.linesize[0],

                                s->last2_frame.data[0], s->last2_frame.linesize[0],

                                x*4, y*4, xoffset, yoffset, s->avctx->width, s->avctx->height);

                raw++;

            }

        }else{  /* inter using last frame as reference */

            int xoffset = (buf[i] & 0xF) - 7;

            int yoffset = ((buf[i] >> 4)) - 7;

            cmv_motcomp(s->frame.data[0], s->frame.linesize[0],

                      s->last_frame.data[0], s->last_frame.linesize[0],

                      x*4, y*4, xoffset, yoffset, s->avctx->width, s->avctx->height);

        }

        i++;

    }

}


int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,

              int flags, BlockDriver *drv, Error **errp)

{

    int ret;

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char tmp_filename[PATH_MAX + 1];

    BlockDriverState *file = NULL;

    QDict *file_options = NULL;

    const char *drvname;

    Error *local_err = NULL;

    /* NULL means an empty set of options */

    if (options == NULL) {

        options = qdict_new();

    }

    bs->options = options;

    options = qdict_clone_shallow(options);

    /* For snapshot=on, create a temporary qcow2 overlay */

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *create_options;

        char backing_filename[PATH_MAX];

        if (qdict_size(options) != 0) {

            error_setg(errp, "Can't use snapshot=on with driver-specific options");

            ret = -EINVAL;

            goto fail;

        }

        assert(filename != NULL);

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open(bs1, filename, NULL, 0, drv, &local_err);

        if (ret < 0) {

            bdrv_unref(bs1);

            goto fail;

        }

        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;

        bdrv_unref(bs1);

        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not get temporary filename");

            goto fail;

        }

        /* Real path is meaningless for protocols */

        if (path_has_protocol(filename)) {

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        } else if (!realpath(filename, backing_filename)) {

            error_setg_errno(errp, errno, "Could not resolve path '%s'", filename);

            ret = -errno;

            goto fail;

        }

        bdrv_qcow2 = bdrv_find_format("qcow2");

        create_options = parse_option_parameters("", bdrv_qcow2->create_options,

                                                 NULL);

        set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);

        set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,

                             backing_filename);

        if (drv) {

            set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);

        free_option_parameters(create_options);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not create temporary overlay "

                             "'%s': %s", tmp_filename,

                             error_get_pretty(local_err));

            error_free(local_err);

            local_err = NULL;

            goto fail;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    /* Open image file without format layer */

    if (flags & BDRV_O_RDWR) {

        flags |= BDRV_O_ALLOW_RDWR;

    }

    qdict_extract_subqdict(options, &file_options, "file.");

    ret = bdrv_file_open(&file, filename, file_options,

                         bdrv_open_flags(bs, flags | BDRV_O_UNMAP), &local_err);

    if (ret < 0) {

        goto fail;

    }

    /* Find the right image format driver */

    drvname = qdict_get_try_str(options, "driver");

    if (drvname) {

        drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));

        qdict_del(options, "driver");

    }

    if (!drv) {

        ret = find_image_format(file, filename, &drv, &local_err);

    }

    if (!drv) {

        goto unlink_and_fail;

    }

    /* Open the image */

    ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);

    if (ret < 0) {

        goto unlink_and_fail;

    }

    if (bs->file != file) {

        bdrv_unref(file);

        file = NULL;

    }

    /* If there is a backing file, use it */

    if ((flags & BDRV_O_NO_BACKING) == 0) {

        QDict *backing_options;

        qdict_extract_subqdict(options, &backing_options, "backing.");

        ret = bdrv_open_backing_file(bs, backing_options, &local_err);

        if (ret < 0) {

            goto close_and_fail;

        }

    }

    /* Check if any unknown options were used */

    if (qdict_size(options) != 0) {

        const QDictEntry *entry = qdict_first(options);

        error_setg(errp, "Block format '%s' used by device '%s' doesn't "

                   "support the option '%s'", drv->format_name, bs->device_name,

                   entry->key);

        ret = -EINVAL;

        goto close_and_fail;

    }

    QDECREF(options);

    if (!bdrv_key_required(bs)) {

        bdrv_dev_change_media_cb(bs, true);

    }

    return 0;

unlink_and_fail:

    if (file != NULL) {

        bdrv_unref(file);

    }

    if (bs->is_temporary) {

        unlink(filename);

    }

fail:

    QDECREF(bs->options);

    QDECREF(options);

    bs->options = NULL;

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

    }

    return ret;

close_and_fail:

    bdrv_close(bs);

    QDECREF(options);

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

    }

    return ret;

}