int cache_insert(PageCache *cache, uint64_t addr, uint8_t *pdata)

{

    CacheItem *it = NULL;

    g_assert(cache);

    g_assert(cache->page_cache);

    /* actual update of entry */

    it = cache_get_by_addr(cache, addr);

    /* allocate page */

    if (!it->it_data) {

        it->it_data = g_try_malloc(cache->page_size);

        if (!it->it_data) {

            DPRINTF("Error allocating page\n");

            return -1;

        }

        cache->num_items++;

    }

    memcpy(it->it_data, pdata, cache->page_size);

    it->it_age = ++cache->max_item_age;

    it->it_addr = addr;

    return 0;

}


int ff_alloc_picture(MpegEncContext *s, Picture *pic, int shared){

    const int big_mb_num= s->mb_stride*(s->mb_height+1) + 1; //the +1 is needed so memset(,,stride*height) does not sig11

    const int mb_array_size= s->mb_stride*s->mb_height;

    const int b8_array_size= s->b8_stride*s->mb_height*2;

    const int b4_array_size= s->b4_stride*s->mb_height*4;

    int i;

    int r= -1;

    if(shared){

        assert(pic->data[0]);

        assert(pic->type == 0 || pic->type == FF_BUFFER_TYPE_SHARED);

        pic->type= FF_BUFFER_TYPE_SHARED;

    }else{

        assert(!pic->data[0]);

        if (alloc_frame_buffer(s, pic) < 0)

            return -1;

        s->linesize  = pic->linesize[0];

        s->uvlinesize= pic->linesize[1];

    }

    if(pic->qscale_table==NULL){

        if (s->encoding) {

            FF_ALLOCZ_OR_GOTO(s->avctx, pic->mb_var   , mb_array_size * sizeof(int16_t)  , fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, pic->mc_mb_var, mb_array_size * sizeof(int16_t)  , fail)

            FF_ALLOCZ_OR_GOTO(s->avctx, pic->mb_mean  , mb_array_size * sizeof(int8_t )  , fail)

        }

        FF_ALLOCZ_OR_GOTO(s->avctx, pic->mbskip_table , mb_array_size * sizeof(uint8_t)+2, fail) //the +2 is for the slice end check

        FF_ALLOCZ_OR_GOTO(s->avctx, pic->qscale_table , mb_array_size * sizeof(uint8_t)  , fail)

        FF_ALLOCZ_OR_GOTO(s->avctx, pic->mb_type_base , (big_mb_num + s->mb_stride) * sizeof(uint32_t), fail)

        pic->mb_type= pic->mb_type_base + 2*s->mb_stride+1;

        if(s->out_format == FMT_H264){

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

                FF_ALLOCZ_OR_GOTO(s->avctx, pic->motion_val_base[i], 2 * (b4_array_size+4)  * sizeof(int16_t), fail)

                pic->motion_val[i]= pic->motion_val_base[i]+4;

                FF_ALLOCZ_OR_GOTO(s->avctx, pic->ref_index[i], 4*mb_array_size * sizeof(uint8_t), fail)

            }

            pic->motion_subsample_log2= 2;

        }else if(s->out_format == FMT_H263 || s->encoding || (s->avctx->debug&FF_DEBUG_MV) || (s->avctx->debug_mv)){

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

                FF_ALLOCZ_OR_GOTO(s->avctx, pic->motion_val_base[i], 2 * (b8_array_size+4) * sizeof(int16_t), fail)

                pic->motion_val[i]= pic->motion_val_base[i]+4;

                FF_ALLOCZ_OR_GOTO(s->avctx, pic->ref_index[i], 4*mb_array_size * sizeof(uint8_t), fail)

            }

            pic->motion_subsample_log2= 3;

        }

        if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {

            FF_ALLOCZ_OR_GOTO(s->avctx, pic->dct_coeff, 64 * mb_array_size * sizeof(DCTELEM)*6, fail)

        }

        pic->qstride= s->mb_stride;

        FF_ALLOCZ_OR_GOTO(s->avctx, pic->pan_scan , 1 * sizeof(AVPanScan), fail)

    }

    /* It might be nicer if the application would keep track of these

     * but it would require an API change. */

    memmove(s->prev_pict_types+1, s->prev_pict_types, PREV_PICT_TYPES_BUFFER_SIZE-1);

    s->prev_pict_types[0]= s->dropable ? AV_PICTURE_TYPE_B : s->pict_type;

    if(pic->age < PREV_PICT_TYPES_BUFFER_SIZE && s->prev_pict_types[pic->age] == AV_PICTURE_TYPE_B)

        pic->age= INT_MAX; // Skipped MBs in B-frames are quite rare in MPEG-1/2 and it is a bit tricky to skip them anyway.

    pic->owner2 = NULL;

    return 0;

fail: //for the FF_ALLOCZ_OR_GOTO macro

    if(r>=0)

        free_frame_buffer(s, pic);

    return -1;

}


static int raw_open_common(BlockDriverState *bs, QDict *options,

                           int bdrv_flags, int open_flags, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *filename = NULL;

    BlockdevAioOptions aio, aio_default;

    int fd, ret;

    struct stat st;

    OnOffAuto locking;

    opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    filename = qemu_opt_get(opts, "filename");

    ret = raw_normalize_devicepath(&filename);

    if (ret != 0) {

        error_setg_errno(errp, -ret, "Could not normalize device path");

        goto fail;

    }

    aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)

                  ? BLOCKDEV_AIO_OPTIONS_NATIVE

                  : BLOCKDEV_AIO_OPTIONS_THREADS;

    aio = qapi_enum_parse(BlockdevAioOptions_lookup, qemu_opt_get(opts, "aio"),

                          BLOCKDEV_AIO_OPTIONS__MAX, aio_default, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);

    locking = qapi_enum_parse(OnOffAuto_lookup, qemu_opt_get(opts, "locking"),

                              ON_OFF_AUTO__MAX, ON_OFF_AUTO_AUTO, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    switch (locking) {

    case ON_OFF_AUTO_ON:

        s->use_lock = true;

#ifndef F_OFD_SETLK

        fprintf(stderr,

                "File lock requested but OFD locking syscall is unavailable, "

                "falling back to POSIX file locks.\n"

                "Due to the implementation, locks can be lost unexpectedly.\n");

#endif

        break;

    case ON_OFF_AUTO_OFF:

        s->use_lock = false;

        break;

    case ON_OFF_AUTO_AUTO:

#ifdef F_OFD_SETLK

        s->use_lock = true;

#else

        s->use_lock = false;

#endif

        break;

    default:

        abort();

    }

    s->open_flags = open_flags;

    raw_parse_flags(bdrv_flags, &s->open_flags);

    s->fd = -1;

    fd = qemu_open(filename, s->open_flags, 0644);

    if (fd < 0) {

        ret = -errno;

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

        if (ret == -EROFS) {

            ret = -EACCES;

        }

        goto fail;

    }

    s->fd = fd;

    s->lock_fd = -1;

    if (s->use_lock) {

        fd = qemu_open(filename, s->open_flags);

        if (fd < 0) {

            ret = -errno;

            error_setg_errno(errp, errno, "Could not open '%s' for locking",

                             filename);

            qemu_close(s->fd);

            goto fail;

        }

        s->lock_fd = fd;

    }

    s->perm = 0;

    s->shared_perm = BLK_PERM_ALL;

#ifdef CONFIG_LINUX_AIO

     /* Currently Linux does AIO only for files opened with O_DIRECT */

    if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {

        error_setg(errp, "aio=native was specified, but it requires "

                         "cache.direct=on, which was not specified.");

        ret = -EINVAL;

        goto fail;

    }

#else

    if (s->use_linux_aio) {

        error_setg(errp, "aio=native was specified, but is not supported "

                         "in this build.");

        ret = -EINVAL;

        goto fail;

    }

#endif /* !defined(CONFIG_LINUX_AIO) */

    s->has_discard = true;

    s->has_write_zeroes = true;

    bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;

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

        s->needs_alignment = true;

    }

    if (fstat(s->fd, &st) < 0) {

        ret = -errno;

        error_setg_errno(errp, errno, "Could not stat file");

        goto fail;

    }

    if (S_ISREG(st.st_mode)) {

        s->discard_zeroes = true;

        s->has_fallocate = true;

    }

    if (S_ISBLK(st.st_mode)) {

#ifdef BLKDISCARDZEROES

        unsigned int arg;

        if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {

            s->discard_zeroes = true;

        }

#endif

#ifdef __linux__

        /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do

         * not rely on the contents of discarded blocks unless using O_DIRECT.

         * Same for BLKZEROOUT.

         */

        if (!(bs->open_flags & BDRV_O_NOCACHE)) {

            s->discard_zeroes = false;

            s->has_write_zeroes = false;

        }

#endif

    }

#ifdef __FreeBSD__

    if (S_ISCHR(st.st_mode)) {

        /*

         * The file is a char device (disk), which on FreeBSD isn't behind

         * a pager, so force all requests to be aligned. This is needed

         * so QEMU makes sure all IO operations on the device are aligned

         * to sector size, or else FreeBSD will reject them with EINVAL.

         */

        s->needs_alignment = true;

    }

#endif

#ifdef CONFIG_XFS

    if (platform_test_xfs_fd(s->fd)) {

        s->is_xfs = true;

    }

#endif

    ret = 0;

fail:

    if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {

        unlink(filename);

    }

    qemu_opts_del(opts);

    return ret;

}


int ff_pre_estimate_p_frame_motion(MpegEncContext * s,

                                    int mb_x, int mb_y)

{

    int mx, my, range, dmin;

    int xmin, ymin, xmax, ymax;

    int rel_xmin, rel_ymin, rel_xmax, rel_ymax;

    int pred_x=0, pred_y=0;

    int P[10][2];

    const int shift= 1+s->quarter_sample;

    uint16_t * const mv_penalty= s->me.mv_penalty[s->f_code] + MAX_MV;

    const int mv_stride= s->mb_width + 2;

    const int xy= mb_x + 1 + (mb_y + 1)*mv_stride;

    assert(s->quarter_sample==0 || s->quarter_sample==1);

    s->me.pre_penalty_factor    = get_penalty_factor(s, s->avctx->me_pre_cmp);

    get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, s->f_code);

    rel_xmin= xmin - mb_x*16;

    rel_xmax= xmax - mb_x*16;

    rel_ymin= ymin - mb_y*16;

    rel_ymax= ymax - mb_y*16;

    s->me.skip=0;

    P_LEFT[0]       = s->p_mv_table[xy + 1][0];

    P_LEFT[1]       = s->p_mv_table[xy + 1][1];

    if(P_LEFT[0]       < (rel_xmin<<shift)) P_LEFT[0]       = (rel_xmin<<shift);

    /* special case for first line */

    if (mb_y == s->mb_height-1) {

        pred_x= P_LEFT[0];

        pred_y= P_LEFT[1];

        P_TOP[0]= P_TOPRIGHT[0]= P_MEDIAN[0]=

        P_TOP[1]= P_TOPRIGHT[1]= P_MEDIAN[1]= 0; //FIXME

    } else {

        P_TOP[0]      = s->p_mv_table[xy + mv_stride    ][0];

        P_TOP[1]      = s->p_mv_table[xy + mv_stride    ][1];

        P_TOPRIGHT[0] = s->p_mv_table[xy + mv_stride - 1][0];

        P_TOPRIGHT[1] = s->p_mv_table[xy + mv_stride - 1][1];

        if(P_TOP[1]      < (rel_ymin<<shift)) P_TOP[1]     = (rel_ymin<<shift);

        if(P_TOPRIGHT[0] > (rel_xmax<<shift)) P_TOPRIGHT[0]= (rel_xmax<<shift);

        if(P_TOPRIGHT[1] < (rel_ymin<<shift)) P_TOPRIGHT[1]= (rel_ymin<<shift);

        P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);

        P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);

        pred_x = P_MEDIAN[0];

        pred_y = P_MEDIAN[1];

    }

    dmin = s->me.pre_motion_search(s, 0, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax,

                                   &s->last_picture, s->p_mv_table, (1<<16)>>shift, mv_penalty);

    s->p_mv_table[xy][0] = mx<<shift;

    s->p_mv_table[xy][1] = my<<shift;

    return dmin;

}


int ff_draw_init(FFDrawContext *draw, enum AVPixelFormat format, unsigned flags)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(format);

    const AVComponentDescriptor *c;

    unsigned i, nb_planes = 0;

    int pixelstep[MAX_PLANES] = { 0 };

    if (!desc->name)

        return AVERROR(EINVAL);

    if (desc->flags & ~(AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PSEUDOPAL | AV_PIX_FMT_FLAG_ALPHA))

        return AVERROR(ENOSYS);

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

        c = &desc->comp[i];

        /* for now, only 8-bits formats */

        if (c->depth_minus1 != 8 - 1)

            return AVERROR(ENOSYS);

        if (c->plane >= MAX_PLANES)

            return AVERROR(ENOSYS);

        /* strange interleaving */

        if (pixelstep[c->plane] != 0 &&

            pixelstep[c->plane] != c->step_minus1 + 1)

            return AVERROR(ENOSYS);

        pixelstep[c->plane] = c->step_minus1 + 1;

        if (pixelstep[c->plane] >= 8)

            return AVERROR(ENOSYS);

        nb_planes = FFMAX(nb_planes, c->plane + 1);

    }

    if ((desc->log2_chroma_w || desc->log2_chroma_h) && nb_planes < 3)

        return AVERROR(ENOSYS); /* exclude NV12 and NV21 */

    memset(draw, 0, sizeof(*draw));

    draw->desc      = desc;

    draw->format    = format;

    draw->nb_planes = nb_planes;

    memcpy(draw->pixelstep, pixelstep, sizeof(draw->pixelstep));

    draw->hsub[1] = draw->hsub[2] = draw->hsub_max = desc->log2_chroma_w;

    draw->vsub[1] = draw->vsub[2] = draw->vsub_max = desc->log2_chroma_h;

    for (i = 0; i < ((desc->nb_components - 1) | 1); i++)

        draw->comp_mask[desc->comp[i].plane] |=

            1 << (desc->comp[i].offset_plus1 - 1);

    return 0;

}


static int htab_save_complete(QEMUFile *f, void *opaque)

{

    sPAPRMachineState *spapr = opaque;

    int fd;

    /* Iteration header */

    qemu_put_be32(f, 0);

    if (!spapr->htab) {

        int rc;

        assert(kvm_enabled());

        fd = get_htab_fd(spapr);

        if (fd < 0) {

            return fd;

        }

        rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, -1);

        if (rc < 0) {

            return rc;

        }

        close_htab_fd(spapr);

    } else {

        if (spapr->htab_first_pass) {

            htab_save_first_pass(f, spapr, -1);

        }

        htab_save_later_pass(f, spapr, -1);

    }

    /* End marker */

    qemu_put_be32(f, 0);

    qemu_put_be16(f, 0);

    qemu_put_be16(f, 0);

    return 0;

}


struct pxa2xx_gpio_info_s *pxa2xx_gpio_init(target_phys_addr_t base,

                CPUState *env, qemu_irq *pic, int lines)

{

    int iomemtype;

    struct pxa2xx_gpio_info_s *s;

    s = (struct pxa2xx_gpio_info_s *)

            qemu_mallocz(sizeof(struct pxa2xx_gpio_info_s));

    memset(s, 0, sizeof(struct pxa2xx_gpio_info_s));

    s->base = base;

    s->pic = pic;

    s->lines = lines;

    s->cpu_env = env;

    iomemtype = cpu_register_io_memory(0, pxa2xx_gpio_readfn,

                    pxa2xx_gpio_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    register_savevm("pxa2xx_gpio", 0, 0,

                    pxa2xx_gpio_save, pxa2xx_gpio_load, s);

    return s;

}


AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b)
{
    AVFilterFormats *ret;
    unsigned i, j, k = 0;
    ret = av_mallocz(sizeof(AVFilterFormats));
    /* merge list of formats */
    ret->formats = av_malloc(sizeof(*ret->formats) * FFMIN(a->format_count,
                                                           b->format_count));
    for(i = 0; i < a->format_count; i ++)
        for(j = 0; j < b->format_count; j ++)
            if(a->formats[i] == b->formats[j])
                ret->formats[k++] = a->formats[i];
    ret->format_count = k;
    /* check that there was at least one common format */
    if(!ret->format_count) {
        av_free(ret->formats);
        av_free(ret);
        return NULL;
    }
    ret->refs = av_malloc(sizeof(AVFilterFormats**)*(a->refcount+b->refcount));
    merge_ref(ret, a);
    merge_ref(ret, b);
    return ret;
}


void console_select(unsigned int index)

{

    TextConsole *s;

    if (index >= MAX_CONSOLES)

        return;

    if (active_console) {

        active_console->g_width = ds_get_width(active_console->ds);

        active_console->g_height = ds_get_height(active_console->ds);

    }

    s = consoles[index];

    if (s) {

        DisplayState *ds = s->ds;

        if (active_console->cursor_timer) {

            qemu_del_timer(active_console->cursor_timer);

        }

        active_console = s;

        if (ds_get_bits_per_pixel(s->ds)) {

            ds->surface = qemu_resize_displaysurface(ds, s->g_width, s->g_height);

        } else {

            s->ds->surface->width = s->width;

            s->ds->surface->height = s->height;

        }

        if (s->cursor_timer) {

            qemu_mod_timer(s->cursor_timer,

                   qemu_get_clock_ms(rt_clock) + CONSOLE_CURSOR_PERIOD / 2);

        }

        dpy_resize(s->ds);

        vga_hw_invalidate();

    }

}


static av_always_inline int simple_limit(uint8_t *p, ptrdiff_t stride, int flim)

{

    LOAD_PIXELS

    return 2*FFABS(p0-q0) + (FFABS(p1-q1) >> 1) <= flim;

}


dshow_read_close(AVFormatContext *s)

{

    struct dshow_ctx *ctx = s->priv_data;

    AVPacketList *pktl;

    if (ctx->control) {

        IMediaControl_Stop(ctx->control);

        IMediaControl_Release(ctx->control);

    }

    if (ctx->graph) {

        IEnumFilters *fenum;

        int r;

        r = IGraphBuilder_EnumFilters(ctx->graph, &fenum);

        if (r == S_OK) {

            IBaseFilter *f;

            IEnumFilters_Reset(fenum);

            while (IEnumFilters_Next(fenum, 1, &f, NULL) == S_OK) {

                if (IGraphBuilder_RemoveFilter(ctx->graph, f) == S_OK)

                    IEnumFilters_Reset(fenum); /* When a filter is removed,

                                                * the list must be reset. */

                IBaseFilter_Release(f);

            }

            IEnumFilters_Release(fenum);

        }

        IGraphBuilder_Release(ctx->graph);

    }

    if (ctx->capture_pin[VideoDevice])

        libAVPin_Release(ctx->capture_pin[VideoDevice]);

    if (ctx->capture_pin[AudioDevice])

        libAVPin_Release(ctx->capture_pin[AudioDevice]);

    if (ctx->capture_filter[VideoDevice])

        libAVFilter_Release(ctx->capture_filter[VideoDevice]);

    if (ctx->capture_filter[AudioDevice])

        libAVFilter_Release(ctx->capture_filter[AudioDevice]);

    if (ctx->device_pin[VideoDevice])

        IPin_Release(ctx->device_pin[VideoDevice]);

    if (ctx->device_pin[AudioDevice])

        IPin_Release(ctx->device_pin[AudioDevice]);

    if (ctx->device_filter[VideoDevice])

        IBaseFilter_Release(ctx->device_filter[VideoDevice]);

    if (ctx->device_filter[AudioDevice])

        IBaseFilter_Release(ctx->device_filter[AudioDevice]);

    if (ctx->device_name[0])

        av_free(ctx->device_name[0]);

    if (ctx->device_name[1])

        av_free(ctx->device_name[1]);

    if(ctx->mutex)

        CloseHandle(ctx->mutex);

    if(ctx->event)

        CloseHandle(ctx->event);

    pktl = ctx->pktl;

    while (pktl) {

        AVPacketList *next = pktl->next;

        av_destruct_packet(&pktl->pkt);

        av_free(pktl);

        pktl = next;

    }

    return 0;

}


static int ftp_conn_control_block_control(void *data)

{

    FTPContext *s = data;

    return s->conn_control_block_flag;

}


static int probe_file(const char *filename)

{

    AVFormatContext *fmt_ctx;

    int ret, i;

    if ((ret = open_input_file(&fmt_ctx, filename)))

        return ret;

    if (do_show_packets)

        show_packets(fmt_ctx);

    if (do_show_streams)

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

            show_stream(fmt_ctx, i);

    if (do_show_format)

        show_format(fmt_ctx);

    close_input_file(&fmt_ctx);

    return 0;

}


av_cold int ff_mjpeg_decode_init(AVCodecContext *avctx)

{

    MJpegDecodeContext *s = avctx->priv_data;

    if (!s->picture_ptr) {

        s->picture = av_frame_alloc();

        if (!s->picture)

            return AVERROR(ENOMEM);

        s->picture_ptr = s->picture;

    }

    s->avctx = avctx;

    ff_blockdsp_init(&s->bdsp, avctx);

    ff_hpeldsp_init(&s->hdsp, avctx->flags);

    ff_idctdsp_init(&s->idsp, avctx);

    ff_init_scantable(s->idsp.idct_permutation, &s->scantable,

                      ff_zigzag_direct);

    s->buffer_size   = 0;

    s->buffer        = NULL;

    s->start_code    = -1;

    s->first_picture = 1;

    s->org_height    = avctx->coded_height;

    avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;

    avctx->colorspace = AVCOL_SPC_BT470BG;

    build_basic_mjpeg_vlc(s);

    if (s->extern_huff) {

        int ret;

        av_log(avctx, AV_LOG_INFO, "mjpeg: using external huffman table\n");

        init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);

        if ((ret = ff_mjpeg_decode_dht(s))) {

            av_log(avctx, AV_LOG_ERROR,

                   "mjpeg: error using external huffman table\n");

            return ret;

        }

    }

    if (avctx->field_order == AV_FIELD_BB) { /* quicktime icefloe 019 */

        s->interlace_polarity = 1;           /* bottom field first */

        av_log(avctx, AV_LOG_DEBUG, "mjpeg bottom field first\n");

    }

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

        s->flipped = 1;

    return 0;

}


int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
              BlockDriver *drv)
{
    int ret;
    int probed = 0;
    if (flags & BDRV_O_SNAPSHOT) {
        BlockDriverState *bs1;
        int64_t total_size;
        int is_protocol = 0;
        BlockDriver *bdrv_qcow2;
        QEMUOptionParameter *options;
        char tmp_filename[PATH_MAX];
        char backing_filename[PATH_MAX];
        /* if snapshot, we create a temporary backing file and open it
           instead of opening 'filename' directly */
        /* if there is a backing file, use it */
        bs1 = bdrv_new("");
        ret = bdrv_open(bs1, filename, 0, drv);
        if (ret < 0) {
            bdrv_delete(bs1);
            return ret;
        }
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
        if (bs1->drv && bs1->drv->protocol_name)
            is_protocol = 1;
        bdrv_delete(bs1);
        get_tmp_filename(tmp_filename, sizeof(tmp_filename));
        /* Real path is meaningless for protocols */
        if (is_protocol)
            snprintf(backing_filename, sizeof(backing_filename),
                     "%s", filename);
        else if (!realpath(filename, backing_filename))
            return -errno;
        bdrv_qcow2 = bdrv_find_format("qcow2");
        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
        if (drv) {
            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
                drv->format_name);
        }
        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
        free_option_parameters(options);
        if (ret < 0) {
            return ret;
        }
        filename = tmp_filename;
        drv = bdrv_qcow2;
        bs->is_temporary = 1;
    }
    /* Find the right image format driver */
    if (!drv) {
        drv = find_image_format(filename);
        probed = 1;
    }
    if (!drv) {
        ret = -ENOENT;
        goto unlink_and_fail;
    }
    /* Open the image */
    ret = bdrv_open_common(bs, filename, flags, drv);
    if (ret < 0) {
        goto unlink_and_fail;
    }
    /* If there is a backing file, use it */
    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
        char backing_filename[PATH_MAX];
        int back_flags;
        BlockDriver *back_drv = NULL;
        bs->backing_hd = bdrv_new("");
        path_combine(backing_filename, sizeof(backing_filename),
                     filename, bs->backing_file);
        if (bs->backing_format[0] != '\0')
            back_drv = bdrv_find_format(bs->backing_format);
        /* backing files always opened read-only */
        back_flags =
            flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
        ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
        if (ret < 0) {
            bdrv_close(bs);
            return ret;
        }
        if (bs->is_temporary) {
            bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
        } else {
            /* base image inherits from "parent" */
            bs->backing_hd->keep_read_only = bs->keep_read_only;
        }
    }
    if (!bdrv_key_required(bs)) {
        /* call the change callback */
        bs->media_changed = 1;
        if (bs->change_cb)
            bs->change_cb(bs->change_opaque);
    }
    return 0;
unlink_and_fail:
    if (bs->is_temporary) {
        unlink(filename);
    }
    return ret;
}


static int parse_outputs(const char **buf, AVFilterInOut **curr_inputs,

                         AVFilterInOut **open_inputs,

                         AVFilterInOut **open_outputs, AVClass *log_ctx)

{

    int ret, pad = 0;

    while (**buf == '[') {

        char *name = parse_link_name(buf, log_ctx);

        AVFilterInOut *match;

        AVFilterInOut *input = *curr_inputs;

        *curr_inputs = (*curr_inputs)->next;

        if (!name)

        /* First check if the label is not in the open_inputs list */

        match = extract_inout(name, open_inputs);

        if (match) {

            if ((ret = link_filter(input->filter_ctx, input->pad_idx,

                                   match->filter_ctx, match->pad_idx, log_ctx)) < 0)

                return ret;

            av_free(match->name);

            av_free(name);

            av_free(match);

            av_free(input);

        } else {

            /* Not in the list, so add the first input as a open_output */

            input->name = name;

            insert_inout(open_outputs, input);

        *buf += strspn(*buf, WHITESPACES);

        pad++;

    return pad;


static inline void rgb2rgb_init_c(void)

{

    rgb15to16          = rgb15to16_c;

    rgb15tobgr24       = rgb15tobgr24_c;

    rgb15to32          = rgb15to32_c;

    rgb16tobgr24       = rgb16tobgr24_c;

    rgb16to32          = rgb16to32_c;

    rgb16to15          = rgb16to15_c;

    rgb24tobgr16       = rgb24tobgr16_c;

    rgb24tobgr15       = rgb24tobgr15_c;

    rgb24tobgr32       = rgb24tobgr32_c;

    rgb32to16          = rgb32to16_c;

    rgb32to15          = rgb32to15_c;

    rgb32tobgr24       = rgb32tobgr24_c;

    rgb24to15          = rgb24to15_c;

    rgb24to16          = rgb24to16_c;

    rgb24tobgr24       = rgb24tobgr24_c;

    shuffle_bytes_2103 = shuffle_bytes_2103_c;

    rgb32tobgr16       = rgb32tobgr16_c;

    rgb32tobgr15       = rgb32tobgr15_c;

    yv12toyuy2         = yv12toyuy2_c;

    yv12touyvy         = yv12touyvy_c;

    yuv422ptoyuy2      = yuv422ptoyuy2_c;

    yuv422ptouyvy      = yuv422ptouyvy_c;

    yuy2toyv12         = yuy2toyv12_c;

    planar2x           = planar2x_c;

    rgb24toyv12        = rgb24toyv12_c;

    interleaveBytes    = interleaveBytes_c;

    vu9_to_vu12        = vu9_to_vu12_c;

    yvu9_to_yuy2       = yvu9_to_yuy2_c;

    uyvytoyuv420       = uyvytoyuv420_c;

    uyvytoyuv422       = uyvytoyuv422_c;

    yuyvtoyuv420       = yuyvtoyuv420_c;

    yuyvtoyuv422       = yuyvtoyuv422_c;

}


static Visitor *visitor_input_test_init_internal(TestInputVisitorData *data,

                                                 const char *json_string,

                                                 va_list *ap)

{

    visitor_input_teardown(data, NULL);

    data->obj = qobject_from_jsonv(json_string, ap);

    g_assert(data->obj);

    data->qiv = qobject_input_visitor_new(data->obj);

    g_assert(data->qiv);

    return data->qiv;

}


static int audio_decode_frame(VideoState *is)

{

    int data_size, resampled_data_size;

    int64_t dec_channel_layout;

    int got_frame = 0;

    av_unused double audio_clock0;

    int wanted_nb_samples;

    AVRational tb;

    int ret;

    int reconfigure;

    if (!is->frame)

        if (!(is->frame = av_frame_alloc()))

            return AVERROR(ENOMEM);

    for (;;) {

        if (is->audioq.serial != is->auddec.pkt_serial)

            is->audio_buf_frames_pending = got_frame = 0;

        if (!got_frame)

            av_frame_unref(is->frame);

        if (is->paused)

            return -1;

        while (is->audio_buf_frames_pending || got_frame) {

            if (!is->audio_buf_frames_pending) {

                got_frame = 0;

                tb = (AVRational){1, is->frame->sample_rate};

#if CONFIG_AVFILTER

                dec_channel_layout = get_valid_channel_layout(is->frame->channel_layout, av_frame_get_channels(is->frame));

                reconfigure =

                    cmp_audio_fmts(is->audio_filter_src.fmt, is->audio_filter_src.channels,

                                   is->frame->format, av_frame_get_channels(is->frame))    ||

                    is->audio_filter_src.channel_layout != dec_channel_layout ||

                    is->audio_filter_src.freq           != is->frame->sample_rate ||

                    is->auddec.pkt_serial               != is->audio_last_serial;

                if (reconfigure) {

                    char buf1[1024], buf2[1024];

                    av_get_channel_layout_string(buf1, sizeof(buf1), -1, is->audio_filter_src.channel_layout);

                    av_get_channel_layout_string(buf2, sizeof(buf2), -1, dec_channel_layout);

                    av_log(NULL, AV_LOG_DEBUG,

                           "Audio frame changed from rate:%d ch:%d fmt:%s layout:%s serial:%d to rate:%d ch:%d fmt:%s layout:%s serial:%d\n",

                           is->audio_filter_src.freq, is->audio_filter_src.channels, av_get_sample_fmt_name(is->audio_filter_src.fmt), buf1, is->audio_last_serial,

                           is->frame->sample_rate, av_frame_get_channels(is->frame), av_get_sample_fmt_name(is->frame->format), buf2, is->auddec.pkt_serial);

                    is->audio_filter_src.fmt            = is->frame->format;

                    is->audio_filter_src.channels       = av_frame_get_channels(is->frame);

                    is->audio_filter_src.channel_layout = dec_channel_layout;

                    is->audio_filter_src.freq           = is->frame->sample_rate;

                    is->audio_last_serial               = is->auddec.pkt_serial;

                    if ((ret = configure_audio_filters(is, afilters, 1)) < 0)

                        return ret;

                }

                if ((ret = av_buffersrc_add_frame(is->in_audio_filter, is->frame)) < 0)

                    return ret;

#endif

            }

#if CONFIG_AVFILTER

            if ((ret = av_buffersink_get_frame_flags(is->out_audio_filter, is->frame, 0)) < 0) {

                if (ret == AVERROR(EAGAIN)) {

                    is->audio_buf_frames_pending = 0;

                    continue;

                }

                if (ret == AVERROR_EOF)

                    is->auddec.finished = is->auddec.pkt_serial;

                return ret;

            }

            is->audio_buf_frames_pending = 1;

            tb = is->out_audio_filter->inputs[0]->time_base;

#endif

            data_size = av_samples_get_buffer_size(NULL, av_frame_get_channels(is->frame),

                                                   is->frame->nb_samples,

                                                   is->frame->format, 1);

            dec_channel_layout =

                (is->frame->channel_layout && av_frame_get_channels(is->frame) == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?

                is->frame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(is->frame));

            wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);

            if (is->frame->format        != is->audio_src.fmt            ||

                dec_channel_layout       != is->audio_src.channel_layout ||

                is->frame->sample_rate   != is->audio_src.freq           ||

                (wanted_nb_samples       != is->frame->nb_samples && !is->swr_ctx)) {

                swr_free(&is->swr_ctx);

                is->swr_ctx = swr_alloc_set_opts(NULL,

                                                 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,

                                                 dec_channel_layout,           is->frame->format, is->frame->sample_rate,

                                                 0, NULL);

                if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {

                    av_log(NULL, AV_LOG_ERROR,

                           "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",

                            is->frame->sample_rate, av_get_sample_fmt_name(is->frame->format), av_frame_get_channels(is->frame),

                            is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);

                    break;

                }

                is->audio_src.channel_layout = dec_channel_layout;

                is->audio_src.channels       = av_frame_get_channels(is->frame);

                is->audio_src.freq = is->frame->sample_rate;

                is->audio_src.fmt = is->frame->format;

            }

            if (is->swr_ctx) {

                const uint8_t **in = (const uint8_t **)is->frame->extended_data;

                uint8_t **out = &is->audio_buf1;

                int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate + 256;

                int out_size  = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, out_count, is->audio_tgt.fmt, 0);

                int len2;

                if (out_size < 0) {

                    av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");

                    break;

                }

                if (wanted_nb_samples != is->frame->nb_samples) {

                    if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,

                                                wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {

                        av_log(NULL, AV_LOG_ERROR, "swr_set_compensation() failed\n");

                        break;

                    }

                }

                av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);

                if (!is->audio_buf1)

                    return AVERROR(ENOMEM);

                len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);

                if (len2 < 0) {

                    av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");

                    break;

                }

                if (len2 == out_count) {

                    av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");

                    swr_init(is->swr_ctx);

                }

                is->audio_buf = is->audio_buf1;

                resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);

            } else {

                is->audio_buf = is->frame->data[0];

                resampled_data_size = data_size;

            }

            audio_clock0 = is->audio_clock;

            /* update the audio clock with the pts */

            if (is->frame->pts != AV_NOPTS_VALUE)

                is->audio_clock = is->frame->pts * av_q2d(tb) + (double) is->frame->nb_samples / is->frame->sample_rate;

            else

                is->audio_clock = NAN;

            is->audio_clock_serial = is->auddec.pkt_serial;

#ifdef DEBUG

            {

                static double last_clock;

                printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",

                       is->audio_clock - last_clock,

                       is->audio_clock, audio_clock0);

                last_clock = is->audio_clock;

            }

#endif

            return resampled_data_size;

        }

        if ((got_frame = decoder_decode_frame(&is->auddec, is->frame, NULL)) < 0)

            return -1;

        if (is->auddec.flushed)

            is->audio_buf_frames_pending = 0;

    }

}


static void scsi_do_read(void *opaque, int ret)
{
    SCSIDiskReq *r = opaque;
    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
    uint32_t n;
    if (r->req.aiocb != NULL) {
        r->req.aiocb = NULL;
        bdrv_acct_done(s->qdev.conf.bs, &r->acct);
    if (ret < 0) {
        if (scsi_handle_rw_error(r, -ret)) {
            goto done;
    if (r->req.sg) {
        dma_acct_start(s->qdev.conf.bs, &r->acct, r->req.sg, BDRV_ACCT_READ);
        r->req.resid -= r->req.sg->size;
        r->req.aiocb = dma_bdrv_read(s->qdev.conf.bs, r->req.sg, r->sector,
                                     scsi_dma_complete, r);
    } else {
        n = scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
        bdrv_acct_start(s->qdev.conf.bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
        r->req.aiocb = bdrv_aio_readv(s->qdev.conf.bs, r->sector, &r->qiov, n,
                                      scsi_read_complete, r);
done:
    if (!r->req.io_canceled) {
        scsi_req_unref(&r->req);


static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)

{

    BDRVSheepdogState *s = acb->common.bs->opaque;

    struct iovec iov;

    AIOReq *aio_req;

    uint32_t offset, data_len, mn, mx;

    mn = s->min_dirty_data_idx;

    mx = s->max_dirty_data_idx;

    if (mn <= mx) {

        /* we need to update the vdi object. */

        offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +

            mn * sizeof(s->inode.data_vdi_id[0]);

        data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);

        s->min_dirty_data_idx = UINT32_MAX;

        s->max_dirty_data_idx = 0;

        iov.iov_base = &s->inode;

        iov.iov_len = sizeof(s->inode);

        aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),

                                data_len, offset, 0, false, 0, offset);

        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

        add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);

        acb->aio_done_func = sd_finish_aiocb;

        acb->aiocb_type = AIOCB_WRITE_UDATA;

        return;

    }

    sd_finish_aiocb(acb);

}


static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,

    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,

    int64_t align, QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    bool waited;

    int ret;

    int64_t start_sector = offset >> BDRV_SECTOR_BITS;

    int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);

    uint64_t bytes_remaining = bytes;

    int max_transfer;

    assert(is_power_of_2(align));

    assert((offset & (align - 1)) == 0);

    assert((bytes & (align - 1)) == 0);

    assert(!qiov || bytes == qiov->size);

    assert((bs->open_flags & BDRV_O_NO_IO) == 0);

    assert(!(flags & ~BDRV_REQ_MASK));

    max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),

                                   align);

    waited = wait_serialising_requests(req);

    assert(!waited || !req->serialising);

    assert(req->overlap_offset <= offset);

    assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);

    ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);

    if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&

        !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&

        qemu_iovec_is_zero(qiov)) {

        flags |= BDRV_REQ_ZERO_WRITE;

        if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {

            flags |= BDRV_REQ_MAY_UNMAP;

        }

    }

    if (ret < 0) {

        /* Do nothing, write notifier decided to fail this request */

    } else if (flags & BDRV_REQ_ZERO_WRITE) {

        bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);

        ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);

    } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {

        ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);

    } else if (bytes <= max_transfer) {

        bdrv_debug_event(bs, BLKDBG_PWRITEV);

        ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);

    } else {

        bdrv_debug_event(bs, BLKDBG_PWRITEV);

        while (bytes_remaining) {

            int num = MIN(bytes_remaining, max_transfer);

            QEMUIOVector local_qiov;

            int local_flags = flags;

            assert(num);

            if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&

                !(bs->supported_write_flags & BDRV_REQ_FUA)) {

                /* If FUA is going to be emulated by flush, we only

                 * need to flush on the last iteration */

                local_flags &= ~BDRV_REQ_FUA;

            }

            qemu_iovec_init(&local_qiov, qiov->niov);

            qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);

            ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,

                                      num, &local_qiov, local_flags);

            qemu_iovec_destroy(&local_qiov);

            if (ret < 0) {

                break;

            }

            bytes_remaining -= num;

        }

    }

    bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);

    ++bs->write_gen;

    bdrv_set_dirty(bs, start_sector, end_sector - start_sector);

    if (bs->wr_highest_offset < offset + bytes) {

        bs->wr_highest_offset = offset + bytes;

    }

    if (ret >= 0) {

        bs->total_sectors = MAX(bs->total_sectors, end_sector);

        ret = 0;

    }

    return ret;

}


static target_ulong get_sigframe(struct target_sigaction *ka,

                                 CPUPPCState *env,

                                 int frame_size)

{

    target_ulong oldsp, newsp;

    oldsp = env->gpr[1];

    if ((ka->sa_flags & TARGET_SA_ONSTACK) &&

        (sas_ss_flags(oldsp))) {

        oldsp = (target_sigaltstack_used.ss_sp

                 + target_sigaltstack_used.ss_size);

    }

    newsp = (oldsp - frame_size) & ~0xFUL;

    return newsp;

}


vsprintf_len(string, format, args)

	char *string;

	const char *format;

	va_list args;

{

	vsprintf(string, format, args);

	return strlen(string);

}


void HELPER(idte)(CPUS390XState *env, uint64_t r1, uint64_t r2, uint32_t m4)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    const uintptr_t ra = GETPC();

    uint64_t table, entry, raddr;

    uint16_t entries, i, index = 0;

    if (r2 & 0xff000) {

        cpu_restore_state(cs, ra);

        program_interrupt(env, PGM_SPECIFICATION, 4);

    }

    if (!(r2 & 0x800)) {

        /* invalidation-and-clearing operation */

        table = r1 & _ASCE_ORIGIN;

        entries = (r2 & 0x7ff) + 1;

        switch (r1 & _ASCE_TYPE_MASK) {

        case _ASCE_TYPE_REGION1:

            index = (r2 >> 53) & 0x7ff;

            break;

        case _ASCE_TYPE_REGION2:

            index = (r2 >> 42) & 0x7ff;

            break;

        case _ASCE_TYPE_REGION3:

            index = (r2 >> 31) & 0x7ff;

            break;

        case _ASCE_TYPE_SEGMENT:

            index = (r2 >> 20) & 0x7ff;

            break;

        }

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

            /* addresses are not wrapped in 24/31bit mode but table index is */

            raddr = table + ((index + i) & 0x7ff) * sizeof(entry);

            entry = cpu_ldq_real_ra(env, raddr, ra);

            if (!(entry & _REGION_ENTRY_INV)) {

                /* we are allowed to not store if already invalid */

                entry |= _REGION_ENTRY_INV;

                cpu_stq_real_ra(env, raddr, entry, ra);

            }

        }

    }

    /* We simply flush the complete tlb, therefore we can ignore r3. */

    if (m4 & 1) {

        tlb_flush(cs);

    } else {

        tlb_flush_all_cpus_synced(cs);

    }

}


CharDriverState *qemu_chr_open_opts(QemuOpts *opts,

                                    void (*init)(struct CharDriverState *s))

{

    CharDriverState *chr;

    int i;

    if (qemu_opts_id(opts) == NULL) {

        fprintf(stderr, "chardev: no id specified\n");

        return NULL;

    }

    for (i = 0; i < ARRAY_SIZE(backend_table); i++) {

        if (strcmp(backend_table[i].name, qemu_opt_get(opts, "backend")) == 0)

            break;

    }

    if (i == ARRAY_SIZE(backend_table)) {

        fprintf(stderr, "chardev: backend \"%s\" not found\n",

                qemu_opt_get(opts, "backend"));

        return NULL;

    }

    chr = backend_table[i].open(opts);

    if (!chr) {

        fprintf(stderr, "chardev: opening backend \"%s\" failed\n",

                qemu_opt_get(opts, "backend"));

        return NULL;

    }

    if (!chr->filename)

        chr->filename = qemu_strdup(qemu_opt_get(opts, "backend"));

    chr->init = init;

    TAILQ_INSERT_TAIL(&chardevs, chr, next);

    if (qemu_opt_get_bool(opts, "mux", 0)) {

        CharDriverState *base = chr;

        int len = strlen(qemu_opts_id(opts)) + 6;

        base->label = qemu_malloc(len);

        snprintf(base->label, len, "%s-base", qemu_opts_id(opts));

        chr = qemu_chr_open_mux(base);

        chr->filename = base->filename;

        TAILQ_INSERT_TAIL(&chardevs, chr, next);

    }

    chr->label = qemu_strdup(qemu_opts_id(opts));

    return chr;

}


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

{

    AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;

    ac3_audio_block *ab = &ctx->audio_block;

    int frame_start;

    int i, j, k, l, value;

    float tmp_block_first_half[128], tmp_block_second_half[128];

    int16_t *out_samples = (int16_t *)data;

    int nfchans;

    //Synchronize the frame.

    frame_start = ac3_synchronize(buf, buf_size);

    if (frame_start == -1) {

        av_log(avctx, AV_LOG_ERROR, "frame is not synchronized\n");

        *data_size = 0;

        return buf_size;

    }

    //Initialize the GetBitContext with the start of valid AC3 Frame.

    init_get_bits(&(ctx->gb), buf + frame_start, (buf_size - frame_start) * 8);

    //Parse the syncinfo.

    //If 'fscod' or 'bsid' is not valid the decoder shall mute as per the standard.

    if (!ac3_parse_sync_info(ctx)) {

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

        *data_size = 0;

        return -1;

    }

    //Check for the errors.

    /* if (ac3_error_check(ctx)) {

        *data_size = 0;

        return -1;

    } */

    //Parse the BSI.

    //If 'bsid' is not valid decoder shall not decode the audio as per the standard.

    if (ac3_parse_bsi(ctx)) {

        av_log(avctx, AV_LOG_ERROR, "bsid is not valid\n");

        *data_size = 0;

        return -1;

    }

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

        memset(ctx->delay[i], 0, sizeof(ctx->delay[i]));

    avctx->sample_rate = ctx->sync_info.sampling_rate;

    avctx->bit_rate = ctx->sync_info.bit_rate;

    if (avctx->channels == 0) {

        //avctx->channels = ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0);

        ctx->output = AC3_OUTPUT_UNMODIFIED;

    }

    else if ((ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0)) < avctx->channels) {

        av_log(avctx, AV_LOG_INFO, "ac3_decoder: AC3 Source Channels Are Less Then Specified %d: Output to %d Channels\n",

                avctx->channels, (ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0)));

        //avctx->channels = ctx->bsi.nfchans + ((ctx->bsi.flags & AC3_BSI_LFEON) ? 1 : 0);

        ctx->output = AC3_OUTPUT_UNMODIFIED;

    }

    else if (avctx->channels == 1) {

        ctx->output = AC3_OUTPUT_MONO;

    } else if (avctx->channels == 2) {

        if (ctx->bsi.dsurmod == 0x02)

            ctx->output = AC3_OUTPUT_DOLBY;

        else

            ctx->output = AC3_OUTPUT_STEREO;

    }

    av_log(avctx, AV_LOG_INFO, "channels = %d \t bit rate = %d \t sampling rate = %d \n", avctx->channels, avctx->sample_rate, avctx->bit_rate);

    //Parse the Audio Blocks.

    *data_size = 0;

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

        if (ac3_parse_audio_block(ctx, i)) {

            av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");

            *data_size = 0;

            return -1;

        }

        av_log(NULL, AV_LOG_INFO, "doing imdct\n");

        if (ctx->bsi.flags & AC3_BSI_LFEON) {

            ff_imdct_calc(&ctx->imdct_ctx_512, ctx->tmp_output, ab->transform_coeffs[0], ctx->tmp_imdct);

            for (l = 0; l < 256; l++)

                ab->block_output[0][l] = ctx->tmp_output[l] * window[l] + ctx->delay[0][l] * window[255 -l];

            memcpy(ctx->delay[0], ctx->tmp_output + 256, sizeof(ctx->delay[0]));

        }

        for (j = 0; j < ctx->bsi.nfchans; j++) {

            if (ctx->audio_block.blksw & (1 << j)) {

                for (k = 0; k < 128; k++) {

                    tmp_block_first_half[k] = ab->transform_coeffs[j + 1][2 * k];

                    tmp_block_second_half[k] = ab->transform_coeffs[j + 1][2 * k + 1];

                }

                ff_imdct_calc(&ctx->imdct_ctx_256, ctx->tmp_output, tmp_block_first_half, ctx->tmp_imdct);

                for (l = 0; l < 256; l++)

                    ab->block_output[j + 1][l] = ctx->tmp_output[l] * window[l] + ctx->delay[j + 1][l] * window[255 - l];

                ff_imdct_calc(&ctx->imdct_ctx_256, ctx->delay[j + 1], tmp_block_second_half, ctx->tmp_imdct);

            } else {

                ff_imdct_calc(&ctx->imdct_ctx_512, ctx->tmp_output, ab->transform_coeffs[j + 1], ctx->tmp_imdct);

                for (l = 0; l < 256; l++)

                    ab->block_output[j + 1][l] = ctx->tmp_output[l] * window[l] + ctx->delay[j + 1][l] * window[255 - l];

                memcpy(ctx->delay[j + 1], ctx->tmp_output + 256, sizeof(ctx->delay[j + 1]));

            }

        }

        if (ctx->bsi.flags & AC3_BSI_LFEON) {

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

                value = lrint(ab->block_output[0][l]);

                if (value < -32768)

                    value = -32768;

                else if (value > 32767)

                    value = 32767;

                *(out_samples++) = value;

            }

            *data_size += 256 * sizeof(int16_t);

        }

        do_downmix(ctx);

        if (ctx->output == AC3_OUTPUT_UNMODIFIED)

            nfchans = ctx->bsi.nfchans;

        else

            nfchans = avctx->channels;

        for (k = 0; k < nfchans; k++)

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

                value = lrint(ab->block_output[k + 1][l]);

                if (value < -32768)

                    value = -32768;

                else if (value > 32767)

                    value = 32767;

                *(out_samples++) = value;

            }

        *data_size += nfchans * 256 * sizeof (int16_t);

    }

    return ctx->sync_info.framesize;

}


static void ac97_save (QEMUFile *f, void *opaque)

{

    size_t i;

    uint8_t active[LAST_INDEX];

    AC97LinkState *s = opaque;

    pci_device_save (s->pci_dev, f);

    qemu_put_be32s (f, &s->glob_cnt);

    qemu_put_be32s (f, &s->glob_sta);

    qemu_put_be32s (f, &s->cas);

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

        AC97BusMasterRegs *r = &s->bm_regs[i];

        qemu_put_be32s (f, &r->bdbar);

        qemu_put_8s (f, &r->civ);

        qemu_put_8s (f, &r->lvi);

        qemu_put_be16s (f, &r->sr);

        qemu_put_be16s (f, &r->picb);

        qemu_put_8s (f, &r->piv);

        qemu_put_8s (f, &r->cr);

        qemu_put_be32s (f, &r->bd_valid);

        qemu_put_be32s (f, &r->bd.addr);

        qemu_put_be32s (f, &r->bd.ctl_len);

    }

    qemu_put_buffer (f, s->mixer_data, sizeof (s->mixer_data));

    active[PI_INDEX] = AUD_is_active_in (s->voice_pi) ? 1 : 0;

    active[PO_INDEX] = AUD_is_active_out (s->voice_po) ? 1 : 0;

    active[MC_INDEX] = AUD_is_active_in (s->voice_mc) ? 1 : 0;

    qemu_put_buffer (f, active, sizeof (active));

}


static void timer_save(QEMUFile *f, void *opaque)

{

    if (cpu_ticks_enabled) {

        hw_error("cannot save state if virtual timers are running");

    }

    qemu_put_be64(f, cpu_ticks_offset);

    qemu_put_be64(f, ticks_per_sec);

    qemu_put_be64(f, cpu_clock_offset);

}


void eth_get_protocols(const uint8_t *headers,

                       uint32_t hdr_length,

                       bool *isip4, bool *isip6,

                       bool *isudp, bool *istcp)

{

    int proto;

    size_t l2hdr_len = eth_get_l2_hdr_length(headers);

    assert(hdr_length >= eth_get_l2_hdr_length(headers));

    *isip4 = *isip6 = *isudp = *istcp = false;

    proto = eth_get_l3_proto(headers, l2hdr_len);

    if (proto == ETH_P_IP) {

        *isip4 = true;

        struct ip_header *iphdr;

        assert(hdr_length >=

            eth_get_l2_hdr_length(headers) + sizeof(struct ip_header));

        iphdr = PKT_GET_IP_HDR(headers);

        if (IP_HEADER_VERSION(iphdr) == IP_HEADER_VERSION_4) {

            if (iphdr->ip_p == IP_PROTO_TCP) {

                *istcp = true;

            } else if (iphdr->ip_p == IP_PROTO_UDP) {

                *isudp = true;

            }

        }

    } else if (proto == ETH_P_IPV6) {

        uint8_t l4proto;

        size_t full_ip6hdr_len;

        struct iovec hdr_vec;

        hdr_vec.iov_base = (void *) headers;

        hdr_vec.iov_len = hdr_length;

        *isip6 = true;

        if (eth_parse_ipv6_hdr(&hdr_vec, 1, l2hdr_len,

                              &l4proto, &full_ip6hdr_len)) {

            if (l4proto == IP_PROTO_TCP) {

                *istcp = true;

            } else if (l4proto == IP_PROTO_UDP) {

                *isudp = true;

            }

        }

    }

}


VncInfo *qmp_query_vnc(Error **errp)

{

    VncInfo *info = g_malloc0(sizeof(*info));

    VncDisplay *vd = vnc_display_find(NULL);

    SocketAddressLegacy *addr = NULL;

    if (vd == NULL || !vd->nlsock) {

        info->enabled = false;

    } else {

        info->enabled = true;

        /* for compatibility with the original command */

        info->has_clients = true;

        info->clients = qmp_query_client_list(vd);

        if (vd->lsock == NULL) {

            return info;

        }

        addr = qio_channel_socket_get_local_address(vd->lsock[0], errp);

        if (!addr) {

            goto out_error;

        }

        switch (addr->type) {

        case SOCKET_ADDRESS_LEGACY_KIND_INET:

            info->host = g_strdup(addr->u.inet.data->host);

            info->service = g_strdup(addr->u.inet.data->port);

            if (addr->u.inet.data->ipv6) {

                info->family = NETWORK_ADDRESS_FAMILY_IPV6;

            } else {

                info->family = NETWORK_ADDRESS_FAMILY_IPV4;

            }

            break;

        case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

            info->host = g_strdup("");

            info->service = g_strdup(addr->u.q_unix.data->path);

            info->family = NETWORK_ADDRESS_FAMILY_UNIX;

            break;

        case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

        case SOCKET_ADDRESS_LEGACY_KIND_FD:

            error_setg(errp, "Unsupported socket address type %s",

                       SocketAddressLegacyKind_lookup[addr->type]);

            goto out_error;

        default:

            abort();

        }

        info->has_host = true;

        info->has_service = true;

        info->has_family = true;

        info->has_auth = true;

        info->auth = g_strdup(vnc_auth_name(vd));

    }

    qapi_free_SocketAddressLegacy(addr);

    return info;

out_error:

    qapi_free_SocketAddressLegacy(addr);

    qapi_free_VncInfo(info);

    return NULL;

}


static void unassigned_mem_write(void *opaque, hwaddr addr,

                                 uint64_t val, unsigned size)

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem write " TARGET_FMT_plx " = 0x%"PRIx64"\n", addr, val);

#endif

#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)

    cpu_unassigned_access(cpu_single_env, addr, 1, 0, 0, size);

#endif

}


static int milkymist_vgafb_init(SysBusDevice *dev)

{

    MilkymistVgafbState *s = FROM_SYSBUS(typeof(*s), dev);

    memory_region_init_io(&s->regs_region, &vgafb_mmio_ops, s,

            "milkymist-vgafb", R_MAX * 4);

    sysbus_init_mmio(dev, &s->regs_region);

    s->con = graphic_console_init(vgafb_update_display,

                                  vgafb_invalidate_display,

                                  NULL, NULL, s);

    return 0;

}


static void memory_init(void)

{

    qemu_mutex_init(&flat_view_mutex);

}


static void tcg_reg_alloc_bb_end(TCGContext *s, TCGRegSet allocated_regs)

{

    int i;

    for (i = s->nb_globals; i < s->nb_temps; i++) {

        TCGTemp *ts = &s->temps[i];

        if (ts->temp_local) {

            temp_save(s, ts, allocated_regs);

        } else {

#ifdef USE_LIVENESS_ANALYSIS

            /* ??? Liveness does not yet incorporate indirect bases.  */

            if (!ts->indirect_base) {

                /* The liveness analysis already ensures that temps are dead.

                   Keep an assert for safety. */

                assert(ts->val_type == TEMP_VAL_DEAD);

                continue;

            }

#endif

            temp_dead(s, ts);

        }

    }

    save_globals(s, allocated_regs);

}


static int bitplane_decoding(uint8_t* plane, int width, int height, VC9Context *v)

{

    int imode, x, y, i, code, use_vertical_tile, tile_w, tile_h;

    uint8_t invert, *planep = plane;

    int stride= width;

    invert = get_bits(&v->gb, 1);

    imode = get_vlc2(&v->gb, vc9_imode_vlc.table, VC9_IMODE_VLC_BITS, 2);

    av_log(v->avctx, AV_LOG_DEBUG, "Bitplane: imode=%i, invert=%i\n",

           imode, invert);

    switch (imode)

    {

    case IMODE_RAW:

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

        {

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

                planep[x] = (-get_bits(&v->gb, 1)); //-1=0xFF

            planep += stride;

        }

        invert=0; //spec says ignore invert if raw

        break;

    case IMODE_DIFF2:

    case IMODE_NORM2:

        if ((height*width) & 1) *(++planep) = get_bits(&v->gb, 1);

        for(i=0; i<(height*width)>>1; i++){

            code = get_vlc2(&v->gb, vc9_norm2_vlc.table, VC9_NORM2_VLC_BITS, 2);

            *(++planep) = code&1; //lsb => left

            *(++planep) = code&2; //msb => right - this is a bitplane, so only !0 matters

            //FIXME width->stride

        }

        break;

    case IMODE_DIFF6:

    case IMODE_NORM6:

        use_vertical_tile= height%3==0 && width%3!=0;

        tile_w= use_vertical_tile ? 2 : 3;

        tile_h= use_vertical_tile ? 3 : 2;

        for(y= height%tile_h; y<height; y+=tile_h){

            for(x= width%tile_w; x<width; x+=tile_w){

                code = get_vlc2(&v->gb, vc9_norm6_vlc.table, VC9_NORM6_VLC_BITS, 2);

                //FIXME following is a pure guess and probably wrong

                planep[x     + 0*stride]= (code>>0)&1;

                planep[x + 1 + 0*stride]= (code>>1)&1;

                if(use_vertical_tile){

                    planep[x + 0 + 1*stride]= (code>>2)&1;

                    planep[x + 1 + 1*stride]= (code>>3)&1;

                    planep[x + 0 + 2*stride]= (code>>4)&1;

                    planep[x + 1 + 2*stride]= (code>>5)&1;

                }else{

                    planep[x + 2 + 0*stride]= (code>>2)&1;

                    planep[x + 0 + 1*stride]= (code>>3)&1;

                    planep[x + 1 + 1*stride]= (code>>4)&1;

                    planep[x + 2 + 1*stride]= (code>>5)&1;

                }

            }

        }

        x= width % tile_w;

        decode_colskip(plane  ,         x, height         , stride, v);

        decode_rowskip(plane+x, width - x, height % tile_h, stride, v);

        break;

    case IMODE_ROWSKIP:

        decode_rowskip(plane, width, height, stride, v);

        break;

    case IMODE_COLSKIP: //Teh ugly

        decode_colskip(plane, width, height, stride, v);

        break;

    default: break;

    }

    /* Applying diff operator */

    if (imode == IMODE_DIFF2 || imode == IMODE_DIFF6)

    {

        planep = plane;

        planep[0] ^= invert;

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

            planep[x] ^= planep[x-1];

        for (y=1; y<height; y++)

        {

            planep += stride;

            planep[0] ^= planep[-stride];

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

            {

                if (planep[x-1] != planep[x-stride]) planep[x] ^= invert;

                else                                 planep[x] ^= planep[x-1];

            }

        }

    }

    else if (invert)

    {

        planep = plane;

        for (x=0; x<width*height; x++) planep[x] = !planep[x]; //FIXME stride

    }

    return 0;

}


static int qpa_init_out (HWVoiceOut *hw, audsettings_t *as)

{

    int error;

    static pa_sample_spec ss;

    audsettings_t obt_as = *as;

    PAVoiceOut *pa = (PAVoiceOut *) hw;

    ss.format = audfmt_to_pa (as->fmt, as->endianness);

    ss.channels = as->nchannels;

    ss.rate = as->freq;

    obt_as.fmt = pa_to_audfmt (ss.format, &obt_as.endianness);

    pa->s = pa_simple_new (

        conf.server,

        "qemu",

        PA_STREAM_PLAYBACK,

        conf.sink,

        "pcm.playback",

        &ss,

        NULL,                   /* channel map */

        NULL,                   /* buffering attributes */

        &error

        );

    if (!pa->s) {

        qpa_logerr (error, "pa_simple_new for playback failed\n");

        goto fail1;

    }

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = conf.samples;

    pa->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!pa->pcm_buf) {

        dolog ("Could not allocate buffer (%d bytes)\n",

               hw->samples << hw->info.shift);

        goto fail2;

    }

    if (audio_pt_init (&pa->pt, qpa_thread_out, hw, AUDIO_CAP, AUDIO_FUNC)) {

        goto fail3;

    }

    return 0;

 fail3:

    free (pa->pcm_buf);

    pa->pcm_buf = NULL;

 fail2:

    pa_simple_free (pa->s);

    pa->s = NULL;

 fail1:

    return -1;

}


static int proxy_name_to_path(FsContext *ctx, V9fsPath *dir_path,

                              const char *name, V9fsPath *target)

{

    if (dir_path) {

        v9fs_string_sprintf((V9fsString *)target, "%s/%s",

                            dir_path->data, name);

    } else {

        v9fs_string_sprintf((V9fsString *)target, "%s", name);

    }

    /* Bump the size for including terminating NULL */

    target->size++;

    return 0;

}


static int v9fs_synth_mknod(FsContext *fs_ctx, V9fsPath *path,

                       const char *buf, FsCred *credp)

{

    errno = EPERM;

    return -1;

}


static int roq_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                            const AVFrame *frame, int *got_packet)

{

    RoqContext *enc = avctx->priv_data;

    int size, ret;

    enc->avctx = avctx;

    enc->frame_to_enc = frame;

    if (frame->quality)

        enc->lambda = frame->quality - 1;

    else

        enc->lambda = 2*ROQ_LAMBDA_SCALE;

    /* 138 bits max per 8x8 block +

     *     256 codebooks*(6 bytes 2x2 + 4 bytes 4x4) + 8 bytes frame header */

    size = ((enc->width * enc->height / 64) * 138 + 7) / 8 + 256 * (6 + 4) + 8;

    if ((ret = ff_alloc_packet(pkt, size)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet with size %d.\n", size);

        return ret;

    }

    enc->out_buf = pkt->data;

    /* Check for I frame */

    if (enc->framesSinceKeyframe == avctx->gop_size)

        enc->framesSinceKeyframe = 0;

    if (enc->first_frame) {

        /* Alloc memory for the reconstruction data (we must know the stride

         for that) */

        if (ff_get_buffer(avctx, enc->current_frame, 0) ||

            ff_get_buffer(avctx, enc->last_frame, 0)) {

            av_log(avctx, AV_LOG_ERROR, "  RoQ: get_buffer() failed\n");

            return -1;

        }

        /* Before the first video frame, write a "video info" chunk */

        roq_write_video_info_chunk(enc);

        enc->first_frame = 0;

    }

    /* Encode the actual frame */

    roq_encode_video(enc);

    pkt->size   = enc->out_buf - pkt->data;

    if (enc->framesSinceKeyframe == 1)

        pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static int swf_write_video(AVFormatContext *s,

                           AVCodecContext *enc, const uint8_t *buf, int size)

{

    SWFContext *swf = s->priv_data;

    ByteIOContext *pb = &s->pb;

    int c = 0;

    int outSize = 0;

    int outSamples = 0;

    /* Flash Player limit */

    if ( swf->swf_frame_number >= 16000 ) {

        return 0;

    }

    /* Store video data in queue */

    if ( enc->codec_type == CODEC_TYPE_VIDEO ) {

        SWFFrame *new_frame = av_malloc(sizeof(SWFFrame));

        new_frame->prev = 0;

        new_frame->next = swf->frame_head;

        new_frame->data = av_malloc(size);

        new_frame->size = size;

        memcpy(new_frame->data,buf,size);

        swf->frame_head = new_frame;

        if ( swf->frame_tail == 0 ) {

            swf->frame_tail = new_frame;

        }

    }

    if ( swf->audio_type ) {

        /* Prescan audio data for this swf frame */

retry_swf_audio_packet:

        if ( ( swf->audio_size-outSize ) >= 4 ) {

            int mp3FrameSize = 0;

            int mp3SampleRate = 0;

            int mp3IsMono = 0;

            int mp3SamplesPerFrame = 0;

            /* copy out mp3 header from ring buffer */

            uint8_t header[4];

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

                header[c] = swf->audio_fifo[(swf->audio_in_pos+outSize+c) % AUDIO_FIFO_SIZE];

            }

            if ( swf_mp3_info(header,&mp3FrameSize,&mp3SamplesPerFrame,&mp3SampleRate,&mp3IsMono) ) {

                if ( ( swf->audio_size-outSize ) >= mp3FrameSize ) {

                    outSize += mp3FrameSize;

                    outSamples += mp3SamplesPerFrame;

                    if ( ( swf->sound_samples + outSamples + swf->samples_per_frame ) < swf->video_samples ) {

                        goto retry_swf_audio_packet;

                    }

                }

            } else {

                /* invalid mp3 data, skip forward

                we need to do this since the Flash Player

                does not like custom headers */

                swf->audio_in_pos ++;

                swf->audio_size --;

                swf->audio_in_pos %= AUDIO_FIFO_SIZE;

                goto retry_swf_audio_packet;

            }

        }

        /* audio stream is behind video stream, bail */

        if ( ( swf->sound_samples + outSamples + swf->samples_per_frame ) < swf->video_samples ) {

            return 0;

        }

        /* compute audio/video drift */

        if ( enc->codec_type == CODEC_TYPE_VIDEO ) {

            swf->skip_samples = (int)( ( (double)(swf->swf_frame_number) * (double)enc->frame_rate_base * 44100. ) / (double)(enc->frame_rate) );

            swf->skip_samples -=  swf->video_samples;

        }

    }

    /* check if we need to insert a padding frame */

    if (swf->skip_samples <= ( swf->samples_per_frame / 2 ) ) {

        /* no, it is time for a real frame, check if one is available */

        if ( swf->frame_tail ) {

            if ( swf->video_type == CODEC_ID_FLV1 ) {

                if ( swf->video_frame_number == 0 ) {

                    /* create a new video object */

                    put_swf_tag(s, TAG_VIDEOSTREAM);

                    put_le16(pb, VIDEO_ID);

                    put_le16(pb, 15000 ); /* hard flash player limit */

                    put_le16(pb, enc->width);

                    put_le16(pb, enc->height);

                    put_byte(pb, 0);

                    put_byte(pb, SWF_VIDEO_CODEC_FLV1);

                    put_swf_end_tag(s);

                    /* place the video object for the first time */

                    put_swf_tag(s, TAG_PLACEOBJECT2);

                    put_byte(pb, 0x36);

                    put_le16(pb, 1);

                    put_le16(pb, VIDEO_ID);

                    put_swf_matrix(pb, 1 << FRAC_BITS, 0, 0, 1 << FRAC_BITS, 0, 0);

                    put_le16(pb, swf->video_frame_number );

                    put_byte(pb, 'v');

                    put_byte(pb, 'i');

                    put_byte(pb, 'd');

                    put_byte(pb, 'e');

                    put_byte(pb, 'o');

                    put_byte(pb, 0x00);

                    put_swf_end_tag(s);

                } else {

                    /* mark the character for update */

                    put_swf_tag(s, TAG_PLACEOBJECT2);

                    put_byte(pb, 0x11);

                    put_le16(pb, 1);

                    put_le16(pb, swf->video_frame_number );

                    put_swf_end_tag(s);

                }

                // write out pending frames

                for (; ( enc->frame_number - swf->video_frame_number ) > 0;) {

                    /* set video frame data */

                    put_swf_tag(s, TAG_VIDEOFRAME | TAG_LONG);

                    put_le16(pb, VIDEO_ID);

                    put_le16(pb, swf->video_frame_number++ );

                    put_buffer(pb, swf->frame_tail->data, swf->frame_tail->size);

                    put_swf_end_tag(s);

                }

            } else if ( swf->video_type == CODEC_ID_MJPEG ) {

                if (swf->swf_frame_number > 0) {

                    /* remove the shape */

                    put_swf_tag(s, TAG_REMOVEOBJECT);

                    put_le16(pb, SHAPE_ID); /* shape ID */

                    put_le16(pb, 1); /* depth */

                    put_swf_end_tag(s);

                    /* free the bitmap */

                    put_swf_tag(s, TAG_FREECHARACTER);

                    put_le16(pb, BITMAP_ID);

                    put_swf_end_tag(s);

                }

                put_swf_tag(s, TAG_JPEG2 | TAG_LONG);

                put_le16(pb, BITMAP_ID); /* ID of the image */

                /* a dummy jpeg header seems to be required */

                put_byte(pb, 0xff);

                put_byte(pb, 0xd8);

                put_byte(pb, 0xff);

                put_byte(pb, 0xd9);

                /* write the jpeg image */

                put_buffer(pb, swf->frame_tail->data, swf->frame_tail->size);

                put_swf_end_tag(s);

                /* draw the shape */

                put_swf_tag(s, TAG_PLACEOBJECT);

                put_le16(pb, SHAPE_ID); /* shape ID */

                put_le16(pb, 1); /* depth */

                put_swf_matrix(pb, 20 << FRAC_BITS, 0, 0, 20 << FRAC_BITS, 0, 0);

                put_swf_end_tag(s);

            } else {

                /* invalid codec */

            }

            av_free(swf->frame_tail->data);

            swf->frame_tail = swf->frame_tail->prev;

            if ( swf->frame_tail ) {

                if ( swf->frame_tail->next ) {

                    av_free(swf->frame_tail->next);

                }

                swf->frame_tail->next = 0;

            } else {

                swf->frame_head = 0;

            }

            swf->swf_frame_number ++;

        }

    }

    swf->video_samples += swf->samples_per_frame;

    /* streaming sound always should be placed just before showframe tags */

    if ( outSize > 0 ) {

        put_swf_tag(s, TAG_STREAMBLOCK | TAG_LONG);

        put_le16(pb, outSamples);

        put_le16(pb, 0);

        for (c=0; c<outSize; c++) {

            put_byte(pb,swf->audio_fifo[(swf->audio_in_pos+c) % AUDIO_FIFO_SIZE]);

        }

        put_swf_end_tag(s);

        /* update FIFO */

        swf->sound_samples += outSamples;

        swf->audio_in_pos += outSize;

        swf->audio_size -= outSize;

        swf->audio_in_pos %= AUDIO_FIFO_SIZE;

    }

    /* output the frame */

    put_swf_tag(s, TAG_SHOWFRAME);

    put_swf_end_tag(s);

    put_flush_packet(&s->pb);

    return 0;

}


static int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,

                           int buf_size, AVCodecContext *avctx)

{

    HEVCParserContext *ctx = s->priv_data;

    int ret, i;

    ret = ff_h2645_packet_split(&ctx->pkt, buf, buf_size, avctx, 0, 0,

                                AV_CODEC_ID_HEVC);

    if (ret < 0)

        return ret;

    for (i = 0; i < ctx->pkt.nb_nals; i++) {

        H2645NAL *nal = &ctx->pkt.nals[i];

        /* ignore everything except parameter sets and VCL NALUs */

        switch (nal->type) {

        case NAL_VPS: ff_hevc_decode_nal_vps(&nal->gb, avctx, &ctx->ps);    break;

        case NAL_SPS: ff_hevc_decode_nal_sps(&nal->gb, avctx, &ctx->ps, 1); break;

        case NAL_PPS: ff_hevc_decode_nal_pps(&nal->gb, avctx, &ctx->ps);    break;

        case NAL_TRAIL_R:

        case NAL_TRAIL_N:

        case NAL_TSA_N:

        case NAL_TSA_R:

        case NAL_STSA_N:

        case NAL_STSA_R:

        case NAL_BLA_W_LP:

        case NAL_BLA_W_RADL:

        case NAL_BLA_N_LP:

        case NAL_IDR_W_RADL:

        case NAL_IDR_N_LP:

        case NAL_CRA_NUT:

        case NAL_RADL_N:

        case NAL_RADL_R:

        case NAL_RASL_N:

        case NAL_RASL_R:

            if (buf == avctx->extradata) {

                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", nal->type);

                return AVERROR_INVALIDDATA;

            }

            hevc_parse_slice_header(s, nal, avctx);

            break;

        }

    }

    return 0;

}


static int get_channel_idx(char **map, int *ch, char delim, int max_ch)

{

    char *next = split(*map, delim);

    int len;

    int n = 0;

    if (!next && delim == '-')

        return AVERROR(EINVAL);

    if (!*map)

        return AVERROR(EINVAL);

    len = strlen(*map);

    sscanf(*map, "%d%n", ch, &n);

    if (n != len)

        return AVERROR(EINVAL);

    if (*ch < 0 || *ch > max_ch)

        return AVERROR(EINVAL);

    *map = next;

    return 0;

}


static int decode_residual_block(AVSContext *h, GetBitContext *gb,

                                 const struct dec_2dvlc *r, int esc_golomb_order,

                                 int qp, uint8_t *dst, int stride) {

    int i, level_code, esc_code, level, run, mask;

    DCTELEM level_buf[65];

    uint8_t run_buf[65];

    DCTELEM *block = h->block;

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

        level_code = get_ue_code(gb,r->golomb_order);

        if(level_code >= ESCAPE_CODE) {

            run = ((level_code - ESCAPE_CODE) >> 1) + 1;

            esc_code = get_ue_code(gb,esc_golomb_order);

            level = esc_code + (run > r->max_run ? 1 : r->level_add[run]);

            while(level > r->inc_limit)

                r++;

            mask = -(level_code & 1);

            level = (level^mask) - mask;

        } else {

            level = r->rltab[level_code][0];

            if(!level) //end of block signal

                break;

            run   = r->rltab[level_code][1];

            r += r->rltab[level_code][2];

        }

        level_buf[i] = level;

        run_buf[i] = run;

    }

    if(dequant(h,level_buf, run_buf, block, ff_cavs_dequant_mul[qp],

               ff_cavs_dequant_shift[qp], i))

        return -1;

    h->cdsp.cavs_idct8_add(dst,block,stride);

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

    return 0;

}


static void device_set_hotplugged(Object *obj, bool value, Error **err)

{

    DeviceState *dev = DEVICE(obj);

    dev->hotplugged = value;

}


static void mips_fulong2e_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    char *filename;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios = g_new(MemoryRegion, 1);

    long bios_size;

    int64_t kernel_entry;

    qemu_irq *i8259;

    qemu_irq *cpu_exit_irq;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    I2CBus *smbus;

    int i;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    MIPSCPU *cpu;

    CPUMIPSState *env;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "Loongson-2E";

    }

    cpu = cpu_mips_init(cpu_model);

    if (cpu == NULL) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    env = &cpu->env;

    qemu_register_reset(main_cpu_reset, cpu);

    /* fulong 2e has 256M ram. */

    ram_size = 256 * 1024 * 1024;

    /* fulong 2e has a 1M flash.Winbond W39L040AP70Z */

    bios_size = 1024 * 1024;

    /* allocate RAM */

    memory_region_init_ram(ram, NULL, "fulong2e.ram", ram_size, &error_abort);

    vmstate_register_ram_global(ram);

    memory_region_init_ram(bios, NULL, "fulong2e.bios", bios_size,

                           &error_abort);

    vmstate_register_ram_global(bios);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_add_subregion(address_space_mem, 0x1fc00000LL, bios);

    /* We do not support flash operation, just loading pmon.bin as raw BIOS.

     * Please use -L to set the BIOS path and -bios to set bios name. */

    if (kernel_filename) {

        loaderparams.ram_size = ram_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        kernel_entry = load_kernel (env);

        write_bootloader(env, memory_region_get_ram_ptr(bios), kernel_entry);

    } else {

        if (bios_name == NULL) {

                bios_name = FULONG_BIOSNAME;

        }

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (filename) {

            bios_size = load_image_targphys(filename, 0x1fc00000LL,

                                            BIOS_SIZE);

            g_free(filename);

        } else {

            bios_size = -1;

        }

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

            !kernel_filename && !qtest_enabled()) {

            error_report("Could not load MIPS bios '%s'", bios_name);

            exit(1);

        }

    }

    /* Init internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /* North bridge, Bonito --> IP2 */

    pci_bus = bonito_init((qemu_irq *)&(env->irq[2]));

    /* South bridge */

    ide_drive_get(hd, MAX_IDE_BUS);

    isa_bus = vt82c686b_init(pci_bus, PCI_DEVFN(FULONG2E_VIA_SLOT, 0));

    if (!isa_bus) {

        fprintf(stderr, "vt82c686b_init error\n");

        exit(1);

    }

    /* Interrupt controller */

    /* The 8259 -> IP5  */

    i8259 = i8259_init(isa_bus, env->irq[5]);

    isa_bus_irqs(isa_bus, i8259);

    vt82c686b_ide_init(pci_bus, hd, PCI_DEVFN(FULONG2E_VIA_SLOT, 1));

    pci_create_simple(pci_bus, PCI_DEVFN(FULONG2E_VIA_SLOT, 2),

                      "vt82c686b-usb-uhci");

    pci_create_simple(pci_bus, PCI_DEVFN(FULONG2E_VIA_SLOT, 3),

                      "vt82c686b-usb-uhci");

    smbus = vt82c686b_pm_init(pci_bus, PCI_DEVFN(FULONG2E_VIA_SLOT, 4),

                              0xeee1, NULL);

    /* TODO: Populate SPD eeprom data.  */

    smbus_eeprom_init(smbus, 1, eeprom_spd, sizeof(eeprom_spd));

    /* init other devices */

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

    /* Super I/O */

    isa_create_simple(isa_bus, "i8042");

    rtc_init(isa_bus, 2000, NULL);

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

        if (serial_hds[i]) {

            serial_isa_init(isa_bus, i, serial_hds[i]);

        }

    }

    if (parallel_hds[0]) {

        parallel_init(isa_bus, 0, parallel_hds[0]);

    }

    /* Sound card */

    audio_init(pci_bus);

    /* Network card */

    network_init(pci_bus);

}


static int pcm_decode_frame(AVCodecContext *avctx,
			    void *data, int *data_size,
			    uint8_t *buf, int buf_size)
{
    PCMDecode *s = avctx->priv_data;
    int n;
    short *samples;
    uint8_t *src;
    samples = data;
    src = buf;
    switch(avctx->codec->id) {
    case CODEC_ID_PCM_S16LE:
        n = buf_size >> 1;
        for(;n>0;n--) {
            *samples++ = src[0] | (src[1] << 8);
            src += 2;
        }
        break;
    case CODEC_ID_PCM_S16BE:
        n = buf_size >> 1;
        for(;n>0;n--) {
            *samples++ = (src[0] << 8) | src[1];
            src += 2;
        }
        break;
    case CODEC_ID_PCM_U16LE:
        n = buf_size >> 1;
        for(;n>0;n--) {
            *samples++ = (src[0] | (src[1] << 8)) - 0x8000;
            src += 2;
        }
        break;
    case CODEC_ID_PCM_U16BE:
        n = buf_size >> 1;
        for(;n>0;n--) {
            *samples++ = ((src[0] << 8) | src[1]) - 0x8000;
            src += 2;
        }
        break;
    case CODEC_ID_PCM_S8:
        n = buf_size;
        for(;n>0;n--) {
            *samples++ = src[0] << 8;
            src++;
        }
        break;
    case CODEC_ID_PCM_U8:
        n = buf_size;
        for(;n>0;n--) {
            *samples++ = ((int)src[0] - 128) << 8;
            src++;
        }
        break;
    case CODEC_ID_PCM_ALAW:
    case CODEC_ID_PCM_MULAW:
        n = buf_size;
        for(;n>0;n--) {
            *samples++ = s->table[src[0]];
            src++;
        }
        break;
    default:
        return -1;
    }
    *data_size = (uint8_t *)samples - (uint8_t *)data;
    return src - buf;
}


void FUNCC(ff_h264_idct8_dc_add)(uint8_t *_dst, int16_t *block, int stride){

    int i, j;

    int dc = (((dctcoef*)block)[0] + 32) >> 6;

    pixel *dst = (pixel*)_dst;

    stride >>= sizeof(pixel)-1;

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

    {

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

            dst[i] = av_clip_pixel( dst[i] + dc );

        dst += stride;

    }

}


static int colo_packet_compare_other(Packet *spkt, Packet *ppkt)

{

    trace_colo_compare_main("compare other");

    if (trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) {

        char pri_ip_src[20], pri_ip_dst[20], sec_ip_src[20], sec_ip_dst[20];

        strcpy(pri_ip_src, inet_ntoa(ppkt->ip->ip_src));

        strcpy(pri_ip_dst, inet_ntoa(ppkt->ip->ip_dst));

        strcpy(sec_ip_src, inet_ntoa(spkt->ip->ip_src));

        strcpy(sec_ip_dst, inet_ntoa(spkt->ip->ip_dst));

        trace_colo_compare_ip_info(ppkt->size, pri_ip_src,

                                   pri_ip_dst, spkt->size,

                                   sec_ip_src, sec_ip_dst);

    }

    return colo_packet_compare_common(ppkt, spkt, 0);

}


void *block_job_create(const BlockJobDriver *driver, BlockDriverState *bs,

                       int64_t speed, BlockCompletionFunc *cb,

                       void *opaque, Error **errp)

{

    BlockBackend *blk;

    BlockJob *job;

    assert(cb);

    if (bs->job) {

        error_setg(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));

        return NULL;

    }

    blk = blk_new();

    blk_insert_bs(blk, bs);

    job = g_malloc0(driver->instance_size);

    error_setg(&job->blocker, "block device is in use by block job: %s",

               BlockJobType_lookup[driver->job_type]);

    bdrv_op_block_all(bs, job->blocker);

    bdrv_op_unblock(bs, BLOCK_OP_TYPE_DATAPLANE, job->blocker);

    job->driver        = driver;

    job->id            = g_strdup(bdrv_get_device_name(bs));

    job->blk           = blk;

    job->cb            = cb;

    job->opaque        = opaque;

    job->busy          = true;

    job->refcnt        = 1;

    bs->job = job;

    QLIST_INSERT_HEAD(&block_jobs, job, job_list);

    blk_add_aio_context_notifier(blk, block_job_attached_aio_context,

                                 block_job_detach_aio_context, job);

    /* Only set speed when necessary to avoid NotSupported error */

    if (speed != 0) {

        Error *local_err = NULL;

        block_job_set_speed(job, speed, &local_err);

        if (local_err) {

            block_job_unref(job);

            error_propagate(errp, local_err);

            return NULL;

        }

    }

    return job;

}


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

{

    PXA2xxSSPState *s = (PXA2xxSSPState *) opaque;

    int i;

    s->enable = qemu_get_be32(f);

    qemu_get_be32s(f, &s->sscr[0]);

    qemu_get_be32s(f, &s->sscr[1]);

    qemu_get_be32s(f, &s->sspsp);

    qemu_get_be32s(f, &s->ssto);

    qemu_get_be32s(f, &s->ssitr);

    qemu_get_be32s(f, &s->sssr);

    qemu_get_8s(f, &s->sstsa);

    qemu_get_8s(f, &s->ssrsa);

    qemu_get_8s(f, &s->ssacd);

    s->rx_level = qemu_get_byte(f);

    s->rx_start = 0;

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

        s->rx_fifo[i] = qemu_get_byte(f);

    return 0;

}


static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)

{

    int precno, compno, reslevelno, bandno, cblkno, lev;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    for (compno = 0; compno < s->ncomponents; compno++){

        Jpeg2000Component *comp = tile->comp + compno;

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

            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){

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

                    int bandpos = bandno + (reslevelno > 0);

                    Jpeg2000Band *band = reslevel->band + bandno;

                    Jpeg2000Prec *prec = band->prec + precno;

                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){

                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                        cblk->ninclpasses = getcut(cblk, s->lambda,

                                (int64_t)dwt_norms[codsty->transform == FF_DWT53][bandpos][lev] * (int64_t)band->i_stepsize >> 16);

                    }

                }

            }

        }

    }

}


static void gen_rfdi(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;

    }

    /* Restore CPU state */

    gen_helper_rfdi(cpu_env);

    gen_sync_exception(ctx);

#endif

}


void ide_data_writel(void *opaque, uint32_t addr, uint32_t val)
{
    IDEBus *bus = opaque;
    IDEState *s = idebus_active_if(bus);
    uint8_t *p;
    /* PIO data access allowed only when DRQ bit is set. The result of a write
     * during PIO out is indeterminate, just ignore it. */
    if (!(s->status & DRQ_STAT) || ide_is_pio_out(s)) {
    p = s->data_ptr;
    *(uint32_t *)p = le32_to_cpu(val);
    p += 4;
    s->data_ptr = p;
    if (p >= s->data_end)
        s->end_transfer_func(s);


void OPPROTO op_addo (void)

{

    do_addo();

    RETURN();

}


static bool run_poll_handlers_once(AioContext *ctx)

{

    bool progress = false;

    AioHandler *node;

    QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {

        if (!node->deleted && node->io_poll &&

                node->io_poll(node->opaque)) {

            progress = true;

        }

        /* Caller handles freeing deleted nodes.  Don't do it here. */

    }

    return progress;

}