static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, uint8_t *buf, int buf_size){

    HYuvContext *s = avctx->priv_data;

    const int width= s->width;

    const int width2= s->width>>1;

    const int height= s->height;

    int fake_ystride, fake_ustride, fake_vstride;

    AVFrame * const p= &s->picture;

    AVFrame *picture = data;

    *data_size = 0;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    bswap_buf((uint32_t*)s->bitstream_buffer, (uint32_t*)buf, buf_size/4);

    init_get_bits(&s->gb, s->bitstream_buffer, buf_size);

    p->reference= 0;

    if(avctx->get_buffer(avctx, p) < 0){

        fprintf(stderr, "get_buffer() failed\n");

        return -1;

    }

    fake_ystride= s->interlaced ? p->linesize[0]*2  : p->linesize[0];

    fake_ustride= s->interlaced ? p->linesize[1]*2  : p->linesize[1];

    fake_vstride= s->interlaced ? p->linesize[2]*2  : p->linesize[2];

    s->last_slice_end= 0;

    if(s->bitstream_bpp<24){

        int y, cy;

        int lefty, leftu, leftv;

        int lefttopy, lefttopu, lefttopv;

        if(s->yuy2){

            p->data[0][3]= get_bits(&s->gb, 8);

            p->data[0][2]= get_bits(&s->gb, 8);

            p->data[0][1]= get_bits(&s->gb, 8);

            p->data[0][0]= get_bits(&s->gb, 8);

            fprintf(stderr, "YUY2 output isnt implemenetd yet\n");

            return -1;

        }else{

            leftv= p->data[2][0]= get_bits(&s->gb, 8);

            lefty= p->data[0][1]= get_bits(&s->gb, 8);

            leftu= p->data[1][0]= get_bits(&s->gb, 8);

                   p->data[0][0]= get_bits(&s->gb, 8);

            switch(s->predictor){

            case LEFT:

            case PLANE:

                decode_422_bitstream(s, width-2);

                lefty= add_left_prediction(p->data[0] + 2, s->temp[0], width-2, lefty);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    leftu= add_left_prediction(p->data[1] + 1, s->temp[1], width2-1, leftu);

                    leftv= add_left_prediction(p->data[2] + 1, s->temp[2], width2-1, leftv);

                }

                for(cy=y=1; y<s->height; y++,cy++){

                    uint8_t *ydst, *udst, *vdst;

                    if(s->bitstream_bpp==12){

                        decode_gray_bitstream(s, width);

                        ydst= p->data[0] + p->linesize[0]*y;

                        lefty= add_left_prediction(ydst, s->temp[0], width, lefty);

                        if(s->predictor == PLANE){

                            if(y>s->interlaced)

                                s->dsp.add_bytes(ydst, ydst - fake_ystride, width);

                        }

                        y++;

                        if(y>=s->height) break;

                    }

                    draw_slice(s, y);

                    ydst= p->data[0] + p->linesize[0]*y;

                    udst= p->data[1] + p->linesize[1]*cy;

                    vdst= p->data[2] + p->linesize[2]*cy;

                    decode_422_bitstream(s, width);

                    lefty= add_left_prediction(ydst, s->temp[0], width, lefty);

                    if(!(s->flags&CODEC_FLAG_GRAY)){

                        leftu= add_left_prediction(udst, s->temp[1], width2, leftu);

                        leftv= add_left_prediction(vdst, s->temp[2], width2, leftv);

                    }

                    if(s->predictor == PLANE){

                        if(cy>s->interlaced){

                            s->dsp.add_bytes(ydst, ydst - fake_ystride, width);

                            if(!(s->flags&CODEC_FLAG_GRAY)){

                                s->dsp.add_bytes(udst, udst - fake_ustride, width2);

                                s->dsp.add_bytes(vdst, vdst - fake_vstride, width2);

                            }

                        }

                    }

                }

                draw_slice(s, height);

                break;

            case MEDIAN:

                /* first line except first 2 pixels is left predicted */

                decode_422_bitstream(s, width-2);

                lefty= add_left_prediction(p->data[0] + 2, s->temp[0], width-2, lefty);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    leftu= add_left_prediction(p->data[1] + 1, s->temp[1], width2-1, leftu);

                    leftv= add_left_prediction(p->data[2] + 1, s->temp[2], width2-1, leftv);

                }

                cy=y=1;

                /* second line is left predicted for interlaced case */

                if(s->interlaced){

                    decode_422_bitstream(s, width);

                    lefty= add_left_prediction(p->data[0] + p->linesize[0], s->temp[0], width, lefty);

                    if(!(s->flags&CODEC_FLAG_GRAY)){

                        leftu= add_left_prediction(p->data[1] + p->linesize[2], s->temp[1], width2, leftu);

                        leftv= add_left_prediction(p->data[2] + p->linesize[1], s->temp[2], width2, leftv);

                    }

                    y++; cy++;

                }

                /* next 4 pixels are left predicted too */

                decode_422_bitstream(s, 4);

                lefty= add_left_prediction(p->data[0] + fake_ystride, s->temp[0], 4, lefty);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    leftu= add_left_prediction(p->data[1] + fake_ustride, s->temp[1], 2, leftu);

                    leftv= add_left_prediction(p->data[2] + fake_vstride, s->temp[2], 2, leftv);

                }

                /* next line except the first 4 pixels is median predicted */

                lefttopy= p->data[0][3];

                decode_422_bitstream(s, width-4);

                add_median_prediction(p->data[0] + fake_ystride+4, p->data[0]+4, s->temp[0], width-4, &lefty, &lefttopy);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    lefttopu= p->data[1][1];

                    lefttopv= p->data[2][1];

                    add_median_prediction(p->data[1] + fake_ustride+2, p->data[1]+2, s->temp[1], width2-2, &leftu, &lefttopu);

                    add_median_prediction(p->data[2] + fake_vstride+2, p->data[2]+2, s->temp[2], width2-2, &leftv, &lefttopv);

                }

                y++; cy++;

                for(; y<height; y++,cy++){

                    uint8_t *ydst, *udst, *vdst;

                    if(s->bitstream_bpp==12){

                        while(2*cy > y){

                            decode_gray_bitstream(s, width);

                            ydst= p->data[0] + p->linesize[0]*y;

                            add_median_prediction(ydst, ydst - fake_ystride, s->temp[0], width, &lefty, &lefttopy);

                            y++;

                        }

                        if(y>=height) break;

                    }

                    draw_slice(s, y);

                    decode_422_bitstream(s, width);

                    ydst= p->data[0] + p->linesize[0]*y;

                    udst= p->data[1] + p->linesize[1]*cy;

                    vdst= p->data[2] + p->linesize[2]*cy;

                    add_median_prediction(ydst, ydst - fake_ystride, s->temp[0], width, &lefty, &lefttopy);

                    if(!(s->flags&CODEC_FLAG_GRAY)){

                        add_median_prediction(udst, udst - fake_ustride, s->temp[1], width2, &leftu, &lefttopu);

                        add_median_prediction(vdst, vdst - fake_vstride, s->temp[2], width2, &leftv, &lefttopv);

                    }

                }

                draw_slice(s, height);

                break;

            }

        }

    }else{

        int y;

        int leftr, leftg, leftb;

        const int last_line= (height-1)*p->linesize[0];

        if(s->bitstream_bpp==32){

                   p->data[0][last_line+3]= get_bits(&s->gb, 8);

            leftr= p->data[0][last_line+2]= get_bits(&s->gb, 8);

            leftg= p->data[0][last_line+1]= get_bits(&s->gb, 8);

            leftb= p->data[0][last_line+0]= get_bits(&s->gb, 8);

        }else{

            leftr= p->data[0][last_line+2]= get_bits(&s->gb, 8);

            leftg= p->data[0][last_line+1]= get_bits(&s->gb, 8);

            leftb= p->data[0][last_line+0]= get_bits(&s->gb, 8);

            skip_bits(&s->gb, 8);

        }

        if(s->bgr32){

            switch(s->predictor){

            case LEFT:

            case PLANE:

                decode_bgr_bitstream(s, width-1);

                add_left_prediction_bgr32(p->data[0] + last_line+4, s->temp[0], width-1, &leftr, &leftg, &leftb);

                for(y=s->height-2; y>=0; y--){ //yes its stored upside down

                    decode_bgr_bitstream(s, width);

                    add_left_prediction_bgr32(p->data[0] + p->linesize[0]*y, s->temp[0], width, &leftr, &leftg, &leftb);

                    if(s->predictor == PLANE){

                        if((y&s->interlaced)==0){

                            s->dsp.add_bytes(p->data[0] + p->linesize[0]*y,

                                             p->data[0] + p->linesize[0]*y + fake_ystride, fake_ystride);

                        }

                    }

                }

                draw_slice(s, height); // just 1 large slice as this isnt possible in reverse order

                break;

            default:

                fprintf(stderr, "prediction type not supported!\n");

            }

        }else{

            fprintf(stderr, "BGR24 output isnt implemenetd yet\n");

            return -1;

        }

    }

    emms_c();

    *picture= *p;

    avctx->release_buffer(avctx, p);

    *data_size = sizeof(AVFrame);

    return (get_bits_count(&s->gb)+7)>>3;

}


static QemuOpts *opts_parse(QemuOptsList *list, const char *params,
                            int permit_abbrev, bool defaults)
{
    const char *firstname;
    char value[1024], *id = NULL;
    const char *p;
    QemuOpts *opts;
    Error *local_err = NULL;
    assert(!permit_abbrev || list->implied_opt_name);
    firstname = permit_abbrev ? list->implied_opt_name : NULL;
    if (strncmp(params, "id=", 3) == 0) {
        get_opt_value(value, sizeof(value), params+3);
        id = value;
    } else if ((p = strstr(params, ",id=")) != NULL) {
        get_opt_value(value, sizeof(value), p+4);
        id = value;
    }
    opts = qemu_opts_create(list, id, !defaults, &local_err);
    if (opts == NULL) {
        if (error_is_set(&local_err)) {
            qerror_report_err(local_err);
            error_free(local_err);
        }
        return NULL;
    }
    if (opts_do_parse(opts, params, firstname, defaults) != 0) {
        qemu_opts_del(opts);
        return NULL;
    }
    return opts;
}


static int get_bool(QEMUFile *f, void *pv, size_t size)

{

    bool *v = pv;

    *v = qemu_get_byte(f);

    return 0;

}


int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
                                              AVFrame *frame,
                                              int *got_frame_ptr,
                                              AVPacket *avpkt)
{
    int planar, channels;
    int ret = 0;
    *got_frame_ptr = 0;
    avctx->pkt = avpkt;
    if (!avpkt->data && avpkt->size) {
        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
        return AVERROR(EINVAL);
    }
    apply_param_change(avctx, avpkt);
    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
        ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);
        if (ret >= 0 && *got_frame_ptr) {
            avctx->frame_number++;
            frame->pkt_dts = avpkt->dts;
            if (frame->format == AV_SAMPLE_FMT_NONE)
                frame->format = avctx->sample_fmt;
        }
    }
    /* many decoders assign whole AVFrames, thus overwriting extended_data;
     * make sure it's set correctly; assume decoders that actually use
     * extended_data are doing it correctly */
    planar   = av_sample_fmt_is_planar(frame->format);
    channels = av_get_channel_layout_nb_channels(frame->channel_layout);
    if (!(planar && channels > AV_NUM_DATA_POINTERS))
        frame->extended_data = frame->data;
    return ret;
}


int ff_j2k_init_component(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty, Jpeg2000QuantStyle *qntsty, int cbps, int dx, int dy)

{

    int reslevelno, bandno, gbandno = 0, ret, i, j, csize = 1;

    if (ret=ff_j2k_dwt_init(&comp->dwt, comp->coord, codsty->nreslevels-1, codsty->transform))

        return ret;

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

        csize *= comp->coord[i][1] - comp->coord[i][0];

    comp->data = av_malloc(csize * sizeof(int));

    if (!comp->data)

        return AVERROR(ENOMEM);

    comp->reslevel = av_malloc(codsty->nreslevels * sizeof(Jpeg2000ResLevel));

    if (!comp->reslevel)

        return AVERROR(ENOMEM);

    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {

        int declvl = codsty->nreslevels - reslevelno;

        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

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

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

                reslevel->coord[i][j] =

                    ff_jpeg2000_ceildivpow2(comp->coord[i][j], declvl - 1);

        if (reslevelno == 0)

            reslevel->nbands = 1;

        else

            reslevel->nbands = 3;

        if (reslevel->coord[0][1] == reslevel->coord[0][0])

            reslevel->num_precincts_x = 0;

        else

            reslevel->num_precincts_x = ff_jpeg2000_ceildivpow2(reslevel->coord[0][1], codsty->log2_prec_width)

                                        - (reslevel->coord[0][0] >> codsty->log2_prec_width);

        if (reslevel->coord[1][1] == reslevel->coord[1][0])

            reslevel->num_precincts_y = 0;

        else

            reslevel->num_precincts_y = ff_jpeg2000_ceildivpow2(reslevel->coord[1][1], codsty->log2_prec_height)

                                        - (reslevel->coord[1][0] >> codsty->log2_prec_height);

        reslevel->band = av_malloc(reslevel->nbands * sizeof(Jpeg2000Band));

        if (!reslevel->band)

            return AVERROR(ENOMEM);

        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {

            Jpeg2000Band *band = reslevel->band + bandno;

            int cblkno, precx, precy, precno;

            int x0, y0, x1, y1;

            int xi0, yi0, xi1, yi1;

            int cblkperprecw, cblkperprech;

            if (qntsty->quantsty != JPEG2000_QSTY_NONE) {

                static const uint8_t lut_gain[2][4] = {{0, 0, 0, 0}, {0, 1, 1, 2}};

                int numbps;

                numbps = cbps + lut_gain[codsty->transform][bandno + reslevelno>0];

                band->stepsize = SHL(2048 + qntsty->mant[gbandno], 2 + numbps - qntsty->expn[gbandno]);

            } else

                band->stepsize = 1 << 13;

            if (reslevelno == 0) {  // the same everywhere

                band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width-1);

                band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height-1);

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

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

                        band->coord[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], declvl-1);

            } else{

                band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width);

                band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height);

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

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

                        band->coord[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j] - (((bandno+1>>i)&1) << declvl-1), declvl);

            }

            band->cblknx = ff_jpeg2000_ceildiv(band->coord[0][1], band->codeblock_width)  - band->coord[0][0] / band->codeblock_width;

            band->cblkny = ff_jpeg2000_ceildiv(band->coord[1][1], band->codeblock_height) - band->coord[1][0] / band->codeblock_height;

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

                band->coord[0][j] = ff_jpeg2000_ceildiv(band->coord[0][j], dx);

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

                band->coord[1][j] = ff_jpeg2000_ceildiv(band->coord[1][j], dy);

            band->cblknx = ff_jpeg2000_ceildiv(band->cblknx, dx);

            band->cblkny = ff_jpeg2000_ceildiv(band->cblkny, dy);

            band->cblk = av_malloc(sizeof(Jpeg2000Cblk) * band->cblknx * band->cblkny);

            if (!band->cblk)

                return AVERROR(ENOMEM);

            band->prec = av_malloc(sizeof(Jpeg2000Cblk) * reslevel->num_precincts_x * reslevel->num_precincts_y);

            if (!band->prec)

                return AVERROR(ENOMEM);

            for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++) {

                Jpeg2000Cblk *cblk = band->cblk + cblkno;

                cblk->zero = 0;

                cblk->lblock = 3;

                cblk->length = 0;

                cblk->lengthinc = 0;

                cblk->npasses = 0;

            }

            y0 = band->coord[1][0];

            y1 = ((band->coord[1][0] + (1<<codsty->log2_prec_height)) & ~((1<<codsty->log2_prec_height)-1)) - y0;

            yi0 = 0;

            yi1 = ff_jpeg2000_ceildivpow2(y1 - y0, codsty->log2_cblk_height) << codsty->log2_cblk_height;

            yi1 = FFMIN(yi1, band->cblkny);

            cblkperprech = 1<<(codsty->log2_prec_height - codsty->log2_cblk_height);

            for (precy = 0, precno = 0; precy < reslevel->num_precincts_y; precy++) {

                for (precx = 0; precx < reslevel->num_precincts_x; precx++, precno++) {

                    band->prec[precno].yi0 = yi0;

                    band->prec[precno].yi1 = yi1;

                }

                yi1 += cblkperprech;

                yi0 = yi1 - cblkperprech;

                yi1 = FFMIN(yi1, band->cblkny);

            }

            x0 = band->coord[0][0];

            x1 = ((band->coord[0][0] + (1<<codsty->log2_prec_width)) & ~((1<<codsty->log2_prec_width)-1)) - x0;

            xi0 = 0;

            xi1 = ff_jpeg2000_ceildivpow2(x1 - x0, codsty->log2_cblk_width) << codsty->log2_cblk_width;

            xi1 = FFMIN(xi1, band->cblknx);

            cblkperprecw = 1<<(codsty->log2_prec_width - codsty->log2_cblk_width);

            for (precx = 0, precno = 0; precx < reslevel->num_precincts_x; precx++) {

                for (precy = 0; precy < reslevel->num_precincts_y; precy++, precno = 0) {

                    Jpeg2000Prec *prec = band->prec + precno;

                    prec->xi0 = xi0;

                    prec->xi1 = xi1;

                    prec->cblkincl = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0,

                                                          prec->yi1 - prec->yi0);

                    prec->zerobits = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0,

                                                          prec->yi1 - prec->yi0);

                    if (!prec->cblkincl || !prec->zerobits)

                        return AVERROR(ENOMEM);

                }

                xi1 += cblkperprecw;

                xi0 = xi1 - cblkperprecw;

                xi1 = FFMIN(xi1, band->cblknx);

            }

        }

    }

    return 0;

}


static int disas_cp_insn(CPUState *env, DisasContext *s, uint32_t insn)

{

    TCGv tmp, tmp2;

    uint32_t rd = (insn >> 12) & 0xf;

    uint32_t cp = (insn >> 8) & 0xf;

    if (IS_USER(s)) {

        return 1;

    }

    if (insn & ARM_CP_RW_BIT) {

        if (!env->cp[cp].cp_read)

            return 1;

        gen_set_pc_im(s->pc);

        tmp = new_tmp();

        tmp2 = tcg_const_i32(insn);

        gen_helper_get_cp(tmp, cpu_env, tmp2);

        tcg_temp_free(tmp2);

        store_reg(s, rd, tmp);

    } else {

        if (!env->cp[cp].cp_write)

            return 1;

        gen_set_pc_im(s->pc);

        tmp = load_reg(s, rd);

        tmp2 = tcg_const_i32(insn);

        gen_helper_set_cp(cpu_env, tmp2, tmp);

        tcg_temp_free(tmp2);

        dead_tmp(tmp);

    }

    return 0;

}


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

{

    AVStream *st;

    int len, ret, i;

    av_init_packet(pkt);

    for(;;) {

        /* select current input stream component */

        st = s->cur_st;

        if (st) {

            if (!st->need_parsing || !st->parser) {

                /* no parsing needed: we just output the packet as is */

                /* raw data support */

                *pkt = st->cur_pkt; st->cur_pkt.data= NULL;

                compute_pkt_fields(s, st, NULL, pkt);

                s->cur_st = NULL;

                if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&

                    (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {

                    ff_reduce_index(s, st->index);

                    av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);

                }

                break;

            } else if (st->cur_len > 0 && st->discard < AVDISCARD_ALL) {

                len = av_parser_parse2(st->parser, st->codec, &pkt->data, &pkt->size,

                                       st->cur_ptr, st->cur_len,

                                       st->cur_pkt.pts, st->cur_pkt.dts,

                                       st->cur_pkt.pos);

                st->cur_pkt.pts = AV_NOPTS_VALUE;

                st->cur_pkt.dts = AV_NOPTS_VALUE;

                /* increment read pointer */

                st->cur_ptr += len;

                st->cur_len -= len;

                /* return packet if any */

                if (pkt->size) {

                got_packet:

                    pkt->duration = 0;

                    pkt->stream_index = st->index;

                    pkt->pts = st->parser->pts;

                    pkt->dts = st->parser->dts;

                    pkt->pos = st->parser->pos;

                    if(pkt->data == st->cur_pkt.data && pkt->size == st->cur_pkt.size){

                        s->cur_st = NULL;

                        pkt->destruct= st->cur_pkt.destruct;

                        st->cur_pkt.destruct= NULL;

                        st->cur_pkt.data    = NULL;

                        assert(st->cur_len == 0);

                    }else{

                        pkt->destruct = NULL;

                    }

                    compute_pkt_fields(s, st, st->parser, pkt);

                    if((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY){

                        int64_t pos= (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->pos : st->parser->frame_offset;

                        ff_reduce_index(s, st->index);

                        av_add_index_entry(st, pos, pkt->dts,

                                           0, 0, AVINDEX_KEYFRAME);

                    }

                    break;

                }

            } else {

                /* free packet */

                av_free_packet(&st->cur_pkt);

                s->cur_st = NULL;

            }

        } else {

            AVPacket cur_pkt;

            /* read next packet */

            ret = av_read_packet(s, &cur_pkt);

            if (ret < 0) {

                if (ret == AVERROR(EAGAIN))

                    return ret;

                /* return the last frames, if any */

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

                    st = s->streams[i];

                    if (st->parser && st->need_parsing) {

                        av_parser_parse2(st->parser, st->codec,

                                        &pkt->data, &pkt->size,

                                        NULL, 0,

                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE,

                                        AV_NOPTS_VALUE);

                        if (pkt->size)

                            goto got_packet;

                    }

                }

                /* no more packets: really terminate parsing */

                return ret;

            }

            st = s->streams[cur_pkt.stream_index];

            st->cur_pkt= cur_pkt;

            if(st->cur_pkt.pts != AV_NOPTS_VALUE &&

               st->cur_pkt.dts != AV_NOPTS_VALUE &&

               st->cur_pkt.pts < st->cur_pkt.dts){

                av_log(s, AV_LOG_WARNING, "Invalid timestamps stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d\n",

                    st->cur_pkt.stream_index,

                    st->cur_pkt.pts,

                    st->cur_pkt.dts,

                    st->cur_pkt.size);

//                av_free_packet(&st->cur_pkt);

//                return -1;

            }

            if(s->debug & FF_FDEBUG_TS)

                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",

                    st->cur_pkt.stream_index,

                    st->cur_pkt.pts,

                    st->cur_pkt.dts,

                    st->cur_pkt.size,

                    st->cur_pkt.duration,

                    st->cur_pkt.flags);

            s->cur_st = st;

            st->cur_ptr = st->cur_pkt.data;

            st->cur_len = st->cur_pkt.size;

            if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {

                st->parser = av_parser_init(st->codec->codec_id);

                if (!st->parser) {

                    av_log(s, AV_LOG_WARNING, "parser not found for codec "

                           "%s, packets or times may be invalid.\n",

                           avcodec_get_name(st->codec->codec_id));

                    /* no parser available: just output the raw packets */

                    st->need_parsing = AVSTREAM_PARSE_NONE;

                }else if(st->need_parsing == AVSTREAM_PARSE_HEADERS){

                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;

                }else if(st->need_parsing == AVSTREAM_PARSE_FULL_ONCE){

                    st->parser->flags |= PARSER_FLAG_ONCE;

                }

            }

        }

    }

    if(s->debug & FF_FDEBUG_TS)

        av_log(s, AV_LOG_DEBUG, "read_frame_internal stream=%d, pts=%"PRId64", dts=%"PRId64", size=%d, duration=%d, flags=%d\n",

            pkt->stream_index,

            pkt->pts,

            pkt->dts,

            pkt->size,

            pkt->duration,

            pkt->flags);

    return 0;

}


void qemu_co_rwlock_unlock(CoRwlock *lock)
{
    assert(qemu_in_coroutine());
    if (lock->writer) {
        lock->writer = false;
        qemu_co_queue_restart_all(&lock->queue);
    } else {
        lock->reader--;
        assert(lock->reader >= 0);
        /* Wakeup only one waiting writer */
        if (!lock->reader) {
            qemu_co_queue_next(&lock->queue);
        }
    }
}


void ide_atapi_cmd_reply_end(IDEState *s)

{

    int byte_count_limit, size, ret;

#ifdef DEBUG_IDE_ATAPI

    printf("reply: tx_size=%d elem_tx_size=%d index=%d\n",

           s->packet_transfer_size,

           s->elementary_transfer_size,

           s->io_buffer_index);

#endif

    if (s->packet_transfer_size <= 0) {

        /* end of transfer */

        ide_atapi_cmd_ok(s);

        ide_set_irq(s->bus);

#ifdef DEBUG_IDE_ATAPI

        printf("status=0x%x\n", s->status);

#endif

    } else {

        /* see if a new sector must be read */

        if (s->lba != -1 && s->io_buffer_index >= s->cd_sector_size) {

            ret = cd_read_sector(s, s->lba, s->io_buffer, s->cd_sector_size);

            if (ret < 0) {

                ide_atapi_io_error(s, ret);

                return;

            }

            s->lba++;

            s->io_buffer_index = 0;

        }

        if (s->elementary_transfer_size > 0) {

            /* there are some data left to transmit in this elementary

               transfer */

            size = s->cd_sector_size - s->io_buffer_index;

            if (size > s->elementary_transfer_size)

                size = s->elementary_transfer_size;

            s->packet_transfer_size -= size;

            s->elementary_transfer_size -= size;

            s->io_buffer_index += size;

            ide_transfer_start(s, s->io_buffer + s->io_buffer_index - size,

                               size, ide_atapi_cmd_reply_end);

        } else {

            /* a new transfer is needed */

            s->nsector = (s->nsector & ~7) | ATAPI_INT_REASON_IO;

            byte_count_limit = atapi_byte_count_limit(s);

#ifdef DEBUG_IDE_ATAPI

            printf("byte_count_limit=%d\n", byte_count_limit);

#endif

            size = s->packet_transfer_size;

            if (size > byte_count_limit) {

                /* byte count limit must be even if this case */

                if (byte_count_limit & 1)

                    byte_count_limit--;

                size = byte_count_limit;

            }

            s->lcyl = size;

            s->hcyl = size >> 8;

            s->elementary_transfer_size = size;

            /* we cannot transmit more than one sector at a time */

            if (s->lba != -1) {

                if (size > (s->cd_sector_size - s->io_buffer_index))

                    size = (s->cd_sector_size - s->io_buffer_index);

            }

            s->packet_transfer_size -= size;

            s->elementary_transfer_size -= size;

            s->io_buffer_index += size;

            ide_transfer_start(s, s->io_buffer + s->io_buffer_index - size,

                               size, ide_atapi_cmd_reply_end);

            ide_set_irq(s->bus);

#ifdef DEBUG_IDE_ATAPI

            printf("status=0x%x\n", s->status);

#endif

        }

    }

}


static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,

                              unsigned int substr, unsigned int channel,

                              unsigned int filter)

{

    SubStream *s = &m->substream[substr];

    FilterParams *fp = &s->channel_params[channel].filter_params[filter];

    const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;

    const char fchar = filter ? 'I' : 'F';

    int i, order;

    // Filter is 0 for FIR, 1 for IIR.

    av_assert0(filter < 2);

    if (m->filter_changed[channel][filter]++ > 1) {

        av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");

        return AVERROR_INVALIDDATA;

    }

    order = get_bits(gbp, 4);

    if (order > max_order) {

        av_log(m->avctx, AV_LOG_ERROR,

               "%cIR filter order %d is greater than maximum %d.\n",

               fchar, order, max_order);

        return AVERROR_INVALIDDATA;

    }

    fp->order = order;

    if (order > 0) {

        int32_t *fcoeff = s->channel_params[channel].coeff[filter];

        int coeff_bits, coeff_shift;

        fp->shift = get_bits(gbp, 4);

        coeff_bits  = get_bits(gbp, 5);

        coeff_shift = get_bits(gbp, 3);

        if (coeff_bits < 1 || coeff_bits > 16) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "%cIR filter coeff_bits must be between 1 and 16.\n",

                   fchar);

            return AVERROR_INVALIDDATA;

        }

        if (coeff_bits + coeff_shift > 16) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",

                   fchar);

            return AVERROR_INVALIDDATA;

        }

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

            fcoeff[i] = get_sbits(gbp, coeff_bits) * (1 << coeff_shift);

        if (get_bits1(gbp)) {

            int state_bits, state_shift;

            if (filter == FIR) {

                av_log(m->avctx, AV_LOG_ERROR,

                       "FIR filter has state data specified.\n");

                return AVERROR_INVALIDDATA;

            }

            state_bits  = get_bits(gbp, 4);

            state_shift = get_bits(gbp, 4);

            /* TODO: Check validity of state data. */

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

                fp->state[i] = state_bits ? get_sbits(gbp, state_bits) << state_shift : 0;

        }

    }

    return 0;

}


static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)

{

    IlContext *il = inlink->dst->priv;

    AVFilterLink *outlink = inlink->dst->outputs[0];

    AVFilterBufferRef *out;

    int ret;

    out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);

    if (!out) {

        avfilter_unref_bufferp(&inpicref);

        return AVERROR(ENOMEM);

    }

    avfilter_copy_buffer_ref_props(out, inpicref);

    interleave(out->data[0], inpicref->data[0],

               il->width, inlink->h,

               out->linesize[0], inpicref->linesize[0],

               il->luma_mode, il->luma_swap);

    if (il->nb_planes > 2) {

        interleave(out->data[1], inpicref->data[1],

                   il->chroma_width, il->chroma_height,

                   out->linesize[1], inpicref->linesize[1],

                   il->chroma_mode, il->chroma_swap);

        interleave(out->data[2], inpicref->data[2],

                   il->chroma_width, il->chroma_height,

                   out->linesize[2], inpicref->linesize[2],

                   il->chroma_mode, il->chroma_swap);

    }

    if (il->nb_planes == 2 && il->nb_planes == 4) {

        int comp = il->nb_planes - 1;

        interleave(out->data[comp], inpicref->data[comp],

                   il->width, inlink->h,

                   out->linesize[comp], inpicref->linesize[comp],

                   il->alpha_mode, il->alpha_swap);

    }

    ret = ff_filter_frame(outlink, out);

    avfilter_unref_bufferp(&inpicref);

    return ret;

}


decode_lpc(WmallDecodeCtx *s)

{

    int ch, i, cbits;

    s->lpc_order = get_bits(&s->gb, 5) + 1;

    s->lpc_scaling = get_bits(&s->gb, 4);

    s->lpc_intbits = get_bits(&s->gb, 3) + 1;

    cbits = s->lpc_scaling + s->lpc_intbits;

    for(ch = 0; ch < s->num_channels; ch++) {

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

	    s->lpc_coefs[ch][i] = get_sbits(&s->gb, cbits);

	}

    }

}


static double get_scene_score(AVFilterContext *ctx, AVFrame *crnt, AVFrame *next)

{

    FrameRateContext *s = ctx->priv;

    double ret = 0;

    ff_dlog(ctx, "get_scene_score()\n");

    if (crnt->height == next->height &&

        crnt->width  == next->width) {

        int64_t sad;

        double mafd, diff;

        ff_dlog(ctx, "get_scene_score() process\n");

        if (s->bitdepth == 8)

            sad = scene_sad8(s, crnt->data[0], crnt->linesize[0], next->data[0], next->linesize[0], crnt->height);

        else

            sad = scene_sad16(s, (const uint16_t*)crnt->data[0], crnt->linesize[0] >> 1, (const uint16_t*)next->data[0], next->linesize[0] >> 1, crnt->height);

        mafd = (double)sad * 100.0 / (crnt->height * crnt->width) / (1 << s->bitdepth);

        diff = fabs(mafd - s->prev_mafd);

        ret  = av_clipf(FFMIN(mafd, diff), 0, 100.0);

        s->prev_mafd = mafd;

    }

    ff_dlog(ctx, "get_scene_score() result is:%f\n", ret);

    return ret;

}


int main(int argc,char* argv[]){

    int i, j;

    uint64_t sse=0;

    uint64_t dev;

    FILE *f[2];

    uint8_t buf[2][SIZE];

    uint64_t psnr;

    int len= argc<4 ? 1 : atoi(argv[3]);

    int64_t max= (1<<(8*len))-1;

    int shift= argc<5 ? 0 : atoi(argv[4]);

    int skip_bytes = argc<6 ? 0 : atoi(argv[5]);

    if(argc<3){

        printf("tiny_psnr <file1> <file2> [<elem size> [<shift> [<skip bytes>]]]\n");

        printf("For WAV files use the following:\n");

        printf("./tiny_psnr file1.wav file2.wav 2 0 44 to skip the header.\n");

        return -1;

    }

    f[0]= fopen(argv[1], "rb");

    f[1]= fopen(argv[2], "rb");

    if(!f[0] || !f[1]){

        fprintf(stderr, "Could not open input files.\n");

        return -1;

    }

    fseek(f[shift<0], shift < 0 ? -shift : shift, SEEK_SET);

    fseek(f[0],skip_bytes,SEEK_CUR);

    fseek(f[1],skip_bytes,SEEK_CUR);

    for(i=0;;){

        if( fread(buf[0], SIZE, 1, f[0]) != 1) break;

        if( fread(buf[1], SIZE, 1, f[1]) != 1) break;

        for(j=0; j<SIZE; i++,j++){

            int64_t a= buf[0][j];

            int64_t b= buf[1][j];

            if(len==2){

                a= (int16_t)(a | (buf[0][++j]<<8));

                b= (int16_t)(b | (buf[1][  j]<<8));

            }

            sse += (a-b) * (a-b);

        }

    }

    if(!i) i=1;

    dev= int_sqrt( ((sse/i)*F*F) + (((sse%i)*F*F) + i/2)/i );

    if(sse)

        psnr= ((2*log16(max<<16) + log16(i) - log16(sse))*284619LL*F + (1<<31)) / (1LL<<32);

    else

        psnr= 100*F-1; //floating point free infinity :)

    printf("stddev:%3d.%02d PSNR:%2d.%02d bytes:%d\n",

        (int)(dev/F), (int)(dev%F),

        (int)(psnr/F), (int)(psnr%F),

        i*len);

    return 0;

}


StrongARMState *sa1110_init(MemoryRegion *sysmem,

                            unsigned int sdram_size, const char *rev)

{

    StrongARMState *s;

    int i;

    s = g_new0(StrongARMState, 1);

    if (!rev) {

        rev = "sa1110-b5";

    }

    if (strncmp(rev, "sa1110", 6)) {

        error_report("Machine requires a SA1110 processor.");

        exit(1);

    }

    s->cpu = ARM_CPU(cpu_generic_init(TYPE_ARM_CPU, rev));

    if (!s->cpu) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    memory_region_allocate_system_memory(&s->sdram, NULL, "strongarm.sdram",

                                         sdram_size);

    memory_region_add_subregion(sysmem, SA_SDCS0, &s->sdram);

    s->pic = sysbus_create_varargs("strongarm_pic", 0x90050000,

                    qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_IRQ),

                    qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_FIQ),

                    NULL);

    sysbus_create_varargs("pxa25x-timer", 0x90000000,

                    qdev_get_gpio_in(s->pic, SA_PIC_OSTC0),

                    qdev_get_gpio_in(s->pic, SA_PIC_OSTC1),

                    qdev_get_gpio_in(s->pic, SA_PIC_OSTC2),

                    qdev_get_gpio_in(s->pic, SA_PIC_OSTC3),

                    NULL);

    sysbus_create_simple(TYPE_STRONGARM_RTC, 0x90010000,

                    qdev_get_gpio_in(s->pic, SA_PIC_RTC_ALARM));

    s->gpio = strongarm_gpio_init(0x90040000, s->pic);

    s->ppc = sysbus_create_varargs(TYPE_STRONGARM_PPC, 0x90060000, NULL);

    for (i = 0; sa_serial[i].io_base; i++) {

        DeviceState *dev = qdev_create(NULL, TYPE_STRONGARM_UART);

        qdev_prop_set_chr(dev, "chardev", serial_hds[i]);

        qdev_init_nofail(dev);

        sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0,

                sa_serial[i].io_base);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,

                qdev_get_gpio_in(s->pic, sa_serial[i].irq));

    }

    s->ssp = sysbus_create_varargs(TYPE_STRONGARM_SSP, 0x80070000,

                qdev_get_gpio_in(s->pic, SA_PIC_SSP), NULL);

    s->ssp_bus = (SSIBus *)qdev_get_child_bus(s->ssp, "ssi");

    return s;

}


static int celt_header(AVFormatContext *s, int idx)

{

    struct ogg *ogg = s->priv_data;

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

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

    struct oggcelt_private *priv = os->private;

    uint8_t *p = os->buf + os->pstart;

    if (os->psize == 60 &&

        !memcmp(p, ff_celt_codec.magic, ff_celt_codec.magicsize)) {

        /* Main header */

        uint32_t version, sample_rate, nb_channels;

        uint32_t overlap, extra_headers;

        priv = av_malloc(sizeof(struct oggcelt_private));

        if (!priv)

            return AVERROR(ENOMEM);

        if (ff_alloc_extradata(st->codecpar, 2 * sizeof(uint32_t)) < 0) {

            av_free(priv);

            return AVERROR(ENOMEM);

        }

        version          = AV_RL32(p + 28);

        /* unused header size field skipped */

        sample_rate      = AV_RL32(p + 36);

        nb_channels      = AV_RL32(p + 40);

        overlap          = AV_RL32(p + 48);

        /* unused bytes per packet field skipped */

        extra_headers    = AV_RL32(p + 56);

        st->codecpar->codec_type     = AVMEDIA_TYPE_AUDIO;

        st->codecpar->codec_id       = AV_CODEC_ID_CELT;

        st->codecpar->sample_rate    = sample_rate;

        st->codecpar->channels       = nb_channels;

        if (sample_rate)

            avpriv_set_pts_info(st, 64, 1, sample_rate);

        priv->extra_headers_left  = 1 + extra_headers;

        av_free(os->private);

        os->private = priv;

        AV_WL32(st->codecpar->extradata + 0, overlap);

        AV_WL32(st->codecpar->extradata + 4, version);

        return 1;

    } else if (priv && priv->extra_headers_left) {

        /* Extra headers (vorbiscomment) */

        ff_vorbis_stream_comment(s, st, p, os->psize);

        priv->extra_headers_left--;

        return 1;

    } else {

        return 0;

    }

}


static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,

                                      int flags, int send)

{

    abi_long ret, len;

    struct msghdr msg;

    int count;

    struct iovec *vec;

    abi_ulong target_vec;

    if (msgp->msg_name) {

        msg.msg_namelen = tswap32(msgp->msg_namelen);

        msg.msg_name = alloca(msg.msg_namelen+1);

        ret = target_to_host_sockaddr(fd, msg.msg_name,

                                      tswapal(msgp->msg_name),

                                      msg.msg_namelen);

        if (ret) {

            goto out2;

        }

    } else {

        msg.msg_name = NULL;

        msg.msg_namelen = 0;

    }

    msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);

    msg.msg_control = alloca(msg.msg_controllen);

    msg.msg_flags = tswap32(msgp->msg_flags);

    count = tswapal(msgp->msg_iovlen);

    target_vec = tswapal(msgp->msg_iov);

    vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,

                     target_vec, count, send);

    if (vec == NULL) {

        ret = -host_to_target_errno(errno);

        goto out2;

    }

    msg.msg_iovlen = count;

    msg.msg_iov = vec;

    if (send) {

        if (fd_trans_target_to_host_data(fd)) {

            ret = fd_trans_target_to_host_data(fd)(msg.msg_iov->iov_base,

                                                   msg.msg_iov->iov_len);

        } else {

            ret = target_to_host_cmsg(&msg, msgp);

        }

        if (ret == 0) {

            ret = get_errno(safe_sendmsg(fd, &msg, flags));

        }

    } else {

        ret = get_errno(safe_recvmsg(fd, &msg, flags));

        if (!is_error(ret)) {

            len = ret;

            if (fd_trans_host_to_target_data(fd)) {

                ret = fd_trans_host_to_target_data(fd)(msg.msg_iov->iov_base,

                                                       len);

            } else {

                ret = host_to_target_cmsg(msgp, &msg);

            }

            if (!is_error(ret)) {

                msgp->msg_namelen = tswap32(msg.msg_namelen);

                if (msg.msg_name != NULL) {

                    ret = host_to_target_sockaddr(tswapal(msgp->msg_name),

                                    msg.msg_name, msg.msg_namelen);

                    if (ret) {

                        goto out;

                    }

                }

                ret = len;

            }

        }

    }

out:

    unlock_iovec(vec, target_vec, count, !send);

out2:

    return ret;

}


static int decode_group3_1d_line(AVCodecContext *avctx, GetBitContext *gb,

                                 int pix_left, int *runs)

{

    int mode = 0, run = 0;

    unsigned int t;

    for(;;){

        t = get_vlc2(gb, ccitt_vlc[mode].table, 9, 2);

        run += t;

        if(t < 64){

            pix_left -= run;

            *runs++ = run;

            if(pix_left <= 0){

                if(!pix_left)

                    break;

                runs[-1] = 0;

                av_log(avctx, AV_LOG_ERROR, "Run went out of bounds\n");

                return -1;

            }

            run = 0;

            mode = !mode;

        }else if((int)t == -1){

            av_log(avctx, AV_LOG_ERROR, "Incorrect code\n");

            return -1;

        }

    }

    *runs++ = 0;

    return 0;

}


static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)

{

    int i, x;

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

        return AVERROR(EINVAL);

    x = bytestream_get_byte(&s->buf); // Sqcd

    q->nguardbits = x >> 5;

    q->quantsty   = x & 0x1f;

    if (q->quantsty == JPEG2000_QSTY_NONE) {

        n -= 3;

        if (s->buf_end - s->buf < n || 32*3 < n)

            return AVERROR(EINVAL);

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

            q->expn[i] = bytestream_get_byte(&s->buf) >> 3;

    } else if (q->quantsty == JPEG2000_QSTY_SI) {

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

            return AVERROR(EINVAL);

        x          = bytestream_get_be16(&s->buf);

        q->expn[0] = x >> 11;

        q->mant[0] = x & 0x7ff;

        for (i = 1; i < 32 * 3; i++) {

            int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);

            q->expn[i] = curexpn;

            q->mant[i] = q->mant[0];

        }

    } else {

        n = (n - 3) >> 1;

        if (s->buf_end - s->buf < 2 * n || 32*3 < n)

            return AVERROR(EINVAL);

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

            x          = bytestream_get_be16(&s->buf);

            q->expn[i] = x >> 11;

            q->mant[i] = x & 0x7ff;

        }

    }

    return 0;

}


void do_compare_and_swap32(void *cpu_env, int num)

{

#ifdef TARGET_I386

    uint32_t old = ((CPUX86State*)cpu_env)->regs[R_EAX];

    uint32_t *value = (uint32_t*)((CPUX86State*)cpu_env)->regs[R_ECX];

    DPRINTF("commpage: compare_and_swap32(%x,new,%p)\n", old, value);

    if(value && old == tswap32(*value))

    {

        uint32_t new = ((CPUX86State*)cpu_env)->regs[R_EDX];

        *value = tswap32(new);

        /* set zf flag */

        ((CPUX86State*)cpu_env)->eflags |= 0x40;

    }

    else

    {

        ((CPUX86State*)cpu_env)->regs[R_EAX] = tswap32(*value);

        /* unset zf flag */

        ((CPUX86State*)cpu_env)->eflags &= ~0x40;

    }

#else

    qerror("do_compare_and_swap32 unimplemented");

#endif

}


static void ready_residue(vorbis_enc_residue *rc, vorbis_enc_context *venc)

{

    int i;

    assert(rc->type == 2);

    rc->maxes = av_mallocz(sizeof(float[2]) * rc->classifications);

    for (i = 0; i < rc->classifications; i++) {

        int j;

        vorbis_enc_codebook * cb;

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

            if (rc->books[i][j] != -1)

                break;

        if (j == 8) // zero

            continue;

        cb = &venc->codebooks[rc->books[i][j]];

        assert(cb->ndimentions >= 2);

        assert(cb->lookup);

        for (j = 0; j < cb->nentries; j++) {

            float a;

            if (!cb->lens[j])

                continue;

            a = fabs(cb->dimentions[j * cb->ndimentions]);

            if (a > rc->maxes[i][0])

                rc->maxes[i][0] = a;

            a = fabs(cb->dimentions[j * cb->ndimentions + 1]);

            if (a > rc->maxes[i][1])

                rc->maxes[i][1] = a;

        }

    }

    // small bias

    for (i = 0; i < rc->classifications; i++) {

        rc->maxes[i][0] += 0.8;

        rc->maxes[i][1] += 0.8;

    }

}


BlockDriverState *bdrv_all_find_vmstate_bs(void)

{

    bool not_found = true;

    BlockDriverState *bs;

    BdrvNextIterator *it = NULL;

    while (not_found && (it = bdrv_next(it, &bs))) {

        AioContext *ctx = bdrv_get_aio_context(bs);

        aio_context_acquire(ctx);

        not_found = !bdrv_can_snapshot(bs);

        aio_context_release(ctx);

    }

    return bs;

}


static av_cold int initFilter(int16_t **outFilter, int32_t **filterPos,

                              int *outFilterSize, int xInc, int srcW,

                              int dstW, int filterAlign, int one,

                              int flags, int cpu_flags,

                              SwsVector *srcFilter, SwsVector *dstFilter,

                              double param[2], int is_horizontal)

{

    int i;

    int filterSize;

    int filter2Size;

    int minFilterSize;

    int64_t *filter    = NULL;

    int64_t *filter2   = NULL;

    const int64_t fone = 1LL << 54;

    int ret            = -1;

    emms_c(); // FIXME should not be required but IS (even for non-MMX versions)

    // NOTE: the +3 is for the MMX(+1) / SSE(+3) scaler which reads over the end

    FF_ALLOC_OR_GOTO(NULL, *filterPos, (dstW + 3) * sizeof(**filterPos), fail);

    if (FFABS(xInc - 0x10000) < 10) { // unscaled

        int i;

        filterSize = 1;

        FF_ALLOCZ_OR_GOTO(NULL, filter,

                          dstW * sizeof(*filter) * filterSize, fail);

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

            filter[i * filterSize] = fone;

            (*filterPos)[i]        = i;

        }

    } else if (flags & SWS_POINT) { // lame looking point sampling mode

        int i;

        int xDstInSrc;

        filterSize = 1;

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc / 2 - 0x8000;

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            (*filterPos)[i] = xx;

            filter[i]       = fone;

            xDstInSrc      += xInc;

        }

    } else if ((xInc <= (1 << 16) && (flags & SWS_AREA)) ||

               (flags & SWS_FAST_BILINEAR)) { // bilinear upscale

        int i;

        int xDstInSrc;

        filterSize = 2;

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc / 2 - 0x8000;

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            int j;

            (*filterPos)[i] = xx;

            // bilinear upscale / linear interpolate / area averaging

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

                int64_t coeff = fone - FFABS((xx << 16) - xDstInSrc) *

                                (fone >> 16);

                if (coeff < 0)

                    coeff = 0;

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += xInc;

        }

    } else {

        int64_t xDstInSrc;

        int sizeFactor;

        if (flags & SWS_BICUBIC)

            sizeFactor = 4;

        else if (flags & SWS_X)

            sizeFactor = 8;

        else if (flags & SWS_AREA)

            sizeFactor = 1;     // downscale only, for upscale it is bilinear

        else if (flags & SWS_GAUSS)

            sizeFactor = 8;     // infinite ;)

        else if (flags & SWS_LANCZOS)

            sizeFactor = param[0] != SWS_PARAM_DEFAULT ? ceil(2 * param[0]) : 6;

        else if (flags & SWS_SINC)

            sizeFactor = 20;    // infinite ;)

        else if (flags & SWS_SPLINE)

            sizeFactor = 20;    // infinite ;)

        else if (flags & SWS_BILINEAR)

            sizeFactor = 2;

        else {

            sizeFactor = 0;     // GCC warning killer

            assert(0);

        }

        if (xInc <= 1 << 16)

            filterSize = 1 + sizeFactor;    // upscale

        else

            filterSize = 1 + (sizeFactor * srcW + dstW - 1) / dstW;

        filterSize = FFMIN(filterSize, srcW - 2);

        filterSize = FFMAX(filterSize, 1);

        FF_ALLOC_OR_GOTO(NULL, filter,

                         dstW * sizeof(*filter) * filterSize, fail);

        xDstInSrc = xInc - 0x10000;

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

            int xx = (xDstInSrc - ((filterSize - 2) << 16)) / (1 << 17);

            int j;

            (*filterPos)[i] = xx;

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

                int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;

                double floatd;

                int64_t coeff;

                if (xInc > 1 << 16)

                    d = d * dstW / srcW;

                floatd = d * (1.0 / (1 << 30));

                if (flags & SWS_BICUBIC) {

                    int64_t B = (param[0] != SWS_PARAM_DEFAULT ? param[0] :   0) * (1 << 24);

                    int64_t C = (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1 << 24);

                    if (d >= 1LL << 31) {

                        coeff = 0.0;

                    } else {

                        int64_t dd  = (d  * d) >> 30;

                        int64_t ddd = (dd * d) >> 30;

                        if (d < 1LL << 30)

                            coeff =  (12 * (1 << 24) -  9 * B - 6 * C) * ddd +

                                    (-18 * (1 << 24) + 12 * B + 6 * C) *  dd +

                                      (6 * (1 << 24) -  2 * B)         * (1 << 30);

                        else

                            coeff =      (-B -  6 * C) * ddd +

                                      (6 * B + 30 * C) * dd  +

                                    (-12 * B - 48 * C) * d   +

                                      (8 * B + 24 * C) * (1 << 30);

                    }

                    coeff *= fone >> (30 + 24);

                }

#if 0

                else if (flags & SWS_X) {

                    double p  = param ? param * 0.01 : 0.3;

                    coeff     = d ? sin(d * M_PI) / (d * M_PI) : 1.0;

                    coeff    *= pow(2.0, -p * d * d);

                }

#endif

                else if (flags & SWS_X) {

                    double A = param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;

                    double c;

                    if (floatd < 1.0)

                        c = cos(floatd * M_PI);

                    else

                        c = -1.0;

                    if (c < 0.0)

                        c = -pow(-c, A);

                    else

                        c = pow(c, A);

                    coeff = (c * 0.5 + 0.5) * fone;

                } else if (flags & SWS_AREA) {

                    int64_t d2 = d - (1 << 29);

                    if (d2 * xInc < -(1LL << (29 + 16)))

                        coeff = 1.0 * (1LL << (30 + 16));

                    else if (d2 * xInc < (1LL << (29 + 16)))

                        coeff = -d2 * xInc + (1LL << (29 + 16));

                    else

                        coeff = 0.0;

                    coeff *= fone >> (30 + 16);

                } else if (flags & SWS_GAUSS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (pow(2.0, -p * floatd * floatd)) * fone;

                } else if (flags & SWS_SINC) {

                    coeff = (d ? sin(floatd * M_PI) / (floatd * M_PI) : 1.0) * fone;

                } else if (flags & SWS_LANCZOS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (d ? sin(floatd * M_PI) * sin(floatd * M_PI / p) /

                             (floatd * floatd * M_PI * M_PI / p) : 1.0) * fone;

                    if (floatd > p)

                        coeff = 0;

                } else if (flags & SWS_BILINEAR) {

                    coeff = (1 << 30) - d;

                    if (coeff < 0)

                        coeff = 0;

                    coeff *= fone >> 30;

                } else if (flags & SWS_SPLINE) {

                    double p = -2.196152422706632;

                    coeff = getSplineCoeff(1.0, 0.0, p, -p - 1.0, floatd) * fone;

                } else {

                    coeff = 0.0; // GCC warning killer

                    assert(0);

                }

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += 2 * xInc;

        }

    }

    /* apply src & dst Filter to filter -> filter2

     * av_free(filter);

     */

    assert(filterSize > 0);

    filter2Size = filterSize;

    if (srcFilter)

        filter2Size += srcFilter->length - 1;

    if (dstFilter)

        filter2Size += dstFilter->length - 1;

    assert(filter2Size > 0);

    FF_ALLOCZ_OR_GOTO(NULL, filter2, filter2Size * dstW * sizeof(*filter2), fail);

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

        int j, k;

        if (srcFilter) {

            for (k = 0; k < srcFilter->length; k++) {

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

                    filter2[i * filter2Size + k + j] +=

                        srcFilter->coeff[k] * filter[i * filterSize + j];

            }

        } else {

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

                filter2[i * filter2Size + j] = filter[i * filterSize + j];

        }

        // FIXME dstFilter

        (*filterPos)[i] += (filterSize - 1) / 2 - (filter2Size - 1) / 2;

    }

    av_freep(&filter);

    /* try to reduce the filter-size (step1 find size and shift left) */

    // Assume it is near normalized (*0.5 or *2.0 is OK but * 0.001 is not).

    minFilterSize = 0;

    for (i = dstW - 1; i >= 0; i--) {

        int min = filter2Size;

        int j;

        int64_t cutOff = 0.0;

        /* get rid of near zero elements on the left by shifting left */

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

            int k;

            cutOff += FFABS(filter2[i * filter2Size]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            /* preserve monotonicity because the core can't handle the

             * filter otherwise */

            if (i < dstW - 1 && (*filterPos)[i] >= (*filterPos)[i + 1])

                break;

            // move filter coefficients left

            for (k = 1; k < filter2Size; k++)

                filter2[i * filter2Size + k - 1] = filter2[i * filter2Size + k];

            filter2[i * filter2Size + k - 1] = 0;

            (*filterPos)[i]++;

        }

        cutOff = 0;

        /* count near zeros on the right */

        for (j = filter2Size - 1; j > 0; j--) {

            cutOff += FFABS(filter2[i * filter2Size + j]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            min--;

        }

        if (min > minFilterSize)

            minFilterSize = min;

    }

    if (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_ALTIVEC) {

        // we can handle the special case 4, so we don't want to go the full 8

        if (minFilterSize < 5)

            filterAlign = 4;

        /* We really don't want to waste our time doing useless computation, so

         * fall back on the scalar C code for very small filters.

         * Vectorizing is worth it only if you have a decent-sized vector. */

        if (minFilterSize < 3)

            filterAlign = 1;

    }

    if (INLINE_MMX(cpu_flags)) {

        // special case for unscaled vertical filtering

        if (minFilterSize == 1 && filterAlign == 2)

            filterAlign = 1;

    }

    assert(minFilterSize > 0);

    filterSize = (minFilterSize + (filterAlign - 1)) & (~(filterAlign - 1));

    assert(filterSize > 0);

    filter = av_malloc(filterSize * dstW * sizeof(*filter));

    if (filterSize >= MAX_FILTER_SIZE * 16 /

                      ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16) || !filter)

        goto fail;

    *outFilterSize = filterSize;

    if (flags & SWS_PRINT_INFO)

        av_log(NULL, AV_LOG_VERBOSE,

               "SwScaler: reducing / aligning filtersize %d -> %d\n",

               filter2Size, filterSize);

    /* try to reduce the filter-size (step2 reduce it) */

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

        int j;

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

            if (j >= filter2Size)

                filter[i * filterSize + j] = 0;

            else

                filter[i * filterSize + j] = filter2[i * filter2Size + j];

            if ((flags & SWS_BITEXACT) && j >= minFilterSize)

                filter[i * filterSize + j] = 0;

        }

    }

    // FIXME try to align filterPos if possible

    // fix borders

    if (is_horizontal) {

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

            int j;

            if ((*filterPos)[i] < 0) {

                // move filter coefficients left to compensate for filterPos

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

                    int left = FFMAX(j + (*filterPos)[i], 0);

                    filter[i * filterSize + left] += filter[i * filterSize + j];

                    filter[i * filterSize + j]     = 0;

                }

                (*filterPos)[i] = 0;

            }

            if ((*filterPos)[i] + filterSize > srcW) {

                int shift = (*filterPos)[i] + filterSize - srcW;

                // move filter coefficients right to compensate for filterPos

                for (j = filterSize - 2; j >= 0; j--) {

                    int right = FFMIN(j + shift, filterSize - 1);

                    filter[i * filterSize + right] += filter[i * filterSize + j];

                    filter[i * filterSize + j]      = 0;

                }

                (*filterPos)[i] = srcW - filterSize;

            }

        }

    }

    // Note the +1 is for the MMX scaler which reads over the end

    /* align at 16 for AltiVec (needed by hScale_altivec_real) */

    FF_ALLOCZ_OR_GOTO(NULL, *outFilter,

                      *outFilterSize * (dstW + 3) * sizeof(int16_t), fail);

    /* normalize & store in outFilter */

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

        int j;

        int64_t error = 0;

        int64_t sum   = 0;

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

            sum += filter[i * filterSize + j];

        }

        sum = (sum + one / 2) / one;

        for (j = 0; j < *outFilterSize; j++) {

            int64_t v = filter[i * filterSize + j] + error;

            int intV  = ROUNDED_DIV(v, sum);

            (*outFilter)[i * (*outFilterSize) + j] = intV;

            error                                  = v - intV * sum;

        }

    }

    (*filterPos)[dstW + 0] =

    (*filterPos)[dstW + 1] =

    (*filterPos)[dstW + 2] = (*filterPos)[dstW - 1]; /* the MMX/SSE scaler will

                                                      * read over the end */

    for (i = 0; i < *outFilterSize; i++) {

        int k = (dstW - 1) * (*outFilterSize) + i;

        (*outFilter)[k + 1 * (*outFilterSize)] =

        (*outFilter)[k + 2 * (*outFilterSize)] =

        (*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];

    }

    ret = 0;

fail:

    av_free(filter);

    av_free(filter2);

    return ret;

}


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

                       const void *bits, int bits_wrap, int bits_size,

                       const void *codes, int codes_wrap, int codes_size,

                       const void *symbols, int symbols_wrap, int symbols_size,

                       int flags)

{

    VLCcode *buf;

    int i, j, ret;

    vlc->bits = nb_bits;

    if (flags & INIT_VLC_USE_NEW_STATIC) {

        VLC dyn_vlc = *vlc;

        if (vlc->table_size)

            return 0;

        ret = ff_init_vlc_sparse(&dyn_vlc, nb_bits, nb_codes,

                                 bits, bits_wrap, bits_size,

                                 codes, codes_wrap, codes_size,

                                 symbols, symbols_wrap, symbols_size,

                                 flags & ~INIT_VLC_USE_NEW_STATIC);

        av_assert0(ret >= 0);

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

        if (dyn_vlc.table_size < vlc->table_allocated)

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

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

        vlc->table_size = dyn_vlc.table_size;

        ff_free_vlc(&dyn_vlc);

        return 0;

    } else {

        vlc->table           = NULL;

        vlc->table_allocated = 0;

        vlc->table_size      = 0;

    }

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

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

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

    j = 0;

#define COPY(condition)\

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

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

        if (!(condition))                                                   \

            continue;                                                       \

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

            av_log(NULL, AV_LOG_ERROR, "Too long VLC (%d) in init_vlc\n", buf[j].bits);\

            av_free(buf);                                                   \

            return -1;                                                      \

        }                                                                   \

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

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

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

            av_free(buf);                                                   \

            return -1;                                                      \

        }                                                                   \

        if (flags & INIT_VLC_LE)                                            \

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

        else                                                                \

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

        if (symbols)                                                        \

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

        else                                                                \

            buf[j].symbol = i;                                              \

        j++;                                                                \

    }

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

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

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

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

    nb_codes = j;

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

    av_free(buf);

    if (ret < 0) {

        av_freep(&vlc->table);

        return ret;

    }

    return 0;

}


static uint64_t macio_nvram_readb(void *opaque, hwaddr addr,

                                  unsigned size)

{

    MacIONVRAMState *s = opaque;

    uint32_t value;

    addr = (addr >> s->it_shift) & (s->size - 1);

    value = s->data[addr];

    NVR_DPRINTF("readb addr %04x val %x\n", (int)addr, value);

    return value;

}


void HELPER(v7m_msr)(CPUARMState *env, uint32_t reg, uint32_t val)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    switch (reg) {

    case 0: /* APSR */

        xpsr_write(env, val, 0xf8000000);

        break;

    case 1: /* IAPSR */

        xpsr_write(env, val, 0xf8000000);

        break;

    case 2: /* EAPSR */

        xpsr_write(env, val, 0xfe00fc00);

        break;

    case 3: /* xPSR */

        xpsr_write(env, val, 0xfe00fc00);

        break;

    case 5: /* IPSR */

        /* IPSR bits are readonly.  */

        break;

    case 6: /* EPSR */

        xpsr_write(env, val, 0x0600fc00);

        break;

    case 7: /* IEPSR */

        xpsr_write(env, val, 0x0600fc00);

        break;

    case 8: /* MSP */

        if (env->v7m.current_sp)

            env->v7m.other_sp = val;

        else

            env->regs[13] = val;

        break;

    case 9: /* PSP */

        if (env->v7m.current_sp)

            env->regs[13] = val;

        else

            env->v7m.other_sp = val;

        break;

    case 16: /* PRIMASK */

        if (val & 1) {

            env->daif |= PSTATE_I;

        } else {

            env->daif &= ~PSTATE_I;

        }

        break;

    case 17: /* BASEPRI */

        env->v7m.basepri = val & 0xff;

        break;

    case 18: /* BASEPRI_MAX */

        val &= 0xff;

        if (val != 0 && (val < env->v7m.basepri || env->v7m.basepri == 0))

            env->v7m.basepri = val;

        break;

    case 19: /* FAULTMASK */

        if (val & 1) {

            env->daif |= PSTATE_F;

        } else {

            env->daif &= ~PSTATE_F;

        }

        break;

    case 20: /* CONTROL */

        env->v7m.control = val & 3;

        switch_v7m_sp(env, (val & 2) != 0);

        break;

    default:

        /* ??? For debugging only.  */

        cpu_abort(CPU(cpu), "Unimplemented system register write (%d)\n", reg);

        return;

    }

}


AVRational av_d2q(double d, int max)

{

    AVRational a;

    int exponent;

    int64_t den;

    if (isnan(d))

        return (AVRational) { 0,0 };

    if (fabs(d) > INT_MAX + 3LL)

        return (AVRational) { d < 0 ? -1 : 1, 0 };

    frexp(d, &exponent);

    exponent = FFMAX(exponent-1, 0);

    den = 1LL << (61 - exponent);

    // (int64_t)rint() and llrint() do not work with gcc on ia64 and sparc64

    av_reduce(&a.num, &a.den, floor(d * den + 0.5), den, max);

    if ((!a.num || !a.den) && d && max>0 && max<INT_MAX)

        av_reduce(&a.num, &a.den, floor(d * den + 0.5), den, INT_MAX);

    return a;

}


static unsigned tget(GetByteContext *gb, int type, int le)

{

    switch (type) {

    case TIFF_BYTE : return bytestream2_get_byteu(gb);

    case TIFF_SHORT: return tget_short(gb, le);

    case TIFF_LONG : return tget_long(gb, le);

    default        : return UINT_MAX;

    }

}


PCIDevice *pci_pcnet_init(PCIBus *bus, NICInfo *nd, int devfn)

{

    PCNetState *d;

    uint8_t *pci_conf;

#if 0

    printf("sizeof(RMD)=%d, sizeof(TMD)=%d\n",

        sizeof(struct pcnet_RMD), sizeof(struct pcnet_TMD));

#endif

    d = (PCNetState *)pci_register_device(bus, "PCNet", sizeof(PCNetState),

                                          devfn, NULL, NULL);

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_AMD);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_AMD_LANCE);

    *(uint16_t *)&pci_conf[0x04] = cpu_to_le16(0x0007);

    *(uint16_t *)&pci_conf[0x06] = cpu_to_le16(0x0280);

    pci_conf[0x08] = 0x10;

    pci_conf[0x09] = 0x00;

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_conf[0x0e] = 0x00; // header_type

    *(uint32_t *)&pci_conf[0x10] = cpu_to_le32(0x00000001);

    *(uint32_t *)&pci_conf[0x14] = cpu_to_le32(0x00000000);

    pci_conf[0x3d] = 1; // interrupt pin 0

    pci_conf[0x3e] = 0x06;

    pci_conf[0x3f] = 0xff;

    /* Handler for memory-mapped I/O */

    d->mmio_index =

      cpu_register_io_memory(0, pcnet_mmio_read, pcnet_mmio_write, d);

    pci_register_io_region((PCIDevice *)d, 0, PCNET_IOPORT_SIZE,

                           PCI_ADDRESS_SPACE_IO, pcnet_ioport_map);

    pci_register_io_region((PCIDevice *)d, 1, PCNET_PNPMMIO_SIZE,

                           PCI_ADDRESS_SPACE_MEM, pcnet_mmio_map);

    d->irq = d->dev.irq[0];

    d->phys_mem_read = pci_physical_memory_read;

    d->phys_mem_write = pci_physical_memory_write;

    d->pci_dev = &d->dev;

    pcnet_common_init(d, nd);

    return (PCIDevice *)d;

}


void aio_notify(AioContext *ctx)

{

    /* Write e.g. bh->scheduled before reading ctx->dispatching.  */

    smp_mb();

    if (!ctx->dispatching) {

        event_notifier_set(&ctx->notifier);

    }

}


static void tb_invalidate_phys_page(tb_page_addr_t addr,

                                    uintptr_t pc, void *puc)

{

    TranslationBlock *tb;

    PageDesc *p;

    int n;

#ifdef TARGET_HAS_PRECISE_SMC

    TranslationBlock *current_tb = NULL;

    CPUState *cpu = current_cpu;

    CPUArchState *env = NULL;

    int current_tb_modified = 0;

    target_ulong current_pc = 0;

    target_ulong current_cs_base = 0;

    int current_flags = 0;

#endif

    addr &= TARGET_PAGE_MASK;

    p = page_find(addr >> TARGET_PAGE_BITS);

    if (!p) {

        return;

    }

    tb = p->first_tb;

#ifdef TARGET_HAS_PRECISE_SMC

    if (tb && pc != 0) {

        current_tb = tb_find_pc(pc);

    }

    if (cpu != NULL) {

        env = cpu->env_ptr;

    }

#endif

    while (tb != NULL) {

        n = (uintptr_t)tb & 3;

        tb = (TranslationBlock *)((uintptr_t)tb & ~3);

#ifdef TARGET_HAS_PRECISE_SMC

        if (current_tb == tb &&

            (current_tb->cflags & CF_COUNT_MASK) != 1) {

                /* If we are modifying the current TB, we must stop

                   its execution. We could be more precise by checking

                   that the modification is after the current PC, but it

                   would require a specialized function to partially

                   restore the CPU state */

            current_tb_modified = 1;

            cpu_restore_state_from_tb(current_tb, env, pc);

            cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base,

                                 &current_flags);

        }

#endif /* TARGET_HAS_PRECISE_SMC */

        tb_phys_invalidate(tb, addr);

        tb = tb->page_next[n];

    }

    p->first_tb = NULL;

#ifdef TARGET_HAS_PRECISE_SMC

    if (current_tb_modified) {

        /* we generate a block containing just the instruction

           modifying the memory. It will ensure that it cannot modify

           itself */

        cpu->current_tb = NULL;

        tb_gen_code(env, current_pc, current_cs_base, current_flags, 1);

        cpu_resume_from_signal(env, puc);

    }

#endif

}


static int rtp_parse_mp4_au(PayloadContext *data, const uint8_t *buf)

{

    int au_headers_length, au_header_size, i;

    GetBitContext getbitcontext;

    /* decode the first 2 bytes where the AUHeader sections are stored

       length in bits */

    au_headers_length = AV_RB16(buf);

    if (au_headers_length > RTP_MAX_PACKET_LENGTH)

      return -1;

    data->au_headers_length_bytes = (au_headers_length + 7) / 8;

    /* skip AU headers length section (2 bytes) */

    buf += 2;

    init_get_bits(&getbitcontext, buf, data->au_headers_length_bytes * 8);

    /* XXX: Wrong if optionnal additional sections are present (cts, dts etc...) */

    au_header_size = data->sizelength + data->indexlength;

    if (au_header_size <= 0 || (au_headers_length % au_header_size != 0))

        return -1;

    data->nb_au_headers = au_headers_length / au_header_size;

    if (!data->au_headers || data->au_headers_allocated < data->nb_au_headers) {

        av_free(data->au_headers);

        data->au_headers = av_malloc(sizeof(struct AUHeaders) * data->nb_au_headers);

        if (!data->au_headers)

            return AVERROR(ENOMEM);

        data->au_headers_allocated = data->nb_au_headers;

    }

    /* XXX: We handle multiple AU Section as only one (need to fix this for interleaving)

       In my test, the FAAD decoder does not behave correctly when sending each AU one by one

       but does when sending the whole as one big packet...  */

    data->au_headers[0].size = 0;

    data->au_headers[0].index = 0;

    for (i = 0; i < data->nb_au_headers; ++i) {

        data->au_headers[0].size += get_bits_long(&getbitcontext, data->sizelength);

        data->au_headers[0].index = get_bits_long(&getbitcontext, data->indexlength);

    }

    data->nb_au_headers = 1;

    return 0;

}


static inline void RENAME(palToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width, uint32_t *pal)

{

	int i;

        assert(src1 == src2);

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

	{

		int p= pal[src1[i]];

		dstU[i]= p>>8;

		dstV[i]= p>>16;

	}

}


static uint64_t pl011_read(void *opaque, target_phys_addr_t offset,

                           unsigned size)

{

    pl011_state *s = (pl011_state *)opaque;

    uint32_t c;

    if (offset >= 0xfe0 && offset < 0x1000) {

        return s->id[(offset - 0xfe0) >> 2];

    }

    switch (offset >> 2) {

    case 0: /* UARTDR */

        s->flags &= ~PL011_FLAG_RXFF;

        c = s->read_fifo[s->read_pos];

        if (s->read_count > 0) {

            s->read_count--;

            if (++s->read_pos == 16)

                s->read_pos = 0;

        }

        if (s->read_count == 0) {

            s->flags |= PL011_FLAG_RXFE;

        }

        if (s->read_count == s->read_trigger - 1)

            s->int_level &= ~ PL011_INT_RX;

        pl011_update(s);

        qemu_chr_accept_input(s->chr);

        return c;

    case 1: /* UARTCR */

        return 0;

    case 6: /* UARTFR */

        return s->flags;

    case 8: /* UARTILPR */

        return s->ilpr;

    case 9: /* UARTIBRD */

        return s->ibrd;

    case 10: /* UARTFBRD */

        return s->fbrd;

    case 11: /* UARTLCR_H */

        return s->lcr;

    case 12: /* UARTCR */

        return s->cr;

    case 13: /* UARTIFLS */

        return s->ifl;

    case 14: /* UARTIMSC */

        return s->int_enabled;

    case 15: /* UARTRIS */

        return s->int_level;

    case 16: /* UARTMIS */

        return s->int_level & s->int_enabled;

    case 18: /* UARTDMACR */

        return s->dmacr;

    default:

        hw_error("pl011_read: Bad offset %x\n", (int)offset);

        return 0;

    }

}


static void icp_pit_write(void *opaque, hwaddr offset,

                          uint64_t value, unsigned size)

{

    icp_pit_state *s = (icp_pit_state *)opaque;

    int n;

    n = offset >> 8;

    if (n > 2) {

        qemu_log_mask(LOG_GUEST_ERROR, "%s: Bad timer %d\n", __func__, n);

    }

    arm_timer_write(s->timer[n], offset & 0xff, value);

}


static void targa_decode_rle(AVCodecContext *avctx, TargaContext *s, const uint8_t *src, uint8_t *dst, int w, int h, int stride, int bpp)

{

    int i, x, y;

    int depth = (bpp + 1) >> 3;

    int type, count;

    int diff;

    diff = stride - w * depth;

    x = y = 0;

    while(y < h){

        type = *src++;

        count = (type & 0x7F) + 1;

        type &= 0x80;

        if((x + count > w) && (x + count + 1 > (h - y) * w)){

            av_log(avctx, AV_LOG_ERROR, "Packet went out of bounds: position (%i,%i) size %i\n", x, y, count);

            return;

        }

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

            switch(depth){

            case 1:

                *dst = *src;

                break;

            case 2:

                *((uint16_t*)dst) = AV_RL16(src);

                break;

            case 3:

                dst[0] = src[0];

                dst[1] = src[1];

                dst[2] = src[2];

                break;

            case 4:

                *((uint32_t*)dst) = AV_RL32(src);

                break;

            }

            dst += depth;

            if(!type)

                src += depth;

            x++;

            if(x == w){

                x = 0;

                y++;

                dst += diff;

            }

        }

        if(type)

            src += depth;

    }

}


static int aasc_decode_frame(AVCodecContext *avctx,
                              void *data, int *data_size,
                              AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    AascContext *s = avctx->priv_data;
    int compr, i, stride, psize;
    s->frame.reference = 3;
    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;
    if (avctx->reget_buffer(avctx, &s->frame)) {
        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
        return -1;
    compr = AV_RL32(buf);
    buf += 4;
    buf_size -= 4;
    psize = avctx->bits_per_coded_sample / 8;
    switch (avctx->codec_tag) {
    case MKTAG('A', 'A', 'S', '4'):
        bytestream2_init(&s->gb, buf - 4, buf_size + 4);
        ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, &s->gb);
        break;
    case MKTAG('A', 'A', 'S', 'C'):
    switch(compr){
    case 0:
        stride = (avctx->width * psize + psize) & ~psize;
        for(i = avctx->height - 1; i >= 0; i--){
            if(avctx->width * psize > buf_size){
                av_log(avctx, AV_LOG_ERROR, "Next line is beyond buffer bounds\n");
                break;
            memcpy(s->frame.data[0] + i*s->frame.linesize[0], buf, avctx->width * psize);
            buf += stride;
            buf_size -= stride;
        break;
    case 1:
        bytestream2_init(&s->gb, buf, buf_size);
        ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, &s->gb);
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr);
        return -1;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "Unknown FourCC: %X\n", avctx->codec_tag);
        return -1;
    if (avctx->pix_fmt == AV_PIX_FMT_PAL8)
        memcpy(s->frame.data[1], s->palette, s->palette_size);
    *data_size = sizeof(AVFrame);
    *(AVFrame*)data = s->frame;
    /* report that the buffer was completely consumed */
    return buf_size;


int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,

                                  int64_t size)

{

    int ret = qcow2_check_metadata_overlap(bs, ign, offset, size);

    if (ret < 0) {

        return ret;

    } else if (ret > 0) {

        int metadata_ol_bitnr = ffs(ret) - 1;

        char *message;

        assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);

        fprintf(stderr, "qcow2: Preventing invalid write on metadata (overlaps "

                "with %s); image marked as corrupt.\n",

                metadata_ol_names[metadata_ol_bitnr]);

        message = g_strdup_printf("Prevented %s overwrite",

                metadata_ol_names[metadata_ol_bitnr]);

        qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),

                                              message,

                                              true,

                                              offset,

                                              true,

                                              size,

                                              true,

                                              &error_abort);

        g_free(message);

        qcow2_mark_corrupt(bs);

        bs->drv = NULL; /* make BDS unusable */

        return -EIO;

    }

    return 0;

}


static int dmg_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
{
    BDRVDMGState *s = bs->opaque;
    uint64_t info_begin, info_end, last_in_offset, last_out_offset;
    uint32_t count, tmp;
    uint32_t max_compressed_size = 1, max_sectors_per_chunk = 1, i;
    int64_t offset;
    int ret;
    bs->read_only = 1;
    s->n_chunks = 0;
    s->offsets = s->lengths = s->sectors = s->sectorcounts = NULL;
    /* read offset of info blocks */
    offset = bdrv_getlength(bs->file);
    if (offset < 0) {
        ret = offset;
    offset -= 0x1d8;
    ret = read_uint64(bs, offset, &info_begin);
    if (ret < 0) {
    } else if (info_begin == 0) {
    ret = read_uint32(bs, info_begin, &tmp);
    if (ret < 0) {
    } else if (tmp != 0x100) {
    ret = read_uint32(bs, info_begin + 4, &count);
    if (ret < 0) {
    } else if (count == 0) {
    info_end = info_begin + count;
    offset = info_begin + 0x100;
    /* read offsets */
    last_in_offset = last_out_offset = 0;
    while (offset < info_end) {
        uint32_t type;
        ret = read_uint32(bs, offset, &count);
        if (ret < 0) {
        } else if (count == 0) {
        offset += 4;
        ret = read_uint32(bs, offset, &type);
        if (ret < 0) {
        if (type == 0x6d697368 && count >= 244) {
            size_t new_size;
            uint32_t chunk_count;
            offset += 4;
            offset += 200;
            chunk_count = (count - 204) / 40;
            new_size = sizeof(uint64_t) * (s->n_chunks + chunk_count);
            s->types = g_realloc(s->types, new_size / 2);
            s->offsets = g_realloc(s->offsets, new_size);
            s->lengths = g_realloc(s->lengths, new_size);
            s->sectors = g_realloc(s->sectors, new_size);
            s->sectorcounts = g_realloc(s->sectorcounts, new_size);
            for (i = s->n_chunks; i < s->n_chunks + chunk_count; i++) {
                ret = read_uint32(bs, offset, &s->types[i]);
                if (ret < 0) {
                offset += 4;
                if (s->types[i] != 0x80000005 && s->types[i] != 1 &&
                    s->types[i] != 2) {
                    if (s->types[i] == 0xffffffff && i > 0) {
                        last_in_offset = s->offsets[i - 1] + s->lengths[i - 1];
                        last_out_offset = s->sectors[i - 1] +
                                          s->sectorcounts[i - 1];
                    chunk_count--;
                    i--;
                    offset += 36;
                    continue;
                offset += 4;
                ret = read_uint64(bs, offset, &s->sectors[i]);
                if (ret < 0) {
                s->sectors[i] += last_out_offset;
                offset += 8;
                ret = read_uint64(bs, offset, &s->sectorcounts[i]);
                if (ret < 0) {
                offset += 8;
                if (s->sectorcounts[i] > DMG_SECTORCOUNTS_MAX) {
                    error_report("sector count %" PRIu64 " for chunk %u is "
                                 "larger than max (%u)",
                                 s->sectorcounts[i], i, DMG_SECTORCOUNTS_MAX);
                ret = read_uint64(bs, offset, &s->offsets[i]);
                if (ret < 0) {
                s->offsets[i] += last_in_offset;
                offset += 8;
                ret = read_uint64(bs, offset, &s->lengths[i]);
                if (ret < 0) {
                offset += 8;
                if (s->lengths[i] > max_compressed_size) {
                    max_compressed_size = s->lengths[i];
                if (s->sectorcounts[i] > max_sectors_per_chunk) {
                    max_sectors_per_chunk = s->sectorcounts[i];
            s->n_chunks += chunk_count;
    /* initialize zlib engine */
    s->compressed_chunk = g_malloc(max_compressed_size + 1);
    s->uncompressed_chunk = g_malloc(512 * max_sectors_per_chunk);
    if (inflateInit(&s->zstream) != Z_OK) {
    s->current_chunk = s->n_chunks;
    qemu_co_mutex_init(&s->lock);
    return 0;
fail:
    g_free(s->types);
    g_free(s->offsets);
    g_free(s->lengths);
    g_free(s->sectors);
    g_free(s->sectorcounts);
    g_free(s->compressed_chunk);
    g_free(s->uncompressed_chunk);
    return ret;


int ff_mjpeg_decode_sof(MJpegDecodeContext *s)

{

    int len, nb_components, i, width, height, pix_fmt_id;

    s->cur_scan = 0;

    s->upscale_h = s->upscale_v = 0;

    /* XXX: verify len field validity */

    len     = get_bits(&s->gb, 16);

    s->bits = get_bits(&s->gb, 8);

    if (s->pegasus_rct)

        s->bits = 9;

    if (s->bits == 9 && !s->pegasus_rct)

        s->rct  = 1;    // FIXME ugly

    if (s->bits != 8 && !s->lossless) {

        av_log(s->avctx, AV_LOG_ERROR, "only 8 bits/component accepted\n");

        return -1;

    }

    if(s->lossless && s->avctx->lowres){

        av_log(s->avctx, AV_LOG_ERROR, "lowres is not possible with lossless jpeg\n");

        return -1;

    }

    height = get_bits(&s->gb, 16);

    width  = get_bits(&s->gb, 16);

    // HACK for odd_height.mov

    if (s->interlaced && s->width == width && s->height == height + 1)

        height= s->height;

    av_log(s->avctx, AV_LOG_DEBUG, "sof0: picture: %dx%d\n", width, height);

    if (av_image_check_size(width, height, 0, s->avctx))

        return AVERROR_INVALIDDATA;

    nb_components = get_bits(&s->gb, 8);

    if (nb_components <= 0 ||

        nb_components > MAX_COMPONENTS)

        return -1;

    if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {

        if (nb_components != s->nb_components) {

            av_log(s->avctx, AV_LOG_ERROR, "nb_components changing in interlaced picture\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (s->ls && !(s->bits <= 8 || nb_components == 1)) {

        av_log_missing_feature(s->avctx,

                               "For JPEG-LS anything except <= 8 bits/component"

                               " or 16-bit gray", 0);

        return AVERROR_PATCHWELCOME;

    }

    s->nb_components = nb_components;

    s->h_max         = 1;

    s->v_max         = 1;

    memset(s->h_count, 0, sizeof(s->h_count));

    memset(s->v_count, 0, sizeof(s->v_count));

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

        /* component id */

        s->component_id[i] = get_bits(&s->gb, 8) - 1;

        s->h_count[i]      = get_bits(&s->gb, 4);

        s->v_count[i]      = get_bits(&s->gb, 4);

        /* compute hmax and vmax (only used in interleaved case) */

        if (s->h_count[i] > s->h_max)

            s->h_max = s->h_count[i];

        if (s->v_count[i] > s->v_max)

            s->v_max = s->v_count[i];

        if (!s->h_count[i] || !s->v_count[i]) {

            av_log(s->avctx, AV_LOG_ERROR, "h/v_count is 0\n");

            return -1;

        }

        s->quant_index[i] = get_bits(&s->gb, 8);

        if (s->quant_index[i] >= 4)

            return AVERROR_INVALIDDATA;

        av_log(s->avctx, AV_LOG_DEBUG, "component %d %d:%d id: %d quant:%d\n",

               i, s->h_count[i], s->v_count[i],

               s->component_id[i], s->quant_index[i]);

    }

    if (s->ls && (s->h_max > 1 || s->v_max > 1)) {

        av_log_missing_feature(s->avctx, "Subsampling in JPEG-LS", 0);

        return AVERROR_PATCHWELCOME;

    }

    if (s->v_max == 1 && s->h_max == 1 && s->lossless==1 && nb_components==3)

        s->rgb = 1;

    /* if different size, realloc/alloc picture */

    /* XXX: also check h_count and v_count */

    if (width != s->width || height != s->height) {

        av_freep(&s->qscale_table);

        s->width      = width;

        s->height     = height;

        s->interlaced = 0;

        /* test interlaced mode */

        if (s->first_picture   &&

            s->org_height != 0 &&

            s->height < ((s->org_height * 3) / 4)) {

            s->interlaced                    = 1;

            s->bottom_field                  = s->interlace_polarity;

            s->picture_ptr->interlaced_frame = 1;

            s->picture_ptr->top_field_first  = !s->interlace_polarity;

            height *= 2;

        }

        avcodec_set_dimensions(s->avctx, width, height);

        s->qscale_table  = av_mallocz((s->width + 15) / 16);

        s->first_picture = 0;

    }

    if (s->interlaced && (s->bottom_field == !s->interlace_polarity)) {

        if (s->progressive) {

            av_log_ask_for_sample(s->avctx, "progressively coded interlaced pictures not supported\n");

            return AVERROR_INVALIDDATA;

        }

    } else{

    /* XXX: not complete test ! */

    pix_fmt_id = (s->h_count[0] << 28) | (s->v_count[0] << 24) |

                 (s->h_count[1] << 20) | (s->v_count[1] << 16) |

                 (s->h_count[2] << 12) | (s->v_count[2] <<  8) |

                 (s->h_count[3] <<  4) |  s->v_count[3];

    av_log(s->avctx, AV_LOG_DEBUG, "pix fmt id %x\n", pix_fmt_id);

    /* NOTE we do not allocate pictures large enough for the possible

     * padding of h/v_count being 4 */

    if (!(pix_fmt_id & 0xD0D0D0D0))

        pix_fmt_id -= (pix_fmt_id & 0xF0F0F0F0) >> 1;

    if (!(pix_fmt_id & 0x0D0D0D0D))

        pix_fmt_id -= (pix_fmt_id & 0x0F0F0F0F) >> 1;

    switch (pix_fmt_id) {

    case 0x11111100:

        if (s->rgb)

            s->avctx->pix_fmt = AV_PIX_FMT_BGR24;

        else {

            if (s->component_id[0] == 'Q' && s->component_id[1] == 'F' && s->component_id[2] == 'A') {

                s->avctx->pix_fmt = AV_PIX_FMT_GBR24P;

            } else {

            s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;

            s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

            }

        }

        av_assert0(s->nb_components == 3);

        break;

    case 0x12121100:

    case 0x22122100:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        s->upscale_v = 2;

        s->upscale_h = (pix_fmt_id == 0x22122100);

        s->chroma_height = s->height;

        break;

    case 0x21211100:

    case 0x22211200:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        s->upscale_v = (pix_fmt_id == 0x22211200);

        s->upscale_h = 2;

        s->chroma_height = s->height;

        break;

    case 0x22221100:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV444P : AV_PIX_FMT_YUVJ444P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        s->upscale_v = 2;

        s->upscale_h = 2;

        s->chroma_height = s->height / 2;

        break;

    case 0x11000000:

        if(s->bits <= 8)

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        else

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;

        break;

    case 0x12111100:

    case 0x22211100:

    case 0x22112100:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV440P : AV_PIX_FMT_YUVJ440P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        s->upscale_h = (pix_fmt_id == 0x22211100) * 2 + (pix_fmt_id == 0x22112100);

        s->chroma_height = s->height / 2;

        break;

    case 0x21111100:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        break;

    case 0x22121100:

    case 0x22111200:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_YUVJ422P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        s->upscale_v = (pix_fmt_id == 0x22121100) + 1;

        break;

    case 0x22111100:

        s->avctx->pix_fmt = s->cs_itu601 ? AV_PIX_FMT_YUV420P : AV_PIX_FMT_YUVJ420P;

        s->avctx->color_range = s->cs_itu601 ? AVCOL_RANGE_MPEG : AVCOL_RANGE_JPEG;

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "Unhandled pixel format 0x%x\n", pix_fmt_id);

        return AVERROR_PATCHWELCOME;

    }

    if ((s->upscale_h || s->upscale_v) && s->avctx->lowres) {

        av_log(s->avctx, AV_LOG_ERROR, "lowres not supported for weird subsampling\n");

        return AVERROR_PATCHWELCOME;

    }

    if (s->ls) {

        s->upscale_h = s->upscale_v = 0;

        if (s->nb_components > 1)

            s->avctx->pix_fmt = AV_PIX_FMT_RGB24;

        else if (s->bits <= 8)

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        else

            s->avctx->pix_fmt = AV_PIX_FMT_GRAY16;

    }

    if (s->picture_ptr->data[0])

        s->avctx->release_buffer(s->avctx, s->picture_ptr);

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

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

        return -1;

    }

    s->picture_ptr->pict_type = AV_PICTURE_TYPE_I;

    s->picture_ptr->key_frame = 1;

    s->got_picture            = 1;

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

        s->linesize[i] = s->picture_ptr->linesize[i] << s->interlaced;

    av_dlog(s->avctx, "%d %d %d %d %d %d\n",

            s->width, s->height, s->linesize[0], s->linesize[1],

            s->interlaced, s->avctx->height);

    if (len != (8 + (3 * nb_components)))

        av_log(s->avctx, AV_LOG_DEBUG, "decode_sof0: error, len(%d) mismatch\n", len);

    }

    /* totally blank picture as progressive JPEG will only add details to it */

    if (s->progressive) {

        int bw = (width  + s->h_max * 8 - 1) / (s->h_max * 8);

        int bh = (height + s->v_max * 8 - 1) / (s->v_max * 8);

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

            int size = bw * bh * s->h_count[i] * s->v_count[i];

            av_freep(&s->blocks[i]);

            av_freep(&s->last_nnz[i]);

            s->blocks[i]       = av_malloc(size * sizeof(**s->blocks));

            s->last_nnz[i]     = av_mallocz(size * sizeof(**s->last_nnz));

            s->block_stride[i] = bw * s->h_count[i];

        }

        memset(s->coefs_finished, 0, sizeof(s->coefs_finished));

    }

    return 0;

}


void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,

                       BlockdevOnError on_write_error)

{

    bs->on_read_error = on_read_error;

    bs->on_write_error = on_write_error;

}


static void test_acpi_one(const char *params, test_data *data)

{

    char *args;

    uint8_t signature_low;

    uint8_t signature_high;

    uint16_t signature;

    int i;

    const char *device = "";

    if (!g_strcmp0(data->machine, MACHINE_Q35)) {

        device = ",id=hd -device ide-hd,drive=hd";

    }

    args = g_strdup_printf("-net none -display none %s -drive file=%s%s,",

                           params ? params : "", disk, device);

    qtest_start(args);

   /* Wait at most 1 minute */

#define TEST_DELAY (1 * G_USEC_PER_SEC / 10)

#define TEST_CYCLES MAX((60 * G_USEC_PER_SEC / TEST_DELAY), 1)

    /* Poll until code has run and modified memory.  Once it has we know BIOS

     * initialization is done.  TODO: check that IP reached the halt

     * instruction.

     */

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

        signature_low = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET);

        signature_high = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

        signature = (signature_high << 8) | signature_low;

        if (signature == SIGNATURE) {

            break;

        }

        g_usleep(TEST_DELAY);

    }

    g_assert_cmphex(signature, ==, SIGNATURE);

    test_acpi_rsdp_address(data);

    test_acpi_rsdp_table(data);

    test_acpi_rsdt_table(data);

    test_acpi_fadt_table(data);

    test_acpi_facs_table(data);

    test_acpi_dsdt_table(data);

    test_acpi_ssdt_tables(data);

    if (iasl) {

        test_acpi_asl(data);

    }

    qtest_quit(global_qtest);

    g_free(args);

}