static CharDriverState *qemu_chr_open_pty(const char *id,

                                          ChardevReturn *ret)

{

    CharDriverState *chr;

    PtyCharDriver *s;

    int master_fd, slave_fd;

    char pty_name[PATH_MAX];

    master_fd = qemu_openpty_raw(&slave_fd, pty_name);

    if (master_fd < 0) {

        return NULL;

    }

    close(slave_fd);

    qemu_set_nonblock(master_fd);

    chr = qemu_chr_alloc();

    chr->filename = g_strdup_printf("pty:%s", pty_name);

    ret->pty = g_strdup(pty_name);

    ret->has_pty = true;

    fprintf(stderr, "char device redirected to %s (label %s)\n",

            pty_name, id);

    s = g_malloc0(sizeof(PtyCharDriver));

    chr->opaque = s;

    chr->chr_write = pty_chr_write;

    chr->chr_update_read_handler = pty_chr_update_read_handler;

    chr->chr_close = pty_chr_close;

    chr->chr_add_watch = pty_chr_add_watch;

    chr->explicit_be_open = true;

    s->fd = io_channel_from_fd(master_fd);

    s->timer_tag = 0;

    return chr;

}


static void RENAME(uyvytoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,

                                 int width, int height,

                                 int lumStride, int chromStride, int srcStride)

{

    int y;

    const int chromWidth = FF_CEIL_RSHIFT(width, 1);

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

        RENAME(extract_even)(src+1, ydst, width);

        if(y&1) {

            RENAME(extract_even2avg)(src-srcStride, src, udst, vdst, chromWidth);

            udst+= chromStride;

            vdst+= chromStride;

        }

        src += srcStride;

        ydst+= lumStride;

    }

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

}


av_cold int ff_h264_decode_init(AVCodecContext *avctx)

{

    H264Context *h = avctx->priv_data;

    int i;

    int ret;

    h->avctx = avctx;

    h->bit_depth_luma    = 8;

    h->chroma_format_idc = 1;

    h->cur_chroma_format_idc = 1;

    ff_h264dsp_init(&h->h264dsp, 8, 1);

    av_assert0(h->sps.bit_depth_chroma == 0);

    ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);

    ff_h264qpel_init(&h->h264qpel, 8);

    ff_h264_pred_init(&h->hpc, h->avctx->codec_id, 8, 1);

    h->dequant_coeff_pps = -1;

    h->current_sps_id = -1;

    /* needed so that IDCT permutation is known early */

    ff_videodsp_init(&h->vdsp, 8);

    memset(h->pps.scaling_matrix4, 16, 6 * 16 * sizeof(uint8_t));

    memset(h->pps.scaling_matrix8, 16, 2 * 64 * sizeof(uint8_t));

    h->picture_structure   = PICT_FRAME;

    h->slice_context_count = 1;

    h->workaround_bugs     = avctx->workaround_bugs;

    h->flags               = avctx->flags;

    /* set defaults */

    // s->decode_mb = ff_h263_decode_mb;

    if (!avctx->has_b_frames)

        h->low_delay = 1;

    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;

    ff_h264_decode_init_vlc();

    ff_init_cabac_states();

    h->pixel_shift        = 0;

    h->cur_bit_depth_luma =

    h->sps.bit_depth_luma = avctx->bits_per_raw_sample = 8;

    h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ?  H264_MAX_THREADS : 1;

    h->slice_ctx = av_mallocz_array(h->nb_slice_ctx, sizeof(*h->slice_ctx));

    if (!h->slice_ctx) {

        h->nb_slice_ctx = 0;

        return AVERROR(ENOMEM);

    }

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

        h->slice_ctx[i].h264 = h;

    h->outputed_poc      = h->next_outputed_poc = INT_MIN;

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

        h->last_pocs[i] = INT_MIN;

    h->prev_poc_msb = 1 << 16;

    h->prev_frame_num = -1;

    h->x264_build   = -1;

    h->sei_fpa.frame_packing_arrangement_cancel_flag = -1;

    ff_h264_reset_sei(h);

    if (avctx->codec_id == AV_CODEC_ID_H264) {

        if (avctx->ticks_per_frame == 1) {

            if(h->avctx->time_base.den < INT_MAX/2) {

                h->avctx->time_base.den *= 2;

            } else

                h->avctx->time_base.num /= 2;

        }

        avctx->ticks_per_frame = 2;

    }

    if (avctx->extradata_size > 0 && avctx->extradata) {

        ret = ff_h264_decode_extradata(h, avctx->extradata, avctx->extradata_size);

        if (ret < 0) {

            ff_h264_free_context(h);

            return ret;

        }

    }

    if (h->sps.bitstream_restriction_flag &&

        h->avctx->has_b_frames < h->sps.num_reorder_frames) {

        h->avctx->has_b_frames = h->sps.num_reorder_frames;

        h->low_delay           = 0;

    }

    avctx->internal->allocate_progress = 1;

    ff_h264_flush_change(h);

    if (h->enable_er) {

        av_log(avctx, AV_LOG_WARNING,

               "Error resilience is enabled. It is unsafe and unsupported and may crash. "

               "Use it at your own risk\n");

    }

    return 0;

}


static int decode_hextile(VmncContext *c, uint8_t* dst, GetByteContext *gb,

                          int w, int h, int stride)

{

    int i, j, k;

    int bg = 0, fg = 0, rects, color, flags, xy, wh;

    const int bpp = c->bpp2;

    uint8_t *dst2;

    int bw = 16, bh = 16;

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

        dst2 = dst;

        bw   = 16;

        if (j + 16 > h)

            bh = h - j;

        for (i = 0; i < w; i += 16, dst2 += 16 * bpp) {

            if (bytestream2_get_bytes_left(gb) <= 0) {

                av_log(c->avctx, AV_LOG_ERROR, "Premature end of data!\n");

                return AVERROR_INVALIDDATA;

            }

            if (i + 16 > w)

                bw = w - i;

            flags = bytestream2_get_byte(gb);

            if (flags & HT_RAW) {

                if (bytestream2_get_bytes_left(gb) < bw * bh * bpp) {

                    av_log(c->avctx, AV_LOG_ERROR, "Premature end of data!\n");

                    return AVERROR_INVALIDDATA;

                }

                paint_raw(dst2, bw, bh, gb, bpp, c->bigendian, stride);

            } else {

                if (flags & HT_BKG)

                    bg = vmnc_get_pixel(gb, bpp, c->bigendian);

                if (flags & HT_FG)

                    fg = vmnc_get_pixel(gb, bpp, c->bigendian);

                rects = 0;

                if (flags & HT_SUB)

                    rects = bytestream2_get_byte(gb);

                color = !!(flags & HT_CLR);

                paint_rect(dst2, 0, 0, bw, bh, bg, bpp, stride);

                if (bytestream2_get_bytes_left(gb) < rects * (color * bpp + 2)) {

                    av_log(c->avctx, AV_LOG_ERROR, "Premature end of data!\n");

                    return AVERROR_INVALIDDATA;

                }

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

                    if (color)

                        fg = vmnc_get_pixel(gb, bpp, c->bigendian);

                    xy = bytestream2_get_byte(gb);

                    wh = bytestream2_get_byte(gb);

                    paint_rect(dst2, xy >> 4, xy & 0xF,

                               (wh>>4)+1, (wh & 0xF)+1, fg, bpp, stride);

                }

            }

        }

        dst += stride * 16;

    }

    return 0;

}


int msi_init(struct PCIDevice *dev, uint8_t offset,

             unsigned int nr_vectors, bool msi64bit, bool msi_per_vector_mask)

{

    unsigned int vectors_order;

    uint16_t flags;

    uint8_t cap_size;

    int config_offset;

    if (!msi_nonbroken) {

        return -ENOTSUP;

    }

    MSI_DEV_PRINTF(dev,

                   "init offset: 0x%"PRIx8" vector: %"PRId8

                   " 64bit %d mask %d\n",

                   offset, nr_vectors, msi64bit, msi_per_vector_mask);

    assert(!(nr_vectors & (nr_vectors - 1)));   /* power of 2 */

    assert(nr_vectors > 0);

    assert(nr_vectors <= PCI_MSI_VECTORS_MAX);

    /* the nr of MSI vectors is up to 32 */

    vectors_order = ctz32(nr_vectors);

    flags = vectors_order << ctz32(PCI_MSI_FLAGS_QMASK);

    if (msi64bit) {

        flags |= PCI_MSI_FLAGS_64BIT;

    }

    if (msi_per_vector_mask) {

        flags |= PCI_MSI_FLAGS_MASKBIT;

    }

    cap_size = msi_cap_sizeof(flags);

    config_offset = pci_add_capability(dev, PCI_CAP_ID_MSI, offset, cap_size);

    if (config_offset < 0) {

        return config_offset;

    }

    dev->msi_cap = config_offset;

    dev->cap_present |= QEMU_PCI_CAP_MSI;

    pci_set_word(dev->config + msi_flags_off(dev), flags);

    pci_set_word(dev->wmask + msi_flags_off(dev),

                 PCI_MSI_FLAGS_QSIZE | PCI_MSI_FLAGS_ENABLE);

    pci_set_long(dev->wmask + msi_address_lo_off(dev),

                 PCI_MSI_ADDRESS_LO_MASK);

    if (msi64bit) {

        pci_set_long(dev->wmask + msi_address_hi_off(dev), 0xffffffff);

    }

    pci_set_word(dev->wmask + msi_data_off(dev, msi64bit), 0xffff);

    if (msi_per_vector_mask) {

        /* Make mask bits 0 to nr_vectors - 1 writable. */

        pci_set_long(dev->wmask + msi_mask_off(dev, msi64bit),

                     0xffffffff >> (PCI_MSI_VECTORS_MAX - nr_vectors));

    }

    return 0;

}


static int read_motion_values(AVCodecContext *avctx, GetBitContext *gb, Bundle *b)

{

    int t, sign, v;

    const uint8_t *dec_end;

    CHECK_READ_VAL(gb, b, t);

    dec_end = b->cur_dec + t;

    if (dec_end > b->data_end) {

        av_log(avctx, AV_LOG_ERROR, "Too many motion values\n");

        return -1;

    }

    if (get_bits1(gb)) {

        v = get_bits(gb, 4);

        if (v) {

            sign = -get_bits1(gb);

            v = (v ^ sign) - sign;

        }

        memset(b->cur_dec, v, t);

        b->cur_dec += t;

    } else {

        do {

            v = GET_HUFF(gb, b->tree);

            if (v) {

                sign = -get_bits1(gb);

                v = (v ^ sign) - sign;

            }

            *b->cur_dec++ = v;

        } while (b->cur_dec < dec_end);

    }

    return 0;

}


static int gen_set_psr(DisasContext *s, uint32_t mask, int spsr, TCGv t0)

{

    TCGv tmp;

    if (spsr) {

        /* ??? This is also undefined in system mode.  */

        if (IS_USER(s))

            return 1;

        tmp = load_cpu_field(spsr);

        tcg_gen_andi_i32(tmp, tmp, ~mask);

        tcg_gen_andi_i32(t0, t0, mask);

        tcg_gen_or_i32(tmp, tmp, t0);

        store_cpu_field(tmp, spsr);

    } else {

        gen_set_cpsr(t0, mask);

    }

    dead_tmp(t0);

    gen_lookup_tb(s);

    return 0;

}


int av_image_fill_linesizes(int linesizes[4], enum PixelFormat pix_fmt, int width)

{

    int i;

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];

    int max_step     [4];       /* max pixel step for each plane */

    int max_step_comp[4];       /* the component for each plane which has the max pixel step */

    memset(linesizes, 0, 4*sizeof(linesizes[0]));

    if ((unsigned)pix_fmt >= PIX_FMT_NB || desc->flags & PIX_FMT_HWACCEL)

        return AVERROR(EINVAL);

    if (desc->flags & PIX_FMT_BITSTREAM) {

        if (width > (INT_MAX -7) / (desc->comp[0].step_minus1+1))

            return AVERROR(EINVAL);

        linesizes[0] = (width * (desc->comp[0].step_minus1+1) + 7) >> 3;

        return 0;

    }

    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);

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

        int s = (max_step_comp[i] == 1 || max_step_comp[i] == 2) ? desc->log2_chroma_w : 0;

        int shifted_w = ((width + (1 << s) - 1)) >> s;

        if (max_step[i] > INT_MAX / shifted_w)

            return AVERROR(EINVAL);

        linesizes[i] = max_step[i] * shifted_w;

    }

    return 0;

}


static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
                                 Error **errp)
{
    uint32_t flags;
    bool fixedNewstyle = false;
    bool no_zeroes = false;
    /* Client sends:
        [ 0 ..   3]   client flags
       Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
        [ 0 ..   7]   NBD_OPTS_MAGIC
        [ 8 ..  11]   NBD option
        [12 ..  15]   Data length
        ...           Rest of request
        [ 0 ..   7]   NBD_OPTS_MAGIC
        [ 8 ..  11]   Second NBD option
        [12 ..  15]   Data length
        ...           Rest of request
    */
    if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
        error_prepend(errp, "read failed: ");
        return -EIO;
    be32_to_cpus(&flags);
    trace_nbd_negotiate_options_flags(flags);
    if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
        fixedNewstyle = true;
        flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
    if (flags & NBD_FLAG_C_NO_ZEROES) {
        no_zeroes = true;
        flags &= ~NBD_FLAG_C_NO_ZEROES;
    if (flags != 0) {
        error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
    while (1) {
        int ret;
        uint32_t option, length;
        uint64_t magic;
        if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
            error_prepend(errp, "read failed: ");
        magic = be64_to_cpu(magic);
        trace_nbd_negotiate_options_check_magic(magic);
        if (magic != NBD_OPTS_MAGIC) {
            error_setg(errp, "Bad magic received");
        if (nbd_read(client->ioc, &option,
                     sizeof(option), errp) < 0) {
            error_prepend(errp, "read failed: ");
        option = be32_to_cpu(option);
        if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
            error_prepend(errp, "read failed: ");
        length = be32_to_cpu(length);
        trace_nbd_negotiate_options_check_option(option,
                                                 nbd_opt_lookup(option));
        if (client->tlscreds &&
            client->ioc == (QIOChannel *)client->sioc) {
            QIOChannel *tioc;
            if (!fixedNewstyle) {
                error_setg(errp, "Unsupported option 0x%" PRIx32, option);
            switch (option) {
            case NBD_OPT_STARTTLS:
                if (length) {
                    /* Unconditionally drop the connection if the client
                     * can't start a TLS negotiation correctly */
                    return nbd_reject_length(client, length, option, true,
                                             errp);
                tioc = nbd_negotiate_handle_starttls(client, errp);
                if (!tioc) {
                    return -EIO;
                ret = 0;
                object_unref(OBJECT(client->ioc));
                client->ioc = QIO_CHANNEL(tioc);
                break;
            case NBD_OPT_EXPORT_NAME:
                /* No way to return an error to client, so drop connection */
                error_setg(errp, "Option 0x%x not permitted before TLS",
                           option);
            default:
                if (nbd_drop(client->ioc, length, errp) < 0) {
                    return -EIO;
                ret = nbd_negotiate_send_rep_err(client->ioc,
                                                 NBD_REP_ERR_TLS_REQD,
                                                 option, errp,
                                                 "Option 0x%" PRIx32
                                                 "not permitted before TLS",
                                                 option);
                /* Let the client keep trying, unless they asked to
                 * quit. In this mode, we've already sent an error, so
                 * we can't ack the abort.  */
                if (option == NBD_OPT_ABORT) {
                    return 1;
                break;
        } else if (fixedNewstyle) {
            switch (option) {
            case NBD_OPT_LIST:
                if (length) {
                    ret = nbd_reject_length(client, length, option, false,
                                            errp);
                } else {
                    ret = nbd_negotiate_handle_list(client, errp);
                break;
            case NBD_OPT_ABORT:
                /* NBD spec says we must try to reply before
                 * disconnecting, but that we must also tolerate
                 * guests that don't wait for our reply. */
                nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);
                return 1;
            case NBD_OPT_EXPORT_NAME:
                return nbd_negotiate_handle_export_name(client, length,
                                                        myflags, no_zeroes,
                                                        errp);
            case NBD_OPT_INFO:
            case NBD_OPT_GO:
                ret = nbd_negotiate_handle_info(client, length, option,
                                                myflags, errp);
                if (ret == 1) {
                    assert(option == NBD_OPT_GO);
                    return 0;
                break;
            case NBD_OPT_STARTTLS:
                if (length) {
                    ret = nbd_reject_length(client, length, option, false,
                                            errp);
                } else if (client->tlscreds) {
                    ret = nbd_negotiate_send_rep_err(client->ioc,
                                                     NBD_REP_ERR_INVALID,
                                                     option, errp,
                                                     "TLS already enabled");
                } else {
                    ret = nbd_negotiate_send_rep_err(client->ioc,
                                                     NBD_REP_ERR_POLICY,
                                                     option, errp,
                                                     "TLS not configured");
                break;
            case NBD_OPT_STRUCTURED_REPLY:
                if (length) {
                    ret = nbd_reject_length(client, length, option, false,
                                            errp);
                } else if (client->structured_reply) {
                    ret = nbd_negotiate_send_rep_err(
                        client->ioc, NBD_REP_ERR_INVALID, option, errp,
                        "structured reply already negotiated");
                } else {
                    ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
                                                 option, errp);
                    client->structured_reply = true;
                    myflags |= NBD_FLAG_SEND_DF;
                break;
            default:
                if (nbd_drop(client->ioc, length, errp) < 0) {
                    return -EIO;
                ret = nbd_negotiate_send_rep_err(client->ioc,
                                                 NBD_REP_ERR_UNSUP,
                                                 option, errp,
                                                 "Unsupported option 0x%"
                                                 PRIx32 " (%s)", option,
                                                 nbd_opt_lookup(option));
                break;
        } else {
            /*
             * If broken new-style we should drop the connection
             * for anything except NBD_OPT_EXPORT_NAME
             */
            switch (option) {
            case NBD_OPT_EXPORT_NAME:
                return nbd_negotiate_handle_export_name(client, length,
                                                        myflags, no_zeroes,
                                                        errp);
            default:
                error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
                           option, nbd_opt_lookup(option));
        if (ret < 0) {
            return ret;


static int virtio_ccw_blk_init(VirtioCcwDevice *ccw_dev)

{

    VirtIOBlkCcw *dev = VIRTIO_BLK_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    virtio_blk_set_conf(vdev, &(dev->blk));

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    if (qdev_init(vdev) < 0) {

        return -1;

    }

    return virtio_ccw_device_init(ccw_dev, VIRTIO_DEVICE(vdev));

}


static av_cold int libschroedinger_decode_close(AVCodecContext *avctx)

{

    SchroDecoderParams *p_schro_params = avctx->priv_data;

    /* Free the decoder. */

    schro_decoder_free(p_schro_params->decoder);

    av_freep(&p_schro_params->format);

    /* Free data in the output frame queue. */

    ff_schro_queue_free(&p_schro_params->dec_frame_queue,

                        libschroedinger_decode_frame_free);

    return 0;

}


static void parse_forced_key_frames(char *kf, OutputStream *ost,

                                    AVCodecContext *avctx)

{

    char *p;

    int n = 1, i;

    int64_t t;

    for (p = kf; *p; p++)

        if (*p == ',')

            n++;

    ost->forced_kf_count = n;

    ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);

    if (!ost->forced_kf_pts) {

        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");

        exit(1);

    }

    p = kf;

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

        char *next = strchr(p, ',');

        if (next)

            *next++ = 0;

        t = parse_time_or_die("force_key_frames", p, 1);

        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);

        p = next;

    }

}


void decode_mvs(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y)

{

    VP8Macroblock *mb_edge[3] = { mb + 2 /* top */,

                                  mb - 1 /* left */,

                                  mb + 1 /* top-left */ };

    enum { CNT_ZERO, CNT_NEAREST, CNT_NEAR, CNT_SPLITMV };

    enum { VP8_EDGE_TOP, VP8_EDGE_LEFT, VP8_EDGE_TOPLEFT };

    int idx = CNT_ZERO;

    int cur_sign_bias = s->sign_bias[mb->ref_frame];

    int8_t *sign_bias = s->sign_bias;

    VP56mv near_mv[4];

    uint8_t cnt[4] = { 0 };

    VP56RangeCoder *c = &s->c;

    AV_ZERO32(&near_mv[0]);

    AV_ZERO32(&near_mv[1]);

    /* Process MB on top, left and top-left */

    #define MV_EDGE_CHECK(n)\

    {\

        VP8Macroblock *edge = mb_edge[n];\

        int edge_ref = edge->ref_frame;\

        if (edge_ref != VP56_FRAME_CURRENT) {\

            uint32_t mv = AV_RN32A(&edge->mv);\

            if (mv) {\

                if (cur_sign_bias != sign_bias[edge_ref]) {\

                    /* SWAR negate of the values in mv. */\

                    mv = ~mv;\

                    mv = ((mv&0x7fff7fff) + 0x00010001) ^ (mv&0x80008000);\

                }\

                if (!n || mv != AV_RN32A(&near_mv[idx]))\

                    AV_WN32A(&near_mv[++idx], mv);\

                cnt[idx]      += 1 + (n != 2);\

            } else\

                cnt[CNT_ZERO] += 1 + (n != 2);\

        }\

    }

    MV_EDGE_CHECK(0)

    MV_EDGE_CHECK(1)

    MV_EDGE_CHECK(2)

    mb->partitioning = VP8_SPLITMVMODE_NONE;

    if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_ZERO]][0])) {

        mb->mode = VP8_MVMODE_MV;

        /* If we have three distinct MVs, merge first and last if they're the same */

        if (cnt[CNT_SPLITMV] && AV_RN32A(&near_mv[1 + VP8_EDGE_TOP]) == AV_RN32A(&near_mv[1 + VP8_EDGE_TOPLEFT]))

            cnt[CNT_NEAREST] += 1;

        /* Swap near and nearest if necessary */

        if (cnt[CNT_NEAR] > cnt[CNT_NEAREST]) {

            FFSWAP(uint8_t,     cnt[CNT_NEAREST],     cnt[CNT_NEAR]);

            FFSWAP( VP56mv, near_mv[CNT_NEAREST], near_mv[CNT_NEAR]);

        }

        if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) {

            if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) {

                /* Choose the best mv out of 0,0 and the nearest mv */

                clamp_mv(s, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);

                cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode    == VP8_MVMODE_SPLIT) +

                                    (mb_edge[VP8_EDGE_TOP]->mode     == VP8_MVMODE_SPLIT)) * 2 +

                                    (mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);

                if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_SPLITMV]][3])) {

                    mb->mode = VP8_MVMODE_SPLIT;

                    mb->mv = mb->bmv[decode_splitmvs(s, c, mb) - 1];

                } else {

                    mb->mv.y += read_mv_component(c, s->prob->mvc[0]);

                    mb->mv.x += read_mv_component(c, s->prob->mvc[1]);

                    mb->bmv[0] = mb->mv;

                }

            } else {

                clamp_mv(s, &mb->mv, &near_mv[CNT_NEAR]);

                mb->bmv[0] = mb->mv;

            }

        } else {

            clamp_mv(s, &mb->mv, &near_mv[CNT_NEAREST]);

            mb->bmv[0] = mb->mv;

        }

    } else {

        mb->mode = VP8_MVMODE_ZERO;

        AV_ZERO32(&mb->mv);

        mb->bmv[0] = mb->mv;

    }

}


static int check_output_constraints(InputStream *ist, OutputStream *ost)

{

    OutputFile *of = output_files[ost->file_index];

    int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;

    if (ost->source_index != ist_index)

        return 0;

    if (of->start_time && ist->pts < of->start_time)

        return 0;

    if (of->recording_time != INT64_MAX &&

        av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,

                      (AVRational){ 1, 1000000 }) >= 0) {

        ost->is_past_recording_time = 1;

        return 0;

    }

    return 1;

}


CPUState *mon_get_cpu(void)

{

    if (!cur_mon->mon_cpu) {

        monitor_set_cpu(0);

    }

    cpu_synchronize_state(cur_mon->mon_cpu);

    return cur_mon->mon_cpu;

}


static int vc1_decode_p_mb_intfr(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i;

    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 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, fourmv = 0, twomv = 0;

    int block_cbp = 0, pat, block_tt = 0;

    int idx_mbmode = 0, mvbp;

    int stride_y, fieldtx;

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

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

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

    if (!skipped) {

        if (v->fourmvswitch)

            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_4MV_MBMODE_VLC_BITS, 2); // try getting this done

        else

            idx_mbmode = get_vlc2(gb, v->mbmode_vlc->table, VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 2); // in a single line

        switch (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0]) {

        /* store the motion vector type in a flag (useful later) */

        case MV_PMODE_INTFR_4MV:

            fourmv = 1;

            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;

            break;

        case MV_PMODE_INTFR_4MV_FIELD:

            fourmv = 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;

            break;

        case 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;

            break;

        case MV_PMODE_INTFR_1MV:

            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;

            break;

        }

        if (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_INTRA) { // intra MB

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

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

            s->current_picture.f.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.f.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->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, stride_y);

                //TODO: loop filter

            }

        } else { // inter MB

            mb_has_coeffs = ff_vc1_mbmode_intfrp[v->fourmvswitch][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 (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_2MV_FIELD) {

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

            } else {

                if ((ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV)

                    || (ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][0] == MV_PMODE_INTFR_4MV_FIELD)) {

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

                }

            }

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

            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[v->fourmvswitch][idx_mbmode][1];

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

            dst_idx = 0;

            if (fourmv) {

                mvbp = v->fourmvbp;

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

                    if (i < 4) {

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

                        if (val) {

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

                        }

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

                        vc1_mc_4mv_luma(v, i, 0);

                    } else if (i == 4) {

                        vc1_mc_4mv_chroma4(v);

                    }

                }

            } else if (twomv) {

                mvbp  = v->twomvbp;

                if (mvbp & 2) {

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

                }

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

                vc1_mc_4mv_luma(v, 0, 0);

                vc1_mc_4mv_luma(v, 1, 0);

                if (mvbp & 1) {

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

                }

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

                vc1_mc_4mv_luma(v, 2, 0);

                vc1_mc_4mv_luma(v, 3, 0);

                vc1_mc_4mv_chroma4(v);

            } else {

                mvbp = ff_vc1_mbmode_intfrp[v->fourmvswitch][idx_mbmode][2];

                if (mvbp) {

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

                }

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

                vc1_mc_1mv(v, 0);

            }

            if (cbp)

                GET_MQUANT();  // p. 227

            s->current_picture.f.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

        s->mb_intra = v->is_intra[s->mb_x] = 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.f.mb_type[mb_pos]      = MB_TYPE_SKIP;

        s->current_picture.f.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;

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

        vc1_mc_1mv(v, 0);

    }

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

    return 0;

}


ssize_t ne2000_receive(NetClientState *nc, const uint8_t *buf, size_t size_)

{

    NE2000State *s = qemu_get_nic_opaque(nc);

    int size = size_;

    uint8_t *p;

    unsigned int total_len, next, avail, len, index, mcast_idx;

    uint8_t buf1[60];

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

#if defined(DEBUG_NE2000)

    printf("NE2000: received len=%d\n", size);

#endif

    if (s->cmd & E8390_STOP || ne2000_buffer_full(s))

        return -1;

    /* XXX: check this */

    if (s->rxcr & 0x10) {

        /* promiscuous: receive all */

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->rxcr & 0x04))

                return size;

        } else if (buf[0] & 0x01) {

            /* multicast */

            if (!(s->rxcr & 0x08))

                return size;

            mcast_idx = compute_mcast_idx(buf);

            if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))))

                return size;

        } else if (s->mem[0] == buf[0] &&

                   s->mem[2] == buf[1] &&

                   s->mem[4] == buf[2] &&

                   s->mem[6] == buf[3] &&

                   s->mem[8] == buf[4] &&

                   s->mem[10] == buf[5]) {

            /* match */

        } else {

            return size;

        }

    }

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    index = s->curpag << 8;

    if (index >= NE2000_PMEM_END) {

        index = s->start;

    }

    /* 4 bytes for header */

    total_len = size + 4;

    /* address for next packet (4 bytes for CRC) */

    next = index + ((total_len + 4 + 255) & ~0xff);

    if (next >= s->stop)

        next -= (s->stop - s->start);

    /* prepare packet header */

    p = s->mem + index;

    s->rsr = ENRSR_RXOK; /* receive status */

    /* XXX: check this */

    if (buf[0] & 0x01)

        s->rsr |= ENRSR_PHY;

    p[0] = s->rsr;

    p[1] = next >> 8;

    p[2] = total_len;

    p[3] = total_len >> 8;

    index += 4;

    /* write packet data */

    while (size > 0) {

        if (index <= s->stop)

            avail = s->stop - index;

        else

            avail = 0;

        len = size;

        if (len > avail)

            len = avail;

        memcpy(s->mem + index, buf, len);

        buf += len;

        index += len;

        if (index == s->stop)

            index = s->start;

        size -= len;

    }

    s->curpag = next >> 8;

    /* now we can signal we have received something */

    s->isr |= ENISR_RX;

    ne2000_update_irq(s);

    return size_;

}


static av_cold int decode_init_thread_copy(AVCodecContext *avctx)
{
    HYuvContext *s = avctx->priv_data;
    int i, ret;
    if ((ret = ff_huffyuv_alloc_temp(s)) < 0) {
        ff_huffyuv_common_end(s);
        return ret;
    }
    for (i = 0; i < 8; i++)
        s->vlc[i].table = NULL;
    if (s->version >= 2) {
        if ((ret = read_huffman_tables(s, avctx->extradata + 4,
                                       avctx->extradata_size)) < 0)
            return ret;
    } else {
        if ((ret = read_old_huffman_tables(s)) < 0)
            return ret;
    }
    return 0;
}


static void get_pci_host_devaddr(Object *obj, Visitor *v, const char *name,

                                 void *opaque, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    PCIHostDeviceAddress *addr = qdev_get_prop_ptr(dev, prop);

    char buffer[] = "xxxx:xx:xx.x";

    char *p = buffer;

    int rc = 0;

    rc = snprintf(buffer, sizeof(buffer), "%04x:%02x:%02x.%d",

                  addr->domain, addr->bus, addr->slot, addr->function);

    assert(rc == sizeof(buffer) - 1);

    visit_type_str(v, name, &p, errp);

}


static int cin_probe(AVProbeData *p)

{

    if (p->buf_size < 18)

        return 0;

    /* header starts with this special marker */

    if (AV_RL32(&p->buf[0]) != 0x55AA0000)

        return 0;

    /* for accuracy, check some header field values */

    if (AV_RL32(&p->buf[12]) != 22050 || p->buf[16] != 16 || p->buf[17] != 0)

        return 0;

    return AVPROBE_SCORE_MAX;

}


static int try_decode_frame(AVStream *st, AVPacket *avpkt, AVDictionary **options)

{

    AVCodec *codec;

    int got_picture = 1, ret = 0;

    AVFrame picture;

    AVPacket pkt = *avpkt;

    if(!st->codec->codec){

        AVDictionary *thread_opt = NULL;

        codec = avcodec_find_decoder(st->codec->codec_id);

        if (!codec)

            return -1;

        /* force thread count to 1 since the h264 decoder will not extract SPS

         *  and PPS to extradata during multi-threaded decoding */

        av_dict_set(options ? options : &thread_opt, "threads", "1", 0);

        ret = avcodec_open2(st->codec, codec, options ? options : &thread_opt);

        if (!options)

            av_dict_free(&thread_opt);

        if (ret < 0)

            return ret;

    }

    while ((pkt.size > 0 || (!pkt.data && got_picture)) &&

           ret >= 0 &&

           (!has_codec_parameters(st->codec)  ||

           !has_decode_delay_been_guessed(st) ||

           (!st->codec_info_nb_frames && st->codec->codec->capabilities & CODEC_CAP_CHANNEL_CONF))) {

        got_picture = 0;

        avcodec_get_frame_defaults(&picture);

        switch(st->codec->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            ret = avcodec_decode_video2(st->codec, &picture,

                                        &got_picture, &pkt);

            break;

        case AVMEDIA_TYPE_AUDIO:

            ret = avcodec_decode_audio4(st->codec, &picture, &got_picture, &pkt);

            break;

        default:

            break;

        }

        if (ret >= 0) {

            if (got_picture)

                st->info->nb_decoded_frames++;

            pkt.data += ret;

            pkt.size -= ret;

            ret       = got_picture;

        }

    }

    return ret;

}


static void validate_thread_parameters(AVCodecContext *avctx)

{

    int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)

                                && !(avctx->flags & CODEC_FLAG_TRUNCATED)

                                && !(avctx->flags & CODEC_FLAG_LOW_DELAY)

                                && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);

    if (avctx->thread_count == 1) {

        avctx->active_thread_type = 0;

    } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {

        avctx->active_thread_type = FF_THREAD_FRAME;

    } else {

        avctx->active_thread_type = FF_THREAD_SLICE;

    }

}


static int xan_unpack_luma(const uint8_t *src, const int src_size,

                           uint8_t *dst, const int dst_size)

{

   int tree_size, eof;

   const uint8_t *tree;

   int bits, mask;

   int tree_root, node;

   const uint8_t *dst_end = dst + dst_size;

   const uint8_t *src_end = src + src_size;

   tree_size = *src++;

   eof       = *src++;

   tree      = src - eof * 2 - 2;

   tree_root = eof + tree_size;

   src += tree_size * 2;

   node = tree_root;

   bits = *src++;

   mask = 0x80;

   for (;;) {

       int bit = !!(bits & mask);

       mask >>= 1;

       node = tree[node*2 + bit];

       if (node == eof)

           break;

       if (node < eof) {

           *dst++ = node;

           if (dst > dst_end)

               break;

           node = tree_root;

       }

       if (!mask) {

           bits = *src++;

           if (src > src_end)

               break;

           mask = 0x80;

       }

   }

   return dst != dst_end;

}


PPC_OP(set_T1)

{

    T1 = PARAM(1);

    RETURN();

}


static int nbd_co_send_request(BlockDriverState *bs,

                               NBDRequest *request,

                               QEMUIOVector *qiov)

{

    NBDClientSession *s = nbd_get_client_session(bs);

    int rc, ret, i;

    qemu_co_mutex_lock(&s->send_mutex);

    while (s->in_flight == MAX_NBD_REQUESTS) {

        qemu_co_queue_wait(&s->free_sema, &s->send_mutex);

    }

    s->in_flight++;

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

        if (s->recv_coroutine[i] == NULL) {

            s->recv_coroutine[i] = qemu_coroutine_self();

            break;

        }

    }

    g_assert(qemu_in_coroutine());

    assert(i < MAX_NBD_REQUESTS);

    request->handle = INDEX_TO_HANDLE(s, i);

    if (!s->ioc) {

        qemu_co_mutex_unlock(&s->send_mutex);

        return -EPIPE;

    }

    if (qiov) {

        qio_channel_set_cork(s->ioc, true);

        rc = nbd_send_request(s->ioc, request);

        if (rc >= 0) {

            ret = nbd_rwv(s->ioc, qiov->iov, qiov->niov, request->len, false,

                          NULL);

            if (ret != request->len) {

                rc = -EIO;

            }

        }

        qio_channel_set_cork(s->ioc, false);

    } else {

        rc = nbd_send_request(s->ioc, request);

    }

    qemu_co_mutex_unlock(&s->send_mutex);

    return rc;

}


static void __attribute__((__constructor__)) rcu_init(void)

{

    QemuThread thread;

    qemu_mutex_init(&rcu_gp_lock);

    qemu_event_init(&rcu_gp_event, true);

    qemu_event_init(&rcu_call_ready_event, false);

    qemu_thread_create(&thread, "call_rcu", call_rcu_thread,

                       NULL, QEMU_THREAD_DETACHED);

    rcu_register_thread();

}


static int decode_frame_headers(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                                const uint8_t *buf, int buf_size)

{

    GetByteContext gb;

    const uint8_t   *bs_hdr;

    uint32_t        frame_num, word2, check_sum, data_size;

    uint32_t        y_offset, u_offset, v_offset, starts[3], ends[3];

    uint16_t        height, width;

    int             i, j;

    bytestream2_init(&gb, buf, buf_size);

    /* parse and check the OS header */

    frame_num = bytestream2_get_le32(&gb);

    word2     = bytestream2_get_le32(&gb);

    check_sum = bytestream2_get_le32(&gb);

    data_size = bytestream2_get_le32(&gb);

    if ((frame_num ^ word2 ^ data_size ^ OS_HDR_ID) != check_sum) {

        av_log(avctx, AV_LOG_ERROR, "OS header checksum mismatch!\n");

        return AVERROR_INVALIDDATA;

    }

    /* parse the bitstream header */

    bs_hdr = gb.buffer;

    if (bytestream2_get_le16(&gb) != 32) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported codec version!\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->frame_num   =  frame_num;

    ctx->frame_flags =  bytestream2_get_le16(&gb);

    ctx->data_size   = (bytestream2_get_le32(&gb) + 7) >> 3;

    ctx->cb_offset   =  bytestream2_get_byte(&gb);

    if (ctx->data_size == 16)

        return 4;

    if (ctx->data_size > buf_size)

        ctx->data_size = buf_size;

    bytestream2_skip(&gb, 3); // skip reserved byte and checksum

    /* check frame dimensions */

    height = bytestream2_get_le16(&gb);

    width  = bytestream2_get_le16(&gb);

    if (av_image_check_size(width, height, 0, avctx))

        return AVERROR_INVALIDDATA;

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

        int res;

        av_dlog(avctx, "Frame dimensions changed!\n");

        if (width  < 16 || width  > 640 ||

            height < 16 || height > 480 ||

            width  &  3 || height &   3) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid picture dimensions: %d x %d!\n", width, height);

            return AVERROR_INVALIDDATA;

        }

        ctx->width  = width;

        ctx->height = height;

        free_frame_buffers(ctx);

        if ((res = allocate_frame_buffers(ctx, avctx)) < 0)

             return res;

        avcodec_set_dimensions(avctx, width, height);

    }

    y_offset = bytestream2_get_le32(&gb);

    v_offset = bytestream2_get_le32(&gb);

    u_offset = bytestream2_get_le32(&gb);

    bytestream2_skip(&gb, 4);

    /* unfortunately there is no common order of planes in the buffer */

    /* so we use that sorting algo for determining planes data sizes  */

    starts[0] = y_offset;

    starts[1] = v_offset;

    starts[2] = u_offset;

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

        ends[j] = ctx->data_size;

        for (i = 2; i >= 0; i--)

            if (starts[i] < ends[j] && starts[i] > starts[j])

                ends[j] = starts[i];

    }

    ctx->y_data_size = ends[0] - starts[0];

    ctx->v_data_size = ends[1] - starts[1];

    ctx->u_data_size = ends[2] - starts[2];

    if (FFMAX3(y_offset, v_offset, u_offset) >= ctx->data_size - 16 ||

        FFMIN3(y_offset, v_offset, u_offset) < gb.buffer - bs_hdr + 16 ||

        FFMIN3(ctx->y_data_size, ctx->v_data_size, ctx->u_data_size) <= 0) {

        av_log(avctx, AV_LOG_ERROR, "One of the y/u/v offsets is invalid\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->y_data_ptr = bs_hdr + y_offset;

    ctx->v_data_ptr = bs_hdr + v_offset;

    ctx->u_data_ptr = bs_hdr + u_offset;

    ctx->alt_quant  = gb.buffer;

    if (ctx->data_size == 16) {

        av_log(avctx, AV_LOG_DEBUG, "Sync frame encountered!\n");

        return 16;

    }

    if (ctx->frame_flags & BS_8BIT_PEL) {

        avpriv_request_sample(avctx, "8-bit pixel format");

        return AVERROR_PATCHWELCOME;

    }

    if (ctx->frame_flags & BS_MV_X_HALF || ctx->frame_flags & BS_MV_Y_HALF) {

        avpriv_request_sample(avctx, "Halfpel motion vectors");

        return AVERROR_PATCHWELCOME;

    }

    return 0;

}


static int libquvi_probe(AVProbeData *p)

{

    int score;

    quvi_t q;

    QUVIcode rc;

    rc = quvi_init(&q);

    if (rc != QUVI_OK)

        return AVERROR(ENOMEM);

    score = quvi_supported(q, (char *)p->filename) == QUVI_OK ? AVPROBE_SCORE_EXTENSION : 0;

    quvi_close(&q);

    return score;

}


void rgb16tobgr16(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	unsigned i;

	unsigned num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

	    g = (rgb&0x7E0)>>5;

	    b = (rgb&0xF800)>>11;

	    dst[2*i] = (b&0x1F) | ((g&0x3F)<<5) | ((r&0x1F)<<11);

	}

}


static int mpeg_decode_mb(MpegEncContext *s, int16_t block[12][64])

{

    int i, j, k, cbp, val, mb_type, motion_type;

    const int mb_block_count = 4 + (1 << s->chroma_format);

    int ret;

    ff_tlog(s->avctx, "decode_mb: x=%d y=%d\n", s->mb_x, s->mb_y);

    av_assert2(s->mb_skipped == 0);

    if (s->mb_skip_run-- != 0) {

        if (s->pict_type == AV_PICTURE_TYPE_P) {

            s->mb_skipped = 1;

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

                MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;

        } else {

            int mb_type;

            if (s->mb_x)

                mb_type = s->current_picture.mb_type[s->mb_x + s->mb_y * s->mb_stride - 1];

            else

                // FIXME not sure if this is allowed in MPEG at all

                mb_type = s->current_picture.mb_type[s->mb_width + (s->mb_y - 1) * s->mb_stride - 1];

            if (IS_INTRA(mb_type)) {

                av_log(s->avctx, AV_LOG_ERROR, "skip with previntra\n");

                return AVERROR_INVALIDDATA;

            }

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

                mb_type | MB_TYPE_SKIP;

            if ((s->mv[0][0][0] | s->mv[0][0][1] | s->mv[1][0][0] | s->mv[1][0][1]) == 0)

                s->mb_skipped = 1;

        }

        return 0;

    }

    switch (s->pict_type) {

    default:

    case AV_PICTURE_TYPE_I:

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

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

                av_log(s->avctx, AV_LOG_ERROR,

                       "Invalid mb type in I-frame at %d %d\n",

                       s->mb_x, s->mb_y);

                return AVERROR_INVALIDDATA;

            }

            mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;

        } else {

            mb_type = MB_TYPE_INTRA;

        }

        break;

    case AV_PICTURE_TYPE_P:

        mb_type = get_vlc2(&s->gb, ff_mb_ptype_vlc.table, MB_PTYPE_VLC_BITS, 1);

        if (mb_type < 0) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid mb type in P-frame at %d %d\n", s->mb_x, s->mb_y);

            return AVERROR_INVALIDDATA;

        }

        mb_type = ptype2mb_type[mb_type];

        break;

    case AV_PICTURE_TYPE_B:

        mb_type = get_vlc2(&s->gb, ff_mb_btype_vlc.table, MB_BTYPE_VLC_BITS, 1);

        if (mb_type < 0) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid mb type in B-frame at %d %d\n", s->mb_x, s->mb_y);

            return AVERROR_INVALIDDATA;

        }

        mb_type = btype2mb_type[mb_type];

        break;

    }

    ff_tlog(s->avctx, "mb_type=%x\n", mb_type);

//    motion_type = 0; /* avoid warning */

    if (IS_INTRA(mb_type)) {

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

        if (!s->chroma_y_shift)

            s->bdsp.clear_blocks(s->block[6]);

        /* compute DCT type */

        // FIXME: add an interlaced_dct coded var?

        if (s->picture_structure == PICT_FRAME &&

            !s->frame_pred_frame_dct)

            s->interlaced_dct = get_bits1(&s->gb);

        if (IS_QUANT(mb_type))

            s->qscale = get_qscale(s);

        if (s->concealment_motion_vectors) {

            /* just parse them */

            if (s->picture_structure != PICT_FRAME)

                skip_bits1(&s->gb);  /* field select */

            s->mv[0][0][0]      =

            s->last_mv[0][0][0] =

            s->last_mv[0][1][0] = mpeg_decode_motion(s, s->mpeg_f_code[0][0],

                                                     s->last_mv[0][0][0]);

            s->mv[0][0][1]      =

            s->last_mv[0][0][1] =

            s->last_mv[0][1][1] = mpeg_decode_motion(s, s->mpeg_f_code[0][1],

                                                     s->last_mv[0][0][1]);

            check_marker(s->avctx, &s->gb, "after concealment_motion_vectors");

        } else {

            /* reset mv prediction */

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

        }

        s->mb_intra = 1;

        // if 1, we memcpy blocks in xvmcvideo

        if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)

            ff_xvmc_pack_pblocks(s, -1); // inter are always full blocks

        if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

            if (s->avctx->flags2 & AV_CODEC_FLAG2_FAST) {

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

                    mpeg2_fast_decode_block_intra(s, *s->pblocks[i], i);

            } else {

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

                    if ((ret = mpeg2_decode_block_intra(s, *s->pblocks[i], i)) < 0)

                        return ret;

            }

        } else {

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

                ret = ff_mpeg1_decode_block_intra(&s->gb,

                                                  s->intra_matrix,

                                                  s->intra_scantable.permutated,

                                                  s->last_dc, *s->pblocks[i],

                                                  i, s->qscale);

                if (ret < 0) {

                    av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n",

                           s->mb_x, s->mb_y);

                    return ret;

                }

                s->block_last_index[i] = ret;

            }

        }

    } else {

        if (mb_type & MB_TYPE_ZERO_MV) {

            av_assert2(mb_type & MB_TYPE_CBP);

            s->mv_dir = MV_DIR_FORWARD;

            if (s->picture_structure == PICT_FRAME) {

                if (s->picture_structure == PICT_FRAME

                    && !s->frame_pred_frame_dct)

                    s->interlaced_dct = get_bits1(&s->gb);

                s->mv_type = MV_TYPE_16X16;

            } else {

                s->mv_type            = MV_TYPE_FIELD;

                mb_type              |= MB_TYPE_INTERLACED;

                s->field_select[0][0] = s->picture_structure - 1;

            }

            if (IS_QUANT(mb_type))

                s->qscale = get_qscale(s);

            s->last_mv[0][0][0] = 0;

            s->last_mv[0][0][1] = 0;

            s->last_mv[0][1][0] = 0;

            s->last_mv[0][1][1] = 0;

            s->mv[0][0][0]      = 0;

            s->mv[0][0][1]      = 0;

        } else {

            av_assert2(mb_type & MB_TYPE_L0L1);

            // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED

            /* get additional motion vector type */

            if (s->picture_structure == PICT_FRAME && s->frame_pred_frame_dct) {

                motion_type = MT_FRAME;

            } else {

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

                if (s->picture_structure == PICT_FRAME && HAS_CBP(mb_type))

                    s->interlaced_dct = get_bits1(&s->gb);

            }

            if (IS_QUANT(mb_type))

                s->qscale = get_qscale(s);

            /* motion vectors */

            s->mv_dir = (mb_type >> 13) & 3;

            ff_tlog(s->avctx, "motion_type=%d\n", motion_type);

            switch (motion_type) {

            case MT_FRAME: /* or MT_16X8 */

                if (s->picture_structure == PICT_FRAME) {

                    mb_type   |= MB_TYPE_16x16;

                    s->mv_type = MV_TYPE_16X16;

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

                        if (USES_LIST(mb_type, i)) {

                            /* MT_FRAME */

                            s->mv[i][0][0]      =

                            s->last_mv[i][0][0] =

                            s->last_mv[i][1][0] =

                                mpeg_decode_motion(s, s->mpeg_f_code[i][0],

                                                   s->last_mv[i][0][0]);

                            s->mv[i][0][1]      =

                            s->last_mv[i][0][1] =

                            s->last_mv[i][1][1] =

                                mpeg_decode_motion(s, s->mpeg_f_code[i][1],

                                                   s->last_mv[i][0][1]);

                            /* full_pel: only for MPEG-1 */

                            if (s->full_pel[i]) {

                                s->mv[i][0][0] *= 2;

                                s->mv[i][0][1] *= 2;

                            }

                        }

                    }

                } else {

                    mb_type   |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;

                    s->mv_type = MV_TYPE_16X8;

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

                        if (USES_LIST(mb_type, i)) {

                            /* MT_16X8 */

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

                                s->field_select[i][j] = get_bits1(&s->gb);

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

                                    val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],

                                                             s->last_mv[i][j][k]);

                                    s->last_mv[i][j][k] = val;

                                    s->mv[i][j][k]      = val;

                                }

                            }

                        }

                    }

                }

                break;

            case MT_FIELD:

                s->mv_type = MV_TYPE_FIELD;

                if (s->picture_structure == PICT_FRAME) {

                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;

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

                        if (USES_LIST(mb_type, i)) {

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

                                s->field_select[i][j] = get_bits1(&s->gb);

                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][0],

                                                         s->last_mv[i][j][0]);

                                s->last_mv[i][j][0] = val;

                                s->mv[i][j][0]      = val;

                                ff_tlog(s->avctx, "fmx=%d\n", val);

                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][1],

                                                         s->last_mv[i][j][1] >> 1);

                                s->last_mv[i][j][1] = 2 * val;

                                s->mv[i][j][1]      = val;

                                ff_tlog(s->avctx, "fmy=%d\n", val);

                            }

                        }

                    }

                } else {

                    av_assert0(!s->progressive_sequence);

                    mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;

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

                        if (USES_LIST(mb_type, i)) {

                            s->field_select[i][0] = get_bits1(&s->gb);

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

                                val = mpeg_decode_motion(s, s->mpeg_f_code[i][k],

                                                         s->last_mv[i][0][k]);

                                s->last_mv[i][0][k] = val;

                                s->last_mv[i][1][k] = val;

                                s->mv[i][0][k]      = val;

                            }

                        }

                    }

                }

                break;

            case MT_DMV:

                if (s->progressive_sequence){

                    av_log(s->avctx, AV_LOG_ERROR, "MT_DMV in progressive_sequence\n");

                    return AVERROR_INVALIDDATA;

                }

                s->mv_type = MV_TYPE_DMV;

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

                    if (USES_LIST(mb_type, i)) {

                        int dmx, dmy, mx, my, m;

                        const int my_shift = s->picture_structure == PICT_FRAME;

                        mx = mpeg_decode_motion(s, s->mpeg_f_code[i][0],

                                                s->last_mv[i][0][0]);

                        s->last_mv[i][0][0] = mx;

                        s->last_mv[i][1][0] = mx;

                        dmx = get_dmv(s);

                        my  = mpeg_decode_motion(s, s->mpeg_f_code[i][1],

                                                 s->last_mv[i][0][1] >> my_shift);

                        dmy = get_dmv(s);

                        s->last_mv[i][0][1] = my * (1 << my_shift);

                        s->last_mv[i][1][1] = my * (1 << my_shift);

                        s->mv[i][0][0] = mx;

                        s->mv[i][0][1] = my;

                        s->mv[i][1][0] = mx; // not used

                        s->mv[i][1][1] = my; // not used

                        if (s->picture_structure == PICT_FRAME) {

                            mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;

                            // m = 1 + 2 * s->top_field_first;

                            m = s->top_field_first ? 1 : 3;

                            /* top -> top pred */

                            s->mv[i][2][0] = ((mx * m + (mx > 0)) >> 1) + dmx;

                            s->mv[i][2][1] = ((my * m + (my > 0)) >> 1) + dmy - 1;

                            m = 4 - m;

                            s->mv[i][3][0] = ((mx * m + (mx > 0)) >> 1) + dmx;

                            s->mv[i][3][1] = ((my * m + (my > 0)) >> 1) + dmy + 1;

                        } else {

                            mb_type |= MB_TYPE_16x16;

                            s->mv[i][2][0] = ((mx + (mx > 0)) >> 1) + dmx;

                            s->mv[i][2][1] = ((my + (my > 0)) >> 1) + dmy;

                            if (s->picture_structure == PICT_TOP_FIELD)

                                s->mv[i][2][1]--;

                            else

                                s->mv[i][2][1]++;

                        }

                    }

                }

                break;

            default:

                av_log(s->avctx, AV_LOG_ERROR,

                       "00 motion_type at %d %d\n", s->mb_x, s->mb_y);

                return AVERROR_INVALIDDATA;

            }

        }

        s->mb_intra = 0;

        if (HAS_CBP(mb_type)) {

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

            cbp = get_vlc2(&s->gb, ff_mb_pat_vlc.table, MB_PAT_VLC_BITS, 1);

            if (mb_block_count > 6) {

                cbp <<= mb_block_count - 6;

                cbp  |= get_bits(&s->gb, mb_block_count - 6);

                s->bdsp.clear_blocks(s->block[6]);

            }

            if (cbp <= 0) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "invalid cbp %d at %d %d\n", cbp, s->mb_x, s->mb_y);

                return AVERROR_INVALIDDATA;

            }

            // if 1, we memcpy blocks in xvmcvideo

            if ((CONFIG_MPEG1_XVMC_HWACCEL || CONFIG_MPEG2_XVMC_HWACCEL) && s->pack_pblocks)

                ff_xvmc_pack_pblocks(s, cbp);

            if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

                if (s->avctx->flags2 & AV_CODEC_FLAG2_FAST) {

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

                        if (cbp & 32)

                            mpeg2_fast_decode_block_non_intra(s, *s->pblocks[i], i);

                        else

                            s->block_last_index[i] = -1;

                        cbp += cbp;

                    }

                } else {

                    cbp <<= 12 - mb_block_count;

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

                        if (cbp & (1 << 11)) {

                            if ((ret = mpeg2_decode_block_non_intra(s, *s->pblocks[i], i)) < 0)

                                return ret;

                        } else {

                            s->block_last_index[i] = -1;

                        }

                        cbp += cbp;

                    }

                }

            } else {

                if (s->avctx->flags2 & AV_CODEC_FLAG2_FAST) {

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

                        if (cbp & 32)

                            mpeg1_fast_decode_block_inter(s, *s->pblocks[i], i);

                        else

                            s->block_last_index[i] = -1;

                        cbp += cbp;

                    }

                } else {

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

                        if (cbp & 32) {

                            if ((ret = mpeg1_decode_block_inter(s, *s->pblocks[i], i)) < 0)

                                return ret;

                        } else {

                            s->block_last_index[i] = -1;

                        }

                        cbp += cbp;

                    }

                }

            }

        } else {

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

                s->block_last_index[i] = -1;

        }

    }

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

    return 0;

}


static inline void RENAME(rgb15ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

	int i;

        assert(src1 == src2);

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

	{

		int d0= ((uint32_t*)src1)[i];

		int dl= (d0&0x03E07C1F);

		int dh= ((d0>>5)&0x03E0F81F);

		int dh2= (dh>>11) + (dh<<21);

		int d= dh2 + dl;

		int g= d&0x7F;

		int r= (d>>10)&0x7F;

		int b= d>>21;

		dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+1-3)) + 128;

		dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+1-3)) + 128;

	}

}


const char *av_get_string(void *obj, const char *name, const AVOption **o_out, char *buf, int buf_len){

    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);

    void *dst;

    if(!o || o->offset<=0)

        return NULL;

    if(o->type != FF_OPT_TYPE_STRING && (!buf || !buf_len))

        return NULL;

    dst= ((uint8_t*)obj) + o->offset;

    if(o_out) *o_out= o;

    if(o->type == FF_OPT_TYPE_STRING)

        return dst;

    switch(o->type){

    case FF_OPT_TYPE_FLAGS:     snprintf(buf, buf_len, "0x%08X",*(int    *)dst);break;

    case FF_OPT_TYPE_INT:       snprintf(buf, buf_len, "%d" , *(int    *)dst);break;

    case FF_OPT_TYPE_INT64:     snprintf(buf, buf_len, "%"PRId64, *(int64_t*)dst);break;

    case FF_OPT_TYPE_FLOAT:     snprintf(buf, buf_len, "%f" , *(float  *)dst);break;

    case FF_OPT_TYPE_DOUBLE:    snprintf(buf, buf_len, "%f" , *(double *)dst);break;

    case FF_OPT_TYPE_RATIONAL:  snprintf(buf, buf_len, "%d/%d", ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;

    default: return NULL;

    }

    return buf;

}


static void increase_dynamic_storage(IVShmemState *s, int new_min_size) {

    int j, old_nb_alloc;

    old_nb_alloc = s->nb_peers;

    while (new_min_size >= s->nb_peers)

        s->nb_peers = s->nb_peers * 2;

    IVSHMEM_DPRINTF("bumping storage to %d guests\n", s->nb_peers);

    s->peers = g_realloc(s->peers, s->nb_peers * sizeof(Peer));

    /* zero out new pointers */

    for (j = old_nb_alloc; j < s->nb_peers; j++) {

        s->peers[j].eventfds = NULL;

        s->peers[j].nb_eventfds = 0;

    }

}


static void usb_host_auto_check(void *unused)

{

    struct USBHostDevice *s;

    struct USBAutoFilter *f;

    libusb_device **devs;

    struct libusb_device_descriptor ddesc;

    int unconnected = 0;

    int i, n;

    if (usb_host_init() != 0) {

        return;

    }

    if (runstate_is_running()) {

        n = libusb_get_device_list(ctx, &devs);

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

            if (libusb_get_device_descriptor(devs[i], &ddesc) != 0) {

                continue;

            }

            if (ddesc.bDeviceClass == LIBUSB_CLASS_HUB) {

                continue;

            }

            QTAILQ_FOREACH(s, &hostdevs, next) {

                f = &s->match;

                if (f->bus_num > 0 &&

                    f->bus_num != libusb_get_bus_number(devs[i])) {

                    continue;

                }

                if (f->addr > 0 &&

                    f->addr != libusb_get_device_address(devs[i])) {

                    continue;

                }

                if (f->port != NULL) {

                    char port[16] = "-";

                    usb_host_get_port(devs[i], port, sizeof(port));

                    if (strcmp(f->port, port) != 0) {

                        continue;

                    }

                }

                if (f->vendor_id > 0 &&

                    f->vendor_id != ddesc.idVendor) {

                    continue;

                }

                if (f->product_id > 0 &&

                    f->product_id != ddesc.idProduct) {

                    continue;

                }

                /* We got a match */

                s->seen++;

                if (s->errcount >= 3) {

                    continue;

                }

                if (s->dh != NULL) {

                    continue;

                }

                if (usb_host_open(s, devs[i]) < 0) {

                    s->errcount++;

                    continue;

                }

                break;

            }

        }

        libusb_free_device_list(devs, 1);

        QTAILQ_FOREACH(s, &hostdevs, next) {

            if (s->dh == NULL) {

                unconnected++;

            }

            if (s->seen == 0) {

                if (s->dh) {

                    usb_host_close(s);

                }

                s->errcount = 0;

            }

            s->seen = 0;

        }

#if 0

        if (unconnected == 0) {

            /* nothing to watch */

            if (usb_auto_timer) {

                timer_del(usb_auto_timer);

                trace_usb_host_auto_scan_disabled();

            }

            return;

        }

#endif

    }

    if (!usb_vmstate) {

        usb_vmstate = qemu_add_vm_change_state_handler(usb_host_vm_state, NULL);

    }

    if (!usb_auto_timer) {

        usb_auto_timer = timer_new_ms(QEMU_CLOCK_REALTIME, usb_host_auto_check, NULL);

        if (!usb_auto_timer) {

            return;

        }

        trace_usb_host_auto_scan_enabled();

    }

    timer_mod(usb_auto_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 2000);

}


int tcg_gen_code(TCGContext *s, TranslationBlock *tb)

{

#ifdef CONFIG_PROFILER

    TCGProfile *prof = &s->prof;

#endif

    int i, oi, oi_next, num_insns;

#ifdef CONFIG_PROFILER

    {

        int n;

        n = s->gen_op_buf[0].prev + 1;

        atomic_set(&prof->op_count, prof->op_count + n);

        if (n > prof->op_count_max) {

            atomic_set(&prof->op_count_max, n);

        }

        n = s->nb_temps;

        atomic_set(&prof->temp_count, prof->temp_count + n);

        if (n > prof->temp_count_max) {

            atomic_set(&prof->temp_count_max, n);

        }

    }

#endif

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP)

                 && qemu_log_in_addr_range(tb->pc))) {

        qemu_log_lock();

        qemu_log("OP:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

        qemu_log_unlock();

    }

#endif

#ifdef CONFIG_PROFILER

    atomic_set(&prof->opt_time, prof->opt_time - profile_getclock());

#endif

#ifdef USE_TCG_OPTIMIZATIONS

    tcg_optimize(s);

#endif

#ifdef CONFIG_PROFILER

    atomic_set(&prof->opt_time, prof->opt_time + profile_getclock());

    atomic_set(&prof->la_time, prof->la_time - profile_getclock());

#endif

    liveness_pass_1(s);

    if (s->nb_indirects > 0) {

#ifdef DEBUG_DISAS

        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_IND)

                     && qemu_log_in_addr_range(tb->pc))) {

            qemu_log_lock();

            qemu_log("OP before indirect lowering:\n");

            tcg_dump_ops(s);

            qemu_log("\n");

            qemu_log_unlock();

        }

#endif

        /* Replace indirect temps with direct temps.  */

        if (liveness_pass_2(s)) {

            /* If changes were made, re-run liveness.  */

            liveness_pass_1(s);

        }

    }

#ifdef CONFIG_PROFILER

    atomic_set(&prof->la_time, prof->la_time + profile_getclock());

#endif

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT)

                 && qemu_log_in_addr_range(tb->pc))) {

        qemu_log_lock();

        qemu_log("OP after optimization and liveness analysis:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

        qemu_log_unlock();

    }

#endif

    tcg_reg_alloc_start(s);

    s->code_buf = tb->tc.ptr;

    s->code_ptr = tb->tc.ptr;

#ifdef TCG_TARGET_NEED_LDST_LABELS

    s->ldst_labels = NULL;

#endif

#ifdef TCG_TARGET_NEED_POOL_LABELS

    s->pool_labels = NULL;

#endif

    num_insns = -1;

    for (oi = s->gen_op_buf[0].next; oi != 0; oi = oi_next) {

        TCGOp * const op = &s->gen_op_buf[oi];

        TCGOpcode opc = op->opc;

        oi_next = op->next;

#ifdef CONFIG_PROFILER

        atomic_set(&prof->table_op_count[opc], prof->table_op_count[opc] + 1);

#endif

        switch (opc) {

        case INDEX_op_mov_i32:

        case INDEX_op_mov_i64:

            tcg_reg_alloc_mov(s, op);

            break;

        case INDEX_op_movi_i32:

        case INDEX_op_movi_i64:

            tcg_reg_alloc_movi(s, op);

            break;

        case INDEX_op_insn_start:

            if (num_insns >= 0) {

                s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);

            }

            num_insns++;

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

                target_ulong a;

#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS

                a = deposit64(op->args[i * 2], 32, 32, op->args[i * 2 + 1]);

#else

                a = op->args[i];

#endif

                s->gen_insn_data[num_insns][i] = a;

            }

            break;

        case INDEX_op_discard:

            temp_dead(s, arg_temp(op->args[0]));

            break;

        case INDEX_op_set_label:

            tcg_reg_alloc_bb_end(s, s->reserved_regs);

            tcg_out_label(s, arg_label(op->args[0]), s->code_ptr);

            break;

        case INDEX_op_call:

            tcg_reg_alloc_call(s, op);

            break;

        default:

            /* Sanity check that we've not introduced any unhandled opcodes. */

            tcg_debug_assert(tcg_op_supported(opc));

            /* Note: in order to speed up the code, it would be much

               faster to have specialized register allocator functions for

               some common argument patterns */

            tcg_reg_alloc_op(s, op);

            break;

        }

#ifdef CONFIG_DEBUG_TCG

        check_regs(s);

#endif

        /* Test for (pending) buffer overflow.  The assumption is that any

           one operation beginning below the high water mark cannot overrun

           the buffer completely.  Thus we can test for overflow after

           generating code without having to check during generation.  */

        if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) {

            return -1;

        }

    }

    tcg_debug_assert(num_insns >= 0);

    s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);

    /* Generate TB finalization at the end of block */

#ifdef TCG_TARGET_NEED_LDST_LABELS

    if (!tcg_out_ldst_finalize(s)) {

        return -1;

    }

#endif

#ifdef TCG_TARGET_NEED_POOL_LABELS

    if (!tcg_out_pool_finalize(s)) {

        return -1;

    }

#endif

    /* flush instruction cache */

    flush_icache_range((uintptr_t)s->code_buf, (uintptr_t)s->code_ptr);

    return tcg_current_code_size(s);

}


void palette_destroy(VncPalette *palette)

{

    if (palette == NULL) {

        qemu_free(palette);

    }

}


static int ivshmem_setup_interrupts(IVShmemState *s)

{

    /* allocate QEMU callback data for receiving interrupts */

    s->msi_vectors = g_malloc0(s->vectors * sizeof(MSIVector));

    if (ivshmem_has_feature(s, IVSHMEM_MSI)) {

        if (msix_init_exclusive_bar(PCI_DEVICE(s), s->vectors, 1)) {

            return -1;

        }

        IVSHMEM_DPRINTF("msix initialized (%d vectors)\n", s->vectors);

        ivshmem_msix_vector_use(s);

    }

    return 0;

}


static int wavpack_encode_block(WavPackEncodeContext *s,
                                int32_t *samples_l, int32_t *samples_r,
                                uint8_t *out, int out_size)
{
    int block_size, start, end, data_size, tcount, temp, m = 0;
    int i, j, ret = 0, got_extra = 0, nb_samples = s->block_samples;
    uint32_t crc = 0xffffffffu;
    struct Decorr *dpp;
    PutByteContext pb;
    if (!(s->flags & WV_MONO) && s->optimize_mono) {
        int32_t lor = 0, diff = 0;
        for (i = 0; i < nb_samples; i++) {
            lor  |= samples_l[i] | samples_r[i];
            diff |= samples_l[i] - samples_r[i];
            if (lor && diff)
                break;
        }
        if (i == nb_samples && lor && !diff) {
            s->flags &= ~(WV_JOINT_STEREO | WV_CROSS_DECORR);
            s->flags |= WV_FALSE_STEREO;
            if (!s->false_stereo) {
                s->false_stereo = 1;
                s->num_terms = 0;
                CLEAR(s->w);
            }
        } else if (s->false_stereo) {
            s->false_stereo = 0;
            s->num_terms = 0;
            CLEAR(s->w);
        }
    }
    if (s->flags & SHIFT_MASK) {
        int shift = (s->flags & SHIFT_MASK) >> SHIFT_LSB;
        int mag = (s->flags & MAG_MASK) >> MAG_LSB;
        if (s->flags & WV_MONO_DATA)
            shift_mono(samples_l, nb_samples, shift);
        else
            shift_stereo(samples_l, samples_r, nb_samples, shift);
        if ((mag -= shift) < 0)
            s->flags &= ~MAG_MASK;
        else
            s->flags -= (1 << MAG_LSB) * shift;
    }
    if ((s->flags & WV_FLOAT_DATA) || (s->flags & MAG_MASK) >> MAG_LSB >= 24) {
        av_fast_padded_malloc(&s->orig_l, &s->orig_l_size, sizeof(int32_t) * nb_samples);
        memcpy(s->orig_l, samples_l, sizeof(int32_t) * nb_samples);
        if (!(s->flags & WV_MONO_DATA)) {
            av_fast_padded_malloc(&s->orig_r, &s->orig_r_size, sizeof(int32_t) * nb_samples);
            memcpy(s->orig_r, samples_r, sizeof(int32_t) * nb_samples);
        }
        if (s->flags & WV_FLOAT_DATA)
            got_extra = scan_float(s, samples_l, samples_r, nb_samples);
        else
            got_extra = scan_int32(s, samples_l, samples_r, nb_samples);
        s->num_terms = 0;
    } else {
        scan_int23(s, samples_l, samples_r, nb_samples);
        if (s->shift != s->int32_zeros + s->int32_ones + s->int32_dups) {
            s->shift = s->int32_zeros + s->int32_ones + s->int32_dups;
            s->num_terms = 0;
        }
    }
    if (!s->num_passes && !s->num_terms) {
        s->num_passes = 1;
        if (s->flags & WV_MONO_DATA)
            ret = wv_mono(s, samples_l, 1, 0);
        else
            ret = wv_stereo(s, samples_l, samples_r, 1, 0);
        s->num_passes = 0;
    }
    if (s->flags & WV_MONO_DATA) {
        for (i = 0; i < nb_samples; i++)
            crc += (crc << 1) + samples_l[i];
        if (s->num_passes)
            ret = wv_mono(s, samples_l, !s->num_terms, 1);
    } else {
        for (i = 0; i < nb_samples; i++)
            crc += (crc << 3) + (samples_l[i] << 1) + samples_l[i] + samples_r[i];
        if (s->num_passes)
            ret = wv_stereo(s, samples_l, samples_r, !s->num_terms, 1);
    }
    if (ret < 0)
        return ret;
    if (!s->ch_offset)
        s->flags |= WV_INITIAL_BLOCK;
    s->ch_offset += 1 + !(s->flags & WV_MONO);
    if (s->ch_offset == s->avctx->channels)
        s->flags |= WV_FINAL_BLOCK;
    bytestream2_init_writer(&pb, out, out_size);
    bytestream2_put_le32(&pb, MKTAG('w', 'v', 'p', 'k'));
    bytestream2_put_le32(&pb, 0);
    bytestream2_put_le16(&pb, 0x410);
    bytestream2_put_le16(&pb, 0);
    bytestream2_put_le32(&pb, 0);
    bytestream2_put_le32(&pb, s->sample_index);
    bytestream2_put_le32(&pb, nb_samples);
    bytestream2_put_le32(&pb, s->flags);
    bytestream2_put_le32(&pb, crc);
    if (s->flags & WV_INITIAL_BLOCK &&
        s->avctx->channel_layout != AV_CH_LAYOUT_MONO &&
        s->avctx->channel_layout != AV_CH_LAYOUT_STEREO) {
        put_metadata_block(&pb, WP_ID_CHANINFO, 5);
        bytestream2_put_byte(&pb, s->avctx->channels);
        bytestream2_put_le32(&pb, s->avctx->channel_layout);
        bytestream2_put_byte(&pb, 0);
    }
    if ((s->flags & SRATE_MASK) == SRATE_MASK) {
        put_metadata_block(&pb, WP_ID_SAMPLE_RATE, 3);
        bytestream2_put_le24(&pb, s->avctx->sample_rate);
        bytestream2_put_byte(&pb, 0);
    }
    put_metadata_block(&pb, WP_ID_DECTERMS, s->num_terms);
    for (i = 0; i < s->num_terms; i++) {
        struct Decorr *dpp = &s->decorr_passes[i];
        bytestream2_put_byte(&pb, ((dpp->value + 5) & 0x1f) | ((dpp->delta << 5) & 0xe0));
    }
    if (s->num_terms & 1)
        bytestream2_put_byte(&pb, 0);
#define WRITE_DECWEIGHT(type) do {            \
        temp = store_weight(type);    \
        bytestream2_put_byte(&pb, temp);      \
        type = restore_weight(temp);  \
    } while (0)
    bytestream2_put_byte(&pb, WP_ID_DECWEIGHTS);
    bytestream2_put_byte(&pb, 0);
    start = bytestream2_tell_p(&pb);
    for (i = s->num_terms - 1; i >= 0; --i) {
        struct Decorr *dpp = &s->decorr_passes[i];
        if (store_weight(dpp->weightA) ||
            (!(s->flags & WV_MONO_DATA) && store_weight(dpp->weightB)))
                break;
    }
    tcount = i + 1;
    for (i = 0; i < s->num_terms; i++) {
        struct Decorr *dpp = &s->decorr_passes[i];
        if (i < tcount) {
            WRITE_DECWEIGHT(dpp->weightA);
            if (!(s->flags & WV_MONO_DATA))
                WRITE_DECWEIGHT(dpp->weightB);
        } else {
            dpp->weightA = dpp->weightB = 0;
        }
    }
    end = bytestream2_tell_p(&pb);
    out[start - 2] = WP_ID_DECWEIGHTS | (((end - start) & 1) ? WP_IDF_ODD: 0);
    out[start - 1] = (end - start + 1) >> 1;
    if ((end - start) & 1)
        bytestream2_put_byte(&pb, 0);
#define WRITE_DECSAMPLE(type) do {        \
        temp = log2s(type);               \
        type = wp_exp2(temp);             \
        bytestream2_put_le16(&pb, temp);  \
    } while (0)
    bytestream2_put_byte(&pb, WP_ID_DECSAMPLES);
    bytestream2_put_byte(&pb, 0);
    start = bytestream2_tell_p(&pb);
    for (i = 0; i < s->num_terms; i++) {
        struct Decorr *dpp = &s->decorr_passes[i];
        if (i == 0) {
            if (dpp->value > MAX_TERM) {
                WRITE_DECSAMPLE(dpp->samplesA[0]);
                WRITE_DECSAMPLE(dpp->samplesA[1]);
                if (!(s->flags & WV_MONO_DATA)) {
                    WRITE_DECSAMPLE(dpp->samplesB[0]);
                    WRITE_DECSAMPLE(dpp->samplesB[1]);
                }
            } else if (dpp->value < 0) {
                WRITE_DECSAMPLE(dpp->samplesA[0]);
                WRITE_DECSAMPLE(dpp->samplesB[0]);
            } else {
                for (j = 0; j < dpp->value; j++) {
                    WRITE_DECSAMPLE(dpp->samplesA[j]);
                    if (!(s->flags & WV_MONO_DATA))
                        WRITE_DECSAMPLE(dpp->samplesB[j]);
                }
            }
        } else {
            CLEAR(dpp->samplesA);
            CLEAR(dpp->samplesB);
        }
    }
    end = bytestream2_tell_p(&pb);
    out[start - 1] = (end - start) >> 1;
#define WRITE_CHAN_ENTROPY(chan) do {               \
        for (i = 0; i < 3; i++) {                   \
            temp = wp_log2(s->w.c[chan].median[i]); \
            bytestream2_put_le16(&pb, temp);        \
            s->w.c[chan].median[i] = wp_exp2(temp); \
        }                                           \
    } while (0)
    put_metadata_block(&pb, WP_ID_ENTROPY, 6 * (1 + (!(s->flags & WV_MONO_DATA))));
    WRITE_CHAN_ENTROPY(0);
    if (!(s->flags & WV_MONO_DATA))
        WRITE_CHAN_ENTROPY(1);
    if (s->flags & WV_FLOAT_DATA) {
        put_metadata_block(&pb, WP_ID_FLOATINFO, 4);
        bytestream2_put_byte(&pb, s->float_flags);
        bytestream2_put_byte(&pb, s->float_shift);
        bytestream2_put_byte(&pb, s->float_max_exp);
        bytestream2_put_byte(&pb, 127);
    }
    if (s->flags & WV_INT32_DATA) {
        put_metadata_block(&pb, WP_ID_INT32INFO, 4);
        bytestream2_put_byte(&pb, s->int32_sent_bits);
        bytestream2_put_byte(&pb, s->int32_zeros);
        bytestream2_put_byte(&pb, s->int32_ones);
        bytestream2_put_byte(&pb, s->int32_dups);
    }
    if (s->flags & WV_MONO_DATA && !s->num_passes) {
        for (i = 0; i < nb_samples; i++) {
            int32_t code = samples_l[i];
            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++) {
                int32_t sam;
                if (dpp->value > MAX_TERM) {
                    if (dpp->value & 1)
                        sam = 2 * dpp->samplesA[0] - dpp->samplesA[1];
                    else
                        sam = (3 * dpp->samplesA[0] - dpp->samplesA[1]) >> 1;
                    dpp->samplesA[1] = dpp->samplesA[0];
                    dpp->samplesA[0] = code;
                } else {
                    sam = dpp->samplesA[m];
                    dpp->samplesA[(m + dpp->value) & (MAX_TERM - 1)] = code;
                }
                code -= APPLY_WEIGHT(dpp->weightA, sam);
                UPDATE_WEIGHT(dpp->weightA, dpp->delta, sam, code);
            }
            m = (m + 1) & (MAX_TERM - 1);
            samples_l[i] = code;
        }
        if (m) {
            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++)
                if (dpp->value > 0 && dpp->value <= MAX_TERM) {
                int32_t temp_A[MAX_TERM], temp_B[MAX_TERM];
                int k;
                memcpy(temp_A, dpp->samplesA, sizeof(dpp->samplesA));
                memcpy(temp_B, dpp->samplesB, sizeof(dpp->samplesB));
                for (k = 0; k < MAX_TERM; k++) {
                    dpp->samplesA[k] = temp_A[m];
                    dpp->samplesB[k] = temp_B[m];
                    m = (m + 1) & (MAX_TERM - 1);
                }
            }
        }
    } else if (!s->num_passes) {
        if (s->flags & WV_JOINT_STEREO) {
            for (i = 0; i < nb_samples; i++)
                samples_r[i] += ((samples_l[i] -= samples_r[i]) >> 1);
        }
        for (i = 0; i < s->num_terms; i++) {
            struct Decorr *dpp = &s->decorr_passes[i];
            if (((s->flags & MAG_MASK) >> MAG_LSB) >= 16 || dpp->delta != 2)
                decorr_stereo_pass2(dpp, samples_l, samples_r, nb_samples);
            else
                decorr_stereo_pass_id2(dpp, samples_l, samples_r, nb_samples);
        }
    }
    bytestream2_put_byte(&pb, WP_ID_DATA | WP_IDF_LONG);
    init_put_bits(&s->pb, pb.buffer + 3, bytestream2_get_bytes_left_p(&pb));
    if (s->flags & WV_MONO_DATA) {
        for (i = 0; i < nb_samples; i++)
            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);
    } else {
        for (i = 0; i < nb_samples; i++) {
            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);
            wavpack_encode_sample(s, &s->w.c[1], s->samples[1][i]);
        }
    }
    encode_flush(s);
    flush_put_bits(&s->pb);
    data_size = put_bits_count(&s->pb) >> 3;
    bytestream2_put_le24(&pb, (data_size + 1) >> 1);
    bytestream2_skip_p(&pb, data_size);
    if (data_size & 1)
        bytestream2_put_byte(&pb, 0);
    if (got_extra) {
        bytestream2_put_byte(&pb, WP_ID_EXTRABITS | WP_IDF_LONG);
        init_put_bits(&s->pb, pb.buffer + 7, bytestream2_get_bytes_left_p(&pb));
        if (s->flags & WV_FLOAT_DATA)
            pack_float(s, s->orig_l, s->orig_r, nb_samples);
        else
            pack_int32(s, s->orig_l, s->orig_r, nb_samples);
        flush_put_bits(&s->pb);
        data_size = put_bits_count(&s->pb) >> 3;
        bytestream2_put_le24(&pb, (data_size + 5) >> 1);
        bytestream2_put_le32(&pb, s->crc_x);
        bytestream2_skip_p(&pb, data_size);
        if (data_size & 1)
            bytestream2_put_byte(&pb, 0);
    }
    block_size = bytestream2_tell_p(&pb);
    AV_WL32(out + 4, block_size - 8);
    return block_size;
}


virtio_crypto_check_cryptodev_is_used(Object *obj, const char *name,

                                      Object *val, Error **errp)

{

    if (cryptodev_backend_is_used(CRYPTODEV_BACKEND(val))) {

        char *path = object_get_canonical_path_component(val);

        error_setg(errp,

            "can't use already used cryptodev backend: %s", path);

        g_free(path);

    } else {

        qdev_prop_allow_set_link_before_realize(obj, name, val, errp);

    }

}


static void unterminated_dict(void)

{

    QObject *obj = qobject_from_json("{'abc':32", NULL);

    g_assert(obj == NULL);

}


static void* attribute_align_arg worker(void *v)

{

    AVCodecContext *avctx = v;

    SliceThreadContext *c = avctx->internal->thread_ctx;

    unsigned last_execute = 0;

    int our_job = c->job_count;

    int thread_count = avctx->thread_count;

    int self_id;

    pthread_mutex_lock(&c->current_job_lock);

    self_id = c->current_job++;

    for (;;){

        while (our_job >= c->job_count) {

            if (c->current_job == thread_count + c->job_count)

                pthread_cond_signal(&c->last_job_cond);

            while (last_execute == c->current_execute && !c->done)

                pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);

            last_execute = c->current_execute;

            our_job = self_id;

            if (c->done) {

                pthread_mutex_unlock(&c->current_job_lock);

                return NULL;

            }

        }

        pthread_mutex_unlock(&c->current_job_lock);

        c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):

                                                   c->func2(avctx, c->args, our_job, self_id);

        pthread_mutex_lock(&c->current_job_lock);

        our_job = c->current_job++;

    }

}