static void scsi_cmd_xfer_mode(SCSICommand *cmd)

{

    if (!cmd->xfer) {

        cmd->mode = SCSI_XFER_NONE;

        return;

    }

    switch (cmd->buf[0]) {

    case WRITE_6:

    case WRITE_10:

    case WRITE_VERIFY_10:

    case WRITE_12:

    case WRITE_VERIFY_12:

    case WRITE_16:

    case WRITE_VERIFY_16:

    case COPY:

    case COPY_VERIFY:

    case COMPARE:

    case CHANGE_DEFINITION:

    case LOG_SELECT:

    case MODE_SELECT:

    case MODE_SELECT_10:

    case SEND_DIAGNOSTIC:

    case WRITE_BUFFER:

    case FORMAT_UNIT:

    case REASSIGN_BLOCKS:

    case SEARCH_EQUAL:

    case SEARCH_HIGH:

    case SEARCH_LOW:

    case UPDATE_BLOCK:

    case WRITE_LONG_10:

    case WRITE_SAME_10:

    case WRITE_SAME_16:

    case UNMAP:

    case SEARCH_HIGH_12:

    case SEARCH_EQUAL_12:

    case SEARCH_LOW_12:

    case MEDIUM_SCAN:

    case SEND_VOLUME_TAG:

    case SEND_CUE_SHEET:

    case SEND_DVD_STRUCTURE:

    case PERSISTENT_RESERVE_OUT:

    case MAINTENANCE_OUT:

        cmd->mode = SCSI_XFER_TO_DEV;

        break;

    default:

        cmd->mode = SCSI_XFER_FROM_DEV;

        break;

    }

}


static void test_visitor_in_union_flat(TestInputVisitorData *data,

                                       const void *unused)

{

    Visitor *v;

    UserDefFlatUnion *tmp;

    UserDefUnionBase *base;

    v = visitor_input_test_init(data,

                                "{ 'enum1': 'value1', "

                                "'integer': 41, "

                                "'string': 'str', "

                                "'boolean': true }");

    visit_type_UserDefFlatUnion(v, NULL, &tmp, &error_abort);

    g_assert_cmpint(tmp->enum1, ==, ENUM_ONE_VALUE1);

    g_assert_cmpstr(tmp->string, ==, "str");

    g_assert_cmpint(tmp->integer, ==, 41);

    g_assert_cmpint(tmp->u.value1->boolean, ==, true);

    base = qapi_UserDefFlatUnion_base(tmp);

    g_assert(&base->enum1 == &tmp->enum1);

    qapi_free_UserDefFlatUnion(tmp);

}


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

{

    AVIOContext *pb = s->pb;

    APEContext *ape = s->priv_data;

    AVStream *st;

    uint32_t tag;

    int i;

    int total_blocks;

    int64_t pts;

    /* TODO: Skip any leading junk such as id3v2 tags */

    ape->junklength = 0;

    tag = avio_rl32(pb);

    if (tag != MKTAG('M', 'A', 'C', ' '))

        return -1;

    ape->fileversion = avio_rl16(pb);

    if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {

        av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10);

        return -1;

    if (ape->fileversion >= 3980) {

        ape->padding1             = avio_rl16(pb);

        ape->descriptorlength     = avio_rl32(pb);

        ape->headerlength         = avio_rl32(pb);

        ape->seektablelength      = avio_rl32(pb);

        ape->wavheaderlength      = avio_rl32(pb);

        ape->audiodatalength      = avio_rl32(pb);

        ape->audiodatalength_high = avio_rl32(pb);

        ape->wavtaillength        = avio_rl32(pb);

        avio_read(pb, ape->md5, 16);

        /* Skip any unknown bytes at the end of the descriptor.

           This is for future compatibility */

        if (ape->descriptorlength > 52)

            avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR);

        /* Read header data */

        ape->compressiontype      = avio_rl16(pb);

        ape->formatflags          = avio_rl16(pb);

        ape->blocksperframe       = avio_rl32(pb);

        ape->finalframeblocks     = avio_rl32(pb);

        ape->totalframes          = avio_rl32(pb);

        ape->bps                  = avio_rl16(pb);

        ape->channels             = avio_rl16(pb);

        ape->samplerate           = avio_rl32(pb);

    } else {

        ape->descriptorlength = 0;

        ape->headerlength = 32;

        ape->compressiontype      = avio_rl16(pb);

        ape->formatflags          = avio_rl16(pb);

        ape->channels             = avio_rl16(pb);

        ape->samplerate           = avio_rl32(pb);

        ape->wavheaderlength      = avio_rl32(pb);

        ape->wavtaillength        = avio_rl32(pb);

        ape->totalframes          = avio_rl32(pb);

        ape->finalframeblocks     = avio_rl32(pb);

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {

            avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */

            ape->headerlength += 4;

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {

            ape->seektablelength = avio_rl32(pb);

            ape->headerlength += 4;

            ape->seektablelength *= sizeof(int32_t);

        } else

            ape->seektablelength = ape->totalframes * sizeof(int32_t);

        if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)

            ape->bps = 8;

        else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)

            ape->bps = 24;

        else

            ape->bps = 16;

        if (ape->fileversion >= 3950)

            ape->blocksperframe = 73728 * 4;

        else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800  && ape->compressiontype >= 4000))

            ape->blocksperframe = 73728;

        else

            ape->blocksperframe = 9216;

        /* Skip any stored wav header */

        if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))

            avio_seek(pb, ape->wavheaderlength, SEEK_CUR);

    if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){

        av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes);

        return -1;

    ape->frames       = av_malloc(ape->totalframes * sizeof(APEFrame));

    if(!ape->frames)

        return AVERROR(ENOMEM);

    ape->firstframe   = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;

    ape->currentframe = 0;

    ape->totalsamples = ape->finalframeblocks;

    if (ape->totalframes > 1)

        ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);

    if (ape->seektablelength > 0) {

        ape->seektable = av_malloc(ape->seektablelength);

        for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)

            ape->seektable[i] = avio_rl32(pb);

    ape->frames[0].pos     = ape->firstframe;

    ape->frames[0].nblocks = ape->blocksperframe;

    ape->frames[0].skip    = 0;

    for (i = 1; i < ape->totalframes; i++) {

        ape->frames[i].pos      = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe;

        ape->frames[i].nblocks  = ape->blocksperframe;

        ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;

        ape->frames[i].skip     = (ape->frames[i].pos - ape->frames[0].pos) & 3;

    ape->frames[ape->totalframes - 1].size    = ape->finalframeblocks * 4;

    ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;

    for (i = 0; i < ape->totalframes; i++) {

        if(ape->frames[i].skip){

            ape->frames[i].pos  -= ape->frames[i].skip;

            ape->frames[i].size += ape->frames[i].skip;

        ape->frames[i].size = (ape->frames[i].size + 3) & ~3;

    ape_dumpinfo(s, ape);

    /* try to read APE tags */

    if (!url_is_streamed(pb)) {

        ff_ape_parse_tag(s);

        avio_seek(pb, 0, SEEK_SET);

    av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype);

    /* now we are ready: build format streams */

    st = av_new_stream(s, 0);

    if (!st)

        return -1;

    total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;

    st->codec->codec_type      = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id        = CODEC_ID_APE;

    st->codec->codec_tag       = MKTAG('A', 'P', 'E', ' ');

    st->codec->channels        = ape->channels;

    st->codec->sample_rate     = ape->samplerate;

    st->codec->bits_per_coded_sample = ape->bps;

    st->codec->frame_size      = MAC_SUBFRAME_SIZE;

    st->nb_frames = ape->totalframes;

    st->start_time = 0;

    st->duration  = total_blocks / MAC_SUBFRAME_SIZE;

    av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);

    st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);

    st->codec->extradata_size = APE_EXTRADATA_SIZE;

    AV_WL16(st->codec->extradata + 0, ape->fileversion);

    AV_WL16(st->codec->extradata + 2, ape->compressiontype);

    AV_WL16(st->codec->extradata + 4, ape->formatflags);

    pts = 0;

    for (i = 0; i < ape->totalframes; i++) {

        ape->frames[i].pts = pts;

        av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);

        pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;

    return 0;


static int buf_close(void *opaque)

{

    QEMUBuffer *s = opaque;

    qsb_free(s->qsb);

    g_free(s);

    return 0;

}


static const struct URLProtocol *url_find_protocol(const char *filename)

{

    const URLProtocol **protocols;

    char proto_str[128], proto_nested[128], *ptr;

    size_t proto_len = strspn(filename, URL_SCHEME_CHARS);

    int i;

    if (filename[proto_len] != ':' &&

        (strncmp(filename, "subfile,", 8) || !strchr(filename + proto_len + 1, ':')) ||

        is_dos_path(filename))

        strcpy(proto_str, "file");

    else

        av_strlcpy(proto_str, filename,

                   FFMIN(proto_len + 1, sizeof(proto_str)));

    if ((ptr = strchr(proto_str, ',')))

        *ptr = '\0';

    av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));

    if ((ptr = strchr(proto_nested, '+')))

        *ptr = '\0';

    protocols = ffurl_get_protocols(NULL, NULL);

    for (i = 0; protocols[i]; i++) {

            const URLProtocol *up = protocols[i];

        if (!strcmp(proto_str, up->name)) {

            av_freep(&protocols);

            return up;

        }

        if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&

            !strcmp(proto_nested, up->name)) {

            av_freep(&protocols);

            return up;

        }

    }

    av_freep(&protocols);

}


void qmp_nbd_server_stop(Error **errp)

{

    while (!QTAILQ_EMPTY(&close_notifiers)) {

        NBDCloseNotifier *cn = QTAILQ_FIRST(&close_notifiers);

        nbd_close_notifier(&cn->n, nbd_export_get_blockdev(cn->exp));

    }

    qemu_set_fd_handler2(server_fd, NULL, NULL, NULL, NULL);

    close(server_fd);

    server_fd = -1;

}


int arm_reset_cpu(uint64_t cpuid)

{

    CPUState *target_cpu_state;

    ARMCPU *target_cpu;

    DPRINTF("cpu %" PRId64 "\n", cpuid);

    /* change to the cpu we are resetting */

    target_cpu_state = arm_get_cpu_by_id(cpuid);

    if (!target_cpu_state) {

        return QEMU_ARM_POWERCTL_INVALID_PARAM;

    }

    target_cpu = ARM_CPU(target_cpu_state);

    if (target_cpu->powered_off) {

        qemu_log_mask(LOG_GUEST_ERROR,

                      "[ARM]%s: CPU %" PRId64 " is off\n",

                      __func__, cpuid);

        return QEMU_ARM_POWERCTL_IS_OFF;

    }

    /* Reset the cpu */

    cpu_reset(target_cpu_state);

    return QEMU_ARM_POWERCTL_RET_SUCCESS;

}


static void postprocess_chroma(AVFrame *frame, int w, int h, int depth)

{

    uint16_t *dstu = (uint16_t *)frame->data[1];

    uint16_t *dstv = (uint16_t *)frame->data[2];

    int16_t *srcu  = (int16_t *)frame->data[1];

    int16_t *srcv  = (int16_t *)frame->data[2];

    ptrdiff_t strideu = frame->linesize[1] / 2;

    ptrdiff_t stridev = frame->linesize[2] / 2;

    const int add = 1 << (depth - 1);

    const int shift = 16 - depth;

    int i, j;

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

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

            dstu[i] = (add + srcu[i]) << shift;

            dstv[i] = (add + srcv[i]) << shift;

        }

        dstu += strideu;

        dstv += stridev;

        srcu += strideu;

        srcv += stridev;

    }

}


static void id3v2_parse(AVFormatContext *s, int len, uint8_t version,

                        uint8_t flags, ID3v2ExtraMeta **extra_meta)

{

    int isv34, tlen, unsync;

    char tag[5];

    int64_t next, end = avio_tell(s->pb) + len;

    int taghdrlen;

    const char *reason = NULL;

    AVIOContext pb;

    AVIOContext *pbx;

    unsigned char *buffer = NULL;

    int buffer_size       = 0;

    const ID3v2EMFunc *extra_func;

    switch (version) {

    case 2:

        if (flags & 0x40) {

            reason = "compression";

            goto error;

        }

        isv34     = 0;

        taghdrlen = 6;

        break;

    case 3:

    case 4:

        isv34     = 1;

        taghdrlen = 10;

        break;

    default:

        reason = "version";

        goto error;

    }

    unsync = flags & 0x80;

    if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */

        int extlen = get_size(s->pb, 4);

        if (version == 4)

            /* In v2.4 the length includes the length field we just read. */

            extlen -= 4;

        if (extlen < 0) {

            reason = "invalid extended header length";

            goto error;

        }

        avio_skip(s->pb, extlen);

    }

    while (len >= taghdrlen) {

        unsigned int tflags = 0;

        int tunsync         = 0;

        if (isv34) {

            avio_read(s->pb, tag, 4);

            tag[4] = 0;

            if (version == 3) {

                tlen = avio_rb32(s->pb);

            } else

                tlen = get_size(s->pb, 4);

            tflags  = avio_rb16(s->pb);

            tunsync = tflags & ID3v2_FLAG_UNSYNCH;

        } else {

            avio_read(s->pb, tag, 3);

            tag[3] = 0;

            tlen   = avio_rb24(s->pb);

        }

        if (tlen < 0 || tlen > len - taghdrlen) {

            av_log(s, AV_LOG_WARNING,

                   "Invalid size in frame %s, skipping the rest of tag.\n",

                   tag);

            break;

        }

        len -= taghdrlen + tlen;

        next = avio_tell(s->pb) + tlen;

        if (!tlen) {

            if (tag[0])

                av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",

                       tag);

            continue;

        }

        if (tflags & ID3v2_FLAG_DATALEN) {

            avio_rb32(s->pb);

            tlen -= 4;

        }

        if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {

            av_log(s, AV_LOG_WARNING,

                   "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);

            avio_skip(s->pb, tlen);

        /* check for text tag or supported special meta tag */

        } else if (tag[0] == 'T' ||

                   (extra_meta &&

                    (extra_func = get_extra_meta_func(tag, isv34)))) {

            if (unsync || tunsync) {

                int64_t end = avio_tell(s->pb) + tlen;

                uint8_t *b;

                av_fast_malloc(&buffer, &buffer_size, tlen);

                if (!buffer) {

                    av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);

                    goto seek;

                }

                b = buffer;

                while (avio_tell(s->pb) < end) {

                    *b++ = avio_r8(s->pb);

                    if (*(b - 1) == 0xff && avio_tell(s->pb) < end - 1) {

                        uint8_t val = avio_r8(s->pb);

                        *b++ = val ? val : avio_r8(s->pb);

                    }

                }

                ffio_init_context(&pb, buffer, b - buffer, 0, NULL, NULL, NULL,

                                  NULL);

                tlen = b - buffer;

                pbx  = &pb; // read from sync buffer

            } else {

                pbx = s->pb; // read straight from input

            }

            if (tag[0] == 'T')

                /* parse text tag */

                read_ttag(s, pbx, tlen, tag);

            else

                /* parse special meta tag */

                extra_func->read(s, pbx, tlen, tag, extra_meta);

        } else if (!tag[0]) {

            if (tag[1])

                av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");

            avio_skip(s->pb, tlen);

            break;

        }

        /* Skip to end of tag */

seek:

        avio_seek(s->pb, next, SEEK_SET);

    }

    /* Footer preset, always 10 bytes, skip over it */

    if (version == 4 && flags & 0x10)

        end += 10;

error:

    if (reason)

        av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",

               version, reason);

    avio_seek(s->pb, end, SEEK_SET);

    av_free(buffer);

    return;

}


static int ehci_state_fetchqtd(EHCIQueue *q)

{

    EHCIqtd qtd;

    EHCIPacket *p;

    int again = 0;

    get_dwords(q->ehci, NLPTR_GET(q->qtdaddr), (uint32_t *) &qtd,

               sizeof(EHCIqtd) >> 2);

    ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &qtd);

    p = QTAILQ_FIRST(&q->packets);

    if (p != NULL) {

        if (p->qtdaddr != q->qtdaddr ||

            (!NLPTR_TBIT(p->qtd.next) && (p->qtd.next != qtd.next)) ||

            (!NLPTR_TBIT(p->qtd.altnext) && (p->qtd.altnext != qtd.altnext)) ||

            p->qtd.bufptr[0] != qtd.bufptr[0]) {

            ehci_cancel_queue(q);

            ehci_trace_guest_bug(q->ehci, "guest updated active QH or qTD");

            p = NULL;

        } else {

            p->qtd = qtd;

            ehci_qh_do_overlay(q);

        }

    }

    if (!(qtd.token & QTD_TOKEN_ACTIVE)) {

        if (p != NULL) {

            /* transfer canceled by guest (clear active) */

            ehci_cancel_queue(q);

            p = NULL;

        }

        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

        again = 1;

    } else if (p != NULL) {

        switch (p->async) {

        case EHCI_ASYNC_NONE:

            /* Previously nacked packet (likely interrupt ep) */

           ehci_set_state(q->ehci, q->async, EST_EXECUTE);

           break;

        case EHCI_ASYNC_INFLIGHT:

            /* Unfinyshed async handled packet, go horizontal */

            ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

            break;

        case EHCI_ASYNC_FINISHED:

            /* Should never happen, as this case is caught by fetchqh */

            ehci_set_state(q->ehci, q->async, EST_EXECUTING);

            break;

        }

        again = 1;

    } else {

        p = ehci_alloc_packet(q);

        p->qtdaddr = q->qtdaddr;

        p->qtd = qtd;

        ehci_set_state(q->ehci, q->async, EST_EXECUTE);

        again = 1;

    }

    return again;

}


static av_always_inline int encode_line(FFV1Context *s, int w,

                                        int16_t *sample[3],

                                        int plane_index, int bits)

{

    PlaneContext *const p = &s->plane[plane_index];

    RangeCoder *const c   = &s->c;

    int x;

    int run_index = s->run_index;

    int run_count = 0;

    int run_mode  = 0;

    if (s->ac) {

        if (c->bytestream_end - c->bytestream < w * 20) {

            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");

            return AVERROR_INVALIDDATA;

        }

    } else {

        if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) < w * 4) {

            av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");

            return AVERROR_INVALIDDATA;

        }

    }

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

        int diff, context;

        context = get_context(p, sample[0] + x, sample[1] + x, sample[2] + x);

        diff    = sample[0][x] - predict(sample[0] + x, sample[1] + x);

        if (context < 0) {

            context = -context;

            diff    = -diff;

        }

        diff = fold(diff, bits);

        if (s->ac) {

            if (s->flags & CODEC_FLAG_PASS1) {

                put_symbol_inline(c, p->state[context], diff, 1, s->rc_stat,

                                  s->rc_stat2[p->quant_table_index][context]);

            } else {

                put_symbol_inline(c, p->state[context], diff, 1, NULL, NULL);

            }

        } else {

            if (context == 0)

                run_mode = 1;

            if (run_mode) {

                if (diff) {

                    while (run_count >= 1 << ff_log2_run[run_index]) {

                        run_count -= 1 << ff_log2_run[run_index];

                        run_index++;

                        put_bits(&s->pb, 1, 1);

                    }

                    put_bits(&s->pb, 1 + ff_log2_run[run_index], run_count);

                    if (run_index)

                        run_index--;

                    run_count = 0;

                    run_mode  = 0;

                    if (diff > 0)

                        diff--;

                } else {

                    run_count++;

                }

            }

            av_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",

                    run_count, run_index, run_mode, x,

                    (int)put_bits_count(&s->pb));

            if (run_mode == 0)

                put_vlc_symbol(&s->pb, &p->vlc_state[context], diff, bits);

        }

    }

    if (run_mode) {

        while (run_count >= 1 << ff_log2_run[run_index]) {

            run_count -= 1 << ff_log2_run[run_index];

            run_index++;

            put_bits(&s->pb, 1, 1);

        }

        if (run_count)

            put_bits(&s->pb, 1, 1);

    }

    s->run_index = run_index;

    return 0;

}


static int mpeg4_decode_header(AVCodecParserContext *s1, AVCodecContext *avctx,

                               const uint8_t *buf, int buf_size)

{

    struct Mp4vParseContext *pc = s1->priv_data;

    Mpeg4DecContext *dec_ctx = &pc->dec_ctx;

    MpegEncContext *s = &dec_ctx->m;

    GetBitContext gb1, *gb = &gb1;

    int ret;

    s->avctx               = avctx;

    s->current_picture_ptr = &s->current_picture;

    if (avctx->extradata_size && pc->first_picture) {

        init_get_bits(gb, avctx->extradata, avctx->extradata_size * 8);

        ret = ff_mpeg4_decode_picture_header(dec_ctx, gb);

    }

    init_get_bits(gb, buf, 8 * buf_size);

    ret = ff_mpeg4_decode_picture_header(dec_ctx, gb);

    if (s->width && (!avctx->width || !avctx->height ||

                     !avctx->coded_width || !avctx->coded_height)) {

        ret = ff_set_dimensions(avctx, s->width, s->height);

            return ret;

    }

    if((s1->flags & PARSER_FLAG_USE_CODEC_TS) && s->avctx->time_base.den>0 && ret>=0){

        av_assert1(s1->pts == AV_NOPTS_VALUE);

        av_assert1(s1->dts == AV_NOPTS_VALUE);

        s1->pts = av_rescale_q(s->time, (AVRational){1, s->avctx->time_base.den}, (AVRational){1, 1200000});

    }

    s1->pict_type     = s->pict_type;

    pc->first_picture = 0;

    return ret;

}


void vnc_tls_client_cleanup(VncState *vs)

{

    if (vs->tls.session) {

        gnutls_deinit(vs->tls.session);

        vs->tls.session = NULL;

    }

    g_free(vs->tls.dname);

}


void colo_do_failover(MigrationState *s)

{

    /* Make sure VM stopped while failover happened. */

    if (!colo_runstate_is_stopped()) {

        vm_stop_force_state(RUN_STATE_COLO);

    }

    if (get_colo_mode() == COLO_MODE_PRIMARY) {

        primary_vm_do_failover();

    }

}


static void test_validate_union_flat(TestInputVisitorData *data,

                                     const void *unused)

{

    UserDefFlatUnion *tmp = NULL;

    Visitor *v;

    Error *err = NULL;

    v = validate_test_init(data,

                           "{ 'enum1': 'value1', "

                           "'string': 'str', "

                           "'boolean': true }");

    /* TODO when generator bug is fixed, add 'integer': 41 */

    visit_type_UserDefFlatUnion(v, &tmp, NULL, &err);

    g_assert(!err);

    qapi_free_UserDefFlatUnion(tmp);

}


static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

	long width, long height,

	long lumStride, long chromStride, long dstStride, long vertLumPerChroma)

{

	long y;

	const long chromWidth= width>>1;

	for(y=0; y<height; y++)

	{

#ifdef HAVE_MMX

//FIXME handle 2 lines a once (fewer prefetch, reuse some chrom, but very likely limited by mem anyway)

		asm volatile(

			"xor %%"REG_a", %%"REG_a"	\n\t"

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 32(%1, %%"REG_a", 2)	\n\t"

			PREFETCH" 32(%2, %%"REG_a")	\n\t"

			PREFETCH" 32(%3, %%"REG_a")	\n\t"

			"movq (%2, %%"REG_a"), %%mm0	\n\t" // U(0)

			"movq %%mm0, %%mm2		\n\t" // U(0)

			"movq (%3, %%"REG_a"), %%mm1	\n\t" // V(0)

			"punpcklbw %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"punpckhbw %%mm1, %%mm2		\n\t" // UVUV UVUV(8)

			"movq (%1, %%"REG_a",2), %%mm3	\n\t" // Y(0)

			"movq 8(%1, %%"REG_a",2), %%mm5	\n\t" // Y(8)

			"movq %%mm0, %%mm4		\n\t" // Y(0)

			"movq %%mm2, %%mm6		\n\t" // Y(8)

			"punpcklbw %%mm3, %%mm0		\n\t" // YUYV YUYV(0)

			"punpckhbw %%mm3, %%mm4		\n\t" // YUYV YUYV(4)

			"punpcklbw %%mm5, %%mm2		\n\t" // YUYV YUYV(8)

			"punpckhbw %%mm5, %%mm6		\n\t" // YUYV YUYV(12)

			MOVNTQ" %%mm0, (%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm4, 8(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm2, 16(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm6, 24(%0, %%"REG_a", 4)\n\t"

			"add $8, %%"REG_a"		\n\t"

			"cmp %4, %%"REG_a"		\n\t"

			" jb 1b				\n\t"

			::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)

			: "%"REG_a

		);

#else

//FIXME adapt the alpha asm code from yv12->yuy2

#if __WORDSIZE >= 64

		int i;

		uint64_t *ldst = (uint64_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

			uint64_t k, l;

			k = uc[0] + (yc[0] << 8) +

			    (vc[0] << 16) + (yc[1] << 24);

			l = uc[1] + (yc[2] << 8) +

			    (vc[1] << 16) + (yc[3] << 24);

			*ldst++ = k + (l << 32);

			yc += 4;

			uc += 2;

			vc += 2;

		}

#else

		int i, *idst = (int32_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#ifdef WORDS_BIGENDIAN

			*idst++ = (uc[0] << 24)+ (yc[0] << 16) +

			    (vc[0] << 8) + (yc[1] << 0);

#else

			*idst++ = uc[0] + (yc[0] << 8) +

			    (vc[0] << 16) + (yc[1] << 24);

#endif

			yc += 2;

			uc++;

			vc++;

		}

#endif

#endif

		if((y&(vertLumPerChroma-1))==(vertLumPerChroma-1) )

		{

			usrc += chromStride;

			vsrc += chromStride;

		}

		ysrc += lumStride;

		dst += dstStride;

	}

#ifdef HAVE_MMX

asm(    EMMS" \n\t"

        SFENCE" \n\t"

        :::"memory");

#endif

}


int target_munmap(target_ulong start, target_ulong len)

{

    target_ulong end, real_start, real_end, addr;

    int prot, ret;

#ifdef DEBUG_MMAP

    printf("munmap: start=0x%lx len=0x%lx\n", start, len);

#endif

    if (start & ~TARGET_PAGE_MASK)

        return -EINVAL;

    len = TARGET_PAGE_ALIGN(len);

    if (len == 0)

        return -EINVAL;

    end = start + len;

    real_start = start & qemu_host_page_mask;

    real_end = HOST_PAGE_ALIGN(end);

    if (start > real_start) {

        /* handle host page containing start */

        prot = 0;

        for(addr = real_start; addr < start; addr += TARGET_PAGE_SIZE) {

            prot |= page_get_flags(addr);

        }

        if (real_end == real_start + qemu_host_page_size) {

            for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {

                prot |= page_get_flags(addr);

            }

            end = real_end;

        }

        if (prot != 0)

            real_start += qemu_host_page_size;

    }

    if (end < real_end) {

        prot = 0;

        for(addr = end; addr < real_end; addr += TARGET_PAGE_SIZE) {

            prot |= page_get_flags(addr);

        }

        if (prot != 0)

            real_end -= qemu_host_page_size;

    }

    /* unmap what we can */

    if (real_start < real_end) {

        ret = munmap((void *)real_start, real_end - real_start);

        if (ret != 0)

            return ret;

    }

    page_set_flags(start, start + len, 0);

    return 0;

}


int cpu_exec(CPUState *env)

{

    int ret, interrupt_request;

    TranslationBlock *tb;

    uint8_t *tc_ptr;

    unsigned long next_tb;

    if (env->halted) {

        if (!cpu_has_work(env)) {

            return EXCP_HALTED;

        }

        env->halted = 0;

    }

    cpu_single_env = env;

    if (unlikely(exit_request)) {

        env->exit_request = 1;

    }

#if defined(TARGET_I386)

    /* put eflags in CPU temporary format */

    CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    DF = 1 - (2 * ((env->eflags >> 10) & 1));

    CC_OP = CC_OP_EFLAGS;

    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_SPARC)

#elif defined(TARGET_M68K)

    env->cc_op = CC_OP_FLAGS;

    env->cc_dest = env->sr & 0xf;

    env->cc_x = (env->sr >> 4) & 1;

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_ARM)

#elif defined(TARGET_UNICORE32)

#elif defined(TARGET_PPC)

#elif defined(TARGET_LM32)

#elif defined(TARGET_MICROBLAZE)

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_CRIS)

#elif defined(TARGET_S390X)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    env->exception_index = -1;

    /* prepare setjmp context for exception handling */

    for(;;) {

        if (setjmp(env->jmp_env) == 0) {

            /* if an exception is pending, we execute it here */

            if (env->exception_index >= 0) {

                if (env->exception_index >= EXCP_INTERRUPT) {

                    /* exit request from the cpu execution loop */

                    ret = env->exception_index;

                    if (ret == EXCP_DEBUG) {

                        cpu_handle_debug_exception(env);

                    }

                    break;

#if defined(CONFIG_USER_ONLY)

                    /* if user mode only, we simulate a fake exception

                       which will be handled outside the cpu execution

                       loop */

#if defined(TARGET_I386)

                    do_interrupt(env);

#endif

                    ret = env->exception_index;

                    break;

#else

                    do_interrupt(env);

                    env->exception_index = -1;

#endif

                }

            }

            next_tb = 0; /* force lookup of first TB */

            for(;;) {

                interrupt_request = env->interrupt_request;

                if (unlikely(interrupt_request)) {

                    if (unlikely(env->singlestep_enabled & SSTEP_NOIRQ)) {

                        /* Mask out external interrupts for this step. */

                        interrupt_request &= ~CPU_INTERRUPT_SSTEP_MASK;

                    }

                    if (interrupt_request & CPU_INTERRUPT_DEBUG) {

                        env->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

                        env->exception_index = EXCP_DEBUG;

                        cpu_loop_exit(env);

                    }

#if defined(TARGET_ARM) || defined(TARGET_SPARC) || defined(TARGET_MIPS) || \

    defined(TARGET_PPC) || defined(TARGET_ALPHA) || defined(TARGET_CRIS) || \

    defined(TARGET_MICROBLAZE) || defined(TARGET_LM32) || defined(TARGET_UNICORE32)

                    if (interrupt_request & CPU_INTERRUPT_HALT) {

                        env->interrupt_request &= ~CPU_INTERRUPT_HALT;

                        env->halted = 1;

                        env->exception_index = EXCP_HLT;

                        cpu_loop_exit(env);

                    }

#endif

#if defined(TARGET_I386)

                    if (interrupt_request & CPU_INTERRUPT_INIT) {

                            svm_check_intercept(env, SVM_EXIT_INIT);

                            do_cpu_init(env);

                            env->exception_index = EXCP_HALTED;

                            cpu_loop_exit(env);

                    } else if (interrupt_request & CPU_INTERRUPT_SIPI) {

                            do_cpu_sipi(env);

                    } else if (env->hflags2 & HF2_GIF_MASK) {

                        if ((interrupt_request & CPU_INTERRUPT_SMI) &&

                            !(env->hflags & HF_SMM_MASK)) {

                            svm_check_intercept(env, SVM_EXIT_SMI);

                            env->interrupt_request &= ~CPU_INTERRUPT_SMI;

                            do_smm_enter(env);

                            next_tb = 0;

                        } else if ((interrupt_request & CPU_INTERRUPT_NMI) &&

                                   !(env->hflags2 & HF2_NMI_MASK)) {

                            env->interrupt_request &= ~CPU_INTERRUPT_NMI;

                            env->hflags2 |= HF2_NMI_MASK;

                            do_interrupt_x86_hardirq(env, EXCP02_NMI, 1);

                            next_tb = 0;

			} else if (interrupt_request & CPU_INTERRUPT_MCE) {

                            env->interrupt_request &= ~CPU_INTERRUPT_MCE;

                            do_interrupt_x86_hardirq(env, EXCP12_MCHK, 0);

                            next_tb = 0;

                        } else if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                                   (((env->hflags2 & HF2_VINTR_MASK) &&

                                     (env->hflags2 & HF2_HIF_MASK)) ||

                                    (!(env->hflags2 & HF2_VINTR_MASK) &&

                                     (env->eflags & IF_MASK &&

                                      !(env->hflags & HF_INHIBIT_IRQ_MASK))))) {

                            int intno;

                            svm_check_intercept(env, SVM_EXIT_INTR);

                            env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);

                            intno = cpu_get_pic_interrupt(env);

                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing hardware INT=0x%02x\n", intno);

                            do_interrupt_x86_hardirq(env, intno, 1);

                            /* ensure that no TB jump will be modified as

                               the program flow was changed */

                            next_tb = 0;

#if !defined(CONFIG_USER_ONLY)

                        } else if ((interrupt_request & CPU_INTERRUPT_VIRQ) &&

                                   (env->eflags & IF_MASK) &&

                                   !(env->hflags & HF_INHIBIT_IRQ_MASK)) {

                            int intno;

                            /* FIXME: this should respect TPR */

                            svm_check_intercept(env, SVM_EXIT_VINTR);

                            intno = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_vector));

                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing virtual hardware INT=0x%02x\n", intno);

                            do_interrupt_x86_hardirq(env, intno, 1);

                            env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;

                            next_tb = 0;

#endif

                        }

                    }

#elif defined(TARGET_PPC)

#if 0

                    if ((interrupt_request & CPU_INTERRUPT_RESET)) {

                        cpu_reset(env);

                    }

#endif

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        ppc_hw_interrupt(env);

                        if (env->pending_interrupts == 0)

                            env->interrupt_request &= ~CPU_INTERRUPT_HARD;

                        next_tb = 0;

                    }

#elif defined(TARGET_LM32)

                    if ((interrupt_request & CPU_INTERRUPT_HARD)

                        && (env->ie & IE_IE)) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_MICROBLAZE)

                    if ((interrupt_request & CPU_INTERRUPT_HARD)

                        && (env->sregs[SR_MSR] & MSR_IE)

                        && !(env->sregs[SR_MSR] & (MSR_EIP | MSR_BIP))

                        && !(env->iflags & (D_FLAG | IMM_FLAG))) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_MIPS)

                    if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                        cpu_mips_hw_interrupts_pending(env)) {

                        /* Raise it */

                        env->exception_index = EXCP_EXT_INTERRUPT;

                        env->error_code = 0;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_SPARC)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        if (cpu_interrupts_enabled(env) &&

                            env->interrupt_index > 0) {

                            int pil = env->interrupt_index & 0xf;

                            int type = env->interrupt_index & 0xf0;

                            if (((type == TT_EXTINT) &&

                                  cpu_pil_allowed(env, pil)) ||

                                  type != TT_EXTINT) {

                                env->exception_index = env->interrupt_index;

                                do_interrupt(env);

                                next_tb = 0;

                            }

                        }

		    }

#elif defined(TARGET_ARM)

                    if (interrupt_request & CPU_INTERRUPT_FIQ

                        && !(env->uncached_cpsr & CPSR_F)) {

                        env->exception_index = EXCP_FIQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

                    /* ARMv7-M interrupt return works by loading a magic value

                       into the PC.  On real hardware the load causes the

                       return to occur.  The qemu implementation performs the

                       jump normally, then does the exception return when the

                       CPU tries to execute code at the magic address.

                       This will cause the magic PC value to be pushed to

                       the stack if an interrupt occurred at the wrong time.

                       We avoid this by disabling interrupts when

                       pc contains a magic address.  */

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((IS_M(env) && env->regs[15] < 0xfffffff0)

                            || !(env->uncached_cpsr & CPSR_I))) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_UNICORE32)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && !(env->uncached_asr & ASR_I)) {

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_SH4)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_ALPHA)

                    {

                        int idx = -1;

                        /* ??? This hard-codes the OSF/1 interrupt levels.  */

		        switch (env->pal_mode ? 7 : env->ps & PS_INT_MASK) {

                        case 0 ... 3:

                            if (interrupt_request & CPU_INTERRUPT_HARD) {

                                idx = EXCP_DEV_INTERRUPT;

                            }

                            /* FALLTHRU */

                        case 4:

                            if (interrupt_request & CPU_INTERRUPT_TIMER) {

                                idx = EXCP_CLK_INTERRUPT;

                            }

                            /* FALLTHRU */

                        case 5:

                            if (interrupt_request & CPU_INTERRUPT_SMP) {

                                idx = EXCP_SMP_INTERRUPT;

                            }

                            /* FALLTHRU */

                        case 6:

                            if (interrupt_request & CPU_INTERRUPT_MCHK) {

                                idx = EXCP_MCHK;

                            }

                        }

                        if (idx >= 0) {

                            env->exception_index = idx;

                            env->error_code = 0;

                            do_interrupt(env);

                            next_tb = 0;

                        }

                    }

#elif defined(TARGET_CRIS)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && (env->pregs[PR_CCS] & I_FLAG)

                        && !env->locked_irq) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

                    if (interrupt_request & CPU_INTERRUPT_NMI

                        && (env->pregs[PR_CCS] & M_FLAG)) {

                        env->exception_index = EXCP_NMI;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_M68K)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((env->sr & SR_I) >> SR_I_SHIFT)

                            < env->pending_level) {

                        /* Real hardware gets the interrupt vector via an

                           IACK cycle at this point.  Current emulated

                           hardware doesn't rely on this, so we

                           provide/save the vector when the interrupt is

                           first signalled.  */

                        env->exception_index = env->pending_vector;

                        do_interrupt_m68k_hardirq(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_S390X) && !defined(CONFIG_USER_ONLY)

                    if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                        (env->psw.mask & PSW_MASK_EXT)) {

                        do_interrupt(env);

                        next_tb = 0;

                    }

#endif

                   /* Don't use the cached interrupt_request value,

                      do_interrupt may have updated the EXITTB flag. */

                    if (env->interrupt_request & CPU_INTERRUPT_EXITTB) {

                        env->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

                        /* ensure that no TB jump will be modified as

                           the program flow was changed */

                        next_tb = 0;

                    }

                }

                if (unlikely(env->exit_request)) {

                    env->exit_request = 0;

                    env->exception_index = EXCP_INTERRUPT;

                    cpu_loop_exit(env);

                }

#if defined(DEBUG_DISAS) || defined(CONFIG_DEBUG_EXEC)

                if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {

                    /* restore flags in standard format */

#if defined(TARGET_I386)

                    env->eflags = env->eflags | cpu_cc_compute_all(env, CC_OP)

                        | (DF & DF_MASK);

                    log_cpu_state(env, X86_DUMP_CCOP);

                    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_M68K)

                    cpu_m68k_flush_flags(env, env->cc_op);

                    env->cc_op = CC_OP_FLAGS;

                    env->sr = (env->sr & 0xffe0)

                              | env->cc_dest | (env->cc_x << 4);

                    log_cpu_state(env, 0);

#else

                    log_cpu_state(env, 0);

#endif

                }

#endif /* DEBUG_DISAS || CONFIG_DEBUG_EXEC */

                spin_lock(&tb_lock);

                tb = tb_find_fast(env);

                /* Note: we do it here to avoid a gcc bug on Mac OS X when

                   doing it in tb_find_slow */

                if (tb_invalidated_flag) {

                    /* as some TB could have been invalidated because

                       of memory exceptions while generating the code, we

                       must recompute the hash index here */

                    next_tb = 0;

                    tb_invalidated_flag = 0;

                }

#ifdef CONFIG_DEBUG_EXEC

                qemu_log_mask(CPU_LOG_EXEC, "Trace 0x%08lx [" TARGET_FMT_lx "] %s\n",

                             (long)tb->tc_ptr, tb->pc,

                             lookup_symbol(tb->pc));

#endif

                /* see if we can patch the calling TB. When the TB

                   spans two pages, we cannot safely do a direct

                   jump. */

                if (next_tb != 0 && tb->page_addr[1] == -1) {

                    tb_add_jump((TranslationBlock *)(next_tb & ~3), next_tb & 3, tb);

                }

                spin_unlock(&tb_lock);

                /* cpu_interrupt might be called while translating the

                   TB, but before it is linked into a potentially

                   infinite loop and becomes env->current_tb. Avoid

                   starting execution if there is a pending interrupt. */

                env->current_tb = tb;

                barrier();

                if (likely(!env->exit_request)) {

                    tc_ptr = tb->tc_ptr;

                /* execute the generated code */

                    next_tb = tcg_qemu_tb_exec(env, tc_ptr);

                    if ((next_tb & 3) == 2) {

                        /* Instruction counter expired.  */

                        int insns_left;

                        tb = (TranslationBlock *)(long)(next_tb & ~3);

                        /* Restore PC.  */

                        cpu_pc_from_tb(env, tb);

                        insns_left = env->icount_decr.u32;

                        if (env->icount_extra && insns_left >= 0) {

                            /* Refill decrementer and continue execution.  */

                            env->icount_extra += insns_left;

                            if (env->icount_extra > 0xffff) {

                                insns_left = 0xffff;

                                insns_left = env->icount_extra;

                            }

                            env->icount_extra -= insns_left;

                            env->icount_decr.u16.low = insns_left;

                            if (insns_left > 0) {

                                /* Execute remaining instructions.  */

                                cpu_exec_nocache(env, insns_left, tb);

                            }

                            env->exception_index = EXCP_INTERRUPT;

                            next_tb = 0;

                            cpu_loop_exit(env);

                        }

                    }

                }

                env->current_tb = NULL;

                /* reset soft MMU for next block (it can currently

                   only be set by a memory fault) */

            } /* for(;;) */

        }

    } /* for(;;) */

#if defined(TARGET_I386)

    /* restore flags in standard format */

    env->eflags = env->eflags | cpu_cc_compute_all(env, CC_OP)

        | (DF & DF_MASK);

#elif defined(TARGET_ARM)

    /* XXX: Save/restore host fpu exception state?.  */

#elif defined(TARGET_UNICORE32)

#elif defined(TARGET_SPARC)

#elif defined(TARGET_PPC)

#elif defined(TARGET_LM32)

#elif defined(TARGET_M68K)

    cpu_m68k_flush_flags(env, env->cc_op);

    env->cc_op = CC_OP_FLAGS;

    env->sr = (env->sr & 0xffe0)

              | env->cc_dest | (env->cc_x << 4);

#elif defined(TARGET_MICROBLAZE)

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_CRIS)

#elif defined(TARGET_S390X)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    /* fail safe : never use cpu_single_env outside cpu_exec() */

    cpu_single_env = NULL;

    return ret;

}


callback(void *priv_data, int index, uint8_t *buf, int buf_size, int64_t time)

{

    AVFormatContext *s = priv_data;

    struct dshow_ctx *ctx = s->priv_data;

    AVPacketList **ppktl, *pktl_next;

//    dump_videohdr(s, vdhdr);

    WaitForSingleObject(ctx->mutex, INFINITE);

    if(shall_we_drop(s))

        goto fail;

    pktl_next = av_mallocz(sizeof(AVPacketList));

    if(!pktl_next)

        goto fail;

    if(av_new_packet(&pktl_next->pkt, buf_size) < 0) {

        av_free(pktl_next);

        goto fail;

    }

    pktl_next->pkt.stream_index = index;

    pktl_next->pkt.pts = time;

    memcpy(pktl_next->pkt.data, buf, buf_size);

    for(ppktl = &ctx->pktl ; *ppktl ; ppktl = &(*ppktl)->next);

    *ppktl = pktl_next;

    ctx->curbufsize += buf_size;

    SetEvent(ctx->event);

    ReleaseMutex(ctx->mutex);

    return;

fail:

    ReleaseMutex(ctx->mutex);

    return;

}


static inline void RENAME(yvu9_to_yuy2)(const uint8_t *src1, const uint8_t *src2, const uint8_t *src3,

			uint8_t *dst,

			unsigned width, unsigned height,

			int srcStride1, int srcStride2,

			int srcStride3, int dstStride)

{

    unsigned long y,x,w,h;

    w=width/2; h=height;

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

	const uint8_t* yp=src1+srcStride1*y;

	const uint8_t* up=src2+srcStride2*(y>>2);

	const uint8_t* vp=src3+srcStride3*(y>>2);

	uint8_t* d=dst+dstStride*y;

	x=0;

#ifdef HAVE_MMX

	for(;x<w-7;x+=8)

	{

	    asm volatile(

		PREFETCH" 32(%1, %0)\n\t"

		PREFETCH" 32(%2, %0)\n\t"

		PREFETCH" 32(%3, %0)\n\t"

		"movq	(%1, %0, 4), %%mm0\n\t"       /* Y0Y1Y2Y3Y4Y5Y6Y7 */

		"movq	(%2, %0), %%mm1\n\t"       /* U0U1U2U3U4U5U6U7 */

		"movq	(%3, %0), %%mm2\n\t"	     /* V0V1V2V3V4V5V6V7 */

		"movq	%%mm0, %%mm3\n\t"    /* Y0Y1Y2Y3Y4Y5Y6Y7 */

		"movq	%%mm1, %%mm4\n\t"    /* U0U1U2U3U4U5U6U7 */

		"movq	%%mm2, %%mm5\n\t"    /* V0V1V2V3V4V5V6V7 */

		"punpcklbw %%mm1, %%mm1\n\t" /* U0U0 U1U1 U2U2 U3U3 */

		"punpcklbw %%mm2, %%mm2\n\t" /* V0V0 V1V1 V2V2 V3V3 */

		"punpckhbw %%mm4, %%mm4\n\t" /* U4U4 U5U5 U6U6 U7U7 */

		"punpckhbw %%mm5, %%mm5\n\t" /* V4V4 V5V5 V6V6 V7V7 */

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

		"punpcklbw %%mm2, %%mm1\n\t" /* U0V0 U0V0 U1V1 U1V1*/

		"punpcklbw %%mm1, %%mm0\n\t" /* Y0U0 Y1V0 Y2U0 Y3V0*/

		"punpckhbw %%mm1, %%mm3\n\t" /* Y4U1 Y5V1 Y6U1 Y7V1*/

		MOVNTQ"	%%mm0, (%4, %0, 8)\n\t"

		MOVNTQ"	%%mm3, 8(%4, %0, 8)\n\t"

		"punpckhbw %%mm2, %%mm6\n\t" /* U2V2 U2V2 U3V3 U3V3*/

		"movq	8(%1, %0, 4), %%mm0\n\t"

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

		"punpcklbw %%mm6, %%mm0\n\t" /* Y U2 Y V2 Y U2 Y V2*/

		"punpckhbw %%mm6, %%mm3\n\t" /* Y U3 Y V3 Y U3 Y V3*/

		MOVNTQ"	%%mm0, 16(%4, %0, 8)\n\t"

		MOVNTQ"	%%mm3, 24(%4, %0, 8)\n\t"

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

		"movq	16(%1, %0, 4), %%mm0\n\t"

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

		"punpcklbw %%mm5, %%mm4\n\t"

		"punpcklbw %%mm4, %%mm0\n\t" /* Y U4 Y V4 Y U4 Y V4*/

		"punpckhbw %%mm4, %%mm3\n\t" /* Y U5 Y V5 Y U5 Y V5*/

		MOVNTQ"	%%mm0, 32(%4, %0, 8)\n\t"

		MOVNTQ"	%%mm3, 40(%4, %0, 8)\n\t"

		"punpckhbw %%mm5, %%mm6\n\t"

		"movq	24(%1, %0, 4), %%mm0\n\t"

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

		"punpcklbw %%mm6, %%mm0\n\t" /* Y U6 Y V6 Y U6 Y V6*/

		"punpckhbw %%mm6, %%mm3\n\t" /* Y U7 Y V7 Y U7 Y V7*/

		MOVNTQ"	%%mm0, 48(%4, %0, 8)\n\t"

		MOVNTQ"	%%mm3, 56(%4, %0, 8)\n\t"

		: "+r" (x)

                : "r"(yp), "r" (up), "r"(vp), "r"(d)

		:"memory");

	}

#endif

	for(; x<w; x++)

	{

	    const int x2= x<<2;

	    d[8*x+0]=yp[x2];

	    d[8*x+1]=up[x];

	    d[8*x+2]=yp[x2+1];

	    d[8*x+3]=vp[x];

	    d[8*x+4]=yp[x2+2];

	    d[8*x+5]=up[x];

	    d[8*x+6]=yp[x2+3];

	    d[8*x+7]=vp[x];

	}

    }

#ifdef HAVE_MMX

	asm(

		EMMS" \n\t"

		SFENCE" \n\t"

		::: "memory"

		);

#endif

}


static int qio_channel_websock_handshake_process(QIOChannelWebsock *ioc,

                                                 const char *line,

                                                 size_t size,

                                                 Error **errp)

{

    int ret = -1;

    char *protocols = qio_channel_websock_handshake_entry(

        line, size, QIO_CHANNEL_WEBSOCK_HEADER_PROTOCOL);

    char *version = qio_channel_websock_handshake_entry(

        line, size, QIO_CHANNEL_WEBSOCK_HEADER_VERSION);

    char *key = qio_channel_websock_handshake_entry(

        line, size, QIO_CHANNEL_WEBSOCK_HEADER_KEY);

    if (!protocols) {

        error_setg(errp, "Missing websocket protocol header data");

        goto cleanup;

    }

    if (!version) {

        error_setg(errp, "Missing websocket version header data");

        goto cleanup;

    }

    if (!key) {

        error_setg(errp, "Missing websocket key header data");

        goto cleanup;

    }

    if (!g_strrstr(protocols, QIO_CHANNEL_WEBSOCK_PROTOCOL_BINARY)) {

        error_setg(errp, "No '%s' protocol is supported by client '%s'",

                   QIO_CHANNEL_WEBSOCK_PROTOCOL_BINARY, protocols);

        goto cleanup;

    }

    if (!g_str_equal(version, QIO_CHANNEL_WEBSOCK_SUPPORTED_VERSION)) {

        error_setg(errp, "Version '%s' is not supported by client '%s'",

                   QIO_CHANNEL_WEBSOCK_SUPPORTED_VERSION, version);

        goto cleanup;

    }

    if (strlen(key) != QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN) {

        error_setg(errp, "Key length '%zu' was not as expected '%d'",

                   strlen(key), QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN);

        goto cleanup;

    }

    ret = qio_channel_websock_handshake_send_response(ioc, key, errp);

 cleanup:

    g_free(protocols);

    g_free(version);

    g_free(key);

    return ret;

}


static void *av_mallocz_static(unsigned int size)

{

    void *ptr = av_mallocz(size);

    if(ptr){

        array_static =av_fast_realloc(array_static, &allocated_static, sizeof(void*)*(last_static+1));

        if(!array_static)

            return NULL;

        array_static[last_static++] = ptr;

    }

    return ptr;

}


int index_from_key(const char *key)

{

    int i;

    for (i = 0; QKeyCode_lookup[i] != NULL; i++) {

        if (!strcmp(key, QKeyCode_lookup[i])) {

            break;

        }

    }

    /* Return Q_KEY_CODE__MAX if the key is invalid */

    return i;

}


static int mxf_read_primer_pack(MXFContext *mxf)

{

    ByteIOContext *pb = mxf->fc->pb;

    int item_num = get_be32(pb);

    int item_len = get_be32(pb);

    if (item_len != 18) {

        av_log(mxf->fc, AV_LOG_ERROR, "unsupported primer pack item length\n");

        return -1;

    }

    if (item_num > UINT_MAX / item_len)

        return -1;

    mxf->local_tags_count = item_num;

    mxf->local_tags = av_malloc(item_num*item_len);

    if (!mxf->local_tags)

        return -1;

    get_buffer(pb, mxf->local_tags, item_num*item_len);

    return 0;

}


static void rtas_ibm_query_interrupt_source_number(PowerPCCPU *cpu,

                                                   sPAPREnvironment *spapr,

                                                   uint32_t token,

                                                   uint32_t nargs,

                                                   target_ulong args,

                                                   uint32_t nret,

                                                   target_ulong rets)

{

    uint32_t config_addr = rtas_ld(args, 0);

    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3);

    int ndev;

    sPAPRPHBState *phb = NULL;

    /* Fins sPAPRPHBState */

    phb = find_phb(spapr, buid);

    if (!phb) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    /* Find device descriptor and start IRQ */

    ndev = spapr_msicfg_find(phb, config_addr, false);

    if (ndev < 0) {

        trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr);

        rtas_st(rets, 0, RTAS_OUT_HW_ERROR);

        return;

    }

    intr_src_num = phb->msi_table[ndev].irq + ioa_intr_num;

    trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num,

                                                           intr_src_num);

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    rtas_st(rets, 1, intr_src_num);

    rtas_st(rets, 2, 1);/* 0 == level; 1 == edge */

}


static int convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst, int max_size)

{

    switch (AV_RB32(src)) {

    case DCA_SYNCWORD_CORE_BE:

    case DCA_SYNCWORD_SUBSTREAM:

        memcpy(dst, src, src_size);

        return src_size;

    case DCA_SYNCWORD_CORE_LE:

    case DCA_SYNCWORD_CORE_14B_BE:

    case DCA_SYNCWORD_CORE_14B_LE:

        return avpriv_dca_convert_bitstream(src, src_size, dst, max_size);

    default:

        return AVERROR_INVALIDDATA;

    }

}


int ff_scale_image(uint8_t *dst_data[4], int dst_linesize[4],

                   int dst_w, int dst_h, enum AVPixelFormat dst_pix_fmt,

                   uint8_t * const src_data[4], int src_linesize[4],

                   int src_w, int src_h, enum AVPixelFormat src_pix_fmt,

                   void *log_ctx)

{

    int ret;

    struct SwsContext *sws_ctx = sws_getContext(src_w, src_h, src_pix_fmt,

                                                dst_w, dst_h, dst_pix_fmt,

                                                SWS_BILINEAR, NULL, NULL, NULL);

    if (!sws_ctx) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Impossible to create scale context for the conversion "

               "fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",

               av_get_pix_fmt_name(src_pix_fmt), src_w, src_h,

               av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h);

        ret = AVERROR(EINVAL);

        goto end;

    }

    if ((ret = av_image_alloc(dst_data, dst_linesize, dst_w, dst_h, dst_pix_fmt, 16)) < 0)

        goto end;

    ret = 0;

    sws_scale(sws_ctx, (const uint8_t * const*)src_data, src_linesize, 0, src_h, dst_data, dst_linesize);

end:

    sws_freeContext(sws_ctx);

    return ret;

}


static int ftp_read(URLContext *h, unsigned char *buf, int size)

{

    FTPContext *s = h->priv_data;

    int read, err, retry_done = 0;

    av_dlog(h, "ftp protocol read %d bytes\n", size);

  retry:

    if (s->state == DISCONNECTED) {

        /* optimization */

        if (s->position >= s->filesize)

            return 0;

        if ((err = ftp_connect_data_connection(h)) < 0)

            return err;

    }

    if (s->state == READY) {

        if (s->position >= s->filesize)

            return 0;

        if ((err = ftp_retrieve(s)) < 0)

            return err;

    }

    if (s->conn_data && s->state == DOWNLOADING) {

        read = ffurl_read(s->conn_data, buf, size);

        if (read >= 0) {

            s->position += read;

            if (s->position >= s->filesize) {

                /* server will terminate, but keep current position to avoid madness */

                /* save position to restart from it */

                int64_t pos = s->position;

                if (ftp_abort(h) < 0) {

                    s->position = pos;

                    return AVERROR(EIO);

                }

                s->position = pos;

            }

        }

        if (read <= 0 && s->position < s->filesize && !h->is_streamed) {

            /* Server closed connection. Probably due to inactivity */

            int64_t pos = s->position;

            av_log(h, AV_LOG_INFO, "Reconnect to FTP server.\n");

            if ((err = ftp_abort(h)) < 0)

                return err;

            if ((err = ftp_seek(h, pos, SEEK_SET)) < 0) {

                av_log(h, AV_LOG_ERROR, "Position cannot be restored.\n");

                return err;

            }

            if (!retry_done) {

                retry_done = 1;

                goto retry;

            }

        }

        return read;

    }

    av_log(h, AV_LOG_DEBUG, "FTP read failed\n");

    return AVERROR(EIO);

}


sPAPROptionVector *spapr_ovec_new(void)

{

    sPAPROptionVector *ov;

    ov = g_new0(sPAPROptionVector, 1);

    ov->bitmap = bitmap_new(OV_MAXBITS);

    return ov;

}


static uint32_t vmdk_read_cid(BlockDriverState *bs, int parent)

{

    char desc[DESC_SIZE];

    uint32_t cid;

    const char *p_name, *cid_str;

    size_t cid_str_size;

    BDRVVmdkState *s = bs->opaque;

    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {

        return 0;

    }

    if (parent) {

        cid_str = "parentCID";

        cid_str_size = sizeof("parentCID");

    } else {

        cid_str = "CID";

        cid_str_size = sizeof("CID");

    }

    p_name = strstr(desc, cid_str);

    if (p_name != NULL) {

        p_name += cid_str_size;

        sscanf(p_name, "%x", &cid);

    }

    return cid;

}


QemuOpts *qemu_opts_find(QemuOptsList *list, const char *id)

{

    QemuOpts *opts;

    QTAILQ_FOREACH(opts, &list->head, next) {

        if (!opts->id) {

            if (!id) {

                return opts;

            }

            continue;

        }

        if (strcmp(opts->id, id) != 0) {

            continue;

        }

        return opts;

    }

    return NULL;

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *in_picture,

                         float quality)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->st->codec;

    int nb_frames;

    double sync_ipts, delta;

    double duration = 0;

    int frame_size = 0;

    InputStream *ist = NULL;

    if (ost->source_index >= 0)

        ist = input_streams[ost->source_index];

    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)

        duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));

    sync_ipts = in_picture->pts;

    delta = sync_ipts - ost->sync_opts + duration;

    /* by default, we output a single frame */

    nb_frames = 1;

    format_video_sync = video_sync_method;

    if (format_video_sync == VSYNC_AUTO)

        format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;

    switch (format_video_sync) {

    case VSYNC_CFR:

        // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

        if (delta < -1.1)

            nb_frames = 0;

        else if (delta > 1.1)

            nb_frames = lrintf(delta);

        break;

    case VSYNC_VFR:

        if (delta <= -0.6)

            nb_frames = 0;

        else if (delta > 0.6)

            ost->sync_opts = lrint(sync_ipts);

        break;

    case VSYNC_DROP:

    case VSYNC_PASSTHROUGH:

        ost->sync_opts = lrint(sync_ipts);

        break;

    default:

        av_assert0(0);

    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);

    if (nb_frames == 0) {

        av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");

    } else if (nb_frames > 1) {

        nb_frames_dup += nb_frames - 1;

        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);

duplicate_frame:

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    in_picture->pts = ost->sync_opts;

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

        enc->codec->id == CODEC_ID_RAWVIDEO) {

        /* raw pictures are written as AVPicture structure to

           avoid any copies. We support temporarily the older

           method. */

        enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;

        enc->coded_frame->top_field_first  = in_picture->top_field_first;

        pkt.data   = (uint8_t *)in_picture;

        pkt.size   =  sizeof(AVPicture);

        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= AV_PKT_FLAG_KEY;

        write_frame(s, &pkt, ost);

        video_size += pkt.size;

    } else {

        int got_packet;

        AVFrame big_picture;

        big_picture = *in_picture;

        /* better than nothing: use input picture interlaced

           settings */

        big_picture.interlaced_frame = in_picture->interlaced_frame;

        if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {

            if (ost->top_field_first == -1)

                big_picture.top_field_first = in_picture->top_field_first;

            else

                big_picture.top_field_first = !!ost->top_field_first;

        /* handles same_quant here. This is not correct because it may

           not be a global option */

        big_picture.quality = quality;

        if (!enc->me_threshold)

            big_picture.pict_type = 0;

        if (ost->forced_kf_index < ost->forced_kf_count &&

            big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

            big_picture.pict_type = AV_PICTURE_TYPE_I;

            ost->forced_kf_index++;

        update_benchmark(NULL);

        ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);

        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);

        if (ret < 0) {

            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

            exit_program(1);

        if (got_packet) {

            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))

                pkt.pts = ost->sync_opts;

            if (pkt.pts != AV_NOPTS_VALUE)

                pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);

            if (pkt.dts != AV_NOPTS_VALUE)

                pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

            write_frame(s, &pkt, ost);

            frame_size = pkt.size;

            video_size += pkt.size;

            av_free_packet(&pkt);

            /* if two pass, output log */

            if (ost->logfile && enc->stats_out) {

                fprintf(ost->logfile, "%s", enc->stats_out);

    ost->sync_opts++;

    /*

     * For video, number of frames in == number of packets out.

     * But there may be reordering, so we can't throw away frames on encoder

     * flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

    if(--nb_frames)

        goto duplicate_frame;

    if (vstats_filename && frame_size)

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


static av_cold int read_specific_config(ALSDecContext *ctx)

{

    GetBitContext gb;

    uint64_t ht_size;

    int i, config_offset;

    MPEG4AudioConfig m4ac;

    ALSSpecificConfig *sconf = &ctx->sconf;

    AVCodecContext *avctx    = ctx->avctx;

    uint32_t als_id, header_size, trailer_size;

    init_get_bits(&gb, avctx->extradata, avctx->extradata_size * 8);

    config_offset = avpriv_mpeg4audio_get_config(&m4ac, avctx->extradata,

                                                 avctx->extradata_size * 8, 1);

    if (config_offset < 0)

        return -1;

    skip_bits_long(&gb, config_offset);

    if (get_bits_left(&gb) < (30 << 3))

        return -1;

    // read the fixed items

    als_id                      = get_bits_long(&gb, 32);

    avctx->sample_rate          = m4ac.sample_rate;

    skip_bits_long(&gb, 32); // sample rate already known

    sconf->samples              = get_bits_long(&gb, 32);

    avctx->channels             = m4ac.channels;

    skip_bits(&gb, 16);      // number of channels already known

    skip_bits(&gb, 3);       // skip file_type

    sconf->resolution           = get_bits(&gb, 3);

    sconf->floating             = get_bits1(&gb);

    sconf->msb_first            = get_bits1(&gb);

    sconf->frame_length         = get_bits(&gb, 16) + 1;

    sconf->ra_distance          = get_bits(&gb, 8);

    sconf->ra_flag              = get_bits(&gb, 2);

    sconf->adapt_order          = get_bits1(&gb);

    sconf->coef_table           = get_bits(&gb, 2);

    sconf->long_term_prediction = get_bits1(&gb);

    sconf->max_order            = get_bits(&gb, 10);

    sconf->block_switching      = get_bits(&gb, 2);

    sconf->bgmc                 = get_bits1(&gb);

    sconf->sb_part              = get_bits1(&gb);

    sconf->joint_stereo         = get_bits1(&gb);

    sconf->mc_coding            = get_bits1(&gb);

    sconf->chan_config          = get_bits1(&gb);

    sconf->chan_sort            = get_bits1(&gb);

    sconf->crc_enabled          = get_bits1(&gb);

    sconf->rlslms               = get_bits1(&gb);

    skip_bits(&gb, 5);       // skip 5 reserved bits

    skip_bits1(&gb);         // skip aux_data_enabled

    // check for ALSSpecificConfig struct

    if (als_id != MKBETAG('A','L','S','\0'))

        return -1;

    ctx->cur_frame_length = sconf->frame_length;

    // read channel config

    if (sconf->chan_config)

        sconf->chan_config_info = get_bits(&gb, 16);

    // TODO: use this to set avctx->channel_layout

    // read channel sorting

    if (sconf->chan_sort && avctx->channels > 1) {

        int chan_pos_bits = av_ceil_log2(avctx->channels);

        int bits_needed  = avctx->channels * chan_pos_bits + 7;

        if (get_bits_left(&gb) < bits_needed)

            return -1;

        if (!(sconf->chan_pos = av_malloc(avctx->channels * sizeof(*sconf->chan_pos))))

            return AVERROR(ENOMEM);

        ctx->cs_switch = 1;

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

            int idx;

            idx = get_bits(&gb, chan_pos_bits);

            if (idx >= avctx->channels) {

                av_log(avctx, AV_LOG_WARNING, "Invalid channel reordering.\n");

                ctx->cs_switch = 0;

                break;

            }

            sconf->chan_pos[idx] = i;

        }

        align_get_bits(&gb);

    }

    // read fixed header and trailer sizes,

    // if size = 0xFFFFFFFF then there is no data field!

    if (get_bits_left(&gb) < 64)

        return -1;

    header_size  = get_bits_long(&gb, 32);

    trailer_size = get_bits_long(&gb, 32);

    if (header_size  == 0xFFFFFFFF)

        header_size  = 0;

    if (trailer_size == 0xFFFFFFFF)

        trailer_size = 0;

    ht_size = ((int64_t)(header_size) + (int64_t)(trailer_size)) << 3;

    // skip the header and trailer data

    if (get_bits_left(&gb) < ht_size)

        return -1;

    if (ht_size > INT32_MAX)

        return -1;

    skip_bits_long(&gb, ht_size);

    // initialize CRC calculation

    if (sconf->crc_enabled) {

        if (get_bits_left(&gb) < 32)

            return -1;

        if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_CAREFUL)) {

            ctx->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);

            ctx->crc       = 0xFFFFFFFF;

            ctx->crc_org   = ~get_bits_long(&gb, 32);

        } else

            skip_bits_long(&gb, 32);

    }

    // no need to read the rest of ALSSpecificConfig (ra_unit_size & aux data)

    dprint_specific_config(ctx);

    return 0;

}


static int v4l2_receive_frame(AVCodecContext *avctx, AVFrame *frame)

{

    V4L2m2mContext *s = avctx->priv_data;

    V4L2Context *const capture = &s->capture;

    V4L2Context *const output = &s->output;

    AVPacket avpkt = {0};

    int ret;

    ret = ff_decode_get_packet(avctx, &avpkt);

    if (ret < 0 && ret != AVERROR_EOF)

        return ret;

    if (s->draining)

        goto dequeue;

    ret = ff_v4l2_context_enqueue_packet(output, &avpkt);

    if (ret < 0) {

        if (ret != AVERROR(ENOMEM))

           return ret;

        /* no input buffers available, continue dequeing */

    }

    if (avpkt.size) {

        ret = v4l2_try_start(avctx);

        if (ret)

            return 0;

    }

dequeue:

    return ff_v4l2_context_dequeue_frame(capture, frame);

}


static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,

                                AVFrame *picture)

{

    int compno, reslevelno, bandno;

    int x, y;

    uint8_t *line;

    Jpeg2000T1Context t1;

    /* Loop on tile components */

    for (compno = 0; compno < s->ncomponents; compno++) {

        Jpeg2000Component *comp     = tile->comp + compno;

        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

        /* Loop on resolution levels */

        for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {

            Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

            /* Loop on bands */

            for (bandno = 0; bandno < rlevel->nbands; bandno++) {

                uint16_t nb_precincts, precno;

                Jpeg2000Band *band = rlevel->band + bandno;

                int cblkno = 0, bandpos;

                bandpos = bandno + (reslevelno > 0);

                if (band->coord[0][0] == band->coord[0][1] ||

                    band->coord[1][0] == band->coord[1][1])

                    continue;

                nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;

                /* Loop on precincts */

                for (precno = 0; precno < nb_precincts; precno++) {

                    Jpeg2000Prec *prec = band->prec + precno;

                    /* Loop on codeblocks */

                    for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                        int x, y;

                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                        decode_cblk(s, codsty, &t1, cblk,

                                    cblk->coord[0][1] - cblk->coord[0][0],

                                    cblk->coord[1][1] - cblk->coord[1][0],

                                    bandpos);

                        x = cblk->coord[0][0];

                        y = cblk->coord[1][0];

                        if (codsty->transform == FF_DWT97)

                            dequantization_float(x, y, cblk, comp, &t1, band);

                        else

                            dequantization_int(x, y, cblk, comp, &t1, band);

                   } /* end cblk */

                } /*end prec */

            } /* end band */

        } /* end reslevel */

        /* inverse DWT */

        ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);

    } /*end comp */

    /* inverse MCT transformation */

    if (tile->codsty[0].mct)

        mct_decode(s, tile);

    if (s->precision <= 8) {

        for (compno = 0; compno < s->ncomponents; compno++) {

            Jpeg2000Component *comp = tile->comp + compno;

            float *datap = comp->f_data;

            int32_t *i_datap = comp->i_data;

            int cbps = s->cbps[compno];

            int w = tile->comp[compno].coord[0][1] - s->image_offset_x;

            y    = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = picture->data[0] + y * picture->linesize[0];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint8_t *dst;

                x   = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = line + x * s->ncomponents + compno;

                if (tile->codsty->transform == FF_DWT97) {

                    for (; x < w; x += s->cdx[compno]) {

                        int val = lrintf(*datap) + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        *dst = val << (8 - cbps);

                        datap++;

                        dst += s->ncomponents;

                    }

                } else {

                    for (; x < w; x += s->cdx[compno]) {

                        int val = *i_datap + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        *dst = val << (8 - cbps);

                        i_datap++;

                        dst += s->ncomponents;

                    }

                }

                line += picture->linesize[0];

            }

        }

    } else {

        for (compno = 0; compno < s->ncomponents; compno++) {

            Jpeg2000Component *comp = tile->comp + compno;

            float *datap = comp->f_data;

            int32_t *i_datap = comp->i_data;

            uint16_t *linel;

            int cbps = s->cbps[compno];

            int w = tile->comp[compno].coord[0][1] - s->image_offset_x;

            y     = tile->comp[compno].coord[1][0] - s->image_offset_y;

            linel = (uint16_t *)picture->data[0] + y * (picture->linesize[0] >> 1);

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint16_t *dst;

                x   = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = linel + (x * s->ncomponents + compno);

                if (tile->codsty->transform == FF_DWT97) {

                    for (; x < w; x += s-> cdx[compno]) {

                        int  val = lrintf(*datap) + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        /* align 12 bit values in little-endian mode */

                        *dst = val << (16 - cbps);

                        datap++;

                        dst += s->ncomponents;

                    }

                } else {

                    for (; x < w; x += s-> cdx[compno]) {

                        int val = *i_datap + (1 << (cbps - 1));

                        /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */

                        val = av_clip(val, 0, (1 << cbps) - 1);

                        /* align 12 bit values in little-endian mode */

                        *dst = val << (16 - cbps);

                        i_datap++;

                        dst += s->ncomponents;

                    }

                }

                linel += picture->linesize[0] >> 1;

            }

        }

    }

    return 0;

}


static int rtmp_open(URLContext *s, const char *uri, int flags)

{

    RTMPContext *rt = s->priv_data;

    char proto[8], hostname[256], path[1024], auth[100], *fname;

    char *old_app, *qmark, fname_buffer[1024];

    uint8_t buf[2048];

    int port;

    AVDictionary *opts = NULL;

    int ret;

    if (rt->listen_timeout > 0)

        rt->listen = 1;

    rt->is_input = !(flags & AVIO_FLAG_WRITE);

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

                 hostname, sizeof(hostname), &port,

                 path, sizeof(path), s->filename);

    if (strchr(path, ' ')) {

        av_log(s, AV_LOG_WARNING,

               "Detected librtmp style URL parameters, these aren't supported "

               "by the libavformat internal RTMP handler currently enabled. "

               "See the documentation for the correct way to pass parameters.\n");

    }

    if (auth[0]) {

        char *ptr = strchr(auth, ':');

        if (ptr) {

            *ptr = '\0';

            av_strlcpy(rt->username, auth, sizeof(rt->username));

            av_strlcpy(rt->password, ptr + 1, sizeof(rt->password));

        }

    }

    if (rt->listen && strcmp(proto, "rtmp")) {

        av_log(s, AV_LOG_ERROR, "rtmp_listen not available for %s\n",

               proto);

        return AVERROR(EINVAL);

    }

    if (!strcmp(proto, "rtmpt") || !strcmp(proto, "rtmpts")) {

        if (!strcmp(proto, "rtmpts"))

            av_dict_set(&opts, "ffrtmphttp_tls", "1", 1);

        /* open the http tunneling connection */

        ff_url_join(buf, sizeof(buf), "ffrtmphttp", NULL, hostname, port, NULL);

    } else if (!strcmp(proto, "rtmps")) {

        /* open the tls connection */

        if (port < 0)

            port = RTMPS_DEFAULT_PORT;

        ff_url_join(buf, sizeof(buf), "tls", NULL, hostname, port, NULL);

    } else if (!strcmp(proto, "rtmpe") || (!strcmp(proto, "rtmpte"))) {

        if (!strcmp(proto, "rtmpte"))

            av_dict_set(&opts, "ffrtmpcrypt_tunneling", "1", 1);

        /* open the encrypted connection */

        ff_url_join(buf, sizeof(buf), "ffrtmpcrypt", NULL, hostname, port, NULL);

        rt->encrypted = 1;

    } else {

        /* open the tcp connection */

        if (port < 0)

            port = RTMP_DEFAULT_PORT;

        if (rt->listen)

            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port,

                        "?listen&listen_timeout=%d",

                        rt->listen_timeout * 1000);

        else

            ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);

    }

reconnect:

    if ((ret = ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE,

                          &s->interrupt_callback, &opts)) < 0) {

        av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);

        goto fail;

    }

    if (rt->swfverify) {

        if ((ret = rtmp_calc_swfhash(s)) < 0)

            goto fail;

    }

    rt->state = STATE_START;

    if (!rt->listen && (ret = rtmp_handshake(s, rt)) < 0)

        goto fail;

    if (rt->listen && (ret = rtmp_server_handshake(s, rt)) < 0)

        goto fail;

    rt->out_chunk_size = 128;

    rt->in_chunk_size  = 128; // Probably overwritten later

    rt->state = STATE_HANDSHAKED;

    // Keep the application name when it has been defined by the user.

    old_app = rt->app;

    rt->app = av_malloc(APP_MAX_LENGTH);

    if (!rt->app) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    //extract "app" part from path

    qmark = strchr(path, '?');

    if (qmark && strstr(qmark, "slist=")) {

        char* amp;

        // After slist we have the playpath, before the params, the app

        av_strlcpy(rt->app, path + 1, FFMIN(qmark - path, APP_MAX_LENGTH));

        fname = strstr(path, "slist=") + 6;

        // Strip any further query parameters from fname

        amp = strchr(fname, '&');

        if (amp) {

            av_strlcpy(fname_buffer, fname, FFMIN(amp - fname + 1,

                                                  sizeof(fname_buffer)));

            fname = fname_buffer;

        }

    } else if (!strncmp(path, "/ondemand/", 10)) {

        fname = path + 10;

        memcpy(rt->app, "ondemand", 9);

    } else {

        char *next = *path ? path + 1 : path;

        char *p = strchr(next, '/');

        if (!p) {

            fname = next;

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

        } else {

            // make sure we do not mismatch a playpath for an application instance

            char *c = strchr(p + 1, ':');

            fname = strchr(p + 1, '/');

            if (!fname || (c && c < fname)) {

                fname = p + 1;

                av_strlcpy(rt->app, path + 1, FFMIN(p - path, APP_MAX_LENGTH));

            } else {

                fname++;

                av_strlcpy(rt->app, path + 1, FFMIN(fname - path - 1, APP_MAX_LENGTH));

            }

        }

    }

    if (old_app) {

        // The name of application has been defined by the user, override it.

        if (strlen(old_app) >= APP_MAX_LENGTH) {

            ret = AVERROR(EINVAL);

            goto fail;

        }

        av_free(rt->app);

        rt->app = old_app;

    }

    if (!rt->playpath) {

        int len = strlen(fname);

        rt->playpath = av_malloc(PLAYPATH_MAX_LENGTH);

        if (!rt->playpath) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (!strchr(fname, ':') && len >= 4 &&

            (!strcmp(fname + len - 4, ".f4v") ||

             !strcmp(fname + len - 4, ".mp4"))) {

            memcpy(rt->playpath, "mp4:", 5);

        } else {

            if (len >= 4 && !strcmp(fname + len - 4, ".flv"))

                fname[len - 4] = '\0';

            rt->playpath[0] = 0;

        }

        av_strlcat(rt->playpath, fname, PLAYPATH_MAX_LENGTH);

    }

    if (!rt->tcurl) {

        rt->tcurl = av_malloc(TCURL_MAX_LENGTH);

        if (!rt->tcurl) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        ff_url_join(rt->tcurl, TCURL_MAX_LENGTH, proto, NULL, hostname,

                    port, "/%s", rt->app);

    }

    if (!rt->flashver) {

        rt->flashver = av_malloc(FLASHVER_MAX_LENGTH);

        if (!rt->flashver) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (rt->is_input) {

            snprintf(rt->flashver, FLASHVER_MAX_LENGTH, "%s %d,%d,%d,%d",

                    RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2,

                    RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);

        } else {

            snprintf(rt->flashver, FLASHVER_MAX_LENGTH,

                    "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);

        }

    }

    rt->client_report_size = 1048576;

    rt->bytes_read = 0;

    rt->has_audio = 0;

    rt->has_video = 0;

    rt->received_metadata = 0;

    rt->last_bytes_read = 0;

    rt->server_bw = 2500000;

    av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",

           proto, path, rt->app, rt->playpath);

    if (!rt->listen) {

        if ((ret = gen_connect(s, rt)) < 0)

            goto fail;

    } else {

        if ((ret = read_connect(s, s->priv_data)) < 0)

            goto fail;

    }

    do {

        ret = get_packet(s, 1);

    } while (ret == AVERROR(EAGAIN));

    if (ret < 0)

        goto fail;

    if (rt->do_reconnect) {

        int i;

        ffurl_close(rt->stream);

        rt->stream       = NULL;

        rt->do_reconnect = 0;

        rt->nb_invokes   = 0;

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

            memset(rt->prev_pkt[i], 0,

                   sizeof(**rt->prev_pkt) * rt->nb_prev_pkt[i]);

        free_tracked_methods(rt);

        goto reconnect;

    }

    if (rt->is_input) {

        int err;

        // generate FLV header for demuxer

        rt->flv_size = 13;

        if ((err = av_reallocp(&rt->flv_data, rt->flv_size)) < 0)

            return err;

        rt->flv_off  = 0;

        memcpy(rt->flv_data, "FLV\1\0\0\0\0\011\0\0\0\0", rt->flv_size);

        // Read packets until we reach the first A/V packet or read metadata.

        // If there was a metadata package in front of the A/V packets, we can

        // build the FLV header from this. If we do not receive any metadata,

        // the FLV decoder will allocate the needed streams when their first

        // audio or video packet arrives.

        while (!rt->has_audio && !rt->has_video && !rt->received_metadata) {

            if ((ret = get_packet(s, 0)) < 0)

               return ret;

        }

        // Either after we have read the metadata or (if there is none) the

        // first packet of an A/V stream, we have a better knowledge about the

        // streams, so set the FLV header accordingly.

        if (rt->has_audio) {

            rt->flv_data[4] |= FLV_HEADER_FLAG_HASAUDIO;

        }

        if (rt->has_video) {

            rt->flv_data[4] |= FLV_HEADER_FLAG_HASVIDEO;

        }

    } else {

        rt->flv_size = 0;

        rt->flv_data = NULL;

        rt->flv_off  = 0;

        rt->skip_bytes = 13;

    }

    s->max_packet_size = rt->stream->max_packet_size;

    s->is_streamed     = 1;

    return 0;

fail:

    av_dict_free(&opts);

    rtmp_close(s);

    return ret;

}


static int read_random(uint32_t *dst, const char *file)

{

    int fd = open(file, O_RDONLY);

    int err = -1;

    if (fd == -1)

        return -1;

#if HAVE_FCNTL && defined(O_NONBLOCK)

    if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) != -1)

#endif

        err = read(fd, dst, sizeof(*dst));

    close(fd);

    return err;

}


static void enable_device(PIIX4PMState *s, int slot)

{

    s->ar.gpe.sts[0] |= PIIX4_PCI_HOTPLUG_STATUS;

    s->pci0_status.up |= (1 << slot);

}


static QObject *parse_literal(JSONParserContext *ctxt)

{

    QObject *token, *obj;

    JSONParserContext saved_ctxt = parser_context_save(ctxt);

    token = parser_context_pop_token(ctxt);

    if (token == NULL) {

        goto out;

    }

    switch (token_get_type(token)) {

    case JSON_STRING:

        obj = QOBJECT(qstring_from_escaped_str(ctxt, token));

        break;

    case JSON_INTEGER:

        obj = QOBJECT(qint_from_int(strtoll(token_get_value(token), NULL, 10)));

        break;

    case JSON_FLOAT:

        /* FIXME dependent on locale */

        obj = QOBJECT(qfloat_from_double(strtod(token_get_value(token), NULL)));

        break;

    default:

        goto out;

    }

    return obj;

out:

    parser_context_restore(ctxt, saved_ctxt);

    return NULL;

}


void cpu_loop(CPUM68KState *env)

{

    CPUState *cs = CPU(m68k_env_get_cpu(env));

    int trapnr;

    unsigned int n;

    target_siginfo_t info;

    TaskState *ts = cs->opaque;

    for(;;) {

        cpu_exec_start(cs);

        trapnr = cpu_exec(cs);

        cpu_exec_end(cs);

        process_queued_cpu_work(cs);

        switch(trapnr) {

        case EXCP_ILLEGAL:

            {

                if (ts->sim_syscalls) {

                    uint16_t nr;

                    get_user_u16(nr, env->pc + 2);

                    env->pc += 4;

                    do_m68k_simcall(env, nr);

                } else {

                    goto do_sigill;

                }

            }

        case EXCP_HALT_INSN:

            /* Semihosing syscall.  */

            env->pc += 4;

            do_m68k_semihosting(env, env->dregs[0]);

        case EXCP_LINEA:

        case EXCP_LINEF:

        case EXCP_UNSUPPORTED:

        do_sigill:

            info.si_signo = TARGET_SIGILL;

            info.si_code = TARGET_ILL_ILLOPN;

        case EXCP_TRAP0:

            {

                abi_long ret;

                ts->sim_syscalls = 0;

                n = env->dregs[0];

                env->pc += 2;

                ret = do_syscall(env,

                                 n,

                                 env->dregs[1],

                                 env->dregs[2],

                                 env->dregs[3],

                                 env->dregs[4],

                                 env->dregs[5],

                                 env->aregs[0],

                                 0, 0);

                if (ret == -TARGET_ERESTARTSYS) {

                    env->pc -= 2;

                } else if (ret != -TARGET_QEMU_ESIGRETURN) {

                    env->dregs[0] = ret;

                }

            }

        case EXCP_INTERRUPT:

            /* just indicate that signals should be handled asap */

        case EXCP_ACCESS:

            {

                info.si_signo = TARGET_SIGSEGV;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = env->mmu.ar;

            }

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig(cs, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_code = TARGET_TRAP_BRKPT;

                  }

            }

        case EXCP_ATOMIC:

            cpu_exec_step_atomic(cs);

        default:

            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);

            abort();

        }

        process_pending_signals(env);

    }

}


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

{

    DriveInfo *dinfo;

    BlockDriverState *bs, *bs1;

    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;

    int ret;

    QEMUFile *f;

    int saved_vm_running;

    uint32_t vm_state_size;

#ifdef _WIN32

    struct _timeb tb;

#else

    struct timeval tv;

#endif

    const char *name = qdict_get_try_str(qdict, "name");

    bs = get_bs_snapshots();

    if (!bs) {

        monitor_printf(mon, "No block device can accept snapshots\n");

        return;

    }

    /* ??? Should this occur after vm_stop?  */

    qemu_aio_flush();

    saved_vm_running = vm_running;

    vm_stop(0);

    memset(sn, 0, sizeof(*sn));

    if (name) {

        ret = bdrv_snapshot_find(bs, old_sn, name);

        if (ret >= 0) {

            pstrcpy(sn->name, sizeof(sn->name), old_sn->name);

            pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);

        } else {

            pstrcpy(sn->name, sizeof(sn->name), name);

        }

    }

    /* fill auxiliary fields */

#ifdef _WIN32

    _ftime(&tb);

    sn->date_sec = tb.time;

    sn->date_nsec = tb.millitm * 1000000;

#else

    gettimeofday(&tv, NULL);

    sn->date_sec = tv.tv_sec;

    sn->date_nsec = tv.tv_usec * 1000;

#endif

    sn->vm_clock_nsec = qemu_get_clock(vm_clock);

    /* Delete old snapshots of the same name */

    if (name && del_existing_snapshots(mon, name) < 0) {

        goto the_end;

    }

    /* save the VM state */

    f = qemu_fopen_bdrv(bs, 1);

    if (!f) {

        monitor_printf(mon, "Could not open VM state file\n");

        goto the_end;

    }

    ret = qemu_savevm_state(mon, f);

    vm_state_size = qemu_ftell(f);

    qemu_fclose(f);

    if (ret < 0) {

        monitor_printf(mon, "Error %d while writing VM\n", ret);

        goto the_end;

    }

    /* create the snapshots */

    QTAILQ_FOREACH(dinfo, &drives, next) {

        bs1 = dinfo->bdrv;

        if (bdrv_has_snapshot(bs1)) {

            /* Write VM state size only to the image that contains the state */

            sn->vm_state_size = (bs == bs1 ? vm_state_size : 0);

            ret = bdrv_snapshot_create(bs1, sn);

            if (ret < 0) {

                monitor_printf(mon, "Error while creating snapshot on '%s'\n",

                               bdrv_get_device_name(bs1));

            }

        }

    }

 the_end:

    if (saved_vm_running)

        vm_start();

}


int paio_init(void)

{

    struct sigaction act;

    PosixAioState *s;

    int fds[2];

    int ret;

    if (posix_aio_state)

        return 0;

    s = qemu_malloc(sizeof(PosixAioState));

    sigfillset(&act.sa_mask);

    act.sa_flags = 0; /* do not restart syscalls to interrupt select() */

    act.sa_handler = aio_signal_handler;

    sigaction(SIGUSR2, &act, NULL);

    s->first_aio = NULL;

    if (pipe(fds) == -1) {

        fprintf(stderr, "failed to create pipe\n");

        return -1;

    }

    s->rfd = fds[0];

    s->wfd = fds[1];

    fcntl(s->rfd, F_SETFL, O_NONBLOCK);

    fcntl(s->wfd, F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush,

        posix_aio_process_queue, s);

    ret = pthread_attr_init(&attr);

    if (ret)

        die2(ret, "pthread_attr_init");

    ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    if (ret)

        die2(ret, "pthread_attr_setdetachstate");

    QTAILQ_INIT(&request_list);

    posix_aio_state = s;

    return 0;

}


static int set_dirty_tracking(void)

{

    BlkMigDevState *bmds;

    int ret;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        bmds->dirty_bitmap = bdrv_create_dirty_bitmap(bmds->bs, BLOCK_SIZE,

                                                      NULL);

        if (!bmds->dirty_bitmap) {

            ret = -errno;

            goto fail;

        }

    }

    return 0;

fail:

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {

        if (bmds->dirty_bitmap) {

            bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);

        }

    }

    return ret;

}


static int draw_slice(AVFilterLink *link, int y, int h, int slice_dir)

{

    SliceContext *slice = link->dst->priv;

    int y2, ret = 0;

    if (slice_dir == 1) {

        for (y2 = y; y2 + slice->h <= y + h; y2 += slice->h) {

            ret = ff_draw_slice(link->dst->outputs[0], y2, slice->h, slice_dir);

            if (ret < 0)

                return ret;

        }

        if (y2 < y + h)

            return ff_draw_slice(link->dst->outputs[0], y2, y + h - y2, slice_dir);

    } else if (slice_dir == -1) {

        for (y2 = y + h; y2 - slice->h >= y; y2 -= slice->h) {

            ret = ff_draw_slice(link->dst->outputs[0], y2 - slice->h, slice->h, slice_dir);

            if (ret < 0)

                return ret;

        }

        if (y2 > y)

            return ff_draw_slice(link->dst->outputs[0], y, y2 - y, slice_dir);

    }

    return 0;

}


void cpu_check_irqs(CPUSPARCState *env)
{
    CPUState *cs;
    if (env->pil_in && (env->interrupt_index == 0 ||
                        (env->interrupt_index & ~15) == TT_EXTINT)) {
        unsigned int i;
        for (i = 15; i > 0; i--) {
            if (env->pil_in & (1 << i)) {
                int old_interrupt = env->interrupt_index;
                env->interrupt_index = TT_EXTINT | i;
                if (old_interrupt != env->interrupt_index) {
                    cs = CPU(sparc_env_get_cpu(env));
                    trace_sun4m_cpu_interrupt(i);
                    cpu_interrupt(cs, CPU_INTERRUPT_HARD);
                }
                break;
            }
        }
    } else if (!env->pil_in && (env->interrupt_index & ~15) == TT_EXTINT) {
        cs = CPU(sparc_env_get_cpu(env));
        trace_sun4m_cpu_reset_interrupt(env->interrupt_index & 15);
        env->interrupt_index = 0;
        cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
    }
}