START_TEST(simple_list)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = "[43,42]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = "[43]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        { }

                    })),

        },

        {

            .encoded = "[]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        { }

                    })),

        },

        {

            .encoded = "[{}]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    {},

                                        })),

                        {},

                            })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QLIST);

        fail_unless(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str));

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QLIST);

        fail_unless(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


static void readline_update(ReadLineState *rs)

{

    int i, delta, len;

    if (rs->cmd_buf_size != rs->last_cmd_buf_size ||

        memcmp(rs->cmd_buf, rs->last_cmd_buf, rs->cmd_buf_size) != 0) {

        for(i = 0; i < rs->last_cmd_buf_index; i++) {

            monitor_printf(rs->mon, "\033[D");

        }

        rs->cmd_buf[rs->cmd_buf_size] = '\0';

        if (rs->read_password) {

            len = strlen(rs->cmd_buf);

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

                monitor_printf(rs->mon, "*");

        } else {

            monitor_printf(rs->mon, "%s", rs->cmd_buf);

        }

        monitor_printf(rs->mon, "\033[K");

        memcpy(rs->last_cmd_buf, rs->cmd_buf, rs->cmd_buf_size);

        rs->last_cmd_buf_size = rs->cmd_buf_size;

        rs->last_cmd_buf_index = rs->cmd_buf_size;

    }

    if (rs->cmd_buf_index != rs->last_cmd_buf_index) {

        delta = rs->cmd_buf_index - rs->last_cmd_buf_index;

        if (delta > 0) {

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

                monitor_printf(rs->mon, "\033[C");

            }

        } else {

            delta = -delta;

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

                monitor_printf(rs->mon, "\033[D");

            }

        }

        rs->last_cmd_buf_index = rs->cmd_buf_index;

    }

    monitor_flush(rs->mon);

}


void virtio_queue_update_rings(VirtIODevice *vdev, int n)

{

    VRing *vring = &vdev->vq[n].vring;

    if (!vring->desc) {

        /* not yet setup -> nothing to do */

        return;

    }

    vring->avail = vring->desc + vring->num * sizeof(VRingDesc);

    vring->used = vring_align(vring->avail +

                              offsetof(VRingAvail, ring[vring->num]),

                              vring->align);

    virtio_init_region_cache(vdev, n);

}


static int qcow2_write_snapshots(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    QCowSnapshot *sn;

    QCowSnapshotHeader h;

    QCowSnapshotExtraData extra;

    int i, name_size, id_str_size, snapshots_size;

    struct {

        uint32_t nb_snapshots;

        uint64_t snapshots_offset;

    } QEMU_PACKED header_data;

    int64_t offset, snapshots_offset;

    int ret;

    /* compute the size of the snapshots */

    offset = 0;

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

        sn = s->snapshots + i;

        offset = align_offset(offset, 8);

        offset += sizeof(h);

        offset += sizeof(extra);

        offset += strlen(sn->id_str);

        offset += strlen(sn->name);

    }

    snapshots_size = offset;

    /* Allocate space for the new snapshot list */

    snapshots_offset = qcow2_alloc_clusters(bs, snapshots_size);

    bdrv_flush(bs->file);

    offset = snapshots_offset;

    if (offset < 0) {

        return offset;

    }

    /* Write all snapshots to the new list */

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

        sn = s->snapshots + i;

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

        h.l1_table_offset = cpu_to_be64(sn->l1_table_offset);

        h.l1_size = cpu_to_be32(sn->l1_size);

        /* If it doesn't fit in 32 bit, older implementations should treat it

         * as a disk-only snapshot rather than truncate the VM state */

        if (sn->vm_state_size <= 0xffffffff) {

            h.vm_state_size = cpu_to_be32(sn->vm_state_size);

        }

        h.date_sec = cpu_to_be32(sn->date_sec);

        h.date_nsec = cpu_to_be32(sn->date_nsec);

        h.vm_clock_nsec = cpu_to_be64(sn->vm_clock_nsec);

        h.extra_data_size = cpu_to_be32(sizeof(extra));

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

        extra.vm_state_size_large = cpu_to_be64(sn->vm_state_size);

        extra.disk_size = cpu_to_be64(sn->disk_size);

        id_str_size = strlen(sn->id_str);

        name_size = strlen(sn->name);

        h.id_str_size = cpu_to_be16(id_str_size);

        h.name_size = cpu_to_be16(name_size);

        offset = align_offset(offset, 8);

        ret = bdrv_pwrite(bs->file, offset, &h, sizeof(h));

        if (ret < 0) {

            goto fail;

        }

        offset += sizeof(h);

        ret = bdrv_pwrite(bs->file, offset, &extra, sizeof(extra));

        if (ret < 0) {

            goto fail;

        }

        offset += sizeof(extra);

        ret = bdrv_pwrite(bs->file, offset, sn->id_str, id_str_size);

        if (ret < 0) {

            goto fail;

        }

        offset += id_str_size;

        ret = bdrv_pwrite(bs->file, offset, sn->name, name_size);

        if (ret < 0) {

            goto fail;

        }

        offset += name_size;

    }

    /*

     * Update the header to point to the new snapshot table. This requires the

     * new table and its refcounts to be stable on disk.

     */

    ret = bdrv_flush(bs);

    if (ret < 0) {

        goto fail;

    }

    QEMU_BUILD_BUG_ON(offsetof(QCowHeader, snapshots_offset) !=

        offsetof(QCowHeader, nb_snapshots) + sizeof(header_data.nb_snapshots));

    header_data.nb_snapshots        = cpu_to_be32(s->nb_snapshots);

    header_data.snapshots_offset    = cpu_to_be64(snapshots_offset);

    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, nb_snapshots),

                           &header_data, sizeof(header_data));

    if (ret < 0) {

        goto fail;

    }

    /* free the old snapshot table */

    qcow2_free_clusters(bs, s->snapshots_offset, s->snapshots_size);

    s->snapshots_offset = snapshots_offset;

    s->snapshots_size = snapshots_size;

    return 0;

fail:

    return ret;

}


void ff_put_h264_qpel4_mc21_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midv_qrt_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4, 0);

}


static void mirror_start_job(const char *job_id, BlockDriverState *bs,

                             BlockDriverState *target, const char *replaces,

                             int64_t speed, uint32_t granularity,

                             int64_t buf_size,

                             BlockMirrorBackingMode backing_mode,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    }

    assert ((granularity & (granularity - 1)) == 0);

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    }

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    s = block_job_create(job_id, driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->target = blk_new();

    blk_insert_bs(s->target, target);

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->is_none_mode = is_none_mode;

    s->backing_mode = backing_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        g_free(s->replaces);

        blk_unref(s->target);

        block_job_unref(&s->common);

        return;

    }

    bdrv_op_block_all(target, s->common.blocker);

    s->common.co = qemu_coroutine_create(mirror_run);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


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

{

    VmGenIdState *vms = VMGENID(dev);

    if (!vms->write_pointer_available) {

        error_setg(errp, "%s requires DMA write support in fw_cfg, "

                   "which this machine type does not provide", VMGENID_DEVICE);

        return;

    }

    /* Given that this function is executing, there is at least one VMGENID

     * device. Check if there are several.

     */

    if (!find_vmgenid_dev()) {

        error_setg(errp, "at most one %s device is permitted", VMGENID_DEVICE);

        return;

    }

    qemu_register_reset(vmgenid_handle_reset, vms);

}


static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,

                                  int *got_frame, uint8_t *data_start,

                                  unsigned int data_size)

{

    WebPContext *s = avctx->priv_data;

    AVPacket pkt;

    int ret;

    if (!s->initialized) {

        ff_vp8_decode_init(avctx);

        s->initialized = 1;

        avctx->get_format = webp_get_format;

    }

    s->lossless = 0;

    if (data_size > INT_MAX) {

        av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");

        return AVERROR_PATCHWELCOME;

    }

    av_init_packet(&pkt);

    pkt.data = data_start;

    pkt.size = data_size;

    ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);

    if (s->has_alpha) {

        ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,

                                     s->alpha_data_size);

        if (ret < 0)

            return ret;

    }

    return ret;

}


static void gen_window_check1(DisasContext *dc, unsigned r1)

{

    if (dc->tb->flags & XTENSA_TBFLAG_EXCM) {

        return;

    }

    if (option_enabled(dc, XTENSA_OPTION_WINDOWED_REGISTER) &&

            r1 / 4 > dc->used_window) {

        int label = gen_new_label();

        TCGv_i32 ws = tcg_temp_new_i32();

        dc->used_window = r1 / 4;

        tcg_gen_deposit_i32(ws, cpu_SR[WINDOW_START], cpu_SR[WINDOW_START],

                dc->config->nareg / 4, dc->config->nareg / 4);

        tcg_gen_shr_i32(ws, ws, cpu_SR[WINDOW_BASE]);

        tcg_gen_andi_i32(ws, ws, (2 << (r1 / 4)) - 2);

        tcg_gen_brcondi_i32(TCG_COND_EQ, ws, 0, label);

        {

            TCGv_i32 pc = tcg_const_i32(dc->pc);

            TCGv_i32 w = tcg_const_i32(r1 / 4);

            gen_advance_ccount_cond(dc);

            gen_helper_window_check(cpu_env, pc, w);

            tcg_temp_free(w);

            tcg_temp_free(pc);

        }

        gen_set_label(label);

        tcg_temp_free(ws);

    }

}


static void set_watchdog_timer(IPMIBmcSim *ibs,

                               uint8_t *cmd, unsigned int cmd_len,

                               uint8_t *rsp, unsigned int *rsp_len,

                               unsigned int max_rsp_len)

{

    IPMIInterface *s = ibs->parent.intf;

    IPMIInterfaceClass *k = IPMI_INTERFACE_GET_CLASS(s);

    unsigned int val;

    IPMI_CHECK_CMD_LEN(8);

    val = cmd[2] & 0x7; /* Validate use */

    if (val == 0 || val > 5) {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    val = cmd[3] & 0x7; /* Validate action */

    switch (val) {

    case IPMI_BMC_WATCHDOG_ACTION_NONE:

        break;

    case IPMI_BMC_WATCHDOG_ACTION_RESET:

        rsp[2] = k->do_hw_op(s, IPMI_RESET_CHASSIS, 1);

        break;

    case IPMI_BMC_WATCHDOG_ACTION_POWER_DOWN:

        rsp[2] = k->do_hw_op(s, IPMI_POWEROFF_CHASSIS, 1);

        break;

    case IPMI_BMC_WATCHDOG_ACTION_POWER_CYCLE:

        rsp[2] = k->do_hw_op(s, IPMI_POWERCYCLE_CHASSIS, 1);

        break;

    default:

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

    }

    if (rsp[2]) {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    val = (cmd[3] >> 4) & 0x7; /* Validate preaction */

    switch (val) {

    case IPMI_BMC_WATCHDOG_PRE_MSG_INT:

    case IPMI_BMC_WATCHDOG_PRE_NONE:

        break;

    case IPMI_BMC_WATCHDOG_PRE_NMI:

        if (!k->do_hw_op(s, IPMI_SEND_NMI, 1)) {

            /* NMI not supported. */

            rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

            return;

        }

        break;

    default:

        /* We don't support PRE_SMI */

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    ibs->watchdog_initialized = 1;

    ibs->watchdog_use = cmd[2] & IPMI_BMC_WATCHDOG_USE_MASK;

    ibs->watchdog_action = cmd[3] & IPMI_BMC_WATCHDOG_ACTION_MASK;

    ibs->watchdog_pretimeout = cmd[4];

    ibs->watchdog_expired &= ~cmd[5];

    ibs->watchdog_timeout = cmd[6] | (((uint16_t) cmd[7]) << 8);

    if (ibs->watchdog_running & IPMI_BMC_WATCHDOG_GET_DONT_STOP(ibs)) {

        do_watchdog_reset(ibs);

    } else {

        ibs->watchdog_running = 0;

    }

}


int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx)

{

    int i, ret;

    Picture *pic;

    s->mb_skipped = 0;

    if (!ff_thread_can_start_frame(avctx)) {

        av_log(avctx, AV_LOG_ERROR, "Attempt to start a frame outside SETUP state\n");

        return -1;

    }

    /* mark & release old frames */

    if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&

        s->last_picture_ptr != s->next_picture_ptr &&

        s->last_picture_ptr->f->buf[0]) {

        ff_mpeg_unref_picture(s, s->last_picture_ptr);

    }

    /* release forgotten pictures */

    /* if (mpeg124/h263) */

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

        if (&s->picture[i] != s->last_picture_ptr &&

            &s->picture[i] != s->next_picture_ptr &&

            s->picture[i].reference && !s->picture[i].needs_realloc) {

            if (!(avctx->active_thread_type & FF_THREAD_FRAME))

                av_log(avctx, AV_LOG_ERROR,

                       "releasing zombie picture\n");

            ff_mpeg_unref_picture(s, &s->picture[i]);

        }

    }

    ff_mpeg_unref_picture(s, &s->current_picture);

    release_unused_pictures(s);

    if (s->current_picture_ptr && !s->current_picture_ptr->f->buf[0]) {

        // we already have a unused image

        // (maybe it was set before reading the header)

        pic = s->current_picture_ptr;

    } else {

        i   = ff_find_unused_picture(s, 0);

        if (i < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");

            return i;

        }

        pic = &s->picture[i];

    }

    pic->reference = 0;

    if (!s->droppable) {

        if (s->pict_type != AV_PICTURE_TYPE_B)

            pic->reference = 3;

    }

    pic->f->coded_picture_number = s->coded_picture_number++;

    if (ff_alloc_picture(s, pic, 0) < 0)

        return -1;

    s->current_picture_ptr = pic;

    // FIXME use only the vars from current_pic

    s->current_picture_ptr->f->top_field_first = s->top_field_first;

    if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

        s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        if (s->picture_structure != PICT_FRAME)

            s->current_picture_ptr->f->top_field_first =

                (s->picture_structure == PICT_TOP_FIELD) == s->first_field;

    }

    s->current_picture_ptr->f->interlaced_frame = !s->progressive_frame &&

                                                 !s->progressive_sequence;

    s->current_picture_ptr->field_picture      =  s->picture_structure != PICT_FRAME;

    s->current_picture_ptr->f->pict_type = s->pict_type;

    // if (s->flags && CODEC_FLAG_QSCALE)

    //     s->current_picture_ptr->quality = s->new_picture_ptr->quality;

    s->current_picture_ptr->f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    if ((ret = ff_mpeg_ref_picture(s, &s->current_picture,

                                   s->current_picture_ptr)) < 0)

        return ret;

    if (s->pict_type != AV_PICTURE_TYPE_B) {

        s->last_picture_ptr = s->next_picture_ptr;

        if (!s->droppable)

            s->next_picture_ptr = s->current_picture_ptr;

    }

    ff_dlog(s->avctx, "L%p N%p C%p L%p N%p C%p type:%d drop:%d\n",

            s->last_picture_ptr, s->next_picture_ptr,s->current_picture_ptr,

            s->last_picture_ptr    ? s->last_picture_ptr->f->data[0]    : NULL,

            s->next_picture_ptr    ? s->next_picture_ptr->f->data[0]    : NULL,

            s->current_picture_ptr ? s->current_picture_ptr->f->data[0] : NULL,

            s->pict_type, s->droppable);

    if ((!s->last_picture_ptr || !s->last_picture_ptr->f->buf[0]) &&

        (s->pict_type != AV_PICTURE_TYPE_I ||

         s->picture_structure != PICT_FRAME)) {

        int h_chroma_shift, v_chroma_shift;

        av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,

                                         &h_chroma_shift, &v_chroma_shift);

        if (s->pict_type == AV_PICTURE_TYPE_B && s->next_picture_ptr && s->next_picture_ptr->f->buf[0])

            av_log(avctx, AV_LOG_DEBUG,

                   "allocating dummy last picture for B frame\n");

        else if (s->pict_type != AV_PICTURE_TYPE_I)

            av_log(avctx, AV_LOG_ERROR,

                   "warning: first frame is no keyframe\n");

        else if (s->picture_structure != PICT_FRAME)

            av_log(avctx, AV_LOG_DEBUG,

                   "allocate dummy last picture for field based first keyframe\n");

        /* Allocate a dummy frame */

        i = ff_find_unused_picture(s, 0);

        if (i < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");

            return i;

        }

        s->last_picture_ptr = &s->picture[i];

        s->last_picture_ptr->reference   = 3;

        s->last_picture_ptr->f->key_frame = 0;

        s->last_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;

        if (ff_alloc_picture(s, s->last_picture_ptr, 0) < 0) {

            s->last_picture_ptr = NULL;

            return -1;

        }

        if (!avctx->hwaccel && !(avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)) {

            for(i=0; i<avctx->height; i++)

                memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i,

                       0x80, avctx->width);

            for(i=0; i<FF_CEIL_RSHIFT(avctx->height, v_chroma_shift); i++) {

                memset(s->last_picture_ptr->f->data[1] + s->last_picture_ptr->f->linesize[1]*i,

                       0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));

                memset(s->last_picture_ptr->f->data[2] + s->last_picture_ptr->f->linesize[2]*i,

                       0x80, FF_CEIL_RSHIFT(avctx->width, h_chroma_shift));

            }

            if(s->codec_id == AV_CODEC_ID_FLV1 || s->codec_id == AV_CODEC_ID_H263){

                for(i=0; i<avctx->height; i++)

                memset(s->last_picture_ptr->f->data[0] + s->last_picture_ptr->f->linesize[0]*i, 16, avctx->width);

            }

        }

        ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 0);

        ff_thread_report_progress(&s->last_picture_ptr->tf, INT_MAX, 1);

    }

    if ((!s->next_picture_ptr || !s->next_picture_ptr->f->buf[0]) &&

        s->pict_type == AV_PICTURE_TYPE_B) {

        /* Allocate a dummy frame */

        i = ff_find_unused_picture(s, 0);

        if (i < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "no frame buffer available\n");

            return i;

        }

        s->next_picture_ptr = &s->picture[i];

        s->next_picture_ptr->reference   = 3;

        s->next_picture_ptr->f->key_frame = 0;

        s->next_picture_ptr->f->pict_type = AV_PICTURE_TYPE_P;

        if (ff_alloc_picture(s, s->next_picture_ptr, 0) < 0) {

            s->next_picture_ptr = NULL;

            return -1;

        }

        ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 0);

        ff_thread_report_progress(&s->next_picture_ptr->tf, INT_MAX, 1);

    }

#if 0 // BUFREF-FIXME

    memset(s->last_picture.f->data, 0, sizeof(s->last_picture.f->data));

    memset(s->next_picture.f->data, 0, sizeof(s->next_picture.f->data));

#endif

    if (s->last_picture_ptr) {

        ff_mpeg_unref_picture(s, &s->last_picture);

        if (s->last_picture_ptr->f->buf[0] &&

            (ret = ff_mpeg_ref_picture(s, &s->last_picture,

                                       s->last_picture_ptr)) < 0)

            return ret;

    }

    if (s->next_picture_ptr) {

        ff_mpeg_unref_picture(s, &s->next_picture);

        if (s->next_picture_ptr->f->buf[0] &&

            (ret = ff_mpeg_ref_picture(s, &s->next_picture,

                                       s->next_picture_ptr)) < 0)

            return ret;

    }

    av_assert0(s->pict_type == AV_PICTURE_TYPE_I || (s->last_picture_ptr &&

                                                 s->last_picture_ptr->f->buf[0]));

    if (s->picture_structure!= PICT_FRAME) {

        int i;

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

            if (s->picture_structure == PICT_BOTTOM_FIELD) {

                s->current_picture.f->data[i] +=

                    s->current_picture.f->linesize[i];

            }

            s->current_picture.f->linesize[i] *= 2;

            s->last_picture.f->linesize[i]    *= 2;

            s->next_picture.f->linesize[i]    *= 2;

        }

    }

    s->err_recognition = avctx->err_recognition;

    /* set dequantizer, we can't do it during init as

     * it might change for mpeg4 and we can't do it in the header

     * decode as init is not called for mpeg4 there yet */

    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

        s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;

        s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;

    } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {

        s->dct_unquantize_intra = s->dct_unquantize_h263_intra;

        s->dct_unquantize_inter = s->dct_unquantize_h263_inter;

    } else {

        s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;

        s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;

    }

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

        gray_frame(s->current_picture_ptr->f);

    }

    return 0;

}


int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    NBDRequest request = {

        .type = NBD_CMD_TRIM,

        .from = offset,

        .len = bytes,

    };

    assert(!(client->info.flags & NBD_FLAG_READ_ONLY));

    if (!(client->info.flags & NBD_FLAG_SEND_TRIM)) {

        return 0;

    }

    return nbd_co_request(bs, &request, NULL);

}


static QEMUCursor *qxl_cursor(PCIQXLDevice *qxl, QXLCursor *cursor,

                              uint32_t group_id)

{

    QEMUCursor *c;

    size_t size;

    c = cursor_alloc(cursor->header.width, cursor->header.height);

    c->hot_x = cursor->header.hot_spot_x;

    c->hot_y = cursor->header.hot_spot_y;

    switch (cursor->header.type) {

    case SPICE_CURSOR_TYPE_ALPHA:

        size = sizeof(uint32_t) * cursor->header.width * cursor->header.height;

        qxl_unpack_chunks(c->data, size, qxl, &cursor->chunk, group_id);

        if (qxl->debug > 2) {

            cursor_print_ascii_art(c, "qxl/alpha");

        }

        break;

    default:

        fprintf(stderr, "%s: not implemented: type %d\n",

                __FUNCTION__, cursor->header.type);

        goto fail;

    }

    return c;

fail:

    cursor_put(c);

    return NULL;

}


QFloat *qfloat_from_double(double value)

{

    QFloat *qf;

    qf = g_malloc(sizeof(*qf));

    qf->value = value;

    QOBJECT_INIT(qf, &qfloat_type);

    return qf;

}


void *qemu_blockalign(BlockDriverState *bs, size_t size)

{

    return qemu_memalign(bdrv_opt_mem_align(bs), size);

}


static void spapr_drc_release(sPAPRDRConnector *drc)

{

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    drck->release(drc->dev);

    drc->awaiting_release = false;

    g_free(drc->fdt);

    drc->fdt = NULL;

    drc->fdt_start_offset = 0;

    object_property_del(OBJECT(drc), "device", &error_abort);

    drc->dev = NULL;

}


static void jpeg_put_comments(MpegEncContext *s)

{

    PutBitContext *p = &s->pb;

    int size;

    uint8_t *ptr;

    if (s->aspect_ratio_info /* && !lossless */)

    {

    /* JFIF header */

    put_marker(p, APP0);

    put_bits(p, 16, 16);

    put_string(p, "JFIF"); /* this puts the trailing zero-byte too */

    put_bits(p, 16, 0x0201); /* v 1.02 */

    put_bits(p, 8, 0); /* units type: 0 - aspect ratio */

    put_bits(p, 16, s->avctx->sample_aspect_ratio.num);

    put_bits(p, 16, s->avctx->sample_aspect_ratio.den);

    put_bits(p, 8, 0); /* thumbnail width */

    put_bits(p, 8, 0); /* thumbnail height */

    }

    /* comment */

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

        put_marker(p, COM);

        flush_put_bits(p);

        ptr = pbBufPtr(p);

        put_bits(p, 16, 0); /* patched later */

        put_string(p, LIBAVCODEC_IDENT);

        size = strlen(LIBAVCODEC_IDENT)+3;

        ptr[0] = size >> 8;

        ptr[1] = size;

    }

}


static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,

                                                           vorbis_residue *vr,

                                                           unsigned ch,

                                                           uint8_t *do_not_decode,

                                                           float *vec,

                                                           unsigned vlen,

                                                           unsigned ch_left,

                                                           int vr_type)

{

    GetBitContext *gb = &vc->gb;

    unsigned c_p_c        = vc->codebooks[vr->classbook].dimensions;

    uint8_t *classifs = vr->classifs;

    unsigned pass, ch_used, i, j, k, l;

    unsigned max_output = (ch - 1) * vlen;

    int ptns_to_read = vr->ptns_to_read;

    int libvorbis_bug = 0;

    if (vr_type == 2) {

        for (j = 1; j < ch; ++j)

            do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input

        if (do_not_decode[0])

            return 0;

        ch_used = 1;

        max_output += vr->end / ch;

    } else {

        ch_used = ch;

        max_output += vr->end;

    }

    if (max_output > ch_left * vlen) {

        if (max_output <= ch_left * vlen + vr->partition_size*ch_used/ch) {

            ptns_to_read--;

            libvorbis_bug = 1;

        } else {

            av_log(vc->avctx, AV_LOG_ERROR, "Insufficient output buffer\n");

            return AVERROR_INVALIDDATA;

        }

    }

    av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);

    for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?

        int voffset, partition_count, j_times_ptns_to_read;

        voffset = vr->begin;

        for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error

            if (!pass) {

                int ret;

                if ((ret = setup_classifs(vc, vr, do_not_decode, ch_used, partition_count)) < 0)

                    return ret;

            }

            for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {

                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {

                    unsigned voffs;

                    if (!do_not_decode[j]) {

                        unsigned vqclass = classifs[j_times_ptns_to_read + partition_count];

                        int vqbook  = vr->books[vqclass][pass];

                        if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {

                            unsigned coffs;

                            unsigned dim  = vc->codebooks[vqbook].dimensions;

                            unsigned step = FASTDIV(vr->partition_size << 1, dim << 1);

                            vorbis_codebook codebook = vc->codebooks[vqbook];

                            if (vr_type == 0) {

                                voffs = voffset+j*vlen;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

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

                                        vec[voffs + k + l * step] += codebook.codevectors[coffs + l];

                                }

                            } else if (vr_type == 1) {

                                voffs = voffset + j * vlen;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l, ++voffs) {

                                        vec[voffs]+=codebook.codevectors[coffs+l];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d  \n",

                                                pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);

                                    }

                                }

                            } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized

                                voffs = voffset >> 1;

                                if (dim == 2) {

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

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;

                                        vec[voffs + k       ] += codebook.codevectors[coffs    ];

                                        vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];

                                    }

                                } else if (dim == 4) {

                                    for (k = 0; k < step; ++k, voffs += 2) {

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;

                                        vec[voffs           ] += codebook.codevectors[coffs    ];

                                        vec[voffs + 1       ] += codebook.codevectors[coffs + 2];

                                        vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];

                                        vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];

                                    }

                                } else

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; l += 2, voffs++) {

                                        vec[voffs       ] += codebook.codevectors[coffs + l    ];

                                        vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",

                                                pass, voffset / ch + (voffs % ch) * vlen,

                                                vec[voffset / ch + (voffs % ch) * vlen],

                                                codebook.codevectors[coffs + l], coffs, l);

                                    }

                                }

                            } else if (vr_type == 2) {

                                unsigned voffs_div = FASTDIV(voffset << 1, ch <<1);

                                unsigned voffs_mod = voffset - voffs_div * ch;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

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

                                        vec[voffs_div + voffs_mod * vlen] +=

                                            codebook.codevectors[coffs + l];

                                        av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n",

                                                pass, voffs_div + voffs_mod * vlen,

                                                vec[voffs_div + voffs_mod * vlen],

                                                codebook.codevectors[coffs + l], coffs, l);

                                        if (++voffs_mod == ch) {

                                            voffs_div++;

                                            voffs_mod = 0;

                                        }

                                    }

                                }

                            }

                        }

                    }

                    j_times_ptns_to_read += ptns_to_read;

                }

                ++partition_count;

                voffset += vr->partition_size;

            }

        }

        if (libvorbis_bug && !pass) {

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

                if (!do_not_decode[j]) {

                    get_vlc2(&vc->gb, vc->codebooks[vr->classbook].vlc.table,

                                vc->codebooks[vr->classbook].nb_bits, 3);

                }

            }

        }

    }

    return 0;

}


static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    ASFContext *asf = s->priv_data;

    GUID g;

    ByteIOContext *pb = &s->pb;

    AVStream *st;

    ASFStream *asf_st;

    int size, i, bps;

    INT64 gsize;

    get_guid(pb, &g);

    if (memcmp(&g, &asf_header, sizeof(GUID)))

        goto fail;

    get_le64(pb);

    get_le32(pb);

    get_byte(pb);

    get_byte(pb);

    memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));

    for(;;) {

        get_guid(pb, &g);

        gsize = get_le64(pb);

#ifdef DEBUG

        printf("%08Lx: ", url_ftell(pb) - 24);

        print_guid(&g);

        printf("  size=0x%Lx\n", gsize);

#endif

        if (gsize < 24)

            goto fail;

        if (!memcmp(&g, &file_header, sizeof(GUID))) {

            get_guid(pb, &asf->hdr.guid);

	    asf->hdr.file_size		= get_le64(pb);

	    asf->hdr.create_time	= get_le64(pb);

	    asf->hdr.packets_count	= get_le64(pb);

	    asf->hdr.play_time		= get_le64(pb);

	    asf->hdr.send_time		= get_le64(pb);

	    asf->hdr.preroll		= get_le32(pb);

	    asf->hdr.ignore		= get_le32(pb);

	    asf->hdr.flags		= get_le32(pb);

	    asf->hdr.min_pktsize	= get_le32(pb);

	    asf->hdr.max_pktsize	= get_le32(pb);

	    asf->hdr.max_bitrate	= get_le32(pb);

	    asf->packet_size = asf->hdr.max_pktsize;

            asf->nb_packets = asf->hdr.packets_count;

        } else if (!memcmp(&g, &stream_header, sizeof(GUID))) {

            int type, id, total_size;

            unsigned int tag1;

            INT64 pos1, pos2;

            pos1 = url_ftell(pb);

            st = av_mallocz(sizeof(AVStream));

            if (!st)

                goto fail;

            s->streams[s->nb_streams] = st;

            asf_st = av_mallocz(sizeof(ASFStream));

            if (!asf_st)

                goto fail;

            st->priv_data = asf_st;

	    st->time_length = (asf->hdr.send_time - asf->hdr.preroll) / 10000;

            get_guid(pb, &g);

            if (!memcmp(&g, &audio_stream, sizeof(GUID))) {

                type = CODEC_TYPE_AUDIO;

            } else if (!memcmp(&g, &video_stream, sizeof(GUID))) {

                type = CODEC_TYPE_VIDEO;

            } else {

                goto fail;

            }

            get_guid(pb, &g);

            total_size = get_le64(pb);

            get_le32(pb);

            get_le32(pb);

	    st->id = get_le16(pb) & 0x7f; /* stream id */

            // mapping of asf ID to AV stream ID;

            asf->asfid2avid[st->id] = s->nb_streams++;

            get_le32(pb);

	    st->codec.codec_type = type;

            st->codec.frame_rate = 1000; // in packet ticks

            if (type == CODEC_TYPE_AUDIO) {

                id = get_le16(pb);

                st->codec.codec_tag = id;

                st->codec.channels = get_le16(pb);

		st->codec.sample_rate = get_le32(pb);

                st->codec.bit_rate = get_le32(pb) * 8;

		st->codec.block_align = get_le16(pb); /* block align */

                bps = get_le16(pb); /* bits per sample */

                st->codec.codec_id = wav_codec_get_id(id, bps);

		size = get_le16(pb);

		if (size > 0) {

		    st->extra_data = av_mallocz(size);

		    get_buffer(pb, st->extra_data, size);

		    st->extra_data_size = size;

		}

		/* We have to init the frame size at some point .... */

		pos2 = url_ftell(pb);

		if (gsize > (pos2 + 8 - pos1 + 24)) {

		    asf_st->ds_span = get_byte(pb);

		    asf_st->ds_packet_size = get_le16(pb);

		    asf_st->ds_chunk_size = get_le16(pb);

		    asf_st->ds_data_size = get_le16(pb);

		    asf_st->ds_silence_data = get_byte(pb);

		}

		//printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",

		//       asf_st->ds_packet_size, asf_st->ds_chunk_size,

		//       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);

		if (asf_st->ds_span > 1) {

		    if (!asf_st->ds_chunk_size

			|| (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1))

			asf_st->ds_span = 0; // disable descrambling

		}

                switch (st->codec.codec_id) {

                case CODEC_ID_MP3LAME:

                    st->codec.frame_size = MPA_FRAME_SIZE;

                    break;

                case CODEC_ID_PCM_S16LE:

                case CODEC_ID_PCM_S16BE:

                case CODEC_ID_PCM_U16LE:

                case CODEC_ID_PCM_U16BE:

                case CODEC_ID_PCM_S8:

                case CODEC_ID_PCM_U8:

                case CODEC_ID_PCM_ALAW:

                case CODEC_ID_PCM_MULAW:

                    st->codec.frame_size = 1;

                    break;

                default:

                    /* This is probably wrong, but it prevents a crash later */

                    st->codec.frame_size = 1;

                    break;

                }

            } else {

		get_le32(pb);

                get_le32(pb);

                get_byte(pb);

                size = get_le16(pb); /* size */

                get_le32(pb); /* size */

                st->codec.width = get_le32(pb);

		st->codec.height = get_le32(pb);

                /* not available for asf */

                get_le16(pb); /* panes */

                get_le16(pb); /* depth */

                tag1 = get_le32(pb);

		url_fskip(pb, 20);

		if (size > 40) {

		    st->extra_data_size = size - 40;

		    st->extra_data = av_mallocz(st->extra_data_size);

		    get_buffer(pb, st->extra_data, st->extra_data_size);

		}

                st->codec.codec_tag = tag1;

		st->codec.codec_id = codec_get_id(codec_asf_bmp_tags, tag1);

            }

            pos2 = url_ftell(pb);

            url_fskip(pb, gsize - (pos2 - pos1 + 24));

        } else if (!memcmp(&g, &data_header, sizeof(GUID))) {

            break;

        } else if (!memcmp(&g, &comment_header, sizeof(GUID))) {

            int len1, len2, len3, len4, len5;

            len1 = get_le16(pb);

            len2 = get_le16(pb);

            len3 = get_le16(pb);

            len4 = get_le16(pb);

            len5 = get_le16(pb);

            get_str16_nolen(pb, len1, s->title, sizeof(s->title));

            get_str16_nolen(pb, len2, s->author, sizeof(s->author));

            get_str16_nolen(pb, len3, s->copyright, sizeof(s->copyright));

            get_str16_nolen(pb, len4, s->comment, sizeof(s->comment));

	    url_fskip(pb, len5);

#if 0

        } else if (!memcmp(&g, &head1_guid, sizeof(GUID))) {

            int v1, v2;

            get_guid(pb, &g);

            v1 = get_le32(pb);

            v2 = get_le16(pb);

        } else if (!memcmp(&g, &codec_comment_header, sizeof(GUID))) {

            int len, v1, n, num;

            char str[256], *q;

            char tag[16];

            get_guid(pb, &g);

            print_guid(&g);

            n = get_le32(pb);

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

                num = get_le16(pb); /* stream number */

                get_str16(pb, str, sizeof(str));

                get_str16(pb, str, sizeof(str));

                len = get_le16(pb);

                q = tag;

                while (len > 0) {

                    v1 = get_byte(pb);

                    if ((q - tag) < sizeof(tag) - 1)

                        *q++ = v1;

                    len--;

                }

                *q = '\0';

            }

#endif

        } else if (url_feof(pb)) {

            goto fail;

        } else {

            url_fseek(pb, gsize - 24, SEEK_CUR);

        }

    }

    get_guid(pb, &g);

    get_le64(pb);

    get_byte(pb);

    get_byte(pb);

    if (url_feof(pb))

        goto fail;

    asf->data_offset = url_ftell(pb);

    asf->packet_size_left = 0;

    return 0;

 fail:

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

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

	if (st) {

	    av_free(st->priv_data);

	    av_free(st->extra_data);

	}

        av_free(st);

    }

    //av_free(asf);

    return -1;

}


static void guess_mv(ERContext *s)

{

    uint8_t *fixed = s->er_temp_buffer;

#define MV_FROZEN    3

#define MV_CHANGED   2

#define MV_UNCHANGED 1

    const int mb_stride = s->mb_stride;

    const int mb_width  = s->mb_width;

    int mb_height = s->mb_height;

    int i, depth, num_avail;

    int mb_x, mb_y, mot_step, mot_stride;

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

        mb_height = FFMIN(mb_height, (s->last_pic.f->height+15)>>4);

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

        mb_height = FFMIN(mb_height, (s->next_pic.f->height+15)>>4);

    set_mv_strides(s, &mot_step, &mot_stride);

    num_avail = 0;

    if (s->last_pic.motion_val[0])

        ff_thread_await_progress(s->last_pic.tf, mb_height-1, 0);

    for (i = 0; i < mb_width * mb_height; i++) {

        const int mb_xy = s->mb_index2xy[i];

        int f = 0;

        int error = s->error_status_table[mb_xy];

        if (IS_INTRA(s->cur_pic.mb_type[mb_xy]))

            f = MV_FROZEN; // intra // FIXME check

        if (!(error & ER_MV_ERROR))

            f = MV_FROZEN; // inter with undamaged MV

        fixed[mb_xy] = f;

        if (f == MV_FROZEN)

            num_avail++;

        else if(s->last_pic.f->data[0] && s->last_pic.motion_val[0]){

            const int mb_y= mb_xy / s->mb_stride;

            const int mb_x= mb_xy % s->mb_stride;

            const int mot_index= (mb_x + mb_y*mot_stride) * mot_step;

            s->cur_pic.motion_val[0][mot_index][0]= s->last_pic.motion_val[0][mot_index][0];

            s->cur_pic.motion_val[0][mot_index][1]= s->last_pic.motion_val[0][mot_index][1];

            s->cur_pic.ref_index[0][4*mb_xy]      = s->last_pic.ref_index[0][4*mb_xy];

        }

    }

    if ((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) ||

        num_avail <= mb_width / 2) {

        for (mb_y = 0; mb_y < mb_height; mb_y++) {

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

                const int mb_xy = mb_x + mb_y * s->mb_stride;

                int mv_dir = (s->last_pic.f && s->last_pic.f->data[0]) ? MV_DIR_FORWARD : MV_DIR_BACKWARD;

                if (IS_INTRA(s->cur_pic.mb_type[mb_xy]))

                    continue;

                if (!(s->error_status_table[mb_xy] & ER_MV_ERROR))

                    continue;

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

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

                s->decode_mb(s->opaque, 0, mv_dir, MV_TYPE_16X16, &s->mv,

                             mb_x, mb_y, 0, 0);

            }

        }

        return;

    }

    for (depth = 0; ; depth++) {

        int changed, pass, none_left;

        none_left = 1;

        changed   = 1;

        for (pass = 0; (changed || pass < 2) && pass < 10; pass++) {

            int mb_x, mb_y;

            int score_sum = 0;

            changed = 0;

            for (mb_y = 0; mb_y < mb_height; mb_y++) {

                for (mb_x = (mb_y ^ pass) & 1; mb_x < s->mb_width; mb_x+=2) {

                    const int mb_xy        = mb_x + mb_y * s->mb_stride;

                    int mv_predictor[8][2] = { { 0 } };

                    int ref[8]             = { 0 };

                    int pred_count         = 0;

                    int j;

                    int best_score         = 256 * 256 * 256 * 64;

                    int best_pred          = 0;

                    const int mot_index    = (mb_x + mb_y * mot_stride) * mot_step;

                    int prev_x = 0, prev_y = 0, prev_ref = 0;

                    if (fixed[mb_xy] == MV_FROZEN)

                        continue;

                    av_assert1(!IS_INTRA(s->cur_pic.mb_type[mb_xy]));

                    av_assert1(s->last_pic.f && s->last_pic.f->data[0]);

                    j = 0;

                    if (mb_x > 0             && fixed[mb_xy - 1]         == MV_FROZEN)

                        j = 1;

                    if (mb_x + 1 < mb_width  && fixed[mb_xy + 1]         == MV_FROZEN)

                        j = 1;

                    if (mb_y > 0             && fixed[mb_xy - mb_stride] == MV_FROZEN)

                        j = 1;

                    if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] == MV_FROZEN)

                        j = 1;

                    if (j == 0)

                        continue;

                    j = 0;

                    if (mb_x > 0             && fixed[mb_xy - 1        ] == MV_CHANGED)

                        j = 1;

                    if (mb_x + 1 < mb_width  && fixed[mb_xy + 1        ] == MV_CHANGED)

                        j = 1;

                    if (mb_y > 0             && fixed[mb_xy - mb_stride] == MV_CHANGED)

                        j = 1;

                    if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] == MV_CHANGED)

                        j = 1;

                    if (j == 0 && pass > 1)

                        continue;

                    none_left = 0;

                    if (mb_x > 0 && fixed[mb_xy - 1]) {

                        mv_predictor[pred_count][0] =

                            s->cur_pic.motion_val[0][mot_index - mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->cur_pic.motion_val[0][mot_index - mot_step][1];

                        ref[pred_count] =

                            s->cur_pic.ref_index[0][4 * (mb_xy - 1)];

                        pred_count++;

                    }

                    if (mb_x + 1 < mb_width && fixed[mb_xy + 1]) {

                        mv_predictor[pred_count][0] =

                            s->cur_pic.motion_val[0][mot_index + mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->cur_pic.motion_val[0][mot_index + mot_step][1];

                        ref[pred_count] =

                            s->cur_pic.ref_index[0][4 * (mb_xy + 1)];

                        pred_count++;

                    }

                    if (mb_y > 0 && fixed[mb_xy - mb_stride]) {

                        mv_predictor[pred_count][0] =

                            s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][1];

                        ref[pred_count] =

                            s->cur_pic.ref_index[0][4 * (mb_xy - s->mb_stride)];

                        pred_count++;

                    }

                    if (mb_y + 1<mb_height && fixed[mb_xy + mb_stride]) {

                        mv_predictor[pred_count][0] =

                            s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][1];

                        ref[pred_count] =

                            s->cur_pic.ref_index[0][4 * (mb_xy + s->mb_stride)];

                        pred_count++;

                    }

                    if (pred_count == 0)

                        continue;

                    if (pred_count > 1) {

                        int sum_x = 0, sum_y = 0, sum_r = 0;

                        int max_x, max_y, min_x, min_y, max_r, min_r;

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

                            sum_x += mv_predictor[j][0];

                            sum_y += mv_predictor[j][1];

                            sum_r += ref[j];

                            if (j && ref[j] != ref[j - 1])

                                goto skip_mean_and_median;

                        }

                        /* mean */

                        mv_predictor[pred_count][0] = sum_x / j;

                        mv_predictor[pred_count][1] = sum_y / j;

                                 ref[pred_count]    = sum_r / j;

                        /* median */

                        if (pred_count >= 3) {

                            min_y = min_x = min_r =  99999;

                            max_y = max_x = max_r = -99999;

                        } else {

                            min_x = min_y = max_x = max_y = min_r = max_r = 0;

                        }

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

                            max_x = FFMAX(max_x, mv_predictor[j][0]);

                            max_y = FFMAX(max_y, mv_predictor[j][1]);

                            max_r = FFMAX(max_r, ref[j]);

                            min_x = FFMIN(min_x, mv_predictor[j][0]);

                            min_y = FFMIN(min_y, mv_predictor[j][1]);

                            min_r = FFMIN(min_r, ref[j]);

                        }

                        mv_predictor[pred_count + 1][0] = sum_x - max_x - min_x;

                        mv_predictor[pred_count + 1][1] = sum_y - max_y - min_y;

                                 ref[pred_count + 1]    = sum_r - max_r - min_r;

                        if (pred_count == 4) {

                            mv_predictor[pred_count + 1][0] /= 2;

                            mv_predictor[pred_count + 1][1] /= 2;

                                     ref[pred_count + 1]    /= 2;

                        }

                        pred_count += 2;

                    }

skip_mean_and_median:

                    /* zero MV */

                    pred_count++;

                    prev_x   = s->cur_pic.motion_val[0][mot_index][0];

                    prev_y   = s->cur_pic.motion_val[0][mot_index][1];

                    prev_ref = s->cur_pic.ref_index[0][4 * mb_xy];

                    /* last MV */

                    mv_predictor[pred_count][0] = prev_x;

                    mv_predictor[pred_count][1] = prev_y;

                             ref[pred_count]    = prev_ref;

                    pred_count++;

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

                        int *linesize = s->cur_pic.f->linesize;

                        int score = 0;

                        uint8_t *src = s->cur_pic.f->data[0] +

                                       mb_x * 16 + mb_y * 16 * linesize[0];

                        s->cur_pic.motion_val[0][mot_index][0] =

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

                        s->cur_pic.motion_val[0][mot_index][1] =

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

                        // predictor intra or otherwise not available

                        if (ref[j] < 0)

                            continue;

                        s->decode_mb(s->opaque, ref[j], MV_DIR_FORWARD,

                                     MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0);

                        if (mb_x > 0 && fixed[mb_xy - 1]) {

                            int k;

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

                                score += FFABS(src[k * linesize[0] - 1] -

                                               src[k * linesize[0]]);

                        }

                        if (mb_x + 1 < mb_width && fixed[mb_xy + 1]) {

                            int k;

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

                                score += FFABS(src[k * linesize[0] + 15] -

                                               src[k * linesize[0] + 16]);

                        }

                        if (mb_y > 0 && fixed[mb_xy - mb_stride]) {

                            int k;

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

                                score += FFABS(src[k - linesize[0]] - src[k]);

                        }

                        if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride]) {

                            int k;

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

                                score += FFABS(src[k + linesize[0] * 15] -

                                               src[k + linesize[0] * 16]);

                        }

                        if (score <= best_score) { // <= will favor the last MV

                            best_score = score;

                            best_pred  = j;

                        }

                    }

                    score_sum += best_score;

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

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

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

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

                            s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][0] = s->mv[0][0][0];

                            s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][1] = s->mv[0][0][1];

                        }

                    s->decode_mb(s->opaque, ref[best_pred], MV_DIR_FORWARD,

                                 MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0);

                    if (s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y) {

                        fixed[mb_xy] = MV_CHANGED;

                        changed++;

                    } else

                        fixed[mb_xy] = MV_UNCHANGED;

                }

            }

        }

        if (none_left)

            return;

        for (i = 0; i < mb_width * mb_height; i++) {

            int mb_xy = s->mb_index2xy[i];

            if (fixed[mb_xy])

                fixed[mb_xy] = MV_FROZEN;

        }

    }

}


static inline void gen_neon_narrow(int size, TCGv dest, TCGv src)

{

    switch (size) {

    case 0: gen_helper_neon_narrow_u8(dest, src); break;

    case 1: gen_helper_neon_narrow_u16(dest, src); break;

    case 2: tcg_gen_trunc_i64_i32(dest, src); break;

    default: abort();

    }

}


int spapr_populate_pci_dt(sPAPRPHBState *phb,

                          uint32_t xics_phandle,

                          void *fdt)

{

    int bus_off, i, j, ret;

    char nodename[FDT_NAME_MAX];

    uint32_t bus_range[] = { cpu_to_be32(0), cpu_to_be32(0xff) };

    const uint64_t mmiosize = memory_region_size(&phb->memwindow);

    const uint64_t w32max = (1ULL << 32) - SPAPR_PCI_MEM_WIN_BUS_OFFSET;

    const uint64_t w32size = MIN(w32max, mmiosize);

    const uint64_t w64size = (mmiosize > w32size) ? (mmiosize - w32size) : 0;

    struct {

        uint32_t hi;

        uint64_t child;

        uint64_t parent;

        uint64_t size;

    } QEMU_PACKED ranges[] = {

        {

            cpu_to_be32(b_ss(1)), cpu_to_be64(0),

            cpu_to_be64(phb->io_win_addr),

            cpu_to_be64(memory_region_size(&phb->iospace)),

        },

        {

            cpu_to_be32(b_ss(2)), cpu_to_be64(SPAPR_PCI_MEM_WIN_BUS_OFFSET),

            cpu_to_be64(phb->mem_win_addr),

            cpu_to_be64(w32size),

        },

        {

            cpu_to_be32(b_ss(3)), cpu_to_be64(1ULL << 32),

            cpu_to_be64(phb->mem_win_addr + w32size),

            cpu_to_be64(w64size)

        },

    };

    const unsigned sizeof_ranges = (w64size ? 3 : 2) * sizeof(ranges[0]);

    uint64_t bus_reg[] = { cpu_to_be64(phb->buid), 0 };

    uint32_t interrupt_map_mask[] = {

        cpu_to_be32(b_ddddd(-1)|b_fff(0)), 0x0, 0x0, cpu_to_be32(-1)};

    uint32_t interrupt_map[PCI_SLOT_MAX * PCI_NUM_PINS][7];

    uint32_t ddw_applicable[] = {

        cpu_to_be32(RTAS_IBM_QUERY_PE_DMA_WINDOW),

        cpu_to_be32(RTAS_IBM_CREATE_PE_DMA_WINDOW),

        cpu_to_be32(RTAS_IBM_REMOVE_PE_DMA_WINDOW)

    };

    uint32_t ddw_extensions[] = {

        cpu_to_be32(1),

        cpu_to_be32(RTAS_IBM_RESET_PE_DMA_WINDOW)

    };

    uint32_t associativity[] = {cpu_to_be32(0x4),

                                cpu_to_be32(0x0),

                                cpu_to_be32(0x0),

                                cpu_to_be32(0x0),

                                cpu_to_be32(phb->numa_node)};

    sPAPRTCETable *tcet;

    PCIBus *bus = PCI_HOST_BRIDGE(phb)->bus;

    sPAPRFDT s_fdt;

    /* Start populating the FDT */

    snprintf(nodename, FDT_NAME_MAX, "pci@%" PRIx64, phb->buid);

    bus_off = fdt_add_subnode(fdt, 0, nodename);

    if (bus_off < 0) {

        return bus_off;

    }

    /* Write PHB properties */

    _FDT(fdt_setprop_string(fdt, bus_off, "device_type", "pci"));

    _FDT(fdt_setprop_string(fdt, bus_off, "compatible", "IBM,Logical_PHB"));

    _FDT(fdt_setprop_cell(fdt, bus_off, "#address-cells", 0x3));

    _FDT(fdt_setprop_cell(fdt, bus_off, "#size-cells", 0x2));

    _FDT(fdt_setprop_cell(fdt, bus_off, "#interrupt-cells", 0x1));

    _FDT(fdt_setprop(fdt, bus_off, "used-by-rtas", NULL, 0));

    _FDT(fdt_setprop(fdt, bus_off, "bus-range", &bus_range, sizeof(bus_range)));

    _FDT(fdt_setprop(fdt, bus_off, "ranges", &ranges, sizeof_ranges));

    _FDT(fdt_setprop(fdt, bus_off, "reg", &bus_reg, sizeof(bus_reg)));

    _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pci-config-space-type", 0x1));

    _FDT(fdt_setprop_cell(fdt, bus_off, "ibm,pe-total-#msi", XICS_IRQS_SPAPR));

    /* Dynamic DMA window */

    if (phb->ddw_enabled) {

        _FDT(fdt_setprop(fdt, bus_off, "ibm,ddw-applicable", &ddw_applicable,

                         sizeof(ddw_applicable)));

        _FDT(fdt_setprop(fdt, bus_off, "ibm,ddw-extensions",

                         &ddw_extensions, sizeof(ddw_extensions)));

    }

    /* Advertise NUMA via ibm,associativity */

    if (nb_numa_nodes > 1) {

        _FDT(fdt_setprop(fdt, bus_off, "ibm,associativity", associativity,

                         sizeof(associativity)));

    }

    /* Build the interrupt-map, this must matches what is done

     * in pci_spapr_map_irq

     */

    _FDT(fdt_setprop(fdt, bus_off, "interrupt-map-mask",

                     &interrupt_map_mask, sizeof(interrupt_map_mask)));

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

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

            uint32_t *irqmap = interrupt_map[i*PCI_NUM_PINS + j];

            int lsi_num = pci_spapr_swizzle(i, j);

            irqmap[0] = cpu_to_be32(b_ddddd(i)|b_fff(0));

            irqmap[1] = 0;

            irqmap[2] = 0;

            irqmap[3] = cpu_to_be32(j+1);

            irqmap[4] = cpu_to_be32(xics_phandle);

            irqmap[5] = cpu_to_be32(phb->lsi_table[lsi_num].irq);

            irqmap[6] = cpu_to_be32(0x8);

        }

    }

    /* Write interrupt map */

    _FDT(fdt_setprop(fdt, bus_off, "interrupt-map", &interrupt_map,

                     sizeof(interrupt_map)));

    tcet = spapr_tce_find_by_liobn(phb->dma_liobn[0]);

    if (!tcet) {

        return -1;

    }

    spapr_dma_dt(fdt, bus_off, "ibm,dma-window",

                 tcet->liobn, tcet->bus_offset,

                 tcet->nb_table << tcet->page_shift);

    /* Walk the bridges and program the bus numbers*/

    spapr_phb_pci_enumerate(phb);

    _FDT(fdt_setprop_cell(fdt, bus_off, "qemu,phb-enumerated", 0x1));

    /* Populate tree nodes with PCI devices attached */

    s_fdt.fdt = fdt;

    s_fdt.node_off = bus_off;

    s_fdt.sphb = phb;

    pci_for_each_device(bus, pci_bus_num(bus),

                        spapr_populate_pci_devices_dt,

                        &s_fdt);

    ret = spapr_drc_populate_dt(fdt, bus_off, OBJECT(phb),

                                SPAPR_DR_CONNECTOR_TYPE_PCI);

    if (ret) {

        return ret;

    }

    return 0;

}


void spapr_dt_events(void *fdt, uint32_t check_exception_irq)

{

    int event_sources, epow_events;

    uint32_t irq_ranges[] = {cpu_to_be32(check_exception_irq), cpu_to_be32(1)};

    uint32_t interrupts[] = {cpu_to_be32(check_exception_irq), 0};

    _FDT(event_sources = fdt_add_subnode(fdt, 0, "event-sources"));

    _FDT(fdt_setprop(fdt, event_sources, "interrupt-controller", NULL, 0));

    _FDT(fdt_setprop_cell(fdt, event_sources, "#interrupt-cells", 2));

    _FDT(fdt_setprop(fdt, event_sources, "interrupt-ranges",

                     irq_ranges, sizeof(irq_ranges)));

    _FDT(epow_events = fdt_add_subnode(fdt, event_sources, "epow-events"));

    _FDT(fdt_setprop(fdt, epow_events, "interrupts",

                     interrupts, sizeof(interrupts)));

}


static void ff_dlog_link(void *ctx, AVFilterLink *link, int end)

{

    if (link->type == AVMEDIA_TYPE_VIDEO) {

        av_dlog(ctx,

                "link[%p s:%dx%d fmt:%-16s %-16s->%-16s]%s",

                link, link->w, link->h,

                av_pix_fmt_descriptors[link->format].name,

                link->src ? link->src->filter->name : "",

                link->dst ? link->dst->filter->name : "",

                end ? "\n" : "");

    } else {

        char buf[128];

        av_get_channel_layout_string(buf, sizeof(buf), -1, link->channel_layout);

        av_dlog(ctx,

                "link[%p r:%"PRId64" cl:%s fmt:%-16s %-16s->%-16s]%s",

                link, link->sample_rate, buf,

                av_get_sample_fmt_name(link->format),

                link->src ? link->src->filter->name : "",

                link->dst ? link->dst->filter->name : "",

                end ? "\n" : "");

    }

}


static int vmdk_write(BlockDriverState *bs, int64_t sector_num,

                      const uint8_t *buf, int nb_sectors,

                      bool zeroed, bool zero_dry_run)

{

    BDRVVmdkState *s = bs->opaque;

    VmdkExtent *extent = NULL;

    int n, ret;

    int64_t index_in_cluster;

    uint64_t extent_begin_sector, extent_relative_sector_num;

    uint64_t cluster_offset;

    VmdkMetaData m_data;

    if (sector_num > bs->total_sectors) {

        error_report("Wrong offset: sector_num=0x%" PRIx64

                " total_sectors=0x%" PRIx64 "\n",

                sector_num, bs->total_sectors);

        return -EIO;

    }

    while (nb_sectors > 0) {

        extent = find_extent(s, sector_num, extent);

        if (!extent) {

            return -EIO;

        }

        ret = get_cluster_offset(

                                bs,

                                extent,

                                &m_data,

                                sector_num << 9, !extent->compressed,

                                &cluster_offset);

        if (extent->compressed) {

            if (ret == VMDK_OK) {

                /* Refuse write to allocated cluster for streamOptimized */

                error_report("Could not write to allocated cluster"

                              " for streamOptimized");

                return -EIO;

            } else {

                /* allocate */

                ret = get_cluster_offset(

                                        bs,

                                        extent,

                                        &m_data,

                                        sector_num << 9, 1,

                                        &cluster_offset);

            }

        }

        if (ret == VMDK_ERROR) {

            return -EINVAL;

        }

        extent_begin_sector = extent->end_sector - extent->sectors;

        extent_relative_sector_num = sector_num - extent_begin_sector;

        index_in_cluster = extent_relative_sector_num % extent->cluster_sectors;

        n = extent->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        if (zeroed) {

            /* Do zeroed write, buf is ignored */

            if (extent->has_zero_grain &&

                    index_in_cluster == 0 &&

                    n >= extent->cluster_sectors) {

                n = extent->cluster_sectors;

                if (!zero_dry_run) {

                    m_data.offset = VMDK_GTE_ZEROED;

                    /* update L2 tables */

                    if (vmdk_L2update(extent, &m_data) != VMDK_OK) {

                        return -EIO;

                    }

                }

            } else {

                return -ENOTSUP;

            }

        } else {

            ret = vmdk_write_extent(extent,

                            cluster_offset, index_in_cluster * 512,

                            buf, n, sector_num);

            if (ret) {

                return ret;

            }

            if (m_data.valid) {

                /* update L2 tables */

                if (vmdk_L2update(extent, &m_data) != VMDK_OK) {

                    return -EIO;

                }

            }

        }

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

        /* update CID on the first write every time the virtual disk is

         * opened */

        if (!s->cid_updated) {

            ret = vmdk_write_cid(bs, time(NULL));

            if (ret < 0) {

                return ret;

            }

            s->cid_updated = true;

        }

    }

    return 0;

}


void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,

                                  Error **errp)

{

    MigrationState *s = migrate_get_current();

    MigrationCapabilityStatusList *cap;

    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {

        error_set(errp, QERR_MIGRATION_ACTIVE);

        return;

    }

    for (cap = params; cap; cap = cap->next) {

        s->enabled_capabilities[cap->value->capability] = cap->value->state;

    }

}


void qmp_qmp_capabilities(Error **errp)

{

    cur_mon->qmp.in_command_mode = true;

}


static int http_connect(URLContext *h, const char *path, const char *hoststr,

                        const char *auth, int *new_location)

{

    HTTPContext *s = h->priv_data;

    int post, err;

    char line[1024];

    char headers[1024] = "";

    char *authstr = NULL;

    int64_t off = s->off;

    int len = 0;

    /* send http header */

    post = h->flags & URL_WRONLY;

    authstr = ff_http_auth_create_response(&s->auth_state, auth, path,

                                        post ? "POST" : "GET");

    /* set default headers if needed */

    if (!has_header(s->headers, "\r\nUser-Agent: "))

       len += av_strlcatf(headers + len, sizeof(headers) - len,

                          "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);

    if (!has_header(s->headers, "\r\nAccept: "))

        len += av_strlcpy(headers + len, "Accept: */*\r\n",

                          sizeof(headers) - len);

    if (!has_header(s->headers, "\r\nRange: "))

        len += av_strlcatf(headers + len, sizeof(headers) - len,

                           "Range: bytes=%"PRId64"-\r\n", s->off);

    if (!has_header(s->headers, "\r\nConnection: "))

        len += av_strlcpy(headers + len, "Connection: close\r\n",

                          sizeof(headers)-len);

    if (!has_header(s->headers, "\r\nHost: "))

        len += av_strlcatf(headers + len, sizeof(headers) - len,

                           "Host: %s\r\n", hoststr);

    /* now add in custom headers */

    av_strlcpy(headers+len, s->headers, sizeof(headers)-len);

    snprintf(s->buffer, sizeof(s->buffer),

             "%s %s HTTP/1.1\r\n"

             "%s"

             "%s"

             "%s"

             "\r\n",

             post ? "POST" : "GET",

             path,

             post && s->is_chunked ? "Transfer-Encoding: chunked\r\n" : "",

             headers,

             authstr ? authstr : "");

    av_freep(&authstr);

    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)

        return AVERROR(EIO);

    /* init input buffer */

    s->buf_ptr = s->buffer;

    s->buf_end = s->buffer;

    s->line_count = 0;

    s->off = 0;

    s->filesize = -1;

    if (post) {

        /* always use chunked encoding for upload data */

        s->chunksize = 0;

        /* Pretend that it did work. We didn't read any header yet, since

         * we've still to send the POST data, but the code calling this

         * function will check http_code after we return. */

        s->http_code = 200;

        return 0;

    }

    /* wait for header */

    for(;;) {

        if (http_get_line(s, line, sizeof(line)) < 0)

            return AVERROR(EIO);

        dprintf(NULL, "header='%s'\n", line);

        err = process_line(h, line, s->line_count, new_location);

        if (err < 0)

            return err;

        if (err == 0)

            break;

        s->line_count++;

    }

    return (off == s->off) ? 0 : -1;

}


static int dxtory_decode_v2_rgb(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    GetByteContext gb;

    GetBitContext  gb2;

    int nslices, slice, slice_height;

    uint32_t off, slice_size;

    uint8_t *dst;

    int ret;

    bytestream2_init(&gb, src, src_size);

    nslices = bytestream2_get_le16(&gb);

    off = FFALIGN(nslices * 4 + 2, 16);

    if (src_size < off) {

        av_log(avctx, AV_LOG_ERROR, "no slice data\n");

        return AVERROR_INVALIDDATA;

    }

    if (!nslices || avctx->height % nslices) {

        avpriv_request_sample(avctx, "%d slices for %dx%d", nslices,

                              avctx->width, avctx->height);

        return AVERROR_PATCHWELCOME;

    }

    slice_height = avctx->height / nslices;

    avctx->pix_fmt = AV_PIX_FMT_BGR24;

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    dst = pic->data[0];

    for (slice = 0; slice < nslices; slice++) {

        slice_size = bytestream2_get_le32(&gb);

        if (slice_size > src_size - off) {

            av_log(avctx, AV_LOG_ERROR,

                   "invalid slice size %"PRIu32" (only %"PRIu32" bytes left)\n",

                   slice_size, src_size - off);

            return AVERROR_INVALIDDATA;

        }

        if (slice_size <= 16) {

            av_log(avctx, AV_LOG_ERROR, "invalid slice size %"PRIu32"\n",

                   slice_size);

            return AVERROR_INVALIDDATA;

        }

        if (AV_RL32(src + off) != slice_size - 16) {

            av_log(avctx, AV_LOG_ERROR,

                   "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",

                   AV_RL32(src + off), slice_size - 16);

        }

        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);

        dx2_decode_slice_rgb(&gb2, avctx->width, slice_height, dst,

                             pic->linesize[0]);

        dst += pic->linesize[0] * slice_height;

        off += slice_size;

    }

    return 0;

}


void dsputil_init_mlib(void)

{

    put_pixels_tab[0][0] = put_pixels16_mlib;

    put_pixels_tab[0][1] = put_pixels16_x2_mlib;

    put_pixels_tab[0][2] = put_pixels16_y2_mlib;

    put_pixels_tab[0][3] = put_pixels16_xy2_mlib;

    put_pixels_tab[1][0] = put_pixels8_mlib;

    put_pixels_tab[1][1] = put_pixels8_x2_mlib;

    put_pixels_tab[1][2] = put_pixels8_y2_mlib;

    put_pixels_tab[1][3] = put_pixels8_xy2_mlib;

    avg_pixels_tab[0][0] = avg_pixels16_mlib;

    avg_pixels_tab[0][1] = avg_pixels16_x2_mlib;

    avg_pixels_tab[0][2] = avg_pixels16_y2_mlib;

    avg_pixels_tab[0][3] = avg_pixels16_xy2_mlib;

    avg_pixels_tab[1][0] = avg_pixels8_mlib;

    avg_pixels_tab[1][1] = avg_pixels8_x2_mlib;

    avg_pixels_tab[1][2] = avg_pixels8_y2_mlib;

    avg_pixels_tab[1][3] = avg_pixels8_xy2_mlib;

    put_no_rnd_pixels_tab[0][0] = put_pixels16_mlib;

    put_no_rnd_pixels_tab[1][0] = put_pixels8_mlib;

    add_pixels_clamped = add_pixels_clamped_mlib;

}


static inline int handle_cpu_signal(uintptr_t pc, unsigned long address,

                                    int is_write, sigset_t *old_set)

{

    CPUState *cpu = current_cpu;

    CPUClass *cc;

    int ret;

    /* We must handle PC addresses from two different sources:

     * a call return address and a signal frame address.

     *

     * Within cpu_restore_state_from_tb we assume the former and adjust

     * the address by -GETPC_ADJ so that the address is within the call

     * insn so that addr does not accidentally match the beginning of the

     * next guest insn.

     *

     * However, when the PC comes from the signal frame, it points to

     * the actual faulting host insn and not a call insn.  Subtracting

     * GETPC_ADJ in that case may accidentally match the previous guest insn.

     *

     * So for the later case, adjust forward to compensate for what

     * will be done later by cpu_restore_state_from_tb.

     */

    if (helper_retaddr) {

        pc = helper_retaddr;

    } else {

        pc += GETPC_ADJ;

    }

    /* For synchronous signals we expect to be coming from the vCPU

     * thread (so current_cpu should be valid) and either from running

     * code or during translation which can fault as we cross pages.

     *

     * If neither is true then something has gone wrong and we should

     * abort rather than try and restart the vCPU execution.

     */

    if (!cpu || !cpu->running) {

        printf("qemu:%s received signal outside vCPU context @ pc=0x%"

               PRIxPTR "\n",  __func__, pc);

        abort();

    }

#if defined(DEBUG_SIGNAL)

    printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n",

           pc, address, is_write, *(unsigned long *)old_set);

#endif

    /* XXX: locking issue */

    if (is_write && h2g_valid(address)) {

        switch (page_unprotect(h2g(address), pc)) {

        case 0:

            /* Fault not caused by a page marked unwritable to protect

             * cached translations, must be the guest binary's problem.

             */

            break;

        case 1:

            /* Fault caused by protection of cached translation; TBs

             * invalidated, so resume execution.  Retain helper_retaddr

             * for a possible second fault.

             */

            return 1;

        case 2:

            /* Fault caused by protection of cached translation, and the

             * currently executing TB was modified and must be exited

             * immediately.  Clear helper_retaddr for next execution.

             */

            helper_retaddr = 0;

            cpu_exit_tb_from_sighandler(cpu, old_set);

            /* NORETURN */

        default:

            g_assert_not_reached();

        }

    }

    /* Convert forcefully to guest address space, invalid addresses

       are still valid segv ones */

    address = h2g_nocheck(address);

    cc = CPU_GET_CLASS(cpu);

    /* see if it is an MMU fault */

    g_assert(cc->handle_mmu_fault);

    ret = cc->handle_mmu_fault(cpu, address, is_write, MMU_USER_IDX);

    if (ret == 0) {

        /* The MMU fault was handled without causing real CPU fault.

         *  Retain helper_retaddr for a possible second fault.

         */

        return 1;

    }

    /* All other paths lead to cpu_exit; clear helper_retaddr

     * for next execution.

     */

    helper_retaddr = 0;

    if (ret < 0) {

        return 0; /* not an MMU fault */

    }

    /* Now we have a real cpu fault.  */

    cpu_restore_state(cpu, pc);

    sigprocmask(SIG_SETMASK, old_set, NULL);

    cpu_loop_exit(cpu);

    /* never comes here */

    return 1;

}


static inline bool media_is_cd(SCSIDiskState *s)

{

    uint64_t nb_sectors;

    if (s->qdev.type != TYPE_ROM) {

        return false;

    }

    if (!bdrv_is_inserted(s->qdev.conf.bs)) {

        return false;

    }

    bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

    return nb_sectors <= CD_MAX_SECTORS;

}


static void lm32_uclinux_init(QEMUMachineInitArgs *args)
{
    const char *cpu_model = args->cpu_model;
    const char *kernel_filename = args->kernel_filename;
    const char *kernel_cmdline = args->kernel_cmdline;
    const char *initrd_filename = args->initrd_filename;
    LM32CPU *cpu;
    CPULM32State *env;
    DriveInfo *dinfo;
    MemoryRegion *address_space_mem =  get_system_memory();
    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);
    qemu_irq *cpu_irq, irq[32];
    HWSetup *hw;
    ResetInfo *reset_info;
    int i;
    /* memory map */
    hwaddr flash_base   = 0x04000000;
    size_t flash_sector_size        = 256 * 1024;
    size_t flash_size               = 32 * 1024 * 1024;
    hwaddr ram_base     = 0x08000000;
    size_t ram_size                 = 64 * 1024 * 1024;
    hwaddr uart0_base   = 0x80000000;
    hwaddr timer0_base  = 0x80002000;
    hwaddr timer1_base  = 0x80010000;
    hwaddr timer2_base  = 0x80012000;
    int uart0_irq                   = 0;
    int timer0_irq                  = 1;
    int timer1_irq                  = 20;
    int timer2_irq                  = 21;
    hwaddr hwsetup_base = 0x0bffe000;
    hwaddr cmdline_base = 0x0bfff000;
    hwaddr initrd_base  = 0x08400000;
    size_t initrd_max               = 0x01000000;
    reset_info = g_malloc0(sizeof(ResetInfo));
    if (cpu_model == NULL) {
        cpu_model = "lm32-full";
    cpu = cpu_lm32_init(cpu_model);
    env = &cpu->env;
    reset_info->cpu = cpu;
    reset_info->flash_base = flash_base;
    memory_region_init_ram(phys_ram, NULL, "lm32_uclinux.sdram", ram_size);
    vmstate_register_ram_global(phys_ram);
    memory_region_add_subregion(address_space_mem, ram_base, phys_ram);
    dinfo = drive_get(IF_PFLASH, 0, 0);
    /* Spansion S29NS128P */
    pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size,
                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
                          flash_size / flash_sector_size, 1, 2,
                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
    /* create irq lines */
    cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);
    env->pic_state = lm32_pic_init(*cpu_irq);
    for (i = 0; i < 32; i++) {
        irq[i] = qdev_get_gpio_in(env->pic_state, i);
    sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);
    sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);
    sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);
    sysbus_create_simple("lm32-timer", timer2_base, irq[timer2_irq]);
    /* make sure juart isn't the first chardev */
    env->juart_state = lm32_juart_init();
    reset_info->bootstrap_pc = flash_base;
    if (kernel_filename) {
        uint64_t entry;
        int kernel_size;
        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,
                               1, ELF_MACHINE, 0);
        reset_info->bootstrap_pc = entry;
        if (kernel_size < 0) {
            kernel_size = load_image_targphys(kernel_filename, ram_base,
                                              ram_size);
            reset_info->bootstrap_pc = ram_base;
        if (kernel_size < 0) {
            fprintf(stderr, "qemu: could not load kernel '%s'\n",
                    kernel_filename);
    /* generate a rom with the hardware description */
    hw = hwsetup_init();
    hwsetup_add_cpu(hw, "LM32", 75000000);
    hwsetup_add_flash(hw, "flash", flash_base, flash_size);
    hwsetup_add_ddr_sdram(hw, "ddr_sdram", ram_base, ram_size);
    hwsetup_add_timer(hw, "timer0", timer0_base, timer0_irq);
    hwsetup_add_timer(hw, "timer1_dev_only", timer1_base, timer1_irq);
    hwsetup_add_timer(hw, "timer2_dev_only", timer2_base, timer2_irq);
    hwsetup_add_uart(hw, "uart", uart0_base, uart0_irq);
    hwsetup_add_trailer(hw);
    hwsetup_create_rom(hw, hwsetup_base);
    hwsetup_free(hw);
    reset_info->hwsetup_base = hwsetup_base;
    if (kernel_cmdline && strlen(kernel_cmdline)) {
        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE,
                kernel_cmdline);
        reset_info->cmdline_base = cmdline_base;
    if (initrd_filename) {
        size_t initrd_size;
        initrd_size = load_image_targphys(initrd_filename, initrd_base,
                initrd_max);
        reset_info->initrd_base = initrd_base;
        reset_info->initrd_size = initrd_size;
    qemu_register_reset(main_cpu_reset, reset_info);


static av_cold int m101_decode_init(AVCodecContext *avctx)

{

    if (avctx->extradata_size < 6*4)

        return AVERROR_INVALIDDATA;

    if (avctx->extradata[2*4] == 10)

        avctx->pix_fmt = AV_PIX_FMT_YUV422P10;

    else

        avctx->pix_fmt = AV_PIX_FMT_YUYV422;

    return 0;

}


static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])

{

    Mpeg4DecContext *ctx = (Mpeg4DecContext *)s;

    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;

    int16_t *mot_val;

    static const int8_t quant_tab[4] = { -1, -2, 1, 2 };

    const int xy = s->mb_x + s->mb_y * s->mb_stride;

    av_assert2(s->h263_pred);

    if (s->pict_type == AV_PICTURE_TYPE_P ||

        s->pict_type == AV_PICTURE_TYPE_S) {

        do {

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

                /* skip mb */

                s->mb_intra = 0;

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

                    s->block_last_index[i] = -1;

                s->mv_dir  = MV_DIR_FORWARD;

                s->mv_type = MV_TYPE_16X16;

                if (s->pict_type == AV_PICTURE_TYPE_S &&

                    ctx->vol_sprite_usage == GMC_SPRITE) {

                    s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |

                                                     MB_TYPE_GMC   |

                                                     MB_TYPE_16x16 |

                                                     MB_TYPE_L0;

                    s->mcsel       = 1;

                    s->mv[0][0][0] = get_amv(ctx, 0);

                    s->mv[0][0][1] = get_amv(ctx, 1);

                    s->mb_skipped  = 0;

                } else {

                    s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |

                                                     MB_TYPE_16x16 |

                                                     MB_TYPE_L0;

                    s->mcsel       = 0;

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

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

                    s->mb_skipped  = 1;

                goto end;

            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);

            if (cbpc < 0) {

                       "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

        } while (cbpc == 20);

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

        dquant      = cbpc & 8;

        s->mb_intra = ((cbpc & 4) != 0);

        if (s->mb_intra)

            goto intra;

        if (s->pict_type == AV_PICTURE_TYPE_S &&

            ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)

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

        else

            s->mcsel = 0;

        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;

        cbp = (cbpc & 3) | (cbpy << 2);

        if (dquant)

            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);

        if ((!s->progressive_sequence) &&

            (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))

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

        s->mv_dir = MV_DIR_FORWARD;

        if ((cbpc & 16) == 0) {

            if (s->mcsel) {

                s->current_picture.mb_type[xy] = MB_TYPE_GMC   |

                                                 MB_TYPE_16x16 |

                                                 MB_TYPE_L0;

                /* 16x16 global motion prediction */

                s->mv_type     = MV_TYPE_16X16;

                mx             = get_amv(ctx, 0);

                my             = get_amv(ctx, 1);

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

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

            } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {

                s->current_picture.mb_type[xy] = MB_TYPE_16x8 |

                                                 MB_TYPE_L0   |

                                                 MB_TYPE_INTERLACED;

                /* 16x8 field motion prediction */

                s->mv_type = MV_TYPE_FIELD;

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

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

                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);

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

                    mx = ff_h263_decode_motion(s, pred_x, s->f_code);

                    if (mx >= 0xffff)

                        return -1;

                    my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);

                    if (my >= 0xffff)

                        return -1;

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

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

            } else {

                s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;

                /* 16x16 motion prediction */

                s->mv_type = MV_TYPE_16X16;

                ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);

                mx = ff_h263_decode_motion(s, pred_x, s->f_code);

                if (mx >= 0xffff)

                    return -1;

                my = ff_h263_decode_motion(s, pred_y, s->f_code);

                if (my >= 0xffff)

                    return -1;

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

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

        } else {

            s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;

            s->mv_type                     = MV_TYPE_8X8;

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

                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);

                mx      = ff_h263_decode_motion(s, pred_x, s->f_code);

                if (mx >= 0xffff)

                    return -1;

                my = ff_h263_decode_motion(s, pred_y, s->f_code);

                if (my >= 0xffff)

                    return -1;

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

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

                mot_val[0]     = mx;

                mot_val[1]     = my;

    } else if (s->pict_type == AV_PICTURE_TYPE_B) {

        int modb1;   // first bit of modb

        int modb2;   // second bit of modb

        int mb_type;

        s->mb_intra = 0;  // B-frames never contain intra blocks

        s->mcsel    = 0;  //      ...               true gmc blocks

        if (s->mb_x == 0) {

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

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

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

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

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

            ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);

        /* if we skipped it in the future P Frame than skip it now too */

        s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x];  // Note, skiptab=0 if last was GMC

        if (s->mb_skipped) {

            /* skip mb */

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

                s->block_last_index[i] = -1;

            s->mv_dir      = MV_DIR_FORWARD;

            s->mv_type     = MV_TYPE_16X16;

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

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

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

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

            s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |

                                             MB_TYPE_16x16 |

                                             MB_TYPE_L0;

            goto end;

        modb1 = get_bits1(&s->gb);

        if (modb1) {

            // like MB_TYPE_B_DIRECT but no vectors coded

            mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;

            cbp     = 0;

        } else {

            modb2   = get_bits1(&s->gb);

            mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);

            if (mb_type < 0) {

                av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");

                return -1;

            mb_type = mb_type_b_map[mb_type];

            if (modb2) {

                cbp = 0;

            } else {

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

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

            if ((!IS_DIRECT(mb_type)) && cbp) {

                if (get_bits1(&s->gb))

                    ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);

            if (!s->progressive_sequence) {

                if (cbp)

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

                if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {

                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;

                    mb_type &= ~MB_TYPE_16x16;

                    if (USES_LIST(mb_type, 0)) {

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

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

                    if (USES_LIST(mb_type, 1)) {

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

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

            s->mv_dir = 0;

            if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {

                s->mv_type = MV_TYPE_16X16;

                if (USES_LIST(mb_type, 0)) {

                    s->mv_dir = MV_DIR_FORWARD;

                    mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);

                    my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);

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

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

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

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

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

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

                if (USES_LIST(mb_type, 1)) {

                    s->mv_dir |= MV_DIR_BACKWARD;

                    mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);

                    my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);

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

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

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

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

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

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

            } else if (!IS_DIRECT(mb_type)) {

                s->mv_type = MV_TYPE_FIELD;

                if (USES_LIST(mb_type, 0)) {

                    s->mv_dir = MV_DIR_FORWARD;

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

                        mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);

                        my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);

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

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

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

                if (USES_LIST(mb_type, 1)) {

                    s->mv_dir |= MV_DIR_BACKWARD;

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

                        mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);

                        my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);

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

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

                        s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;

        if (IS_DIRECT(mb_type)) {

            if (IS_SKIP(mb_type)) {

                mx =

                my = 0;

            } else {

                mx = ff_h263_decode_motion(s, 0, 1);

                my = ff_h263_decode_motion(s, 0, 1);

            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;

            mb_type  |= ff_mpeg4_set_direct_mv(s, mx, my);

        s->current_picture.mb_type[xy] = mb_type;

    } else { /* I-Frame */

        do {

            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);

            if (cbpc < 0) {

                       "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

        } while (cbpc == 8);

        dquant = cbpc & 4;

        s->mb_intra = 1;

intra:

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

        if (s->ac_pred)

            s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;

        else

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

        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);

                   "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        cbp = (cbpc & 3) | (cbpy << 2);

        ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;

        if (dquant)

            ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);

        if (!s->progressive_sequence)

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

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

        /* decode each block */

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

            if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)

                return -1;

            cbp += cbp;

        goto end;

    /* decode each block */

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

        if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)

            return -1;

        cbp += cbp;

end:

    /* per-MB end of slice check */

    if (s->codec_id == AV_CODEC_ID_MPEG4) {

        int next = mpeg4_is_resync(ctx);

        if (next) {

            if        (s->mb_x + s->mb_y*s->mb_width + 1 >  next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {

                return -1;

            } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)

                return SLICE_END;

            if (s->pict_type == AV_PICTURE_TYPE_B) {

                const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;

                ff_thread_await_progress(&s->next_picture_ptr->tf,

                                         (s->mb_x + delta >= s->mb_width)

                                         ? FFMIN(s->mb_y + 1, s->mb_height - 1)

                                         : s->mb_y, 0);

                if (s->next_picture.mbskip_table[xy + delta])

                    return SLICE_OK;

            return SLICE_END;

    return SLICE_OK;