void qemu_system_reset_request(void)

{

    if (no_reboot) {

        shutdown_requested = 1;

    } else {

        reset_requested = 1;

    }

    cpu_stop_current();

    qemu_notify_event();

}


static void encode_frame(VC2EncContext *s, const AVFrame *frame,

                         const char *aux_data, int field)

{

    int i;

    /* Sequence header */

    encode_parse_info(s, DIRAC_PCODE_SEQ_HEADER);

    encode_seq_header(s);

    /* Encoder version */

    if (aux_data) {

        encode_parse_info(s, DIRAC_PCODE_AUX);

        avpriv_put_string(&s->pb, aux_data, 1);

    }

    /* Picture header */

    encode_parse_info(s, DIRAC_PCODE_PICTURE_HQ);

    encode_picture_start(s);

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

        s->transform_args[i].ctx   = s;

        s->transform_args[i].field = field;

        s->transform_args[i].plane = &s->plane[i];

        s->transform_args[i].idata = frame->data[i];

        s->transform_args[i].istride = frame->linesize[i];

    }

    /* Do a DWT transform */

    s->avctx->execute(s->avctx, dwt_plane, s->transform_args, NULL, 3,

                      sizeof(TransformArgs));

    /* Calculate per-slice quantizers and sizes */

    calc_slice_sizes(s);

    /* Init planes and encode slices */

    encode_slices(s);

    /* End sequence */

    encode_parse_info(s, DIRAC_PCODE_END_SEQ);

}


static void gen_tlbre_booke206(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_booke206_tlbre(cpu_env);

#endif

}


static inline av_flatten int get_symbol_inline(RangeCoder *c, uint8_t *state,

                                               int is_signed)

{

    if (get_rac(c, state + 0))

        return 0;

    else {

        int i, e, a;

        e = 0;

        while (get_rac(c, state + 1 + FFMIN(e, 9))) { // 1..10

            e++;

            if (e > 31)

                return AVERROR_INVALIDDATA;

        }

        a = 1;

        for (i = e - 1; i >= 0; i--)

            a += a + get_rac(c, state + 22 + FFMIN(i, 9));  // 22..31

        e = -(is_signed && get_rac(c, state + 11 + FFMIN(e, 10))); // 11..21

        return (a ^ e) - e;

    }

}


static int mpeg_mux_end(AVFormatContext *ctx)

{

    MpegMuxContext *s = ctx->priv_data;

    StreamInfo *stream;

    int i;

    /* flush each packet */

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

        stream = ctx->streams[i]->priv_data;

        while (stream->buffer_ptr > 0) {

            flush_packet(ctx, i, AV_NOPTS_VALUE, AV_NOPTS_VALUE, s->last_scr);

        }

    }

    /* End header according to MPEG1 systems standard. We do not write

       it as it is usually not needed by decoders and because it

       complicates MPEG stream concatenation. */

    //put_be32(&ctx->pb, ISO_11172_END_CODE);

    //put_flush_packet(&ctx->pb);

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

        av_freep(&ctx->streams[i]->priv_data);

    return 0;

}


static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)

{

    BDRVRawState *s = bs->opaque;

    int rc;

    rc = fd_open(bs);

    if (rc < 0) {

        return rc;

    }

    if (!(flags & BDRV_REQ_MAY_UNMAP)) {

        return -ENOTSUP;

    }

    if (!s->discard_zeroes) {

        return -ENOTSUP;

    }

    return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,

                          QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);

}


theora_gptopts(AVFormatContext *ctx, int idx, uint64_t gp, int64_t *dts)

{

    struct ogg *ogg = ctx->priv_data;

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

    struct theora_params *thp = os->private;

    uint64_t iframe = gp >> thp->gpshift;

    uint64_t pframe = gp & thp->gpmask;

    if (thp->version < 0x030201)

        iframe++;

    if(!pframe)

        os->pflags |= AV_PKT_FLAG_KEY;

    if (dts)

        *dts = iframe + pframe;

    return iframe + pframe;

}


static void qtrle_decode_32bpp(QtrleContext *s, int stream_ptr, int row_ptr, int lines_to_change)

{

    int rle_code;

    int pixel_ptr;

    int row_inc = s->frame.linesize[0];

    unsigned char a, r, g, b;

    unsigned int argb;

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 4;

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (s->buf[stream_ptr++] - 1) * 4;

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                CHECK_STREAM_PTR(4);

                a = s->buf[stream_ptr++];

                r = s->buf[stream_ptr++];

                g = s->buf[stream_ptr++];

                b = s->buf[stream_ptr++];

                argb = (a << 24) | (r << 16) | (g << 8) | (b << 0);

                CHECK_PIXEL_PTR(rle_code * 4);

                while (rle_code--) {

                    *(unsigned int *)(&rgb[pixel_ptr]) = argb;

                    pixel_ptr += 4;

                }

            } else {

                CHECK_STREAM_PTR(rle_code * 4);

                CHECK_PIXEL_PTR(rle_code * 4);

                /* copy pixels directly to output */

                while (rle_code--) {

                    a = s->buf[stream_ptr++];

                    r = s->buf[stream_ptr++];

                    g = s->buf[stream_ptr++];

                    b = s->buf[stream_ptr++];

                    argb = (a << 24) | (r << 16) | (g << 8) | (b << 0);

                    *(unsigned int *)(&rgb[pixel_ptr]) = argb;

                    pixel_ptr += 4;

                }

            }

        }

        row_ptr += row_inc;

    }

}


int loader_exec(const char * filename, char ** argv, char ** envp,

             struct target_pt_regs * regs, struct image_info *infop)

{

    struct linux_binprm bprm;

    int retval;

    int i;

    bprm.p = TARGET_PAGE_SIZE*MAX_ARG_PAGES-sizeof(unsigned int);

    for (i=0 ; i<MAX_ARG_PAGES ; i++)       /* clear page-table */

            bprm.page[i] = NULL;

    retval = open(filename, O_RDONLY);

    if (retval < 0)

        return retval;

    bprm.fd = retval;

    bprm.filename = (char *)filename;

    bprm.argc = count(argv);

    bprm.argv = argv;

    bprm.envc = count(envp);

    bprm.envp = envp;

    retval = prepare_binprm(&bprm);

    if(retval>=0) {

        if (bprm.buf[0] == 0x7f

                && bprm.buf[1] == 'E'

                && bprm.buf[2] == 'L'

                && bprm.buf[3] == 'F') {

            retval = load_elf_binary(&bprm,regs,infop);

        } else {

            fprintf(stderr, "Unknown binary format\n");

            return -1;

        }

    }

    if(retval>=0) {

        /* success.  Initialize important registers */

        do_init_thread(regs, infop);

        return retval;

    }

    /* Something went wrong, return the inode and free the argument pages*/

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

        free(bprm.page[i]);

    }

    return(retval);

}


static av_always_inline SoftFloat autocorr_calc(int64_t accu)

{

        int nz, mant, expo, round;

        int i = (int)(accu >> 32);

        if (i == 0) {

            nz = 1;

        } else {

            nz = 0;

            while (FFABS(i) < 0x40000000) {

                i <<= 1;

                nz++;

            }

            nz = 32-nz;

        }

        round = 1 << (nz-1);

        mant = (int)((accu + round) >> nz);

        mant = (mant + 0x40)>>7;

        mant <<= 6;

        expo = nz + 15;

        return av_int2sf(mant, 30 - expo);

}


static void search_for_ms(AACEncContext *s, ChannelElement *cpe,

                          const float lambda)

{

    int start = 0, i, w, w2, g;

    float M[128], S[128];

    float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;

    SingleChannelElement *sce0 = &cpe->ch[0];

    SingleChannelElement *sce1 = &cpe->ch[1];

    if (!cpe->common_window)

        return;

    for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {

        for (g = 0;  g < sce0->ics.num_swb; g++) {

            if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {

                float dist1 = 0.0f, dist2 = 0.0f;

                for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {

                    FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];

                    FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];

                    float minthr = FFMIN(band0->threshold, band1->threshold);

                    float maxthr = FFMAX(band0->threshold, band1->threshold);

                    for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {

                        M[i] = (sce0->coeffs[start+w2*128+i]

                              + sce1->coeffs[start+w2*128+i]) * 0.5;

                        S[i] =  M[i]

                              - sce1->coeffs[start+w2*128+i];

                    }

                    abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);

                    abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);

                    abs_pow34_v(M34, M,                         sce0->ics.swb_sizes[g]);

                    abs_pow34_v(S34, S,                         sce0->ics.swb_sizes[g]);

                    dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,

                                                L34,

                                                sce0->ics.swb_sizes[g],

                                                sce0->sf_idx[(w+w2)*16+g],

                                                sce0->band_type[(w+w2)*16+g],

                                                lambda / band0->threshold, INFINITY, NULL);

                    dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,

                                                R34,

                                                sce1->ics.swb_sizes[g],

                                                sce1->sf_idx[(w+w2)*16+g],

                                                sce1->band_type[(w+w2)*16+g],

                                                lambda / band1->threshold, INFINITY, NULL);

                    dist2 += quantize_band_cost(s, M,

                                                M34,

                                                sce0->ics.swb_sizes[g],

                                                sce0->sf_idx[(w+w2)*16+g],

                                                sce0->band_type[(w+w2)*16+g],

                                                lambda / maxthr, INFINITY, NULL);

                    dist2 += quantize_band_cost(s, S,

                                                S34,

                                                sce1->ics.swb_sizes[g],

                                                sce1->sf_idx[(w+w2)*16+g],

                                                sce1->band_type[(w+w2)*16+g],

                                                lambda / minthr, INFINITY, NULL);

                }

                cpe->ms_mask[w*16+g] = dist2 < dist1;

            }

            start += sce0->ics.swb_sizes[g];

        }

    }

}


struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,

                                      int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate,

                                      int64_t  in_ch_layout, enum AVSampleFormat  in_sample_fmt, int  in_sample_rate,

                                      int log_offset, void *log_ctx){

    if(!s) s= swr_alloc();

    if(!s) return NULL;

    s->log_level_offset= log_offset;

    s->log_ctx= log_ctx;

    av_opt_set_int(s, "ocl", out_ch_layout,   0);

    av_opt_set_int(s, "osf", out_sample_fmt,  0);

    av_opt_set_int(s, "osr", out_sample_rate, 0);

    av_opt_set_int(s, "icl", in_ch_layout,    0);

    av_opt_set_int(s, "isf", in_sample_fmt,   0);

    av_opt_set_int(s, "isr", in_sample_rate,  0);

    av_opt_set_int(s, "tsf", AV_SAMPLE_FMT_NONE,   0);

    av_opt_set_int(s, "ich", av_get_channel_layout_nb_channels(s-> in_ch_layout), 0);

    av_opt_set_int(s, "och", av_get_channel_layout_nb_channels(s->out_ch_layout), 0);

    av_opt_set_int(s, "uch", 0, 0);

    return s;

}


static int ipvideo_decode_block_opcode_0x8(IpvideoContext *s, AVFrame *frame)
{
    int x, y;
    unsigned char P[4];
    unsigned int flags = 0;
    /* 2-color encoding for each 4x4 quadrant, or 2-color encoding on
     * either top and bottom or left and right halves */
    P[0] = bytestream2_get_byte(&s->stream_ptr);
    P[1] = bytestream2_get_byte(&s->stream_ptr);
    if (P[0] <= P[1]) {
        for (y = 0; y < 16; y++) {
            // new values for each 4x4 block
            if (!(y & 3)) {
                if (y) {
                    P[0]  = bytestream2_get_byte(&s->stream_ptr);
                    P[1]  = bytestream2_get_byte(&s->stream_ptr);
                flags = bytestream2_get_le16(&s->stream_ptr);
            for (x = 0; x < 4; x++, flags >>= 1)
                *s->pixel_ptr++ = P[flags & 1];
            s->pixel_ptr += s->stride - 4;
            // switch to right half
            if (y == 7) s->pixel_ptr -= 8 * s->stride - 4;
    } else {
        flags = bytestream2_get_le32(&s->stream_ptr);
        P[2] = bytestream2_get_byte(&s->stream_ptr);
        P[3] = bytestream2_get_byte(&s->stream_ptr);
        if (P[2] <= P[3]) {
            /* vertical split; left & right halves are 2-color encoded */
            for (y = 0; y < 16; y++) {
                for (x = 0; x < 4; x++, flags >>= 1)
                    *s->pixel_ptr++ = P[flags & 1];
                s->pixel_ptr += s->stride - 4;
                // switch to right half
                if (y == 7) {
                    s->pixel_ptr -= 8 * s->stride - 4;
                    P[0]  = P[2];
                    P[1]  = P[3];
                    flags = bytestream2_get_le32(&s->stream_ptr);
        } else {
            /* horizontal split; top & bottom halves are 2-color encoded */
            for (y = 0; y < 8; y++) {
                if (y == 4) {
                    P[0]  = P[2];
                    P[1]  = P[3];
                    flags = bytestream2_get_le32(&s->stream_ptr);
                for (x = 0; x < 8; x++, flags >>= 1)
                    *s->pixel_ptr++ = P[flags & 1];
                s->pixel_ptr += s->line_inc;
    /* report success */
    return 0;


FpPort *fp_port_alloc(Rocker *r, char *sw_name,

                      MACAddr *start_mac, unsigned int index,

                      NICPeers *peers)

{

    FpPort *port = g_malloc0(sizeof(FpPort));

    if (!port) {

        return NULL;

    }

    port->r = r;

    port->index = index;

    port->pport = index + 1;

    /* front-panel switch port names are 1-based */

    port->name = g_strdup_printf("%sp%d", sw_name, port->pport);

    memcpy(port->conf.macaddr.a, start_mac, sizeof(port->conf.macaddr.a));

    port->conf.macaddr.a[5] += index;

    port->conf.bootindex = -1;

    port->conf.peers = *peers;

    port->nic = qemu_new_nic(&fp_port_info, &port->conf,

                             sw_name, NULL, port);

    qemu_format_nic_info_str(qemu_get_queue(port->nic),

                             port->conf.macaddr.a);

    fp_port_reset(port);

    return port;

}


static void show_stream(AVFormatContext *fmt_ctx, int stream_idx)

{

    AVStream *stream = fmt_ctx->streams[stream_idx];

    AVCodecContext *dec_ctx;

    AVCodec *dec;

    const char *profile;

    char val_str[128];

    AVRational display_aspect_ratio;

    probe_object_header("stream");

    probe_int("index", stream->index);

    if ((dec_ctx = stream->codec)) {

        if ((dec = dec_ctx->codec)) {

            probe_str("codec_name", dec->name);

            probe_str("codec_long_name", dec->long_name);

        } else {

            probe_str("codec_name", "unknown");

        }

        probe_str("codec_type", media_type_string(dec_ctx->codec_type));

        probe_str("codec_time_base",

                  rational_string(val_str, sizeof(val_str),

                                  "/", &dec_ctx->time_base));

        /* print AVI/FourCC tag */

        av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);

        probe_str("codec_tag_string", val_str);

        probe_str("codec_tag", tag_string(val_str, sizeof(val_str),

                                          dec_ctx->codec_tag));

        /* print profile, if there is one */

        if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))

            probe_str("profile", profile);

        switch (dec_ctx->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            probe_int("width", dec_ctx->width);

            probe_int("height", dec_ctx->height);

            probe_int("has_b_frames", dec_ctx->has_b_frames);

            if (dec_ctx->sample_aspect_ratio.num) {

                probe_str("sample_aspect_ratio",

                          rational_string(val_str, sizeof(val_str), ":",

                          &dec_ctx->sample_aspect_ratio));

                av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,

                          dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,

                          dec_ctx->height * dec_ctx->sample_aspect_ratio.den,

                          1024*1024);

                probe_str("display_aspect_ratio",

                          rational_string(val_str, sizeof(val_str), ":",

                          &display_aspect_ratio));

            }

            probe_str("pix_fmt",

                      dec_ctx->pix_fmt != PIX_FMT_NONE ? av_pix_fmt_descriptors[dec_ctx->pix_fmt].name

                                                    : "unknown");

            probe_int("level", dec_ctx->level);

            break;

        case AVMEDIA_TYPE_AUDIO:

            probe_str("sample_rate",

                      value_string(val_str, sizeof(val_str),

                                   dec_ctx->sample_rate,

                                   unit_hertz_str));

            probe_int("channels", dec_ctx->channels);

            probe_int("bits_per_sample",

                      av_get_bits_per_sample(dec_ctx->codec_id));

            break;

        }

    } else {

        probe_str("codec_type", "unknown");

    }

    if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)

        probe_int("id", stream->id);

    probe_str("r_frame_rate",

              rational_string(val_str, sizeof(val_str), "/",

              &stream->r_frame_rate));

    probe_str("avg_frame_rate",

              rational_string(val_str, sizeof(val_str), "/",

              &stream->avg_frame_rate));

    probe_str("time_base",

              rational_string(val_str, sizeof(val_str), "/",

              &stream->time_base));

    probe_str("start_time",

              time_value_string(val_str, sizeof(val_str),

                                stream->start_time, &stream->time_base));

    probe_str("duration",

              time_value_string(val_str, sizeof(val_str),

                                stream->duration, &stream->time_base));

    if (stream->nb_frames)

        probe_int("nb_frames", stream->nb_frames);

    probe_dict(stream->metadata, "tags");

    probe_object_footer("stream");

}


static int is_not_zero(const uint8_t *sector, int len)

{

    /*

     * Use long as the biggest available internal data type that fits into the

     * CPU register and unroll the loop to smooth out the effect of memory

     * latency.

     */

    int i;

    long d0, d1, d2, d3;

    const long * const data = (const long *) sector;

    len /= sizeof(long);

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

        d0 = data[i + 0];

        d1 = data[i + 1];

        d2 = data[i + 2];

        d3 = data[i + 3];

        if (d0 || d1 || d2 || d3) {

            return 1;

        }

    }

    return 0;

}


static void taihu_405ep_init(ram_addr_t ram_size,

                             const char *boot_device,

                             const char *kernel_filename,

                             const char *kernel_cmdline,

                             const char *initrd_filename,

                             const char *cpu_model)

{

    char *filename;

    CPUPPCState *env;

    qemu_irq *pic;

    ram_addr_t bios_offset;

    target_phys_addr_t ram_bases[2], ram_sizes[2];

    target_ulong bios_size;

    target_ulong kernel_base, kernel_size, initrd_base, initrd_size;

    int linux_boot;

    int fl_idx, fl_sectors;

    DriveInfo *dinfo;

    /* RAM is soldered to the board so the size cannot be changed */

    ram_bases[0] = qemu_ram_alloc(NULL, "taihu_405ep.ram-0", 0x04000000);

    ram_sizes[0] = 0x04000000;

    ram_bases[1] = qemu_ram_alloc(NULL, "taihu_405ep.ram-1", 0x04000000);

    ram_sizes[1] = 0x04000000;

    ram_size = 0x08000000;

#ifdef DEBUG_BOARD_INIT

    printf("%s: register cpu\n", __func__);

#endif

    env = ppc405ep_init(ram_bases, ram_sizes, 33333333, &pic,

                        kernel_filename == NULL ? 0 : 1);

    /* allocate and load BIOS */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register BIOS\n", __func__);

#endif

    fl_idx = 0;

#if defined(USE_FLASH_BIOS)

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 2MB */

        //        bios_size = 2 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", bios_size);

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size " TARGET_FMT_lx

               " at offset %08lx addr " TARGET_FMT_lx " '%s' %d\n",

               fl_idx, bios_size, bios_offset, -bios_size,

               bdrv_get_device_name(dinfo->bdrv), fl_sectors);

#endif

        pflash_cfi02_register((uint32_t)(-bios_size), bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    } else

#endif

    {

#ifdef DEBUG_BOARD_INIT

        printf("Load BIOS from file\n");

#endif

        if (bios_name == NULL)

            bios_name = BIOS_FILENAME;

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.bios", BIOS_SIZE);

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image(filename, qemu_get_ram_ptr(bios_offset));

        } else {

            bios_size = -1;

        }

        if (bios_size < 0 || bios_size > BIOS_SIZE) {

            fprintf(stderr, "qemu: could not load PowerPC bios '%s'\n",

                    bios_name);

            exit(1);

        }

        bios_size = (bios_size + 0xfff) & ~0xfff;

        cpu_register_physical_memory((uint32_t)(-bios_size),

                                     bios_size, bios_offset | IO_MEM_ROM);

    }

    /* Register Linux flash */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

    if (dinfo) {

        bios_size = bdrv_getlength(dinfo->bdrv);

        /* XXX: should check that size is 32MB */

        bios_size = 32 * 1024 * 1024;

        fl_sectors = (bios_size + 65535) >> 16;

#ifdef DEBUG_BOARD_INIT

        printf("Register parallel flash %d size " TARGET_FMT_lx

               " at offset %08lx  addr " TARGET_FMT_lx " '%s'\n",

               fl_idx, bios_size, bios_offset, (target_ulong)0xfc000000,

               bdrv_get_device_name(dinfo->bdrv));

#endif

        bios_offset = qemu_ram_alloc(NULL, "taihu_405ep.flash", bios_size);

        pflash_cfi02_register(0xfc000000, bios_offset,

                              dinfo->bdrv, 65536, fl_sectors, 1,

                              4, 0x0001, 0x22DA, 0x0000, 0x0000, 0x555, 0x2AA,

                              1);

        fl_idx++;

    }

    /* Register CLPD & LCD display */

#ifdef DEBUG_BOARD_INIT

    printf("%s: register CPLD\n", __func__);

#endif

    taihu_cpld_init(0x50100000);

    /* Load kernel */

    linux_boot = (kernel_filename != NULL);

    if (linux_boot) {

#ifdef DEBUG_BOARD_INIT

        printf("%s: load kernel\n", __func__);

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                fprintf(stderr,

                        "qemu: could not load initial ram disk '%s'\n",

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

    }

#ifdef DEBUG_BOARD_INIT

    printf("%s: Done\n", __func__);

#endif

}


static int decode_frame_header (bit_buffer_t *bitbuf,MpegEncContext *s) {

  int frame_size_code;

  /* unknown field */

  get_bits (bitbuf, 8);

  /* frame type */

  s->pict_type = get_bits (bitbuf, 2);

  if (s->pict_type == 3)

    return -1;

  if (s->pict_type == SVQ1_FRAME_INTRA) {

    /* unknown fields */

    if (s->f_code == 0x50 || s->f_code == 0x60) {

      get_bits (bitbuf, 16);

    }

    if ((s->f_code ^ 0x10) >= 0x50) {

      skip_bits(bitbuf,8*get_bits (bitbuf, 8));

    }

    get_bits (bitbuf, 2);

    get_bits (bitbuf, 2);

    get_bits (bitbuf, 1);

    /* load frame size */

    frame_size_code = get_bits (bitbuf, 3);

    if (frame_size_code == 7) {

      /* load width, height (12 bits each) */

      s->width = get_bits (bitbuf, 12);

      s->height = get_bits (bitbuf, 12);

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

        return -1;

    } else {

      /* get width, height from table */

      s->width = frame_size_table[frame_size_code].width;

      s->height = frame_size_table[frame_size_code].height;

    }

  }

  /* unknown fields */

  if (get_bits (bitbuf, 1) == 1) {

    get_bits (bitbuf, 1);

    get_bits (bitbuf, 1);

    if (get_bits (bitbuf, 2) != 0)

      return -1;

  }

  if (get_bits (bitbuf, 1) == 1) {

    get_bits (bitbuf, 1);

    get_bits (bitbuf, 4);

    get_bits (bitbuf, 1);

    get_bits (bitbuf, 2);

    while (get_bits (bitbuf, 1) == 1) {

      get_bits (bitbuf, 8);

    }

  }

  return 0;

}


static void posix_aio_read(void *opaque)

{

    PosixAioState *s = opaque;

    RawAIOCB *acb, **pacb;

    int ret;

    ssize_t len;

    /* read all bytes from signal pipe */

    for (;;) {

        char bytes[16];

        len = read(s->rfd, bytes, sizeof(bytes));

        if (len == -1 && errno == EINTR)

            continue; /* try again */

        if (len == sizeof(bytes))

            continue; /* more to read */

        break;

    }

    for(;;) {

        pacb = &s->first_aio;

        for(;;) {

            acb = *pacb;

            if (!acb)

                goto the_end;

            ret = aio_error(&acb->aiocb);

            if (ret == ECANCELED) {

                /* remove the request */

                *pacb = acb->next;

                raw_fd_pool_put(acb);

                qemu_aio_release(acb);

            } else if (ret != EINPROGRESS) {

                /* end of aio */

                if (ret == 0) {

                    ret = aio_return(&acb->aiocb);

                    if (ret == acb->aiocb.aio_nbytes)

                        ret = 0;

                    else

                        ret = -EINVAL;

                } else {

                    ret = -ret;

                }

                /* remove the request */

                *pacb = acb->next;

                /* call the callback */

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

                raw_fd_pool_put(acb);

                qemu_aio_release(acb);

                break;

            } else {

                pacb = &acb->next;

            }

        }

    }

 the_end: ;

}


static int usbredir_handle_data(USBDevice *udev, USBPacket *p)

{

    USBRedirDevice *dev = DO_UPCAST(USBRedirDevice, dev, udev);

    uint8_t ep;

    ep = p->devep;

    if (p->pid == USB_TOKEN_IN) {

        ep |= USB_DIR_IN;

    }

    switch (dev->endpoint[EP2I(ep)].type) {

    case USB_ENDPOINT_XFER_CONTROL:

        ERROR("handle_data called for control transfer on ep %02X\n", ep);

        return USB_RET_NAK;

    case USB_ENDPOINT_XFER_ISOC:

        return usbredir_handle_iso_data(dev, p, ep);

    case USB_ENDPOINT_XFER_BULK:

        return usbredir_handle_bulk_data(dev, p, ep);

    case USB_ENDPOINT_XFER_INT:

        return usbredir_handle_interrupt_data(dev, p, ep);

    default:

        ERROR("handle_data ep %02X has unknown type %d\n", ep,

              dev->endpoint[EP2I(ep)].type);

        return USB_RET_NAK;

    }

}


int kvm_s390_vcpu_interrupt_post_load(S390CPU *cpu)

{

    CPUState *cs = CPU(cpu);

    struct kvm_s390_irq_state irq_state;

    int r;

    if (!kvm_check_extension(kvm_state, KVM_CAP_S390_IRQ_STATE)) {

        return -ENOSYS;

    }

    if (cpu->irqstate_saved_size == 0) {

        return 0;

    }

    irq_state.buf = (uint64_t) cpu->irqstate;

    irq_state.len = cpu->irqstate_saved_size;

    r = kvm_vcpu_ioctl(cs, KVM_S390_SET_IRQ_STATE, &irq_state);

    if (r) {

        error_report("Setting interrupt state failed %d", r);

    }

    return r;

}


void do_info_roms(Monitor *mon)

{

    Rom *rom;

    QTAILQ_FOREACH(rom, &roms, next) {

        if (!rom->fw_file) {

            monitor_printf(mon, "addr=" TARGET_FMT_plx

                           " size=0x%06zx mem=%s name=\"%s\" \n",

                           rom->addr, rom->romsize,

                           rom->isrom ? "rom" : "ram",

                           rom->name);

        } else {

            monitor_printf(mon, "fw=%s%s%s"

                           " size=0x%06zx name=\"%s\" \n",

                           rom->fw_dir ? rom->fw_dir : "",

                           rom->fw_dir ? "/" : "",

                           rom->fw_file,

                           rom->romsize,

                           rom->name);

        }

    }

}


static void do_smbios_option(const char *optarg)

{

    if (smbios_entry_add(optarg) < 0) {

        fprintf(stderr, "Wrong smbios provided\n");

        exit(1);

    }

}


static ExitStatus gen_store_conditional(DisasContext *ctx, int ra, int rb,

                                        int32_t disp16, int quad)

{

    TCGv addr;

    if (ra == 31) {

        /* ??? Don't bother storing anything.  The user can't tell

           the difference, since the zero register always reads zero.  */

        return NO_EXIT;

    }

#if defined(CONFIG_USER_ONLY)

    addr = cpu_lock_st_addr;

#else

    addr = tcg_temp_local_new();

#endif

    tcg_gen_addi_i64(addr, load_gpr(ctx, rb), disp16);

#if defined(CONFIG_USER_ONLY)

    /* ??? This is handled via a complicated version of compare-and-swap

       in the cpu_loop.  Hopefully one day we'll have a real CAS opcode

       in TCG so that this isn't necessary.  */

    return gen_excp(ctx, quad ? EXCP_STQ_C : EXCP_STL_C, ra);

#else

    /* ??? In system mode we are never multi-threaded, so CAS can be

       implemented via a non-atomic load-compare-store sequence.  */

    {

        int lab_fail, lab_done;

        TCGv val;

        lab_fail = gen_new_label();

        lab_done = gen_new_label();

        tcg_gen_brcond_i64(TCG_COND_NE, addr, cpu_lock_addr, lab_fail);

        val = tcg_temp_new();

        tcg_gen_qemu_ld_i64(val, addr, ctx->mem_idx, quad ? MO_LEQ : MO_LESL);

        tcg_gen_brcond_i64(TCG_COND_NE, val, cpu_lock_value, lab_fail);

        tcg_gen_qemu_st_i64(cpu_ir[ra], addr, ctx->mem_idx,

                            quad ? MO_LEQ : MO_LEUL);

        tcg_gen_movi_i64(cpu_ir[ra], 1);

        tcg_gen_br(lab_done);

        gen_set_label(lab_fail);

        tcg_gen_movi_i64(cpu_ir[ra], 0);

        gen_set_label(lab_done);

        tcg_gen_movi_i64(cpu_lock_addr, -1);

        tcg_temp_free(addr);

        return NO_EXIT;

    }

#endif

}


static int mp_pacl_setxattr(FsContext *ctx, const char *path, const char *name,

                            void *value, size_t size, int flags)

{

    char buffer[PATH_MAX];

    return lsetxattr(rpath(ctx, path, buffer), MAP_ACL_ACCESS, value,

            size, flags);

}


static int mkv_write_attachments(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

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

    ebml_master attachments;

    AVLFG c;

    int i, ret;

    if (!mkv->have_attachments)

        return 0;

    mkv->attachments = av_mallocz(sizeof(*mkv->attachments));

    if (!mkv->attachments)

        return ret;

    av_lfg_init(&c, av_get_random_seed());

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

    if (ret < 0) return ret;

    ret = start_ebml_master_crc32(pb, &dyn_cp, &attachments, MATROSKA_ID_ATTACHMENTS, 0);

    if (ret < 0) return ret;

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

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

        ebml_master attached_file;

        mkv_attachment *attachment = mkv->attachments->entries;

        AVDictionaryEntry *t;

        const char *mimetype = NULL;

        uint32_t fileuid;

        if (st->codecpar->codec_type != AVMEDIA_TYPE_ATTACHMENT)

            continue;

        attachment = av_realloc_array(attachment, mkv->attachments->num_entries + 1, sizeof(mkv_attachment));

        if (!attachment)

            return AVERROR(ENOMEM);

        mkv->attachments->entries = attachment;

        attached_file = start_ebml_master(dyn_cp, MATROSKA_ID_ATTACHEDFILE, 0);

        if (t = av_dict_get(st->metadata, "title", NULL, 0))

            put_ebml_string(dyn_cp, MATROSKA_ID_FILEDESC, t->value);

        if (!(t = av_dict_get(st->metadata, "filename", NULL, 0))) {

            av_log(s, AV_LOG_ERROR, "Attachment stream %d has no filename tag.\n", i);

            return AVERROR(EINVAL);

        }

        put_ebml_string(dyn_cp, MATROSKA_ID_FILENAME, t->value);

        if (t = av_dict_get(st->metadata, "mimetype", NULL, 0))

            mimetype = t->value;

        else if (st->codecpar->codec_id != AV_CODEC_ID_NONE ) {

            int i;

            for (i = 0; ff_mkv_mime_tags[i].id != AV_CODEC_ID_NONE; i++)

                if (ff_mkv_mime_tags[i].id == st->codecpar->codec_id) {

                    mimetype = ff_mkv_mime_tags[i].str;

                    break;

                }

            for (i = 0; ff_mkv_image_mime_tags[i].id != AV_CODEC_ID_NONE; i++)

                if (ff_mkv_image_mime_tags[i].id == st->codecpar->codec_id) {

                    mimetype = ff_mkv_image_mime_tags[i].str;

                    break;

                }

        }

        if (!mimetype) {

            av_log(s, AV_LOG_ERROR, "Attachment stream %d has no mimetype tag and "

                                    "it cannot be deduced from the codec id.\n", i);

            return AVERROR(EINVAL);

        }

        if (s->flags & AVFMT_FLAG_BITEXACT) {

            struct AVSHA *sha = av_sha_alloc();

            uint8_t digest[20];

            if (!sha)

                return AVERROR(ENOMEM);

            av_sha_init(sha, 160);

            av_sha_update(sha, st->codecpar->extradata, st->codecpar->extradata_size);

            av_sha_final(sha, digest);

            av_free(sha);

            fileuid = AV_RL32(digest);

        } else {

            fileuid = av_lfg_get(&c);

        }

        av_log(s, AV_LOG_VERBOSE, "Using %.8"PRIx32" for attachment %d\n",

               fileuid, mkv->attachments->num_entries);

        put_ebml_string(dyn_cp, MATROSKA_ID_FILEMIMETYPE, mimetype);

        put_ebml_binary(dyn_cp, MATROSKA_ID_FILEDATA, st->codecpar->extradata, st->codecpar->extradata_size);

        put_ebml_uint(dyn_cp, MATROSKA_ID_FILEUID, fileuid);

        end_ebml_master(dyn_cp, attached_file);

        mkv->attachments->entries[mkv->attachments->num_entries].stream_idx = i;

        mkv->attachments->entries[mkv->attachments->num_entries++].fileuid  = fileuid;

    }

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

    return 0;

}


static void spr_write_dbatu (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_dbatu((sprn - SPR_DBAT0U) / 2);

    RET_STOP(ctx);

}


void vga_hw_invalidate(void)

{

    if (active_console->hw_invalidate)

        active_console->hw_invalidate(active_console->hw);

}


static uint32_t pmac_ide_readw (void *opaque,target_phys_addr_t addr)

{

    uint16_t retval;

    MACIOIDEState *d = opaque;

    addr = (addr & 0xFFF) >> 4;

    if (addr == 0) {

        retval = ide_data_readw(&d->bus, 0);

    } else {

        retval = 0xFFFF;

    }

    retval = bswap16(retval);

    return retval;

}


DeviceState *pxa2xx_gpio_init(target_phys_addr_t base,

                CPUState *env, qemu_irq *pic, int lines)

{

    DeviceState *dev;

    dev = qdev_create(NULL, "pxa2xx-gpio");

    qdev_prop_set_int32(dev, "lines", lines);

    qdev_prop_set_int32(dev, "ncpu", env->cpu_index);

    qdev_init_nofail(dev);

    sysbus_mmio_map(sysbus_from_qdev(dev), 0, base);

    sysbus_connect_irq(sysbus_from_qdev(dev), 0, pic[PXA2XX_PIC_GPIO_0]);

    sysbus_connect_irq(sysbus_from_qdev(dev), 1, pic[PXA2XX_PIC_GPIO_1]);

    sysbus_connect_irq(sysbus_from_qdev(dev), 2, pic[PXA2XX_PIC_GPIO_X]);

    return dev;

}


static void v9fs_renameat(void *opaque)

{

    ssize_t err = 0;

    size_t offset = 7;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    int32_t olddirfid, newdirfid;

    V9fsString old_name, new_name;

    pdu_unmarshal(pdu, offset, "dsds", &olddirfid,

                  &old_name, &newdirfid, &new_name);

    v9fs_path_write_lock(s);

    err = v9fs_complete_renameat(pdu, olddirfid,

                                 &old_name, newdirfid, &new_name);

    v9fs_path_unlock(s);

    if (!err) {

        err = offset;

    }

    complete_pdu(s, pdu, err);

    v9fs_string_free(&old_name);

    v9fs_string_free(&new_name);

}


static int ssi_sd_init(SSISlave *d)

{

    DeviceState *dev = DEVICE(d);

    ssi_sd_state *s = FROM_SSI_SLAVE(ssi_sd_state, d);

    DriveInfo *dinfo;

    s->mode = SSI_SD_CMD;

    dinfo = drive_get_next(IF_SD);

    s->sd = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, true);

    if (s->sd == NULL) {

        return -1;

    }

    register_savevm(dev, "ssi_sd", -1, 1, ssi_sd_save, ssi_sd_load, s);

    return 0;

}


static int vfio_mmap_bar(VFIOBAR *bar, MemoryRegion *mem, MemoryRegion *submem,

                         void **map, size_t size, off_t offset,

                         const char *name)

{

    int ret = 0;

    if (size && bar->flags & VFIO_REGION_INFO_FLAG_MMAP) {

        int prot = 0;

        if (bar->flags & VFIO_REGION_INFO_FLAG_READ) {

            prot |= PROT_READ;

        }

        if (bar->flags & VFIO_REGION_INFO_FLAG_WRITE) {

            prot |= PROT_WRITE;

        }

        *map = mmap(NULL, size, prot, MAP_SHARED,

                    bar->fd, bar->fd_offset + offset);

        if (*map == MAP_FAILED) {

            *map = NULL;

            ret = -errno;

            goto empty_region;

        }

        memory_region_init_ram_ptr(submem, name, size, *map);

    } else {

empty_region:

        /* Create a zero sized sub-region to make cleanup easy. */

        memory_region_init(submem, name, 0);

    }

    memory_region_add_subregion(mem, offset, submem);

    return ret;

}


int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic){

    AVFrame temp_pic;

    int i;

    assert(s->codec_type == AVMEDIA_TYPE_VIDEO);

    if (pic->data[0] && (pic->width != s->width || pic->height != s->height || pic->format != s->pix_fmt)) {

        av_log(s, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",

               pic->width, pic->height, av_get_pix_fmt_name(pic->format), s->width, s->height, av_get_pix_fmt_name(s->pix_fmt));

        s->release_buffer(s, pic);

    }

    /* If no picture return a new buffer */

    if(pic->data[0] == NULL) {

        /* We will copy from buffer, so must be readable */

        pic->buffer_hints |= FF_BUFFER_HINTS_READABLE;

        return s->get_buffer(s, pic);

    }

    /* If internal buffer type return the same buffer */

    if(pic->type == FF_BUFFER_TYPE_INTERNAL) {

        if(s->pkt) pic->pkt_pts= s->pkt->pts;

        else       pic->pkt_pts= AV_NOPTS_VALUE;

        pic->reordered_opaque= s->reordered_opaque;

        return 0;

    }

    /*

     * Not internal type and reget_buffer not overridden, emulate cr buffer

     */

    temp_pic = *pic;

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

        pic->data[i] = pic->base[i] = NULL;

    pic->opaque = NULL;

    /* Allocate new frame */

    if (s->get_buffer(s, pic))

        return -1;

    /* Copy image data from old buffer to new buffer */

    av_picture_copy((AVPicture*)pic, (AVPicture*)&temp_pic, s->pix_fmt, s->width,

             s->height);

    s->release_buffer(s, &temp_pic); // Release old frame

    return 0;

}


void helper_ldfsr(CPUSPARCState *env, uint32_t new_fsr)

{

    env->fsr = (new_fsr & FSR_LDFSR_MASK) | (env->fsr & FSR_LDFSR_OLDMASK);

    set_fsr(env);

}


void qemu_thread_self(QemuThread *thread)

{

    thread->thread = pthread_self();

}


static int create_shared_memory_BAR(IVShmemState *s, int fd, uint8_t attr,

                                    Error **errp)

{

    void * ptr;

    ptr = mmap(0, s->ivshmem_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    if (ptr == MAP_FAILED) {

        error_setg_errno(errp, errno, "Failed to mmap shared memory");

        return -1;

    }

    s->shm_fd = fd;

    memory_region_init_ram_ptr(&s->ivshmem, OBJECT(s), "ivshmem.bar2",

                               s->ivshmem_size, ptr);

    vmstate_register_ram(&s->ivshmem, DEVICE(s));

    memory_region_add_subregion(&s->bar, 0, &s->ivshmem);

    /* region for shared memory */

    pci_register_bar(PCI_DEVICE(s), 2, attr, &s->bar);

    return 0;

}


static av_always_inline int vc1_filter_line(uint8_t* src, int stride, int pq){

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int a0 = (2*(src[-2*stride] - src[ 1*stride]) - 5*(src[-1*stride] - src[ 0*stride]) + 4) >> 3;

    int a0_sign = a0 >> 31;        /* Store sign */

    a0 = (a0 ^ a0_sign) - a0_sign; /* a0 = FFABS(a0); */

    if(a0 < pq){

        int a1 = FFABS((2*(src[-4*stride] - src[-1*stride]) - 5*(src[-3*stride] - src[-2*stride]) + 4) >> 3);

        int a2 = FFABS((2*(src[ 0*stride] - src[ 3*stride]) - 5*(src[ 1*stride] - src[ 2*stride]) + 4) >> 3);

        if(a1 < a0 || a2 < a0){

            int clip = src[-1*stride] - src[ 0*stride];

            int clip_sign = clip >> 31;

            clip = ((clip ^ clip_sign) - clip_sign)>>1;

            if(clip){

                int a3 = FFMIN(a1, a2);

                int d = 5 * (a3 - a0);

                int d_sign = (d >> 31);

                d = ((d ^ d_sign) - d_sign) >> 3;

                d_sign ^= a0_sign;

                if( d_sign ^ clip_sign )

                    d = 0;

                else{

                    d = FFMIN(d, clip);

                    d = (d ^ d_sign) - d_sign;          /* Restore sign */

                    src[-1*stride] = cm[src[-1*stride] - d];

                    src[ 0*stride] = cm[src[ 0*stride] + d];

                }

                return 1;

            }

        }

    }

    return 0;

}


static AVCodec *choose_codec(OptionsContext *o, AVFormatContext *s, AVStream *st, enum AVMediaType type)

{

    char *codec_name = NULL;

    MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);

    if (!codec_name) {

        if (s->oformat) {

            st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename, NULL, type);

            return avcodec_find_encoder(st->codec->codec_id);

        }

    } else if (!strcmp(codec_name, "copy"))

        st->stream_copy = 1;

    else {

        st->codec->codec_id = find_codec_or_die(codec_name, type, s->iformat == NULL);

        return s->oformat ? avcodec_find_encoder_by_name(codec_name) :

                            avcodec_find_decoder_by_name(codec_name);

    }

    return NULL;

}


static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeCmd *cmd)

{

    NvmeCQueue *cq;

    NvmeCreateCq *c = (NvmeCreateCq *)cmd;

    uint16_t cqid = le16_to_cpu(c->cqid);

    uint16_t vector = le16_to_cpu(c->irq_vector);

    uint16_t qsize = le16_to_cpu(c->qsize);

    uint16_t qflags = le16_to_cpu(c->cq_flags);

    uint64_t prp1 = le64_to_cpu(c->prp1);

    if (!cqid || !nvme_check_cqid(n, cqid)) {

        return NVME_INVALID_CQID | NVME_DNR;

    }

    if (!qsize || qsize > NVME_CAP_MQES(n->bar.cap)) {

        return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;

    }

    if (!prp1) {

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    if (vector > n->num_queues) {

        return NVME_INVALID_IRQ_VECTOR | NVME_DNR;

    }

    if (!(NVME_CQ_FLAGS_PC(qflags))) {

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    cq = g_malloc0(sizeof(*cq));

    nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,

        NVME_CQ_FLAGS_IEN(qflags));

    return NVME_SUCCESS;

}


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

                                        int16_t *src2,

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

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

{

    int x, y;

    pixel *src = (pixel *)_src;

    ptrdiff_t srcstride = _srcstride / sizeof(pixel);

    pixel *dst          = (pixel *)_dst;

    ptrdiff_t dststride = _dststride / sizeof(pixel);

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

    int16_t tmp_array[(MAX_PB_SIZE + EPEL_EXTRA) * MAX_PB_SIZE];

    int16_t *tmp = tmp_array;

    int shift = 14 + 1 - BIT_DEPTH;

    int log2Wd = denom + shift - 1;

    src -= EPEL_EXTRA_BEFORE * srcstride;

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

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

            tmp[x] = EPEL_FILTER(src, 1) >> (BIT_DEPTH - 8);

        src += srcstride;

        tmp += MAX_PB_SIZE;

    }

    tmp      = tmp_array + EPEL_EXTRA_BEFORE * MAX_PB_SIZE;

    filter = ff_hevc_epel_filters[my - 1];

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

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

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

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

            dst[x] = av_clip_pixel(((EPEL_FILTER(tmp, MAX_PB_SIZE) >> 6) * wx1 + src2[x] * wx0 +

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

        tmp  += MAX_PB_SIZE;

        dst  += dststride;

        src2 += MAX_PB_SIZE;

    }

}


static int vc1_decode_p_mb(VC1Context *v, DCTELEM block[6][64])

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int cbp; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int status;

    static const int size_table[6] = { 0, 2, 3, 4, 5, 8 },

      offset_table[6] = { 0, 1, 3, 7, 15, 31 };

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int index, index1; /* LUT indices */

    int val, sign; /* temp values */

    int first_block = 1;

    int dst_idx, off;

    int skipped, fourmv;

    mquant = v->pq; /* Loosy initialization */

    if (v->mv_type_is_raw)

        fourmv = get_bits1(gb);

    else

        fourmv = v->mv_type_mb_plane[mb_pos];

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    s->dsp.clear_blocks(s->block[0]);

    if (!fourmv) /* 1MV mode */

    {

        if (!skipped)

        {

            GET_MVDATA(dmv_x, dmv_y);

            s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;

            vc1_pred_mv(s, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);

            /* FIXME Set DC val for inter block ? */

            if (s->mb_intra && !mb_has_coeffs)

            {

                GET_MQUANT();

                s->ac_pred = get_bits(gb, 1);

                cbp = 0;

            }

            else if (mb_has_coeffs)

            {

                if (s->mb_intra) s->ac_pred = get_bits(gb, 1);

                cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

                GET_MQUANT();

            }

            else

            {

                mquant = v->pq;

                cbp = 0;

            }

            s->current_picture.qscale_table[mb_pos] = mquant;

            if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)

                ttmb = get_vlc2(gb, vc1_ttmb_vlc[v->tt_index].table,

                                VC1_TTMB_VLC_BITS, 2);

            if(!s->mb_intra) vc1_mc_1mv(v);

            dst_idx = 0;

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

            {

                s->dc_val[0][s->block_index[i]] = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                v->mb_type[0][s->block_index[i]] = s->mb_intra;

                if(s->mb_intra) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || s->mb_y)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, block[i], i, val, mquant, (i&4)?v->codingset2:v->codingset);

                    vc1_inv_trans(block[i], 8, 8);

                    for(j = 0; j < 64; j++) block[i][j] += 128;

                    s->dsp.put_pixels_clamped(block[i], s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                    /* TODO: proper loop filtering */

                    if(v->pq >= 9 && v->overlap) {

                        if(v->a_avail)

                            s->dsp.h263_v_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                        if(v->c_avail)

                            s->dsp.h263_h_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                    }

                } else if(val) {

                    vc1_decode_p_block(v, block[i], i, mquant, ttmb, first_block);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                    s->dsp.add_pixels_clamped(block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                }

            }

        }

        else //Skipped

        {

            s->mb_intra = 0;

            for(i = 0; i < 6; i++) v->mb_type[0][s->block_index[i]] = 0;

            s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;

            s->current_picture.qscale_table[mb_pos] = 0;

            vc1_pred_mv(s, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);

            vc1_mc_1mv(v);

            return 0;

        }

    } //1MV mode

    else //4MV mode

    {

        if (!skipped /* unskipped MB */)

        {

            int intra_count = 0, coded_inter = 0;

            int is_intra[6], is_coded[6];

            /* Get CBPCY */

            cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

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

            {

                val = ((cbp >> (5 - i)) & 1);

                s->dc_val[0][s->block_index[i]] = 0;

                s->mb_intra = 0;

                if(i < 4) {

                    dmv_x = dmv_y = 0;

                    s->mb_intra = 0;

                    mb_has_coeffs = 0;

                    if(val) {

                        GET_MVDATA(dmv_x, dmv_y);

                    }

                    vc1_pred_mv(s, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);

                    if(!s->mb_intra) vc1_mc_4mv_luma(v, i);

                    intra_count += s->mb_intra;

                    is_intra[i] = s->mb_intra;

                    is_coded[i] = mb_has_coeffs;

                }

                if(i&4){

                    is_intra[i] = (intra_count >= 3);

                    is_coded[i] = val;

                }

                if(i == 4) vc1_mc_4mv_chroma(v);

                v->mb_type[0][s->block_index[i]] = is_intra[i];

                if(!coded_inter) coded_inter = !is_intra[i] & is_coded[i];

            }

            dst_idx = 0;

            GET_MQUANT();

            s->current_picture.qscale_table[mb_pos] = mquant;

            /* test if block is intra and has pred */

            {

                int intrapred = 0;

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

                    if(is_intra[i]) {

                        if(v->mb_type[0][s->block_index[i] - s->block_wrap[i]] || v->mb_type[0][s->block_index[i] - 1]) {

                            intrapred = 1;

                            break;

                        }

                    }

                if(intrapred)s->ac_pred = get_bits(gb, 1);

                else s->ac_pred = 0;

            }

            if (!v->ttmbf && coded_inter)

                ttmb = get_vlc2(gb, vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 12);

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

            {

                dst_idx += i >> 2;

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                s->mb_intra = is_intra[i];

                if (is_intra[i]) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || s->mb_y)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, s->block[i], i, is_coded[i], mquant, (i&4)?v->codingset2:v->codingset);

                    vc1_inv_trans(block[i], 8, 8);

                    for(j = 0; j < 64; j++) block[i][j] += 128;

                    s->dsp.put_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                    /* TODO: proper loop filtering */

                    if(v->pq >= 9 && v->overlap) {

                        if(v->a_avail)

                            s->dsp.h263_v_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                        if(v->c_avail)

                            s->dsp.h263_h_loop_filter(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2), s->y_dc_scale);

                    }

                } else if(is_coded[i]) {

                    status = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                    s->dsp.add_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                }

            }

            return status;

        }

        else //Skipped MB

        {

            s->mb_intra = 0;

            for (i=0; i<6; i++) v->mb_type[0][s->block_index[i]] = 0;

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

            {

                vc1_pred_mv(s, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0]);

                vc1_mc_4mv_luma(v, i);

            }

            vc1_mc_4mv_chroma(v);

            s->current_picture.qscale_table[mb_pos] = 0;

            return 0;

        }

    }

    /* Should never happen */

    return -1;

}


void qemu_co_rwlock_rdlock(CoRwlock *lock)
{
    while (lock->writer) {
        qemu_co_queue_wait(&lock->queue);
    }
    lock->reader++;
}


static Qcow2BitmapList *bitmap_list_load(BlockDriverState *bs, uint64_t offset,

                                         uint64_t size, Error **errp)

{

    int ret;

    BDRVQcow2State *s = bs->opaque;

    uint8_t *dir, *dir_end;

    Qcow2BitmapDirEntry *e;

    uint32_t nb_dir_entries = 0;

    Qcow2BitmapList *bm_list = NULL;

    if (size == 0) {

        error_setg(errp, "Requested bitmap directory size is zero");

        return NULL;

    }

    if (size > QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {

        error_setg(errp, "Requested bitmap directory size is too big");

        return NULL;

    }

    dir = g_try_malloc(size);

    if (dir == NULL) {

        error_setg(errp, "Failed to allocate space for bitmap directory");

        return NULL;

    }

    dir_end = dir + size;

    ret = bdrv_pread(bs->file, offset, dir, size);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Failed to read bitmap directory");

        goto fail;

    }

    bm_list = bitmap_list_new();

    for (e = (Qcow2BitmapDirEntry *)dir;

         e < (Qcow2BitmapDirEntry *)dir_end;

         e = next_dir_entry(e))

    {

        Qcow2Bitmap *bm;

        if ((uint8_t *)(e + 1) > dir_end) {

            goto broken_dir;

        }

        if (++nb_dir_entries > s->nb_bitmaps) {

            error_setg(errp, "More bitmaps found than specified in header"

                       " extension");

            goto fail;

        }

        bitmap_dir_entry_to_cpu(e);

        if ((uint8_t *)next_dir_entry(e) > dir_end) {

            goto broken_dir;

        }

        if (e->extra_data_size != 0) {

            error_setg(errp, "Bitmap extra data is not supported");

            goto fail;

        }

        ret = check_dir_entry(bs, e);

        if (ret < 0) {

            error_setg(errp, "Bitmap '%.*s' doesn't satisfy the constraints",

                       e->name_size, dir_entry_name_field(e));

            goto fail;

        }

        bm = g_new(Qcow2Bitmap, 1);

        bm->table.offset = e->bitmap_table_offset;

        bm->table.size = e->bitmap_table_size;

        bm->flags = e->flags;

        bm->granularity_bits = e->granularity_bits;

        bm->name = dir_entry_copy_name(e);

        QSIMPLEQ_INSERT_TAIL(bm_list, bm, entry);

    }

    if (nb_dir_entries != s->nb_bitmaps) {

        error_setg(errp, "Less bitmaps found than specified in header"

                         " extension");

        goto fail;

    }

    if ((uint8_t *)e != dir_end) {

        goto broken_dir;

    }

    g_free(dir);

    return bm_list;

broken_dir:

    ret = -EINVAL;

    error_setg(errp, "Broken bitmap directory");

fail:

    g_free(dir);

    bitmap_list_free(bm_list);

    return NULL;

}


static void test_copy(const AVCodec *c1, const AVCodec *c2)

{

    AVCodecContext *ctx1, *ctx2;

    printf("%s -> %s\nclosed:\n", c1 ? c1->name : "NULL", c2 ? c2->name : "NULL");

    ctx1 = avcodec_alloc_context3(c1);

    ctx2 = avcodec_alloc_context3(c2);

    ctx1->width = ctx1->height = 128;

    if (ctx2->codec && ctx2->codec->priv_class && ctx2->codec->priv_data_size) {

        av_opt_set(ctx2->priv_data, "num", "667", 0);

        av_opt_set(ctx2->priv_data, "str", "i'm dest value before copy", 0);

    }

    avcodec_copy_context(ctx2, ctx1);

    test_copy_print_codec(ctx1);

    test_copy_print_codec(ctx2);

    if (ctx1->codec) {

        printf("opened:\n");

        avcodec_open2(ctx1, ctx1->codec, NULL);

        if (ctx2->codec && ctx2->codec->priv_class && ctx2->codec->priv_data_size) {

            av_opt_set(ctx2->priv_data, "num", "667", 0);

            av_opt_set(ctx2->priv_data, "str", "i'm dest value before copy", 0);

        }

        avcodec_copy_context(ctx2, ctx1);

        test_copy_print_codec(ctx1);

        test_copy_print_codec(ctx2);

        avcodec_close(ctx1);

    }

    avcodec_free_context(&ctx1);

    avcodec_free_context(&ctx2);

}


static int process_audio_header_elements(AVFormatContext *s)

{

    int inHeader = 1;

    EaDemuxContext *ea = s->priv_data;

    ByteIOContext *pb = &s->pb;

    int compression_type;

    ea->num_channels = 1;

    while (inHeader) {

        int inSubheader;

        uint8_t byte;

        byte = get_byte(pb);

        switch (byte) {

        case 0xFD:

            av_log (s, AV_LOG_INFO, "entered audio subheader\n");

            inSubheader = 1;

            while (inSubheader) {

                uint8_t subbyte;

                subbyte = get_byte(pb);

                switch (subbyte) {

                case 0x82:

                    ea->num_channels = read_arbitary(pb);

                    av_log (s, AV_LOG_INFO, "num_channels (element 0x82) set to 0x%08x\n", ea->num_channels);

                    break;

                case 0x83:

                    compression_type = read_arbitary(pb);

                    av_log (s, AV_LOG_INFO, "compression_type (element 0x83) set to 0x%08x\n", compression_type);

                    break;

                case 0x85:

                    ea->num_samples = read_arbitary(pb);

                    av_log (s, AV_LOG_INFO, "num_samples (element 0x85) set to 0x%08x\n", ea->num_samples);

                    break;

                case 0x8A:

                    av_log (s, AV_LOG_INFO, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb));

                    av_log (s, AV_LOG_INFO, "exited audio subheader\n");

                    inSubheader = 0;

                    break;

                case 0xFF:

                    av_log (s, AV_LOG_INFO, "end of header block reached (within audio subheader)\n");

                    inSubheader = 0;

                    inHeader = 0;

                    break;

                default:

                    av_log (s, AV_LOG_INFO, "element 0x%02x set to 0x%08x\n", subbyte, read_arbitary(pb));

                    break;

                }

            }

            break;

        case 0xFF:

            av_log (s, AV_LOG_INFO, "end of header block reached\n");

            inHeader = 0;

            break;

        default:

            av_log (s, AV_LOG_INFO, "header element 0x%02x set to 0x%08x\n", byte, read_arbitary(pb));

            break;

        }

    }

    ea->audio_codec = CODEC_ID_ADPCM_EA;

    return 1;

}


static int vc1_decode_b_mb_intfr(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int cbp = 0; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int mvsw = 0; /* motion vector switch */

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int val; /* temp value */

    int first_block = 1;

    int dst_idx, off;

    int skipped, direct, twomv = 0;

    int block_cbp = 0, pat, block_tt = 0;

    int idx_mbmode = 0, mvbp;

    int stride_y, fieldtx;

    int bmvtype = BMV_TYPE_BACKWARD;

    int dir, dir2;

    mquant = v->pq; /* Lossy initialization */

    s->mb_intra = 0;

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    if (!skipped) {

        idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2);

        if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {

            twomv = 1;

            v->blk_mv_type[s->block_index[0]] = 1;

            v->blk_mv_type[s->block_index[1]] = 1;

            v->blk_mv_type[s->block_index[2]] = 1;

            v->blk_mv_type[s->block_index[3]] = 1;

        } else {

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

        }

    }

    if (v->dmb_is_raw)

        direct = get_bits1(gb);

    else

        direct = v->direct_mb_plane[mb_pos];

    if (direct) {

        s->mv[0][0][0] = s->current_picture.motion_val[0][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 0, s->quarter_sample);

        s->mv[0][0][1] = s->current_picture.motion_val[0][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 0, s->quarter_sample);

        s->mv[1][0][0] = s->current_picture.motion_val[1][s->block_index[0]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][0], v->bfraction, 1, s->quarter_sample);

        s->mv[1][0][1] = s->current_picture.motion_val[1][s->block_index[0]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[0]][1], v->bfraction, 1, s->quarter_sample);

        if (twomv) {

            s->mv[0][2][0] = s->current_picture.motion_val[0][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 0, s->quarter_sample);

            s->mv[0][2][1] = s->current_picture.motion_val[0][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 0, s->quarter_sample);

            s->mv[1][2][0] = s->current_picture.motion_val[1][s->block_index[2]][0] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][0], v->bfraction, 1, s->quarter_sample);

            s->mv[1][2][1] = s->current_picture.motion_val[1][s->block_index[2]][1] = scale_mv(s->next_picture.motion_val[1][s->block_index[2]][1], v->bfraction, 1, s->quarter_sample);

            for (i = 1; i < 4; i += 2) {

                s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][i-1][0];

                s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][i-1][1];

                s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][i-1][0];

                s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][i-1][1];

            }

        } else {

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

                s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = s->mv[0][0][0];

                s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = s->mv[0][0][1];

                s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = s->mv[1][0][0];

                s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = s->mv[1][0][1];

            }

        }

    }

    if (ff_vc1_mbmode_intfrp[0][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB

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

            s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0] = 0;

            s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1] = 0;

            s->mv[1][i][0] = s->current_picture.motion_val[1][s->block_index[i]][0] = 0;

            s->mv[1][i][1] = s->current_picture.motion_val[1][s->block_index[i]][1] = 0;

        }

        s->current_picture.mb_type[mb_pos] = MB_TYPE_INTRA;

        s->mb_intra = v->is_intra[s->mb_x] = 1;

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

            v->mb_type[0][s->block_index[i]] = 1;

        fieldtx = v->fieldtx_plane[mb_pos] = get_bits1(gb);

        mb_has_coeffs = get_bits1(gb);

        if (mb_has_coeffs)

            cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

        v->s.ac_pred = v->acpred_plane[mb_pos] = get_bits1(gb);

        GET_MQUANT();

        s->current_picture.qscale_table[mb_pos] = mquant;

        /* Set DC scale - y and c use the same (not sure if necessary here) */

        s->y_dc_scale = s->y_dc_scale_table[mquant];

        s->c_dc_scale = s->c_dc_scale_table[mquant];

        dst_idx = 0;

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

            s->dc_val[0][s->block_index[i]] = 0;

            dst_idx += i >> 2;

            val = ((cbp >> (5 - i)) & 1);

            v->mb_type[0][s->block_index[i]] = s->mb_intra;

            v->a_avail = v->c_avail = 0;

            if (i == 2 || i == 3 || !s->first_slice_line)

                v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

            if (i == 1 || i == 3 || s->mb_x)

                v->c_avail = v->mb_type[0][s->block_index[i] - 1];

            vc1_decode_intra_block(v, s->block[i], i, val, mquant,

                                   (i & 4) ? v->codingset2 : v->codingset);

            if (i > 3 && (s->flags & CODEC_FLAG_GRAY))

                continue;

            v->vc1dsp.vc1_inv_trans_8x8(s->block[i]);

            if (i < 4) {

                stride_y = s->linesize << fieldtx;

                off = (fieldtx) ? ((i & 1) * 8) + ((i & 2) >> 1) * s->linesize : (i & 1) * 8 + 4 * (i & 2) * s->linesize;

            } else {

                stride_y = s->uvlinesize;

                off = 0;

            }

            s->idsp.put_signed_pixels_clamped(s->block[i],

                                              s->dest[dst_idx] + off,

                                              stride_y);

        }

    } else {

        s->mb_intra = v->is_intra[s->mb_x] = 0;

        if (!direct) {

            if (skipped || !s->mb_intra) {

                bmvtype = decode012(gb);

                switch (bmvtype) {

                case 0:

                    bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_BACKWARD : BMV_TYPE_FORWARD;

                    break;

                case 1:

                    bmvtype = (v->bfraction >= (B_FRACTION_DEN/2)) ? BMV_TYPE_FORWARD : BMV_TYPE_BACKWARD;

                    break;

                case 2:

                    bmvtype  = BMV_TYPE_INTERPOLATED;

                }

            }

            if (twomv && bmvtype != BMV_TYPE_INTERPOLATED)

                mvsw = get_bits1(gb);

        }

        if (!skipped) { // inter MB

            mb_has_coeffs = ff_vc1_mbmode_intfrp[0][idx_mbmode][3];

            if (mb_has_coeffs)

                cbp = 1 + get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

            if (!direct) {

                if (bmvtype == BMV_TYPE_INTERPOLATED && twomv) {

                    v->fourmvbp = get_vlc2(gb, v->fourmvbp_vlc->table, VC1_4MV_BLOCK_PATTERN_VLC_BITS, 1);

                } else if (bmvtype == BMV_TYPE_INTERPOLATED || twomv) {

                    v->twomvbp = get_vlc2(gb, v->twomvbp_vlc->table, VC1_2MV_BLOCK_PATTERN_VLC_BITS, 1);

                }

            }

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

                v->mb_type[0][s->block_index[i]] = 0;

            fieldtx = v->fieldtx_plane[mb_pos] = ff_vc1_mbmode_intfrp[0][idx_mbmode][1];

            /* for all motion vector read MVDATA and motion compensate each block */

            dst_idx = 0;

            if (direct) {

                if (twomv) {

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

                        ff_vc1_mc_4mv_luma(v, i, 0, 0);

                        ff_vc1_mc_4mv_luma(v, i, 1, 1);

                    }

                    ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);

                    ff_vc1_mc_4mv_chroma4(v, 1, 1, 1);

                } else {

                    ff_vc1_mc_1mv(v, 0);

                    ff_vc1_interp_mc(v);

                }

            } else if (twomv && bmvtype == BMV_TYPE_INTERPOLATED) {

                mvbp = v->fourmvbp;

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

                    dir = i==1 || i==3;

                    dmv_x = dmv_y = 0;

                    val = ((mvbp >> (3 - i)) & 1);

                    if (val)

                        get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                    j = i > 1 ? 2 : 0;

                    ff_vc1_pred_mv_intfr(v, j, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);

                    ff_vc1_mc_4mv_luma(v, j, dir, dir);

                    ff_vc1_mc_4mv_luma(v, j+1, dir, dir);

                }

                ff_vc1_mc_4mv_chroma4(v, 0, 0, 0);

                ff_vc1_mc_4mv_chroma4(v, 1, 1, 1);

            } else if (bmvtype == BMV_TYPE_INTERPOLATED) {

                mvbp = v->twomvbp;

                dmv_x = dmv_y = 0;

                if (mvbp & 2)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 0);

                ff_vc1_mc_1mv(v, 0);

                dmv_x = dmv_y = 0;

                if (mvbp & 1)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], 1);

                ff_vc1_interp_mc(v);

            } else if (twomv) {

                dir = bmvtype == BMV_TYPE_BACKWARD;

                dir2 = dir;

                if (mvsw)

                    dir2 = !dir;

                mvbp = v->twomvbp;

                dmv_x = dmv_y = 0;

                if (mvbp & 2)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir);

                dmv_x = dmv_y = 0;

                if (mvbp & 1)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                ff_vc1_pred_mv_intfr(v, 2, dmv_x, dmv_y, 2, v->range_x, v->range_y, v->mb_type[0], dir2);

                if (mvsw) {

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

                        s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];

                        s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];

                        s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];

                        s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];

                    }

                } else {

                    ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);

                    ff_vc1_pred_mv_intfr(v, 2, 0, 0, 2, v->range_x, v->range_y, v->mb_type[0], !dir);

                }

                ff_vc1_mc_4mv_luma(v, 0, dir, 0);

                ff_vc1_mc_4mv_luma(v, 1, dir, 0);

                ff_vc1_mc_4mv_luma(v, 2, dir2, 0);

                ff_vc1_mc_4mv_luma(v, 3, dir2, 0);

                ff_vc1_mc_4mv_chroma4(v, dir, dir2, 0);

            } else {

                dir = bmvtype == BMV_TYPE_BACKWARD;

                mvbp = ff_vc1_mbmode_intfrp[0][idx_mbmode][2];

                dmv_x = dmv_y = 0;

                if (mvbp)

                    get_mvdata_interlaced(v, &dmv_x, &dmv_y, 0);

                ff_vc1_pred_mv_intfr(v, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0], dir);

                v->blk_mv_type[s->block_index[0]] = 1;

                v->blk_mv_type[s->block_index[1]] = 1;

                v->blk_mv_type[s->block_index[2]] = 1;

                v->blk_mv_type[s->block_index[3]] = 1;

                ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);

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

                    s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];

                    s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];

                }

                ff_vc1_mc_1mv(v, dir);

            }

            if (cbp)

                GET_MQUANT();  // p. 227

            s->current_picture.qscale_table[mb_pos] = mquant;

            if (!v->ttmbf && cbp)

                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);

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

                s->dc_val[0][s->block_index[i]] = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                if (!fieldtx)

                    off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                else

                    off = (i & 4) ? 0 : ((i & 1) * 8 + ((i > 1) * s->linesize));

                if (val) {

                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb,

                                             first_block, s->dest[dst_idx] + off,

                                             (i & 4) ? s->uvlinesize : (s->linesize << fieldtx),

                                             (i & 4) && (s->flags & CODEC_FLAG_GRAY), &block_tt);

                    block_cbp |= pat << (i << 2);

                    if (!v->ttmbf && ttmb < 8)

                        ttmb = -1;

                    first_block = 0;

                }

            }

        } else { // skipped

            dir = 0;

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

                v->mb_type[0][s->block_index[i]] = 0;

                s->dc_val[0][s->block_index[i]] = 0;

            }

            s->current_picture.mb_type[mb_pos]      = MB_TYPE_SKIP;

            s->current_picture.qscale_table[mb_pos] = 0;

            v->blk_mv_type[s->block_index[0]] = 0;

            v->blk_mv_type[s->block_index[1]] = 0;

            v->blk_mv_type[s->block_index[2]] = 0;

            v->blk_mv_type[s->block_index[3]] = 0;

            if (!direct) {

                if (bmvtype == BMV_TYPE_INTERPOLATED) {

                    ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 0);

                    ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], 1);

                } else {

                    dir = bmvtype == BMV_TYPE_BACKWARD;

                    ff_vc1_pred_mv_intfr(v, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0], dir);

                    if (mvsw) {

                        int dir2 = dir;

                        if (mvsw)

                            dir2 = !dir;

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

                            s->mv[dir][i+2][0] = s->mv[dir][i][0] = s->current_picture.motion_val[dir][s->block_index[i+2]][0] = s->current_picture.motion_val[dir][s->block_index[i]][0];

                            s->mv[dir][i+2][1] = s->mv[dir][i][1] = s->current_picture.motion_val[dir][s->block_index[i+2]][1] = s->current_picture.motion_val[dir][s->block_index[i]][1];

                            s->mv[dir2][i+2][0] = s->mv[dir2][i][0] = s->current_picture.motion_val[dir2][s->block_index[i]][0] = s->current_picture.motion_val[dir2][s->block_index[i+2]][0];

                            s->mv[dir2][i+2][1] = s->mv[dir2][i][1] = s->current_picture.motion_val[dir2][s->block_index[i]][1] = s->current_picture.motion_val[dir2][s->block_index[i+2]][1];

                        }

                    } else {

                        v->blk_mv_type[s->block_index[0]] = 1;

                        v->blk_mv_type[s->block_index[1]] = 1;

                        v->blk_mv_type[s->block_index[2]] = 1;

                        v->blk_mv_type[s->block_index[3]] = 1;

                        ff_vc1_pred_mv_intfr(v, 0, 0, 0, 2, v->range_x, v->range_y, 0, !dir);

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

                            s->mv[!dir][i+2][0] = s->mv[!dir][i][0] = s->current_picture.motion_val[!dir][s->block_index[i+2]][0] = s->current_picture.motion_val[!dir][s->block_index[i]][0];

                            s->mv[!dir][i+2][1] = s->mv[!dir][i][1] = s->current_picture.motion_val[!dir][s->block_index[i+2]][1] = s->current_picture.motion_val[!dir][s->block_index[i]][1];

                        }

                    }

                }

            }

            ff_vc1_mc_1mv(v, dir);

            if (direct || bmvtype == BMV_TYPE_INTERPOLATED) {

                ff_vc1_interp_mc(v);

            }

        }

    }

    if (s->mb_x == s->mb_width - 1)

        memmove(v->is_intra_base, v->is_intra, sizeof(v->is_intra_base[0]) * s->mb_stride);

    v->cbp[s->mb_x]      = block_cbp;

    v->ttblk[s->mb_x]    = block_tt;

    return 0;

}


static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)

{

    int start = 0, w, w2, g;

    const float lambda = s->lambda;

    const float freq_mult = avctx->sample_rate/(1024.0f/sce->ics.num_windows)/2.0f;

    const float spread_threshold = NOISE_SPREAD_THRESHOLD*(lambda/120.f);

    const float thr_mult = NOISE_LAMBDA_NUMERATOR/lambda;

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        start = 0;

        for (g = 0;  g < sce->ics.num_swb; g++) {

            if (start*freq_mult > NOISE_LOW_LIMIT*(lambda/170.0f)) {

                float energy = 0.0f, threshold = 0.0f, spread = 0.0f;

                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                    FFPsyBand *band = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];

                    energy += band->energy;

                    threshold += band->threshold;

                    spread += band->spread;

                }

                if (spread > spread_threshold*sce->ics.group_len[w] &&

                    ((sce->zeroes[w*16+g] && energy >= threshold) ||

                    energy < threshold*thr_mult*sce->ics.group_len[w])) {

                    sce->band_type[w*16+g] = NOISE_BT;

                    sce->pns_ener[w*16+g] = energy / sce->ics.group_len[w];

                    sce->zeroes[w*16+g] = 0;

                }

            }

            start += sce->ics.swb_sizes[g];

        }

    }

}


static void curses_calc_pad(void)

{

    if (is_graphic_console()) {

        width = gwidth;

        height = gheight;

    } else {

        width = COLS;

        height = LINES;

    }

    if (screenpad)

        delwin(screenpad);

    clear();

    refresh();

    screenpad = newpad(height, width);

    if (width > COLS) {

        px = (width - COLS) / 2;

        sminx = 0;

        smaxx = COLS;

    } else {

        px = 0;

        sminx = (COLS - width) / 2;

        smaxx = sminx + width;

    }

    if (height > LINES) {

        py = (height - LINES) / 2;

        sminy = 0;

        smaxy = LINES;

    } else {

        py = 0;

        sminy = (LINES - height) / 2;

        smaxy = sminy + height;

    }

}


static void fpu_dump_state(CPUState *env, FILE *f,

                           int (*fpu_fprintf)(FILE *f, const char *fmt, ...),

                           int flags)

{

    int i;

    int is_fpu64 = !!(env->hflags & MIPS_HFLAG_F64);

#define printfpr(fp)                                                    \

    do {                                                                \

        if (is_fpu64)                                                   \

            fpu_fprintf(f, "w:%08x d:%016" PRIx64                       \

                        " fd:%13g fs:%13g psu: %13g\n",                 \

                        (fp)->w[FP_ENDIAN_IDX], (fp)->d,                \

                        (double)(fp)->fd,                               \

                        (double)(fp)->fs[FP_ENDIAN_IDX],                \

                        (double)(fp)->fs[!FP_ENDIAN_IDX]);              \

        else {                                                          \

            fpr_t tmp;                                                  \

            tmp.w[FP_ENDIAN_IDX] = (fp)->w[FP_ENDIAN_IDX];              \

            tmp.w[!FP_ENDIAN_IDX] = ((fp) + 1)->w[FP_ENDIAN_IDX];       \

            fpu_fprintf(f, "w:%08x d:%016" PRIx64                       \

                        " fd:%13g fs:%13g psu:%13g\n",                  \

                        tmp.w[FP_ENDIAN_IDX], tmp.d,                    \

                        (double)tmp.fd,                                 \

                        (double)tmp.fs[FP_ENDIAN_IDX],                  \

                        (double)tmp.fs[!FP_ENDIAN_IDX]);                \

        }                                                               \

    } while(0)

    fpu_fprintf(f, "CP1 FCR0 0x%08x  FCR31 0x%08x  SR.FR %d  fp_status 0x%08x(0x%02x)\n",

                env->active_fpu.fcr0, env->active_fpu.fcr31, is_fpu64, env->active_fpu.fp_status,

                get_float_exception_flags(&env->active_fpu.fp_status));

    for (i = 0; i < 32; (is_fpu64) ? i++ : (i += 2)) {

        fpu_fprintf(f, "%3s: ", fregnames[i]);

        printfpr(&env->active_fpu.fpr[i]);

    }

#undef printfpr

}


static void qxl_hw_screen_dump(void *opaque, const char *filename, bool cswitch,

                               Error **errp)

{

    PCIQXLDevice *qxl = opaque;

    VGACommonState *vga = &qxl->vga;

    switch (qxl->mode) {

    case QXL_MODE_COMPAT:

    case QXL_MODE_NATIVE:

        qxl_render_update(qxl);

        ppm_save(filename, qxl->ssd.ds, errp);

        break;

    case QXL_MODE_VGA:

        vga->screen_dump(vga, filename, cswitch, errp);

        break;

    default:

        break;

    }

}


void qmp_input_send_event(int64_t console, InputEventList *events,

                          Error **errp)

{

    InputEventList *e;

    QemuConsole *con;

    con = qemu_console_lookup_by_index(console);

    if (!con) {

        error_setg(errp, "console %" PRId64 " not found", console);

        return;

    }

    if (!runstate_is_running() && !runstate_check(RUN_STATE_SUSPENDED)) {

        error_setg(errp, "VM not running");

        return;

    }

    for (e = events; e != NULL; e = e->next) {

        InputEvent *event = e->value;

        if (!qemu_input_find_handler(1 << event->kind, con)) {

            error_setg(errp, "Input handler not found for "

                             "event type %s",

                            InputEventKind_lookup[event->kind]);

            return;

        }

    }

    for (e = events; e != NULL; e = e->next) {

        InputEvent *event = e->value;

        qemu_input_event_send(con, event);

    }

    qemu_input_event_sync();

}


static av_cold int cuvid_decode_init(AVCodecContext *avctx)

{

    CuvidContext *ctx = avctx->priv_data;

    AVCUDADeviceContext *device_hwctx;

    AVHWDeviceContext *device_ctx;

    AVHWFramesContext *hwframe_ctx;

    CUVIDSOURCEDATAPACKET seq_pkt;

    CUcontext cuda_ctx = NULL;

    CUcontext dummy;

    const AVBitStreamFilter *bsf;

    int ret = 0;

    enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_CUDA,

                                       AV_PIX_FMT_NV12,

                                       AV_PIX_FMT_NONE };

    int probed_width = avctx->coded_width ? avctx->coded_width : 1280;

    int probed_height = avctx->coded_height ? avctx->coded_height : 720;

    // Accelerated transcoding scenarios with 'ffmpeg' require that the

    // pix_fmt be set to AV_PIX_FMT_CUDA early. The sw_pix_fmt, and the

    // pix_fmt for non-accelerated transcoding, do not need to be correct

    // but need to be set to something. We arbitrarily pick NV12.

    ret = ff_get_format(avctx, pix_fmts);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "ff_get_format failed: %d\n", ret);

        return ret;

    }

    avctx->pix_fmt = ret;

    if (ctx->resize_expr && sscanf(ctx->resize_expr, "%dx%d",

                                   &ctx->resize.width, &ctx->resize.height) != 2) {

        av_log(avctx, AV_LOG_ERROR, "Invalid resize expressions\n");

        ret = AVERROR(EINVAL);

        goto error;

    }

    if (ctx->crop_expr && sscanf(ctx->crop_expr, "%dx%dx%dx%d",

                                 &ctx->crop.top, &ctx->crop.bottom,

                                 &ctx->crop.left, &ctx->crop.right) != 4) {

        av_log(avctx, AV_LOG_ERROR, "Invalid cropping expressions\n");

        ret = AVERROR(EINVAL);

        goto error;

    }

    ret = cuvid_load_functions(&ctx->cvdl);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");

        goto error;

    }

    ctx->frame_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(CuvidParsedFrame));

    if (!ctx->frame_queue) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    if (avctx->hw_frames_ctx) {

        ctx->hwframe = av_buffer_ref(avctx->hw_frames_ctx);

        if (!ctx->hwframe) {

            ret = AVERROR(ENOMEM);

            goto error;

        }

        hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;

        ctx->hwdevice = av_buffer_ref(hwframe_ctx->device_ref);

        if (!ctx->hwdevice) {

            ret = AVERROR(ENOMEM);

            goto error;

        }

    } else {

        if (avctx->hw_device_ctx) {

            ctx->hwdevice = av_buffer_ref(avctx->hw_device_ctx);

            if (!ctx->hwdevice) {

                ret = AVERROR(ENOMEM);

                goto error;

            }

        } else {

            ret = av_hwdevice_ctx_create(&ctx->hwdevice, AV_HWDEVICE_TYPE_CUDA, ctx->cu_gpu, NULL, 0);

            if (ret < 0)

                goto error;

        }

        ctx->hwframe = av_hwframe_ctx_alloc(ctx->hwdevice);

        if (!ctx->hwframe) {

            av_log(avctx, AV_LOG_ERROR, "av_hwframe_ctx_alloc failed\n");

            ret = AVERROR(ENOMEM);

            goto error;

        }

        hwframe_ctx = (AVHWFramesContext*)ctx->hwframe->data;

    }

    device_ctx = hwframe_ctx->device_ctx;

    device_hwctx = device_ctx->hwctx;

    cuda_ctx = device_hwctx->cuda_ctx;

    ctx->cudl = device_hwctx->internal->cuda_dl;

    memset(&ctx->cuparseinfo, 0, sizeof(ctx->cuparseinfo));

    memset(&ctx->cuparse_ext, 0, sizeof(ctx->cuparse_ext));

    memset(&seq_pkt, 0, sizeof(seq_pkt));

    ctx->cuparseinfo.pExtVideoInfo = &ctx->cuparse_ext;

    switch (avctx->codec->id) {

#if CONFIG_H264_CUVID_DECODER

    case AV_CODEC_ID_H264:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_H264;

        break;

#endif

#if CONFIG_HEVC_CUVID_DECODER

    case AV_CODEC_ID_HEVC:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_HEVC;

        break;

#endif

#if CONFIG_MJPEG_CUVID_DECODER

    case AV_CODEC_ID_MJPEG:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_JPEG;

        break;

#endif

#if CONFIG_MPEG1_CUVID_DECODER

    case AV_CODEC_ID_MPEG1VIDEO:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG1;

        break;

#endif

#if CONFIG_MPEG2_CUVID_DECODER

    case AV_CODEC_ID_MPEG2VIDEO:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG2;

        break;

#endif

#if CONFIG_MPEG4_CUVID_DECODER

    case AV_CODEC_ID_MPEG4:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_MPEG4;

        break;

#endif

#if CONFIG_VP8_CUVID_DECODER

    case AV_CODEC_ID_VP8:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_VP8;

        break;

#endif

#if CONFIG_VP9_CUVID_DECODER

    case AV_CODEC_ID_VP9:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_VP9;

        break;

#endif

#if CONFIG_VC1_CUVID_DECODER

    case AV_CODEC_ID_VC1:

        ctx->cuparseinfo.CodecType = cudaVideoCodec_VC1;

        break;

#endif

    default:

        av_log(avctx, AV_LOG_ERROR, "Invalid CUVID codec!\n");

        return AVERROR_BUG;

    }

    if (avctx->codec->id == AV_CODEC_ID_H264 || avctx->codec->id == AV_CODEC_ID_HEVC) {

        if (avctx->codec->id == AV_CODEC_ID_H264)

            bsf = av_bsf_get_by_name("h264_mp4toannexb");

        else

            bsf = av_bsf_get_by_name("hevc_mp4toannexb");

        if (!bsf) {

            ret = AVERROR_BSF_NOT_FOUND;

            goto error;

        }

        if (ret = av_bsf_alloc(bsf, &ctx->bsf)) {

            goto error;

        }

        if (((ret = avcodec_parameters_from_context(ctx->bsf->par_in, avctx)) < 0) || ((ret = av_bsf_init(ctx->bsf)) < 0)) {

            av_bsf_free(&ctx->bsf);

            goto error;

        }

        ctx->cuparse_ext.format.seqhdr_data_length = ctx->bsf->par_out->extradata_size;

        memcpy(ctx->cuparse_ext.raw_seqhdr_data,

               ctx->bsf->par_out->extradata,

               FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), ctx->bsf->par_out->extradata_size));

    } else if (avctx->extradata_size > 0) {

        ctx->cuparse_ext.format.seqhdr_data_length = avctx->extradata_size;

        memcpy(ctx->cuparse_ext.raw_seqhdr_data,

               avctx->extradata,

               FFMIN(sizeof(ctx->cuparse_ext.raw_seqhdr_data), avctx->extradata_size));

    }

    ctx->cuparseinfo.ulMaxNumDecodeSurfaces = ctx->nb_surfaces;

    ctx->cuparseinfo.ulMaxDisplayDelay = 4;

    ctx->cuparseinfo.pUserData = avctx;

    ctx->cuparseinfo.pfnSequenceCallback = cuvid_handle_video_sequence;

    ctx->cuparseinfo.pfnDecodePicture = cuvid_handle_picture_decode;

    ctx->cuparseinfo.pfnDisplayPicture = cuvid_handle_picture_display;

    ret = CHECK_CU(ctx->cudl->cuCtxPushCurrent(cuda_ctx));

    if (ret < 0)

        goto error;

    ret = cuvid_test_dummy_decoder(avctx, &ctx->cuparseinfo,

                                   probed_width,

                                   probed_height);

    if (ret < 0)

        goto error;

    ret = CHECK_CU(ctx->cvdl->cuvidCreateVideoParser(&ctx->cuparser, &ctx->cuparseinfo));

    if (ret < 0)

        goto error;

    seq_pkt.payload = ctx->cuparse_ext.raw_seqhdr_data;

    seq_pkt.payload_size = ctx->cuparse_ext.format.seqhdr_data_length;

    if (seq_pkt.payload && seq_pkt.payload_size) {

        ret = CHECK_CU(ctx->cvdl->cuvidParseVideoData(ctx->cuparser, &seq_pkt));

        if (ret < 0)

            goto error;

    }

    ret = CHECK_CU(ctx->cudl->cuCtxPopCurrent(&dummy));

    if (ret < 0)

        goto error;

    ctx->prev_pts = INT64_MIN;

    if (!avctx->pkt_timebase.num || !avctx->pkt_timebase.den)

        av_log(avctx, AV_LOG_WARNING, "Invalid pkt_timebase, passing timestamps as-is.\n");

    return 0;

error:

    cuvid_decode_end(avctx);

    return ret;

}


static void default_end_frame(AVFilterLink *inlink)

{

    AVFilterLink *outlink = NULL;

    if (inlink->dst->nb_outputs)

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

    if (outlink) {

        if (outlink->out_buf) {

            avfilter_unref_buffer(outlink->out_buf);

            outlink->out_buf = NULL;

        }

        ff_end_frame(outlink);

    }

}


static inline void gen_op_addq_ESP_im(int32_t val)

{

    tcg_gen_ld_tl(cpu_tmp0, cpu_env, offsetof(CPUState, regs[R_ESP]));

    tcg_gen_addi_tl(cpu_tmp0, cpu_tmp0, val);

    tcg_gen_st_tl(cpu_tmp0, cpu_env, offsetof(CPUState, regs[R_ESP]));

}


static int img_snapshot(int argc, char **argv)

{

    BlockDriverState *bs;

    QEMUSnapshotInfo sn;

    char *filename, *snapshot_name = NULL;

    int c, ret = 0, bdrv_oflags;

    int action = 0;

    qemu_timeval tv;

    bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;

    /* Parse commandline parameters */

    for(;;) {

        c = getopt(argc, argv, "la:c:d:h");

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            return 0;

        case 'l':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_LIST;

            bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */

            break;

        case 'a':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_APPLY;

            snapshot_name = optarg;

            break;

        case 'c':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_CREATE;

            snapshot_name = optarg;

            break;

        case 'd':

            if (action) {

                help();

                return 0;

            }

            action = SNAPSHOT_DELETE;

            snapshot_name = optarg;

            break;

        }

    }

    if (optind >= argc) {

        help();

    }

    filename = argv[optind++];

    /* Open the image */

    bs = bdrv_new_open(filename, NULL, bdrv_oflags);

    if (!bs) {

        return 1;

    }

    /* Perform the requested action */

    switch(action) {

    case SNAPSHOT_LIST:

        dump_snapshots(bs);

        break;

    case SNAPSHOT_CREATE:

        memset(&sn, 0, sizeof(sn));

        pstrcpy(sn.name, sizeof(sn.name), snapshot_name);

        qemu_gettimeofday(&tv);

        sn.date_sec = tv.tv_sec;

        sn.date_nsec = tv.tv_usec * 1000;

        ret = bdrv_snapshot_create(bs, &sn);

        if (ret) {

            error_report("Could not create snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    case SNAPSHOT_APPLY:

        ret = bdrv_snapshot_goto(bs, snapshot_name);

        if (ret) {

            error_report("Could not apply snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    case SNAPSHOT_DELETE:

        ret = bdrv_snapshot_delete(bs, snapshot_name);

        if (ret) {

            error_report("Could not delete snapshot '%s': %d (%s)",

                snapshot_name, ret, strerror(-ret));

        }

        break;

    }

    /* Cleanup */

    bdrv_delete(bs);

    if (ret) {

        return 1;

    }

    return 0;

}


static void pcnet_aprom_writeb(void *opaque, uint32_t addr, uint32_t val)

{

    PCNetState *s = opaque;

#ifdef PCNET_DEBUG

    printf("pcnet_aprom_writeb addr=0x%08x val=0x%02x\n", addr, val);

#endif

    /* Check APROMWE bit to enable write access */

    if (pcnet_bcr_readw(s,2) & 0x100)

        s->prom[addr & 15] = val;

}