static int mjpegb_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    AVFrame *picture = data;

    GetBitContext hgb; /* for the header */

    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;

    uint32_t field_size, sod_offs;

    buf_ptr = buf;

    buf_end = buf + buf_size;

read_header:

    /* reset on every SOI */

    s->restart_interval = 0;

    s->restart_count = 0;

    s->mjpb_skiptosod = 0;

    if (buf_end - buf_ptr >= 1 << 28)

        return AVERROR_INVALIDDATA;

    init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);

    skip_bits(&hgb, 32); /* reserved zeros */

    if (get_bits_long(&hgb, 32) != MKBETAG('m','j','p','g'))

    {

        av_log(avctx, AV_LOG_WARNING, "not mjpeg-b (bad fourcc)\n");

        return AVERROR_INVALIDDATA;

    }

    field_size = get_bits_long(&hgb, 32); /* field size */

    av_log(avctx, AV_LOG_DEBUG, "field size: 0x%x\n", field_size);

    skip_bits(&hgb, 32); /* padded field size */

    second_field_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "second_field_offs is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "second field offs: 0x%x\n", second_field_offs);

    dqt_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "dqt is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "dqt offs: 0x%x\n", dqt_offs);

    if (dqt_offs)

    {

        init_get_bits(&s->gb, buf_ptr+dqt_offs, (buf_end - (buf_ptr+dqt_offs))*8);

        s->start_code = DQT;

        if (ff_mjpeg_decode_dqt(s) < 0 &&

            (avctx->err_recognition & AV_EF_EXPLODE))

          return AVERROR_INVALIDDATA;

    }

    dht_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "dht is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "dht offs: 0x%x\n", dht_offs);

    if (dht_offs)

    {

        init_get_bits(&s->gb, buf_ptr+dht_offs, (buf_end - (buf_ptr+dht_offs))*8);

        s->start_code = DHT;

        ff_mjpeg_decode_dht(s);

    }

    sof_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sof is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sof offs: 0x%x\n", sof_offs);

    if (sof_offs)

    {

        init_get_bits(&s->gb, buf_ptr+sof_offs, (buf_end - (buf_ptr+sof_offs))*8);

        s->start_code = SOF0;

        if (ff_mjpeg_decode_sof(s) < 0)

            return -1;

    }

    sos_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sos is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sos offs: 0x%x\n", sos_offs);

    sod_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sof is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sod offs: 0x%x\n", sod_offs);

    if (sos_offs)

    {

        init_get_bits(&s->gb, buf_ptr + sos_offs,

                      8 * FFMIN(field_size, buf_end - buf_ptr - sos_offs));

        s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));

        s->start_code = SOS;

        if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&

            (avctx->err_recognition & AV_EF_EXPLODE))

          return AVERROR_INVALIDDATA;

    }

    if (s->interlaced) {

        s->bottom_field ^= 1;

        /* if not bottom field, do not output image yet */

        if (s->bottom_field != s->interlace_polarity && second_field_offs)

        {

            buf_ptr = buf + second_field_offs;

            goto read_header;

            }

    }

    //XXX FIXME factorize, this looks very similar to the EOI code

    *picture= *s->picture_ptr;

    *data_size = sizeof(AVFrame);

    if(!s->lossless){

        picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);

        picture->qstride= 0;

        picture->qscale_table= s->qscale_table;

        memset(picture->qscale_table, picture->quality, (s->width+15)/16);

        if(avctx->debug & FF_DEBUG_QP)

            av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);

        picture->quality*= FF_QP2LAMBDA;

    }

    return buf_size;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = pl110_initfn;

    set_bit(DEVICE_CATEGORY_DISPLAY, dc->categories);

    dc->no_user = 1;

    dc->vmsd = &vmstate_pl110;

}


static always_inline void fload_invalid_op_excp (int op)

{

    int ve;

    ve = fpscr_ve;

    if (op & POWERPC_EXCP_FP_VXSNAN) {

        /* Operation on signaling NaN */

        env->fpscr |= 1 << FPSCR_VXSNAN;

    }

    if (op & POWERPC_EXCP_FP_VXSOFT) {

        /* Software-defined condition */

        env->fpscr |= 1 << FPSCR_VXSOFT;

    }

    switch (op & ~(POWERPC_EXCP_FP_VXSOFT | POWERPC_EXCP_FP_VXSNAN)) {

    case POWERPC_EXCP_FP_VXISI:

        /* Magnitude subtraction of infinities */

        env->fpscr |= 1 << FPSCR_VXISI;

        goto update_arith;

    case POWERPC_EXCP_FP_VXIDI:

        /* Division of infinity by infinity */

        env->fpscr |= 1 << FPSCR_VXIDI;

        goto update_arith;

    case POWERPC_EXCP_FP_VXZDZ:

        /* Division of zero by zero */

        env->fpscr |= 1 << FPSCR_VXZDZ;

        goto update_arith;

    case POWERPC_EXCP_FP_VXIMZ:

        /* Multiplication of zero by infinity */

        env->fpscr |= 1 << FPSCR_VXIMZ;

        goto update_arith;

    case POWERPC_EXCP_FP_VXVC:

        /* Ordered comparison of NaN */

        env->fpscr |= 1 << FPSCR_VXVC;

        env->fpscr &= ~(0xF << FPSCR_FPCC);

        env->fpscr |= 0x11 << FPSCR_FPCC;

        /* We must update the target FPR before raising the exception */

        if (ve != 0) {

            env->exception_index = POWERPC_EXCP_PROGRAM;

            env->error_code = POWERPC_EXCP_FP | POWERPC_EXCP_FP_VXVC;

            /* Update the floating-point enabled exception summary */

            env->fpscr |= 1 << FPSCR_FEX;

            /* Exception is differed */

            ve = 0;

        }

        break;

    case POWERPC_EXCP_FP_VXSQRT:

        /* Square root of a negative number */

        env->fpscr |= 1 << FPSCR_VXSQRT;

    update_arith:

        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));

        if (ve == 0) {

            /* Set the result to quiet NaN */

            FT0 = (uint64_t)-1;

            env->fpscr &= ~(0xF << FPSCR_FPCC);

            env->fpscr |= 0x11 << FPSCR_FPCC;

        }

        break;

    case POWERPC_EXCP_FP_VXCVI:

        /* Invalid conversion */

        env->fpscr |= 1 << FPSCR_VXCVI;

        env->fpscr &= ~((1 << FPSCR_FR) | (1 << FPSCR_FI));

        if (ve == 0) {

            /* Set the result to quiet NaN */

            FT0 = (uint64_t)-1;

            env->fpscr &= ~(0xF << FPSCR_FPCC);

            env->fpscr |= 0x11 << FPSCR_FPCC;

        }

        break;

    }

    /* Update the floating-point invalid operation summary */

    env->fpscr |= 1 << FPSCR_VX;

    /* Update the floating-point exception summary */

    env->fpscr |= 1 << FPSCR_FX;

    if (ve != 0) {

        /* Update the floating-point enabled exception summary */

        env->fpscr |= 1 << FPSCR_FEX;

        if (msr_fe0 != 0 || msr_fe1 != 0)

            do_raise_exception_err(POWERPC_EXCP_PROGRAM, POWERPC_EXCP_FP | op);

    }

}


void gd_egl_scanout(DisplayChangeListener *dcl,

                    uint32_t backing_id, bool backing_y_0_top,

                    uint32_t x, uint32_t y,

                    uint32_t w, uint32_t h)

{

    VirtualConsole *vc = container_of(dcl, VirtualConsole, gfx.dcl);

    vc->gfx.x = x;

    vc->gfx.y = y;

    vc->gfx.w = w;

    vc->gfx.h = h;

    vc->gfx.tex_id = backing_id;

    vc->gfx.y0_top = backing_y_0_top;

    eglMakeCurrent(qemu_egl_display, vc->gfx.esurface,

                   vc->gfx.esurface, vc->gfx.ectx);

    if (vc->gfx.tex_id == 0 || vc->gfx.w == 0 || vc->gfx.h == 0) {

        gtk_egl_set_scanout_mode(vc, false);

        return;

    }

    gtk_egl_set_scanout_mode(vc, true);

    if (!vc->gfx.fbo_id) {

        glGenFramebuffers(1, &vc->gfx.fbo_id);

    }

    glBindFramebuffer(GL_FRAMEBUFFER_EXT, vc->gfx.fbo_id);

    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,

                              GL_TEXTURE_2D, vc->gfx.tex_id, 0);

}


static av_cold int vaapi_encode_check_config(AVCodecContext *avctx)

{

    VAAPIEncodeContext *ctx = avctx->priv_data;

    VAStatus vas;

    int i, n, err;

    VAProfile    *profiles    = NULL;

    VAEntrypoint *entrypoints = NULL;

    VAConfigAttrib attr[] = {

        { VAConfigAttribRateControl     },

        { VAConfigAttribEncMaxRefFrames },

    };

    n = vaMaxNumProfiles(ctx->hwctx->display);

    profiles = av_malloc_array(n, sizeof(VAProfile));

    if (!profiles) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",

               vas, vaErrorStr(vas));

        err = AVERROR(ENOSYS);

        goto fail;

    }

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

        if (profiles[i] == ctx->va_profile)

            break;

    }

    if (i >= n) {

        av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",

               ctx->va_profile);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    n = vaMaxNumEntrypoints(ctx->hwctx->display);

    entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));

    if (!entrypoints) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,

                                   entrypoints, &n);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "

               "profile %u: %d (%s).\n", ctx->va_profile,

               vas, vaErrorStr(vas));

        err = AVERROR(ENOSYS);

        goto fail;

    }

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

        if (entrypoints[i] == ctx->va_entrypoint)

            break;

    }

    if (i >= n) {

        av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "

               "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    vas = vaGetConfigAttributes(ctx->hwctx->display,

                                ctx->va_profile, ctx->va_entrypoint,

                                attr, FF_ARRAY_ELEMS(attr));

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "

               "attributes: %d (%s).\n", vas, vaErrorStr(vas));

        return AVERROR(EINVAL);

    }

    for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {

        if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {

            // Unfortunately we have to treat this as "don't know" and hope

            // for the best, because the Intel MJPEG encoder returns this

            // for all the interesting attributes.

            continue;

        }

        switch (attr[i].type) {

        case VAConfigAttribRateControl:

            if (!(ctx->va_rc_mode & attr[i].value)) {

                av_log(avctx, AV_LOG_ERROR, "Rate control mode is not "

                       "supported: %x\n", attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

            break;

        case VAConfigAttribEncMaxRefFrames:

        {

            unsigned int ref_l0 = attr[i].value & 0xffff;

            unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;

            if (avctx->gop_size > 1 && ref_l0 < 1) {

                av_log(avctx, AV_LOG_ERROR, "P frames are not "

                       "supported (%x).\n", attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

            if (avctx->max_b_frames > 0 && ref_l1 < 1) {

                av_log(avctx, AV_LOG_ERROR, "B frames are not "

                       "supported (%x).\n", attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

        }

        break;

        }

    }

    err = 0;

fail:

    av_freep(&profiles);

    av_freep(&entrypoints);

    return err;

}


static int64_t qemu_icount_delta(void)

{

    if (!use_icount) {

        return 5000 * (int64_t) 1000000;

    } else if (use_icount == 1) {

        /* When not using an adaptive execution frequency

           we tend to get badly out of sync with real time,

           so just delay for a reasonable amount of time.  */

        return 0;

    } else {

        return cpu_get_icount() - cpu_get_clock();

    }

}


static int unpack_parse_unit(DiracParseUnit *pu, DiracParseContext *pc,

                             int offset)

{

    uint8_t *start = pc->buffer + offset;

    uint8_t *end   = pc->buffer + pc->index;

    if (start < pc->buffer || (start + 13 > end))

        return 0;

    pu->pu_type = start[4];

    pu->next_pu_offset = AV_RB32(start + 5);

    pu->prev_pu_offset = AV_RB32(start + 9);

    if (pu->pu_type == 0x10 && pu->next_pu_offset == 0)

        pu->next_pu_offset = 13;

    return 1;

}


int qcow2_get_refcount(BlockDriverState *bs, int64_t cluster_index,

                       uint64_t *refcount)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t refcount_table_index, block_index;

    int64_t refcount_block_offset;

    int ret;

    uint16_t *refcount_block;

    refcount_table_index = cluster_index >> s->refcount_block_bits;

    if (refcount_table_index >= s->refcount_table_size) {

        *refcount = 0;

        return 0;

    }

    refcount_block_offset =

        s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;

    if (!refcount_block_offset) {

        *refcount = 0;

        return 0;

    }

    if (offset_into_cluster(s, refcount_block_offset)) {

        qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#" PRIx64

                                " unaligned (reftable index: %#" PRIx64 ")",

                                refcount_block_offset, refcount_table_index);

        return -EIO;

    }

    ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,

        (void**) &refcount_block);

    if (ret < 0) {

        return ret;

    }

    block_index = cluster_index & (s->refcount_block_size - 1);

    *refcount = be16_to_cpu(refcount_block[block_index]);

    ret = qcow2_cache_put(bs, s->refcount_block_cache,

        (void**) &refcount_block);

    if (ret < 0) {

        return ret;

    }

    return 0;

}


static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)

{

    unsigned char response[VNC_AUTH_CHALLENGE_SIZE];

    size_t i, pwlen;

    unsigned char key[8];

    time_t now = time(NULL);

    QCryptoCipher *cipher = NULL;

    Error *err = NULL;

    if (!vs->vd->password) {

        VNC_DEBUG("No password configured on server");

        goto reject;

    }

    if (vs->vd->expires < now) {

        VNC_DEBUG("Password is expired");

        goto reject;

    }

    memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);

    /* Calculate the expected challenge response */

    pwlen = strlen(vs->vd->password);

    for (i=0; i<sizeof(key); i++)

        key[i] = i<pwlen ? vs->vd->password[i] : 0;

    cipher = qcrypto_cipher_new(

        QCRYPTO_CIPHER_ALG_DES_RFB,

        QCRYPTO_CIPHER_MODE_ECB,

        key, G_N_ELEMENTS(key),

        &err);

    if (!cipher) {

        VNC_DEBUG("Cannot initialize cipher %s",

                  error_get_pretty(err));

        error_free(err);

        goto reject;

    }

    if (qcrypto_cipher_encrypt(cipher,

                               vs->challenge,

                               response,

                               VNC_AUTH_CHALLENGE_SIZE,

                               &err) < 0) {

        VNC_DEBUG("Cannot encrypt challenge %s",

                  error_get_pretty(err));

        error_free(err);

        goto reject;

    }

    /* Compare expected vs actual challenge response */

    if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {

        VNC_DEBUG("Client challenge response did not match\n");

        goto reject;

    } else {

        VNC_DEBUG("Accepting VNC challenge response\n");

        vnc_write_u32(vs, 0); /* Accept auth */

        vnc_flush(vs);

        start_client_init(vs);

    }

    qcrypto_cipher_free(cipher);

    return 0;

reject:

    vnc_write_u32(vs, 1); /* Reject auth */

    if (vs->minor >= 8) {

        static const char err[] = "Authentication failed";

        vnc_write_u32(vs, sizeof(err));

        vnc_write(vs, err, sizeof(err));

    }

    vnc_flush(vs);

    vnc_client_error(vs);

    qcrypto_cipher_free(cipher);

    return 0;

}


QapiDeallocVisitor *qapi_dealloc_visitor_new(void)

{

    QapiDeallocVisitor *v;

    v = g_malloc0(sizeof(*v));

    v->visitor.start_struct = qapi_dealloc_start_struct;

    v->visitor.end_struct = qapi_dealloc_end_struct;

    v->visitor.start_implicit_struct = qapi_dealloc_start_implicit_struct;

    v->visitor.end_implicit_struct = qapi_dealloc_end_implicit_struct;

    v->visitor.start_list = qapi_dealloc_start_list;

    v->visitor.next_list = qapi_dealloc_next_list;

    v->visitor.end_list = qapi_dealloc_end_list;

    v->visitor.type_enum = qapi_dealloc_type_enum;

    v->visitor.type_int64 = qapi_dealloc_type_int64;

    v->visitor.type_uint64 = qapi_dealloc_type_uint64;

    v->visitor.type_bool = qapi_dealloc_type_bool;

    v->visitor.type_str = qapi_dealloc_type_str;

    v->visitor.type_number = qapi_dealloc_type_number;

    v->visitor.type_any = qapi_dealloc_type_anything;

    v->visitor.start_union = qapi_dealloc_start_union;

    QTAILQ_INIT(&v->stack);

    return v;

}


static void test_qemu_strtoll_empty(void)

{

    const char *str = "";

    char f = 'X';

    const char *endptr = &f;

    int64_t res = 999;

    int err;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

    g_assert(endptr == str);

}


static void adb_kbd_realizefn(DeviceState *dev, Error **errp)

{

    ADBKeyboardClass *akc = ADB_KEYBOARD_GET_CLASS(dev);

    akc->parent_realize(dev, errp);

    qemu_input_handler_register(dev, &adb_keyboard_handler);

}


static int h264_init_context(AVCodecContext *avctx, H264Context *h)
{
    int i;
    h->avctx                 = avctx;
    h->picture_structure     = PICT_FRAME;
    h->workaround_bugs       = avctx->workaround_bugs;
    h->flags                 = avctx->flags;
    h->poc.prev_poc_msb      = 1 << 16;
    h->recovery_frame        = -1;
    h->frame_recovered       = 0;
    h->next_outputed_poc = INT_MIN;
    for (i = 0; i < MAX_DELAYED_PIC_COUNT; i++)
        h->last_pocs[i] = INT_MIN;
    ff_h264_sei_uninit(&h->sei);
    avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
    h->nb_slice_ctx = (avctx->active_thread_type & FF_THREAD_SLICE) ? avctx->thread_count : 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 < H264_MAX_PICTURE_COUNT; i++) {
        h->DPB[i].f = av_frame_alloc();
        if (!h->DPB[i].f)
            return AVERROR(ENOMEM);
    }
    h->cur_pic.f = av_frame_alloc();
    if (!h->cur_pic.f)
        return AVERROR(ENOMEM);
    h->output_frame = av_frame_alloc();
    if (!h->output_frame)
        return AVERROR(ENOMEM);
    for (i = 0; i < h->nb_slice_ctx; i++)
        h->slice_ctx[i].h264 = h;
    return 0;
}


static int xcbgrab_reposition(AVFormatContext *s,

                              xcb_query_pointer_reply_t *p,

                              xcb_get_geometry_reply_t *geo)

{

    XCBGrabContext *c = s->priv_data;

    int x = c->x, y = c->y, p_x = p->win_x, p_y = p->win_y;

    int w = c->width, h = c->height, f = c->follow_mouse;

    if (!p || !geo)

        return AVERROR(EIO);

    if (f == FOLLOW_CENTER) {

        x = p_x - w / 2;

        y = p_y - h / 2;

    } else {

        int left   = x + f;

        int right  = x + w - f;

        int top    = y + f;

        int bottom = y + h + f;

        if (p_x > right) {

            x += p_x - right;

        } else if (p_x < left) {

            x -= left - p_x;

        }

        if (p_y > bottom) {

            y += p_y - bottom;

        } else if (p_y < top) {

            y -= top - p_y;

        }

    }

    c->x = FFMIN(FFMAX(0, x), geo->width  - w);

    c->y = FFMIN(FFMAX(0, y), geo->height - h);

    return 0;

}


clk_setup_cb cpu_ppc_tb_init (CPUPPCState *env, uint32_t freq)

{

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    ppc_tb_t *tb_env;

    tb_env = g_malloc0(sizeof(ppc_tb_t));

    env->tb_env = tb_env;

    tb_env->flags = PPC_DECR_UNDERFLOW_TRIGGERED;

    if (env->insns_flags & PPC_SEGMENT_64B) {

        /* All Book3S 64bit CPUs implement level based DEC logic */

        tb_env->flags |= PPC_DECR_UNDERFLOW_LEVEL;

    }

    /* Create new timer */

    tb_env->decr_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, &cpu_ppc_decr_cb, cpu);

    if (0) {

        /* XXX: find a suitable condition to enable the hypervisor decrementer

         */

        tb_env->hdecr_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, &cpu_ppc_hdecr_cb,

                                                cpu);

    } else {

        tb_env->hdecr_timer = NULL;

    }

    cpu_ppc_set_tb_clk(env, freq);

    return &cpu_ppc_set_tb_clk;

}


static int tscc2_decode_frame(AVCodecContext *avctx, void *data,

                              int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TSCC2Context *c = avctx->priv_data;

    GetByteContext gb;

    uint32_t frame_type, size;

    int i, val, len, pos = 0;

    int num_mb = c->mb_width * c->mb_height;

    int ret;

    bytestream2_init(&gb, buf, buf_size);

    frame_type = bytestream2_get_byte(&gb);

    if (frame_type > 1) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect frame type %"PRIu32"\n",

               frame_type);

        return AVERROR_INVALIDDATA;

    }

    if ((ret = ff_reget_buffer(avctx, c->pic)) < 0) {

        return ret;

    }

    if (frame_type == 0) {

        *got_frame      = 1;

        if ((ret = av_frame_ref(data, c->pic)) < 0)

            return ret;

        return buf_size;

    }

    if (bytestream2_get_bytes_left(&gb) < 4) {

        av_log(avctx, AV_LOG_ERROR, "Frame is too short\n");

        return AVERROR_INVALIDDATA;

    }

    c->quant[0] = bytestream2_get_byte(&gb);

    c->quant[1] = bytestream2_get_byte(&gb);

    if (c->quant[0] < 2 || c->quant[0] > NUM_VLC_SETS + 1 ||

        c->quant[1] < 2 || c->quant[1] > NUM_VLC_SETS + 1) {

        av_log(avctx, AV_LOG_ERROR, "Invalid quantisers %d / %d\n",

               c->quant[0], c->quant[1]);

        return AVERROR_INVALIDDATA;

    }

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

        c->q[0][i] = tscc2_quants[c->quant[0] - 2][i];

        c->q[1][i] = tscc2_quants[c->quant[1] - 2][i];

    }

    bytestream2_skip(&gb, 1);

    size = bytestream2_get_le32(&gb);

    if (size > bytestream2_get_bytes_left(&gb)) {

        av_log(avctx, AV_LOG_ERROR, "Slice properties chunk is too large\n");

        return AVERROR_INVALIDDATA;

    }

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

        val   = bytestream2_get_byte(&gb);

        len   = val & 0x3F;

        val >>= 6;

        if (pos + len > num_mb) {

            av_log(avctx, AV_LOG_ERROR, "Too many slice properties\n");

            return AVERROR_INVALIDDATA;

        }

        memset(c->slice_quants + pos, val, len);

        pos += len;

    }

    if (pos < num_mb) {

        av_log(avctx, AV_LOG_ERROR, "Too few slice properties (%d / %d)\n",

               pos, num_mb);

        return AVERROR_INVALIDDATA;

    }

    for (i = 0; i < c->mb_height; i++) {

        size = bytestream2_peek_byte(&gb);

        if (size & 1) {

            size = bytestream2_get_byte(&gb) - 1;

        } else {

            size = bytestream2_get_le32(&gb) >> 1;

        }

        if (!size) {

            int skip_row = 1, j, off = i * c->mb_width;

            for (j = 0; j < c->mb_width; j++) {

                if (c->slice_quants[off + j] == 1 ||

                    c->slice_quants[off + j] == 2) {

                    skip_row = 0;

                    break;

                }

            }

            if (!skip_row) {

                av_log(avctx, AV_LOG_ERROR, "Non-skip row with zero size\n");

                return AVERROR_INVALIDDATA;

            }

        }

        if (bytestream2_get_bytes_left(&gb) < size) {

            av_log(avctx, AV_LOG_ERROR, "Invalid slice size (%"PRIu32"/%u)\n",

                   size, bytestream2_get_bytes_left(&gb));

            return AVERROR_INVALIDDATA;

        }

        ret = tscc2_decode_slice(c, i, buf + bytestream2_tell(&gb), size);

        if (ret) {

            av_log(avctx, AV_LOG_ERROR, "Error decoding slice %d\n", i);

            return ret;

        }

        bytestream2_skip(&gb, size);

    }

    *got_frame      = 1;

    if ((ret = av_frame_ref(data, c->pic)) < 0)

        return ret;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


static void test_ide_mbr(bool use_device, MBRcontents mbr)

{

    char *argv[256];

    int argc;

    Backend i;

    const char *dev;

    argc = setup_common(argv, ARRAY_SIZE(argv));

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

        cur_ide[i] = &hd_chst[i][mbr];

        dev = use_device ? (is_hd(cur_ide[i]) ? "ide-hd" : "ide-cd") : NULL;

        argc = setup_ide(argc, argv, ARRAY_SIZE(argv), i, dev, i, mbr, "");

    }

    qtest_start(g_strjoinv(" ", argv));

    test_cmos();

    qtest_end();

}


static int ram_save_block(QEMUFile *f, bool last_stage)

{

    RAMBlock *block = last_seen_block;

    ram_addr_t offset = last_offset;

    bool complete_round = false;

    int bytes_sent = 0;

    MemoryRegion *mr;

    ram_addr_t current_addr;

    if (!block)

        block = QTAILQ_FIRST(&ram_list.blocks);

    while (true) {

        mr = block->mr;

        offset = migration_bitmap_find_and_reset_dirty(mr, offset);

        if (complete_round && block == last_seen_block &&

            offset >= last_offset) {

            break;

        }

        if (offset >= block->length) {

            offset = 0;

            block = QTAILQ_NEXT(block, next);

            if (!block) {

                block = QTAILQ_FIRST(&ram_list.blocks);

                complete_round = true;

                ram_bulk_stage = false;

            }

        } else {

            int ret;

            uint8_t *p;

            int cont = (block == last_sent_block) ?

                RAM_SAVE_FLAG_CONTINUE : 0;

            p = memory_region_get_ram_ptr(mr) + offset;

            /* In doubt sent page as normal */

            bytes_sent = -1;

            ret = ram_control_save_page(f, block->offset,

                               offset, TARGET_PAGE_SIZE, &bytes_sent);

            if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {

                if (ret != RAM_SAVE_CONTROL_DELAYED) {

                    if (bytes_sent > 0) {

                        acct_info.norm_pages++;

                    } else if (bytes_sent == 0) {

                        acct_info.dup_pages++;

                    }

                }

            } else if (is_zero_range(p, TARGET_PAGE_SIZE)) {

                acct_info.dup_pages++;

                bytes_sent = save_block_hdr(f, block, offset, cont,

                                            RAM_SAVE_FLAG_COMPRESS);

                qemu_put_byte(f, 0);

                bytes_sent++;

            } else if (!ram_bulk_stage && migrate_use_xbzrle()) {

                current_addr = block->offset + offset;

                bytes_sent = save_xbzrle_page(f, p, current_addr, block,

                                              offset, cont, last_stage);

                if (!last_stage) {

                    p = get_cached_data(XBZRLE.cache, current_addr);

                }

            }

            /* XBZRLE overflow or normal page */

            if (bytes_sent == -1) {

                bytes_sent = save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);

                qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);

                bytes_sent += TARGET_PAGE_SIZE;

                acct_info.norm_pages++;

            }

            /* if page is unmodified, continue to the next */

            if (bytes_sent > 0) {

                last_sent_block = block;

                break;

            }

        }

    }

    last_seen_block = block;

    last_offset = offset;

    return bytes_sent;

}


static inline void RENAME(rgb32tobgr15)(const uint8_t *src, uint8_t *dst, unsigned src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_15mask),"m"(green_15mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

		"movq	%%mm0, %%mm1\n\t"

		"movq	%%mm0, %%mm2\n\t"

		"movq	%%mm3, %%mm4\n\t"

		"movq	%%mm3, %%mm5\n\t"

		"psllq	$7, %%mm0\n\t"

		"psllq	$7, %%mm3\n\t"

		"pand	%%mm7, %%mm0\n\t"

		"pand	%%mm7, %%mm3\n\t"

		"psrlq	$6, %%mm1\n\t"

		"psrlq	$6, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$19, %%mm2\n\t"

		"psrlq	$19, %%mm5\n\t"

		"pand	%2, %%mm2\n\t"

		"pand	%2, %%mm5\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 16;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		// FIXME on bigendian

		const int src= *s; s += 4;

		*d++ = ((src&0xF8)<<7) + ((src&0xF800)>>6) + ((src&0xF80000)>>19);

	}

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    static int counter = 0;

    *data_size = 0;

    init_get_bits(&gb, buf, buf_size * 8);

    s->keyframe = get_bits(&gb, 1);

    s->keyframe ^= 1;

    skip_bits(&gb, 1);

    s->last_quality_index = s->quality_index;

    s->quality_index = get_bits(&gb, 6);

    if (s->quality_index != s->last_quality_index)

        init_dequantizer(s);

    debug_vp3(" VP3 frame #%d: Q index = %d", counter, s->quality_index);

    counter++;

    if (s->keyframe) {

        if ((s->golden_frame.data[0]) &&

            (s->last_frame.data[0] == s->golden_frame.data[0]))

            avctx->release_buffer(avctx, &s->golden_frame);

        else if (s->last_frame.data[0])

            avctx->release_buffer(avctx, &s->last_frame);

        s->golden_frame.reference = 0;

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

            printf("vp3: get_buffer() failed\n");

            return -1;

        }

        /* golden frame is also the current frame */

        memcpy(&s->current_frame, &s->golden_frame, sizeof(AVFrame));

        /* time to figure out pixel addresses? */

        if (!s->pixel_addresses_inited)

            vp3_calculate_pixel_addresses(s);

    } else {

        /* allocate a new current frame */

        s->current_frame.reference = 0;

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

            printf("vp3: get_buffer() failed\n");

            return -1;

        }

    }

    if (s->keyframe) {

      debug_vp3(", keyframe\n");

      /* skip the other 2 header bytes for now */

      skip_bits(&gb, 16);

    } else

      debug_vp3("\n");

    init_frame(s, &gb);

#if KEYFRAMES_ONLY

if (!s->keyframe) {

    memcpy(s->current_frame.data[0], s->golden_frame.data[0],

        s->current_frame.linesize[0] * s->height);

    memcpy(s->current_frame.data[1], s->golden_frame.data[1],

        s->current_frame.linesize[1] * s->height / 2);

    memcpy(s->current_frame.data[2], s->golden_frame.data[2],

        s->current_frame.linesize[2] * s->height / 2);

} else {

#endif

    if (unpack_superblocks(s, &gb) ||

        unpack_modes(s, &gb) ||

        unpack_vectors(s, &gb) ||

        unpack_dct_coeffs(s, &gb)) {

        printf("  vp3: could not decode frame\n");

        return -1;

    }

    reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);

    reverse_dc_prediction(s, s->u_fragment_start,

        s->fragment_width / 2, s->fragment_height / 2);

    reverse_dc_prediction(s, s->v_fragment_start,

        s->fragment_width / 2, s->fragment_height / 2);

    render_fragments(s, 0, s->width, s->height, 0);

    render_fragments(s, s->u_fragment_start, s->width / 2, s->height / 2, 1);

    render_fragments(s, s->v_fragment_start, s->width / 2, s->height / 2, 2);

#if KEYFRAMES_ONLY

}

#endif

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data= s->current_frame;

    /* release the last frame, if it is allocated and if it is not the

     * golden frame */

    if ((s->last_frame.data[0]) &&

        (s->last_frame.data[0] != s->golden_frame.data[0]))

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames (last = current) */

    memcpy(&s->last_frame, &s->current_frame, sizeof(AVFrame));

    return buf_size;

}


static int ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)

{

    CCID_Header *ccid_header;

    if (p->len + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {

        return USB_RET_STALL;

    }

    ccid_header = (CCID_Header *)s->bulk_out_data;

    memcpy(s->bulk_out_data + s->bulk_out_pos, p->data, p->len);

    s->bulk_out_pos += p->len;

    if (p->len == CCID_MAX_PACKET_SIZE) {

        DPRINTF(s, D_VERBOSE,

            "usb-ccid: bulk_in: expecting more packets (%d/%d)\n",

            p->len, ccid_header->dwLength);

        return 0;

    }

    if (s->bulk_out_pos < 10) {

        DPRINTF(s, 1,

                "%s: bad USB_TOKEN_OUT length, should be at least 10 bytes\n",

                __func__);

    } else {

        DPRINTF(s, D_MORE_INFO, "%s %x\n", __func__, ccid_header->bMessageType);

        switch (ccid_header->bMessageType) {

        case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:

            ccid_write_slot_status(s, ccid_header);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:

            DPRINTF(s, 1, "PowerOn: %d\n",

                ((CCID_IccPowerOn *)(ccid_header))->bPowerSelect);

            s->powered = true;

            if (!ccid_card_inserted(s)) {

                ccid_report_error_failed(s, ERROR_ICC_MUTE);

            }

            /* atr is written regardless of error. */

            ccid_write_data_block_atr(s, ccid_header);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:

            DPRINTF(s, 1, "PowerOff\n");

            ccid_reset_error_status(s);

            s->powered = false;

            ccid_write_slot_status(s, ccid_header);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:

            ccid_on_apdu_from_guest(s, (CCID_XferBlock *)s->bulk_out_data);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:

            ccid_reset_error_status(s);

            ccid_set_parameters(s, ccid_header);

            ccid_write_parameters(s, ccid_header);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:

            ccid_reset_error_status(s);

            ccid_reset_parameters(s);

            ccid_write_parameters(s, ccid_header);

            break;

        case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:

            ccid_reset_error_status(s);

            ccid_write_parameters(s, ccid_header);

            break;

        default:

            DPRINTF(s, 1,

                "handle_data: ERROR: unhandled message type %Xh\n",

                ccid_header->bMessageType);

            /*

             * The caller is expecting the device to respond, tell it we

             * don't support the operation.

             */

            ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);

            ccid_write_slot_status(s, ccid_header);

            break;

        }

    }

    s->bulk_out_pos = 0;

    return 0;

}


static int vp9_alloc_frame(AVCodecContext *ctx, VP9Frame *f)

{

    VP9Context *s = ctx->priv_data;

    int ret, sz;

    if ((ret = ff_thread_get_buffer(ctx, &f->tf, AV_GET_BUFFER_FLAG_REF)) < 0)

        return ret;

    sz = 64 * s->sb_cols * s->sb_rows;

    if (!(f->extradata = av_buffer_allocz(sz * (1 + sizeof(struct VP9mvrefPair))))) {

        ff_thread_release_buffer(ctx, &f->tf);

        return AVERROR(ENOMEM);

    }

    f->segmentation_map = f->extradata->data;

    f->mv = (struct VP9mvrefPair *) (f->extradata->data + sz);

    // retain segmentation map if it doesn't update

    if (s->segmentation.enabled && !s->segmentation.update_map &&

        !s->keyframe && !s->intraonly) {

        memcpy(f->segmentation_map, s->frames[LAST_FRAME].segmentation_map, sz);

    }

    return 0;

}


static int usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,

                                      uint8_t ep)

{

    AsyncURB *aurb = async_alloc(dev, p);

    struct usb_redir_bulk_packet_header bulk_packet;

    DPRINTF("bulk-out ep %02X len %d id %u\n", ep, p->len, aurb->packet_id);

    bulk_packet.endpoint  = ep;

    bulk_packet.length    = p->len;

    bulk_packet.stream_id = 0;

    aurb->bulk_packet = bulk_packet;

    if (ep & USB_DIR_IN) {

        usbredirparser_send_bulk_packet(dev->parser, aurb->packet_id,

                                        &bulk_packet, NULL, 0);

    } else {

        usbredir_log_data(dev, "bulk data out:", p->data, p->len);

        usbredirparser_send_bulk_packet(dev->parser, aurb->packet_id,

                                        &bulk_packet, p->data, p->len);

    }

    usbredirparser_do_write(dev->parser);

    return USB_RET_ASYNC;

}


void do_info_vnc(void)

{

    if (vnc_state == NULL)

	term_printf("VNC server disabled\n");

    else {

	term_printf("VNC server active on: ");

	term_print_filename(vnc_state->display);

	term_printf("\n");

	if (vnc_state->csock == -1)

	    term_printf("No client connected\n");

	else

	    term_printf("Client connected\n");

    }

}


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

{

    int ret = 0, i, got_packet = 0;

    AVDictionary *metadata = NULL;

    av_init_packet(pkt);

    while (!got_packet && !s->parse_queue) {

        AVStream *st;

        AVPacket cur_pkt;

        /* read next packet */

        ret = ff_read_packet(s, &cur_pkt);

        if (ret < 0) {

            if (ret == AVERROR(EAGAIN))

                return ret;

            /* flush the parsers */

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

                st = s->streams[i];

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

                    parse_packet(s, NULL, st->index);

            }

            /* all remaining packets are now in parse_queue =>

             * really terminate parsing */

            break;

        }

        ret = 0;

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

        if (cur_pkt.pts != AV_NOPTS_VALUE &&

            cur_pkt.dts != AV_NOPTS_VALUE &&

            cur_pkt.pts < cur_pkt.dts) {

            av_log(s, AV_LOG_WARNING,

                   "Invalid timestamps stream=%d, pts=%s, dts=%s, size=%d\n",

                   cur_pkt.stream_index,

                   av_ts2str(cur_pkt.pts),

                   av_ts2str(cur_pkt.dts),

                   cur_pkt.size);

        }

        if (s->debug & FF_FDEBUG_TS)

            av_log(s, AV_LOG_DEBUG,

                   "ff_read_packet stream=%d, pts=%s, dts=%s, size=%d, duration=%d, flags=%d\n",

                   cur_pkt.stream_index,

                   av_ts2str(cur_pkt.pts),

                   av_ts2str(cur_pkt.dts),

                   cur_pkt.size, cur_pkt.duration, cur_pkt.flags);

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

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

            if (!st->parser) {

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

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

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

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

                st->need_parsing = AVSTREAM_PARSE_NONE;

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

                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;

            else if (st->need_parsing == AVSTREAM_PARSE_FULL_ONCE)

                st->parser->flags |= PARSER_FLAG_ONCE;

            else if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)

                st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;

        }

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

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

            *pkt = cur_pkt;

            compute_pkt_fields(s, st, NULL, pkt);

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

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

                ff_reduce_index(s, st->index);

                av_add_index_entry(st, pkt->pos, pkt->dts,

                                   0, 0, AVINDEX_KEYFRAME);

            }

            got_packet = 1;

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

            if ((ret = parse_packet(s, &cur_pkt, cur_pkt.stream_index)) < 0)

                return ret;

        } else {

            /* free packet */

            av_free_packet(&cur_pkt);

        }

        if (pkt->flags & AV_PKT_FLAG_KEY)

            st->skip_to_keyframe = 0;

        if (st->skip_to_keyframe) {

            av_free_packet(&cur_pkt);

            if (got_packet) {

                *pkt = cur_pkt;

            }

            got_packet = 0;

        }

    }

    if (!got_packet && s->parse_queue)

        ret = read_from_packet_buffer(&s->parse_queue, &s->parse_queue_end, pkt);

    if (ret >= 0) {

        AVStream *st = s->streams[pkt->stream_index];

        int discard_padding = 0;

        if (st->end_discard_sample && pkt->pts != AV_NOPTS_VALUE) {

            int64_t pts = pkt->pts - (is_relative(pkt->pts) ? RELATIVE_TS_BASE : 0);

            int64_t sample = ts_to_samples(st, pts);

            int duration = ts_to_samples(st, pkt->duration);

            int64_t end_sample = sample + duration;

            if (duration > 0 && end_sample >= st->end_discard_sample)

                discard_padding = FFMIN(end_sample - st->end_discard_sample, duration);

        }

        if (st->skip_samples || discard_padding) {

            uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);

            if (p) {

                AV_WL32(p, st->skip_samples);

                AV_WL32(p + 4, discard_padding);

                av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d\n", st->skip_samples);

            }

            st->skip_samples = 0;

        }

        if (st->inject_global_side_data) {

            for (i = 0; i < st->nb_side_data; i++) {

                AVPacketSideData *src_sd = &st->side_data[i];

                uint8_t *dst_data;

                if (av_packet_get_side_data(pkt, src_sd->type, NULL))

                    continue;

                dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);

                if (!dst_data) {

                    av_log(s, AV_LOG_WARNING, "Could not inject global side data\n");

                    continue;

                }

                memcpy(dst_data, src_sd->data, src_sd->size);

            }

            st->inject_global_side_data = 0;

        }

        if (!(s->flags & AVFMT_FLAG_KEEP_SIDE_DATA))

            av_packet_merge_side_data(pkt);

    }

    av_opt_get_dict_val(s, "metadata", AV_OPT_SEARCH_CHILDREN, &metadata);

    if (metadata) {

        s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;

        av_dict_copy(&s->metadata, metadata, 0);

        av_dict_free(&metadata);

        av_opt_set_dict_val(s, "metadata", NULL, AV_OPT_SEARCH_CHILDREN);

    }

    if (s->debug & FF_FDEBUG_TS)

        av_log(s, AV_LOG_DEBUG,

               "read_frame_internal stream=%d, pts=%s, dts=%s, "

               "size=%d, duration=%d, flags=%d\n",

               pkt->stream_index,

               av_ts2str(pkt->pts),

               av_ts2str(pkt->dts),

               pkt->size, pkt->duration, pkt->flags);

    return ret;

}


void ff_hevcdsp_init_x86(HEVCDSPContext *c, const int bit_depth)

{

    int mm_flags = av_get_cpu_flags();

    if (bit_depth == 8) {

        if (EXTERNAL_MMX(mm_flags)) {

            if (EXTERNAL_MMXEXT(mm_flags)) {

                if (EXTERNAL_SSSE3(mm_flags) && ARCH_X86_64) {

                    EPEL_LINKS(c->put_hevc_epel, 0, 0, pel_pixels,  8);

                    EPEL_LINKS(c->put_hevc_epel, 0, 1, epel_h,      8);

                    EPEL_LINKS(c->put_hevc_epel, 1, 0, epel_v,      8);

                    EPEL_LINKS(c->put_hevc_epel, 1, 1, epel_hv,     8);

                    QPEL_LINKS(c->put_hevc_qpel, 0, 0, pel_pixels, 8);

                    QPEL_LINKS(c->put_hevc_qpel, 0, 1, qpel_h,     8);

                    QPEL_LINKS(c->put_hevc_qpel, 1, 0, qpel_v,     8);

                    QPEL_LINKS(c->put_hevc_qpel, 1, 1, qpel_hv,    8);

                }

            }

        }

    } else if (bit_depth == 10) {

        if (EXTERNAL_MMX(mm_flags)) {

            if (EXTERNAL_MMXEXT(mm_flags) && ARCH_X86_64) {

                if (EXTERNAL_SSSE3(mm_flags)) {

                    EPEL_LINKS(c->put_hevc_epel, 0, 0, pel_pixels, 10);

                    EPEL_LINKS(c->put_hevc_epel, 0, 1, epel_h,     10);

                    EPEL_LINKS(c->put_hevc_epel, 1, 0, epel_v,     10);

                    EPEL_LINKS(c->put_hevc_epel, 1, 1, epel_hv,    10);

                    QPEL_LINKS(c->put_hevc_qpel, 0, 0, pel_pixels, 10);

                    QPEL_LINKS(c->put_hevc_qpel, 0, 1, qpel_h,     10);

                    QPEL_LINKS(c->put_hevc_qpel, 1, 0, qpel_v,     10);

                    QPEL_LINKS(c->put_hevc_qpel, 1, 1, qpel_hv,    10);

                }

            }

        }

    }

}


static void postfilter(EVRCContext *e, float *in, const float *coeff,

                       float *out, int idx, const struct PfCoeff *pfc,

                       int length)

{

    float wcoef1[FILTER_ORDER], wcoef2[FILTER_ORDER],

          scratch[SUBFRAME_SIZE], temp[SUBFRAME_SIZE],

          mem[SUBFRAME_SIZE];

    float sum1 = 0.0, sum2 = 0.0, gamma, gain;

    float tilt = pfc->tilt;

    int i, n, best;

    bandwidth_expansion(wcoef1, coeff, pfc->p1);

    bandwidth_expansion(wcoef2, coeff, pfc->p2);

    /* Tilt compensation filter, TIA/IS-127 5.9.1 */

    for (i = 0; i < length - 1; i++)

        sum2 += in[i] * in[i + 1];

    if (sum2 < 0.0)

        tilt = 0.0;

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

        scratch[i] = in[i] - tilt * e->last;

        e->last = in[i];

    }

    /* Short term residual filter, TIA/IS-127 5.9.2 */

    residual_filter(&e->postfilter_residual[ACB_SIZE], scratch, wcoef1, e->postfilter_fir, length);

    /* Long term postfilter */

    best = idx;

    for (i = FFMIN(MIN_DELAY, idx - 3); i <= FFMAX(MAX_DELAY, idx + 3); i++) {

        for (n = ACB_SIZE, sum2 = 0; n < ACB_SIZE + length; n++)

            sum2 += e->postfilter_residual[n] * e->postfilter_residual[n - i];

        if (sum2 > sum1) {

            sum1 = sum2;

            best = i;

        }

    }

    for (i = ACB_SIZE, sum1 = 0; i < ACB_SIZE + length; i++)

        sum1 += e->postfilter_residual[i - best] * e->postfilter_residual[i - best];

    for (i = ACB_SIZE, sum2 = 0; i < ACB_SIZE + length; i++)

        sum2 += e->postfilter_residual[i] * e->postfilter_residual[i - best];

    if (sum2 * sum1 == 0 || e->bitrate == RATE_QUANT) {

        memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));

    } else {

        gamma = sum2 / sum1;

        if (gamma < 0.5)

            memcpy(temp, e->postfilter_residual + ACB_SIZE, length * sizeof(float));

        else {

            gamma = FFMIN(gamma, 1.0);

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

                temp[i] = e->postfilter_residual[ACB_SIZE + i] + gamma *

                    pfc->ltgain * e->postfilter_residual[ACB_SIZE + i - best];

            }

        }

    }

    memcpy(scratch, temp, length * sizeof(float));

    memcpy(mem, e->postfilter_iir, FILTER_ORDER * sizeof(float));

    synthesis_filter(scratch, wcoef2, mem, length, scratch);

    /* Gain computation, TIA/IS-127 5.9.4-2 */

    for (i = 0, sum1 = 0, sum2 = 0; i < length; i++) {

        sum1 += in[i] * in[i];

        sum2 += scratch[i] * scratch[i];

    }

    gain = sum2 ? sqrt(sum1 / sum2) : 1.0;

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

        temp[i] *= gain;

    /* Short term postfilter */

    synthesis_filter(temp, wcoef2, e->postfilter_iir, length, out);

    memcpy(e->postfilter_residual,

           e->postfilter_residual + length, ACB_SIZE * sizeof(float));

}


int ff_get_best_fcode(MpegEncContext * s, int16_t (*mv_table)[2], int type)

{

    int f_code;

    if(s->me_method>=ME_EPZS){

        int mv_num[8];

        int i, y;

        int loose=0;

        UINT8 * fcode_tab= s->fcode_tab;

        for(i=0; i<8; i++) mv_num[i]=0;

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

            int x;

            int xy= (y+1)* (s->mb_width+2) + 1;

            i= y*s->mb_width;

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

                if(s->mb_type[i] & type){

                    mv_num[ fcode_tab[mv_table[xy][0] + MAX_MV] ]++;

                    mv_num[ fcode_tab[mv_table[xy][1] + MAX_MV] ]++;

//printf("%d %d %d\n", s->mv_table[0][i], fcode_tab[s->mv_table[0][i] + MAX_MV], i);

                }

                i++;

                xy++;

            }

        }

        for(i=MAX_FCODE; i>1; i--){

            int threshold;

            loose+= mv_num[i];

            if(s->pict_type==B_TYPE) threshold= 0;

            else                     threshold= s->mb_num/20; //FIXME

            if(loose > threshold) break;

        }

//    printf("fcode: %d type: %d\n", i, s->pict_type);

        return i;

/*        for(i=0; i<=MAX_FCODE; i++){

            printf("%d ", mv_num[i]);

        }

        printf("\n");*/

    }else{

        return 1;

    }

}


static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries;

    int64_t duration=0;

    int64_t total_sample_count=0;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_dlog(c->fc, "track[%i].stts.entries = %i\n",

            c->fc->nb_streams-1, entries);

    if (!entries)

        return 0;

    if (entries >= UINT_MAX / sizeof(*sc->stts_data))

        return AVERROR(EINVAL);

    sc->stts_data = av_malloc(entries * sizeof(*sc->stts_data));

    if (!sc->stts_data)

        return AVERROR(ENOMEM);

    sc->stts_count = entries;

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

        int sample_duration;

        int sample_count;

        sample_count=avio_rb32(pb);

        sample_duration = avio_rb32(pb);

        sc->stts_data[i].count= sample_count;

        sc->stts_data[i].duration= sample_duration;

        av_dlog(c->fc, "sample_count=%d, sample_duration=%d\n",

                sample_count, sample_duration);

        duration+=(int64_t)sample_duration*sample_count;

        total_sample_count+=sample_count;

    }

    st->nb_frames= total_sample_count;

    if (duration)

        st->duration= duration;

    sc->track_end = duration;

    return 0;

}


static void start_frame(AVFilterLink *link, AVFilterPicRef *picref)

{

    CropContext *crop = link->dst->priv;

    AVFilterPicRef *ref2 = avfilter_ref_pic(picref, ~0);

    int i;

    ref2->w        = crop->w;

    ref2->h        = crop->h;

    ref2->data[0] += crop->y * ref2->linesize[0];

    ref2->data[0] += (crop->x * crop->bpp) >> 3;

    if (link->format != PIX_FMT_PAL8      &&

        link->format != PIX_FMT_BGR4_BYTE &&

        link->format != PIX_FMT_RGB4_BYTE &&

        link->format != PIX_FMT_BGR8      &&

        link->format != PIX_FMT_RGB8) {

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

            if (ref2->data[i]) {

                ref2->data[i] += (crop->y >> crop->vsub) * ref2->linesize[i];

                ref2->data[i] += ((crop->x * crop->bpp) >> 3) >> crop->hsub;

            }

        }

    }

    /* alpha plane */

    if (ref2->data[3]) {

        ref2->data[3] += crop->y * ref2->linesize[3];

        ref2->data[3] += (crop->x * crop->bpp) >> 3;

    }

    avfilter_start_frame(link->dst->outputs[0], ref2);

}


static void lsi_execute_script(LSIState *s)

{

    uint32_t insn;

    uint32_t addr;

    int opcode;

    s->istat1 |= LSI_ISTAT1_SRUN;

again:

    insn = read_dword(s, s->dsp);

    addr = read_dword(s, s->dsp + 4);

    DPRINTF("SCRIPTS dsp=%08x opcode %08x arg %08x\n", s->dsp, insn, addr);

    s->dsps = addr;

    s->dcmd = insn >> 24;

    s->dsp += 8;

    switch (insn >> 30) {

    case 0: /* Block move.  */

        if (s->sist1 & LSI_SIST1_STO) {

            DPRINTF("Delayed select timeout\n");

            lsi_stop_script(s);

            break;

        }

        s->dbc = insn & 0xffffff;

        s->rbc = s->dbc;

        if (insn & (1 << 29)) {

            /* Indirect addressing.  */

            addr = read_dword(s, addr);

        } else if (insn & (1 << 28)) {

            uint32_t buf[2];

            int32_t offset;

            /* Table indirect addressing.  */

            offset = sxt24(addr);

            cpu_physical_memory_read(s->dsa + offset, (uint8_t *)buf, 8);

            s->dbc = cpu_to_le32(buf[0]);

            s->rbc = s->dbc;

            addr = cpu_to_le32(buf[1]);

        }

        if ((s->sstat1 & PHASE_MASK) != ((insn >> 24) & 7)) {

            DPRINTF("Wrong phase got %d expected %d\n",

                    s->sstat1 & PHASE_MASK, (insn >> 24) & 7);

            lsi_script_scsi_interrupt(s, LSI_SIST0_MA, 0);

            break;

        }

        s->dnad = addr;

        /* ??? Set ESA.  */

        s->ia = s->dsp - 8;

        switch (s->sstat1 & 0x7) {

        case PHASE_DO:

            s->waiting = 2;

            lsi_do_dma(s, 1);

            if (s->waiting)

                s->waiting = 3;

            break;

        case PHASE_DI:

            s->waiting = 2;

            lsi_do_dma(s, 0);

            if (s->waiting)

                s->waiting = 3;

            break;

        case PHASE_CMD:

            lsi_do_command(s);

            break;

        case PHASE_ST:

            lsi_do_status(s);

            break;

        case PHASE_MO:

            lsi_do_msgout(s);

            break;

        case PHASE_MI:

            lsi_do_msgin(s);

            break;

        default:

            BADF("Unimplemented phase %d\n", s->sstat1 & PHASE_MASK);

            exit(1);

        }

        s->dfifo = s->dbc & 0xff;

        s->ctest5 = (s->ctest5 & 0xfc) | ((s->dbc >> 8) & 3);

        s->sbc = s->dbc;

        s->rbc -= s->dbc;

        s->ua = addr + s->dbc;

        break;

    case 1: /* IO or Read/Write instruction.  */

        opcode = (insn >> 27) & 7;

        if (opcode < 5) {

            uint32_t id;

            if (insn & (1 << 25)) {

                id = read_dword(s, s->dsa + sxt24(insn));

            } else {

                id = addr;

            }

            id = (id >> 16) & 0xf;

            if (insn & (1 << 26)) {

                addr = s->dsp + sxt24(addr);

            }

            s->dnad = addr;

            switch (opcode) {

            case 0: /* Select */

                s->sdid = id;

                if (s->current_dma_len && (s->ssid & 0xf) == id) {

                    DPRINTF("Already reselected by target %d\n", id);

                    break;

                }

                s->sstat0 |= LSI_SSTAT0_WOA;

                s->scntl1 &= ~LSI_SCNTL1_IARB;

                if (id >= LSI_MAX_DEVS || !s->scsi_dev[id]) {

                    DPRINTF("Selected absent target %d\n", id);

                    lsi_script_scsi_interrupt(s, 0, LSI_SIST1_STO);

                    lsi_disconnect(s);

                    break;

                }

                DPRINTF("Selected target %d%s\n",

                        id, insn & (1 << 3) ? " ATN" : "");

                /* ??? Linux drivers compain when this is set.  Maybe

                   it only applies in low-level mode (unimplemented).

                lsi_script_scsi_interrupt(s, LSI_SIST0_CMP, 0); */

                s->current_dev = s->scsi_dev[id];

                s->current_tag = id << 8;

                s->scntl1 |= LSI_SCNTL1_CON;

                if (insn & (1 << 3)) {

                    s->socl |= LSI_SOCL_ATN;

                }

                lsi_set_phase(s, PHASE_MO);

                break;

            case 1: /* Disconnect */

                DPRINTF("Wait Disconect\n");

                s->scntl1 &= ~LSI_SCNTL1_CON;

                break;

            case 2: /* Wait Reselect */

                lsi_wait_reselect(s);

                break;

            case 3: /* Set */

                DPRINTF("Set%s%s%s%s\n",

                        insn & (1 << 3) ? " ATN" : "",

                        insn & (1 << 6) ? " ACK" : "",

                        insn & (1 << 9) ? " TM" : "",

                        insn & (1 << 10) ? " CC" : "");

                if (insn & (1 << 3)) {

                    s->socl |= LSI_SOCL_ATN;

                    lsi_set_phase(s, PHASE_MO);

                }

                if (insn & (1 << 9)) {

                    BADF("Target mode not implemented\n");

                    exit(1);

                }

                if (insn & (1 << 10))

                    s->carry = 1;

                break;

            case 4: /* Clear */

                DPRINTF("Clear%s%s%s%s\n",

                        insn & (1 << 3) ? " ATN" : "",

                        insn & (1 << 6) ? " ACK" : "",

                        insn & (1 << 9) ? " TM" : "",

                        insn & (1 << 10) ? " CC" : "");

                if (insn & (1 << 3)) {

                    s->socl &= ~LSI_SOCL_ATN;

                }

                if (insn & (1 << 10))

                    s->carry = 0;

                break;

            }

        } else {

            uint8_t op0;

            uint8_t op1;

            uint8_t data8;

            int reg;

            int operator;

#ifdef DEBUG_LSI

            static const char *opcode_names[3] =

                {"Write", "Read", "Read-Modify-Write"};

            static const char *operator_names[8] =

                {"MOV", "SHL", "OR", "XOR", "AND", "SHR", "ADD", "ADC"};

#endif

            reg = ((insn >> 16) & 0x7f) | (insn & 0x80);

            data8 = (insn >> 8) & 0xff;

            opcode = (insn >> 27) & 7;

            operator = (insn >> 24) & 7;

            DPRINTF("%s reg 0x%x %s data8=0x%02x sfbr=0x%02x%s\n",

                    opcode_names[opcode - 5], reg,

                    operator_names[operator], data8, s->sfbr,

                    (insn & (1 << 23)) ? " SFBR" : "");

            op0 = op1 = 0;

            switch (opcode) {

            case 5: /* From SFBR */

                op0 = s->sfbr;

                op1 = data8;

                break;

            case 6: /* To SFBR */

                if (operator)

                    op0 = lsi_reg_readb(s, reg);

                op1 = data8;

                break;

            case 7: /* Read-modify-write */

                if (operator)

                    op0 = lsi_reg_readb(s, reg);

                if (insn & (1 << 23)) {

                    op1 = s->sfbr;

                } else {

                    op1 = data8;

                }

                break;

            }

            switch (operator) {

            case 0: /* move */

                op0 = op1;

                break;

            case 1: /* Shift left */

                op1 = op0 >> 7;

                op0 = (op0 << 1) | s->carry;

                s->carry = op1;

                break;

            case 2: /* OR */

                op0 |= op1;

                break;

            case 3: /* XOR */

                op0 ^= op1;

                break;

            case 4: /* AND */

                op0 &= op1;

                break;

            case 5: /* SHR */

                op1 = op0 & 1;

                op0 = (op0 >> 1) | (s->carry << 7);

                s->carry = op1;

                break;

            case 6: /* ADD */

                op0 += op1;

                s->carry = op0 < op1;

                break;

            case 7: /* ADC */

                op0 += op1 + s->carry;

                if (s->carry)

                    s->carry = op0 <= op1;

                else

                    s->carry = op0 < op1;

                break;

            }

            switch (opcode) {

            case 5: /* From SFBR */

            case 7: /* Read-modify-write */

                lsi_reg_writeb(s, reg, op0);

                break;

            case 6: /* To SFBR */

                s->sfbr = op0;

                break;

            }

        }

        break;

    case 2: /* Transfer Control.  */

        {

            int cond;

            int jmp;

            if ((insn & 0x002e0000) == 0) {

                DPRINTF("NOP\n");

                break;

            }

            if (s->sist1 & LSI_SIST1_STO) {

                DPRINTF("Delayed select timeout\n");

                lsi_stop_script(s);

                break;

            }

            cond = jmp = (insn & (1 << 19)) != 0;

            if (cond == jmp && (insn & (1 << 21))) {

                DPRINTF("Compare carry %d\n", s->carry == jmp);

                cond = s->carry != 0;

            }

            if (cond == jmp && (insn & (1 << 17))) {

                DPRINTF("Compare phase %d %c= %d\n",

                        (s->sstat1 & PHASE_MASK),

                        jmp ? '=' : '!',

                        ((insn >> 24) & 7));

                cond = (s->sstat1 & PHASE_MASK) == ((insn >> 24) & 7);

            }

            if (cond == jmp && (insn & (1 << 18))) {

                uint8_t mask;

                mask = (~insn >> 8) & 0xff;

                DPRINTF("Compare data 0x%x & 0x%x %c= 0x%x\n",

                        s->sfbr, mask, jmp ? '=' : '!', insn & mask);

                cond = (s->sfbr & mask) == (insn & mask);

            }

            if (cond == jmp) {

                if (insn & (1 << 23)) {

                    /* Relative address.  */

                    addr = s->dsp + sxt24(addr);

                }

                switch ((insn >> 27) & 7) {

                case 0: /* Jump */

                    DPRINTF("Jump to 0x%08x\n", addr);

                    s->dsp = addr;

                    break;

                case 1: /* Call */

                    DPRINTF("Call 0x%08x\n", addr);

                    s->temp = s->dsp;

                    s->dsp = addr;

                    break;

                case 2: /* Return */

                    DPRINTF("Return to 0x%08x\n", s->temp);

                    s->dsp = s->temp;

                    break;

                case 3: /* Interrupt */

                    DPRINTF("Interrupt 0x%08x\n", s->dsps);

                    if ((insn & (1 << 20)) != 0) {

                        s->istat0 |= LSI_ISTAT0_INTF;

                        lsi_update_irq(s);

                    } else {

                        lsi_script_dma_interrupt(s, LSI_DSTAT_SIR);

                    }

                    break;

                default:

                    DPRINTF("Illegal transfer control\n");

                    lsi_script_dma_interrupt(s, LSI_DSTAT_IID);

                    break;

                }

            } else {

                DPRINTF("Control condition failed\n");

            }

        }

        break;

    case 3:

        if ((insn & (1 << 29)) == 0) {

            /* Memory move.  */

            uint32_t dest;

            /* ??? The docs imply the destination address is loaded into

               the TEMP register.  However the Linux drivers rely on

               the value being presrved.  */

            dest = read_dword(s, s->dsp);

            s->dsp += 4;

            lsi_memcpy(s, dest, addr, insn & 0xffffff);

        } else {

            uint8_t data[7];

            int reg;

            int n;

            int i;

            if (insn & (1 << 28)) {

                addr = s->dsa + sxt24(addr);

            }

            n = (insn & 7);

            reg = (insn >> 16) & 0xff;

            if (insn & (1 << 24)) {

                cpu_physical_memory_read(addr, data, n);

                DPRINTF("Load reg 0x%x size %d addr 0x%08x = %08x\n", reg, n,

                        addr, *(int *)data);

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

                    lsi_reg_writeb(s, reg + i, data[i]);

                }

            } else {

                DPRINTF("Store reg 0x%x size %d addr 0x%08x\n", reg, n, addr);

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

                    data[i] = lsi_reg_readb(s, reg + i);

                }

                cpu_physical_memory_write(addr, data, n);

            }

        }

    }

    /* ??? Need to avoid infinite loops.  */

    if (s->istat1 & LSI_ISTAT1_SRUN && !s->waiting) {

        if (s->dcntl & LSI_DCNTL_SSM) {

            lsi_script_dma_interrupt(s, LSI_DSTAT_SSI);

        } else {

            goto again;

        }

    }

    DPRINTF("SCRIPTS execution stopped\n");

}


static void handle_arg_cpu(const char *arg)

{

    cpu_model = strdup(arg);

    if (cpu_model == NULL || strcmp(cpu_model, "?") == 0) {

        /* XXX: implement xxx_cpu_list for targets that still miss it */

#if defined(cpu_list_id)

        cpu_list_id(stdout, &fprintf, "");

#elif defined(cpu_list)

        cpu_list(stdout, &fprintf); /* deprecated */

#endif

        exit(1);

    }

}


static int run_test(AVCodec *enc, AVCodec *dec, AVCodecContext *enc_ctx,

                    AVCodecContext *dec_ctx)

{

    AVPacket enc_pkt;

    AVFrame *in_frame, *out_frame;

    uint8_t *raw_in = NULL, *raw_out = NULL;

    int in_offset = 0, out_offset = 0;

    int frame_data_size = 0;

    int result = 0;

    int got_output = 0;

    int i = 0;

    in_frame = av_frame_alloc();

    if (!in_frame) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate input frame\n");

        return AVERROR(ENOMEM);

    }

    in_frame->nb_samples = enc_ctx->frame_size;

    in_frame->format = enc_ctx->sample_fmt;

    in_frame->channel_layout = enc_ctx->channel_layout;

    if (av_frame_get_buffer(in_frame, 32) != 0) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate a buffer for input frame\n");

        return AVERROR(ENOMEM);

    }

    out_frame = av_frame_alloc();

    if (!out_frame) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate output frame\n");

        return AVERROR(ENOMEM);

    }

    raw_in = av_malloc(in_frame->linesize[0] * NUMBER_OF_FRAMES);

    if (!raw_in) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate memory for raw_in\n");

        return AVERROR(ENOMEM);

    }

    raw_out = av_malloc(in_frame->linesize[0] * NUMBER_OF_FRAMES);

    if (!raw_out) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate memory for raw_out\n");

        return AVERROR(ENOMEM);

    }

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

        av_init_packet(&enc_pkt);

        enc_pkt.data = NULL;

        enc_pkt.size = 0;

        generate_raw_frame((uint16_t*)(in_frame->data[0]), i, enc_ctx->sample_rate,

                           enc_ctx->channels, enc_ctx->frame_size);

        memcpy(raw_in + in_offset, in_frame->data[0], in_frame->linesize[0]);

        in_offset += in_frame->linesize[0];

        result = avcodec_encode_audio2(enc_ctx, &enc_pkt, in_frame, &got_output);

        if (result < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error encoding audio frame\n");

            return result;

        }

        /* if we get an encoded packet, feed it straight to the decoder */

        if (got_output) {

            result = avcodec_decode_audio4(dec_ctx, out_frame, &got_output, &enc_pkt);

            if (result < 0) {

                av_log(NULL, AV_LOG_ERROR, "Error decoding audio packet\n");

                return result;

            }

            if (got_output) {

                if (result != enc_pkt.size) {

                    av_log(NULL, AV_LOG_INFO, "Decoder consumed only part of a packet, it is allowed to do so -- need to update this test\n");

                    return AVERROR_UNKNOWN;

                }

                if (in_frame->nb_samples != out_frame->nb_samples) {

                    av_log(NULL, AV_LOG_ERROR, "Error frames before and after decoding has different number of samples\n");

                    return AVERROR_UNKNOWN;

                }

                if (in_frame->channel_layout != out_frame->channel_layout) {

                    av_log(NULL, AV_LOG_ERROR, "Error frames before and after decoding has different channel layout\n");

                    return AVERROR_UNKNOWN;

                }

                if (in_frame->format != out_frame->format) {

                    av_log(NULL, AV_LOG_ERROR, "Error frames before and after decoding has different sample format\n");

                    return AVERROR_UNKNOWN;

                }

                memcpy(raw_out + out_offset, out_frame->data[0], out_frame->linesize[0]);

                out_offset += out_frame->linesize[0];

            }

        }

        av_free_packet(&enc_pkt);

    }

    if (memcmp(raw_in, raw_out, frame_data_size * NUMBER_OF_FRAMES) != 0) {

        av_log(NULL, AV_LOG_ERROR, "Output differs\n");

        return 1;

    }

    av_log(NULL, AV_LOG_INFO, "OK\n");

    av_freep(&raw_in);

    av_freep(&raw_out);

    av_frame_free(&in_frame);

    av_frame_free(&out_frame);

    return 0;

}


static av_cold int pcm_encode_init(AVCodecContext *avctx)

{

    avctx->frame_size = 0;

    switch(avctx->codec->id) {

    case CODEC_ID_PCM_ALAW:

        pcm_alaw_tableinit();

        break;

    case CODEC_ID_PCM_MULAW:

        pcm_ulaw_tableinit();

        break;

    default:

        break;

    }

    avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);

    avctx->block_align = avctx->channels * avctx->bits_per_coded_sample/8;

    avctx->coded_frame= avcodec_alloc_frame();

    return 0;

}


static int vorbis_encode_frame(AVCodecContext *avccontext,

                               unsigned char *packets,

                               int buf_size, void *data)

{

    vorbis_enc_context *venc = avccontext->priv_data;

    const signed short *audio = data;

    int samples = data ? avccontext->frame_size : 0;

    vorbis_enc_mode *mode;

    vorbis_enc_mapping *mapping;

    PutBitContext pb;

    int i;

    if (!apply_window_and_mdct(venc, audio, samples))

        return 0;

    samples = 1 << (venc->log2_blocksize[0] - 1);

    init_put_bits(&pb, packets, buf_size);

    put_bits(&pb, 1, 0); // magic bit

    put_bits(&pb, ilog(venc->nmodes - 1), 0); // 0 bits, the mode

    mode    = &venc->modes[0];

    mapping = &venc->mappings[mode->mapping];

    if (mode->blockflag) {

        put_bits(&pb, 1, 0);

        put_bits(&pb, 1, 0);

    }

    for (i = 0; i < venc->channels; i++) {

        vorbis_enc_floor *fc = &venc->floors[mapping->floor[mapping->mux[i]]];

        uint16_t posts[MAX_FLOOR_VALUES];

        floor_fit(venc, fc, &venc->coeffs[i * samples], posts, samples);

        floor_encode(venc, fc, &pb, posts, &venc->floor[i * samples], samples);

    }

    for (i = 0; i < venc->channels * samples; i++)

        venc->coeffs[i] /= venc->floor[i];

    for (i = 0; i < mapping->coupling_steps; i++) {

        float *mag = venc->coeffs + mapping->magnitude[i] * samples;

        float *ang = venc->coeffs + mapping->angle[i]     * samples;

        int j;

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

            float a = ang[j];

            ang[j] -= mag[j];

            if (mag[j] > 0)

                ang[j] = -ang[j];

            if (ang[j] < 0)

                mag[j] = a;

        }

    }

    residue_encode(venc, &venc->residues[mapping->residue[mapping->mux[0]]],

                   &pb, venc->coeffs, samples, venc->channels);

    avccontext->coded_frame->pts = venc->sample_count;

    venc->sample_count += avccontext->frame_size;

    flush_put_bits(&pb);

    return put_bits_count(&pb) >> 3;

}


void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,

    uint32_t max_frags, bool has_virt_hdr)

{

    struct NetTxPkt *p = g_malloc0(sizeof *p);

    p->pci_dev = pci_dev;

    p->vec = g_malloc((sizeof *p->vec) *

        (max_frags + NET_TX_PKT_PL_START_FRAG));

    p->raw = g_malloc((sizeof *p->raw) * max_frags);

    p->max_payload_frags = max_frags;

    p->max_raw_frags = max_frags;

    p->has_virt_hdr = has_virt_hdr;

    p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;

    p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =

        p->has_virt_hdr ? sizeof p->virt_hdr : 0;

    p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;

    p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;

    *pkt = p;

}


static int xen_pt_cmd_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                                uint16_t *val, uint16_t dev_value,

                                uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint16_t writable_mask = 0;

    uint16_t throughable_mask = 0;

    uint16_t emu_mask = reg->emu_mask;

    if (s->is_virtfn) {

        emu_mask |= PCI_COMMAND_MEMORY;

    }

    /* modify emulate register */

    writable_mask = ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    /* create value for writing to I/O device register */

    throughable_mask = ~emu_mask & valid_mask;

    if (*val & PCI_COMMAND_INTX_DISABLE) {

        throughable_mask |= PCI_COMMAND_INTX_DISABLE;

    } else {

        if (s->machine_irq) {

            throughable_mask |= PCI_COMMAND_INTX_DISABLE;

        }

    }

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;

}


static int rv34_decode_cbp(GetBitContext *gb, RV34VLC *vlc, int table)

{

    int pattern, code, cbp=0;

    int ones;

    static const int cbp_masks[3] = {0x100000, 0x010000, 0x110000};

    static const int shifts[4] = { 0, 2, 8, 10 };

    const int *curshift = shifts;

    int i, t, mask;

    code = get_vlc2(gb, vlc->cbppattern[table].table, 9, 2);

    pattern = code & 0xF;

    code >>= 4;

    ones = rv34_count_ones[pattern];

    for(mask = 8; mask; mask >>= 1, curshift++){

        if(pattern & mask)

            cbp |= get_vlc2(gb, vlc->cbp[table][ones].table, vlc->cbp[table][ones].bits, 1) << curshift[0];

    }

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

        t = modulo_three_table[code][i];

        if(t == 1)

            cbp |= cbp_masks[get_bits1(gb)] << i;

        if(t == 2)

            cbp |= cbp_masks[2] << i;

    }

    return cbp;

}


static int mtv_read_header(AVFormatContext *s)

{

    MTVDemuxContext *mtv = s->priv_data;

    AVIOContext   *pb  = s->pb;

    AVStream        *st;

    unsigned int    audio_subsegments;

    avio_skip(pb, 3);

    mtv->file_size         = avio_rl32(pb);

    mtv->segments          = avio_rl32(pb);

    avio_skip(pb, 32);

    mtv->audio_identifier  = avio_rl24(pb);

    mtv->audio_br          = avio_rl16(pb);

    mtv->img_colorfmt      = avio_rl24(pb);

    mtv->img_bpp           = avio_r8(pb);

    mtv->img_width         = avio_rl16(pb);

    mtv->img_height        = avio_rl16(pb);

    mtv->img_segment_size  = avio_rl16(pb);

    /* Calculate width and height if missing from header */

    if(!mtv->img_width)

        mtv->img_width=mtv->img_segment_size / (mtv->img_bpp>>3)

                        / mtv->img_height;

    if(!mtv->img_height)

        mtv->img_height=mtv->img_segment_size / (mtv->img_bpp>>3)

                        / mtv->img_width;

    avio_skip(pb, 4);

    audio_subsegments = avio_rl16(pb);

    if (audio_subsegments == 0) {

        avpriv_request_sample(s, "MTV files without audio");

        return AVERROR_PATCHWELCOME;

    }

    mtv->full_segment_size =

        audio_subsegments * (MTV_AUDIO_PADDING_SIZE + MTV_ASUBCHUNK_DATA_SIZE) +

        mtv->img_segment_size;

    mtv->video_fps         = (mtv->audio_br / 4) / audio_subsegments;

    // FIXME Add sanity check here

    // all systems go! init decoders

    // video - raw rgb565

    st = avformat_new_stream(s, NULL);

    if(!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 64, 1, mtv->video_fps);

    st->codec->codec_type      = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id        = AV_CODEC_ID_RAWVIDEO;

    st->codec->pix_fmt         = AV_PIX_FMT_RGB565BE;

    st->codec->width           = mtv->img_width;

    st->codec->height          = mtv->img_height;

    st->codec->extradata       = av_strdup("BottomUp");

    st->codec->extradata_size  = 9;

    // audio - mp3

    st = avformat_new_stream(s, NULL);

    if(!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 64, 1, AUDIO_SAMPLING_RATE);

    st->codec->codec_type      = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id        = AV_CODEC_ID_MP3;

    st->codec->bit_rate        = mtv->audio_br;

    st->need_parsing           = AVSTREAM_PARSE_FULL;

    // Jump over header

    if(avio_seek(pb, MTV_HEADER_SIZE, SEEK_SET) != MTV_HEADER_SIZE)

        return AVERROR(EIO);

    return 0;

}


static int check_refcounts_l2(BlockDriverState *bs,

    uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,

    int check_copied)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l2_table, offset;

    int i, l2_size, nb_csectors, refcount;

    int errors = 0;

    /* Read L2 table from disk */

    l2_size = s->l2_size * sizeof(uint64_t);

    l2_table = qemu_malloc(l2_size);

    if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size)

        goto fail;

    /* Do the actual checks */

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

        offset = be64_to_cpu(l2_table[i]);

        if (offset != 0) {

            if (offset & QCOW_OFLAG_COMPRESSED) {

                /* Compressed clusters don't have QCOW_OFLAG_COPIED */

                if (offset & QCOW_OFLAG_COPIED) {

                    fprintf(stderr, "ERROR: cluster %" PRId64 ": "

                        "copied flag must never be set for compressed "

                        "clusters\n", offset >> s->cluster_bits);

                    offset &= ~QCOW_OFLAG_COPIED;

                    errors++;

                }

                /* Mark cluster as used */

                nb_csectors = ((offset >> s->csize_shift) &

                               s->csize_mask) + 1;

                offset &= s->cluster_offset_mask;

                errors += inc_refcounts(bs, refcount_table,

                              refcount_table_size,

                              offset & ~511, nb_csectors * 512);

            } else {

                /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */

                if (check_copied) {

                    uint64_t entry = offset;

                    offset &= ~QCOW_OFLAG_COPIED;

                    refcount = get_refcount(bs, offset >> s->cluster_bits);

                    if (refcount < 0) {

                        fprintf(stderr, "Can't get refcount for offset %"

                            PRIx64 ": %s\n", entry, strerror(-refcount));

                    }

                    if ((refcount == 1) != ((entry & QCOW_OFLAG_COPIED) != 0)) {

                        fprintf(stderr, "ERROR OFLAG_COPIED: offset=%"

                            PRIx64 " refcount=%d\n", entry, refcount);

                        errors++;

                    }

                }

                /* Mark cluster as used */

                offset &= ~QCOW_OFLAG_COPIED;

                errors += inc_refcounts(bs, refcount_table,

                              refcount_table_size,

                              offset, s->cluster_size);

                /* Correct offsets are cluster aligned */

                if (offset & (s->cluster_size - 1)) {

                    fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "

                        "properly aligned; L2 entry corrupted.\n", offset);

                    errors++;

                }

            }

        }

    }

    qemu_free(l2_table);

    return errors;

fail:

    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");

    qemu_free(l2_table);

    return -EIO;

}


static int bink_decode_plane(BinkContext *c, AVFrame *frame, GetBitContext *gb,

                             int plane_idx, int is_chroma)

{

    int blk, ret;

    int i, j, bx, by;

    uint8_t *dst, *prev, *ref, *ref_start, *ref_end;

    int v, col[2];

    const uint8_t *scan;

    int xoff, yoff;

    LOCAL_ALIGNED_16(int16_t, block, [64]);

    LOCAL_ALIGNED_16(uint8_t, ublock, [64]);

    LOCAL_ALIGNED_16(int32_t, dctblock, [64]);

    int coordmap[64];

    const int stride = frame->linesize[plane_idx];

    int bw = is_chroma ? (c->avctx->width  + 15) >> 4 : (c->avctx->width  + 7) >> 3;

    int bh = is_chroma ? (c->avctx->height + 15) >> 4 : (c->avctx->height + 7) >> 3;

    int width = c->avctx->width >> is_chroma;

    init_lengths(c, FFMAX(width, 8), bw);

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

        read_bundle(gb, c, i);

    ref_start = c->last->data[plane_idx] ? c->last->data[plane_idx]

                                         : frame->data[plane_idx];

    ref_end   = ref_start

                + (bw - 1 + c->last->linesize[plane_idx] * (bh - 1)) * 8;

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

        coordmap[i] = (i & 7) + (i >> 3) * stride;

    for (by = 0; by < bh; by++) {

        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_BLOCK_TYPES])) < 0)

            return ret;

        if ((ret = read_block_types(c->avctx, gb, &c->bundle[BINK_SRC_SUB_BLOCK_TYPES])) < 0)

            return ret;

        if ((ret = read_colors(gb, &c->bundle[BINK_SRC_COLORS], c)) < 0)

            return ret;

        if ((ret = read_patterns(c->avctx, gb, &c->bundle[BINK_SRC_PATTERN])) < 0)

            return ret;

        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_X_OFF])) < 0)

            return ret;

        if ((ret = read_motion_values(c->avctx, gb, &c->bundle[BINK_SRC_Y_OFF])) < 0)

            return ret;

        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTRA_DC], DC_START_BITS, 0)) < 0)

            return ret;

        if ((ret = read_dcs(c->avctx, gb, &c->bundle[BINK_SRC_INTER_DC], DC_START_BITS, 1)) < 0)

            return ret;

        if ((ret = read_runs(c->avctx, gb, &c->bundle[BINK_SRC_RUN])) < 0)

            return ret;

        if (by == bh)

            break;

        dst  = frame->data[plane_idx]  + 8*by*stride;

        prev = (c->last->data[plane_idx] ? c->last->data[plane_idx]

                                         : frame->data[plane_idx]) + 8*by*stride;

        for (bx = 0; bx < bw; bx++, dst += 8, prev += 8) {

            blk = get_value(c, BINK_SRC_BLOCK_TYPES);

            // 16x16 block type on odd line means part of the already decoded block, so skip it

            if ((by & 1) && blk == SCALED_BLOCK) {

                bx++;

                dst  += 8;

                prev += 8;

                continue;

            }

            switch (blk) {

            case SKIP_BLOCK:

                c->hdsp.put_pixels_tab[1][0](dst, prev, stride, 8);

                break;

            case SCALED_BLOCK:

                blk = get_value(c, BINK_SRC_SUB_BLOCK_TYPES);

                switch (blk) {

                case RUN_BLOCK:

                    scan = bink_patterns[get_bits(gb, 4)];

                    i = 0;

                    do {

                        int run = get_value(c, BINK_SRC_RUN) + 1;

                        i += run;

                        if (i > 64) {

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

                            return AVERROR_INVALIDDATA;

                        }

                        if (get_bits1(gb)) {

                            v = get_value(c, BINK_SRC_COLORS);

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

                                ublock[*scan++] = v;

                        } else {

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

                                ublock[*scan++] = get_value(c, BINK_SRC_COLORS);

                        }

                    } while (i < 63);

                    if (i == 63)

                        ublock[*scan++] = get_value(c, BINK_SRC_COLORS);

                    break;

                case INTRA_BLOCK:

                    memset(dctblock, 0, sizeof(*dctblock) * 64);

                    dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);

                    read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);

                    c->binkdsp.idct_put(ublock, 8, dctblock);

                    break;

                case FILL_BLOCK:

                    v = get_value(c, BINK_SRC_COLORS);

                    c->bdsp.fill_block_tab[0](dst, v, stride, 16);

                    break;

                case PATTERN_BLOCK:

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

                        col[i] = get_value(c, BINK_SRC_COLORS);

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

                        v = get_value(c, BINK_SRC_PATTERN);

                        for (i = 0; i < 8; i++, v >>= 1)

                            ublock[i + j*8] = col[v & 1];

                    }

                    break;

                case RAW_BLOCK:

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

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

                            ublock[i + j*8] = get_value(c, BINK_SRC_COLORS);

                    break;

                default:

                    av_log(c->avctx, AV_LOG_ERROR, "Incorrect 16x16 block type %d\n", blk);

                    return AVERROR_INVALIDDATA;

                }

                if (blk != FILL_BLOCK)

                c->binkdsp.scale_block(ublock, dst, stride);

                bx++;

                dst  += 8;

                prev += 8;

                break;

            case MOTION_BLOCK:

                xoff = get_value(c, BINK_SRC_X_OFF);

                yoff = get_value(c, BINK_SRC_Y_OFF);

                ref = prev + xoff + yoff * stride;

                if (ref < ref_start || ref > ref_end) {

                    av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",

                           bx*8 + xoff, by*8 + yoff);

                    return AVERROR_INVALIDDATA;

                }

                c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                break;

            case RUN_BLOCK:

                scan = bink_patterns[get_bits(gb, 4)];

                i = 0;

                do {

                    int run = get_value(c, BINK_SRC_RUN) + 1;

                    i += run;

                    if (i > 64) {

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

                        return AVERROR_INVALIDDATA;

                    }

                    if (get_bits1(gb)) {

                        v = get_value(c, BINK_SRC_COLORS);

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

                            dst[coordmap[*scan++]] = v;

                    } else {

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

                            dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);

                    }

                } while (i < 63);

                if (i == 63)

                    dst[coordmap[*scan++]] = get_value(c, BINK_SRC_COLORS);

                break;

            case RESIDUE_BLOCK:

                xoff = get_value(c, BINK_SRC_X_OFF);

                yoff = get_value(c, BINK_SRC_Y_OFF);

                ref = prev + xoff + yoff * stride;

                if (ref < ref_start || ref > ref_end) {

                    av_log(c->avctx, AV_LOG_ERROR, "Copy out of bounds @%d, %d\n",

                           bx*8 + xoff, by*8 + yoff);

                    return AVERROR_INVALIDDATA;

                }

                c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                c->bdsp.clear_block(block);

                v = get_bits(gb, 7);

                read_residue(gb, block, v);

                c->binkdsp.add_pixels8(dst, block, stride);

                break;

            case INTRA_BLOCK:

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = get_value(c, BINK_SRC_INTRA_DC);

                read_dct_coeffs(gb, dctblock, bink_scan, bink_intra_quant, -1);

                c->binkdsp.idct_put(dst, stride, dctblock);

                break;

            case FILL_BLOCK:

                v = get_value(c, BINK_SRC_COLORS);

                c->bdsp.fill_block_tab[1](dst, v, stride, 8);

                break;

            case INTER_BLOCK:

                xoff = get_value(c, BINK_SRC_X_OFF);

                yoff = get_value(c, BINK_SRC_Y_OFF);

                ref = prev + xoff + yoff * stride;

                c->hdsp.put_pixels_tab[1][0](dst, ref, stride, 8);

                memset(dctblock, 0, sizeof(*dctblock) * 64);

                dctblock[0] = get_value(c, BINK_SRC_INTER_DC);

                read_dct_coeffs(gb, dctblock, bink_scan, bink_inter_quant, -1);

                c->binkdsp.idct_add(dst, stride, dctblock);

                break;

            case PATTERN_BLOCK:

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

                    col[i] = get_value(c, BINK_SRC_COLORS);

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

                    v = get_value(c, BINK_SRC_PATTERN);

                    for (j = 0; j < 8; j++, v >>= 1)

                        dst[i*stride + j] = col[v & 1];

                }

                break;

            case RAW_BLOCK:

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

                    memcpy(dst + i*stride, c->bundle[BINK_SRC_COLORS].cur_ptr + i*8, 8);

                c->bundle[BINK_SRC_COLORS].cur_ptr += 64;

                break;

            default:

                av_log(c->avctx, AV_LOG_ERROR, "Unknown block type %d\n", blk);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (get_bits_count(gb) & 0x1F) //next plane data starts at 32-bit boundary

        skip_bits_long(gb, 32 - (get_bits_count(gb) & 0x1F));

    return 0;

}


static void unterminated_string(void)

{

    QObject *obj = qobject_from_json("\"abc", NULL);

    g_assert(obj == NULL);

}


int kvm_coalesce_mmio_region(target_phys_addr_t start, ram_addr_t size)

{

    int ret = -ENOSYS;

#ifdef KVM_CAP_COALESCED_MMIO

    KVMState *s = kvm_state;

    if (s->coalesced_mmio) {

        struct kvm_coalesced_mmio_zone zone;

        zone.addr = start;

        zone.size = size;

        ret = kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);

    }

#endif

    return ret;

}


static void test_visitor_in_errors(TestInputVisitorData *data,

                                   const void *unused)

{

    TestStruct *p = NULL;

    Error *err = NULL;

    Visitor *v;

    v = visitor_input_test_init(data, "{ 'integer': false, 'boolean': 'foo', 'string': -42 }");

    visit_type_TestStruct(v, &p, NULL, &err);

    error_free_or_abort(&err);

    /* FIXME - a failed parse should not leave a partially-allocated p

     * for us to clean up; this could cause callers to leak memory. */

    g_assert(p->string == NULL);

    g_free(p->string);

    g_free(p);

}


static int wmavoice_decode_packet(AVCodecContext *ctx, void *data,

                                  int *got_frame_ptr, AVPacket *avpkt)

{

    WMAVoiceContext *s = ctx->priv_data;

    GetBitContext *gb = &s->gb;

    int size, res, pos;

    /* Packets are sometimes a multiple of ctx->block_align, with a packet

     * header at each ctx->block_align bytes. However, FFmpeg's ASF demuxer

     * feeds us ASF packets, which may concatenate multiple "codec" packets

     * in a single "muxer" packet, so we artificially emulate that by

     * capping the packet size at ctx->block_align. */

    for (size = avpkt->size; size > ctx->block_align; size -= ctx->block_align);

    if (!size) {

        *got_frame_ptr = 0;

        return 0;

    }

    init_get_bits(&s->gb, avpkt->data, size << 3);

    /* size == ctx->block_align is used to indicate whether we are dealing with

     * a new packet or a packet of which we already read the packet header

     * previously. */

    if (size == ctx->block_align) { // new packet header

        if ((res = parse_packet_header(s)) < 0)

            return res;

        /* If the packet header specifies a s->spillover_nbits, then we want

         * to push out all data of the previous packet (+ spillover) before

         * continuing to parse new superframes in the current packet. */

        if (s->spillover_nbits > 0) {

            if (s->sframe_cache_size > 0) {

                int cnt = get_bits_count(gb);

                copy_bits(&s->pb, avpkt->data, size, gb, s->spillover_nbits);

                flush_put_bits(&s->pb);

                s->sframe_cache_size += s->spillover_nbits;

                if ((res = synth_superframe(ctx, data, got_frame_ptr)) == 0 &&

                    *got_frame_ptr) {

                    cnt += s->spillover_nbits;

                    s->skip_bits_next = cnt & 7;

                    return cnt >> 3;

                } else

                    skip_bits_long (gb, s->spillover_nbits - cnt +

                                    get_bits_count(gb)); // resync

            } else

                skip_bits_long(gb, s->spillover_nbits);  // resync

        }

    } else if (s->skip_bits_next)

        skip_bits(gb, s->skip_bits_next);

    /* Try parsing superframes in current packet */

    s->sframe_cache_size = 0;

    s->skip_bits_next = 0;

    pos = get_bits_left(gb);

    if ((res = synth_superframe(ctx, data, got_frame_ptr)) < 0) {

        return res;

    } else if (*got_frame_ptr) {

        int cnt = get_bits_count(gb);

        s->skip_bits_next = cnt & 7;

        return cnt >> 3;

    } else if ((s->sframe_cache_size = pos) > 0) {

        /* rewind bit reader to start of last (incomplete) superframe... */

        init_get_bits(gb, avpkt->data, size << 3);

        skip_bits_long(gb, (size << 3) - pos);

        av_assert1(get_bits_left(gb) == pos);

        /* ...and cache it for spillover in next packet */

        init_put_bits(&s->pb, s->sframe_cache, SFRAME_CACHE_MAXSIZE);

        copy_bits(&s->pb, avpkt->data, size, gb, s->sframe_cache_size);

        // FIXME bad - just copy bytes as whole and add use the

        // skip_bits_next field

    }

    return size;

}


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

{

    MOVContext *mov = s->priv_data;

    MOVStreamContext *sc;

    AVIndexEntry *sample;

    AVStream *st = NULL;

    int ret;

    mov->fc = s;

 retry:

    sample = mov_find_next_sample(s, &st);

    if (!sample) {

        mov->found_mdat = 0;

        if (!mov->next_root_atom)

            return AVERROR_EOF;

        avio_seek(s->pb, mov->next_root_atom, SEEK_SET);

        mov->next_root_atom = 0;

        if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||

            avio_feof(s->pb))

            return AVERROR_EOF;

        av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));

        goto retry;

    }

    sc = st->priv_data;

    /* must be done just before reading, to avoid infinite loop on sample */

    sc->current_sample++;

    if (mov->next_root_atom) {

        sample->pos = FFMIN(sample->pos, mov->next_root_atom);

        sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos));

    }

    if (st->discard != AVDISCARD_ALL) {

        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {

            av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",

                   sc->ffindex, sample->pos);

            return AVERROR_INVALIDDATA;

        }

        ret = av_get_packet(sc->pb, pkt, sample->size);

        if (ret < 0)

            return ret;

        if (sc->has_palette) {

            uint8_t *pal;

            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);

            if (!pal) {

                av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");

            } else {

                memcpy(pal, sc->palette, AVPALETTE_SIZE);

                sc->has_palette = 0;

            }

        }

#if CONFIG_DV_DEMUXER

        if (mov->dv_demux && sc->dv_audio_container) {

            avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);

            av_freep(&pkt->data);

            pkt->size = 0;

            ret = avpriv_dv_get_packet(mov->dv_demux, pkt);

            if (ret < 0)

                return ret;

        }

#endif

    }

    pkt->stream_index = sc->ffindex;

    pkt->dts = sample->timestamp;

    if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {

        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;

        /* update ctts context */

        sc->ctts_sample++;

        if (sc->ctts_index < sc->ctts_count &&

            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {

            sc->ctts_index++;

            sc->ctts_sample = 0;

        }

        if (sc->wrong_dts)

            pkt->dts = AV_NOPTS_VALUE;

    } else {

        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?

            st->index_entries[sc->current_sample].timestamp : st->duration;

        pkt->duration = next_dts - pkt->dts;

        pkt->pts = pkt->dts;

    }

    if (st->discard == AVDISCARD_ALL)

        goto retry;

    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;

    pkt->pos = sample->pos;

    return 0;

}