static ssize_t usbnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size)

{

    USBNetState *s = DO_UPCAST(NICState, nc, nc)->opaque;

    struct rndis_packet_msg_type *msg;

    if (is_rndis(s)) {

        msg = (struct rndis_packet_msg_type *) s->in_buf;

        if (!s->rndis_state == RNDIS_DATA_INITIALIZED)

            return -1;

        if (size + sizeof(struct rndis_packet_msg_type) > sizeof(s->in_buf))

            return -1;

        memset(msg, 0, sizeof(struct rndis_packet_msg_type));

        msg->MessageType = cpu_to_le32(RNDIS_PACKET_MSG);

        msg->MessageLength = cpu_to_le32(size + sizeof(struct rndis_packet_msg_type));

        msg->DataOffset = cpu_to_le32(sizeof(struct rndis_packet_msg_type) - 8);

        msg->DataLength = cpu_to_le32(size);

        /* msg->OOBDataOffset;

         * msg->OOBDataLength;

         * msg->NumOOBDataElements;

         * msg->PerPacketInfoOffset;

         * msg->PerPacketInfoLength;

         * msg->VcHandle;

         * msg->Reserved;

         */

        memcpy(msg + 1, buf, size);

        s->in_len = size + sizeof(struct rndis_packet_msg_type);

    } else {

        if (size > sizeof(s->in_buf))

            return -1;

        memcpy(s->in_buf, buf, size);

        s->in_len = size;

    }

    s->in_ptr = 0;

    return size;

}


int unix_connect(const char *path)

{

    QemuOpts *opts;

    int sock;

    opts = qemu_opts_create(&dummy_opts, NULL, 0);

    qemu_opt_set(opts, "path", path);

    sock = unix_connect_opts(opts);

    qemu_opts_del(opts);

    return sock;

}


static inline bool regime_translation_disabled(CPUARMState *env,

                                               ARMMMUIdx mmu_idx)

{

    if (arm_feature(env, ARM_FEATURE_M)) {

        switch (env->v7m.mpu_ctrl[regime_is_secure(env, mmu_idx)] &

                (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {

        case R_V7M_MPU_CTRL_ENABLE_MASK:

            /* Enabled, but not for HardFault and NMI */

            return mmu_idx == ARMMMUIdx_MNegPri ||

                mmu_idx == ARMMMUIdx_MSNegPri;

        case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:

            /* Enabled for all cases */

            return false;

        case 0:

        default:

            /* HFNMIENA set and ENABLE clear is UNPREDICTABLE, but

             * we warned about that in armv7m_nvic.c when the guest set it.

             */

            return true;

        }

    }

    if (mmu_idx == ARMMMUIdx_S2NS) {

        return (env->cp15.hcr_el2 & HCR_VM) == 0;

    }

    return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;

}


static void migration_instance_init(Object *obj)

{

    MigrationState *ms = MIGRATION_OBJ(obj);

    ms->state = MIGRATION_STATUS_NONE;

    ms->xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE;

    ms->mbps = -1;

    ms->parameters.tls_creds = g_strdup("");

    ms->parameters.tls_hostname = g_strdup("");

}


static void do_stop_capture(Monitor *mon, const QDict *qdict)

{

    int i;

    int n = qdict_get_int(qdict, "n");

    CaptureState *s;

    for (s = capture_head.lh_first, i = 0; s; s = s->entries.le_next, ++i) {

        if (i == n) {

            s->ops.destroy (s->opaque);

            LIST_REMOVE (s, entries);

            qemu_free (s);

            return;

        }

    }

}


static void nbd_refresh_filename(BlockDriverState *bs)

{

    QDict *opts = qdict_new();

    const char *path   = qdict_get_try_str(bs->options, "path");

    const char *host   = qdict_get_try_str(bs->options, "host");

    const char *port   = qdict_get_try_str(bs->options, "port");

    const char *export = qdict_get_try_str(bs->options, "export");

    qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("nbd")));

    if (path && export) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd+unix:///%s?socket=%s", export, path);

    } else if (path && !export) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd+unix://?socket=%s", path);

    } else if (!path && export && port) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd://%s:%s/%s", host, port, export);

    } else if (!path && export && !port) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd://%s/%s", host, export);

    } else if (!path && !export && port) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd://%s:%s", host, port);

    } else if (!path && !export && !port) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nbd://%s", host);

    }

    if (path) {

        qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));

    } else if (port) {

        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));

        qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));

    } else {

        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));

    }

    if (export) {

        qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));

    }

    bs->full_open_options = opts;

}


static int select_input_picture(MpegEncContext *s)

{

    int i, ret;

    for (i = 1; i < MAX_PICTURE_COUNT; i++)

        s->reordered_input_picture[i - 1] = s->reordered_input_picture[i];

    s->reordered_input_picture[MAX_PICTURE_COUNT - 1] = NULL;

    /* set next picture type & ordering */

    if (!s->reordered_input_picture[0] && s->input_picture[0]) {

        if (/*s->picture_in_gop_number >= s->gop_size ||*/

            !s->next_picture_ptr || s->intra_only) {

            s->reordered_input_picture[0] = s->input_picture[0];

            s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_I;

            s->reordered_input_picture[0]->f->coded_picture_number =

                s->coded_picture_number++;

        } else {

            int b_frames;

            if (s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor) {

                if (s->picture_in_gop_number < s->gop_size &&

                    skip_check(s, s->input_picture[0], s->next_picture_ptr)) {

                    // FIXME check that te gop check above is +-1 correct

                    av_frame_unref(s->input_picture[0]->f);

                    emms_c();

                    ff_vbv_update(s, 0);

                    goto no_output_pic;

                }

            }

            if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {

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

                    int pict_num = s->input_picture[0]->f->display_picture_number + i;

                    if (pict_num >= s->rc_context.num_entries)

                        break;

                    if (!s->input_picture[i]) {

                        s->rc_context.entry[pict_num - 1].new_pict_type = AV_PICTURE_TYPE_P;

                        break;

                    }

                    s->input_picture[i]->f->pict_type =

                        s->rc_context.entry[pict_num].new_pict_type;

                }

            }

            if (s->avctx->b_frame_strategy == 0) {

                b_frames = s->max_b_frames;

                while (b_frames && !s->input_picture[b_frames])

                    b_frames--;

            } else if (s->avctx->b_frame_strategy == 1) {

                for (i = 1; i < s->max_b_frames + 1; i++) {

                    if (s->input_picture[i] &&

                        s->input_picture[i]->b_frame_score == 0) {

                        s->input_picture[i]->b_frame_score =

                            get_intra_count(s,

                                            s->input_picture[i    ]->f->data[0],

                                            s->input_picture[i - 1]->f->data[0],

                                            s->linesize) + 1;

                    }

                }

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

                    if (!s->input_picture[i] ||

                        s->input_picture[i]->b_frame_score - 1 >

                            s->mb_num / s->avctx->b_sensitivity)

                        break;

                }

                b_frames = FFMAX(0, i - 1);

                /* reset scores */

                for (i = 0; i < b_frames + 1; i++) {

                    s->input_picture[i]->b_frame_score = 0;

                }

            } else if (s->avctx->b_frame_strategy == 2) {

                b_frames = estimate_best_b_count(s);

            } else {

                av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");

                b_frames = 0;

            }

            emms_c();

            for (i = b_frames - 1; i >= 0; i--) {

                int type = s->input_picture[i]->f->pict_type;

                if (type && type != AV_PICTURE_TYPE_B)

                    b_frames = i;

            }

            if (s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_B &&

                b_frames == s->max_b_frames) {

                av_log(s->avctx, AV_LOG_ERROR,

                       "warning, too many b frames in a row\n");

            }

            if (s->picture_in_gop_number + b_frames >= s->gop_size) {

                if ((s->mpv_flags & FF_MPV_FLAG_STRICT_GOP) &&

                    s->gop_size > s->picture_in_gop_number) {

                    b_frames = s->gop_size - s->picture_in_gop_number - 1;

                } else {

                    if (s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)

                        b_frames = 0;

                    s->input_picture[b_frames]->f->pict_type = AV_PICTURE_TYPE_I;

                }

            }

            if ((s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) && b_frames &&

                s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_I)

                b_frames--;

            s->reordered_input_picture[0] = s->input_picture[b_frames];

            if (s->reordered_input_picture[0]->f->pict_type != AV_PICTURE_TYPE_I)

                s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_P;

            s->reordered_input_picture[0]->f->coded_picture_number =

                s->coded_picture_number++;

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

                s->reordered_input_picture[i + 1] = s->input_picture[i];

                s->reordered_input_picture[i + 1]->f->pict_type =

                    AV_PICTURE_TYPE_B;

                s->reordered_input_picture[i + 1]->f->coded_picture_number =

                    s->coded_picture_number++;

            }

        }

    }

no_output_pic:

    ff_mpeg_unref_picture(s->avctx, &s->new_picture);

    if (s->reordered_input_picture[0]) {

        s->reordered_input_picture[0]->reference =

           s->reordered_input_picture[0]->f->pict_type !=

               AV_PICTURE_TYPE_B ? 3 : 0;

        if ((ret = ff_mpeg_ref_picture(s->avctx, &s->new_picture, s->reordered_input_picture[0])))

            return ret;

        if (s->reordered_input_picture[0]->shared || s->avctx->rc_buffer_size) {

            // input is a shared pix, so we can't modifiy it -> alloc a new

            // one & ensure that the shared one is reuseable

            Picture *pic;

            int i = ff_find_unused_picture(s->avctx, s->picture, 0);

            if (i < 0)

                return i;

            pic = &s->picture[i];

            pic->reference = s->reordered_input_picture[0]->reference;

            if (alloc_picture(s, pic, 0) < 0) {

                return -1;

            }

            ret = av_frame_copy_props(pic->f, s->reordered_input_picture[0]->f);

            if (ret < 0)

                return ret;

            /* mark us unused / free shared pic */

            av_frame_unref(s->reordered_input_picture[0]->f);

            s->reordered_input_picture[0]->shared = 0;

            s->current_picture_ptr = pic;

        } else {

            // input is not a shared pix -> reuse buffer for current_pix

            s->current_picture_ptr = s->reordered_input_picture[0];

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

                s->new_picture.f->data[i] += INPLACE_OFFSET;

            }

        }

        ff_mpeg_unref_picture(s->avctx, &s->current_picture);

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

                                       s->current_picture_ptr)) < 0)

            return ret;

        s->picture_number = s->new_picture.f->display_picture_number;

    }

    return 0;

}


static inline void iwmmxt_store_reg(TCGv var, int reg)

{

    tcg_gen_st_i64(var, cpu_env, offsetof(CPUState, iwmmxt.regs[reg]));

}


static int msix_is_masked(PCIDevice *dev, int vector)

{

    unsigned offset = vector * MSIX_ENTRY_SIZE + MSIX_VECTOR_CTRL;

    return dev->msix_table_page[offset] & MSIX_VECTOR_MASK;

}


static void qed_aio_next_io(QEDAIOCB *acb)

{

    BDRVQEDState *s = acb_to_s(acb);

    uint64_t offset;

    size_t len;

    int ret;

    trace_qed_aio_next_io(s, acb, 0, acb->cur_pos + acb->cur_qiov.size);

    if (acb->backing_qiov) {

        qemu_iovec_destroy(acb->backing_qiov);

        g_free(acb->backing_qiov);

        acb->backing_qiov = NULL;

    }

    acb->qiov_offset += acb->cur_qiov.size;

    acb->cur_pos += acb->cur_qiov.size;

    qemu_iovec_reset(&acb->cur_qiov);

    /* Complete request */

    if (acb->cur_pos >= acb->end_pos) {

        qed_aio_complete(acb, 0);

        return;

    }

    /* Find next cluster and start I/O */

    len = acb->end_pos - acb->cur_pos;

    ret = qed_find_cluster(s, &acb->request, acb->cur_pos, &len, &offset);

    if (ret < 0) {

        qed_aio_complete(acb, ret);

        return;

    }

    if (acb->flags & QED_AIOCB_WRITE) {

        ret = qed_aio_write_data(acb, ret, offset, len);

    } else {

        ret = qed_aio_read_data(acb, ret, offset, len);

    }

    if (ret < 0) {

        if (ret != -EINPROGRESS) {

            qed_aio_complete(acb, ret);

        }

        return;

    }

    qed_aio_next_io(acb);

}


writev_f(int argc, char **argv)

{

	struct timeval t1, t2;

	int Cflag = 0, qflag = 0;

	int c, cnt;

	char *buf;

	int64_t offset;

	int total;

	int nr_iov;

	int pattern = 0xcd;

	QEMUIOVector qiov;

	while ((c = getopt(argc, argv, "CqP:")) != EOF) {

		switch (c) {

		case 'C':

			Cflag = 1;

			break;

		case 'q':

			qflag = 1;

			break;

		case 'P':

			pattern = atoi(optarg);

			break;

		default:

			return command_usage(&writev_cmd);

		}

	}

	if (optind > argc - 2)

		return command_usage(&writev_cmd);

	offset = cvtnum(argv[optind]);

	if (offset < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		return 0;

	}

	optind++;

	if (offset & 0x1ff) {

		printf("offset %lld is not sector aligned\n",

			(long long)offset);

		return 0;

	}

	nr_iov = argc - optind;

	buf = create_iovec(&qiov, &argv[optind], nr_iov, pattern);

	gettimeofday(&t1, NULL);

	cnt = do_aio_writev(&qiov, offset, &total);

	gettimeofday(&t2, NULL);

	if (cnt < 0) {

		printf("writev failed: %s\n", strerror(-cnt));

		goto out;

	}

	if (qflag)

		goto out;

	/* Finally, report back -- -C gives a parsable format */

	t2 = tsub(t2, t1);

	print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);

out:

	qemu_io_free(buf);

	return 0;

}


static void test_qemu_strtoull_decimal(void)

{

    const char *str = "0123";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 10, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + strlen(str));

    str = "123";

    endptr = &f;

    res = 999;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + strlen(str));

}


static uint64_t imx_timerp_read(void *opaque, target_phys_addr_t offset,

                                unsigned size)

{

    IMXTimerPState *s = (IMXTimerPState *)opaque;

    DPRINTF("p-read(offset=%x)", offset >> 2);

    switch (offset >> 2) {

    case 0: /* Control Register */

        DPRINTF("cr %x\n", s->cr);

        return s->cr;

    case 1: /* Status Register */

        DPRINTF("int_level %x\n", s->int_level);

        return s->int_level;

    case 2: /* LR - ticks*/

        DPRINTF("lr %x\n", s->lr);

        return s->lr;

    case 3: /* CMP */

        DPRINTF("cmp %x\n", s->cmp);

        return s->cmp;

    case 4: /* CNT */

        return ptimer_get_count(s->timer);

    }

    IPRINTF("imx_timerp_read: Bad offset %x\n",

            (int)offset >> 2);

    return 0;

}


static void tcg_out_brcond2(TCGContext *s, TCGCond cond, TCGReg al, TCGReg ah,

                            TCGReg bl, TCGReg bh, int label_index)

{

    TCGCond b_cond = TCG_COND_NE;

    TCGReg tmp = TCG_TMP1;

    /* With branches, we emit between 4 and 9 insns with 2 or 3 branches.

       With setcond, we emit between 3 and 10 insns and only 1 branch,

       which ought to get better branch prediction.  */

     switch (cond) {

     case TCG_COND_EQ:

     case TCG_COND_NE:

        b_cond = cond;

        tmp = tcg_out_reduce_eq2(s, TCG_TMP0, TCG_TMP1, al, ah, bl, bh);

        break;

    default:

        /* Minimize code size by preferring a compare not requiring INV.  */

        if (mips_cmp_map[cond] & MIPS_CMP_INV) {

            cond = tcg_invert_cond(cond);

            b_cond = TCG_COND_EQ;

        }

        tcg_out_setcond2(s, cond, tmp, al, ah, bl, bh);

        break;

    }

    tcg_out_brcond(s, b_cond, tmp, TCG_REG_ZERO, label_index);

}


static void legacy_mouse_event(DeviceState *dev, QemuConsole *src,

                               InputEvent *evt)

{

    static const int bmap[INPUT_BUTTON__MAX] = {

        [INPUT_BUTTON_LEFT]   = MOUSE_EVENT_LBUTTON,

        [INPUT_BUTTON_MIDDLE] = MOUSE_EVENT_MBUTTON,

        [INPUT_BUTTON_RIGHT]  = MOUSE_EVENT_RBUTTON,

    };

    QEMUPutMouseEntry *s = (QEMUPutMouseEntry *)dev;

    InputBtnEvent *btn;

    InputMoveEvent *move;

    switch (evt->type) {

    case INPUT_EVENT_KIND_BTN:

        btn = evt->u.btn;

        if (btn->down) {

            s->buttons |= bmap[btn->button];

        } else {

            s->buttons &= ~bmap[btn->button];

        }

        if (btn->down && btn->button == INPUT_BUTTON_WHEEL_UP) {

            s->qemu_put_mouse_event(s->qemu_put_mouse_event_opaque,

                                    s->axis[INPUT_AXIS_X],

                                    s->axis[INPUT_AXIS_Y],

                                    -1,

                                    s->buttons);

        }

        if (btn->down && btn->button == INPUT_BUTTON_WHEEL_DOWN) {

            s->qemu_put_mouse_event(s->qemu_put_mouse_event_opaque,

                                    s->axis[INPUT_AXIS_X],

                                    s->axis[INPUT_AXIS_Y],

                                    1,

                                    s->buttons);

        }

        break;

    case INPUT_EVENT_KIND_ABS:

        move = evt->u.abs;

        s->axis[move->axis] = move->value;

        break;

    case INPUT_EVENT_KIND_REL:

        move = evt->u.rel;

        s->axis[move->axis] += move->value;

        break;

    default:

        break;

    }

}


static int h264_slice_header_init(H264Context *h)

{

    int nb_slices = (HAVE_THREADS &&

                     h->avctx->active_thread_type & FF_THREAD_SLICE) ?

                    h->avctx->thread_count : 1;

    int i, ret;

    ff_set_sar(h->avctx, h->sps.sar);

    av_pix_fmt_get_chroma_sub_sample(h->avctx->pix_fmt,

                                     &h->chroma_x_shift, &h->chroma_y_shift);

    if (h->sps.timing_info_present_flag) {

        int64_t den = h->sps.time_scale;

        if (h->x264_build < 44U)

            den *= 2;

        av_reduce(&h->avctx->framerate.den, &h->avctx->framerate.num,

                  h->sps.num_units_in_tick, den, 1 << 30);

    }

    ff_h264_free_tables(h);

    h->first_field           = 0;

    h->prev_interlaced_frame = 1;

    init_scan_tables(h);

    ret = ff_h264_alloc_tables(h);

    if (ret < 0) {

        av_log(h->avctx, AV_LOG_ERROR, "Could not allocate memory\n");

        return ret;

    }

    if (h->sps.bit_depth_luma < 8 || h->sps.bit_depth_luma > 10) {

        av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",

               h->sps.bit_depth_luma);

        return AVERROR_INVALIDDATA;

    }

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

    h->pixel_shift                = h->sps.bit_depth_luma > 8;

    h->chroma_format_idc          = h->sps.chroma_format_idc;

    h->bit_depth_luma             = h->sps.bit_depth_luma;

    ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,

                    h->sps.chroma_format_idc);

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

    ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);

    ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,

                      h->sps.chroma_format_idc);

    ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);

    if (nb_slices > H264_MAX_THREADS || (nb_slices > h->mb_height && h->mb_height)) {

        int max_slices;

        if (h->mb_height)

            max_slices = FFMIN(H264_MAX_THREADS, h->mb_height);

        else

            max_slices = H264_MAX_THREADS;

        av_log(h->avctx, AV_LOG_WARNING, "too many threads/slices %d,"

               " reducing to %d\n", nb_slices, max_slices);

        nb_slices = max_slices;

    }

    h->slice_context_count = nb_slices;

    if (!HAVE_THREADS || !(h->avctx->active_thread_type & FF_THREAD_SLICE)) {

        ret = ff_h264_slice_context_init(h, &h->slice_ctx[0]);

        if (ret < 0) {

            av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");

            return ret;

        }

    } else {

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

            H264SliceContext *sl = &h->slice_ctx[i];

            sl->h264               = h;

            sl->intra4x4_pred_mode = h->intra4x4_pred_mode + i * 8 * 2 * h->mb_stride;

            sl->mvd_table[0]       = h->mvd_table[0]       + i * 8 * 2 * h->mb_stride;

            sl->mvd_table[1]       = h->mvd_table[1]       + i * 8 * 2 * h->mb_stride;

            if ((ret = ff_h264_slice_context_init(h, sl)) < 0) {

                av_log(h->avctx, AV_LOG_ERROR, "context_init() failed.\n");

                return ret;

            }

        }

    }

    h->context_initialized = 1;

    return 0;

}


int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx)

{

    int i, ret;

    Picture *pic;

    s->mb_skipped = 0;

    /* 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->avctx, s->last_picture_ptr);

    }

    /* release forgotten pictures */

    /* if (MPEG-124 / H.263) */

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

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

        }

    }

    ff_mpeg_unref_picture(s->avctx, &s->current_picture);

    /* release non reference frames */

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

        if (!s->picture[i].reference)

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

    }

    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->avctx, s->picture, 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 (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->avctx->flags && AV_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->avctx, &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_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_INFO,

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

        /* Allocate a dummy frame */

        i = ff_find_unused_picture(s->avctx, s->picture, 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->pict_type = AV_PICTURE_TYPE_I;

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

            s->last_picture_ptr = NULL;

            return -1;

        }

        memset(s->last_picture_ptr->f->data[0], 0,

               avctx->height * s->last_picture_ptr->f->linesize[0]);

        memset(s->last_picture_ptr->f->data[1], 0x80,

               (avctx->height >> v_chroma_shift) *

               s->last_picture_ptr->f->linesize[1]);

        memset(s->last_picture_ptr->f->data[2], 0x80,

               (avctx->height >> v_chroma_shift) *

               s->last_picture_ptr->f->linesize[2]);

        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->avctx, s->picture, 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->pict_type = AV_PICTURE_TYPE_I;

        if (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 (s->last_picture_ptr) {

        ff_mpeg_unref_picture(s->avctx, &s->last_picture);

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

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

                                       s->last_picture_ptr)) < 0)

            return ret;

    }

    if (s->next_picture_ptr) {

        ff_mpeg_unref_picture(s->avctx, &s->next_picture);

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

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

                                       s->next_picture_ptr)) < 0)

            return ret;

    }

    if (s->pict_type != AV_PICTURE_TYPE_I &&

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

        av_log(s, AV_LOG_ERROR,

               "Non-reference picture received and no reference available\n");

        return AVERROR_INVALIDDATA;

    }

    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;

        }

    }

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

     * it might change for MPEG-4 and we can't do it in the header

     * decode as init is not called for MPEG-4 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 FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)

        return ff_xvmc_field_start(s, avctx);

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    return 0;

}


static guint io_add_watch_poll(GIOChannel *channel,

                               IOCanReadHandler *fd_can_read,

                               GIOFunc fd_read,

                               gpointer user_data)

{

    IOWatchPoll *iwp;

    iwp = (IOWatchPoll *) g_source_new(&io_watch_poll_funcs, sizeof(IOWatchPoll));

    iwp->fd_can_read = fd_can_read;

    iwp->opaque = user_data;

    iwp->src = g_io_create_watch(channel, G_IO_IN | G_IO_ERR | G_IO_HUP);

    g_source_set_callback(iwp->src, (GSourceFunc)fd_read, user_data, NULL);

    return g_source_attach(&iwp->parent, NULL);

}


int qio_channel_socket_dgram_sync(QIOChannelSocket *ioc,

                                  SocketAddress *localAddr,

                                  SocketAddress *remoteAddr,

                                  Error **errp)

{

    int fd;

    trace_qio_channel_socket_dgram_sync(ioc, localAddr, remoteAddr);

    fd = socket_dgram(remoteAddr, localAddr, errp);

    if (fd < 0) {

        trace_qio_channel_socket_dgram_fail(ioc);

        return -1;

    }

    trace_qio_channel_socket_dgram_complete(ioc, fd);

    if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {

        close(fd);

        return -1;

    }

    return 0;

}


int ff_init_me(MpegEncContext *s){

    MotionEstContext * const c= &s->me;

    int cache_size= FFMIN(ME_MAP_SIZE>>ME_MAP_SHIFT, 1<<ME_MAP_SHIFT);

    int dia_size= FFMAX(FFABS(s->avctx->dia_size)&255, FFABS(s->avctx->pre_dia_size)&255);

    if(FFMIN(s->avctx->dia_size, s->avctx->pre_dia_size) < -ME_MAP_SIZE){

        av_log(s->avctx, AV_LOG_ERROR, "ME_MAP size is too small for SAB diamond\n");

        return -1;

    }

    //special case of snow is needed because snow uses its own iterative ME code

    if(s->me_method!=ME_ZERO && s->me_method!=ME_EPZS && s->me_method!=ME_X1 && s->avctx->codec_id != AV_CODEC_ID_SNOW){

        av_log(s->avctx, AV_LOG_ERROR, "me_method is only allowed to be set to zero and epzs; for hex,umh,full and others see dia_size\n");

        return -1;

    }

    c->avctx= s->avctx;

    if(cache_size < 2*dia_size && !c->stride){

        av_log(s->avctx, AV_LOG_INFO, "ME_MAP size may be a little small for the selected diamond size\n");

    }

    ff_set_cmp(&s->dsp, s->dsp.me_pre_cmp, c->avctx->me_pre_cmp);

    ff_set_cmp(&s->dsp, s->dsp.me_cmp, c->avctx->me_cmp);

    ff_set_cmp(&s->dsp, s->dsp.me_sub_cmp, c->avctx->me_sub_cmp);

    ff_set_cmp(&s->dsp, s->dsp.mb_cmp, c->avctx->mb_cmp);

    c->flags    = get_flags(c, 0, c->avctx->me_cmp    &FF_CMP_CHROMA);

    c->sub_flags= get_flags(c, 0, c->avctx->me_sub_cmp&FF_CMP_CHROMA);

    c->mb_flags = get_flags(c, 0, c->avctx->mb_cmp    &FF_CMP_CHROMA);

/*FIXME s->no_rounding b_type*/

    if(s->flags&CODEC_FLAG_QPEL){

        c->sub_motion_search= qpel_motion_search;

        c->qpel_avg= s->dsp.avg_qpel_pixels_tab;

        if(s->no_rounding) c->qpel_put= s->dsp.put_no_rnd_qpel_pixels_tab;

        else               c->qpel_put= s->dsp.put_qpel_pixels_tab;

    }else{

        if(c->avctx->me_sub_cmp&FF_CMP_CHROMA)

            c->sub_motion_search= hpel_motion_search;

        else if(   c->avctx->me_sub_cmp == FF_CMP_SAD

                && c->avctx->    me_cmp == FF_CMP_SAD

                && c->avctx->    mb_cmp == FF_CMP_SAD)

            c->sub_motion_search= sad_hpel_motion_search; // 2050 vs. 2450 cycles

        else

            c->sub_motion_search= hpel_motion_search;

    }

    c->hpel_avg= s->dsp.avg_pixels_tab;

    if(s->no_rounding) c->hpel_put= s->dsp.put_no_rnd_pixels_tab;

    else               c->hpel_put= s->dsp.put_pixels_tab;

    if(s->linesize){

        c->stride  = s->linesize;

        c->uvstride= s->uvlinesize;

    }else{

        c->stride  = 16*s->mb_width + 32;

        c->uvstride=  8*s->mb_width + 16;

    }

    /* 8x8 fullpel search would need a 4x4 chroma compare, which we do

     * not have yet, and even if we had, the motion estimation code

     * does not expect it. */

    if(s->codec_id != AV_CODEC_ID_SNOW){

        if((c->avctx->me_cmp&FF_CMP_CHROMA)/* && !s->dsp.me_cmp[2]*/){

            s->dsp.me_cmp[2]= zero_cmp;

        }

        if((c->avctx->me_sub_cmp&FF_CMP_CHROMA) && !s->dsp.me_sub_cmp[2]){

            s->dsp.me_sub_cmp[2]= zero_cmp;

        }

        c->hpel_put[2][0]= c->hpel_put[2][1]=

        c->hpel_put[2][2]= c->hpel_put[2][3]= zero_hpel;

    }

    if(s->codec_id == AV_CODEC_ID_H261){

        c->sub_motion_search= no_sub_motion_search;

    }

    return 0;

}


float32 float32_scalbn( float32 a, int n STATUS_PARAM )

{

    flag aSign;

    int16 aExp;

    uint32_t aSig;

    a = float32_squash_input_denormal(a STATUS_VAR);

    aSig = extractFloat32Frac( a );

    aExp = extractFloat32Exp( a );

    aSign = extractFloat32Sign( a );

    if ( aExp == 0xFF ) {

        return a;

    }

    if ( aExp != 0 )

        aSig |= 0x00800000;

    else if ( aSig == 0 )

        return a;

    aExp += n - 1;

    aSig <<= 7;

    return normalizeRoundAndPackFloat32( aSign, aExp, aSig STATUS_VAR );

}


void net_check_clients(void)

{

    VLANState *vlan;

    VLANClientState *vc;

    int has_nic, has_host_dev;

    QTAILQ_FOREACH(vlan, &vlans, next) {

        QTAILQ_FOREACH(vc, &vlan->clients, next) {

            switch (vc->info->type) {

            case NET_CLIENT_TYPE_NIC:

                has_nic = 1;

                break;

            case NET_CLIENT_TYPE_SLIRP:

            case NET_CLIENT_TYPE_TAP:

            case NET_CLIENT_TYPE_SOCKET:

            case NET_CLIENT_TYPE_VDE:

                has_host_dev = 1;

                break;

            default: ;

            }

        }

        if (has_host_dev && !has_nic)

            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);

        if (has_nic && !has_host_dev)

            fprintf(stderr,

                    "Warning: vlan %d is not connected to host network\n",

                    vlan->id);

    }

    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {

        if (!vc->peer) {

            fprintf(stderr, "Warning: %s %s has no peer\n",

                    vc->info->type == NET_CLIENT_TYPE_NIC ? "nic" : "netdev",

                    vc->name);

        }

    }

}


static uint32_t hpet_time_after64(uint64_t a, uint64_t b)

{

    return ((int64_t)(b) - (int64_t)(a) < 0);

}


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

{

    GICv3State *s = KVM_ARM_GICV3(dev);

    KVMARMGICv3Class *kgc = KVM_ARM_GICV3_GET_CLASS(s);

    Error *local_err = NULL;

    DPRINTF("kvm_arm_gicv3_realize\n");

    kgc->parent_realize(dev, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (s->security_extn) {

        error_setg(errp, "the in-kernel VGICv3 does not implement the "

                   "security extensions");

        return;

    }

    gicv3_init_irqs_and_mmio(s, kvm_arm_gicv3_set_irq, NULL);

    /* Try to create the device via the device control API */

    s->dev_fd = kvm_create_device(kvm_state, KVM_DEV_TYPE_ARM_VGIC_V3, false);

    if (s->dev_fd < 0) {

        error_setg_errno(errp, -s->dev_fd, "error creating in-kernel VGIC");

        return;

    }

    kvm_device_access(s->dev_fd, KVM_DEV_ARM_VGIC_GRP_NR_IRQS,

                      0, &s->num_irq, true);

    /* Tell the kernel to complete VGIC initialization now */

    kvm_device_access(s->dev_fd, KVM_DEV_ARM_VGIC_GRP_CTRL,

                      KVM_DEV_ARM_VGIC_CTRL_INIT, NULL, true);

    kvm_arm_register_device(&s->iomem_dist, -1, KVM_DEV_ARM_VGIC_GRP_ADDR,

                            KVM_VGIC_V3_ADDR_TYPE_DIST, s->dev_fd);

    kvm_arm_register_device(&s->iomem_redist, -1, KVM_DEV_ARM_VGIC_GRP_ADDR,

                            KVM_VGIC_V3_ADDR_TYPE_REDIST, s->dev_fd);

    /* Block migration of a KVM GICv3 device: the API for saving and restoring

     * the state in the kernel is not yet finalised in the kernel or

     * implemented in QEMU.

     */

    error_setg(&s->migration_blocker, "vGICv3 migration is not implemented");

    migrate_add_blocker(s->migration_blocker);

    if (kvm_has_gsi_routing()) {

        /* set up irq routing */

        kvm_init_irq_routing(kvm_state);

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

            kvm_irqchip_add_irq_route(kvm_state, i, 0, i);

        }

        kvm_gsi_routing_allowed = true;

        kvm_irqchip_commit_routes(kvm_state);

    }

}


static TypeImpl *type_register_internal(const TypeInfo *info)

{

    TypeImpl *ti = g_malloc0(sizeof(*ti));

    int i;

    g_assert(info->name != NULL);

    if (type_table_lookup(info->name) != NULL) {

        fprintf(stderr, "Registering `%s' which already exists\n", info->name);

        abort();

    }

    ti->name = g_strdup(info->name);

    ti->parent = g_strdup(info->parent);

    ti->class_size = info->class_size;

    ti->instance_size = info->instance_size;

    ti->class_init = info->class_init;

    ti->class_base_init = info->class_base_init;

    ti->class_finalize = info->class_finalize;

    ti->class_data = info->class_data;

    ti->instance_init = info->instance_init;

    ti->instance_post_init = info->instance_post_init;

    ti->instance_finalize = info->instance_finalize;

    ti->abstract = info->abstract;

    for (i = 0; info->interfaces && info->interfaces[i].type; i++) {

        ti->interfaces[i].typename = g_strdup(info->interfaces[i].type);

    }

    ti->num_interfaces = i;

    type_table_add(ti);

    return ti;

}


static int disas_vfp_insn(CPUState * env, DisasContext *s, uint32_t insn)

{

    uint32_t rd, rn, rm, op, i, n, offset, delta_d, delta_m, bank_mask;

    int dp, veclen;

    TCGv addr;

    TCGv tmp;

    TCGv tmp2;

    if (!arm_feature(env, ARM_FEATURE_VFP))

        return 1;

    if (!vfp_enabled(env)) {

        /* VFP disabled.  Only allow fmxr/fmrx to/from some control regs.  */

        if ((insn & 0x0fe00fff) != 0x0ee00a10)

            return 1;

        rn = (insn >> 16) & 0xf;

        if (rn != ARM_VFP_FPSID && rn != ARM_VFP_FPEXC

            && rn != ARM_VFP_MVFR1 && rn != ARM_VFP_MVFR0)

            return 1;

    }

    dp = ((insn & 0xf00) == 0xb00);

    switch ((insn >> 24) & 0xf) {

    case 0xe:

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

            /* single register transfer */

            rd = (insn >> 12) & 0xf;

            if (dp) {

                int size;

                int pass;

                VFP_DREG_N(rn, insn);

                if (insn & 0xf)

                    return 1;

                if (insn & 0x00c00060

                    && !arm_feature(env, ARM_FEATURE_NEON))

                    return 1;

                pass = (insn >> 21) & 1;

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

                    size = 0;

                    offset = ((insn >> 5) & 3) * 8;

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

                    size = 1;

                    offset = (insn & (1 << 6)) ? 16 : 0;

                } else {

                    size = 2;

                    offset = 0;

                }

                if (insn & ARM_CP_RW_BIT) {

                    /* vfp->arm */

                    tmp = neon_load_reg(rn, pass);

                    switch (size) {

                    case 0:

                        if (offset)

                            tcg_gen_shri_i32(tmp, tmp, offset);

                        if (insn & (1 << 23))

                            gen_uxtb(tmp);

                        else

                            gen_sxtb(tmp);

                        break;

                    case 1:

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

                            if (offset) {

                                tcg_gen_shri_i32(tmp, tmp, 16);

                            } else {

                                gen_uxth(tmp);

                            }

                        } else {

                            if (offset) {

                                tcg_gen_sari_i32(tmp, tmp, 16);

                            } else {

                                gen_sxth(tmp);

                            }

                        }

                        break;

                    case 2:

                        break;

                    }

                    store_reg(s, rd, tmp);

                } else {

                    /* arm->vfp */

                    tmp = load_reg(s, rd);

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

                        /* VDUP */

                        if (size == 0) {

                            gen_neon_dup_u8(tmp, 0);

                        } else if (size == 1) {

                            gen_neon_dup_low16(tmp);

                        }

                        for (n = 0; n <= pass * 2; n++) {

                            tmp2 = new_tmp();

                            tcg_gen_mov_i32(tmp2, tmp);

                            neon_store_reg(rn, n, tmp2);

                        }

                        neon_store_reg(rn, n, tmp);

                    } else {

                        /* VMOV */

                        switch (size) {

                        case 0:

                            tmp2 = neon_load_reg(rn, pass);

                            gen_bfi(tmp, tmp2, tmp, offset, 0xff);

                            dead_tmp(tmp2);

                            break;

                        case 1:

                            tmp2 = neon_load_reg(rn, pass);

                            gen_bfi(tmp, tmp2, tmp, offset, 0xffff);

                            dead_tmp(tmp2);

                            break;

                        case 2:

                            break;

                        }

                        neon_store_reg(rn, pass, tmp);

                    }

                }

            } else { /* !dp */

                if ((insn & 0x6f) != 0x00)

                    return 1;

                rn = VFP_SREG_N(insn);

                if (insn & ARM_CP_RW_BIT) {

                    /* vfp->arm */

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

                        /* system register */

                        rn >>= 1;

                        switch (rn) {

                        case ARM_VFP_FPSID:

                            /* VFP2 allows access to FSID from userspace.

                               VFP3 restricts all id registers to privileged

                               accesses.  */

                            if (IS_USER(s)

                                && arm_feature(env, ARM_FEATURE_VFP3))

                                return 1;

                            tmp = load_cpu_field(vfp.xregs[rn]);

                            break;

                        case ARM_VFP_FPEXC:

                            if (IS_USER(s))

                                return 1;

                            tmp = load_cpu_field(vfp.xregs[rn]);

                            break;

                        case ARM_VFP_FPINST:

                        case ARM_VFP_FPINST2:

                            /* Not present in VFP3.  */

                            if (IS_USER(s)

                                || arm_feature(env, ARM_FEATURE_VFP3))

                                return 1;

                            tmp = load_cpu_field(vfp.xregs[rn]);

                            break;

                        case ARM_VFP_FPSCR:

                            if (rd == 15) {

                                tmp = load_cpu_field(vfp.xregs[ARM_VFP_FPSCR]);

                                tcg_gen_andi_i32(tmp, tmp, 0xf0000000);

                            } else {

                                tmp = new_tmp();

                                gen_helper_vfp_get_fpscr(tmp, cpu_env);

                            }

                            break;

                        case ARM_VFP_MVFR0:

                        case ARM_VFP_MVFR1:

                            if (IS_USER(s)

                                || !arm_feature(env, ARM_FEATURE_VFP3))

                                return 1;

                            tmp = load_cpu_field(vfp.xregs[rn]);

                            break;

                        default:

                            return 1;

                        }

                    } else {

                        gen_mov_F0_vreg(0, rn);

                        tmp = gen_vfp_mrs();

                    }

                    if (rd == 15) {

                        /* Set the 4 flag bits in the CPSR.  */

                        gen_set_nzcv(tmp);

                        dead_tmp(tmp);

                    } else {

                        store_reg(s, rd, tmp);

                    }

                } else {

                    /* arm->vfp */

                    tmp = load_reg(s, rd);

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

                        rn >>= 1;

                        /* system register */

                        switch (rn) {

                        case ARM_VFP_FPSID:

                        case ARM_VFP_MVFR0:

                        case ARM_VFP_MVFR1:

                            /* Writes are ignored.  */

                            break;

                        case ARM_VFP_FPSCR:

                            gen_helper_vfp_set_fpscr(cpu_env, tmp);

                            dead_tmp(tmp);

                            gen_lookup_tb(s);

                            break;

                        case ARM_VFP_FPEXC:

                            if (IS_USER(s))

                                return 1;

                            store_cpu_field(tmp, vfp.xregs[rn]);

                            gen_lookup_tb(s);

                            break;

                        case ARM_VFP_FPINST:

                        case ARM_VFP_FPINST2:

                            store_cpu_field(tmp, vfp.xregs[rn]);

                            break;

                        default:

                            return 1;

                        }

                    } else {

                        gen_vfp_msr(tmp);

                        gen_mov_vreg_F0(0, rn);

                    }

                }

            }

        } else {

            /* data processing */

            /* The opcode is in bits 23, 21, 20 and 6.  */

            op = ((insn >> 20) & 8) | ((insn >> 19) & 6) | ((insn >> 6) & 1);

            if (dp) {

                if (op == 15) {

                    /* rn is opcode */

                    rn = ((insn >> 15) & 0x1e) | ((insn >> 7) & 1);

                } else {

                    /* rn is register number */

                    VFP_DREG_N(rn, insn);

                }

                if (op == 15 && (rn == 15 || rn > 17)) {

                    /* Integer or single precision destination.  */

                    rd = VFP_SREG_D(insn);

                } else {

                    VFP_DREG_D(rd, insn);

                }

                if (op == 15 && (rn == 16 || rn == 17)) {

                    /* Integer source.  */

                    rm = ((insn << 1) & 0x1e) | ((insn >> 5) & 1);

                } else {

                    VFP_DREG_M(rm, insn);

                }

            } else {

                rn = VFP_SREG_N(insn);

                if (op == 15 && rn == 15) {

                    /* Double precision destination.  */

                    VFP_DREG_D(rd, insn);

                } else {

                    rd = VFP_SREG_D(insn);

                }

                rm = VFP_SREG_M(insn);

            }

            veclen = env->vfp.vec_len;

            if (op == 15 && rn > 3)

                veclen = 0;

            /* Shut up compiler warnings.  */

            delta_m = 0;

            delta_d = 0;

            bank_mask = 0;

            if (veclen > 0) {

                if (dp)

                    bank_mask = 0xc;

                else

                    bank_mask = 0x18;

                /* Figure out what type of vector operation this is.  */

                if ((rd & bank_mask) == 0) {

                    /* scalar */

                    veclen = 0;

                } else {

                    if (dp)

                        delta_d = (env->vfp.vec_stride >> 1) + 1;

                    else

                        delta_d = env->vfp.vec_stride + 1;

                    if ((rm & bank_mask) == 0) {

                        /* mixed scalar/vector */

                        delta_m = 0;

                    } else {

                        /* vector */

                        delta_m = delta_d;

                    }

                }

            }

            /* Load the initial operands.  */

            if (op == 15) {

                switch (rn) {

                case 16:

                case 17:

                    /* Integer source */

                    gen_mov_F0_vreg(0, rm);

                    break;

                case 8:

                case 9:

                    /* Compare */

                    gen_mov_F0_vreg(dp, rd);

                    gen_mov_F1_vreg(dp, rm);

                    break;

                case 10:

                case 11:

                    /* Compare with zero */

                    gen_mov_F0_vreg(dp, rd);

                    gen_vfp_F1_ld0(dp);

                    break;

                case 20:

                case 21:

                case 22:

                case 23:

                case 28:

                case 29:

                case 30:

                case 31:

                    /* Source and destination the same.  */

                    gen_mov_F0_vreg(dp, rd);

                    break;

                default:

                    /* One source operand.  */

                    gen_mov_F0_vreg(dp, rm);

                    break;

                }

            } else {

                /* Two source operands.  */

                gen_mov_F0_vreg(dp, rn);

                gen_mov_F1_vreg(dp, rm);

            }

            for (;;) {

                /* Perform the calculation.  */

                switch (op) {

                case 0: /* mac: fd + (fn * fm) */

                    gen_vfp_mul(dp);

                    gen_mov_F1_vreg(dp, rd);

                    gen_vfp_add(dp);

                    break;

                case 1: /* nmac: fd - (fn * fm) */

                    gen_vfp_mul(dp);

                    gen_vfp_neg(dp);

                    gen_mov_F1_vreg(dp, rd);

                    gen_vfp_add(dp);

                    break;

                case 2: /* msc: -fd + (fn * fm) */

                    gen_vfp_mul(dp);

                    gen_mov_F1_vreg(dp, rd);

                    gen_vfp_sub(dp);

                    break;

                case 3: /* nmsc: -fd - (fn * fm)  */

                    gen_vfp_mul(dp);

                    gen_vfp_neg(dp);

                    gen_mov_F1_vreg(dp, rd);

                    gen_vfp_sub(dp);

                    break;

                case 4: /* mul: fn * fm */

                    gen_vfp_mul(dp);

                    break;

                case 5: /* nmul: -(fn * fm) */

                    gen_vfp_mul(dp);

                    gen_vfp_neg(dp);

                    break;

                case 6: /* add: fn + fm */

                    gen_vfp_add(dp);

                    break;

                case 7: /* sub: fn - fm */

                    gen_vfp_sub(dp);

                    break;

                case 8: /* div: fn / fm */

                    gen_vfp_div(dp);

                    break;

                case 14: /* fconst */

                    if (!arm_feature(env, ARM_FEATURE_VFP3))

                      return 1;

                    n = (insn << 12) & 0x80000000;

                    i = ((insn >> 12) & 0x70) | (insn & 0xf);

                    if (dp) {

                        if (i & 0x40)

                            i |= 0x3f80;

                        else

                            i |= 0x4000;

                        n |= i << 16;

                        tcg_gen_movi_i64(cpu_F0d, ((uint64_t)n) << 32);

                    } else {

                        if (i & 0x40)

                            i |= 0x780;

                        else

                            i |= 0x800;

                        n |= i << 19;

                        tcg_gen_movi_i32(cpu_F0s, n);

                    }

                    break;

                case 15: /* extension space */

                    switch (rn) {

                    case 0: /* cpy */

                        /* no-op */

                        break;

                    case 1: /* abs */

                        gen_vfp_abs(dp);

                        break;

                    case 2: /* neg */

                        gen_vfp_neg(dp);

                        break;

                    case 3: /* sqrt */

                        gen_vfp_sqrt(dp);

                        break;

                    case 8: /* cmp */

                        gen_vfp_cmp(dp);

                        break;

                    case 9: /* cmpe */

                        gen_vfp_cmpe(dp);

                        break;

                    case 10: /* cmpz */

                        gen_vfp_cmp(dp);

                        break;

                    case 11: /* cmpez */

                        gen_vfp_F1_ld0(dp);

                        gen_vfp_cmpe(dp);

                        break;

                    case 15: /* single<->double conversion */

                        if (dp)

                            gen_helper_vfp_fcvtsd(cpu_F0s, cpu_F0d, cpu_env);

                        else

                            gen_helper_vfp_fcvtds(cpu_F0d, cpu_F0s, cpu_env);

                        break;

                    case 16: /* fuito */

                        gen_vfp_uito(dp);

                        break;

                    case 17: /* fsito */

                        gen_vfp_sito(dp);

                        break;

                    case 20: /* fshto */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_shto(dp, 16 - rm);

                        break;

                    case 21: /* fslto */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_slto(dp, 32 - rm);

                        break;

                    case 22: /* fuhto */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_uhto(dp, 16 - rm);

                        break;

                    case 23: /* fulto */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_ulto(dp, 32 - rm);

                        break;

                    case 24: /* ftoui */

                        gen_vfp_toui(dp);

                        break;

                    case 25: /* ftouiz */

                        gen_vfp_touiz(dp);

                        break;

                    case 26: /* ftosi */

                        gen_vfp_tosi(dp);

                        break;

                    case 27: /* ftosiz */

                        gen_vfp_tosiz(dp);

                        break;

                    case 28: /* ftosh */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_tosh(dp, 16 - rm);

                        break;

                    case 29: /* ftosl */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_tosl(dp, 32 - rm);

                        break;

                    case 30: /* ftouh */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_touh(dp, 16 - rm);

                        break;

                    case 31: /* ftoul */

                        if (!arm_feature(env, ARM_FEATURE_VFP3))

                          return 1;

                        gen_vfp_toul(dp, 32 - rm);

                        break;

                    default: /* undefined */

                        printf ("rn:%d\n", rn);

                        return 1;

                    }

                    break;

                default: /* undefined */

                    printf ("op:%d\n", op);

                    return 1;

                }

                /* Write back the result.  */

                if (op == 15 && (rn >= 8 && rn <= 11))

                    ; /* Comparison, do nothing.  */

                else if (op == 15 && rn > 17)

                    /* Integer result.  */

                    gen_mov_vreg_F0(0, rd);

                else if (op == 15 && rn == 15)

                    /* conversion */

                    gen_mov_vreg_F0(!dp, rd);

                else

                    gen_mov_vreg_F0(dp, rd);

                /* break out of the loop if we have finished  */

                if (veclen == 0)

                    break;

                if (op == 15 && delta_m == 0) {

                    /* single source one-many */

                    while (veclen--) {

                        rd = ((rd + delta_d) & (bank_mask - 1))

                             | (rd & bank_mask);

                        gen_mov_vreg_F0(dp, rd);

                    }

                    break;

                }

                /* Setup the next operands.  */

                veclen--;

                rd = ((rd + delta_d) & (bank_mask - 1))

                     | (rd & bank_mask);

                if (op == 15) {

                    /* One source operand.  */

                    rm = ((rm + delta_m) & (bank_mask - 1))

                         | (rm & bank_mask);

                    gen_mov_F0_vreg(dp, rm);

                } else {

                    /* Two source operands.  */

                    rn = ((rn + delta_d) & (bank_mask - 1))

                         | (rn & bank_mask);

                    gen_mov_F0_vreg(dp, rn);

                    if (delta_m) {

                        rm = ((rm + delta_m) & (bank_mask - 1))

                             | (rm & bank_mask);

                        gen_mov_F1_vreg(dp, rm);

                    }

                }

            }

        }

        break;

    case 0xc:

    case 0xd:

        if (dp && (insn & 0x03e00000) == 0x00400000) {

            /* two-register transfer */

            rn = (insn >> 16) & 0xf;

            rd = (insn >> 12) & 0xf;

            if (dp) {

                VFP_DREG_M(rm, insn);

            } else {

                rm = VFP_SREG_M(insn);

            }

            if (insn & ARM_CP_RW_BIT) {

                /* vfp->arm */

                if (dp) {

                    gen_mov_F0_vreg(0, rm * 2);

                    tmp = gen_vfp_mrs();

                    store_reg(s, rd, tmp);

                    gen_mov_F0_vreg(0, rm * 2 + 1);

                    tmp = gen_vfp_mrs();

                    store_reg(s, rn, tmp);

                } else {

                    gen_mov_F0_vreg(0, rm);

                    tmp = gen_vfp_mrs();

                    store_reg(s, rn, tmp);

                    gen_mov_F0_vreg(0, rm + 1);

                    tmp = gen_vfp_mrs();

                    store_reg(s, rd, tmp);

                }

            } else {

                /* arm->vfp */

                if (dp) {

                    tmp = load_reg(s, rd);

                    gen_vfp_msr(tmp);

                    gen_mov_vreg_F0(0, rm * 2);

                    tmp = load_reg(s, rn);

                    gen_vfp_msr(tmp);

                    gen_mov_vreg_F0(0, rm * 2 + 1);

                } else {

                    tmp = load_reg(s, rn);

                    gen_vfp_msr(tmp);

                    gen_mov_vreg_F0(0, rm);

                    tmp = load_reg(s, rd);

                    gen_vfp_msr(tmp);

                    gen_mov_vreg_F0(0, rm + 1);

                }

            }

        } else {

            /* Load/store */

            rn = (insn >> 16) & 0xf;

            if (dp)

                VFP_DREG_D(rd, insn);

            else

                rd = VFP_SREG_D(insn);

            if (s->thumb && rn == 15) {

                addr = new_tmp();

                tcg_gen_movi_i32(addr, s->pc & ~2);

            } else {

                addr = load_reg(s, rn);

            }

            if ((insn & 0x01200000) == 0x01000000) {

                /* Single load/store */

                offset = (insn & 0xff) << 2;

                if ((insn & (1 << 23)) == 0)

                    offset = -offset;

                tcg_gen_addi_i32(addr, addr, offset);

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

                    gen_vfp_ld(s, dp, addr);

                    gen_mov_vreg_F0(dp, rd);

                } else {

                    gen_mov_F0_vreg(dp, rd);

                    gen_vfp_st(s, dp, addr);

                }

                dead_tmp(addr);

            } else {

                /* load/store multiple */

                if (dp)

                    n = (insn >> 1) & 0x7f;

                else

                    n = insn & 0xff;

                if (insn & (1 << 24)) /* pre-decrement */

                    tcg_gen_addi_i32(addr, addr, -((insn & 0xff) << 2));

                if (dp)

                    offset = 8;

                else

                    offset = 4;

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

                    if (insn & ARM_CP_RW_BIT) {

                        /* load */

                        gen_vfp_ld(s, dp, addr);

                        gen_mov_vreg_F0(dp, rd + i);

                    } else {

                        /* store */

                        gen_mov_F0_vreg(dp, rd + i);

                        gen_vfp_st(s, dp, addr);

                    }

                    tcg_gen_addi_i32(addr, addr, offset);

                }

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

                    /* writeback */

                    if (insn & (1 << 24))

                        offset = -offset * n;

                    else if (dp && (insn & 1))

                        offset = 4;

                    else

                        offset = 0;

                    if (offset != 0)

                        tcg_gen_addi_i32(addr, addr, offset);

                    store_reg(s, rn, addr);

                } else {

                    dead_tmp(addr);

                }

            }

        }

        break;

    default:

        /* Should never happen.  */

        return 1;

    }

    return 0;

}


void drive_hot_add(Monitor *mon, const QDict *qdict)

{

    int dom, pci_bus;

    unsigned slot;

    int type, bus;

    PCIDevice *dev;

    DriveInfo *dinfo = NULL;

    const char *pci_addr = qdict_get_str(qdict, "pci_addr");

    const char *opts = qdict_get_str(qdict, "opts");

    BusState *scsibus;

    dinfo = add_init_drive(opts);

    if (!dinfo)

        goto err;

    if (dinfo->devaddr) {

        monitor_printf(mon, "Parameter addr not supported\n");

        goto err;

    }

    type = dinfo->type;

    bus = drive_get_max_bus (type);

    switch (type) {

    case IF_SCSI:

        if (pci_read_devaddr(mon, pci_addr, &dom, &pci_bus, &slot)) {

            goto err;

        }

        dev = pci_find_device(pci_bus, slot, 0);

        if (!dev) {

            monitor_printf(mon, "no pci device with address %s\n", pci_addr);

            goto err;

        }

        scsibus = QLIST_FIRST(&dev->qdev.child_bus);

        scsi_bus_legacy_add_drive(DO_UPCAST(SCSIBus, qbus, scsibus),

                                  dinfo, dinfo->unit);

        monitor_printf(mon, "OK bus %d, unit %d\n",

                       dinfo->bus,

                       dinfo->unit);

        break;

    case IF_NONE:

        monitor_printf(mon, "OK\n");

        break;

    default:

        monitor_printf(mon, "Can't hot-add drive to type %d\n", type);

        goto err;

    }

    return;

err:

    if (dinfo)

        drive_uninit(dinfo);

    return;

}


static inline int msmpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded)

{

    int level, i, last, run, run_diff;

    int dc_pred_dir;

    RLTable *rl;

    RL_VLC_ELEM *rl_vlc;

    const UINT8 *scan_table;

    int qmul, qadd;

    if (s->mb_intra) {

        qmul=1;

        qadd=0;

	/* DC coef */

        set_stat(ST_DC);

        level = msmpeg4_decode_dc(s, n, &dc_pred_dir);

#ifdef PRINT_MB

{

    static int c;

    if(n==0) c=0;

    if(n==4) printf("%X", c);

    c+= c +dc_pred_dir;

}

#endif

        if (level < 0){

            fprintf(stderr, "dc overflow- block: %d qscale: %d//\n", n, s->qscale);

            if(s->inter_intra_pred) level=0;

            else                    return -1;

        }

        if (n < 4) {

            rl = &rl_table[s->rl_table_index];

            if(level > 256*s->y_dc_scale){

                fprintf(stderr, "dc overflow+ L qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        } else {

            rl = &rl_table[3 + s->rl_chroma_table_index];

            if(level > 256*s->c_dc_scale){

                fprintf(stderr, "dc overflow+ C qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        }

        block[0] = level;

        run_diff = 0;

        i = 0;

        if (!coded) {

            goto not_coded;

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable; /* left */

            else

                scan_table = s->intra_h_scantable; /* top */

        } else {

            scan_table = s->intra_scantable;

        }

        set_stat(ST_INTRA_AC);

        rl_vlc= rl->rl_vlc[0];

    } else {

        qmul = s->qscale << 1;

        qadd = (s->qscale - 1) | 1;

        i = -1;

        rl = &rl_table[3 + s->rl_table_index];

        if(s->msmpeg4_version==2)

            run_diff = 0;

        else

            run_diff = 1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        scan_table = s->inter_scantable;

        set_stat(ST_INTER_AC);

        rl_vlc= rl->rl_vlc[s->qscale];

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

        if (level==0) {

            int cache;

            cache= GET_CACHE(re, &s->gb);

            /* escape */

            if (s->msmpeg4_version==1 || (cache&0x80000000)==0) {

                if (s->msmpeg4_version==1 || (cache&0x40000000)==0) {

                    /* third escape */

                    if(s->msmpeg4_version!=1) LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

                    if(s->msmpeg4_version<=3){

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                        run=   SHOW_UBITS(re, &s->gb, 6); SKIP_CACHE(re, &s->gb, 6);

                        level= SHOW_SBITS(re, &s->gb, 8); LAST_SKIP_CACHE(re, &s->gb, 8);

                        SKIP_COUNTER(re, &s->gb, 1+6+8);

                    }else{

                        int sign;

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_BITS(re, &s->gb, 1);

                        if(!s->esc3_level_length){

                            int ll;

                            //printf("ESC-3 %X at %d %d\n", show_bits(&s->gb, 24), s->mb_x, s->mb_y);

                            if(s->qscale<8){

                                ll= SHOW_UBITS(re, &s->gb, 3); SKIP_BITS(re, &s->gb, 3);

                                if(ll==0){

                                    if(SHOW_UBITS(re, &s->gb, 1)) printf("cool a new vlc code ,contact the ffmpeg developers and upload the file\n");

                                    SKIP_BITS(re, &s->gb, 1);

                                    ll=8;

                                }

                            }else{

                                ll=2;

                                while(ll<8 && SHOW_UBITS(re, &s->gb, 1)==0){

                                    ll++;

                                    SKIP_BITS(re, &s->gb, 1);

                                }

                                if(ll<8) SKIP_BITS(re, &s->gb, 1);

                            }

                            s->esc3_level_length= ll;

                            s->esc3_run_length= SHOW_UBITS(re, &s->gb, 2) + 3; SKIP_BITS(re, &s->gb, 2);

//printf("level length:%d, run length: %d\n", ll, s->esc3_run_length);

                            UPDATE_CACHE(re, &s->gb);

                        }

                        run=   SHOW_UBITS(re, &s->gb, s->esc3_run_length);

                        SKIP_BITS(re, &s->gb, s->esc3_run_length);

                        sign=  SHOW_UBITS(re, &s->gb, 1);

                        SKIP_BITS(re, &s->gb, 1);

                        level= SHOW_UBITS(re, &s->gb, s->esc3_level_length);

                        SKIP_BITS(re, &s->gb, s->esc3_level_length);

                        if(sign) level= -level;

                    }

//printf("level: %d, run: %d at %d %d\n", level, run, s->mb_x, s->mb_y);

#if 0 // waste of time / this will detect very few errors

                    {

                        const int abs_level= ABS(level);

                        const int run1= run - rl->max_run[last][abs_level] - run_diff;

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            if(abs_level <= rl->max_level[last][run]){

                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(abs_level <= rl->max_level[last][run]*2){

                                fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(run1>=0 && abs_level <= rl->max_level[last][run1]){

                                fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                        }

                    }

#endif

		    //level = level * qmul + (level>0) * qadd - (level<=0) * qadd ;

		    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

#if 0 // waste of time too :(

                    if(level>2048 || level<-2048){

                        fprintf(stderr, "|level| overflow in 3. esc\n");

                        return DECODING_AC_LOST;

                    }

#endif

                    i+= run + 1;

                    if(last) i+=192;

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC3 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC3 i=%d run=%d level=%d\n", i, run, level);

#endif

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 23

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                    i+= run + rl->max_run[run>>7][level/qmul] + run_diff; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC2 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC2 i=%d run=%d level=%d\n", i, run, level);

#endif

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 22

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC1 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC1 i=%d run=%d level=%d\n", i, run, level);

#endif

            }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow i=%d run=%d level=%d\n", i, run, level);

#endif

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                if(s->error_resilience<0){

                    fprintf(stderr, "ignoring overflow at %d %d\n", s->mb_x, s->mb_y);

                    break;

                }else{

                    fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                    return -1;

                }

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (s->mb_intra) {

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    if(s->msmpeg4_version==4 && i>0) i=63; //FIXME/XXX optimize

    s->block_last_index[n] = i;

    return 0;

}


static int usb_device_post_load(void *opaque, int version_id)

{

    USBDevice *dev = opaque;

    if (dev->state == USB_STATE_NOTATTACHED) {

        dev->attached = 0;

    } else {

        dev->attached = 1;

    return 0;


int inet_listen_opts(QemuOpts *opts, int port_offset, Error **errp)

{

    struct addrinfo ai,*res,*e;

    const char *addr;

    char port[33];

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int slisten, rc, to, port_min, port_max, p;

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

    ai.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    if ((qemu_opt_get(opts, "host") == NULL) ||

        (qemu_opt_get(opts, "port") == NULL)) {

        error_setg(errp, "host and/or port not specified");

        return -1;

    }

    pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));

    addr = qemu_opt_get(opts, "host");

    to = qemu_opt_get_number(opts, "to", 0);

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    /* lookup */

    if (port_offset) {

        unsigned long long baseport;

        if (parse_uint_full(port, &baseport, 10) < 0) {

            error_setg(errp, "can't convert to a number: %s", port);

            return -1;

        }

        if (baseport > 65535 ||

            baseport + port_offset > 65535) {

            error_setg(errp, "port %s out of range", port);

            return -1;

        }

        snprintf(port, sizeof(port), "%d", (int)baseport + port_offset);

    }

    rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);

    if (rc != 0) {

        error_setg(errp, "address resolution failed for %s:%s: %s", addr, port,

                   gai_strerror(rc));

        return -1;

    }

    /* create socket + bind */

    for (e = res; e != NULL; e = e->ai_next) {

        getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

		        uaddr,INET6_ADDRSTRLEN,uport,32,

		        NI_NUMERICHOST | NI_NUMERICSERV);

        slisten = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (slisten < 0) {

            if (!e->ai_next) {

                error_setg_errno(errp, errno, "Failed to create socket");

            }

            continue;

        }

        socket_set_fast_reuse(slisten);

#ifdef IPV6_V6ONLY

        if (e->ai_family == PF_INET6) {

            /* listen on both ipv4 and ipv6 */

            const int off = 0;

            qemu_setsockopt(slisten, IPPROTO_IPV6, IPV6_V6ONLY, &off,

                            sizeof(off));

        }

#endif

        port_min = inet_getport(e);

        port_max = to ? to + port_offset : port_min;

        for (p = port_min; p <= port_max; p++) {

            inet_setport(e, p);

            if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {

                goto listen;

            }

            if (p == port_max) {

                if (!e->ai_next) {

                    error_setg_errno(errp, errno, "Failed to bind socket");

                }

            }

        }

        closesocket(slisten);

    }

    freeaddrinfo(res);

    return -1;

listen:

    if (listen(slisten,1) != 0) {

        error_setg_errno(errp, errno, "Failed to listen on socket");

        closesocket(slisten);

        freeaddrinfo(res);

        return -1;

    }

    qemu_opt_set(opts, "host", uaddr, &error_abort);

    qemu_opt_set_number(opts, "port", inet_getport(e) - port_offset,

                        &error_abort);

    qemu_opt_set_bool(opts, "ipv6", e->ai_family == PF_INET6,

                      &error_abort);

    qemu_opt_set_bool(opts, "ipv4", e->ai_family != PF_INET6,

                      &error_abort);

    freeaddrinfo(res);

    return slisten;

}


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

{

    OMAContext *oc  = s->priv_data;

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

    int packet_size = st->codec->block_align;

    int byte_rate   = st->codec->bit_rate >> 3;

    int64_t pos     = avio_tell(s->pb);

    int ret         = av_get_packet(s->pb, pkt, packet_size);

    if (ret < packet_size)

        pkt->flags |= AV_PKT_FLAG_CORRUPT;

    if (ret < 0)

        return ret;

    if (!ret)

        return AVERROR_EOF;

    pkt->stream_index = 0;

    if (pos > 0) {

        pkt->pts =

        pkt->dts = av_rescale(pos, st->time_base.den,

                              byte_rate * (int64_t)st->time_base.num);

    }

    if (oc->encrypted) {

        /* previous unencrypted block saved in IV for

         * the next packet (CBC mode) */

        if (ret == packet_size)

            av_des_crypt(&oc->av_des, pkt->data, pkt->data,

                         (packet_size >> 3), oc->iv, 1);

        else

            memset(oc->iv, 0, 8);

    }

    return ret;

}


void av_opt_set_defaults2(void *s, int mask, int flags)

{

#endif

    const AVOption *opt = NULL;

    while ((opt = av_opt_next(s, opt)) != NULL) {

#if FF_API_OLD_AVOPTIONS

        if ((opt->flags & mask) != flags)

            continue;

#endif

        switch (opt->type) {

            case AV_OPT_TYPE_CONST:

                /* Nothing to be done here */

            break;

            case AV_OPT_TYPE_FLAGS:

            case AV_OPT_TYPE_INT:

            case AV_OPT_TYPE_INT64:

                av_opt_set_int(s, opt->name, opt->default_val.i64, 0);

            break;

            case AV_OPT_TYPE_DOUBLE:

            case AV_OPT_TYPE_FLOAT: {

                double val;

                val = opt->default_val.dbl;

                av_opt_set_double(s, opt->name, val, 0);

            }

            break;

            case AV_OPT_TYPE_RATIONAL: {

                AVRational val;

                val = av_d2q(opt->default_val.dbl, INT_MAX);

                av_opt_set_q(s, opt->name, val, 0);

            }

            break;

            case AV_OPT_TYPE_STRING:

            case AV_OPT_TYPE_IMAGE_SIZE:

            case AV_OPT_TYPE_PIXEL_FMT:

            case AV_OPT_TYPE_SAMPLE_FMT:

                av_opt_set(s, opt->name, opt->default_val.str, 0);

                break;

            case AV_OPT_TYPE_BINARY:

                /* Cannot set default for binary */

            break;

            default:

                av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n", opt->type, opt->name);

        }

    }

}


static int RENAME(resample_common)(ResampleContext *c,

                                   void *dest, const void *source,

                                   int n, int update_ctx)

{

    DELEM *dst = dest;

    const DELEM *src = source;

    int dst_index;

    int index= c->index;

    int frac= c->frac;

    int sample_index = 0;

    while (index >= c->phase_count) {

        sample_index++;

        index -= c->phase_count;

    }

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

        FELEM *filter = ((FELEM *) c->filter_bank) + c->filter_alloc * index;

        FELEM2 val= FOFFSET;

        int i;

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

            val += src[sample_index + i] * (FELEM2)filter[i];

        }

        OUT(dst[dst_index], val);

        frac  += c->dst_incr_mod;

        index += c->dst_incr_div;

        if (frac >= c->src_incr) {

            frac -= c->src_incr;

            index++;

        }

        while (index >= c->phase_count) {

            sample_index++;

            index -= c->phase_count;

        }

    }

    if(update_ctx){

        c->frac= frac;

        c->index= index;

    }

    return sample_index;

}


BdrvNextIterator *bdrv_next(BdrvNextIterator *it, BlockDriverState **bs)

{

    if (!it) {

        it = g_new(BdrvNextIterator, 1);

        *it = (BdrvNextIterator) {

            .phase = BDRV_NEXT_BACKEND_ROOTS,

        };

    }

    /* First, return all root nodes of BlockBackends. In order to avoid

     * returning a BDS twice when multiple BBs refer to it, we only return it

     * if the BB is the first one in the parent list of the BDS. */

    if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {

        do {

            it->blk = blk_all_next(it->blk);

            *bs = it->blk ? blk_bs(it->blk) : NULL;

        } while (it->blk && (*bs == NULL || bdrv_first_blk(*bs) != it->blk));

        if (*bs) {

            return it;

        }

        it->phase = BDRV_NEXT_MONITOR_OWNED;

    }

    /* Then return the monitor-owned BDSes without a BB attached. Ignore all

     * BDSes that are attached to a BlockBackend here; they have been handled

     * by the above block already */

    do {

        it->bs = bdrv_next_monitor_owned(it->bs);

        *bs = it->bs;

    } while (*bs && bdrv_has_blk(*bs));

    return *bs ? it : NULL;

}


static int channelmap_filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)

{

    AVFilterContext  *ctx = inlink->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    const ChannelMapContext *s = ctx->priv;

    const int nch_in = av_get_channel_layout_nb_channels(inlink->channel_layout);

    const int nch_out = s->nch;

    int ch;

    uint8_t *source_planes[MAX_CH];

    memcpy(source_planes, buf->extended_data,

           nch_in * sizeof(source_planes[0]));

    if (nch_out > nch_in) {

        if (nch_out > FF_ARRAY_ELEMS(buf->data)) {

            uint8_t **new_extended_data =

                av_mallocz(nch_out * sizeof(*buf->extended_data));

            if (!new_extended_data) {

                avfilter_unref_buffer(buf);

                return AVERROR(ENOMEM);

            }

            if (buf->extended_data == buf->data) {

                buf->extended_data = new_extended_data;

            } else {

                buf->extended_data = new_extended_data;

                av_free(buf->extended_data);

            }

        } else if (buf->extended_data != buf->data) {

            av_free(buf->extended_data);

            buf->extended_data = buf->data;

        }

    }

    for (ch = 0; ch < nch_out; ch++) {

        buf->extended_data[s->map[ch].out_channel_idx] =

            source_planes[s->map[ch].in_channel_idx];

    }

    if (buf->data != buf->extended_data)

        memcpy(buf->data, buf->extended_data,

           FFMIN(FF_ARRAY_ELEMS(buf->data), nch_out) * sizeof(buf->data[0]));

    return ff_filter_samples(outlink, buf);

}