static void av_estimate_timings_from_pts(AVFormatContext *ic)

{

    AVPacket pkt1, *pkt = &pkt1;

    AVStream *st;

    int read_size, i, ret;

    int64_t end_time;

    int64_t filesize, offset, duration;

    /* free previous packet */

    if (ic->cur_st && ic->cur_st->parser)

        av_free_packet(&ic->cur_pkt);

    ic->cur_st = NULL;

    /* flush packet queue */

    flush_packet_queue(ic);

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

        st = ic->streams[i];

        if (st->parser) {

            av_parser_close(st->parser);

            st->parser= NULL;

        }

    }

    /* we read the first packets to get the first PTS (not fully

       accurate, but it is enough now) */

    url_fseek(&ic->pb, 0, SEEK_SET);

    read_size = 0;

    for(;;) {

        if (read_size >= DURATION_MAX_READ_SIZE)

            break;

        /* if all info is available, we can stop */

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

            st = ic->streams[i];

            if (st->start_time == AV_NOPTS_VALUE)

                break;

        }

        if (i == ic->nb_streams)

            break;

        ret = av_read_packet(ic, pkt);

        if (ret != 0)

            break;

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if (pkt->pts != AV_NOPTS_VALUE) {

            if (st->start_time == AV_NOPTS_VALUE)

                st->start_time = pkt->pts;

        }

        av_free_packet(pkt);

    }

    /* estimate the end time (duration) */

    /* XXX: may need to support wrapping */

    filesize = ic->file_size;

    offset = filesize - DURATION_MAX_READ_SIZE;

    if (offset < 0)

        offset = 0;

    url_fseek(&ic->pb, offset, SEEK_SET);

    read_size = 0;

    for(;;) {

        if (read_size >= DURATION_MAX_READ_SIZE)

            break;

        /* if all info is available, we can stop */

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

            st = ic->streams[i];

            if (st->duration == AV_NOPTS_VALUE)

                break;

        }

        if (i == ic->nb_streams)

            break;

        ret = av_read_packet(ic, pkt);

        if (ret != 0)

            break;

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if (pkt->pts != AV_NOPTS_VALUE) {

            end_time = pkt->pts;

            duration = end_time - st->start_time;

            if (duration > 0) {

                if (st->duration == AV_NOPTS_VALUE ||

                    st->duration < duration)

                    st->duration = duration;

            }

        }

        av_free_packet(pkt);

    }

    fill_all_stream_timings(ic);

    url_fseek(&ic->pb, 0, SEEK_SET);

}


static int vmdaudio_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 uint8_t *buf, int buf_size)

{

    VmdAudioContext *s = (VmdAudioContext *)avctx->priv_data;

    unsigned int sound_flags;

    unsigned char *output_samples = (unsigned char *)data;

    /* point to the start of the encoded data */

    unsigned char *p = buf + 16;

    unsigned char *p_end = buf + buf_size;

    if (buf_size < 16)

        return buf_size;

    if (buf[6] == 1) {

        /* the chunk contains audio */

        *data_size = vmdaudio_loadsound(s, output_samples, p, 0);

    } else if (buf[6] == 2) {

        /* the chunk contains audio and silence mixed together */

        sound_flags = LE_32(p);

        p += 4;

        /* do something with extrabufs here? */

        while (p < p_end) {

            if (sound_flags & 0x01)

                /* silence */

                *data_size += vmdaudio_loadsound(s, output_samples, p, 1);

            else {

                /* audio */

                *data_size += vmdaudio_loadsound(s, output_samples, p, 0);

                p += s->block_align;

            }

            output_samples += (s->block_align * s->bits / 8);

            sound_flags >>= 1;

        }

    } else if (buf[6] == 3) {

        /* silent chunk */

        *data_size = vmdaudio_loadsound(s, output_samples, p, 1);

    }

    return buf_size;

}


static void scsi_write_same_complete(void *opaque, int ret)

{

    WriteSameCBData *data = opaque;

    SCSIDiskReq *r = data->r;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    assert(r->req.aiocb != NULL);

    r->req.aiocb = NULL;

    aio_context_acquire(blk_get_aio_context(s->qdev.conf.blk));

    if (scsi_disk_req_check_error(r, ret, true)) {

        goto done;

    }

    block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct);

    data->nb_sectors -= data->iov.iov_len / 512;

    data->sector += data->iov.iov_len / 512;

    data->iov.iov_len = MIN(data->nb_sectors * 512, data->iov.iov_len);

    if (data->iov.iov_len) {

        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,

                         data->iov.iov_len, BLOCK_ACCT_WRITE);

        /* Reinitialize qiov, to handle unaligned WRITE SAME request

         * where final qiov may need smaller size */

        qemu_iovec_init_external(&data->qiov, &data->iov, 1);

        r->req.aiocb = blk_aio_pwritev(s->qdev.conf.blk,

                                       data->sector << BDRV_SECTOR_BITS,

                                       &data->qiov, 0,

                                       scsi_write_same_complete, data);

        return;

    }

    scsi_req_complete(&r->req, GOOD);

done:

    scsi_req_unref(&r->req);

    qemu_vfree(data->iov.iov_base);

    g_free(data);

}


PXA2xxState *pxa255_init(MemoryRegion *address_space, unsigned int sdram_size)

{

    PXA2xxState *s;

    int i;

    DriveInfo *dinfo;

    s = (PXA2xxState *) g_malloc0(sizeof(PXA2xxState));

    s->cpu = cpu_arm_init("pxa255");

    if (s->cpu == NULL) {

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

        exit(1);

    }

    s->reset = qemu_allocate_irq(pxa2xx_reset, s, 0);

    /* SDRAM & Internal Memory Storage */

    memory_region_init_ram(&s->sdram, NULL, "pxa255.sdram", sdram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->sdram);

    memory_region_add_subregion(address_space, PXA2XX_SDRAM_BASE, &s->sdram);

    memory_region_init_ram(&s->internal, NULL, "pxa255.internal",

                           PXA2XX_INTERNAL_SIZE, &error_abort);

    vmstate_register_ram_global(&s->internal);

    memory_region_add_subregion(address_space, PXA2XX_INTERNAL_BASE,

                                &s->internal);

    s->pic = pxa2xx_pic_init(0x40d00000, s->cpu);

    s->dma = pxa255_dma_init(0x40000000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_DMA));

    sysbus_create_varargs("pxa25x-timer", 0x40a00000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 0),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 1),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 2),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_OST_0 + 3),

                    NULL);

    s->gpio = pxa2xx_gpio_init(0x40e00000, s->cpu, s->pic, 85);

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = pxa2xx_mmci_init(address_space, 0x41100000,

                    blk_by_legacy_dinfo(dinfo),

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_MMC),

                    qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_MMCI),

                    qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_MMCI));

    for (i = 0; pxa255_serial[i].io_base; i++) {

        if (serial_hds[i]) {

            serial_mm_init(address_space, pxa255_serial[i].io_base, 2,

                           qdev_get_gpio_in(s->pic, pxa255_serial[i].irqn),

                           14745600 / 16, serial_hds[i],

                           DEVICE_NATIVE_ENDIAN);

        } else {

            break;

        }

    }

    if (serial_hds[i])

        s->fir = pxa2xx_fir_init(address_space, 0x40800000,

                        qdev_get_gpio_in(s->pic, PXA2XX_PIC_ICP),

                        qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_ICP),

                        qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_ICP),

                        serial_hds[i]);

    s->lcd = pxa2xx_lcdc_init(address_space, 0x44000000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_LCD));

    s->cm_base = 0x41300000;

    s->cm_regs[CCCR >> 2] = 0x02000210;	/* 416.0 MHz */

    s->clkcfg = 0x00000009;		/* Turbo mode active */

    memory_region_init_io(&s->cm_iomem, NULL, &pxa2xx_cm_ops, s, "pxa2xx-cm", 0x1000);

    memory_region_add_subregion(address_space, s->cm_base, &s->cm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_cm, s);

    pxa2xx_setup_cp14(s);

    s->mm_base = 0x48000000;

    s->mm_regs[MDMRS >> 2] = 0x00020002;

    s->mm_regs[MDREFR >> 2] = 0x03ca4000;

    s->mm_regs[MECR >> 2] = 0x00000001;	/* Two PC Card sockets */

    memory_region_init_io(&s->mm_iomem, NULL, &pxa2xx_mm_ops, s, "pxa2xx-mm", 0x1000);

    memory_region_add_subregion(address_space, s->mm_base, &s->mm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_mm, s);

    s->pm_base = 0x40f00000;

    memory_region_init_io(&s->pm_iomem, NULL, &pxa2xx_pm_ops, s, "pxa2xx-pm", 0x100);

    memory_region_add_subregion(address_space, s->pm_base, &s->pm_iomem);

    vmstate_register(NULL, 0, &vmstate_pxa2xx_pm, s);

    for (i = 0; pxa255_ssp[i].io_base; i ++);

    s->ssp = (SSIBus **)g_malloc0(sizeof(SSIBus *) * i);

    for (i = 0; pxa255_ssp[i].io_base; i ++) {

        DeviceState *dev;

        dev = sysbus_create_simple(TYPE_PXA2XX_SSP, pxa255_ssp[i].io_base,

                        qdev_get_gpio_in(s->pic, pxa255_ssp[i].irqn));

        s->ssp[i] = (SSIBus *)qdev_get_child_bus(dev, "ssi");

    }

    if (usb_enabled()) {

        sysbus_create_simple("sysbus-ohci", 0x4c000000,

                        qdev_get_gpio_in(s->pic, PXA2XX_PIC_USBH1));

    }

    s->pcmcia[0] = pxa2xx_pcmcia_init(address_space, 0x20000000);

    s->pcmcia[1] = pxa2xx_pcmcia_init(address_space, 0x30000000);

    sysbus_create_simple(TYPE_PXA2XX_RTC, 0x40900000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_RTCALARM));

    s->i2c[0] = pxa2xx_i2c_init(0x40301600,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2C), 0xffff);

    s->i2c[1] = pxa2xx_i2c_init(0x40f00100,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_PWRI2C), 0xff);

    s->i2s = pxa2xx_i2s_init(address_space, 0x40400000,

                    qdev_get_gpio_in(s->pic, PXA2XX_PIC_I2S),

                    qdev_get_gpio_in(s->dma, PXA2XX_RX_RQ_I2S),

                    qdev_get_gpio_in(s->dma, PXA2XX_TX_RQ_I2S));

    /* GPIO1 resets the processor */

    /* The handler can be overridden by board-specific code */

    qdev_connect_gpio_out(s->gpio, 1, s->reset);

    return s;

}


static int audio_open(AVFormatContext *s1, int is_output, const char *audio_device)

{

    AudioData *s = s1->priv_data;

    int audio_fd;

    int tmp, err;

    char *flip = getenv("AUDIO_FLIP_LEFT");

    if (is_output)

        audio_fd = avpriv_open(audio_device, O_WRONLY);

    else

        audio_fd = avpriv_open(audio_device, O_RDONLY);

    if (audio_fd < 0) {

        av_log(s1, AV_LOG_ERROR, "%s: %s\n", audio_device, strerror(errno));

        return AVERROR(EIO);

    }

    if (flip && *flip == '1') {

        s->flip_left = 1;

    }

    /* non blocking mode */

    if (!is_output) {

        if (fcntl(audio_fd, F_SETFL, O_NONBLOCK) < 0) {

            av_log(s1, AV_LOG_WARNING, "%s: Could not enable non block mode (%s)\n", audio_device, strerror(errno));

        }

    }

    s->frame_size = AUDIO_BLOCK_SIZE;

    /* select format : favour native format */

    err = ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &tmp);

#if HAVE_BIGENDIAN

    if (tmp & AFMT_S16_BE) {

        tmp = AFMT_S16_BE;

    } else if (tmp & AFMT_S16_LE) {

        tmp = AFMT_S16_LE;

    } else {

        tmp = 0;

    }

#else

    if (tmp & AFMT_S16_LE) {

        tmp = AFMT_S16_LE;

    } else if (tmp & AFMT_S16_BE) {

        tmp = AFMT_S16_BE;

    } else {

        tmp = 0;

    }

#endif

    switch(tmp) {

    case AFMT_S16_LE:

        s->codec_id = AV_CODEC_ID_PCM_S16LE;

        break;

    case AFMT_S16_BE:

        s->codec_id = AV_CODEC_ID_PCM_S16BE;

        break;

    default:

        av_log(s1, AV_LOG_ERROR, "Soundcard does not support 16 bit sample format\n");

        close(audio_fd);

        return AVERROR(EIO);

    }

    err=ioctl(audio_fd, SNDCTL_DSP_SETFMT, &tmp);

    if (err < 0) {

        av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_SETFMT: %s\n", strerror(errno));

        goto fail;

    }

    tmp = (s->channels == 2);

    err = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp);

    if (err < 0) {

        av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_STEREO: %s\n", strerror(errno));

        goto fail;

    }

    tmp = s->sample_rate;

    err = ioctl(audio_fd, SNDCTL_DSP_SPEED, &tmp);

    if (err < 0) {

        av_log(s1, AV_LOG_ERROR, "SNDCTL_DSP_SPEED: %s\n", strerror(errno));

        goto fail;

    }

    s->sample_rate = tmp; /* store real sample rate */

    s->fd = audio_fd;

    return 0;

 fail:

    close(audio_fd);

    return AVERROR(EIO);

}


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

{

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

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

    int ret;

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

    av_assert2(s->mb_skipped == 0);

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

        if (s->pict_type == AV_PICTURE_TYPE_P) {

            s->mb_skipped = 1;

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

                MB_TYPE_SKIP | MB_TYPE_L0 | MB_TYPE_16x16;

        } else {

            int mb_type;

            if (s->mb_x)

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

            else

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

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

            if (IS_INTRA(mb_type)) {

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

                return AVERROR_INVALIDDATA;

            }

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

                mb_type | MB_TYPE_SKIP;

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

                s->mb_skipped = 1;

        }

        return 0;

    }

    switch (s->pict_type) {

    default:

    case AV_PICTURE_TYPE_I:

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

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

                av_log(s->avctx, AV_LOG_ERROR,

                       "invalid mb type in I Frame at %d %d\n",

                       s->mb_x, s->mb_y);

                return AVERROR_INVALIDDATA;

            }

            mb_type = MB_TYPE_QUANT | MB_TYPE_INTRA;

        } else {

            mb_type = MB_TYPE_INTRA;

        }

        break;

    case AV_PICTURE_TYPE_P:

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

        if (mb_type < 0) {

            av_log(s->avctx, AV_LOG_ERROR,

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

            return AVERROR_INVALIDDATA;

        }

        mb_type = ptype2mb_type[mb_type];

        break;

    case AV_PICTURE_TYPE_B:

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

        if (mb_type < 0) {

            av_log(s->avctx, AV_LOG_ERROR,

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

            return AVERROR_INVALIDDATA;

        }

        mb_type = btype2mb_type[mb_type];

        break;

    }

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

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

    if (IS_INTRA(mb_type)) {

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

        if (!s->chroma_y_shift)

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

        /* compute DCT type */

        // FIXME: add an interlaced_dct coded var?

        if (s->picture_structure == PICT_FRAME &&

            !s->frame_pred_frame_dct)

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

        if (IS_QUANT(mb_type))

            s->qscale = get_qscale(s);

        if (s->concealment_motion_vectors) {

            /* just parse them */

            if (s->picture_structure != PICT_FRAME)

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

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

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

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

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

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

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

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

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

            skip_bits1(&s->gb); /* marker */

        } else {

            /* reset mv prediction */

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

        }

        s->mb_intra = 1;

        // if 1, we memcpy blocks in xvmcvideo

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

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

        if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

            if (s->flags2 & CODEC_FLAG2_FAST) {

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

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

            } else {

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

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

                        return ret;

            }

        } else {

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

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

                    return ret;

        }

    } else {

        if (mb_type & MB_TYPE_ZERO_MV) {

            av_assert2(mb_type & MB_TYPE_CBP);

            s->mv_dir = MV_DIR_FORWARD;

            if (s->picture_structure == PICT_FRAME) {

                if (s->picture_structure == PICT_FRAME

                    && !s->frame_pred_frame_dct)

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

                s->mv_type = MV_TYPE_16X16;

            } else {

                s->mv_type            = MV_TYPE_FIELD;

                mb_type              |= MB_TYPE_INTERLACED;

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

            }

            if (IS_QUANT(mb_type))

                s->qscale = get_qscale(s);

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

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

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

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

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

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

        } else {

            av_assert2(mb_type & MB_TYPE_L0L1);

            // FIXME decide if MBs in field pictures are MB_TYPE_INTERLACED

            /* get additional motion vector type */

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

                motion_type = MT_FRAME;

            } else {

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

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

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

            }

            if (IS_QUANT(mb_type))

                s->qscale = get_qscale(s);

            /* motion vectors */

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

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

            switch (motion_type) {

            case MT_FRAME: /* or MT_16X8 */

                if (s->picture_structure == PICT_FRAME) {

                    mb_type   |= MB_TYPE_16x16;

                    s->mv_type = MV_TYPE_16X16;

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

                        if (USES_LIST(mb_type, i)) {

                            /* MT_FRAME */

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

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

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

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

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

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

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

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

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

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

                            /* full_pel: only for MPEG-1 */

                            if (s->full_pel[i]) {

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

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

                            }

                        }

                    }

                } else {

                    mb_type   |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;

                    s->mv_type = MV_TYPE_16X8;

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

                        if (USES_LIST(mb_type, i)) {

                            /* MT_16X8 */

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

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

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

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

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

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

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

                                }

                            }

                        }

                    }

                }

                break;

            case MT_FIELD:

                s->mv_type = MV_TYPE_FIELD;

                if (s->picture_structure == PICT_FRAME) {

                    mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;

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

                        if (USES_LIST(mb_type, i)) {

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

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

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

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

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

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

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

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

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

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

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

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

                            }

                        }

                    }

                } else {

                    av_assert0(!s->progressive_sequence);

                    mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;

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

                        if (USES_LIST(mb_type, i)) {

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

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

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

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

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

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

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

                            }

                        }

                    }

                }

                break;

            case MT_DMV:

                if (s->progressive_sequence){

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

                    return AVERROR_INVALIDDATA;

                }

                s->mv_type = MV_TYPE_DMV;

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

                    if (USES_LIST(mb_type, i)) {

                        int dmx, dmy, mx, my, m;

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

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

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

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

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

                        dmx = get_dmv(s);

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

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

                        dmy = get_dmv(s);

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

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

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

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

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

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

                        if (s->picture_structure == PICT_FRAME) {

                            mb_type |= MB_TYPE_16x16 | MB_TYPE_INTERLACED;

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

                            m = s->top_field_first ? 1 : 3;

                            /* top -> top pred */

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

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

                            m = 4 - m;

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

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

                        } else {

                            mb_type |= MB_TYPE_16x16;

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

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

                            if (s->picture_structure == PICT_TOP_FIELD)

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

                            else

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

                        }

                    }

                }

                break;

            default:

                av_log(s->avctx, AV_LOG_ERROR,

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

                return AVERROR_INVALIDDATA;

            }

        }

        s->mb_intra = 0;

        if (HAS_CBP(mb_type)) {

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

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

            if (mb_block_count > 6) {

                cbp <<= mb_block_count - 6;

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

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

            }

            if (cbp <= 0) {

                av_log(s->avctx, AV_LOG_ERROR,

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

                return AVERROR_INVALIDDATA;

            }

            // if 1, we memcpy blocks in xvmcvideo

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

                ff_xvmc_pack_pblocks(s, cbp);

            if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

                if (s->flags2 & CODEC_FLAG2_FAST) {

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

                        if (cbp & 32)

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

                        else

                            s->block_last_index[i] = -1;

                        cbp += cbp;

                    }

                } else {

                    cbp <<= 12 - mb_block_count;

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

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

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

                                return ret;

                        } else {

                            s->block_last_index[i] = -1;

                        }

                        cbp += cbp;

                    }

                }

            } else {

                if (s->flags2 & CODEC_FLAG2_FAST) {

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

                        if (cbp & 32)

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

                        else

                            s->block_last_index[i] = -1;

                        cbp += cbp;

                    }

                } else {

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

                        if (cbp & 32) {

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

                                return ret;

                        } else {

                            s->block_last_index[i] = -1;

                        }

                        cbp += cbp;

                    }

                }

            }

        } else {

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

                s->block_last_index[i] = -1;

        }

    }

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

    return 0;

}


void xen_be_unbind_evtchn(struct XenDevice *xendev)

{

    if (xendev->local_port == -1) {

        return;

    }

    qemu_set_fd_handler(xc_evtchn_fd(xendev->evtchndev), NULL, NULL, NULL);

    xc_evtchn_unbind(xendev->evtchndev, xendev->local_port);

    xen_be_printf(xendev, 2, "unbind evtchn port %d\n", xendev->local_port);

    xendev->local_port = -1;

}


int avio_printf(AVIOContext *s, const char *fmt, ...)

{

    va_list ap;

    char buf[4096];

    int ret;

    va_start(ap, fmt);

    ret = vsnprintf(buf, sizeof(buf), fmt, ap);

    va_end(ap);

    avio_write(s, buf, strlen(buf));

    return ret;

}


static int ppc_hash64_check_prot(int prot, int rw, int access_type)

{

    int ret;

    if (access_type == ACCESS_CODE) {

        if (prot & PAGE_EXEC) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else if (rw) {

        if (prot & PAGE_WRITE) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else {

        if (prot & PAGE_READ) {

            ret = 0;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static int scsi_disk_emulate_inquiry(SCSIRequest *req, uint8_t *outbuf)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    int buflen = 0;

    int start;

    if (req->cmd.buf[1] & 0x1) {

        /* Vital product data */

        uint8_t page_code = req->cmd.buf[2];

        outbuf[buflen++] = s->qdev.type & 0x1f;

        outbuf[buflen++] = page_code ; // this page

        outbuf[buflen++] = 0x00;

        outbuf[buflen++] = 0x00;

        start = buflen;

        switch (page_code) {

        case 0x00: /* Supported page codes, mandatory */

        {

            DPRINTF("Inquiry EVPD[Supported pages] "

                    "buffer size %zd\n", req->cmd.xfer);

            outbuf[buflen++] = 0x00; // list of supported pages (this page)

            if (s->serial) {

                outbuf[buflen++] = 0x80; // unit serial number

            }

            outbuf[buflen++] = 0x83; // device identification

            if (s->qdev.type == TYPE_DISK) {

                outbuf[buflen++] = 0xb0; // block limits

                outbuf[buflen++] = 0xb2; // thin provisioning

            }

            break;

        }

        case 0x80: /* Device serial number, optional */

        {

            int l;

            if (!s->serial) {

                DPRINTF("Inquiry (EVPD[Serial number] not supported\n");

                return -1;

            }

            l = strlen(s->serial);

            if (l > 20) {

                l = 20;

            }

            DPRINTF("Inquiry EVPD[Serial number] "

                    "buffer size %zd\n", req->cmd.xfer);

            memcpy(outbuf+buflen, s->serial, l);

            buflen += l;

            break;

        }

        case 0x83: /* Device identification page, mandatory */

        {

            const char *str = s->serial ?: bdrv_get_device_name(s->qdev.conf.bs);

            int max_len = s->serial ? 20 : 255 - 8;

            int id_len = strlen(str);

            if (id_len > max_len) {

                id_len = max_len;

            }

            DPRINTF("Inquiry EVPD[Device identification] "

                    "buffer size %zd\n", req->cmd.xfer);

            outbuf[buflen++] = 0x2; // ASCII

            outbuf[buflen++] = 0;   // not officially assigned

            outbuf[buflen++] = 0;   // reserved

            outbuf[buflen++] = id_len; // length of data following

            memcpy(outbuf+buflen, str, id_len);

            buflen += id_len;

            if (s->wwn) {

                outbuf[buflen++] = 0x1; // Binary

                outbuf[buflen++] = 0x3; // NAA

                outbuf[buflen++] = 0;   // reserved

                outbuf[buflen++] = 8;

                stq_be_p(&outbuf[buflen], s->wwn);

                buflen += 8;

            }

            break;

        }

        case 0xb0: /* block limits */

        {

            unsigned int unmap_sectors =

                    s->qdev.conf.discard_granularity / s->qdev.blocksize;

            unsigned int min_io_size =

                    s->qdev.conf.min_io_size / s->qdev.blocksize;

            unsigned int opt_io_size =

                    s->qdev.conf.opt_io_size / s->qdev.blocksize;

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

                DPRINTF("Inquiry (EVPD[%02X] not supported for CDROM\n",

                        page_code);

                return -1;

            }

            /* required VPD size with unmap support */

            buflen = 0x40;

            memset(outbuf + 4, 0, buflen - 4);

            /* optimal transfer length granularity */

            outbuf[6] = (min_io_size >> 8) & 0xff;

            outbuf[7] = min_io_size & 0xff;

            /* optimal transfer length */

            outbuf[12] = (opt_io_size >> 24) & 0xff;

            outbuf[13] = (opt_io_size >> 16) & 0xff;

            outbuf[14] = (opt_io_size >> 8) & 0xff;

            outbuf[15] = opt_io_size & 0xff;

            /* optimal unmap granularity */

            outbuf[28] = (unmap_sectors >> 24) & 0xff;

            outbuf[29] = (unmap_sectors >> 16) & 0xff;

            outbuf[30] = (unmap_sectors >> 8) & 0xff;

            outbuf[31] = unmap_sectors & 0xff;

            break;

        }

        case 0xb2: /* thin provisioning */

        {

            buflen = 8;

            outbuf[4] = 0;

            outbuf[5] = 0xe0; /* unmap & write_same 10/16 all supported */

            outbuf[6] = s->qdev.conf.discard_granularity ? 2 : 1;

            outbuf[7] = 0;

            break;

        }

        default:

            return -1;

        }

        /* done with EVPD */

        assert(buflen - start <= 255);

        outbuf[start - 1] = buflen - start;

        return buflen;

    }

    /* Standard INQUIRY data */

    if (req->cmd.buf[2] != 0) {

        return -1;

    }

    /* PAGE CODE == 0 */

    buflen = req->cmd.xfer;

    if (buflen > SCSI_MAX_INQUIRY_LEN) {

        buflen = SCSI_MAX_INQUIRY_LEN;

    }

    memset(outbuf, 0, buflen);

    outbuf[0] = s->qdev.type & 0x1f;

    outbuf[1] = (s->features & (1 << SCSI_DISK_F_REMOVABLE)) ? 0x80 : 0;

    strpadcpy((char *) &outbuf[16], 16, s->product, ' ');

    strpadcpy((char *) &outbuf[8], 8, s->vendor, ' ');

    memset(&outbuf[32], 0, 4);

    memcpy(&outbuf[32], s->version, MIN(4, strlen(s->version)));

    /*

     * We claim conformance to SPC-3, which is required for guests

     * to ask for modern features like READ CAPACITY(16) or the

     * block characteristics VPD page by default.  Not all of SPC-3

     * is actually implemented, but we're good enough.

     */

    outbuf[2] = 5;

    outbuf[3] = 2 | 0x10; /* Format 2, HiSup */

    if (buflen > 36) {

        outbuf[4] = buflen - 5; /* Additional Length = (Len - 1) - 4 */

    } else {

        /* If the allocation length of CDB is too small,

               the additional length is not adjusted */

        outbuf[4] = 36 - 5;

    }

    /* Sync data transfer and TCQ.  */

    outbuf[7] = 0x10 | (req->bus->info->tcq ? 0x02 : 0);

    return buflen;

}


static void vmd_decode(VmdVideoContext *s)

{

    int i;

    unsigned int *palette32;

    unsigned char r, g, b;

    /* point to the start of the encoded data */

    const unsigned char *p = s->buf + 16;

    const unsigned char *pb;

    unsigned char meth;

    unsigned char *dp;   /* pointer to current frame */

    unsigned char *pp;   /* pointer to previous frame */

    unsigned char len;

    int ofs;

    int frame_x, frame_y;

    int frame_width, frame_height;

    frame_x = AV_RL16(&s->buf[6]);

    frame_y = AV_RL16(&s->buf[8]);

    frame_width = AV_RL16(&s->buf[10]) - frame_x + 1;

    frame_height = AV_RL16(&s->buf[12]) - frame_y + 1;

    if (frame_x < 0 || frame_width < 0 ||

        frame_x >= s->avctx->width ||

        frame_width > s->avctx->width ||

        frame_x + frame_width > s->avctx->width)

        return;

    if (frame_y < 0 || frame_height < 0 ||

        frame_y >= s->avctx->height ||

        frame_height > s->avctx->height ||

        frame_y + frame_height > s->avctx->height)

        return;

    if ((frame_width == s->avctx->width && frame_height == s->avctx->height) &&

        (frame_x || frame_y)) {

        s->x_off = frame_x;

        s->y_off = frame_y;

    }

    frame_x -= s->x_off;

    frame_y -= s->y_off;

    /* if only a certain region will be updated, copy the entire previous

     * frame before the decode */

    if (s->prev_frame.data[0] &&

        (frame_x || frame_y || (frame_width != s->avctx->width) ||

        (frame_height != s->avctx->height))) {

        memcpy(s->frame.data[0], s->prev_frame.data[0],

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

    }

    /* check if there is a new palette */

    if (s->buf[15] & 0x02) {

        p += 2;

        palette32 = (unsigned int *)s->palette;

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

            r = *p++ * 4;

            g = *p++ * 4;

            b = *p++ * 4;

            palette32[i] = (r << 16) | (g << 8) | (b);

        }

        s->size -= (256 * 3 + 2);

    }

    if (s->size >= 0) {

        /* originally UnpackFrame in VAG's code */

        pb = p;

        meth = *pb++;

        if (meth & 0x80) {

            lz_unpack(pb, s->unpack_buffer, s->unpack_buffer_size);

            meth &= 0x7F;

            pb = s->unpack_buffer;

        }

        dp = &s->frame.data[0][frame_y * s->frame.linesize[0] + frame_x];

        pp = &s->prev_frame.data[0][frame_y * s->prev_frame.linesize[0] + frame_x];

        switch (meth) {

        case 1:

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

                ofs = 0;

                do {

                    len = *pb++;

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        if (ofs + len > frame_width)

                            return;

                        memcpy(&dp[ofs], pb, len);

                        pb += len;

                        ofs += len;

                    } else {

                        /* interframe pixel copy */

                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])

                            return;

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                    break;

                }

                dp += s->frame.linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 2:

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

                memcpy(dp, pb, frame_width);

                pb += frame_width;

                dp += s->frame.linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 3:

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

                ofs = 0;

                do {

                    len = *pb++;

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        if (*pb++ == 0xFF)

                            len = rle_unpack(pb, &dp[ofs], len, frame_width - ofs);

                        else

                            memcpy(&dp[ofs], pb, len);

                        pb += len;

                        ofs += len;

                    } else {

                        /* interframe pixel copy */

                        if (ofs + len + 1 > frame_width || !s->prev_frame.data[0])

                            return;

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                }

                dp += s->frame.linesize[0];

                pp += s->prev_frame.linesize[0];

            }

            break;

        }

    }

}


static int unin_agp_pci_host_init(PCIDevice *d)

{

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_APPLE);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_APPLE_UNI_N_AGP);

    d->config[0x08] = 0x00; // revision

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    d->config[0x0C] = 0x08; // cache_line_size

    d->config[0x0D] = 0x10; // latency_timer

    //    d->config[0x34] = 0x80; // capabilities_pointer

    return 0;

}


static void float_number(void)

{

    int i;

    struct {

        const char *encoded;

        double decoded;

        int skip;

    } test_cases[] = {

        { "32.43", 32.43 },

        { "0.222", 0.222 },

        { "-32.12313", -32.12313 },

        { "-32.20e-10", -32.20e-10, .skip = 1 },

        { },

    };

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

        QObject *obj;

        QFloat *qfloat;

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

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QFLOAT);

        qfloat = qobject_to_qfloat(obj);

        g_assert(qfloat_get_double(qfloat) == test_cases[i].decoded);

        if (test_cases[i].skip == 0) {

            QString *str;

            str = qobject_to_json(obj);

            g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

            QDECREF(str);

        }

        QDECREF(qfloat);

    }

}


static void colo_process_checkpoint(MigrationState *s)

{

    QIOChannelBuffer *bioc;

    QEMUFile *fb = NULL;

    int64_t current_time, checkpoint_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);

    Error *local_err = NULL;

    int ret;

    failover_init_state();

    s->rp_state.from_dst_file = qemu_file_get_return_path(s->to_dst_file);

    if (!s->rp_state.from_dst_file) {

        error_report("Open QEMUFile from_dst_file failed");

        goto out;

    }

    /*

     * Wait for Secondary finish loading VM states and enter COLO

     * restore.

     */

    colo_receive_check_message(s->rp_state.from_dst_file,

                       COLO_MESSAGE_CHECKPOINT_READY, &local_err);

    if (local_err) {

        goto out;

    }

    bioc = qio_channel_buffer_new(COLO_BUFFER_BASE_SIZE);

    fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));

    object_unref(OBJECT(bioc));

    qemu_mutex_lock_iothread();

    vm_start();

    qemu_mutex_unlock_iothread();

    trace_colo_vm_state_change("stop", "run");

    while (s->state == MIGRATION_STATUS_COLO) {

        if (failover_get_state() != FAILOVER_STATUS_NONE) {

            error_report("failover request");

            goto out;

        }

        current_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);

        if (current_time - checkpoint_time <

            s->parameters.x_checkpoint_delay) {

            int64_t delay_ms;

            delay_ms = s->parameters.x_checkpoint_delay -

                       (current_time - checkpoint_time);

            g_usleep(delay_ms * 1000);

        }

        ret = colo_do_checkpoint_transaction(s, bioc, fb);

        if (ret < 0) {

            goto out;

        }

        checkpoint_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);

    }

out:

    /* Throw the unreported error message after exited from loop */

    if (local_err) {

        error_report_err(local_err);

    }

    if (fb) {

        qemu_fclose(fb);

    }

    if (s->rp_state.from_dst_file) {

        qemu_fclose(s->rp_state.from_dst_file);

    }

}


static void ecc_mem_write(void *opaque, target_phys_addr_t addr, uint64_t val,

                          unsigned size)

{

    ECCState *s = opaque;

    switch (addr >> 2) {

    case ECC_MER:

        if (s->version == ECC_MCC)

            s->regs[ECC_MER] = (val & ECC_MER_MASK_0);

        else if (s->version == ECC_EMC)

            s->regs[ECC_MER] = s->version | (val & ECC_MER_MASK_1);

        else if (s->version == ECC_SMC)

            s->regs[ECC_MER] = s->version | (val & ECC_MER_MASK_2);

        trace_ecc_mem_writel_mer(val);

        break;

    case ECC_MDR:

        s->regs[ECC_MDR] =  val & ECC_MDR_MASK;

        trace_ecc_mem_writel_mdr(val);

        break;

    case ECC_MFSR:

        s->regs[ECC_MFSR] =  val;

        qemu_irq_lower(s->irq);

        trace_ecc_mem_writel_mfsr(val);

        break;

    case ECC_VCR:

        s->regs[ECC_VCR] =  val;

        trace_ecc_mem_writel_vcr(val);

        break;

    case ECC_DR:

        s->regs[ECC_DR] =  val;

        trace_ecc_mem_writel_dr(val);

        break;

    case ECC_ECR0:

        s->regs[ECC_ECR0] =  val;

        trace_ecc_mem_writel_ecr0(val);

        break;

    case ECC_ECR1:

        s->regs[ECC_ECR0] =  val;

        trace_ecc_mem_writel_ecr1(val);

        break;

    }

}


static void gen_op_mull_T0_T1(void)

{

    TCGv tmp1 = tcg_temp_new(TCG_TYPE_I64);

    TCGv tmp2 = tcg_temp_new(TCG_TYPE_I64);

    tcg_gen_extu_i32_i64(tmp1, cpu_T[0]);

    tcg_gen_extu_i32_i64(tmp2, cpu_T[1]);

    tcg_gen_mul_i64(tmp1, tmp1, tmp2);

    tcg_gen_trunc_i64_i32(cpu_T[0], tmp1);

    tcg_gen_shri_i64(tmp1, tmp1, 32);

    tcg_gen_trunc_i64_i32(cpu_T[1], tmp1);

}


static int get_stats(AVCodecContext *avctx, int eos)

{

#ifdef TH_ENCCTL_2PASS_OUT

    TheoraContext *h = avctx->priv_data;

    uint8_t *buf;

    int bytes;

    bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));

    if (bytes < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");

        return AVERROR_EXTERNAL;

    }

    if (!eos) {

        void *tmp = av_fast_realloc(h->stats, &h->stats_size,

                                   h->stats_offset + bytes);

        if (!tmp)

        h->stats = tmp;

        memcpy(h->stats + h->stats_offset, buf, bytes);

        h->stats_offset += bytes;

    } else {

        int b64_size = AV_BASE64_SIZE(h->stats_offset);

        // libtheora generates a summary header at the end

        memcpy(h->stats, buf, bytes);

        avctx->stats_out = av_malloc(b64_size);

        av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);

    }

    return 0;

#else

    av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");

    return AVERROR(ENOSUP);

#endif

}


static int allocate_buffers(ALACContext *alac)

{

    int ch;

    int buf_size = alac->max_samples_per_frame * sizeof(int32_t);

    for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {

        FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],

                         buf_size, buf_alloc_fail);

        alac->direct_output = alac->sample_size > 16 && av_sample_fmt_is_planar(alac->avctx->sample_fmt);

        if (!alac->direct_output) {

            FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],

                             buf_size, buf_alloc_fail);

        }

        FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],

                         buf_size, buf_alloc_fail);

    }

    return 0;

buf_alloc_fail:

    alac_decode_close(alac->avctx);

    return AVERROR(ENOMEM);

}


static av_cold int iss_read_header(AVFormatContext *s)

{

    IssDemuxContext *iss = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st;

    char token[MAX_TOKEN_SIZE];

    int stereo, rate_divisor;

    get_token(pb, token, sizeof(token)); //"IMA_ADPCM_Sound"

    get_token(pb, token, sizeof(token)); //packet size

    sscanf(token, "%d", &iss->packet_size);

    get_token(pb, token, sizeof(token)); //File ID

    get_token(pb, token, sizeof(token)); //out size

    get_token(pb, token, sizeof(token)); //stereo

    sscanf(token, "%d", &stereo);

    get_token(pb, token, sizeof(token)); //Unknown1

    get_token(pb, token, sizeof(token)); //RateDivisor

    sscanf(token, "%d", &rate_divisor);

    get_token(pb, token, sizeof(token)); //Unknown2

    get_token(pb, token, sizeof(token)); //Version ID

    get_token(pb, token, sizeof(token)); //Size

    if (iss->packet_size <= 0) {

        av_log(s, AV_LOG_ERROR, "packet_size %d is invalid\n", iss->packet_size);

        return AVERROR_INVALIDDATA;

    }

    iss->sample_start_pos = avio_tell(pb);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_ISS;

    if (stereo) {

        st->codec->channels       = 2;

        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

    } else {

        st->codec->channels       = 1;

        st->codec->channel_layout = AV_CH_LAYOUT_MONO;

    }

    st->codec->sample_rate = 44100;

    if(rate_divisor > 0)

         st->codec->sample_rate /= rate_divisor;

    st->codec->bits_per_coded_sample = 4;

    st->codec->bit_rate = st->codec->channels * st->codec->sample_rate

                                      * st->codec->bits_per_coded_sample;

    st->codec->block_align = iss->packet_size;

    avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);

    return 0;

}


static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeCmd *cmd)

{

    NvmeDeleteQ *c = (NvmeDeleteQ *)cmd;

    NvmeRequest *req, *next;

    NvmeSQueue *sq;

    NvmeCQueue *cq;

    uint16_t qid = le16_to_cpu(c->qid);

    if (!qid || nvme_check_sqid(n, qid)) {

        return NVME_INVALID_QID | NVME_DNR;

    }

    sq = n->sq[qid];

    while (!QTAILQ_EMPTY(&sq->out_req_list)) {

        req = QTAILQ_FIRST(&sq->out_req_list);

        assert(req->aiocb);

        blk_aio_cancel(req->aiocb);

    }

    if (!nvme_check_cqid(n, sq->cqid)) {

        cq = n->cq[sq->cqid];

        QTAILQ_REMOVE(&cq->sq_list, sq, entry);

        nvme_post_cqes(cq);

        QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {

            if (req->sq == sq) {

                QTAILQ_REMOVE(&cq->req_list, req, entry);

                QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);

            }

        }

    }

    nvme_free_sq(sq, n);

    return NVME_SUCCESS;

}


static void virtio_scsi_locate_device(VDev *vdev)

{

    const uint16_t channel = 0; /* again, it's what QEMU does */

    uint16_t target;

    static uint8_t data[16 + 8 * 63];

    ScsiLunReport *r = (void *) data;

    ScsiDevice *sdev = vdev->scsi_device;

    int i, luns;

    /* QEMU has hardcoded channel #0 in many places.

     * If this hardcoded value is ever changed, we'll need to add code for

     * vdev->config.scsi.max_channel != 0 here.

     */

    debug_print_int("config.scsi.max_channel", vdev->config.scsi.max_channel);

    debug_print_int("config.scsi.max_target ", vdev->config.scsi.max_target);

    debug_print_int("config.scsi.max_lun    ", vdev->config.scsi.max_lun);

    debug_print_int("config.scsi.max_sectors", vdev->config.scsi.max_sectors);

    if (vdev->scsi_device_selected) {

        sdev->channel = vdev->selected_scsi_device.channel;

        sdev->target = vdev->selected_scsi_device.target;

        sdev->lun = vdev->selected_scsi_device.lun;

        IPL_check(sdev->channel == 0, "non-zero channel requested");

        IPL_check(sdev->target <= vdev->config.scsi.max_target, "target# high");

        IPL_check(sdev->lun <= vdev->config.scsi.max_lun, "LUN# high");

        return;

    }

    for (target = 0; target <= vdev->config.scsi.max_target; target++) {

        sdev->channel = channel;

        sdev->target = target; /* sdev->lun will be 0 here */

        if (!scsi_report_luns(vdev, data, sizeof(data))) {

            if (resp.response == VIRTIO_SCSI_S_BAD_TARGET) {

                continue;

            }

            print_int("target", target);

            virtio_scsi_verify_response(&resp, "SCSI cannot report LUNs");

        }

        if (r->lun_list_len == 0) {

            print_int("no LUNs for target", target);

            continue;

        }

        luns = r->lun_list_len / 8;

        debug_print_int("LUNs reported", luns);

        if (luns == 1) {

            /* There is no ",lun=#" arg for -device or ",lun=0" given.

             * Hence, the only LUN reported.

             * Usually, it's 0.

             */

            sdev->lun = r->lun[0].v16[0]; /* it's returned this way */

            debug_print_int("Have to use LUN", sdev->lun);

            return; /* we have to use this device */

        }

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

            if (r->lun[i].v64) {

                /* Look for non-zero LUN - we have where to choose from */

                sdev->lun = r->lun[i].v16[0];

                debug_print_int("Will use LUN", sdev->lun);

                return; /* we have found a device */

            }

        }

    }

    panic("\n! Cannot locate virtio-scsi device !\n");

}


static void qcow2_aio_read_cb(void *opaque, int ret)

{

    QCowAIOCB *acb = opaque;

    BlockDriverState *bs = acb->common.bs;

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n1;

    acb->hd_aiocb = NULL;

    if (ret < 0)

        goto done;

    /* post process the read buffer */

    if (!acb->cluster_offset) {

        /* nothing to do */

    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {

        /* nothing to do */

    } else {

        if (s->crypt_method) {

            qcow2_encrypt_sectors(s, acb->sector_num,  acb->cluster_data,

                acb->cluster_data, acb->cur_nr_sectors, 0, &s->aes_decrypt_key);

            qemu_iovec_reset(&acb->hd_qiov);

            qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,

                acb->cur_nr_sectors * 512);

            qemu_iovec_from_buffer(&acb->hd_qiov, acb->cluster_data,

                512 * acb->cur_nr_sectors);

        }

    }

    acb->remaining_sectors -= acb->cur_nr_sectors;

    acb->sector_num += acb->cur_nr_sectors;

    acb->bytes_done += acb->cur_nr_sectors * 512;

    if (acb->remaining_sectors == 0) {

        /* request completed */

        ret = 0;

        goto done;

    }

    /* prepare next AIO request */

    acb->cur_nr_sectors = acb->remaining_sectors;

    if (s->crypt_method) {

        acb->cur_nr_sectors = MIN(acb->cur_nr_sectors,

            QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);

    }

    ret = qcow2_get_cluster_offset(bs, acb->sector_num << 9,

        &acb->cur_nr_sectors, &acb->cluster_offset);

    if (ret < 0) {

        goto done;

    }

    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);

    qemu_iovec_reset(&acb->hd_qiov);

    qemu_iovec_copy(&acb->hd_qiov, acb->qiov, acb->bytes_done,

        acb->cur_nr_sectors * 512);

    if (!acb->cluster_offset) {

        if (bs->backing_hd) {

            /* read from the base image */

            n1 = qcow2_backing_read1(bs->backing_hd, &acb->hd_qiov,

                acb->sector_num, acb->cur_nr_sectors);

            if (n1 > 0) {

                BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);

                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,

                                    &acb->hd_qiov, acb->cur_nr_sectors,

				    qcow2_aio_read_cb, acb);

                if (acb->hd_aiocb == NULL)

                    goto done;

            } else {

                ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);

                if (ret < 0)

                    goto done;

            }

        } else {

            /* Note: in this case, no need to wait */

            qemu_iovec_memset(&acb->hd_qiov, 0, 512 * acb->cur_nr_sectors);

            ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);

            if (ret < 0)

                goto done;

        }

    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {

        /* add AIO support for compressed blocks ? */

        if (qcow2_decompress_cluster(bs, acb->cluster_offset) < 0)

            goto done;

        qemu_iovec_from_buffer(&acb->hd_qiov,

            s->cluster_cache + index_in_cluster * 512,

            512 * acb->cur_nr_sectors);

        ret = qcow2_schedule_bh(qcow2_aio_read_bh, acb);

        if (ret < 0)

            goto done;

    } else {

        if ((acb->cluster_offset & 511) != 0) {

            ret = -EIO;

            goto done;

        }

        if (s->crypt_method) {

            /*

             * For encrypted images, read everything into a temporary

             * contiguous buffer on which the AES functions can work.

             */

            if (!acb->cluster_data) {

                acb->cluster_data =

                    qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);

            }

            assert(acb->cur_nr_sectors <=

                QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);

            qemu_iovec_reset(&acb->hd_qiov);

            qemu_iovec_add(&acb->hd_qiov, acb->cluster_data,

                512 * acb->cur_nr_sectors);

        }

        BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);

        acb->hd_aiocb = bdrv_aio_readv(bs->file,

                            (acb->cluster_offset >> 9) + index_in_cluster,

                            &acb->hd_qiov, acb->cur_nr_sectors,

                            qcow2_aio_read_cb, acb);

        if (acb->hd_aiocb == NULL) {

            ret = -EIO;

            goto done;

        }

    }

    return;

done:

    acb->common.cb(acb->common.opaque, ret);

    qemu_iovec_destroy(&acb->hd_qiov);

    qemu_aio_release(acb);

}


static int mmsh_open(URLContext *h, const char *uri, int flags)

{

    int i, port, err;

    char httpname[256], path[256], host[128], location[1024];

    char *stream_selection;

    char headers[1024];

    MMSHContext *mmsh;

    MMSContext *mms;

    mmsh = h->priv_data = av_mallocz(sizeof(MMSHContext));

    if (!h->priv_data)

        return AVERROR(ENOMEM);

    mmsh->request_seq = h->is_streamed = 1;

    mms = &mmsh->mms;

    av_strlcpy(location, uri, sizeof(location));

    av_url_split(NULL, 0, NULL, 0,

        host, sizeof(host), &port, path, sizeof(path), location);

    if (port<0)

        port = 80; // default mmsh protocol port

    ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, path);

    if (url_alloc(&mms->mms_hd, httpname, URL_RDONLY) < 0) {

        return AVERROR(EIO);

    }

    snprintf(headers, sizeof(headers),

             "Accept: */*\r\n"

             USERAGENT

             "Host: %s:%d\r\n"

             "Pragma: no-cache,rate=1.000000,stream-time=0,"

             "stream-offset=0:0,request-context=%u,max-duration=0\r\n"

             CLIENTGUID

             "Connection: Close\r\n\r\n",

             host, port, mmsh->request_seq++);

    ff_http_set_headers(mms->mms_hd, headers);

    err = url_connect(mms->mms_hd);

    if (err) {

        goto fail;

    }

    err = get_http_header_data(mmsh);

    if (err) {

        av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");

        goto fail;

    }

    // close the socket and then reopen it for sending the second play request.

    url_close(mms->mms_hd);

    memset(headers, 0, sizeof(headers));

    if (url_alloc(&mms->mms_hd, httpname, URL_RDONLY) < 0) {

        return AVERROR(EIO);

    }

    stream_selection = av_mallocz(mms->stream_num * 19 + 1);

    if (!stream_selection)

        return AVERROR(ENOMEM);

    for (i = 0; i < mms->stream_num; i++) {

        char tmp[20];

        err = snprintf(tmp, sizeof(tmp), "ffff:%d:0 ", mms->streams[i].id);

        if (err < 0)

            goto fail;

        av_strlcat(stream_selection, tmp, mms->stream_num * 19 + 1);

    }

    // send play request

    err = snprintf(headers, sizeof(headers),

                   "Accept: */*\r\n"

                   USERAGENT

                   "Host: %s:%d\r\n"

                   "Pragma: no-cache,rate=1.000000,request-context=%u\r\n"

                   "Pragma: xPlayStrm=1\r\n"

                   CLIENTGUID

                   "Pragma: stream-switch-count=%d\r\n"

                   "Pragma: stream-switch-entry=%s\r\n"

                   "Connection: Close\r\n\r\n",

                   host, port, mmsh->request_seq++, mms->stream_num, stream_selection);

    av_freep(&stream_selection);

    if (err < 0) {

        av_log(NULL, AV_LOG_ERROR, "Build play request failed!\n");

        goto fail;

    }

    dprintf(NULL, "out_buffer is %s", headers);

    ff_http_set_headers(mms->mms_hd, headers);

    err = url_connect(mms->mms_hd);

    if (err) {

          goto fail;

    }

    err = get_http_header_data(mmsh);

    if (err) {

        av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");

        goto fail;

    }

    dprintf(NULL, "Connection successfully open\n");

    return 0;

fail:

    av_freep(&stream_selection);

    mmsh_close(h);

    dprintf(NULL, "Connection failed with error %d\n", err);

    return err;

}


static void t_gen_btst(TCGv d, TCGv a, TCGv b)

{

        TCGv sbit;

        TCGv bset;

        TCGv t0;

	int l1;

        /* des ref:

           The N flag is set according to the selected bit in the dest reg.

           The Z flag is set if the selected bit and all bits to the right are

           zero.

           The X flag is cleared.

           Other flags are left untouched.

           The destination reg is not affected.

        unsigned int fz, sbit, bset, mask, masked_t0;

        sbit = T1 & 31;

        bset = !!(T0 & (1 << sbit));

        mask = sbit == 31 ? -1 : (1 << (sbit + 1)) - 1;

        masked_t0 = T0 & mask;

        fz = !(masked_t0 | bset);

        // Clear the X, N and Z flags.

        T0 = env->pregs[PR_CCS] & ~(X_FLAG | N_FLAG | Z_FLAG);

        // Set the N and Z flags accordingly.

        T0 |= (bset << 3) | (fz << 2);

        */

	l1 = gen_new_label();

        sbit = tcg_temp_new(TCG_TYPE_TL);

        bset = tcg_temp_new(TCG_TYPE_TL);

        t0 = tcg_temp_new(TCG_TYPE_TL);

        /* Compute bset and sbit.  */

        tcg_gen_andi_tl(sbit, b, 31);

        tcg_gen_shl_tl(t0, tcg_const_tl(1), sbit);

        tcg_gen_and_tl(bset, a, t0);

        tcg_gen_shr_tl(bset, bset, sbit);

	/* Displace to N_FLAG.  */

        tcg_gen_shli_tl(bset, bset, 3);

        tcg_gen_shl_tl(sbit, tcg_const_tl(2), sbit);

        tcg_gen_subi_tl(sbit, sbit, 1);

        tcg_gen_and_tl(sbit, a, sbit);

        tcg_gen_andi_tl(d, cpu_PR[PR_CCS], ~(X_FLAG | N_FLAG | Z_FLAG));

	/* or in the N_FLAG.  */

        tcg_gen_or_tl(d, d, bset);

	tcg_gen_brcondi_tl(TCG_COND_NE, sbit, 0, l1);

	/* or in the Z_FLAG.  */

	tcg_gen_ori_tl(d, d, Z_FLAG);

	gen_set_label(l1);

        tcg_temp_free(sbit);

        tcg_temp_free(bset);

}


read_f(int argc, char **argv)

{

	struct timeval t1, t2;

	int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;

	int Pflag = 0, sflag = 0, lflag = 0, bflag = 0;

	int c, cnt;

	char *buf;

	int64_t offset;

	int count;

        /* Some compilers get confused and warn if this is not initialized.  */

        int total = 0;

	int pattern = 0, pattern_offset = 0, pattern_count = 0;

	while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) {

		switch (c) {

		case 'b':

			bflag = 1;

			break;

		case 'C':

			Cflag = 1;

			break;

		case 'l':

			lflag = 1;

			pattern_count = cvtnum(optarg);

			if (pattern_count < 0) {

				printf("non-numeric length argument -- %s\n", optarg);

				return 0;

			}

			break;

		case 'p':

			pflag = 1;

			break;

		case 'P':

			Pflag = 1;

			pattern = atoi(optarg);

			break;

		case 'q':

			qflag = 1;

			break;

		case 's':

			sflag = 1;

			pattern_offset = cvtnum(optarg);

			if (pattern_offset < 0) {

				printf("non-numeric length argument -- %s\n", optarg);

				return 0;

			}

			break;

		case 'v':

			vflag = 1;

			break;

		default:

			return command_usage(&read_cmd);

		}

	}

	if (optind != argc - 2)

		return command_usage(&read_cmd);

	if (bflag && pflag) {

		printf("-b and -p cannot be specified at the same time\n");

		return 0;

	}

	offset = cvtnum(argv[optind]);

	if (offset < 0) {

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

		return 0;

	}

	optind++;

	count = cvtnum(argv[optind]);

	if (count < 0) {

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

		return 0;

	}

    if (!Pflag && (lflag || sflag)) {

        return command_usage(&read_cmd);

    }

    if (!lflag) {

        pattern_count = count - pattern_offset;

    }

    if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {

        printf("pattern verfication range exceeds end of read data\n");

        return 0;

    }

	if (!pflag)

		if (offset & 0x1ff) {

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

				(long long)offset);

			return 0;

		if (count & 0x1ff) {

			printf("count %d is not sector aligned\n",

				count);

			return 0;

		}

	}

	buf = qemu_io_alloc(count, 0xab);

	gettimeofday(&t1, NULL);

	if (pflag)

		cnt = do_pread(buf, offset, count, &total);

	else if (bflag)

		cnt = do_load_vmstate(buf, offset, count, &total);

	else

		cnt = do_read(buf, offset, count, &total);

	gettimeofday(&t2, NULL);

	if (cnt < 0) {

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

		goto out;

	}

	if (Pflag) {

		void* cmp_buf = malloc(pattern_count);

		memset(cmp_buf, pattern, pattern_count);

		if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {

			printf("Pattern verification failed at offset %lld, "

				"%d bytes\n",

				(long long) offset + pattern_offset, pattern_count);

		}

		free(cmp_buf);

	}

	if (qflag)

		goto out;

        if (vflag)

		dump_buffer(buf, offset, count);

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

	t2 = tsub(t2, t1);

	print_report("read", &t2, offset, count, total, cnt, Cflag);

out:

	qemu_io_free(buf);

	return 0;

}


int ff_network_init(void)

{

#if HAVE_WINSOCK2_H

    WSADATA wsaData;

#endif

    if (!ff_network_inited_globally)

        av_log(NULL, AV_LOG_WARNING, "Using network protocols without global "

                                     "network initialization. Please use "

                                     "avformat_network_init(), this will "

                                     "become mandatory later.\n");

#if HAVE_WINSOCK2_H

    if (WSAStartup(MAKEWORD(1,1), &wsaData))

        return 0;

#endif

    return 1;

}


static int handle_connect_error(URLContext *s, const char *desc)

{

    RTMPContext *rt = s->priv_data;

    char buf[300], *ptr, authmod[15];

    int i = 0, ret = 0;

    const char *user = "", *salt = "", *opaque = NULL,

               *challenge = NULL, *cptr = NULL, *nonce = NULL;

    if (!(cptr = strstr(desc, "authmod=adobe")) &&

        !(cptr = strstr(desc, "authmod=llnw"))) {

        av_log(s, AV_LOG_ERROR,

               "Unknown connect error (unsupported authentication method?)\n");

        return AVERROR_UNKNOWN;

    }

    cptr += strlen("authmod=");

    while (*cptr && *cptr != ' ' && i < sizeof(authmod) - 1)

        authmod[i++] = *cptr++;

    authmod[i] = '\0';

    if (!rt->username[0] || !rt->password[0]) {

        av_log(s, AV_LOG_ERROR, "No credentials set\n");

        return AVERROR_UNKNOWN;

    }

    if (strstr(desc, "?reason=authfailed")) {

        av_log(s, AV_LOG_ERROR, "Incorrect username/password\n");

        return AVERROR_UNKNOWN;

    } else if (strstr(desc, "?reason=nosuchuser")) {

        av_log(s, AV_LOG_ERROR, "Incorrect username\n");

        return AVERROR_UNKNOWN;

    }

    if (rt->auth_tried) {

        av_log(s, AV_LOG_ERROR, "Authentication failed\n");

        return AVERROR_UNKNOWN;

    }

    rt->auth_params[0] = '\0';

    if (strstr(desc, "code=403 need auth")) {

        snprintf(rt->auth_params, sizeof(rt->auth_params),

                 "?authmod=%s&user=%s", authmod, rt->username);

        return 0;

    }

    if (!(cptr = strstr(desc, "?reason=needauth"))) {

        av_log(s, AV_LOG_ERROR, "No auth parameters found\n");

        return AVERROR_UNKNOWN;

    }

    av_strlcpy(buf, cptr + 1, sizeof(buf));

    ptr = buf;

    while (ptr) {

        char *next  = strchr(ptr, '&');

        char *value = strchr(ptr, '=');

        if (next)

            *next++ = '\0';

        if (value)

            *value++ = '\0';

        if (!strcmp(ptr, "user")) {

            user = value;

        } else if (!strcmp(ptr, "salt")) {

            salt = value;

        } else if (!strcmp(ptr, "opaque")) {

            opaque = value;

        } else if (!strcmp(ptr, "challenge")) {

            challenge = value;

        } else if (!strcmp(ptr, "nonce")) {

            nonce = value;

        }

        ptr = next;

    }

    if (!strcmp(authmod, "adobe")) {

        if ((ret = do_adobe_auth(rt, user, salt, opaque, challenge)) < 0)

            return ret;

    } else {

        if ((ret = do_llnw_auth(rt, user, nonce)) < 0)

            return ret;

    }

    rt->auth_tried = 1;

    return 0;

}


static int jacosub_probe(AVProbeData *p)

{

    const char *ptr     = p->buf;

    const char *ptr_end = p->buf + p->buf_size;

    if (AV_RB24(ptr) == 0xEFBBBF)

        ptr += 3; /* skip UTF-8 BOM */

    while (ptr < ptr_end) {

        while (jss_whitespace(*ptr))

            ptr++;

        if (*ptr != '#' && *ptr != '\n') {

            if (timed_line(ptr))

                return AVPROBE_SCORE_EXTENSION + 1;

            return 0;

        }

        ptr += strcspn(ptr, "\n") + 1;

    }

    return 0;

}


static void vp6_parse_coeff(VP56Context *s)

{

    VP56RangeCoder *c = s->ccp;

    VP56Model *model = s->modelp;

    uint8_t *permute = s->scantable.permutated;

    uint8_t *model1, *model2, *model3;

    int coeff, sign, coeff_idx;

    int b, i, cg, idx, ctx;

    int pt = 0;    /* plane type (0 for Y, 1 for U or V) */

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

        int ct = 1;    /* code type */

        int run = 1;

        if (b > 3) pt = 1;

        ctx = s->left_block[vp56_b6to4[b]].not_null_dc

              + s->above_blocks[s->above_block_idx[b]].not_null_dc;

        model1 = model->coeff_dccv[pt];

        model2 = model->coeff_dcct[pt][ctx];

        for (coeff_idx=0; coeff_idx<64; ) {

            if ((coeff_idx>1 && ct==0) || vp56_rac_get_prob(c, model2[0])) {

                /* parse a coeff */

                if (vp56_rac_get_prob(c, model2[2])) {

                    if (vp56_rac_get_prob(c, model2[3])) {

                        idx = vp56_rac_get_tree(c, vp56_pc_tree, model1);

                        coeff = vp56_coeff_bias[idx+5];

                        for (i=vp56_coeff_bit_length[idx]; i>=0; i--)

                            coeff += vp56_rac_get_prob(c, vp56_coeff_parse_table[idx][i]) << i;

                    } else {

                        if (vp56_rac_get_prob(c, model2[4]))

                            coeff = 3 + vp56_rac_get_prob(c, model1[5]);

                        else

                            coeff = 2;

                    }

                    ct = 2;

                } else {

                    ct = 1;

                    coeff = 1;

                }

                sign = vp56_rac_get(c);

                coeff = (coeff ^ -sign) + sign;

                if (coeff_idx)

                    coeff *= s->dequant_ac;

                idx = model->coeff_index_to_pos[coeff_idx];

                s->block_coeff[b][permute[idx]] = coeff;

                run = 1;

            } else {

                /* parse a run */

                ct = 0;

                if (coeff_idx > 0) {

                    if (!vp56_rac_get_prob(c, model2[1]))

                        break;

                    model3 = model->coeff_runv[coeff_idx >= 6];

                    run = vp56_rac_get_tree(c, vp6_pcr_tree, model3);

                    if (!run)

                        for (run=9, i=0; i<6; i++)

                            run += vp56_rac_get_prob(c, model3[i+8]) << i;

                }

            }

            cg = vp6_coeff_groups[coeff_idx+=run];

            model1 = model2 = model->coeff_ract[pt][ct][cg];

        }

        s->left_block[vp56_b6to4[b]].not_null_dc =

        s->above_blocks[s->above_block_idx[b]].not_null_dc = !!s->block_coeff[b][0];

    }

}


static void test_parse_path(void)

{

    g_test_trap_subprocess ("/logging/parse_path/subprocess", 0, 0);

    g_test_trap_assert_passed();

    g_test_trap_assert_stdout("");

    g_test_trap_assert_stderr("");

}


int floatx80_unordered(floatx80 a, floatx80 b, float_status *status)

{

    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( a )<<1 ) )

         || (    ( extractFloatx80Exp( b ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( b )<<1 ) )

       ) {

        float_raise(float_flag_invalid, status);

        return 1;

    }

    return 0;

}


static void usbredir_do_attach(void *opaque)

{

    USBRedirDevice *dev = opaque;

    /* In order to work properly with XHCI controllers we need these caps */

    if ((dev->dev.port->speedmask & USB_SPEED_MASK_SUPER) && !(

        usbredirparser_peer_has_cap(dev->parser,

                                    usb_redir_cap_ep_info_max_packet_size) &&

        usbredirparser_peer_has_cap(dev->parser,

                                    usb_redir_cap_32bits_bulk_length) &&

        usbredirparser_peer_has_cap(dev->parser,

                                    usb_redir_cap_64bits_ids))) {

        ERROR("usb-redir-host lacks capabilities needed for use with XHCI\n");

        usbredir_reject_device(dev);

        return;

    }

    if (usb_device_attach(&dev->dev) != 0) {

        WARNING("rejecting device due to speed mismatch\n");

        usbredir_reject_device(dev);

    }

}


uint64_t helper_fctidz (uint64_t arg)

{

    CPU_DoubleU farg;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN conversion */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);

    } else if (unlikely(float64_is_nan(farg.d) || float64_is_infinity(farg.d))) {

        /* qNan / infinity conversion */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);

    } else {

        farg.ll = float64_to_int64_round_to_zero(farg.d, &env->fp_status);

    }

    return farg.ll;

}


static void vtd_iommu_notify_flag_changed(MemoryRegion *iommu,

                                          IOMMUNotifierFlag old,

                                          IOMMUNotifierFlag new)

{

    VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);

    if (new & IOMMU_NOTIFIER_MAP) {

        error_report("Device at bus %s addr %02x.%d requires iommu "

                     "notifier which is currently not supported by "

                     "intel-iommu emulation",

                     vtd_as->bus->qbus.name, PCI_SLOT(vtd_as->devfn),

                     PCI_FUNC(vtd_as->devfn));

        exit(1);

    }

}


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

                                 uint32_t *val, uint32_t dev_value,

                                 uint32_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint32_t writable_mask = 0;

    uint32_t throughable_mask = get_throughable_mask(s, reg, valid_mask);

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

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

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

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

    return 0;

}


coroutine_fn iscsi_co_write_zeroes(BlockDriverState *bs, int64_t sector_num,

                                   int nb_sectors, BdrvRequestFlags flags)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    uint64_t lba;

    uint32_t nb_blocks;

    if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        return -EINVAL;

    }

    if (!iscsilun->lbp.lbpws) {

        /* WRITE SAME is not supported by the target */

        return -ENOTSUP;

    }

    lba = sector_qemu2lun(sector_num, iscsilun);

    nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);

    if (iscsilun->zeroblock == NULL) {

        iscsilun->zeroblock = g_malloc0(iscsilun->block_size);

    }

    iscsi_co_init_iscsitask(iscsilun, &iTask);

retry:

    if (iscsi_writesame16_task(iscsilun->iscsi, iscsilun->lun, lba,

                               iscsilun->zeroblock, iscsilun->block_size,

                               nb_blocks, 0, !!(flags & BDRV_REQ_MAY_UNMAP),

                               0, 0, iscsi_co_generic_cb, &iTask) == NULL) {

        return -EIO;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

        iTask.task = NULL;

    }

    if (iTask.do_retry) {

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        return -EIO;

    }

    return 0;

}


static BlkverifyAIOCB *blkverify_aio_get(BlockDriverState *bs, bool is_write,

                                         int64_t sector_num, QEMUIOVector *qiov,

                                         int nb_sectors,

                                         BlockCompletionFunc *cb,

                                         void *opaque)

{

    BlkverifyAIOCB *acb = qemu_aio_get(&blkverify_aiocb_info, bs, cb, opaque);

    acb->is_write = is_write;

    acb->sector_num = sector_num;

    acb->nb_sectors = nb_sectors;

    acb->ret = -EINPROGRESS;

    acb->done = 0;

    acb->qiov = qiov;

    acb->buf = NULL;

    acb->verify = NULL;

    return acb;

}


int av_write_header(AVFormatContext *s)

{

    int ret, i;

    AVStream *st;

    // some sanity checks

    if (s->nb_streams == 0) {

        av_log(s, AV_LOG_ERROR, "no streams\n");

        return -1;

    }

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

        st = s->streams[i];

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if(st->codec->sample_rate<=0){

                av_log(s, AV_LOG_ERROR, "sample rate not set\n");

                return -1;

            }

            if(!st->codec->block_align)

                st->codec->block_align = st->codec->channels *

                    av_get_bits_per_sample(st->codec->codec_id) >> 3;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?

                av_log(s, AV_LOG_ERROR, "time base not set\n");

                return -1;

            }

            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){

                av_log(s, AV_LOG_ERROR, "dimensions not set\n");

                return -1;

            }

            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)){

                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between encoder and muxer layer\n");

                return -1;

            }

            break;

        }

        if(s->oformat->codec_tag){

            if(st->codec->codec_tag){

                //FIXME

                //check that tag + id is in the table

                //if neither is in the table -> OK

                //if tag is in the table with another id -> FAIL

                //if id is in the table with another tag -> FAIL unless strict < ?

            }else

                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);

        }

        if(s->oformat->flags & AVFMT_GLOBALHEADER &&

            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))

          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);

    }

    if (!s->priv_data && s->oformat->priv_data_size > 0) {

        s->priv_data = av_mallocz(s->oformat->priv_data_size);

        if (!s->priv_data)

            return AVERROR(ENOMEM);

    }

#if LIBAVFORMAT_VERSION_MAJOR < 53

    ff_metadata_mux_compat(s);

#endif

    /* set muxer identification string */

    if (!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {

        AVMetadata *m;

        AVMetadataTag *t;

        if (!(m = av_mallocz(sizeof(AVMetadata))))

            return AVERROR(ENOMEM);

        av_metadata_set2(&m, "encoder", LIBAVFORMAT_IDENT, 0);

        metadata_conv(&m, s->oformat->metadata_conv, NULL);

        if ((t = av_metadata_get(m, "", NULL, AV_METADATA_IGNORE_SUFFIX)))

            av_metadata_set2(&s->metadata, t->key, t->value, 0);

        av_metadata_free(&m);

    }

    if(s->oformat->write_header){

        ret = s->oformat->write_header(s);

        if (ret < 0)

            return ret;

    }

    /* init PTS generation */

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

        int64_t den = AV_NOPTS_VALUE;

        st = s->streams[i];

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            den = (int64_t)st->time_base.num * st->codec->sample_rate;

            break;

        case AVMEDIA_TYPE_VIDEO:

            den = (int64_t)st->time_base.num * st->codec->time_base.den;

            break;

        default:

            break;

        }

        if (den != AV_NOPTS_VALUE) {

            if (den <= 0)

                return AVERROR_INVALIDDATA;

            av_frac_init(&st->pts, 0, 0, den);

        }

    }

    return 0;

}


static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)

{

    AVFrame *decoded_frame, *filtered_frame = NULL;

    void *buffer_to_free = NULL;

    int i, ret = 0;

    float quality;

#if CONFIG_AVFILTER

    int frame_available = 1;

#endif

    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))

        return AVERROR(ENOMEM);

    else

        avcodec_get_frame_defaults(ist->decoded_frame);

    decoded_frame = ist->decoded_frame;

    pkt->pts  = *pkt_pts;

    pkt->dts  = ist->last_dts;

    *pkt_pts  = AV_NOPTS_VALUE;

    ret = avcodec_decode_video2(ist->st->codec,

                                decoded_frame, got_output, pkt);

    if (ret < 0)

        return ret;

    quality = same_quant ? decoded_frame->quality : 0;

    if (!*got_output) {

        /* no picture yet */

        return ret;

    }

    decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,

                                           decoded_frame->pkt_dts);

    pkt->size = 0;

    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

    rate_emu_sleep(ist);

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

        OutputStream *ost = &output_streams[i];

        int frame_size, resample_changed;

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

#if CONFIG_AVFILTER

        resample_changed = ost->resample_width   != decoded_frame->width  ||

                           ost->resample_height  != decoded_frame->height ||

                           ost->resample_pix_fmt != decoded_frame->format;

        if (resample_changed) {

            av_log(NULL, AV_LOG_INFO,

                    "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",

                    ist->file_index, ist->st->index,

                    ost->resample_width,  ost->resample_height,  av_get_pix_fmt_name(ost->resample_pix_fmt),

                    decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));

            avfilter_graph_free(&ost->graph);

            if (configure_video_filters(ist, ost)) {

                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");

                exit_program(1);

            }

            ost->resample_width   = decoded_frame->width;

            ost->resample_height  = decoded_frame->height;

            ost->resample_pix_fmt = decoded_frame->format;

        }

        if (ist->st->sample_aspect_ratio.num)

            decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;

        if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {

            FrameBuffer      *buf = decoded_frame->opaque;

            AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(

                                        decoded_frame->data, decoded_frame->linesize,

                                        AV_PERM_READ | AV_PERM_PRESERVE,

                                        ist->st->codec->width, ist->st->codec->height,

                                        ist->st->codec->pix_fmt);

            avfilter_copy_frame_props(fb, decoded_frame);

            fb->buf->priv           = buf;

            fb->buf->free           = filter_release_buffer;

            buf->refcount++;

            av_buffersrc_buffer(ost->input_video_filter, fb);

        } else

            av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame,

                                     decoded_frame->pts, decoded_frame->sample_aspect_ratio);

        if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {

            av_free(buffer_to_free);

            return AVERROR(ENOMEM);

        } else

            avcodec_get_frame_defaults(ist->filtered_frame);

        filtered_frame = ist->filtered_frame;

        frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);

        while (frame_available) {

            AVRational ist_pts_tb;

            get_filtered_video_frame(ost->output_video_filter, filtered_frame, &ost->picref, &ist_pts_tb);

            if (ost->picref)

                filtered_frame->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

            if (ost->picref->video && !ost->frame_aspect_ratio)

                ost->st->codec->sample_aspect_ratio = ost->picref->video->pixel_aspect;

#else

            filtered_frame = decoded_frame;

#endif

            do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,

                         same_quant ? quality : ost->st->codec->global_quality);

            if (vstats_filename && frame_size)

                do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);

#if CONFIG_AVFILTER

            frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);

            if (ost->picref)

                avfilter_unref_buffer(ost->picref);

        }

#endif

    }

    av_free(buffer_to_free);

    return ret;

}


static void test_validate_list(TestInputVisitorData *data,

                                const void *unused)

{

    UserDefOneList *head = NULL;

    Visitor *v;

    v = validate_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44 } ]");

    visit_type_UserDefOneList(v, NULL, &head, &error_abort);

    qapi_free_UserDefOneList(head);

}


static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int predictor, int point_transform){

    int i, mb_x, mb_y;

    uint16_t (*buffer)[4];

    int left[3], top[3], topleft[3];

    const int linesize= s->linesize[0];

    const int mask= (1<<s->bits)-1;

    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size, (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));

    buffer= s->ljpeg_buffer;

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

        buffer[0][i]= 1 << (s->bits + point_transform - 1);

    }

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

        const int modified_predictor= mb_y ? predictor : 1;

        uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);

        if (s->interlaced && s->bottom_field)

            ptr += linesize >> 1;

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

            top[i]= left[i]= topleft[i]= buffer[0][i];

        }

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

            if (s->restart_interval && !s->restart_count)

                s->restart_count = s->restart_interval;

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

                int pred;

                topleft[i]= top[i];

                top[i]= buffer[mb_x][i];

                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);

                left[i]=

                buffer[mb_x][i]= mask & (pred + (mjpeg_decode_dc(s, s->dc_index[i]) << point_transform));

            }

            if (s->restart_interval && !--s->restart_count) {

                align_get_bits(&s->gb);

                skip_bits(&s->gb, 16); /* skip RSTn */

            }

        }

        if(s->rct){

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

                ptr[3*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200)>>2);

                ptr[3*mb_x+0] = buffer[mb_x][1] + ptr[3*mb_x+1];

                ptr[3*mb_x+2] = buffer[mb_x][2] + ptr[3*mb_x+1];

            }

        }else if(s->pegasus_rct){

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

                ptr[3*mb_x+1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2])>>2);

                ptr[3*mb_x+0] = buffer[mb_x][1] + ptr[3*mb_x+1];

                ptr[3*mb_x+2] = buffer[mb_x][2] + ptr[3*mb_x+1];

            }

        }else{

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

                ptr[3*mb_x+0] = buffer[mb_x][2];

                ptr[3*mb_x+1] = buffer[mb_x][1];

                ptr[3*mb_x+2] = buffer[mb_x][0];

            }

        }

    }

    return 0;

}


void vga_common_init(VGAState *s, DisplayState *ds, uint8_t *vga_ram_base,

                     unsigned long vga_ram_offset, int vga_ram_size)

{

    int i, j, v, b;

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

        v = 0;

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

            v |= ((i >> j) & 1) << (j * 4);

        }

        expand4[i] = v;

        v = 0;

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

            v |= ((i >> (2 * j)) & 3) << (j * 4);

        }

        expand2[i] = v;

    }

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

        v = 0;

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

            b = ((i >> j) & 1);

            v |= b << (2 * j);

            v |= b << (2 * j + 1);

        }

        expand4to8[i] = v;

    }

    vga_reset(s);

    s->vram_ptr = vga_ram_base;

    s->vram_offset = vga_ram_offset;

    s->vram_size = vga_ram_size;

    s->ds = ds;

    s->get_bpp = vga_get_bpp;

    s->get_offsets = vga_get_offsets;

    s->get_resolution = vga_get_resolution;

    s->update = vga_update_display;

    s->invalidate = vga_invalidate_display;

    s->screen_dump = vga_screen_dump;

    s->text_update = vga_update_text;

    switch (vga_retrace_method) {

    case VGA_RETRACE_DUMB:

        s->retrace = vga_dumb_retrace;

        s->update_retrace_info = vga_dumb_update_retrace_info;

        break;

    case VGA_RETRACE_PRECISE:

        s->retrace = vga_precise_retrace;

        s->update_retrace_info = vga_precise_update_retrace_info;

        memset(&s->retrace_info, 0, sizeof (s->retrace_info));

        break;

    }

}


void monitor_init(CharDriverState *chr, int show_banner)

{

    int i;

    if (is_first_init) {

        key_timer = qemu_new_timer(vm_clock, release_keys, NULL);

        if (!key_timer)

            return;

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

            monitor_hd[i] = NULL;

        }

        is_first_init = 0;

    }

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

        if (monitor_hd[i] == NULL) {

            monitor_hd[i] = chr;

            break;

        }

    }

    hide_banner = !show_banner;

    qemu_chr_add_handlers(chr, term_can_read, term_read, term_event, cur_mon);

    readline_start("", 0, monitor_command_cb, NULL);

}


static int twinvq_read_bitstream(AVCodecContext *avctx, TwinVQContext *tctx,

                                 const uint8_t *buf, int buf_size)

{

    TwinVQFrameData     *bits = &tctx->bits;

    const TwinVQModeTab *mtab = tctx->mtab;

    int channels              = tctx->avctx->channels;

    int sub;

    GetBitContext gb;

    int i, j, k;

    if (buf_size * 8 < avctx->bit_rate * mtab->size / avctx->sample_rate + 8) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame too small (%d bytes). Truncated file?\n", buf_size);

        return AVERROR(EINVAL);

    }

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

    skip_bits(&gb, get_bits(&gb, 8));

    bits->window_type = get_bits(&gb, TWINVQ_WINDOW_TYPE_BITS);

    if (bits->window_type > 8) {

        av_log(avctx, AV_LOG_ERROR, "Invalid window type, broken sample?\n");

        return AVERROR_INVALIDDATA;

    }

    bits->ftype = ff_twinvq_wtype_to_ftype_table[tctx->bits.window_type];

    sub = mtab->fmode[bits->ftype].sub;

    read_cb_data(tctx, &gb, bits->main_coeffs, bits->ftype);

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

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

            for (k = 0; k < mtab->fmode[bits->ftype].bark_n_coef; k++)

                bits->bark1[i][j][k] =

                    get_bits(&gb, mtab->fmode[bits->ftype].bark_n_bit);

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

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

            bits->bark_use_hist[i][j] = get_bits1(&gb);

    if (bits->ftype == TWINVQ_FT_LONG) {

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

            bits->gain_bits[i] = get_bits(&gb, TWINVQ_GAIN_BITS);

    } else {

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

            bits->gain_bits[i] = get_bits(&gb, TWINVQ_GAIN_BITS);

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

                bits->sub_gain_bits[i * sub + j] = get_bits(&gb,

                                                       TWINVQ_SUB_GAIN_BITS);

        }

    }

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

        bits->lpc_hist_idx[i] = get_bits(&gb, mtab->lsp_bit0);

        bits->lpc_idx1[i]     = get_bits(&gb, mtab->lsp_bit1);

        for (j = 0; j < mtab->lsp_split; j++)

            bits->lpc_idx2[i][j] = get_bits(&gb, mtab->lsp_bit2);

    }

    if (bits->ftype == TWINVQ_FT_LONG) {

        read_cb_data(tctx, &gb, bits->ppc_coeffs, 3);

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

            bits->p_coef[i] = get_bits(&gb, mtab->ppc_period_bit);

            bits->g_coef[i] = get_bits(&gb, mtab->pgain_bit);

        }

    }

    return 0;

}


int iommu_dma_memory_rw(DMAContext *dma, dma_addr_t addr,

                        void *buf, dma_addr_t len, DMADirection dir)

{

    target_phys_addr_t paddr, plen;

    int err;

#ifdef DEBUG_IOMMU

    fprintf(stderr, "dma_memory_rw context=%p addr=0x" DMA_ADDR_FMT " len=0x"

            DMA_ADDR_FMT " dir=%d\n", dma, addr, len, dir);

#endif

    while (len) {

        err = dma->translate(dma, addr, &paddr, &plen, dir);

        if (err) {

	    /*

             * In case of failure on reads from the guest, we clean the

             * destination buffer so that a device that doesn't test

             * for errors will not expose qemu internal memory.

	     */

	    memset(buf, 0, len);

            return -1;

        }

        /* The translation might be valid for larger regions. */

        if (plen > len) {

            plen = len;

        }

        address_space_rw(dma->as, paddr, buf, plen, dir == DMA_DIRECTION_FROM_DEVICE);

        len -= plen;

        addr += plen;

        buf += plen;

    }

    return 0;

}


static void blend_frame(AVFilterContext *ctx,

                        AVFrame *top_buf,

                        AVFrame *bottom_buf,

                        AVFrame *dst_buf)

{

    BlendContext *b = ctx->priv;

    AVFilterLink *inlink = ctx->inputs[0];

    FilterParams *param;

    int plane;

    for (plane = 0; dst_buf->data[plane]; plane++) {

        int hsub = plane == 1 || plane == 2 ? b->hsub : 0;

        int vsub = plane == 1 || plane == 2 ? b->vsub : 0;

        int outw = dst_buf->width  >> hsub;

        int outh = dst_buf->height >> vsub;

        uint8_t *dst    = dst_buf->data[plane];

        uint8_t *top    = top_buf->data[plane];

        uint8_t *bottom = bottom_buf->data[plane];

        param = &b->params[plane];

        param->values[VAR_N]  = inlink->frame_count;

        param->values[VAR_T]  = dst_buf->pts == AV_NOPTS_VALUE ? NAN : dst_buf->pts * av_q2d(inlink->time_base);

        param->values[VAR_W]  = outw;

        param->values[VAR_H]  = outh;

        param->values[VAR_SW] = outw / dst_buf->width;

        param->values[VAR_SH] = outh / dst_buf->height;

        param->blend(top, top_buf->linesize[plane],

                     bottom, bottom_buf->linesize[plane],

                     dst, dst_buf->linesize[plane], outw, outh, param);

    }

}