static av_cold int encode_init(AVCodecContext* avc_context)

{

    theora_info t_info;

    theora_comment t_comment;

    ogg_packet o_packet;

    unsigned int offset;

    TheoraContext *h = avc_context->priv_data;

    /* Set up the theora_info struct */

    theora_info_init( &t_info );

    t_info.width = FFALIGN(avc_context->width, 16);

    t_info.height = FFALIGN(avc_context->height, 16);

    t_info.frame_width = avc_context->width;

    t_info.frame_height = avc_context->height;

    t_info.offset_x = 0;

    t_info.offset_y = avc_context->height & 0xf;

    /* Swap numerator and denominator as time_base in AVCodecContext gives the

     * time period between frames, but theora_info needs the framerate.  */

    t_info.fps_numerator = avc_context->time_base.den;

    t_info.fps_denominator = avc_context->time_base.num;

    if (avc_context->sample_aspect_ratio.num != 0) {

        t_info.aspect_numerator = avc_context->sample_aspect_ratio.num;

        t_info.aspect_denominator = avc_context->sample_aspect_ratio.den;

    } else {

        t_info.aspect_numerator = 1;

        t_info.aspect_denominator = 1;

    }

    t_info.colorspace = OC_CS_UNSPECIFIED;

    t_info.pixelformat = OC_PF_420;

    t_info.target_bitrate = avc_context->bit_rate;

    t_info.keyframe_frequency = avc_context->gop_size;

    t_info.keyframe_frequency_force = avc_context->gop_size;

    t_info.keyframe_mindistance = avc_context->keyint_min;

    t_info.quality = 0;

    t_info.quick_p = 1;

    t_info.dropframes_p = 0;

    t_info.keyframe_auto_p = 1;

    t_info.keyframe_data_target_bitrate = t_info.target_bitrate * 1.5;

    t_info.keyframe_auto_threshold = 80;

    t_info.noise_sensitivity = 1;

    t_info.sharpness = 0;

    /* Now initialise libtheora */

    if (theora_encode_init( &(h->t_state), &t_info ) != 0) {

        av_log(avc_context, AV_LOG_ERROR, "theora_encode_init failed\n");

        return -1;

    }

    /* Clear up theora_info struct */

    theora_info_clear( &t_info );

    /*

        Output first header packet consisting of theora

        header, comment, and tables.

        Each one is prefixed with a 16bit size, then they

        are concatenated together into ffmpeg's extradata.

    */

    offset = 0;

    /* Header */

    theora_encode_header( &(h->t_state), &o_packet );

    if (concatenate_packet( &offset, avc_context, &o_packet ) != 0) {

        return -1;

    }

    /* Comment */

    theora_comment_init( &t_comment );

    theora_encode_comment( &t_comment, &o_packet );

    if (concatenate_packet( &offset, avc_context, &o_packet ) != 0) {

        return -1;

    }

    /* Tables */

    theora_encode_tables( &(h->t_state), &o_packet );

    if (concatenate_packet( &offset, avc_context, &o_packet ) != 0) {

        return -1;

    }

    /* Clear up theora_comment struct */

    theora_comment_clear( &t_comment );

    /* Set up the output AVFrame */

    avc_context->coded_frame= avcodec_alloc_frame();

    return 0;

}


static int frame_thread_init(AVCodecContext *avctx)

{

    int thread_count = avctx->thread_count;

    AVCodec *codec = avctx->codec;

    AVCodecContext *src = avctx;

    FrameThreadContext *fctx;

    int i, err = 0;

    if (thread_count <= 1) {

        avctx->active_thread_type = 0;

        return 0;

    }

    avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));

    fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);

    pthread_mutex_init(&fctx->buffer_mutex, NULL);

    fctx->delaying = 1;

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

        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));

        PerThreadContext *p  = &fctx->threads[i];

        pthread_mutex_init(&p->mutex, NULL);

        pthread_mutex_init(&p->progress_mutex, NULL);

        pthread_cond_init(&p->input_cond, NULL);

        pthread_cond_init(&p->progress_cond, NULL);

        pthread_cond_init(&p->output_cond, NULL);

        p->parent = fctx;

        p->avctx  = copy;

        if (!copy) {

            err = AVERROR(ENOMEM);

            goto error;

        }

        *copy = *src;

        copy->thread_opaque = p;

        copy->pkt = &p->avpkt;

        if (!i) {

            src = copy;

            if (codec->init)

                err = codec->init(copy);

            update_context_from_thread(avctx, copy, 1);

        } else {

            copy->priv_data = av_malloc(codec->priv_data_size);

            if (!copy->priv_data) {

                err = AVERROR(ENOMEM);

                goto error;

            }

            memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);

            copy->internal = av_malloc(sizeof(AVCodecInternal));

            if (!copy->internal) {

                err = AVERROR(ENOMEM);

                goto error;

            }

            *(copy->internal) = *(src->internal);

            copy->internal->is_copy = 1;

            if (codec->init_thread_copy)

                err = codec->init_thread_copy(copy);

        }

        if (err) goto error;

        pthread_create(&p->thread, NULL, frame_worker_thread, p);

    }

    return 0;

error:

    frame_thread_free(avctx, i+1);

    return err;

}


static char *shorts2str(int16_t *sp, int count, const char *sep)

{

    int i;

    char *ap, *ap0;

    if (!sep) sep = ", ";

    ap = av_malloc((5 + strlen(sep)) * count);

    if (!ap)

        return NULL;

    ap0   = ap;

    ap[0] = '\0';

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

        int l = snprintf(ap, 5 + strlen(sep), "%d%s", sp[i], sep);

        ap += l;

    }

    ap0[strlen(ap0) - strlen(sep)] = '\0';

    return ap0;

}


static int h264_set_parameter_from_sps(H264Context *h)
{
    if (h->flags & CODEC_FLAG_LOW_DELAY ||
        (h->sps.bitstream_restriction_flag &&
         !h->sps.num_reorder_frames)) {
        if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])
            av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "
                   "Reenabling low delay requires a codec flush.\n");
        else
            h->low_delay = 1;
    if (h->avctx->has_b_frames < 2)
        h->avctx->has_b_frames = !h->low_delay;
    if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||
        h->cur_chroma_format_idc      != h->sps.chroma_format_idc) {
        if (h->avctx->codec &&
            h->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU &&
            (h->sps.bit_depth_luma != 8 || h->sps.chroma_format_idc > 1)) {
            av_log(h->avctx, AV_LOG_ERROR,
                   "VDPAU decoding does not support video colorspace.\n");
            return AVERROR_INVALIDDATA;
        if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {
            h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;
            h->cur_chroma_format_idc      = h->sps.chroma_format_idc;
            h->pixel_shift                = h->sps.bit_depth_luma > 8;
            ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,
                            h->sps.chroma_format_idc);
            ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);
            ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);
            ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,
                              h->sps.chroma_format_idc);
            h->dsp.dct_bits = h->sps.bit_depth_luma > 8 ? 32 : 16;
            ff_dsputil_init(&h->dsp, h->avctx);
            ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);
        } else {
            av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth: %d\n",
                   h->sps.bit_depth_luma);
            return AVERROR_INVALIDDATA;
    return 0;


static inline int array_roll(array_t* array,int index_to,int index_from,int count)

{

    char* buf;

    char* from;

    char* to;

    int is;

    if(!array ||

	    index_to<0 || index_to>=array->next ||

	    index_from<0 || index_from>=array->next)

	return -1;

    if(index_to==index_from)

	return 0;

    is=array->item_size;

    from=array->pointer+index_from*is;

    to=array->pointer+index_to*is;

    buf=g_malloc(is*count);

    memcpy(buf,from,is*count);

    if(index_to<index_from)

	memmove(to+is*count,to,from-to);

    else

	memmove(from,from+is*count,to-from);

    memcpy(to,buf,is*count);

    free(buf);

    return 0;

}


int ff_raw_video_read_header(AVFormatContext *s)

{

    AVStream *st;

    FFRawVideoDemuxerContext *s1 = s->priv_data;

    AVRational framerate;

    int ret = 0;

    st = avformat_new_stream(s, NULL);

    if (!st) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = s->iformat->raw_codec_id;

    st->need_parsing = AVSTREAM_PARSE_FULL;

    if ((ret = av_parse_video_rate(&framerate, s1->framerate)) < 0) {

        av_log(s, AV_LOG_ERROR, "Could not parse framerate: %s.\n", s1->framerate);

        goto fail;

    }

    st->r_frame_rate = st->avg_frame_rate = framerate;

    avpriv_set_pts_info(st, 64, framerate.den, framerate.num);

fail:

    return ret;

}


static int mov_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    MOVContext *mov = s->priv_data;
    MOVStreamContext *sc;
    AVIndexEntry *sample;
    AVStream *st = NULL;
    int ret;
    mov->fc = s;
 retry:
    sample = mov_find_next_sample(s, &st);
    if (!sample) {
        mov->found_mdat = 0;
        if (!mov->next_root_atom)
            return AVERROR_EOF;
        avio_seek(s->pb, mov->next_root_atom, SEEK_SET);
        mov->next_root_atom = 0;
        if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 ||
            url_feof(s->pb))
            return AVERROR_EOF;
        av_dlog(s, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb));
        goto retry;
    sc = st->priv_data;
    /* must be done just before reading, to avoid infinite loop on sample */
    sc->current_sample++;
    if (st->discard != AVDISCARD_ALL) {
        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {
            av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n",
                   sc->ffindex, sample->pos);
            return AVERROR_INVALIDDATA;
        ret = av_get_packet(sc->pb, pkt, sample->size);
        if (ret < 0)
            return ret;
        if (sc->has_palette) {
            uint8_t *pal;
            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
            if (!pal) {
                av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n");
            } else {
                memcpy(pal, sc->palette, AVPALETTE_SIZE);
                sc->has_palette = 0;
#if CONFIG_DV_DEMUXER
        if (mov->dv_demux && sc->dv_audio_container) {
            avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos);
            av_free(pkt->data);
            pkt->size = 0;
            ret = avpriv_dv_get_packet(mov->dv_demux, pkt);
            if (ret < 0)
                return ret;
#endif
    pkt->stream_index = sc->ffindex;
    pkt->dts = sample->timestamp;
    if (sc->ctts_data && sc->ctts_index < sc->ctts_count) {
        pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration;
        /* update ctts context */
        sc->ctts_sample++;
        if (sc->ctts_index < sc->ctts_count &&
            sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) {
            sc->ctts_index++;
            sc->ctts_sample = 0;
        if (sc->wrong_dts)
            pkt->dts = AV_NOPTS_VALUE;
    } else {
        int64_t next_dts = (sc->current_sample < st->nb_index_entries) ?
            st->index_entries[sc->current_sample].timestamp : st->duration;
        pkt->duration = next_dts - pkt->dts;
        pkt->pts = pkt->dts;
    if (st->discard == AVDISCARD_ALL)
        goto retry;
    pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0;
    pkt->pos = sample->pos;
    av_dlog(s, "stream %d, pts %"PRId64", dts %"PRId64", pos 0x%"PRIx64", duration %d\n",
            pkt->stream_index, pkt->pts, pkt->dts, pkt->pos, pkt->duration);
    return 0;


QEMUSizedBuffer *qsb_create(const uint8_t *buffer, size_t len)

{

    QEMUSizedBuffer *qsb;

    size_t alloc_len, num_chunks, i, to_copy;

    size_t chunk_size = (len > QSB_MAX_CHUNK_SIZE)

                        ? QSB_MAX_CHUNK_SIZE

                        : QSB_CHUNK_SIZE;

    num_chunks = DIV_ROUND_UP(len ? len : QSB_CHUNK_SIZE, chunk_size);

    alloc_len = num_chunks * chunk_size;

    qsb = g_try_new0(QEMUSizedBuffer, 1);

    if (!qsb) {

        return NULL;

    }

    qsb->iov = g_try_new0(struct iovec, num_chunks);

    if (!qsb->iov) {

        g_free(qsb);

        return NULL;

    }

    qsb->n_iov = num_chunks;

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

        qsb->iov[i].iov_base = g_try_malloc0(chunk_size);

        if (!qsb->iov[i].iov_base) {

            /* qsb_free is safe since g_free can cope with NULL */

            qsb_free(qsb);

            return NULL;

        }

        qsb->iov[i].iov_len = chunk_size;

        if (buffer) {

            to_copy = (len - qsb->used) > chunk_size

                      ? chunk_size : (len - qsb->used);

            memcpy(qsb->iov[i].iov_base, &buffer[qsb->used], to_copy);

            qsb->used += to_copy;

        }

    }

    qsb->size = alloc_len;

    return qsb;

}


static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
{
    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
    if (k->notify) {
        k->notify(qbus->parent, vector);


static int svq1_motion_inter_4v_block(DSPContext *dsp, GetBitContext *bitbuf,

                                      uint8_t *current, uint8_t *previous,

                                      int pitch, svq1_pmv *motion, int x, int y)

{

    uint8_t *src;

    uint8_t *dst;

    svq1_pmv mv;

    svq1_pmv *pmv[4];

    int i, result;

    /* predict and decode motion vector (0) */

    pmv[0] = &motion[0];

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[(x / 8) + 2];

        pmv[2] = &motion[(x / 8) + 4];

    }

    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (1) */

    pmv[0] = &mv;

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[(x / 8) + 3];

    }

    result = svq1_decode_motion_vector(bitbuf, &motion[0], pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (2) */

    pmv[1] = &motion[0];

    pmv[2] = &motion[(x / 8) + 1];

    result = svq1_decode_motion_vector(bitbuf, &motion[(x / 8) + 2], pmv);

    if (result != 0)

        return result;

    /* predict and decode motion vector (3) */

    pmv[2] = &motion[(x / 8) + 2];

    pmv[3] = &motion[(x / 8) + 3];

    result = svq1_decode_motion_vector(bitbuf, pmv[3], pmv);

    if (result != 0)

        return result;

    /* form predictions */

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

        int mvx = pmv[i]->x + (i  & 1) * 16;

        int mvy = pmv[i]->y + (i >> 1) * 16;

        // FIXME: clipping or padding?

        if (y + (mvy >> 1) < 0)

            mvy = 0;

        if (x + (mvx >> 1) < 0)

            mvx = 0;

        src = &previous[(x + (mvx >> 1)) + (y + (mvy >> 1)) * pitch];

        dst = current;

        dsp->put_pixels_tab[1][((mvy & 1) << 1) | (mvx & 1)](dst, src, pitch, 8);

        /* select next block */

        if (i & 1)

            current += 8 * (pitch - 1);

        else

            current += 8;

    }

    return 0;

}


CPUState *cpu_create(const char *typename)

{

    Error *err = NULL;

    CPUState *cpu = CPU(object_new(typename));

    object_property_set_bool(OBJECT(cpu), true, "realized", &err);

    if (err != NULL) {

        error_report_err(err);

        object_unref(OBJECT(cpu));

        return NULL;

    }

    return cpu;

}


static int qio_channel_socket_connect_worker(QIOTask *task,

                                             Error **errp,

                                             gpointer opaque)

{

    QIOChannelSocket *ioc = QIO_CHANNEL_SOCKET(qio_task_get_source(task));

    SocketAddress *addr = opaque;

    int ret;

    ret = qio_channel_socket_connect_sync(ioc,

                                          addr,

                                          errp);

    object_unref(OBJECT(ioc));

    return ret;

}


static const void *boston_kernel_filter(void *opaque, const void *kernel,

                                        hwaddr *load_addr, hwaddr *entry_addr)

{

    BostonState *s = BOSTON(opaque);

    s->kernel_entry = *entry_addr;

    return kernel;

}


static av_always_inline void idct_mb(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb)

{

    int x, y, ch;

    if (mb->mode != MODE_I4x4) {

        uint8_t *y_dst = dst[0];

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

            uint32_t nnz4 = AV_RL32(s->non_zero_count_cache[y]);

            if (nnz4) {

                if (nnz4&~0x01010101) {

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

                        if ((uint8_t)nnz4 == 1)

                            s->vp8dsp.vp8_idct_dc_add(y_dst+4*x, s->block[y][x], s->linesize);

                        else if((uint8_t)nnz4 > 1)

                            s->vp8dsp.vp8_idct_add(y_dst+4*x, s->block[y][x], s->linesize);

                        nnz4 >>= 8;

                        if (!nnz4)

                            break;

                    }

                } else {

                    s->vp8dsp.vp8_idct_dc_add4y(y_dst, s->block[y], s->linesize);

                }

            }

            y_dst += 4*s->linesize;

        }

    }

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

        uint32_t nnz4 = AV_RL32(s->non_zero_count_cache[4+ch]);

        if (nnz4) {

            uint8_t *ch_dst = dst[1+ch];

            if (nnz4&~0x01010101) {

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

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

                        if ((uint8_t)nnz4 == 1)

                            s->vp8dsp.vp8_idct_dc_add(ch_dst+4*x, s->block[4+ch][(y<<1)+x], s->uvlinesize);

                        else if((uint8_t)nnz4 > 1)

                            s->vp8dsp.vp8_idct_add(ch_dst+4*x, s->block[4+ch][(y<<1)+x], s->uvlinesize);

                        nnz4 >>= 8;

                        if (!nnz4)

                            break;

                    }

                    ch_dst += 4*s->uvlinesize;

                }

            } else {

                s->vp8dsp.vp8_idct_dc_add4uv(ch_dst, s->block[4+ch], s->uvlinesize);

            }

        }

    }

}


PCIDevice *virtio_net_init(PCIBus *bus, NICInfo *nd, int devfn)

{

    VirtIONet *n;

    static int virtio_net_id;

    n = (VirtIONet *)virtio_init_pci(bus, "virtio-net",

                                     PCI_VENDOR_ID_REDHAT_QUMRANET,

                                     PCI_DEVICE_ID_VIRTIO_NET,

                                     PCI_VENDOR_ID_REDHAT_QUMRANET,

                                     VIRTIO_ID_NET,

                                     PCI_CLASS_NETWORK_ETHERNET, 0x00,

                                     sizeof(struct virtio_net_config),

                                     sizeof(VirtIONet));

    if (!n)

        return NULL;

    n->vdev.get_config = virtio_net_get_config;

    n->vdev.set_config = virtio_net_set_config;

    n->vdev.get_features = virtio_net_get_features;

    n->vdev.set_features = virtio_net_set_features;

    n->vdev.bad_features = virtio_net_bad_features;

    n->vdev.reset = virtio_net_reset;

    n->rx_vq = virtio_add_queue(&n->vdev, 256, virtio_net_handle_rx);

    n->tx_vq = virtio_add_queue(&n->vdev, 256, virtio_net_handle_tx);

    n->ctrl_vq = virtio_add_queue(&n->vdev, 16, virtio_net_handle_ctrl);

    memcpy(n->mac, nd->macaddr, ETH_ALEN);

    n->status = VIRTIO_NET_S_LINK_UP;

    n->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                 virtio_net_receive, virtio_net_can_receive, n);

    n->vc->link_status_changed = virtio_net_set_link_status;

    qemu_format_nic_info_str(n->vc, n->mac);

    n->tx_timer = qemu_new_timer(vm_clock, virtio_net_tx_timer, n);

    n->tx_timer_active = 0;

    n->mergeable_rx_bufs = 0;

    n->promisc = 1; /* for compatibility */

    n->mac_table.macs = qemu_mallocz(MAC_TABLE_ENTRIES * ETH_ALEN);

    n->vlans = qemu_mallocz(MAX_VLAN >> 3);

    register_savevm("virtio-net", virtio_net_id++, VIRTIO_NET_VM_VERSION,

                    virtio_net_save, virtio_net_load, n);

    return (PCIDevice *)n;

}


static inline void RENAME(rgb15to16)(const uint8_t *src, uint8_t *dst, int src_size)

{

    register const uint8_t* s=src;

    register uint8_t* d=dst;

    register const uint8_t *end;

    const uint8_t *mm_end;

    end = s + src_size;

    __asm__ volatile(PREFETCH"    %0"::"m"(*s));

    __asm__ volatile("movq        %0, %%mm4"::"m"(mask15s));

    mm_end = end - 15;

    while (s<mm_end) {

        __asm__ volatile(

            PREFETCH"  32%1         \n\t"

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

            "movq       8%1, %%mm2  \n\t"

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

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

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

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

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

            "paddw    %%mm3, %%mm2  \n\t"

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

            MOVNTQ"   %%mm2, 8%0"

            :"=m"(*d)

            :"m"(*s)

        );

        d+=16;

        s+=16;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    mm_end = end - 3;

    while (s < mm_end) {

        register unsigned x= *((const uint32_t *)s);

        *((uint32_t *)d) = (x&0x7FFF7FFF) + (x&0x7FE07FE0);

        d+=4;

        s+=4;

    }

    if (s < end) {

        register unsigned short x= *((const uint16_t *)s);

        *((uint16_t *)d) = (x&0x7FFF) + (x&0x7FE0);

    }

}


static inline void RENAME(rgb15to32)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (const uint16_t *)src;

	end = s + src_size/2;

#ifdef HAVE_MMX

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

	__asm __volatile("pxor	%%mm7,%%mm7\n\t":::"memory");

	mm_end = end - 3;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

		"punpcklwd %%mm7, %%mm1\n\t"

		"punpcklwd %%mm7, %%mm2\n\t"

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

		"punpckhwd %%mm7, %%mm4\n\t"

		"punpckhwd %%mm7, %%mm5\n\t"

		"psllq	$8, %%mm1\n\t"

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

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

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

		"psllq	$8, %%mm4\n\t"

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

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

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

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

		MOVNTQ"	%%mm3, 8%0\n\t"

		:"=m"(*d)

		:"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r)

		:"memory");

		d += 16;

		s += 4;

	}

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

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

#endif

	while(s < end)

	{

#if 0 //slightly slower on athlon

		int bgr= *s++;

		*((uint32_t*)d)++ = ((bgr&0x1F)<<3) + ((bgr&0x3E0)<<6) + ((bgr&0x7C00)<<9);

#else

		register uint16_t bgr;

		bgr = *s++;

#ifdef WORDS_BIGENDIAN

		*d++ = 0;

		*d++ = (bgr&0x7C00)>>7;

		*d++ = (bgr&0x3E0)>>2;

		*d++ = (bgr&0x1F)<<3;

#else

		*d++ = (bgr&0x1F)<<3;

		*d++ = (bgr&0x3E0)>>2;

		*d++ = (bgr&0x7C00)>>7;

		*d++ = 0;

#endif

#endif

	}

}


static void tap_send(void *opaque)

{

    TAPState *s = opaque;

    int size;

    do {

        uint8_t *buf = s->buf;

        size = tap_read_packet(s->fd, s->buf, sizeof(s->buf));

        if (size <= 0) {

            break;

        }

        if (s->host_vnet_hdr_len && !s->using_vnet_hdr) {

            buf  += s->host_vnet_hdr_len;

            size -= s->host_vnet_hdr_len;

        }

        size = qemu_send_packet_async(&s->nc, buf, size, tap_send_completed);

        if (size == 0) {

            tap_read_poll(s, false);

        }

    } while (size > 0 && qemu_can_send_packet(&s->nc));

}


int decode_splitmvs(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb, int layout)

{

    int part_idx;

    int n, num;

    VP8Macroblock *top_mb;

    VP8Macroblock *left_mb = &mb[-1];

    const uint8_t *mbsplits_left = vp8_mbsplits[left_mb->partitioning];

    const uint8_t *mbsplits_top, *mbsplits_cur, *firstidx;

    VP56mv *top_mv;

    VP56mv *left_mv = left_mb->bmv;

    VP56mv *cur_mv  = mb->bmv;

    if (!layout) // layout is inlined, s->mb_layout is not

        top_mb = &mb[2];

    else

        top_mb = &mb[-s->mb_width - 1];

    mbsplits_top = vp8_mbsplits[top_mb->partitioning];

    top_mv       = top_mb->bmv;

    if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[0])) {

        if (vp56_rac_get_prob_branchy(c, vp8_mbsplit_prob[1]))

            part_idx = VP8_SPLITMVMODE_16x8 + vp56_rac_get_prob(c, vp8_mbsplit_prob[2]);

        else

            part_idx = VP8_SPLITMVMODE_8x8;

    } else {

        part_idx = VP8_SPLITMVMODE_4x4;

    }

    num              = vp8_mbsplit_count[part_idx];

    mbsplits_cur     = vp8_mbsplits[part_idx],

    firstidx         = vp8_mbfirstidx[part_idx];

    mb->partitioning = part_idx;

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

        int k = firstidx[n];

        uint32_t left, above;

        const uint8_t *submv_prob;

        if (!(k & 3))

            left = AV_RN32A(&left_mv[mbsplits_left[k + 3]]);

        else

            left = AV_RN32A(&cur_mv[mbsplits_cur[k - 1]]);

        if (k <= 3)

            above = AV_RN32A(&top_mv[mbsplits_top[k + 12]]);

        else

            above = AV_RN32A(&cur_mv[mbsplits_cur[k - 4]]);

        submv_prob = get_submv_prob(left, above);

        if (vp56_rac_get_prob_branchy(c, submv_prob[0])) {

            if (vp56_rac_get_prob_branchy(c, submv_prob[1])) {

                if (vp56_rac_get_prob_branchy(c, submv_prob[2])) {

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

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

                } else {

                    AV_ZERO32(&mb->bmv[n]);

                }

            } else {

                AV_WN32A(&mb->bmv[n], above);

            }

        } else {

            AV_WN32A(&mb->bmv[n], left);

        }

    }

    return num;

}


static inline void FUNC(idctSparseColPut)(pixel *dest, int line_size,

                                          DCTELEM *col)

{

    int a0, a1, a2, a3, b0, b1, b2, b3;

    INIT_CLIP;

    IDCT_COLS;

    dest[0] = CLIP((a0 + b0) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a1 + b1) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a2 + b2) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a3 + b3) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a3 - b3) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a2 - b2) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a1 - b1) >> COL_SHIFT);

    dest += line_size;

    dest[0] = CLIP((a0 - b0) >> COL_SHIFT);

}


void hbitmap_reset(HBitmap *hb, uint64_t start, uint64_t count)

{

    /* Compute range in the last layer.  */

    uint64_t last = start + count - 1;

    trace_hbitmap_reset(hb, start, count,

                        start >> hb->granularity, last >> hb->granularity);

    start >>= hb->granularity;

    last >>= hb->granularity;

    hb->count -= hb_count_between(hb, start, last);

    hb_reset_between(hb, HBITMAP_LEVELS - 1, start, last);

}


static int raw_create(const char *filename, QemuOpts *opts, Error **errp)

{

    int fd;

    int result = 0;

    int64_t total_size = 0;

    bool nocow = false;

    PreallocMode prealloc;

    char *buf = NULL;

    Error *local_err = NULL;

    strstart(filename, "file:", &filename);

    /* Read out options */

    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                          BDRV_SECTOR_SIZE);

    nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);

    buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);

    prealloc = qapi_enum_parse(PreallocMode_lookup, buf,

                               PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,

                               &local_err);

    g_free(buf);

    if (local_err) {

        error_propagate(errp, local_err);

        result = -EINVAL;

        goto out;

    }

    fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,

                   0644);

    if (fd < 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not create file");

        goto out;

    }

    if (nocow) {

#ifdef __linux__

        /* Set NOCOW flag to solve performance issue on fs like btrfs.

         * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value

         * will be ignored since any failure of this operation should not

         * block the left work.

         */

        int attr;

        if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {

            attr |= FS_NOCOW_FL;

            ioctl(fd, FS_IOC_SETFLAGS, &attr);

        }

#endif

    }

    if (ftruncate(fd, total_size) != 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not resize file");

        goto out_close;

    }

    switch (prealloc) {

#ifdef CONFIG_POSIX_FALLOCATE

    case PREALLOC_MODE_FALLOC:

        /* posix_fallocate() doesn't set errno. */

        result = -posix_fallocate(fd, 0, total_size);

        if (result != 0) {

            error_setg_errno(errp, -result,

                             "Could not preallocate data for the new file");

        }

        break;

#endif

    case PREALLOC_MODE_FULL:

    {

        int64_t num = 0, left = total_size;

        buf = g_malloc0(65536);

        while (left > 0) {

            num = MIN(left, 65536);

            result = write(fd, buf, num);

            if (result < 0) {

                result = -errno;

                error_setg_errno(errp, -result,

                                 "Could not write to the new file");

                break;

            }

            left -= result;

        }

        if (result >= 0) {

            result = fsync(fd);

            if (result < 0) {

                result = -errno;

                error_setg_errno(errp, -result,

                                 "Could not flush new file to disk");

            }

        }

        g_free(buf);

        break;

    }

    case PREALLOC_MODE_OFF:

        break;

    default:

        result = -EINVAL;

        error_setg(errp, "Unsupported preallocation mode: %s",

                   PreallocMode_lookup[prealloc]);

        break;

    }

out_close:

    if (qemu_close(fd) != 0 && result == 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not close the new file");

    }

out:

    return result;

}


static int aasc_decode_frame(AVCodecContext *avctx,

                              void *data, int *got_frame,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    AascContext *s     = avctx->priv_data;

    int compr, i, stride, ret;

    if (buf_size < 4)

    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return ret;

    }

    compr     = AV_RL32(buf);

    buf      += 4;

    buf_size -= 4;

    switch (compr) {

    case 0:

        stride = (avctx->width * 3 + 3) & ~3;

        for (i = avctx->height - 1; i >= 0; i--) {

            memcpy(s->frame->data[0] + i * s->frame->linesize[0], buf, avctx->width * 3);

            buf += stride;

        }

        break;

    case 1:

        bytestream2_init(&s->gb, buf, buf_size);

        ff_msrle_decode(avctx, (AVPicture*)s->frame, 8, &s->gb);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr);

    }

    *got_frame = 1;

    if ((ret = av_frame_ref(data, s->frame)) < 0)

        return ret;

    /* report that the buffer was completely consumed */

    return buf_size;

}


void mips_malta_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    ram_addr_t ram_low_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    char *filename;

    pflash_t *fl;

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *ram_high = g_new(MemoryRegion, 1);

    MemoryRegion *ram_low_preio = g_new(MemoryRegion, 1);

    MemoryRegion *ram_low_postio;

    MemoryRegion *bios, *bios_copy = g_new(MemoryRegion, 1);

    target_long bios_size = FLASH_SIZE;

    const size_t smbus_eeprom_size = 8 * 256;

    uint8_t *smbus_eeprom_buf = g_malloc0(smbus_eeprom_size);

    int64_t kernel_entry, bootloader_run_addr;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    MIPSCPU *cpu;

    CPUMIPSState *env;

    qemu_irq *isa_irq;

    qemu_irq *cpu_exit_irq;

    int piix4_devfn;

    I2CBus *smbus;

    int i;

    DriveInfo *dinfo;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    int fl_idx = 0;

    int fl_sectors = bios_size >> 16;

    int be;

    DeviceState *dev = qdev_create(NULL, TYPE_MIPS_MALTA);

    MaltaState *s = MIPS_MALTA(dev);

    /* The whole address space decoded by the GT-64120A doesn't generate

       exception when accessing invalid memory. Create an empty slot to

       emulate this feature. */

    empty_slot_init(0, 0x20000000);

    qdev_init_nofail(dev);

    /* Make sure the first 3 serial ports are associated with a device. */

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

        if (!serial_hds[i]) {

            char label[32];

            snprintf(label, sizeof(label), "serial%d", i);

            serial_hds[i] = qemu_chr_new(label, "null", NULL);

        }

    }

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "20Kc";

#else

        cpu_model = "24Kf";

#endif

    }

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

        cpu = cpu_mips_init(cpu_model);

        if (cpu == NULL) {

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

            exit(1);

        }

        env = &cpu->env;

        /* Init internal devices */

        cpu_mips_irq_init_cpu(env);

        cpu_mips_clock_init(env);

        qemu_register_reset(main_cpu_reset, cpu);

    }

    cpu = MIPS_CPU(first_cpu);

    env = &cpu->env;

    /* allocate RAM */

    if (ram_size > (2048u << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 2048 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    /* register RAM at high address where it is undisturbed by IO */

    memory_region_allocate_system_memory(ram_high, NULL, "mips_malta.ram",

                                         ram_size);

    memory_region_add_subregion(system_memory, 0x80000000, ram_high);

    /* alias for pre IO hole access */

    memory_region_init_alias(ram_low_preio, NULL, "mips_malta_low_preio.ram",

                             ram_high, 0, MIN(ram_size, (256 << 20)));

    memory_region_add_subregion(system_memory, 0, ram_low_preio);

    /* alias for post IO hole access, if there is enough RAM */

    if (ram_size > (512 << 20)) {

        ram_low_postio = g_new(MemoryRegion, 1);

        memory_region_init_alias(ram_low_postio, NULL,

                                 "mips_malta_low_postio.ram",

                                 ram_high, 512 << 20,

                                 ram_size - (512 << 20));

        memory_region_add_subregion(system_memory, 512 << 20, ram_low_postio);

    }

    /* generate SPD EEPROM data */

    generate_eeprom_spd(&smbus_eeprom_buf[0 * 256], ram_size);

    generate_eeprom_serial(&smbus_eeprom_buf[6 * 256]);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    /* FPGA */

    /* The CBUS UART is attached to the MIPS CPU INT2 pin, ie interrupt 4 */

    malta_fpga_init(system_memory, FPGA_ADDRESS, env->irq[4], serial_hds[2]);

    /* Load firmware in flash / BIOS. */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

#ifdef DEBUG_BOARD_INIT

    if (dinfo) {

        printf("Register parallel flash %d size " TARGET_FMT_lx " at "

               "addr %08llx '%s' %x\n",

               fl_idx, bios_size, FLASH_ADDRESS,

               blk_name(dinfo->bdrv), fl_sectors);

    }

#endif

    fl = pflash_cfi01_register(FLASH_ADDRESS, NULL, "mips_malta.bios",

                               BIOS_SIZE,

                               dinfo ? blk_by_legacy_dinfo(dinfo) : NULL,

                               65536, fl_sectors,

                               4, 0x0000, 0x0000, 0x0000, 0x0000, be);

    bios = pflash_cfi01_get_memory(fl);

    fl_idx++;

    if (kernel_filename) {

        ram_low_size = MIN(ram_size, 256 << 20);

        /* For KVM we reserve 1MB of RAM for running bootloader */

        if (kvm_enabled()) {

            ram_low_size -= 0x100000;

            bootloader_run_addr = 0x40000000 + ram_low_size;

        } else {

            bootloader_run_addr = 0xbfc00000;

        }

        /* Write a small bootloader to the flash location. */

        loaderparams.ram_size = ram_low_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        kernel_entry = load_kernel();

        write_bootloader(env, memory_region_get_ram_ptr(bios),

                         bootloader_run_addr, kernel_entry);

        if (kvm_enabled()) {

            /* Write the bootloader code @ the end of RAM, 1MB reserved */

            write_bootloader(env, memory_region_get_ram_ptr(ram_low_preio) +

                                    ram_low_size,

                             bootloader_run_addr, kernel_entry);

        }

    } else {

        /* The flash region isn't executable from a KVM guest */

        if (kvm_enabled()) {

            error_report("KVM enabled but no -kernel argument was specified. "

                         "Booting from flash is not supported with KVM.");

            exit(1);

        }

        /* Load firmware from flash. */

        if (!dinfo) {

            /* Load a BIOS image. */

            if (bios_name == NULL) {

                bios_name = BIOS_FILENAME;

            }

            filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

            if (filename) {

                bios_size = load_image_targphys(filename, FLASH_ADDRESS,

                                                BIOS_SIZE);

                g_free(filename);

            } else {

                bios_size = -1;

            }

            if ((bios_size < 0 || bios_size > BIOS_SIZE) &&

                !kernel_filename && !qtest_enabled()) {

                error_report("Could not load MIPS bios '%s', and no "

                             "-kernel argument was specified", bios_name);

                exit(1);

            }

        }

        /* In little endian mode the 32bit words in the bios are swapped,

           a neat trick which allows bi-endian firmware. */

#ifndef TARGET_WORDS_BIGENDIAN

        {

            uint32_t *end, *addr = rom_ptr(FLASH_ADDRESS);

            if (!addr) {

                addr = memory_region_get_ram_ptr(bios);

            }

            end = (void *)addr + MIN(bios_size, 0x3e0000);

            while (addr < end) {

                bswap32s(addr);

                addr++;

            }

        }

#endif

    }

    /*

     * Map the BIOS at a 2nd physical location, as on the real board.

     * Copy it so that we can patch in the MIPS revision, which cannot be

     * handled by an overlapping region as the resulting ROM code subpage

     * regions are not executable.

     */

    memory_region_init_ram(bios_copy, NULL, "bios.1fc", BIOS_SIZE,

                           &error_abort);

    if (!rom_copy(memory_region_get_ram_ptr(bios_copy),

                  FLASH_ADDRESS, BIOS_SIZE)) {

        memcpy(memory_region_get_ram_ptr(bios_copy),

               memory_region_get_ram_ptr(bios), BIOS_SIZE);

    }

    memory_region_set_readonly(bios_copy, true);

    memory_region_add_subregion(system_memory, RESET_ADDRESS, bios_copy);

    /* Board ID = 0x420 (Malta Board with CoreLV) */

    stl_p(memory_region_get_ram_ptr(bios_copy) + 0x10, 0x00000420);

    /* Init internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /*

     * We have a circular dependency problem: pci_bus depends on isa_irq,

     * isa_irq is provided by i8259, i8259 depends on ISA, ISA depends

     * on piix4, and piix4 depends on pci_bus.  To stop the cycle we have

     * qemu_irq_proxy() adds an extra bit of indirection, allowing us

     * to resolve the isa_irq -> i8259 dependency after i8259 is initialized.

     */

    isa_irq = qemu_irq_proxy(&s->i8259, 16);

    /* Northbridge */

    pci_bus = gt64120_register(isa_irq);

    /* Southbridge */

    ide_drive_get(hd, ARRAY_SIZE(hd));

    piix4_devfn = piix4_init(pci_bus, &isa_bus, 80);

    /* Interrupt controller */

    /* The 8259 is attached to the MIPS CPU INT0 pin, ie interrupt 2 */

    s->i8259 = i8259_init(isa_bus, env->irq[2]);

    isa_bus_irqs(isa_bus, s->i8259);

    pci_piix4_ide_init(pci_bus, hd, piix4_devfn + 1);

    pci_create_simple(pci_bus, piix4_devfn + 2, "piix4-usb-uhci");

    smbus = piix4_pm_init(pci_bus, piix4_devfn + 3, 0x1100,

                          isa_get_irq(NULL, 9), NULL, 0, NULL, NULL);

    smbus_eeprom_init(smbus, 8, smbus_eeprom_buf, smbus_eeprom_size);

    g_free(smbus_eeprom_buf);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

    /* Super I/O */

    isa_create_simple(isa_bus, "i8042");

    rtc_init(isa_bus, 2000, NULL);

    serial_hds_isa_init(isa_bus, 2);

    parallel_hds_isa_init(isa_bus, 1);

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(isa_bus, fd);

    /* Network card */

    network_init(pci_bus);

    /* Optional PCI video card */

    pci_vga_init(pci_bus);

}


static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,

                              const char *desc_file_path, QDict *options,

                              Error **errp)

{

    int ret;

    int matches;

    char access[11];

    char type[11];

    char fname[512];

    const char *p = desc;

    int64_t sectors = 0;

    int64_t flat_offset;

    char *extent_path;

    BdrvChild *extent_file;

    BDRVVmdkState *s = bs->opaque;

    VmdkExtent *extent;

    char extent_opt_prefix[32];

    Error *local_err = NULL;

    while (*p) {

        /* parse extent line in one of below formats:

         *

         * RW [size in sectors] FLAT "file-name.vmdk" OFFSET

         * RW [size in sectors] SPARSE "file-name.vmdk"

         * RW [size in sectors] VMFS "file-name.vmdk"

         * RW [size in sectors] VMFSSPARSE "file-name.vmdk"

         */

        flat_offset = -1;

        matches = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,

                         access, &sectors, type, fname, &flat_offset);

        if (matches < 4 || strcmp(access, "RW")) {

            goto next_line;

        } else if (!strcmp(type, "FLAT")) {

            if (matches != 5 || flat_offset < 0) {

                error_setg(errp, "Invalid extent lines: \n%s", p);

                return -EINVAL;

            }

        } else if (!strcmp(type, "VMFS")) {

            if (matches == 4) {

                flat_offset = 0;

            } else {

                error_setg(errp, "Invalid extent lines:\n%s", p);

                return -EINVAL;

            }

        } else if (matches != 4) {

            error_setg(errp, "Invalid extent lines:\n%s", p);

            return -EINVAL;

        }

        if (sectors <= 0 ||

            (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&

             strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||

            (strcmp(access, "RW"))) {

            goto next_line;

        }

        if (!path_is_absolute(fname) && !path_has_protocol(fname) &&

            !desc_file_path[0])

        {

            error_setg(errp, "Cannot use relative extent paths with VMDK "

                       "descriptor file '%s'", bs->file->bs->filename);

            return -EINVAL;

        }

        extent_path = g_malloc0(PATH_MAX);

        path_combine(extent_path, PATH_MAX, desc_file_path, fname);

        ret = snprintf(extent_opt_prefix, 32, "extents.%d", s->num_extents);

        assert(ret < 32);

        extent_file = bdrv_open_child(extent_path, options, extent_opt_prefix,

                                      bs, &child_file, false, &local_err);

        g_free(extent_path);

        if (local_err) {

            error_propagate(errp, local_err);

            return -EINVAL;

        }

        /* save to extents array */

        if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {

            /* FLAT extent */

            ret = vmdk_add_extent(bs, extent_file, true, sectors,

                            0, 0, 0, 0, 0, &extent, errp);

            if (ret < 0) {

                bdrv_unref_child(bs, extent_file);

                return ret;

            }

            extent->flat_start_offset = flat_offset << 9;

        } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {

            /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/

            char *buf = vmdk_read_desc(extent_file->bs, 0, errp);

            if (!buf) {

                ret = -EINVAL;

            } else {

                ret = vmdk_open_sparse(bs, extent_file, bs->open_flags, buf,

                                       options, errp);

            }

            g_free(buf);

            if (ret) {

                bdrv_unref_child(bs, extent_file);

                return ret;

            }

            extent = &s->extents[s->num_extents - 1];

        } else {

            error_setg(errp, "Unsupported extent type '%s'", type);

            bdrv_unref_child(bs, extent_file);

            return -ENOTSUP;

        }

        extent->type = g_strdup(type);

next_line:

        /* move to next line */

        while (*p) {

            if (*p == '\n') {

                p++;

                break;

            }

            p++;

        }

    }

    return 0;

}


static void external_snapshot_prepare(BlkTransactionState *common,

                                      Error **errp)

{

    BlockDriver *drv;

    int flags, ret;

    QDict *options = NULL;

    Error *local_err = NULL;

    bool has_device = false;

    const char *device;

    bool has_node_name = false;

    const char *node_name;

    bool has_snapshot_node_name = false;

    const char *snapshot_node_name;

    const char *new_image_file;

    const char *format = "qcow2";

    enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    ExternalSnapshotState *state =

                             DO_UPCAST(ExternalSnapshotState, common, common);

    TransactionAction *action = common->action;

    /* get parameters */

    g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);

    has_device = action->blockdev_snapshot_sync->has_device;

    device = action->blockdev_snapshot_sync->device;

    has_node_name = action->blockdev_snapshot_sync->has_node_name;

    node_name = action->blockdev_snapshot_sync->node_name;

    has_snapshot_node_name =

        action->blockdev_snapshot_sync->has_snapshot_node_name;

    snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;

    new_image_file = action->blockdev_snapshot_sync->snapshot_file;

    if (action->blockdev_snapshot_sync->has_format) {

        format = action->blockdev_snapshot_sync->format;

    }

    if (action->blockdev_snapshot_sync->has_mode) {

        mode = action->blockdev_snapshot_sync->mode;

    }

    /* start processing */

    drv = bdrv_find_format(format);

    if (!drv) {

        error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);

        return;

    }

    state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,

                                   has_node_name ? node_name : NULL,

                                   &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (has_node_name && !has_snapshot_node_name) {

        error_setg(errp, "New snapshot node name missing");

        return;

    }

    if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {

        error_setg(errp, "New snapshot node name already existing");

        return;

    }

    if (!bdrv_is_inserted(state->old_bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (bdrv_in_use(state->old_bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, device);

        return;

    }

    if (!bdrv_is_read_only(state->old_bs)) {

        if (bdrv_flush(state->old_bs)) {

            error_set(errp, QERR_IO_ERROR);

            return;

        }

    }

    if (!bdrv_is_first_non_filter(state->old_bs)) {

        error_set(errp, QERR_FEATURE_DISABLED, "snapshot");

        return;

    }

    flags = state->old_bs->open_flags;

    /* create new image w/backing file */

    if (mode != NEW_IMAGE_MODE_EXISTING) {

        bdrv_img_create(new_image_file, format,

                        state->old_bs->filename,

                        state->old_bs->drv->format_name,

                        NULL, -1, flags, &local_err, false);

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

    }

    if (has_snapshot_node_name) {

        options = qdict_new();

        qdict_put(options, "node-name",

                  qstring_from_str(snapshot_node_name));

    }

    /* TODO Inherit bs->options or only take explicit options with an

     * extended QMP command? */

    assert(state->new_bs == NULL);

    ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,

                    flags | BDRV_O_NO_BACKING, drv, &local_err);

    /* We will manually add the backing_hd field to the bs later */

    if (ret != 0) {

        error_propagate(errp, local_err);

    }

}


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

{

	TCGv t0, t_31;

	t0 = tcg_temp_new(TCG_TYPE_TL);

	t_31 = tcg_const_tl(31);

	tcg_gen_shl_tl(d, a, b);

	tcg_gen_sub_tl(t0, t_31, b);

	tcg_gen_sar_tl(t0, t0, t_31);

	tcg_gen_and_tl(t0, t0, d);

	tcg_gen_xor_tl(d, d, t0);

	tcg_temp_free(t0);

	tcg_temp_free(t_31);

}


int unix_listen_opts(QemuOpts *opts, Error **errp)

{

    struct sockaddr_un un;

    const char *path = qemu_opt_get(opts, "path");

    int sock, fd;

    sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

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

        return -1;

    }

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

    un.sun_family = AF_UNIX;

    if (path && strlen(path)) {

        snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);

    } else {

        char *tmpdir = getenv("TMPDIR");

        snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",

                 tmpdir ? tmpdir : "/tmp");

        /*

         * This dummy fd usage silences the mktemp() unsecure warning.

         * Using mkstemp() doesn't make things more secure here

         * though.  bind() complains about existing files, so we have

         * to unlink first and thus re-open the race window.  The

         * worst case possible is bind() failing, i.e. a DoS attack.

         */

        fd = mkstemp(un.sun_path); close(fd);

        qemu_opt_set(opts, "path", un.sun_path);

    }

    unlink(un.sun_path);

    if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

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

        goto err;

    }

    if (listen(sock, 1) < 0) {

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

        goto err;

    }

    return sock;

err:

    closesocket(sock);

    return -1;

}


int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs, int stream)

{

    int matches = 1;

#define CHECK_CODEC(x)  (ccf->x != ccs->x)

    if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {

        http_log("Codecs do not match for stream %d\n", stream);

        matches = 0;

    } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {

        http_log("Codec bitrates do not match for stream %d\n", stream);

        matches = 0;

    } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {

        if (CHECK_CODEC(time_base.den) ||

            CHECK_CODEC(time_base.num) ||

            CHECK_CODEC(width) ||

            CHECK_CODEC(height)) {

            http_log("Codec width, height or framerate do not match for stream %d\n", stream);

            matches = 0;

        }

    } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {

        if (CHECK_CODEC(sample_rate) ||

            CHECK_CODEC(channels) ||

            CHECK_CODEC(frame_size)) {

            http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);

            matches = 0;

        }

    } else {

        http_log("Unknown codec type for stream %d\n", stream);

        matches = 0;

    }

    return matches;

}


void memory_region_add_subregion(MemoryRegion *mr,

                                 hwaddr offset,

                                 MemoryRegion *subregion)

{

    subregion->may_overlap = false;

    subregion->priority = 0;

    memory_region_add_subregion_common(mr, offset, subregion);

}


static void xen_be_evtchn_event(void *opaque)

{

    struct XenDevice *xendev = opaque;

    evtchn_port_t port;

    port = xc_evtchn_pending(xendev->evtchndev);

    if (port != xendev->local_port) {

        xen_be_printf(xendev, 0, "xc_evtchn_pending returned %d (expected %d)\n",

                      port, xendev->local_port);

        return;

    }

    xc_evtchn_unmask(xendev->evtchndev, port);

    if (xendev->ops->event) {

        xendev->ops->event(xendev);

    }

}


static void qpi_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    CPUState *env;

    env = cpu_single_env;

    if (!env)

        return;

    env->eflags = (env->eflags & ~(IF_MASK | IOPL_MASK)) |

        (val & (IF_MASK | IOPL_MASK));

}


static int pci_apb_map_irq(PCIDevice *pci_dev, int irq_num)

{

    return ((pci_dev->devfn & 0x18) >> 1) + irq_num;

}


static void mirror_read_complete(void *opaque, int ret)

{

    MirrorOp *op = opaque;

    MirrorBlockJob *s = op->s;

    aio_context_acquire(blk_get_aio_context(s->common.blk));

    if (ret < 0) {

        BlockErrorAction action;

        bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);

        action = mirror_error_action(s, true, -ret);

        if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {

            s->ret = ret;

        }

        mirror_iteration_done(op, ret);

    } else {

        blk_aio_pwritev(s->target, op->sector_num * BDRV_SECTOR_SIZE, &op->qiov,

                        0, mirror_write_complete, op);

    }

    aio_context_release(blk_get_aio_context(s->common.blk));

}


static struct omap_mpu_timer_s *omap_mpu_timer_init(MemoryRegion *system_memory,

                target_phys_addr_t base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_mpu_timer_s *s = (struct omap_mpu_timer_s *)

            g_malloc0(sizeof(struct omap_mpu_timer_s));

    s->irq = irq;

    s->clk = clk;

    s->timer = qemu_new_timer_ns(vm_clock, omap_timer_tick, s);

    s->tick = qemu_bh_new(omap_timer_fire, s);

    omap_mpu_timer_reset(s);

    omap_timer_clk_setup(s);

    memory_region_init_io(&s->iomem, &omap_mpu_timer_ops, s,

                          "omap-mpu-timer", 0x100);

    memory_region_add_subregion(system_memory, base, &s->iomem);

    return s;

}


static void arm_cpu_reset(CPUState *s)

{

    ARMCPU *cpu = ARM_CPU(s);

    ARMCPUClass *acc = ARM_CPU_GET_CLASS(cpu);

    CPUARMState *env = &cpu->env;

    acc->parent_reset(s);

    memset(env, 0, offsetof(CPUARMState, end_reset_fields));

    g_hash_table_foreach(cpu->cp_regs, cp_reg_reset, cpu);

    g_hash_table_foreach(cpu->cp_regs, cp_reg_check_reset, cpu);

    env->vfp.xregs[ARM_VFP_FPSID] = cpu->reset_fpsid;

    env->vfp.xregs[ARM_VFP_MVFR0] = cpu->mvfr0;

    env->vfp.xregs[ARM_VFP_MVFR1] = cpu->mvfr1;

    env->vfp.xregs[ARM_VFP_MVFR2] = cpu->mvfr2;

    cpu->power_state = cpu->start_powered_off ? PSCI_OFF : PSCI_ON;

    s->halted = cpu->start_powered_off;

    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {

        env->iwmmxt.cregs[ARM_IWMMXT_wCID] = 0x69051000 | 'Q';

    }

    if (arm_feature(env, ARM_FEATURE_AARCH64)) {

        /* 64 bit CPUs always start in 64 bit mode */

        env->aarch64 = 1;

#if defined(CONFIG_USER_ONLY)

        env->pstate = PSTATE_MODE_EL0t;

        /* Userspace expects access to DC ZVA, CTL_EL0 and the cache ops */

        env->cp15.sctlr_el[1] |= SCTLR_UCT | SCTLR_UCI | SCTLR_DZE;

        /* and to the FP/Neon instructions */

        env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 2, 3);

#else

        /* Reset into the highest available EL */

        if (arm_feature(env, ARM_FEATURE_EL3)) {

            env->pstate = PSTATE_MODE_EL3h;

        } else if (arm_feature(env, ARM_FEATURE_EL2)) {

            env->pstate = PSTATE_MODE_EL2h;

        } else {

            env->pstate = PSTATE_MODE_EL1h;

        }

        env->pc = cpu->rvbar;

#endif

    } else {

#if defined(CONFIG_USER_ONLY)

        /* Userspace expects access to cp10 and cp11 for FP/Neon */

        env->cp15.cpacr_el1 = deposit64(env->cp15.cpacr_el1, 20, 4, 0xf);

#endif

    }

#if defined(CONFIG_USER_ONLY)

    env->uncached_cpsr = ARM_CPU_MODE_USR;

    /* For user mode we must enable access to coprocessors */

    env->vfp.xregs[ARM_VFP_FPEXC] = 1 << 30;

    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {

        env->cp15.c15_cpar = 3;

    } else if (arm_feature(env, ARM_FEATURE_XSCALE)) {

        env->cp15.c15_cpar = 1;

    }

#else

    /* SVC mode with interrupts disabled.  */

    env->uncached_cpsr = ARM_CPU_MODE_SVC;

    env->daif = PSTATE_D | PSTATE_A | PSTATE_I | PSTATE_F;

    if (arm_feature(env, ARM_FEATURE_M)) {

        uint32_t initial_msp; /* Loaded from 0x0 */

        uint32_t initial_pc; /* Loaded from 0x4 */

        uint8_t *rom;

        if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {

            env->v7m.secure = true;

        }

        /* The reset value of this bit is IMPDEF, but ARM recommends

         * that it resets to 1, so QEMU always does that rather than making

         * it dependent on CPU model.

         */

        env->v7m.ccr = R_V7M_CCR_STKALIGN_MASK;

        /* Unlike A/R profile, M profile defines the reset LR value */

        env->regs[14] = 0xffffffff;

        /* Load the initial SP and PC from the vector table at address 0 */

        rom = rom_ptr(0);

        if (rom) {

            /* Address zero is covered by ROM which hasn't yet been

             * copied into physical memory.

             */

            initial_msp = ldl_p(rom);

            initial_pc = ldl_p(rom + 4);

        } else {

            /* Address zero not covered by a ROM blob, or the ROM blob

             * is in non-modifiable memory and this is a second reset after

             * it got copied into memory. In the latter case, rom_ptr

             * will return a NULL pointer and we should use ldl_phys instead.

             */

            initial_msp = ldl_phys(s->as, 0);

            initial_pc = ldl_phys(s->as, 4);

        }

        env->regs[13] = initial_msp & 0xFFFFFFFC;

        env->regs[15] = initial_pc & ~1;

        env->thumb = initial_pc & 1;

    }

    /* AArch32 has a hard highvec setting of 0xFFFF0000.  If we are currently

     * executing as AArch32 then check if highvecs are enabled and

     * adjust the PC accordingly.

     */

    if (A32_BANKED_CURRENT_REG_GET(env, sctlr) & SCTLR_V) {

        env->regs[15] = 0xFFFF0000;

    }

    env->vfp.xregs[ARM_VFP_FPEXC] = 0;

#endif

    if (arm_feature(env, ARM_FEATURE_PMSA)) {

        if (cpu->pmsav7_dregion > 0) {

            if (arm_feature(env, ARM_FEATURE_V8)) {

                memset(env->pmsav8.rbar[M_REG_NS], 0,

                       sizeof(*env->pmsav8.rbar[M_REG_NS])

                       * cpu->pmsav7_dregion);

                memset(env->pmsav8.rlar[M_REG_NS], 0,

                       sizeof(*env->pmsav8.rlar[M_REG_NS])

                       * cpu->pmsav7_dregion);

                if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {

                    memset(env->pmsav8.rbar[M_REG_S], 0,

                           sizeof(*env->pmsav8.rbar[M_REG_S])

                           * cpu->pmsav7_dregion);

                    memset(env->pmsav8.rlar[M_REG_S], 0,

                           sizeof(*env->pmsav8.rlar[M_REG_S])

                           * cpu->pmsav7_dregion);

                }

            } else if (arm_feature(env, ARM_FEATURE_V7)) {

                memset(env->pmsav7.drbar, 0,

                       sizeof(*env->pmsav7.drbar) * cpu->pmsav7_dregion);

                memset(env->pmsav7.drsr, 0,

                       sizeof(*env->pmsav7.drsr) * cpu->pmsav7_dregion);

                memset(env->pmsav7.dracr, 0,

                       sizeof(*env->pmsav7.dracr) * cpu->pmsav7_dregion);

            }

        }

        env->pmsav7.rnr[M_REG_NS] = 0;

        env->pmsav7.rnr[M_REG_S] = 0;

        env->pmsav8.mair0[M_REG_NS] = 0;

        env->pmsav8.mair0[M_REG_S] = 0;

        env->pmsav8.mair1[M_REG_NS] = 0;

        env->pmsav8.mair1[M_REG_S] = 0;

    }

    set_flush_to_zero(1, &env->vfp.standard_fp_status);

    set_flush_inputs_to_zero(1, &env->vfp.standard_fp_status);

    set_default_nan_mode(1, &env->vfp.standard_fp_status);

    set_float_detect_tininess(float_tininess_before_rounding,

                              &env->vfp.fp_status);

    set_float_detect_tininess(float_tininess_before_rounding,

                              &env->vfp.standard_fp_status);

#ifndef CONFIG_USER_ONLY

    if (kvm_enabled()) {

        kvm_arm_reset_vcpu(cpu);

    }

#endif

    hw_breakpoint_update_all(cpu);

    hw_watchpoint_update_all(cpu);

}


void json_start_array(QJSON *json, const char *name)

{

    json_emit_element(json, name);

    qstring_append(json->str, "[ ");

    json->omit_comma = true;

}


vreader_get_reader_by_id(vreader_id_t id)

{

    VReader *reader = NULL;

    VReaderListEntry *current_entry = NULL;

    if (id == (vreader_id_t) -1) {

        return NULL;

    }

    vreader_list_lock();

    for (current_entry = vreader_list_get_first(vreader_list); current_entry;

            current_entry = vreader_list_get_next(current_entry)) {

        VReader *creader = vreader_list_get_reader(current_entry);

        if (creader->id == id) {

            reader = creader;

            break;

        }

        vreader_free(creader);

    }

    vreader_list_unlock();

    return reader;

}


AVFilter **av_filter_next(AVFilter **filter)

{

    return filter ? ++filter : &registered_avfilters[0];

}


static void gem_cleanup(NetClientState *nc)

{

    GemState *s = qemu_get_nic_opaque(nc);

    DB_PRINT("\n");

    s->nic = NULL;

}


void qxl_render_cursor(PCIQXLDevice *qxl, QXLCommandExt *ext)

{

    QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

    QXLCursor *cursor;

    QEMUCursor *c;

    if (!qxl->ssd.ds->mouse_set || !qxl->ssd.ds->cursor_define) {

        return;

    }

    if (qxl->debug > 1 && cmd->type != QXL_CURSOR_MOVE) {

        fprintf(stderr, "%s", __FUNCTION__);

        qxl_log_cmd_cursor(qxl, cmd, ext->group_id);

        fprintf(stderr, "\n");

    }

    switch (cmd->type) {

    case QXL_CURSOR_SET:

        cursor = qxl_phys2virt(qxl, cmd->u.set.shape, ext->group_id);

        if (cursor->chunk.data_size != cursor->data_size) {

            fprintf(stderr, "%s: multiple chunks\n", __FUNCTION__);

            return;

        }

        c = qxl_cursor(qxl, cursor);

        if (c == NULL) {

            c = cursor_builtin_left_ptr();

        }

        qemu_mutex_lock(&qxl->ssd.lock);

        if (qxl->ssd.cursor) {

            cursor_put(qxl->ssd.cursor);

        }

        qxl->ssd.cursor = c;

        qxl->ssd.mouse_x = cmd->u.set.position.x;

        qxl->ssd.mouse_y = cmd->u.set.position.y;

        qemu_mutex_unlock(&qxl->ssd.lock);

        break;

    case QXL_CURSOR_MOVE:

        qemu_mutex_lock(&qxl->ssd.lock);

        qxl->ssd.mouse_x = cmd->u.position.x;

        qxl->ssd.mouse_y = cmd->u.position.y;

        qemu_mutex_unlock(&qxl->ssd.lock);

        break;

    }

}


static uint64_t qemu_opt_get_number_helper(QemuOpts *opts, const char *name,

                                           uint64_t defval, bool del)

{

    QemuOpt *opt = qemu_opt_find(opts, name);

    uint64_t ret = defval;

    if (opt == NULL) {

        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);

        if (desc && desc->def_value_str) {

            parse_option_number(name, desc->def_value_str, &ret, &error_abort);

        }

        return ret;

    }

    assert(opt->desc && opt->desc->type == QEMU_OPT_NUMBER);

    ret = opt->value.uint;

    if (del) {

        qemu_opt_del_all(opts, name);

    }

    return ret;

}


void helper_unlock(void)

{

    spin_unlock(&global_cpu_lock);

}


static void vmsvga_screen_dump(void *opaque, const char *filename, bool cswitch,

                               Error **errp)

{

    struct vmsvga_state_s *s = opaque;

    DisplaySurface *surface = qemu_console_surface(s->vga.con);

    if (!s->enable) {

        s->vga.screen_dump(&s->vga, filename, cswitch, errp);

        return;

    }

    if (surface_bits_per_pixel(surface) == 32) {

        DisplaySurface *ds = qemu_create_displaysurface_from(

                                 surface_width(surface),

                                 surface_height(surface),

                                 32,

                                 surface_stride(surface),

                                 s->vga.vram_ptr, false);

        ppm_save(filename, ds, errp);

        g_free(ds);

    }

}


static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size)

{

    char *value;

    int64_t off = avio_tell(s->pb);

    if ((unsigned)len >= (UINT_MAX - 1) / 2)

        return;

    value = av_malloc(2 * len + 1);

    if (!value)

        goto finish;

    if (type == 0) {         // UTF16-LE

        avio_get_str16le(s->pb, len, value, 2 * len + 1);

    } else if (type == -1) { // ASCII

        avio_read(s->pb, value, len);

        value[len]=0;

    } else if (type == 1) {  // byte array

        if (!strcmp(key, "WM/Picture")) { // handle cover art

            asf_read_picture(s, len);

        } else if (!strcmp(key, "ID3")) { // handle ID3 tag

            get_id3_tag(s, len);

        } else {

            av_log(s, AV_LOG_VERBOSE, "Unsupported byte array in tag %s.\n", key);

        }

        goto finish;

    } else if (type > 1 && type <= 5) {  // boolean or DWORD or QWORD or WORD

        uint64_t num = get_value(s->pb, type, type2_size);

        snprintf(value, len, "%"PRIu64, num);

    } else if (type == 6) { // (don't) handle GUID

        av_log(s, AV_LOG_DEBUG, "Unsupported GUID value in tag %s.\n", key);

        goto finish;

    } else {

        av_log(s, AV_LOG_DEBUG,

               "Unsupported value type %d in tag %s.\n", type, key);

        goto finish;

    }

    if (*value)

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

finish:

    av_freep(&value);

    avio_seek(s->pb, off + len, SEEK_SET);

}


void sth_tce(VIOsPAPRDevice *dev, uint64_t taddr, uint16_t val)

{

    val = tswap16(val);

    spapr_tce_dma_write(dev, taddr, &val, sizeof(val));

}


av_cold int ff_yuv2rgb_c_init_tables(SwsContext *c, const int inv_table[4], int fullRange,

                                     int brightness, int contrast, int saturation)

{

    const int isRgb =      c->dstFormat==PIX_FMT_RGB32

                        || c->dstFormat==PIX_FMT_RGB32_1

                        || c->dstFormat==PIX_FMT_BGR24

                        || c->dstFormat==PIX_FMT_RGB565BE

                        || c->dstFormat==PIX_FMT_RGB565LE

                        || c->dstFormat==PIX_FMT_RGB555BE

                        || c->dstFormat==PIX_FMT_RGB555LE

                        || c->dstFormat==PIX_FMT_RGB444BE

                        || c->dstFormat==PIX_FMT_RGB444LE

                        || c->dstFormat==PIX_FMT_RGB8

                        || c->dstFormat==PIX_FMT_RGB4

                        || c->dstFormat==PIX_FMT_RGB4_BYTE

                        || c->dstFormat==PIX_FMT_MONOBLACK;

    const int isNotNe =    c->dstFormat==PIX_FMT_NE(RGB565LE,RGB565BE)

                        || c->dstFormat==PIX_FMT_NE(RGB555LE,RGB555BE)

                        || c->dstFormat==PIX_FMT_NE(RGB444LE,RGB444BE)

                        || c->dstFormat==PIX_FMT_NE(BGR565LE,BGR565BE)

                        || c->dstFormat==PIX_FMT_NE(BGR555LE,BGR555BE)

                        || c->dstFormat==PIX_FMT_NE(BGR444LE,BGR444BE);

    const int bpp = c->dstFormatBpp;

    uint8_t *y_table;

    uint16_t *y_table16;

    uint32_t *y_table32;

    int i, base, rbase, gbase, bbase, abase, needAlpha;

    const int yoffs = fullRange ? 384 : 326;

    int64_t crv =  inv_table[0];

    int64_t cbu =  inv_table[1];

    int64_t cgu = -inv_table[2];

    int64_t cgv = -inv_table[3];

    int64_t cy  = 1<<16;

    int64_t oy  = 0;

    int64_t yb = 0;

    if (!fullRange) {

        cy = (cy*255) / 219;

        oy = 16<<16;

    } else {

        crv = (crv*224) / 255;

        cbu = (cbu*224) / 255;

        cgu = (cgu*224) / 255;

        cgv = (cgv*224) / 255;

    }

    cy  = (cy *contrast             ) >> 16;

    crv = (crv*contrast * saturation) >> 32;

    cbu = (cbu*contrast * saturation) >> 32;

    cgu = (cgu*contrast * saturation) >> 32;

    cgv = (cgv*contrast * saturation) >> 32;

    oy -= 256*brightness;

    c->uOffset=   0x0400040004000400LL;

    c->vOffset=   0x0400040004000400LL;

    c->yCoeff=    roundToInt16(cy *8192) * 0x0001000100010001ULL;

    c->vrCoeff=   roundToInt16(crv*8192) * 0x0001000100010001ULL;

    c->ubCoeff=   roundToInt16(cbu*8192) * 0x0001000100010001ULL;

    c->vgCoeff=   roundToInt16(cgv*8192) * 0x0001000100010001ULL;

    c->ugCoeff=   roundToInt16(cgu*8192) * 0x0001000100010001ULL;

    c->yOffset=   roundToInt16(oy *   8) * 0x0001000100010001ULL;

    c->yuv2rgb_y_coeff  = (int16_t)roundToInt16(cy <<13);

    c->yuv2rgb_y_offset = (int16_t)roundToInt16(oy << 9);

    c->yuv2rgb_v2r_coeff= (int16_t)roundToInt16(crv<<13);

    c->yuv2rgb_v2g_coeff= (int16_t)roundToInt16(cgv<<13);

    c->yuv2rgb_u2g_coeff= (int16_t)roundToInt16(cgu<<13);

    c->yuv2rgb_u2b_coeff= (int16_t)roundToInt16(cbu<<13);

    //scale coefficients by cy

    crv = ((crv << 16) + 0x8000) / cy;

    cbu = ((cbu << 16) + 0x8000) / cy;

    cgu = ((cgu << 16) + 0x8000) / cy;

    cgv = ((cgv << 16) + 0x8000) / cy;

    av_free(c->yuvTable);

    switch (bpp) {

    case 1:

        c->yuvTable = av_malloc(1024);

        y_table = c->yuvTable;

        yb = -(384<<16) - oy;

        for (i = 0; i < 1024-110; i++) {

            y_table[i+110] = av_clip_uint8((yb + 0x8000) >> 16) >> 7;

            yb += cy;

        }

        fill_table(c->table_gU, 1, cgu, y_table + yoffs);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 4:

    case 4|128:

        rbase = isRgb ? 3 : 0;

        gbase = 1;

        bbase = isRgb ? 0 : 3;

        c->yuvTable = av_malloc(1024*3);

        y_table = c->yuvTable;

        yb = -(384<<16) - oy;

        for (i = 0; i < 1024-110; i++) {

            int yval = av_clip_uint8((yb + 0x8000) >> 16);

            y_table[i+110     ] =  (yval >> 7)       << rbase;

            y_table[i+ 37+1024] = ((yval + 43) / 85) << gbase;

            y_table[i+110+2048] =  (yval >> 7)       << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs + 1024);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs + 2048);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 8:

        rbase = isRgb ? 5 : 0;

        gbase = isRgb ? 2 : 3;

        bbase = isRgb ? 0 : 6;

        c->yuvTable = av_malloc(1024*3);

        y_table = c->yuvTable;

        yb = -(384<<16) - oy;

        for (i = 0; i < 1024-38; i++) {

            int yval = av_clip_uint8((yb + 0x8000) >> 16);

            y_table[i+16     ] = ((yval + 18) / 36) << rbase;

            y_table[i+16+1024] = ((yval + 18) / 36) << gbase;

            y_table[i+37+2048] = ((yval + 43) / 85) << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs + 1024);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs + 2048);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 12:

        rbase = isRgb ? 8 : 0;

        gbase = 4;

        bbase = isRgb ? 0 : 8;

        c->yuvTable = av_malloc(1024*3*2);

        y_table16 = c->yuvTable;

        yb = -(384<<16) - oy;

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

            uint8_t yval = av_clip_uint8((yb + 0x8000) >> 16);

            y_table16[i     ] = (yval >> 4) << rbase;

            y_table16[i+1024] = (yval >> 4) << gbase;

            y_table16[i+2048] = (yval >> 4) << bbase;

            yb += cy;

        }

        if (isNotNe)

            for (i = 0; i < 1024*3; i++)

                y_table16[i] = av_bswap16(y_table16[i]);

        fill_table(c->table_rV, 2, crv, y_table16 + yoffs);

        fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);

        fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);

        fill_gv_table(c->table_gV, 2, cgv);

        break;

    case 15:

    case 16:

        rbase = isRgb ? bpp - 5 : 0;

        gbase = 5;

        bbase = isRgb ? 0 : (bpp - 5);

        c->yuvTable = av_malloc(1024*3*2);

        y_table16 = c->yuvTable;

        yb = -(384<<16) - oy;

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

            uint8_t yval = av_clip_uint8((yb + 0x8000) >> 16);

            y_table16[i     ] = (yval >> 3)          << rbase;

            y_table16[i+1024] = (yval >> (18 - bpp)) << gbase;

            y_table16[i+2048] = (yval >> 3)          << bbase;

            yb += cy;

        }

        if(isNotNe)

            for (i = 0; i < 1024*3; i++)

                y_table16[i] = av_bswap16(y_table16[i]);

        fill_table(c->table_rV, 2, crv, y_table16 + yoffs);

        fill_table(c->table_gU, 2, cgu, y_table16 + yoffs + 1024);

        fill_table(c->table_bU, 2, cbu, y_table16 + yoffs + 2048);

        fill_gv_table(c->table_gV, 2, cgv);

        break;

    case 24:

    case 48:

        c->yuvTable = av_malloc(1024);

        y_table = c->yuvTable;

        yb = -(384<<16) - oy;

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

            y_table[i] = av_clip_uint8((yb + 0x8000) >> 16);

            yb += cy;

        }

        fill_table(c->table_rV, 1, crv, y_table + yoffs);

        fill_table(c->table_gU, 1, cgu, y_table + yoffs);

        fill_table(c->table_bU, 1, cbu, y_table + yoffs);

        fill_gv_table(c->table_gV, 1, cgv);

        break;

    case 32:

        base = (c->dstFormat == PIX_FMT_RGB32_1 || c->dstFormat == PIX_FMT_BGR32_1) ? 8 : 0;

        rbase = base + (isRgb ? 16 : 0);

        gbase = base + 8;

        bbase = base + (isRgb ? 0 : 16);

        needAlpha = CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat);

        if (!needAlpha)

            abase = (base + 24) & 31;

        c->yuvTable = av_malloc(1024*3*4);

        y_table32 = c->yuvTable;

        yb = -(384<<16) - oy;

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

            unsigned yval = av_clip_uint8((yb + 0x8000) >> 16);

            y_table32[i     ] = (yval << rbase) + (needAlpha ? 0 : (255u << abase));

            y_table32[i+1024] = yval << gbase;

            y_table32[i+2048] = yval << bbase;

            yb += cy;

        }

        fill_table(c->table_rV, 4, crv, y_table32 + yoffs);

        fill_table(c->table_gU, 4, cgu, y_table32 + yoffs + 1024);

        fill_table(c->table_bU, 4, cbu, y_table32 + yoffs + 2048);

        fill_gv_table(c->table_gV, 4, cgv);

        break;

    default:

        c->yuvTable = NULL;

        av_log(c, AV_LOG_ERROR, "%ibpp not supported by yuv2rgb\n", bpp);

        return -1;

    }

    return 0;

}


static inline int opsize_bytes(int opsize)

{

    switch (opsize) {

    case OS_BYTE: return 1;

    case OS_WORD: return 2;

    case OS_LONG: return 4;

    case OS_SINGLE: return 4;

    case OS_DOUBLE: return 8;

    default:

        qemu_assert(0, "bad operand size");

        return 0;

    }

}


static int config_input_ref(AVFilterLink *inlink)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);

    AVFilterContext *ctx  = inlink->dst;

    PSNRContext *s = ctx->priv;

    unsigned sum;

    int j;

    s->nb_components = desc->nb_components;

    if (ctx->inputs[0]->w != ctx->inputs[1]->w ||

        ctx->inputs[0]->h != ctx->inputs[1]->h) {

        av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");

        return AVERROR(EINVAL);

    }

    if (ctx->inputs[0]->format != ctx->inputs[1]->format) {

        av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");

        return AVERROR(EINVAL);

    }

    s->max[0] = (1 << (desc->comp[0].depth_minus1 + 1)) - 1;

    s->max[1] = (1 << (desc->comp[1].depth_minus1 + 1)) - 1;

    s->max[2] = (1 << (desc->comp[2].depth_minus1 + 1)) - 1;

    s->max[3] = (1 << (desc->comp[3].depth_minus1 + 1)) - 1;

    s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;

    s->comps[0] = s->is_rgb ? 'r' : 'y' ;

    s->comps[1] = s->is_rgb ? 'g' : 'u' ;

    s->comps[2] = s->is_rgb ? 'b' : 'v' ;

    s->comps[3] = 'a';

    s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);

    s->planeheight[0] = s->planeheight[3] = inlink->h;

    s->planewidth[1]  = s->planewidth[2]  = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);

    s->planewidth[0]  = s->planewidth[3]  = inlink->w;

    sum = 0;

    for (j = 0; j < s->nb_components; j++)

        sum += s->planeheight[j] * s->planewidth[j];

    for (j = 0; j < s->nb_components; j++) {

        s->planeweight[j] = (double) s->planeheight[j] * s->planewidth[j] / sum;

        s->average_max += s->max[j] * s->planeweight[j];

    }

    s->compute_mse = desc->comp[0].depth_minus1 > 7 ? compute_images_mse_16bit : compute_images_mse;

    return 0;

}


int dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,

                      uint8_t* buf, int buf_size)

{

    int size, i;

    uint8_t *ppcm[4] = {0};

    if (buf_size < DV_PROFILE_BYTES ||

        !(c->sys = dv_frame_profile(buf)) ||

        buf_size < c->sys->frame_size) {

          return -1;   /* Broken frame, or not enough data */

    }

    /* Queueing audio packet */

    /* FIXME: in case of no audio/bad audio we have to do something */

    size = dv_extract_audio_info(c, buf);

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

       c->audio_pkt[i].size = size;

       c->audio_pkt[i].pts  = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;

       ppcm[i] = c->audio_buf[i];

    }

    dv_extract_audio(buf, ppcm, c->sys);

    c->abytes += size;

    /* We work with 720p frames split in half, thus even frames have

     * channels 0,1 and odd 2,3. */

    if (c->sys->height == 720) {

        if (buf[1] & 0x0C)

            c->audio_pkt[2].size = c->audio_pkt[3].size = 0;

        else

            c->audio_pkt[0].size = c->audio_pkt[1].size = 0;

    }

    /* Now it's time to return video packet */

    size = dv_extract_video_info(c, buf);

    av_init_packet(pkt);

    pkt->data         = buf;

    pkt->size         = size;

    pkt->flags       |= PKT_FLAG_KEY;

    pkt->stream_index = c->vst->id;

    pkt->pts          = c->frames;

    c->frames++;

    return size;

}


int ff_rtmp_packet_create(RTMPPacket *pkt, int channel_id, RTMPPacketType type,

                          int timestamp, int size)

{

    pkt->data = av_malloc(size);

    if (!pkt->data)

        return AVERROR(ENOMEM);

    pkt->data_size  = size;

    pkt->channel_id = channel_id;

    pkt->type       = type;

    pkt->timestamp  = timestamp;

    pkt->extra      = 0;

    pkt->ts_delta   = 0;

    return 0;


static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    AC3DecodeContext *s = avctx->priv_data;

    int16_t *out_samples = (int16_t *)data;

    int blk, ch, err;

    const uint8_t *channel_map;

    const float *output[AC3_MAX_CHANNELS];

    /* initialize the GetBitContext with the start of valid AC-3 Frame */

    if (s->input_buffer) {

        /* copy input buffer to decoder context to avoid reading past the end

           of the buffer, which can be caused by a damaged input stream. */

        memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));

        init_get_bits(&s->gbc, s->input_buffer, buf_size * 8);

    } else {

        init_get_bits(&s->gbc, buf, buf_size * 8);

    }

    /* parse the syncinfo */

    *data_size = 0;

    err = parse_frame_header(s);

    /* check that reported frame size fits in input buffer */

    if(s->frame_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");

        err = AAC_AC3_PARSE_ERROR_FRAME_SIZE;

    }

    /* check for crc mismatch */

    if(err != AAC_AC3_PARSE_ERROR_FRAME_SIZE && avctx->error_recognition >= FF_ER_CAREFUL) {

        if(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &buf[2], s->frame_size-2)) {

            av_log(avctx, AV_LOG_ERROR, "frame CRC mismatch\n");

            err = AAC_AC3_PARSE_ERROR_CRC;

        }

    }

    if(err && err != AAC_AC3_PARSE_ERROR_CRC) {

        switch(err) {

            case AAC_AC3_PARSE_ERROR_SYNC:

                av_log(avctx, AV_LOG_ERROR, "frame sync error\n");

                return -1;

            case AAC_AC3_PARSE_ERROR_BSID:

                av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n");

                break;

            case AAC_AC3_PARSE_ERROR_SAMPLE_RATE:

                av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");

                break;

            case AAC_AC3_PARSE_ERROR_FRAME_SIZE:

                av_log(avctx, AV_LOG_ERROR, "invalid frame size\n");

                break;

            case AAC_AC3_PARSE_ERROR_FRAME_TYPE:

                /* skip frame if CRC is ok. otherwise use error concealment. */

                /* TODO: add support for substreams and dependent frames */

                if(s->frame_type == EAC3_FRAME_TYPE_DEPENDENT || s->substreamid) {

                    av_log(avctx, AV_LOG_ERROR, "unsupported frame type : skipping frame\n");

                    return s->frame_size;

                } else {

                    av_log(avctx, AV_LOG_ERROR, "invalid frame type\n");

                }

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "invalid header\n");

                break;

        }

    }

    /* if frame is ok, set audio parameters */

    if (!err) {

        avctx->sample_rate = s->sample_rate;

        avctx->bit_rate = s->bit_rate;

        /* channel config */

        s->out_channels = s->channels;

        s->output_mode = s->channel_mode;

        if(s->lfe_on)

            s->output_mode |= AC3_OUTPUT_LFEON;

        if (avctx->request_channels > 0 && avctx->request_channels <= 2 &&

                avctx->request_channels < s->channels) {

            s->out_channels = avctx->request_channels;

            s->output_mode  = avctx->request_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;

            s->channel_layout = ff_ac3_channel_layout_tab[s->output_mode];

        }

        avctx->channels = s->out_channels;

        avctx->channel_layout = s->channel_layout;

        /* set downmixing coefficients if needed */

        if(s->channels != s->out_channels && !((s->output_mode & AC3_OUTPUT_LFEON) &&

                s->fbw_channels == s->out_channels)) {

            set_downmix_coeffs(s);

        }

    } else if (!s->out_channels) {

        s->out_channels = avctx->channels;

        if(s->out_channels < s->channels)

            s->output_mode  = s->out_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;

    }

    /* decode the audio blocks */

    channel_map = ff_ac3_dec_channel_map[s->output_mode & ~AC3_OUTPUT_LFEON][s->lfe_on];

    for (ch = 0; ch < s->out_channels; ch++)

        output[ch] = s->output[channel_map[ch]];

    for (blk = 0; blk < s->num_blocks; blk++) {

        if (!err && decode_audio_block(s, blk)) {

            av_log(avctx, AV_LOG_ERROR, "error decoding the audio block\n");

            err = 1;

        }

        s->dsp.float_to_int16_interleave(out_samples, output, 256, s->out_channels);

        out_samples += 256 * s->out_channels;

    }

    *data_size = s->num_blocks * 256 * avctx->channels * sizeof (int16_t);

    return s->frame_size;

}


static void pl011_write(void *opaque, hwaddr offset,

                        uint64_t value, unsigned size)

{

    PL011State *s = (PL011State *)opaque;

    unsigned char ch;

    switch (offset >> 2) {

    case 0: /* UARTDR */

        /* ??? Check if transmitter is enabled.  */

        ch = value;

        if (s->chr)

            qemu_chr_fe_write(s->chr, &ch, 1);

        s->int_level |= PL011_INT_TX;

        pl011_update(s);

        break;

    case 1: /* UARTCR */

        s->cr = value;

        break;

    case 6: /* UARTFR */

        /* Writes to Flag register are ignored.  */

        break;

    case 8: /* UARTUARTILPR */

        s->ilpr = value;

        break;

    case 9: /* UARTIBRD */

        s->ibrd = value;

        break;

    case 10: /* UARTFBRD */

        s->fbrd = value;

        break;

    case 11: /* UARTLCR_H */

        /* Reset the FIFO state on FIFO enable or disable */

        if ((s->lcr ^ value) & 0x10) {

            s->read_count = 0;

            s->read_pos = 0;

        }

        s->lcr = value;

        pl011_set_read_trigger(s);

        break;

    case 12: /* UARTCR */

        /* ??? Need to implement the enable and loopback bits.  */

        s->cr = value;

        break;

    case 13: /* UARTIFS */

        s->ifl = value;

        pl011_set_read_trigger(s);

        break;

    case 14: /* UARTIMSC */

        s->int_enabled = value;

        pl011_update(s);

        break;

    case 17: /* UARTICR */

        s->int_level &= ~value;

        pl011_update(s);

        break;

    case 18: /* UARTDMACR */

        s->dmacr = value;

        if (value & 3) {

            qemu_log_mask(LOG_UNIMP, "pl011: DMA not implemented\n");

        }

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "pl011_write: Bad offset %x\n", (int)offset);

    }

}


static uint64_t openpic_gbl_read(void *opaque, hwaddr addr, unsigned len)

{

    OpenPICState *opp = opaque;

    uint32_t retval;

    DPRINTF("%s: addr " TARGET_FMT_plx "\n", __func__, addr);

    retval = 0xFFFFFFFF;

    if (addr & 0xF)

        return retval;

    switch (addr) {

    case 0x1000: /* FREP */

        retval = opp->frep;

        break;

    case 0x1020: /* GLBC */

        retval = opp->glbc;

        break;

    case 0x1080: /* VENI */

        retval = opp->veni;

        break;

    case 0x1090: /* PINT */

        retval = 0x00000000;

        break;

    case 0x00: /* Block Revision Register1 (BRR1) */

        retval = opp->brr1;

        break;

    case 0x40:

    case 0x50:

    case 0x60:

    case 0x70:

    case 0x80:

    case 0x90:

    case 0xA0:

    case 0xB0:

        retval = openpic_cpu_read_internal(opp, addr, get_current_cpu());

        break;

    case 0x10A0: /* IPI_IPVP */

    case 0x10B0:

    case 0x10C0:

    case 0x10D0:

        {

            int idx;

            idx = (addr - 0x10A0) >> 4;

            retval = read_IRQreg_ipvp(opp, opp->irq_ipi0 + idx);

        }

        break;

    case 0x10E0: /* SPVE */

        retval = opp->spve;

        break;

    default:

        break;

    }

    DPRINTF("%s: => %08x\n", __func__, retval);

    return retval;

}


static void FUNCC(pred8x8l_vertical)(uint8_t *_src, int has_topleft, int has_topright, int _stride)

{

    int y;

    pixel *src = (pixel*)_src;

    int stride = _stride/sizeof(pixel);

    PREDICT_8x8_LOAD_TOP;

    src[0] = t0;

    src[1] = t1;

    src[2] = t2;

    src[3] = t3;

    src[4] = t4;

    src[5] = t5;

    src[6] = t6;

    src[7] = t7;

    for( y = 1; y < 8; y++ ) {

        ((pixel4*)(src+y*stride))[0] = ((pixel4*)src)[0];

        ((pixel4*)(src+y*stride))[1] = ((pixel4*)src)[1];

    }

}


static int check_intra_pred_mode(int mode, int mb_x, int mb_y)

{

    if (mode == DC_PRED8x8) {

        if (!(mb_x|mb_y))

            mode = DC_128_PRED8x8;

        else if (!mb_y)

            mode = LEFT_DC_PRED8x8;

        else if (!mb_x)

            mode = TOP_DC_PRED8x8;

    }

    return mode;

}


static void gen_swap_half(TCGv var)

{

    TCGv tmp = new_tmp();

    tcg_gen_shri_i32(tmp, var, 16);

    tcg_gen_shli_i32(var, var, 16);

    tcg_gen_or_i32(var, var, tmp);

    dead_tmp(tmp);

}


void g_free(void *mem)

{

    free(mem);

}


static int http_open_cnx(URLContext *h)

{

    const char *path, *proxy_path, *lower_proto = "tcp", *local_path;

    char hostname[1024], hoststr[1024], proto[10];

    char auth[1024], proxyauth[1024];

    char path1[1024];

    char buf[1024], urlbuf[1024];

    int port, use_proxy, err, location_changed = 0, redirects = 0;

    HTTPAuthType cur_auth_type, cur_proxy_auth_type;

    HTTPContext *s = h->priv_data;

    URLContext *hd = NULL;

    proxy_path = getenv("http_proxy");

    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&

        av_strstart(proxy_path, "http://", NULL);

    /* fill the dest addr */

 redo:

    /* needed in any case to build the host string */

    av_url_split(proto, sizeof(proto), auth, sizeof(auth),

                 hostname, sizeof(hostname), &port,

                 path1, sizeof(path1), s->location);

    ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);

    if (!strcmp(proto, "https")) {

        lower_proto = "tls";

        use_proxy = 0;

        if (port < 0)

            port = 443;

    }

    if (port < 0)

        port = 80;

    if (path1[0] == '\0')

        path = "/";

    else

        path = path1;

    local_path = path;

    if (use_proxy) {

        /* Reassemble the request URL without auth string - we don't

         * want to leak the auth to the proxy. */

        ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",

                    path1);

        path = urlbuf;

        av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),

                     hostname, sizeof(hostname), &port, NULL, 0, proxy_path);

    }

    ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);

    err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE,

                     &h->interrupt_callback, NULL);

    if (err < 0)

        goto fail;

    s->hd = hd;

    cur_auth_type = s->auth_state.auth_type;

    cur_proxy_auth_type = s->auth_state.auth_type;

    if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)

        goto fail;

    if (s->http_code == 401) {

        if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {

            ffurl_close(hd);

            goto redo;

        } else

            goto fail;

    }

    if (s->http_code == 407) {

        if (cur_proxy_auth_type == HTTP_AUTH_NONE &&

            s->proxy_auth_state.auth_type != HTTP_AUTH_NONE) {

            ffurl_close(hd);

            goto redo;

        } else

            goto fail;

    }

    if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)

        && location_changed == 1) {

        /* url moved, get next */

        ffurl_close(hd);

        if (redirects++ >= MAX_REDIRECTS)

            return AVERROR(EIO);

        location_changed = 0;

        goto redo;

    }

    return 0;

 fail:

    if (hd)

        ffurl_close(hd);

    s->hd = NULL;

    return AVERROR(EIO);

}


static void vmdaudio_loadsound(VmdAudioContext *s, unsigned char *data,

    uint8_t *buf, int silence)

{

    if (s->channels == 2) {

        if ((s->block_align & 0x01) == 0) {

            if (silence)

                memset(data, 0, s->block_align * 2);

            else

                vmdaudio_decode_audio(s, data, buf, 1);

        } else {

            if (silence)

                memset(data, 0, s->block_align * 2);

//            else

//                vmdaudio_decode_audio(s, data, buf, 1);

        }

    } else {

    }

}


uint64_t helper_mullv(CPUAlphaState *env, uint64_t op1, uint64_t op2)

{

    int64_t res = (int64_t)op1 * (int64_t)op2;

    if (unlikely((int32_t)res != res)) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return (int64_t)((int32_t)res);

}