void *qemu_vmalloc(size_t size)

{

    /* FIXME: this is not exactly optimal solution since VirtualAlloc

       has 64Kb granularity, but at least it guarantees us that the

       memory is page aligned. */

    if (!size) {

        abort();

    }

    return oom_check(VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE));

}


static int real_seek(AVFormatContext *avf, int stream,

                     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)

{

    ConcatContext *cat = avf->priv_data;

    int ret, left, right;

    if (stream >= 0) {

        if (stream >= avf->nb_streams)

            return AVERROR(EINVAL);

        rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,

                         &min_ts, &ts, &max_ts);

    }

    left  = 0;

    right = cat->nb_files;

    while (right - left > 1) {

        int mid = (left + right) / 2;

        if (ts < cat->files[mid].start_time)

            right = mid;

        else

            left  = mid;

    }

    if ((ret = open_file(avf, left)) < 0)

        return ret;

    ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);

    if (ret < 0 && !(flags & AVSEEK_FLAG_BACKWARD) &&

        left < cat->nb_files - 1 &&

        cat->files[left + 1].start_time < max_ts) {

        if ((ret = open_file(avf, left + 1)) < 0)

            return ret;

        ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);

    }

    return ret;

}


static void FUNC(dequant)(int16_t *coeffs, int16_t log2_size)

{

    int shift  = 15 - BIT_DEPTH - log2_size;

    int x, y;

    int size = 1 << log2_size;

    if (shift > 0) {

        int offset = 1 << (shift - 1);

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

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

                *coeffs = (*coeffs + offset) >> shift;

                coeffs++;

            }

        }

    } else {

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

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

                *coeffs = *coeffs << -shift;

                coeffs++;

            }

        }

    }

}


vpc_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

              QEMUIOVector *qiov, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int ret;

    int64_t image_offset;

    int64_t n_bytes;

    int64_t bytes_done = 0;

    VHDFooter *footer = (VHDFooter *) s->footer_buf;

    QEMUIOVector local_qiov;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        return bdrv_co_preadv(bs->file, offset, bytes, qiov, 0);

    }

    qemu_co_mutex_lock(&s->lock);

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (bytes > 0) {

        image_offset = get_image_offset(bs, offset, false);

        n_bytes = MIN(bytes, s->block_size - (offset % s->block_size));

        if (image_offset == -1) {

            qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);

        } else {

            qemu_iovec_reset(&local_qiov);

            qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);

            ret = bdrv_co_preadv(bs->file, image_offset, n_bytes,

                                 &local_qiov, 0);

            if (ret < 0) {

                goto fail;

            }

        }

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    ret = 0;

fail:

    qemu_iovec_destroy(&local_qiov);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


long do_rt_sigreturn(CPUMIPSState *env)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr;

    sigset_t blocked;

    frame_addr = env->active_tc.gpr[29];

    trace_user_do_rt_sigreturn(env, frame_addr);

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    target_to_host_sigset(&blocked, &frame->rs_uc.tuc_sigmask);

    set_sigmask(&blocked);

    restore_sigcontext(env, &frame->rs_uc.tuc_mcontext);

    if (do_sigaltstack(frame_addr +

                       offsetof(struct target_rt_sigframe, rs_uc.tuc_stack),

                       0, get_sp_from_cpustate(env)) == -EFAULT)

        goto badframe;

    env->active_tc.PC = env->CP0_EPC;

    mips_set_hflags_isa_mode_from_pc(env);

    /* I am not sure this is right, but it seems to work

    * maybe a problem with nested signals ? */

    env->CP0_EPC = 0;

    return -TARGET_QEMU_ESIGRETURN;

badframe:

    force_sig(TARGET_SIGSEGV/*, current*/);

    return 0;

}


static CharDriverState *qemu_chr_open_socket(QemuOpts *opts)

{

    CharDriverState *chr = NULL;

    TCPCharDriver *s = NULL;

    int fd = -1;

    int is_listen;

    int is_waitconnect;

    int do_nodelay;

    int is_unix;

    int is_telnet;

    is_listen      = qemu_opt_get_bool(opts, "server", 0);

    is_waitconnect = qemu_opt_get_bool(opts, "wait", 1);

    is_telnet      = qemu_opt_get_bool(opts, "telnet", 0);

    do_nodelay     = !qemu_opt_get_bool(opts, "delay", 1);

    is_unix        = qemu_opt_get(opts, "path") != NULL;

    if (!is_listen)

        is_waitconnect = 0;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(TCPCharDriver));

    if (is_unix) {

        if (is_listen) {

            fd = unix_listen_opts(opts);

        } else {

            fd = unix_connect_opts(opts);

        }

    } else {

        if (is_listen) {

            fd = inet_listen_opts(opts, 0, NULL);

        } else {

            fd = inet_connect_opts(opts, true, NULL, NULL);

        }

    }

    if (fd < 0) {

        goto fail;

    }

    if (!is_waitconnect)

        socket_set_nonblock(fd);

    s->connected = 0;

    s->fd = -1;

    s->listen_fd = -1;

    s->msgfd = -1;

    s->is_unix = is_unix;

    s->do_nodelay = do_nodelay && !is_unix;

    chr->opaque = s;

    chr->chr_write = tcp_chr_write;

    chr->chr_close = tcp_chr_close;

    chr->get_msgfd = tcp_get_msgfd;

    chr->chr_add_client = tcp_chr_add_client;

    if (is_listen) {

        s->listen_fd = fd;

        qemu_set_fd_handler2(s->listen_fd, NULL, tcp_chr_accept, NULL, chr);

        if (is_telnet)

            s->do_telnetopt = 1;

    } else {

        s->connected = 1;

        s->fd = fd;

        socket_set_nodelay(fd);

        tcp_chr_connect(chr);

    }

    /* for "info chardev" monitor command */

    chr->filename = g_malloc(256);

    if (is_unix) {

        snprintf(chr->filename, 256, "unix:%s%s",

                 qemu_opt_get(opts, "path"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    } else if (is_telnet) {

        snprintf(chr->filename, 256, "telnet:%s:%s%s",

                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    } else {

        snprintf(chr->filename, 256, "tcp:%s:%s%s",

                 qemu_opt_get(opts, "host"), qemu_opt_get(opts, "port"),

                 qemu_opt_get_bool(opts, "server", 0) ? ",server" : "");

    }

    if (is_listen && is_waitconnect) {

        printf("QEMU waiting for connection on: %s\n",

               chr->filename);

        tcp_chr_accept(chr);

        socket_set_nonblock(s->listen_fd);

    }

    return chr;

 fail:

    if (fd >= 0)

        closesocket(fd);

    g_free(s);

    g_free(chr);

    return NULL;

}


void qtest_qmpv_discard_response(QTestState *s, const char *fmt, va_list ap)

{

    bool has_reply = false;

    int nesting = 0;

    /* Send QMP request */

    socket_sendf(s->qmp_fd, fmt, ap);

    /* Receive reply */

    while (!has_reply || nesting > 0) {

        ssize_t len;

        char c;

        len = read(s->qmp_fd, &c, 1);

        if (len == -1 && errno == EINTR) {

            continue;

        }

        if (len == -1 || len == 0) {

            fprintf(stderr, "Broken pipe\n");

            exit(1);

        }

        switch (c) {

        case '{':

            nesting++;

            has_reply = true;

            break;

        case '}':

            nesting--;

            break;

        }

    }

}


static av_noinline void FUNC(hl_decode_mb_444)(H264Context *h)

{

    const int mb_x    = h->mb_x;

    const int mb_y    = h->mb_y;

    const int mb_xy   = h->mb_xy;

    const int mb_type = h->cur_pic.f.mb_type[mb_xy];

    uint8_t *dest[3];

    int linesize;

    int i, j, p;

    int *block_offset = &h->block_offset[0];

    const int transform_bypass = !SIMPLE && (h->qscale == 0 && h->sps.transform_bypass);

    const int plane_count      = (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) ? 3 : 1;

    for (p = 0; p < plane_count; p++) {

        dest[p] = h->cur_pic.f.data[p] +

                  ((mb_x << PIXEL_SHIFT) + mb_y * h->linesize) * 16;

        h->vdsp.prefetch(dest[p] + (h->mb_x & 3) * 4 * h->linesize + (64 << PIXEL_SHIFT),

                         h->linesize, 4);

    }

    h->list_counts[mb_xy] = h->list_count;

    if (!SIMPLE && MB_FIELD) {

        linesize     = h->mb_linesize = h->mb_uvlinesize = h->linesize * 2;

        block_offset = &h->block_offset[48];

        if (mb_y & 1) // FIXME move out of this function?

            for (p = 0; p < 3; p++)

                dest[p] -= h->linesize * 15;

        if (FRAME_MBAFF) {

            int list;

            for (list = 0; list < h->list_count; list++) {

                if (!USES_LIST(mb_type, list))

                    continue;

                if (IS_16X16(mb_type)) {

                    int8_t *ref = &h->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);

                } else {

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

                        int ref = h->ref_cache[list][scan8[i]];

                        if (ref >= 0)

                            fill_rectangle(&h->ref_cache[list][scan8[i]], 2, 2,

                                           8, (16 + ref) ^ (h->mb_y & 1), 1);

                    }

                }

            }

        }

    } else {

        linesize = h->mb_linesize = h->mb_uvlinesize = h->linesize;

    }

    if (!SIMPLE && IS_INTRA_PCM(mb_type)) {

        if (PIXEL_SHIFT) {

            const int bit_depth = h->sps.bit_depth_luma;

            GetBitContext gb;

            init_get_bits(&gb, (uint8_t *)h->intra_pcm_ptr, 768 * bit_depth);

            for (p = 0; p < plane_count; p++)

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

                    uint16_t *tmp = (uint16_t *)(dest[p] + i * linesize);

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

                        tmp[j] = get_bits(&gb, bit_depth);

                }

        } else {

            for (p = 0; p < plane_count; p++)

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

                    memcpy(dest[p] + i * linesize,

                           (uint8_t *)h->intra_pcm_ptr + p * 256 + i * 16, 16);

        }

    } else {

        if (IS_INTRA(mb_type)) {

            if (h->deblocking_filter)

                xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,

                               linesize, 1, 1, SIMPLE, PIXEL_SHIFT);

            for (p = 0; p < plane_count; p++)

                hl_decode_mb_predict_luma(h, mb_type, 1, SIMPLE,

                                          transform_bypass, PIXEL_SHIFT,

                                          block_offset, linesize, dest[p], p);

            if (h->deblocking_filter)

                xchg_mb_border(h, dest[0], dest[1], dest[2], linesize,

                               linesize, 0, 1, SIMPLE, PIXEL_SHIFT);

        } else {

            FUNC(hl_motion_444)(h, dest[0], dest[1], dest[2],

                      h->me.qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                      h->me.qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                      h->h264dsp.weight_h264_pixels_tab,

                      h->h264dsp.biweight_h264_pixels_tab);

        }

        for (p = 0; p < plane_count; p++)

            hl_decode_mb_idct_luma(h, mb_type, 1, SIMPLE, transform_bypass,

                                   PIXEL_SHIFT, block_offset, linesize,

                                   dest[p], p);

        if (h->cbp || IS_INTRA(mb_type)) {

            h->dsp.clear_blocks(h->mb);

            h->dsp.clear_blocks(h->mb + (24 * 16 << PIXEL_SHIFT));

        }

    }

}


static void msvideo1_decode_8bit(Msvideo1Context *s)

{

    int block_ptr, pixel_ptr;

    int total_blocks;

    int pixel_x, pixel_y;  /* pixel width and height iterators */

    int block_x, block_y;  /* block width and height iterators */

    int blocks_wide, blocks_high;  /* width and height in 4x4 blocks */

    int block_inc;

    int row_dec;

    /* decoding parameters */

    int stream_ptr;

    unsigned char byte_a, byte_b;

    unsigned short flags;

    int skip_blocks;

    unsigned char colors[8];

    unsigned char *pixels = s->frame.data[0];

    unsigned char *prev_pixels = s->prev_frame.data[0];

    int stride = s->frame.linesize[0];

    stream_ptr = 0;

    skip_blocks = 0;

    blocks_wide = s->avctx->width / 4;

    blocks_high = s->avctx->height / 4;

    total_blocks = blocks_wide * blocks_high;

    block_inc = 4;

    row_dec = stride + 4;

    for (block_y = blocks_high; block_y > 0; block_y--) {

        block_ptr = ((block_y * 4) - 1) * stride;

        for (block_x = blocks_wide; block_x > 0; block_x--) {

            /* check if this block should be skipped */

            if (skip_blocks) {

                COPY_PREV_BLOCK();

                block_ptr += block_inc;

                skip_blocks--;

                total_blocks--;

                continue;

            }

            pixel_ptr = block_ptr;

            /* get the next two bytes in the encoded data stream */

            CHECK_STREAM_PTR(2);

            byte_a = s->buf[stream_ptr++];

            byte_b = s->buf[stream_ptr++];

            /* check if the decode is finished */

            if ((byte_a == 0) && (byte_b == 0) && (total_blocks == 0))

                return;

            else if ((byte_b & 0xFC) == 0x84) {

                /* skip code, but don't count the current block */

                skip_blocks = ((byte_b - 0x84) << 8) + byte_a - 1;

                COPY_PREV_BLOCK();

            } else if (byte_b < 0x80) {

                /* 2-color encoding */

                flags = (byte_b << 8) | byte_a;

                CHECK_STREAM_PTR(2);

                colors[0] = s->buf[stream_ptr++];

                colors[1] = s->buf[stream_ptr++];

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

                    for (pixel_x = 0; pixel_x < 4; pixel_x++, flags >>= 1)

                        pixels[pixel_ptr++] = colors[(flags & 0x1) ^ 1];

                    pixel_ptr -= row_dec;

                }

            } else if (byte_b >= 0x90) {

                /* 8-color encoding */

                flags = (byte_b << 8) | byte_a;

                CHECK_STREAM_PTR(8);

                memcpy(colors, &s->buf[stream_ptr], 8);

                stream_ptr += 8;

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

                    for (pixel_x = 0; pixel_x < 4; pixel_x++, flags >>= 1)

                        pixels[pixel_ptr++] =

                            colors[((pixel_y & 0x2) << 1) +

                                (pixel_x & 0x2) + ((flags & 0x1) ^ 1)];

                    pixel_ptr -= row_dec;

                }

            } else {

                /* 1-color encoding */

                colors[0] = byte_a;

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

                    for (pixel_x = 0; pixel_x < 4; pixel_x++)

                        pixels[pixel_ptr++] = colors[0];

                    pixel_ptr -= row_dec;

                }

            }

            block_ptr += block_inc;

            total_blocks--;

        }

    }

    /* make the palette available on the way out */

    if (s->avctx->pix_fmt == PIX_FMT_PAL8)

        memcpy(s->frame.data[1], s->palette, PALETTE_COUNT * 4);

}


static int lrc_read_header(AVFormatContext *s)

{

    LRCContext *lrc = s->priv_data;

    AVBPrint line;

    AVStream *st;

    st = avformat_new_stream(s, NULL);

    if(!st) {

        return AVERROR(ENOMEM);

    }

    avpriv_set_pts_info(st, 64, 1, 1000);

    lrc->ts_offset = 0;

    st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;

    st->codecpar->codec_id   = AV_CODEC_ID_TEXT;

    av_bprint_init(&line, 0, AV_BPRINT_SIZE_UNLIMITED);

    while(!avio_feof(s->pb)) {

        int64_t pos = read_line(&line, s->pb);

        int64_t header_offset = find_header(line.str);

        if(header_offset >= 0) {

            char *comma_offset = strchr(line.str, ':');

            if(comma_offset) {

                char *right_bracket_offset = strchr(line.str, ']');

                if(!right_bracket_offset) {

                    continue;

                }

                *right_bracket_offset = *comma_offset = '\0';

                if(strcmp(line.str + 1, "offset") ||

                   sscanf(comma_offset + 1, "%"SCNd64, &lrc->ts_offset) != 1) {

                    av_dict_set(&s->metadata, line.str + 1, comma_offset + 1, 0);

                }

                *comma_offset = ':';

                *right_bracket_offset = ']';

            }

        } else {

            AVPacket *sub;

            int64_t ts_start = AV_NOPTS_VALUE;

            int64_t ts_stroffset = 0;

            int64_t ts_stroffset_incr = 0;

            int64_t ts_strlength = count_ts(line.str);

            while((ts_stroffset_incr = read_ts(line.str + ts_stroffset,

                                               &ts_start)) != 0) {

                ts_stroffset += ts_stroffset_incr;

                sub = ff_subtitles_queue_insert(&lrc->q, line.str + ts_strlength,

                                                line.len - ts_strlength, 0);

                if(!sub) {

                    return AVERROR(ENOMEM);

                }

                sub->pos = pos;

                sub->pts = ts_start - lrc->ts_offset;

                sub->duration = -1;

            }

        }

    }

    ff_subtitles_queue_finalize(s, &lrc->q);

    ff_metadata_conv_ctx(s, NULL, ff_lrc_metadata_conv);

    return 0;

}


static int asf_write_header1(AVFormatContext *s, int64_t file_size,

                             int64_t data_chunk_size)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVDictionaryEntry *tags[5];

    int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;

    int has_title;

    int metadata_count;

    AVCodecParameters *par;

    int64_t header_offset, cur_pos, hpos;

    int bit_rate;

    int64_t duration;

    ff_metadata_conv(&s->metadata, ff_asf_metadata_conv, NULL);

    tags[0] = av_dict_get(s->metadata, "title", NULL, 0);

    tags[1] = av_dict_get(s->metadata, "author", NULL, 0);

    tags[2] = av_dict_get(s->metadata, "copyright", NULL, 0);

    tags[3] = av_dict_get(s->metadata, "comment", NULL, 0);

    tags[4] = av_dict_get(s->metadata, "rating", NULL, 0);

    duration       = asf->duration + PREROLL_TIME * 10000;

    has_title      = tags[0] || tags[1] || tags[2] || tags[3] || tags[4];

    metadata_count = av_dict_count(s->metadata);

    bit_rate = 0;

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

        par = s->streams[n]->codecpar;

        avpriv_set_pts_info(s->streams[n], 32, 1, 1000); /* 32 bit pts in ms */

        bit_rate += par->bit_rate;

    }

    if (asf->is_streamed) {

        put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */

    }

    put_guid(pb, &ff_asf_header);

    avio_wl64(pb, -1); /* header length, will be patched after */

    avio_wl32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 2); /* ??? */

    /* file header */

    header_offset = avio_tell(pb);

    hpos          = put_header(pb, &ff_asf_file_header);

    put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, file_size);

    file_time = 0;

    avio_wl64(pb, unix_to_file_time(file_time));

    avio_wl64(pb, asf->nb_packets); /* number of packets */

    avio_wl64(pb, duration); /* end time stamp (in 100ns units) */

    avio_wl64(pb, asf->duration); /* duration (in 100ns units) */

    avio_wl64(pb, PREROLL_TIME); /* start time stamp */

    avio_wl32(pb, (asf->is_streamed || !pb->seekable) ? 3 : 2);  /* ??? */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, bit_rate); /* Nominal data rate in bps */

    end_header(pb, hpos);

    /* unknown headers */

    hpos = put_header(pb, &ff_asf_head1_guid);

    put_guid(pb, &ff_asf_head2_guid);

    avio_wl32(pb, 6);

    avio_wl16(pb, 0);

    end_header(pb, hpos);

    /* title and other infos */

    if (has_title) {

        int len;

        uint8_t *buf;

        AVIOContext *dyn_buf;

        if (avio_open_dyn_buf(&dyn_buf) < 0)

            return AVERROR(ENOMEM);

        hpos = put_header(pb, &ff_asf_comment_header);

        for (n = 0; n < FF_ARRAY_ELEMS(tags); n++) {

            len = tags[n] ? avio_put_str16le(dyn_buf, tags[n]->value) : 0;

            avio_wl16(pb, len);

        }

        len = avio_close_dyn_buf(dyn_buf, &buf);

        avio_write(pb, buf, len);

        av_freep(&buf);

        end_header(pb, hpos);

    }

    if (metadata_count) {

        AVDictionaryEntry *tag = NULL;

        hpos = put_header(pb, &ff_asf_extended_content_header);

        avio_wl16(pb, metadata_count);

        while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {

            put_str16(pb, tag->key);

            avio_wl16(pb, 0);

            put_str16(pb, tag->value);

        }

        end_header(pb, hpos);

    }

    /* chapters using ASF markers */

    if (!asf->is_streamed && s->nb_chapters) {

        int ret;

        if (ret = asf_write_markers(s))

            return ret;

    }

    /* stream headers */

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

        int64_t es_pos;

        //        ASFStream *stream = &asf->streams[n];

        par                 = s->streams[n]->codecpar;

        asf->streams[n].num = n + 1;

        asf->streams[n].seq = 0;

        switch (par->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            wav_extra_size = 0;

            extra_size     = 18 + wav_extra_size;

            extra_size2    = 8;

            break;

        default:

        case AVMEDIA_TYPE_VIDEO:

            wav_extra_size = par->extradata_size;

            extra_size     = 0x33 + wav_extra_size;

            extra_size2    = 0;

            break;

        }

        hpos = put_header(pb, &ff_asf_stream_header);

        if (par->codec_type == AVMEDIA_TYPE_AUDIO) {

            put_guid(pb, &ff_asf_audio_stream);

            put_guid(pb, &ff_asf_audio_conceal_spread);

        } else {

            put_guid(pb, &ff_asf_video_stream);

            put_guid(pb, &ff_asf_video_conceal_none);

        }

        avio_wl64(pb, 0); /* ??? */

        es_pos = avio_tell(pb);

        avio_wl32(pb, extra_size); /* wav header len */

        avio_wl32(pb, extra_size2); /* additional data len */

        avio_wl16(pb, n + 1); /* stream number */

        avio_wl32(pb, 0); /* ??? */

        if (par->codec_type == AVMEDIA_TYPE_AUDIO) {

            /* WAVEFORMATEX header */

            int wavsize = ff_put_wav_header(s, pb, par);

            if (wavsize < 0)

                return -1;

            if (wavsize != extra_size) {

                cur_pos = avio_tell(pb);

                avio_seek(pb, es_pos, SEEK_SET);

                avio_wl32(pb, wavsize); /* wav header len */

                avio_seek(pb, cur_pos, SEEK_SET);

            }

            /* ERROR Correction */

            avio_w8(pb, 0x01);

            if (par->codec_id == AV_CODEC_ID_ADPCM_G726 || !par->block_align) {

                avio_wl16(pb, 0x0190);

                avio_wl16(pb, 0x0190);

            } else {

                avio_wl16(pb, par->block_align);

                avio_wl16(pb, par->block_align);

            }

            avio_wl16(pb, 0x01);

            avio_w8(pb, 0x00);

        } else {

            avio_wl32(pb, par->width);

            avio_wl32(pb, par->height);

            avio_w8(pb, 2); /* ??? */

            avio_wl16(pb, 40 + par->extradata_size); /* size */

            /* BITMAPINFOHEADER header */

            ff_put_bmp_header(pb, par, ff_codec_bmp_tags, 1);

        }

        end_header(pb, hpos);

    }

    /* media comments */

    hpos = put_header(pb, &ff_asf_codec_comment_header);

    put_guid(pb, &ff_asf_codec_comment1_header);

    avio_wl32(pb, s->nb_streams);

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

        const AVCodecDescriptor *codec_desc;

        const char *desc;

        par  = s->streams[n]->codecpar;

        codec_desc = avcodec_descriptor_get(par->codec_id);

        if (par->codec_type == AVMEDIA_TYPE_AUDIO)

            avio_wl16(pb, 2);

        else if (par->codec_type == AVMEDIA_TYPE_VIDEO)

            avio_wl16(pb, 1);

        else

            avio_wl16(pb, -1);

        if (par->codec_id == AV_CODEC_ID_WMAV2)

            desc = "Windows Media Audio V8";

        else

            desc = codec_desc ? codec_desc->name : NULL;

        if (desc) {

            AVIOContext *dyn_buf;

            uint8_t *buf;

            int len;

            if (avio_open_dyn_buf(&dyn_buf) < 0)

                return AVERROR(ENOMEM);

            avio_put_str16le(dyn_buf, desc);

            len = avio_close_dyn_buf(dyn_buf, &buf);

            avio_wl16(pb, len / 2); // "number of characters" = length in bytes / 2

            avio_write(pb, buf, len);

            av_freep(&buf);

        } else

            avio_wl16(pb, 0);

        avio_wl16(pb, 0); /* no parameters */

        /* id */

        if (par->codec_type == AVMEDIA_TYPE_AUDIO) {

            avio_wl16(pb, 2);

            avio_wl16(pb, par->codec_tag);

        } else {

            avio_wl16(pb, 4);

            avio_wl32(pb, par->codec_tag);

        }

        if (!par->codec_tag)

            return -1;

    }

    end_header(pb, hpos);

    /* patch the header size fields */

    cur_pos     = avio_tell(pb);

    header_size = cur_pos - header_offset;

    if (asf->is_streamed) {

        header_size += 8 + 30 + DATA_HEADER_SIZE;

        avio_seek(pb, header_offset - 10 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        avio_seek(pb, header_offset - 2 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        header_size -= 8 + 30 + DATA_HEADER_SIZE;

    }

    header_size += 24 + 6;

    avio_seek(pb, header_offset - 14, SEEK_SET);

    avio_wl64(pb, header_size);

    avio_seek(pb, cur_pos, SEEK_SET);

    /* movie chunk, followed by packets of packet_size */

    asf->data_offset = cur_pos;

    put_guid(pb, &ff_asf_data_header);

    avio_wl64(pb, data_chunk_size);

    put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, asf->nb_packets); /* nb packets */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 1); /* ??? */

    return 0;

}


void qemu_aio_wait(void)

{

    sigset_t set;

    int nb_sigs;

#if !defined(QEMU_IMG) && !defined(QEMU_NBD)

    if (qemu_bh_poll())

        return;

#endif

    sigemptyset(&set);

    sigaddset(&set, aio_sig_num);

    sigwait(&set, &nb_sigs);

    qemu_aio_poll();

}


static void config_error(Monitor *mon, const char *fmt, ...)

{

    va_list ap;

    va_start(ap, fmt);

    if (mon) {

        monitor_vprintf(mon, fmt, ap);

    } else {

        fprintf(stderr, "qemu: ");

        vfprintf(stderr, fmt, ap);

        exit(1);

    }

    va_end(ap);

}


static int coroutine_fn raw_co_writev(BlockDriverState *bs, int64_t sector_num,

                                      int nb_sectors, QEMUIOVector *qiov)

{

    BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);

    return bdrv_co_writev(bs->file, sector_num, nb_sectors, qiov);

}


void g_free(void *ptr)

{

    /* FIXME: We should unmark the reserved pages here.  However this gets

       complicated when one target page spans multiple host pages, so we

       don't bother.  */

    size_t *p;

    p = (size_t *)((char *)ptr - 16);

    munmap(p, *p);

}


static SCSIGenericReq *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun)

{

    SCSIRequest *req;

    req = scsi_req_alloc(sizeof(SCSIGenericReq), d, tag, lun);

    return DO_UPCAST(SCSIGenericReq, req, req);

}


static void test_reconnect(void)

{

    gchar *path = g_strdup_printf("/%s/vhost-user/reconnect/subprocess",

                                  qtest_get_arch());

    g_test_trap_subprocess(path, 0, 0);

    g_test_trap_assert_passed();

}


int64_t qdict_get_try_int(const QDict *qdict, const char *key,

                          int64_t def_value)

{

    QObject *obj;

    obj = qdict_get(qdict, key);

    if (!obj || qobject_type(obj) != QTYPE_QINT)

        return def_value;

    return qint_get_int(qobject_to_qint(obj));

}


static inline void RENAME(bgr24ToY)(uint8_t *dst, uint8_t *src, int width)

{

#ifdef HAVE_MMX

	asm volatile(

		"mov %2, %%"REG_a"		\n\t"

		"movq "MANGLE(bgr2YCoeff)", %%mm6		\n\t"

		"movq "MANGLE(w1111)", %%mm5		\n\t"

		"pxor %%mm7, %%mm7		\n\t"

		"lea (%%"REG_a", %%"REG_a", 2), %%"REG_b"\n\t"

		".balign 16			\n\t"

		"1:				\n\t"

		PREFETCH" 64(%0, %%"REG_b")	\n\t"

		"movd (%0, %%"REG_b"), %%mm0	\n\t"

		"movd 3(%0, %%"REG_b"), %%mm1	\n\t"

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

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

		"movd 6(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 9(%0, %%"REG_b"), %%mm3	\n\t"

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

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

		"pmaddwd %%mm6, %%mm0		\n\t"

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

		"pmaddwd %%mm6, %%mm2		\n\t"

		"pmaddwd %%mm6, %%mm3		\n\t"

#ifndef FAST_BGR2YV12

		"psrad $8, %%mm0		\n\t"

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

		"psrad $8, %%mm2		\n\t"

		"psrad $8, %%mm3		\n\t"

#endif

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

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

		"pmaddwd %%mm5, %%mm0		\n\t"

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

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

		"psraw $7, %%mm0		\n\t"

		"movd 12(%0, %%"REG_b"), %%mm4	\n\t"

		"movd 15(%0, %%"REG_b"), %%mm1	\n\t"

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

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

		"movd 18(%0, %%"REG_b"), %%mm2	\n\t"

		"movd 21(%0, %%"REG_b"), %%mm3	\n\t"

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

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

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

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

		"pmaddwd %%mm6, %%mm2		\n\t"

		"pmaddwd %%mm6, %%mm3		\n\t"

#ifndef FAST_BGR2YV12

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

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

		"psrad $8, %%mm2		\n\t"

		"psrad $8, %%mm3		\n\t"

#endif

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

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

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

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

		"add $24, %%"REG_b"		\n\t"

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

		"psraw $7, %%mm4		\n\t"

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

		"paddusb "MANGLE(bgr2YOffset)", %%mm0	\n\t"

		"movq %%mm0, (%1, %%"REG_a")	\n\t"

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

		" js 1b				\n\t"

		: : "r" (src+width*3), "r" (dst+width), "g" ((long)-width)

		: "%"REG_a, "%"REG_b

	);

#else

	int i;

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

	{

		int b= src[i*3+0];

		int g= src[i*3+1];

		int r= src[i*3+2];

		dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)) )>>RGB2YUV_SHIFT);

	}

#endif

}


void dsputil_init_armv4l(void)

{

//  ff_idct = j_rev_dct_ARM;

}


static void RENAME(resample_one)(DELEM *dst, const DELEM *src,

                                 int dst_size, int64_t index2, int64_t incr)

{

    int dst_index;

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

        dst[dst_index] = src[index2 >> 32];

        index2 += incr;

    }

}


static int qemu_gluster_create(const char *filename,

        QEMUOptionParameter *options, Error **errp)

{

    struct glfs *glfs;

    struct glfs_fd *fd;

    int ret = 0;

    int prealloc = 0;

    int64_t total_size = 0;

    GlusterConf *gconf = g_malloc0(sizeof(GlusterConf));

    glfs = qemu_gluster_init(gconf, filename, errp);

    if (!glfs) {

        ret = -EINVAL;

        goto out;

    }

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            total_size = options->value.n / BDRV_SECTOR_SIZE;

        } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {

            if (!options->value.s || !strcmp(options->value.s, "off")) {

                prealloc = 0;

            } else if (!strcmp(options->value.s, "full") &&

                    gluster_supports_zerofill()) {

                prealloc = 1;

            } else {

                error_setg(errp, "Invalid preallocation mode: '%s'"

                    " or GlusterFS doesn't support zerofill API",

                           options->value.s);

                ret = -EINVAL;

                goto out;

            }

        }

        options++;

    }

    fd = glfs_creat(glfs, gconf->image,

        O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR);

    if (!fd) {

        ret = -errno;

    } else {

        if (!glfs_ftruncate(fd, total_size * BDRV_SECTOR_SIZE)) {

            if (prealloc && qemu_gluster_zerofill(fd, 0,

                    total_size * BDRV_SECTOR_SIZE)) {

                ret = -errno;

            }

        } else {

            ret = -errno;

        }

        if (glfs_close(fd) != 0) {

            ret = -errno;

        }

    }

out:

    qemu_gluster_gconf_free(gconf);

    if (glfs) {

        glfs_fini(glfs);

    }

    return ret;

}


void OPPROTO op_subfme (void)

{

    T0 = ~T0 + xer_ca - 1;

    if (likely((uint32_t)T0 != (uint32_t)-1))

        xer_ca = 1;

    RETURN();

}


int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,

                                int count, BdrvRequestFlags flags)

{

    ssize_t ret;

    NBDClientSession *client = nbd_get_client_session(bs);

    NBDRequest request = {

        .type = NBD_CMD_WRITE_ZEROES,

        .from = offset,

        .len = count,

    };

    NBDReply reply;

    if (!(client->nbdflags & NBD_FLAG_SEND_WRITE_ZEROES)) {

        return -ENOTSUP;

    }

    if (flags & BDRV_REQ_FUA) {

        assert(client->nbdflags & NBD_FLAG_SEND_FUA);

        request.flags |= NBD_CMD_FLAG_FUA;

    }

    if (!(flags & BDRV_REQ_MAY_UNMAP)) {

        request.flags |= NBD_CMD_FLAG_NO_HOLE;

    }

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(bs, &request, NULL);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL);

    }

    nbd_coroutine_end(bs, &request);

    return -reply.error;

}


static void usbredir_control_packet(void *priv, uint32_t id,

    struct usb_redir_control_packet_header *control_packet,

    uint8_t *data, int data_len)

{

    USBRedirDevice *dev = priv;

    int len = control_packet->length;

    AsyncURB *aurb;

    DPRINTF("ctrl-in status %d len %d id %u\n", control_packet->status,

            len, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        free(data);

        return;

    }

    aurb->control_packet.status = control_packet->status;

    aurb->control_packet.length = control_packet->length;

    if (memcmp(&aurb->control_packet, control_packet,

               sizeof(*control_packet))) {

        ERROR("return control packet mismatch, please report this!\n");

        len = USB_RET_NAK;

    }

    if (aurb->packet) {

        len = usbredir_handle_status(dev, control_packet->status, len);

        if (len > 0) {

            usbredir_log_data(dev, "ctrl data in:", data, data_len);

            if (data_len <= sizeof(dev->dev.data_buf)) {

                memcpy(dev->dev.data_buf, data, data_len);

            } else {

                ERROR("ctrl buffer too small (%d > %zu)\n",

                      data_len, sizeof(dev->dev.data_buf));

                len = USB_RET_STALL;

            }

        }

        aurb->packet->len = len;

        usb_generic_async_ctrl_complete(&dev->dev, aurb->packet);

    }

    async_free(dev, aurb);

    free(data);

}


int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)

{

    if (avctx->internal->pkt) {

        frame->pkt_pts = avctx->internal->pkt->pts;

        av_frame_set_pkt_pos     (frame, avctx->internal->pkt->pos);

        av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);

        av_frame_set_pkt_size    (frame, avctx->internal->pkt->size);

    } else {

        frame->pkt_pts = AV_NOPTS_VALUE;

        av_frame_set_pkt_pos     (frame, -1);

        av_frame_set_pkt_duration(frame, 0);

        av_frame_set_pkt_size    (frame, -1);

    }

    frame->reordered_opaque = avctx->reordered_opaque;

    switch (avctx->codec->type) {

    case AVMEDIA_TYPE_VIDEO:

        if (frame->format < 0)

            frame->format              = avctx->pix_fmt;

        if (!frame->sample_aspect_ratio.num)

            frame->sample_aspect_ratio = avctx->sample_aspect_ratio;

        if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)

            av_frame_set_colorspace(frame, avctx->colorspace);

        if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)

            av_frame_set_color_range(frame, avctx->color_range);

        break;

    case AVMEDIA_TYPE_AUDIO:

        if (!frame->sample_rate)

            frame->sample_rate    = avctx->sample_rate;

        if (frame->format < 0)

            frame->format         = avctx->sample_fmt;

        if (!frame->channel_layout) {

            if (avctx->channel_layout) {

                 if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=

                     avctx->channels) {

                     av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "

                            "configuration.\n");

                     return AVERROR(EINVAL);

                 }

                frame->channel_layout = avctx->channel_layout;

            } else {

                if (avctx->channels > FF_SANE_NB_CHANNELS) {

                    av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",

                           avctx->channels);

                    return AVERROR(ENOSYS);

                }

            }

        }

        av_frame_set_channels(frame, avctx->channels);

        break;

    }

    return 0;

}


AVFilterContext *avfilter_open(AVFilter *filter, char *inst_name)

{

    AVFilterContext *ret = av_malloc(sizeof(AVFilterContext));

    ret->av_class = av_mallocz(sizeof(AVClass));

    ret->av_class->item_name = filter_name;

    ret->filter   = filter;

    ret->name     = inst_name ? av_strdup(inst_name) : NULL;

    ret->priv     = av_mallocz(filter->priv_size);

    ret->input_count  = pad_count(filter->inputs);

    ret->input_pads   = av_malloc(sizeof(AVFilterPad) * ret->input_count);

    memcpy(ret->input_pads, filter->inputs, sizeof(AVFilterPad)*ret->input_count);

    ret->inputs       = av_mallocz(sizeof(AVFilterLink*) * ret->input_count);

    ret->output_count = pad_count(filter->outputs);

    ret->output_pads  = av_malloc(sizeof(AVFilterPad) * ret->output_count);

    memcpy(ret->output_pads, filter->outputs, sizeof(AVFilterPad)*ret->output_count);

    ret->outputs      = av_mallocz(sizeof(AVFilterLink*) * ret->output_count);

    return ret;

}


static int vnc_zlib_stop(VncState *vs)

{

    z_streamp zstream = &vs->zlib.stream;

    int previous_out;

    // switch back to normal output/zlib buffers

    vs->zlib.zlib = vs->output;

    vs->output = vs->zlib.tmp;

    // compress the zlib buffer

    // initialize the stream

    // XXX need one stream per session

    if (zstream->opaque != vs) {

        int err;

        VNC_DEBUG("VNC: initializing zlib stream\n");

        VNC_DEBUG("VNC: opaque = %p | vs = %p\n", zstream->opaque, vs);

        zstream->zalloc = vnc_zlib_zalloc;

        zstream->zfree = vnc_zlib_zfree;

        err = deflateInit2(zstream, vs->tight.compression, Z_DEFLATED, MAX_WBITS,

                           MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);

        if (err != Z_OK) {

            fprintf(stderr, "VNC: error initializing zlib\n");

            return -1;

        }

        vs->zlib.level = vs->tight.compression;

        zstream->opaque = vs;

    }

    if (vs->tight.compression != vs->zlib.level) {

        if (deflateParams(zstream, vs->tight.compression,

                          Z_DEFAULT_STRATEGY) != Z_OK) {

            return -1;

        }

        vs->zlib.level = vs->tight.compression;

    }

    // reserve memory in output buffer

    buffer_reserve(&vs->output, vs->zlib.zlib.offset + 64);

    // set pointers

    zstream->next_in = vs->zlib.zlib.buffer;

    zstream->avail_in = vs->zlib.zlib.offset;

    zstream->next_out = vs->output.buffer + vs->output.offset;

    zstream->avail_out = vs->output.capacity - vs->output.offset;

    zstream->data_type = Z_BINARY;

    previous_out = zstream->total_out;

    // start encoding

    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {

        fprintf(stderr, "VNC: error during zlib compression\n");

        return -1;

    }

    vs->output.offset = vs->output.capacity - zstream->avail_out;

    return zstream->total_out - previous_out;

}


void OPPROTO op_divw_AX_T0(void)

{

    unsigned int num, den, q, r;

    num = (EAX & 0xffff) | ((EDX & 0xffff) << 16);

    den = (T0 & 0xffff);

    if (den == 0) {

        raise_exception(EXCP00_DIVZ);

    }

    q = (num / den) & 0xffff;

    r = (num % den) & 0xffff;

    EAX = (EAX & ~0xffff) | q;

    EDX = (EDX & ~0xffff) | r;

}


static void fic_draw_cursor(AVCodecContext *avctx, int cur_x, int cur_y)

{

    FICContext *ctx = avctx->priv_data;

    uint8_t *ptr    = ctx->cursor_buf;

    uint8_t *dstptr[3];

    uint8_t planes[4][1024];

    uint8_t chroma[3][256];

    int i, j, p;

    /* Convert to YUVA444. */

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

        planes[0][i] = av_clip_uint8((( 25 * ptr[0] + 129 * ptr[1] +  66 * ptr[2]) / 255) + 16);

        planes[1][i] = av_clip_uint8(((-38 * ptr[0] + 112 * ptr[1] + -74 * ptr[2]) / 255) + 128);

        planes[2][i] = av_clip_uint8(((-18 * ptr[0] + 112 * ptr[1] + -94 * ptr[2]) / 255) + 128);

        planes[3][i] = ptr[3];

        ptr += 4;

    }

    /* Subsample chroma. */

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

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

            for (p = 0; p < 3; p++)

                chroma[p][16 * (i / 2) + j / 2] = (planes[p + 1][32 *  i      + j    ] +

                                                   planes[p + 1][32 *  i      + j + 1] +

                                                   planes[p + 1][32 * (i + 1) + j    ] +

                                                   planes[p + 1][32 * (i + 1) + j + 1]) / 4;

    /* Seek to x/y pos of cursor. */

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

        dstptr[i] = ctx->final_frame->data[i]                        +

                    (ctx->final_frame->linesize[i] * (cur_y >> !!i)) +

                    (cur_x >> !!i) + !!i;

    /* Copy. */

    for (i = 0; i < FFMIN(32, avctx->height - cur_y) - 1; i += 2) {

        int lsize = FFMIN(32, avctx->width - cur_x);

        int csize = lsize / 2;

        fic_alpha_blend(dstptr[0],

                        planes[0] + i * 32, lsize, planes[3] + i * 32);

        fic_alpha_blend(dstptr[0] + ctx->final_frame->linesize[0],

                        planes[0] + (i + 1) * 32, lsize, planes[3] + (i + 1) * 32);

        fic_alpha_blend(dstptr[1],

                        chroma[0] + (i / 2) * 16, csize, chroma[2] + (i / 2) * 16);

        fic_alpha_blend(dstptr[2],

                        chroma[1] + (i / 2) * 16, csize, chroma[2] + (i / 2) * 16);

        dstptr[0] += ctx->final_frame->linesize[0] * 2;

        dstptr[1] += ctx->final_frame->linesize[1];

        dstptr[2] += ctx->final_frame->linesize[2];

    }

}


static int decode_ref_pic_list_reordering(H264Context *h){

    MpegEncContext * const s = &h->s;

    int list, index;

    print_short_term(h);

    print_long_term(h);

    if(h->slice_type==I_TYPE || h->slice_type==SI_TYPE) return 0; //FIXME move before func

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

        memcpy(h->ref_list[list], h->default_ref_list[list], sizeof(Picture)*h->ref_count[list]);

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

            int pred= h->curr_pic_num;

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

                int reordering_of_pic_nums_idc= get_ue_golomb(&s->gb);

                int pic_id;

                int i;

                Picture *ref = NULL;

                if(reordering_of_pic_nums_idc==3)

                    break;

                if(index >= h->ref_count[list]){

                    av_log(h->s.avctx, AV_LOG_ERROR, "reference count overflow\n");

                    return -1;

                }

                if(reordering_of_pic_nums_idc<3){

                    if(reordering_of_pic_nums_idc<2){

                        const int abs_diff_pic_num= get_ue_golomb(&s->gb) + 1;

                        if(abs_diff_pic_num >= h->max_pic_num){

                            av_log(h->s.avctx, AV_LOG_ERROR, "abs_diff_pic_num overflow\n");

                            return -1;

                        }

                        if(reordering_of_pic_nums_idc == 0) pred-= abs_diff_pic_num;

                        else                                pred+= abs_diff_pic_num;

                        pred &= h->max_pic_num - 1;

                        for(i= h->short_ref_count-1; i>=0; i--){

                            ref = h->short_ref[i];

                            assert(ref->reference == 3);

                            assert(!ref->long_ref);

                            if(ref->data[0] != NULL && ref->frame_num == pred && ref->long_ref == 0) // ignore non existing pictures by testing data[0] pointer

                                break;

                        }

                        if(i>=0)

                            ref->pic_id= ref->frame_num;

                    }else{

                        pic_id= get_ue_golomb(&s->gb); //long_term_pic_idx

                        ref = h->long_ref[pic_id];

                        if(ref){

                            ref->pic_id= pic_id;

                            assert(ref->reference == 3);

                            assert(ref->long_ref);

                            i=0;

                        }else{

                            i=-1;

                        }

                    }

                    if (i < 0) {

                        av_log(h->s.avctx, AV_LOG_ERROR, "reference picture missing during reorder\n");

                        memset(&h->ref_list[list][index], 0, sizeof(Picture)); //FIXME

                    } else {

                        for(i=index; i+1<h->ref_count[list]; i++){

                            if(ref->long_ref == h->ref_list[list][i].long_ref && ref->pic_id == h->ref_list[list][i].pic_id)

                                break;

                        }

                        for(; i > index; i--){

                            h->ref_list[list][i]= h->ref_list[list][i-1];

                        }

                        h->ref_list[list][index]= *ref;

                    }

                }else{

                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal reordering_of_pic_nums_idc\n");

                    return -1;

                }

            }

        }

        if(h->slice_type!=B_TYPE) break;

    }

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

        for(index= 0; index < h->ref_count[list]; index++){

            if(!h->ref_list[list][index].data[0])

                h->ref_list[list][index]= s->current_picture;

        }

        if(h->slice_type!=B_TYPE) break;

    }

    if(h->slice_type==B_TYPE && !h->direct_spatial_mv_pred)

        direct_dist_scale_factor(h);

    direct_ref_list_init(h);

    return 0;

}


TCGOp *tcg_op_insert_before(TCGContext *s, TCGOp *old_op,

                            TCGOpcode opc, int nargs)

{

    int oi = s->gen_next_op_idx;

    int prev = old_op->prev;

    int next = old_op - s->gen_op_buf;

    TCGOp *new_op;

    tcg_debug_assert(oi < OPC_BUF_SIZE);

    s->gen_next_op_idx = oi + 1;

    new_op = &s->gen_op_buf[oi];

    *new_op = (TCGOp){

        .opc = opc,

        .prev = prev,

        .next = next

    };

    s->gen_op_buf[prev].next = oi;

    old_op->prev = oi;

    return new_op;

}


void FUNCC(ff_h264_idct8_dc_add)(uint8_t *_dst, DCTELEM *block, int stride){

    int i, j;

    int dc = (((dctcoef*)block)[0] + 32) >> 6;

    INIT_CLIP

    pixel *dst = (pixel*)_dst;

    stride /= sizeof(pixel);

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

    {

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

            dst[i] = CLIP( dst[i] + dc );

        dst += stride;

    }

}


static int svq3_decode_frame(AVCodecContext *avctx, void *data,

                             int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    SVQ3Context *svq3  = avctx->priv_data;

    H264Context *h     = &svq3->h;

    MpegEncContext *s  = &h->s;

    int buf_size       = avpkt->size;

    int m, mb_type;

    /* special case for last picture */

    if (buf_size == 0) {

        if (s->next_picture_ptr && !s->low_delay) {

            *(AVFrame *) data   = s->next_picture.f;

            s->next_picture_ptr = NULL;

            *got_frame          = 1;

        }

        return 0;

    }

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

    s->mb_x = s->mb_y = h->mb_xy = 0;

    if (svq3_decode_slice_header(avctx))

        return -1;

    s->pict_type      = h->slice_type;

    s->picture_number = h->slice_num;

    if (avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(h->s.avctx, AV_LOG_DEBUG,

               "%c hpel:%d, tpel:%d aqp:%d qp:%d, slice_num:%02X\n",

               av_get_picture_type_char(s->pict_type),

               svq3->halfpel_flag, svq3->thirdpel_flag,

               s->adaptive_quant, s->qscale, h->slice_num);

    /* for skipping the frame */

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = (s->pict_type == AV_PICTURE_TYPE_I);

    /* Skip B-frames if we do not have reference frames. */

    if (s->last_picture_ptr == NULL && s->pict_type == AV_PICTURE_TYPE_B)

        return 0;

    if (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B ||

        avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return 0;

    if (s->next_p_frame_damaged) {

        if (s->pict_type == AV_PICTURE_TYPE_B)

            return 0;

        else

            s->next_p_frame_damaged = 0;

    }

    if (ff_h264_frame_start(h) < 0)

        return -1;

    if (s->pict_type == AV_PICTURE_TYPE_B) {

        h->frame_num_offset = h->slice_num - h->prev_frame_num;

        if (h->frame_num_offset < 0)

            h->frame_num_offset += 256;

        if (h->frame_num_offset == 0 ||

            h->frame_num_offset >= h->prev_frame_num_offset) {

            av_log(h->s.avctx, AV_LOG_ERROR, "error in B-frame picture id\n");

            return -1;

        }

    } else {

        h->prev_frame_num        = h->frame_num;

        h->frame_num             = h->slice_num;

        h->prev_frame_num_offset = h->frame_num - h->prev_frame_num;

        if (h->prev_frame_num_offset < 0)

            h->prev_frame_num_offset += 256;

    }

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

        int i;

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

            int j;

            for (j = -1; j < 4; j++)

                h->ref_cache[m][scan8[0] + 8 * i + j] = 1;

            if (i < 3)

                h->ref_cache[m][scan8[0] + 8 * i + j] = PART_NOT_AVAILABLE;

        }

    }

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

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

            h->mb_xy = s->mb_x + s->mb_y * s->mb_stride;

            if ((get_bits_count(&s->gb) + 7) >= s->gb.size_in_bits &&

                ((get_bits_count(&s->gb) & 7) == 0 ||

                 show_bits(&s->gb, -get_bits_count(&s->gb) & 7) == 0)) {

                skip_bits(&s->gb, svq3->next_slice_index - get_bits_count(&s->gb));

                s->gb.size_in_bits = 8 * buf_size;

                if (svq3_decode_slice_header(avctx))

                    return -1;

                /* TODO: support s->mb_skip_run */

            }

            mb_type = svq3_get_ue_golomb(&s->gb);

            if (s->pict_type == AV_PICTURE_TYPE_I)

                mb_type += 8;

            else if (s->pict_type == AV_PICTURE_TYPE_B && mb_type >= 4)

                mb_type += 4;

            if ((unsigned)mb_type > 33 || svq3_decode_mb(svq3, mb_type)) {

                av_log(h->s.avctx, AV_LOG_ERROR,

                       "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            if (mb_type != 0)

                ff_h264_hl_decode_mb(h);

            if (s->pict_type != AV_PICTURE_TYPE_B && !s->low_delay)

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

                    (s->pict_type == AV_PICTURE_TYPE_P && mb_type < 8) ? (mb_type - 1) : -1;

        }

        ff_draw_horiz_band(s, 16 * s->mb_y, 16);

    }

    ff_MPV_frame_end(s);

    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)

        *(AVFrame *)data = s->current_picture.f;

    else

        *(AVFrame *)data = s->last_picture.f;

    /* Do not output the last pic after seeking. */

    if (s->last_picture_ptr || s->low_delay)

        *got_frame = 1;

    return buf_size;

}


static void mpeg4_decode_sprite_trajectory(MpegEncContext * s, GetBitContext *gb)

{

    int i;

    int a= 2<<s->sprite_warping_accuracy;

    int rho= 3-s->sprite_warping_accuracy;

    int r=16/a;

    const int vop_ref[4][2]= {{0,0}, {s->width,0}, {0, s->height}, {s->width, s->height}}; // only true for rectangle shapes

    int d[4][2]={{0,0}, {0,0}, {0,0}, {0,0}};

    int sprite_ref[4][2];

    int virtual_ref[2][2];

    int w2, h2, w3, h3;

    int alpha=0, beta=0;

    int w= s->width;

    int h= s->height;

    int min_ab;

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

        int length;

        int x=0, y=0;

        length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);

        if(length){

            x= get_xbits(gb, length);

        }

        if(!(s->divx_version==500 && s->divx_build==413)) skip_bits1(gb); /* marker bit */

        length= get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);

        if(length){

            y=get_xbits(gb, length);

        }

        skip_bits1(gb); /* marker bit */

        s->sprite_traj[i][0]= d[i][0]= x;

        s->sprite_traj[i][1]= d[i][1]= y;

    }

    for(; i<4; i++)

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

    while((1<<alpha)<w) alpha++;

    while((1<<beta )<h) beta++; // there seems to be a typo in the mpeg4 std for the definition of w' and h'

    w2= 1<<alpha;

    h2= 1<<beta;

// Note, the 4th point isn't used for GMC

    if(s->divx_version==500 && s->divx_build==413){

        sprite_ref[0][0]= a*vop_ref[0][0] + d[0][0];

        sprite_ref[0][1]= a*vop_ref[0][1] + d[0][1];

        sprite_ref[1][0]= a*vop_ref[1][0] + d[0][0] + d[1][0];

        sprite_ref[1][1]= a*vop_ref[1][1] + d[0][1] + d[1][1];

        sprite_ref[2][0]= a*vop_ref[2][0] + d[0][0] + d[2][0];

        sprite_ref[2][1]= a*vop_ref[2][1] + d[0][1] + d[2][1];

    } else {

        sprite_ref[0][0]= (a>>1)*(2*vop_ref[0][0] + d[0][0]);

        sprite_ref[0][1]= (a>>1)*(2*vop_ref[0][1] + d[0][1]);

        sprite_ref[1][0]= (a>>1)*(2*vop_ref[1][0] + d[0][0] + d[1][0]);

        sprite_ref[1][1]= (a>>1)*(2*vop_ref[1][1] + d[0][1] + d[1][1]);

        sprite_ref[2][0]= (a>>1)*(2*vop_ref[2][0] + d[0][0] + d[2][0]);

        sprite_ref[2][1]= (a>>1)*(2*vop_ref[2][1] + d[0][1] + d[2][1]);

    }

/*    sprite_ref[3][0]= (a>>1)*(2*vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);

    sprite_ref[3][1]= (a>>1)*(2*vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */

// this is mostly identical to the mpeg4 std (and is totally unreadable because of that ...)

// perhaps it should be reordered to be more readable ...

// the idea behind this virtual_ref mess is to be able to use shifts later per pixel instead of divides

// so the distance between points is converted from w&h based to w2&h2 based which are of the 2^x form

    virtual_ref[0][0]= 16*(vop_ref[0][0] + w2)

        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + w2*(r*sprite_ref[1][0] - 16*vop_ref[1][0])),w);

    virtual_ref[0][1]= 16*vop_ref[0][1]

        + ROUNDED_DIV(((w - w2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + w2*(r*sprite_ref[1][1] - 16*vop_ref[1][1])),w);

    virtual_ref[1][0]= 16*vop_ref[0][0]

        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][0] - 16*vop_ref[0][0]) + h2*(r*sprite_ref[2][0] - 16*vop_ref[2][0])),h);

    virtual_ref[1][1]= 16*(vop_ref[0][1] + h2)

        + ROUNDED_DIV(((h - h2)*(r*sprite_ref[0][1] - 16*vop_ref[0][1]) + h2*(r*sprite_ref[2][1] - 16*vop_ref[2][1])),h);

    switch(s->num_sprite_warping_points)

    {

        case 0:

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

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

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

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

            s->sprite_delta[0][0]= a;

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

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

            s->sprite_delta[1][1]= a;

            s->sprite_shift[0]= 0;

            s->sprite_shift[1]= 0;

            break;

        case 1: //GMC only

            s->sprite_offset[0][0]= sprite_ref[0][0] - a*vop_ref[0][0];

            s->sprite_offset[0][1]= sprite_ref[0][1] - a*vop_ref[0][1];

            s->sprite_offset[1][0]= ((sprite_ref[0][0]>>1)|(sprite_ref[0][0]&1)) - a*(vop_ref[0][0]/2);

            s->sprite_offset[1][1]= ((sprite_ref[0][1]>>1)|(sprite_ref[0][1]&1)) - a*(vop_ref[0][1]/2);

            s->sprite_delta[0][0]= a;

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

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

            s->sprite_delta[1][1]= a;

            s->sprite_shift[0]= 0;

            s->sprite_shift[1]= 0;

            break;

        case 2:

            s->sprite_offset[0][0]= (sprite_ref[0][0]<<(alpha+rho))

                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][0])

                                                  + ( r*sprite_ref[0][1] - virtual_ref[0][1])*(-vop_ref[0][1])

                                                  + (1<<(alpha+rho-1));

            s->sprite_offset[0][1]= (sprite_ref[0][1]<<(alpha+rho))

                                                  + (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-vop_ref[0][0])

                                                  + (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-vop_ref[0][1])

                                                  + (1<<(alpha+rho-1));

            s->sprite_offset[1][0]= ( (-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][0] + 1)

                                     +( r*sprite_ref[0][1] - virtual_ref[0][1])*(-2*vop_ref[0][1] + 1)

                                     +2*w2*r*sprite_ref[0][0]

                                     - 16*w2

                                     + (1<<(alpha+rho+1)));

            s->sprite_offset[1][1]= ( (-r*sprite_ref[0][1] + virtual_ref[0][1])*(-2*vop_ref[0][0] + 1)

                                     +(-r*sprite_ref[0][0] + virtual_ref[0][0])*(-2*vop_ref[0][1] + 1)

                                     +2*w2*r*sprite_ref[0][1]

                                     - 16*w2

                                     + (1<<(alpha+rho+1)));

            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);

            s->sprite_delta[0][1]=   (+r*sprite_ref[0][1] - virtual_ref[0][1]);

            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1]);

            s->sprite_delta[1][1]=   (-r*sprite_ref[0][0] + virtual_ref[0][0]);

            s->sprite_shift[0]= alpha+rho;

            s->sprite_shift[1]= alpha+rho+2;

            break;

        case 3:

            min_ab= FFMIN(alpha, beta);

            w3= w2>>min_ab;

            h3= h2>>min_ab;

            s->sprite_offset[0][0]=  (sprite_ref[0][0]<<(alpha+beta+rho-min_ab))

                                   + (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-vop_ref[0][0])

                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-vop_ref[0][1])

                                   + (1<<(alpha+beta+rho-min_ab-1));

            s->sprite_offset[0][1]=  (sprite_ref[0][1]<<(alpha+beta+rho-min_ab))

                                   + (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-vop_ref[0][0])

                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-vop_ref[0][1])

                                   + (1<<(alpha+beta+rho-min_ab-1));

            s->sprite_offset[1][0]=  (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3*(-2*vop_ref[0][0] + 1)

                                   + (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3*(-2*vop_ref[0][1] + 1)

                                   + 2*w2*h3*r*sprite_ref[0][0]

                                   - 16*w2*h3

                                   + (1<<(alpha+beta+rho-min_ab+1));

            s->sprite_offset[1][1]=  (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3*(-2*vop_ref[0][0] + 1)

                                   + (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3*(-2*vop_ref[0][1] + 1)

                                   + 2*w2*h3*r*sprite_ref[0][1]

                                   - 16*w2*h3

                                   + (1<<(alpha+beta+rho-min_ab+1));

            s->sprite_delta[0][0]=   (-r*sprite_ref[0][0] + virtual_ref[0][0])*h3;

            s->sprite_delta[0][1]=   (-r*sprite_ref[0][0] + virtual_ref[1][0])*w3;

            s->sprite_delta[1][0]=   (-r*sprite_ref[0][1] + virtual_ref[0][1])*h3;

            s->sprite_delta[1][1]=   (-r*sprite_ref[0][1] + virtual_ref[1][1])*w3;

            s->sprite_shift[0]= alpha + beta + rho - min_ab;

            s->sprite_shift[1]= alpha + beta + rho - min_ab + 2;

            break;

    }

    /* try to simplify the situation */

    if(   s->sprite_delta[0][0] == a<<s->sprite_shift[0]

       && s->sprite_delta[0][1] == 0

       && s->sprite_delta[1][0] == 0

       && s->sprite_delta[1][1] == a<<s->sprite_shift[0])

    {

        s->sprite_offset[0][0]>>=s->sprite_shift[0];

        s->sprite_offset[0][1]>>=s->sprite_shift[0];

        s->sprite_offset[1][0]>>=s->sprite_shift[1];

        s->sprite_offset[1][1]>>=s->sprite_shift[1];

        s->sprite_delta[0][0]= a;

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

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

        s->sprite_delta[1][1]= a;

        s->sprite_shift[0]= 0;

        s->sprite_shift[1]= 0;

        s->real_sprite_warping_points=1;

    }

    else{

        int shift_y= 16 - s->sprite_shift[0];

        int shift_c= 16 - s->sprite_shift[1];

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

            s->sprite_offset[0][i]<<= shift_y;

            s->sprite_offset[1][i]<<= shift_c;

            s->sprite_delta[0][i]<<= shift_y;

            s->sprite_delta[1][i]<<= shift_y;

            s->sprite_shift[i]= 16;

        }

        s->real_sprite_warping_points= s->num_sprite_warping_points;

    }

}


static int parse(AVCodecParserContext *ctx,

                 AVCodecContext *avctx,

                 const uint8_t **out_data, int *out_size,

                 const uint8_t *data, int size)

{

    VP9ParseContext *s = ctx->priv_data;

    int full_size = size;

    int marker;

    if (size <= 0) {

        *out_size = 0;

        *out_data = data;

        return 0;

    }

    if (s->n_frames > 0) {

        *out_data = data;

        *out_size = s->size[--s->n_frames];

        parse_frame(ctx, *out_data, *out_size);

        return s->n_frames > 0 ? *out_size : size /* i.e. include idx tail */;

    }

    marker = data[size - 1];

    if ((marker & 0xe0) == 0xc0) {

        int nbytes = 1 + ((marker >> 3) & 0x3);

        int n_frames = 1 + (marker & 0x7), idx_sz = 2 + n_frames * nbytes;

        if (size >= idx_sz && data[size - idx_sz] == marker) {

            const uint8_t *idx = data + size + 1 - idx_sz;

            int first = 1;

            switch (nbytes) {

#define case_n(a, rd) \

            case a: \

                while (n_frames--) { \

                    unsigned sz = rd; \

                    idx += a; \

                    if (sz > size) { \

                        s->n_frames = 0; \

                        *out_size = size; \

                        *out_data = data; \

                        av_log(avctx, AV_LOG_ERROR, \

                               "Superframe packet size too big: %u > %d\n", \

                               sz, size); \

                        return full_size; \

                    } \

                    if (first) { \

                        first = 0; \

                        *out_data = data; \

                        *out_size = sz; \

                        s->n_frames = n_frames; \

                    } else { \

                        s->size[n_frames] = sz; \

                    } \

                    data += sz; \

                    size -= sz; \

                } \

                parse_frame(ctx, *out_data, *out_size); \

                return *out_size

                case_n(1, *idx);

                case_n(2, AV_RL16(idx));

                case_n(3, AV_RL24(idx));

                case_n(4, AV_RL32(idx));

            }

        }

    }

    *out_data = data;

    *out_size = size;

    parse_frame(ctx, data, size);

    return size;

}


void axisdev88_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    CRISCPU *cpu;

    CPUCRISState *env;

    DeviceState *dev;

    SysBusDevice *s;

    DriveInfo *nand;

    qemu_irq irq[30], nmi[2];

    void *etraxfs_dmac;

    struct etraxfs_dma_client *dma_eth;

    int i;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    MemoryRegion *phys_intmem = g_new(MemoryRegion, 1);

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "crisv32";

    }

    cpu = cpu_cris_init(cpu_model);

    env = &cpu->env;

    /* allocate RAM */

    memory_region_allocate_system_memory(phys_ram, NULL, "axisdev88.ram",

                                         ram_size);

    memory_region_add_subregion(address_space_mem, 0x40000000, phys_ram);

    /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the

       internal memory.  */

    memory_region_init_ram(phys_intmem, NULL, "axisdev88.chipram", INTMEM_SIZE,

                           &error_abort);

    vmstate_register_ram_global(phys_intmem);

    memory_region_add_subregion(address_space_mem, 0x38000000, phys_intmem);

      /* Attach a NAND flash to CS1.  */

    nand = drive_get(IF_MTD, 0, 0);

    nand_state.nand = nand_init(nand ? blk_by_legacy_dinfo(nand) : NULL,

                                NAND_MFR_STMICRO, 0x39);

    memory_region_init_io(&nand_state.iomem, NULL, &nand_ops, &nand_state,

                          "nand", 0x05000000);

    memory_region_add_subregion(address_space_mem, 0x10000000,

                                &nand_state.iomem);

    gpio_state.nand = &nand_state;

    memory_region_init_io(&gpio_state.iomem, NULL, &gpio_ops, &gpio_state,

                          "gpio", 0x5c);

    memory_region_add_subregion(address_space_mem, 0x3001a000,

                                &gpio_state.iomem);

    dev = qdev_create(NULL, "etraxfs,pic");

    /* FIXME: Is there a proper way to signal vectors to the CPU core?  */

    qdev_prop_set_ptr(dev, "interrupt_vector", &env->interrupt_vector);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(s, 0, 0x3001c000);

    sysbus_connect_irq(s, 0, qdev_get_gpio_in(DEVICE(cpu), CRIS_CPU_IRQ));

    sysbus_connect_irq(s, 1, qdev_get_gpio_in(DEVICE(cpu), CRIS_CPU_NMI));

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

        irq[i] = qdev_get_gpio_in(dev, i);

    }

    nmi[0] = qdev_get_gpio_in(dev, 30);

    nmi[1] = qdev_get_gpio_in(dev, 31);

    etraxfs_dmac = etraxfs_dmac_init(0x30000000, 10);

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

        /* On ETRAX, odd numbered channels are inputs.  */

        etraxfs_dmac_connect(etraxfs_dmac, i, irq + 7 + i, i & 1);

    }

    /* Add the two ethernet blocks.  */

    dma_eth = g_malloc0(sizeof dma_eth[0] * 4); /* Allocate 4 channels.  */

    etraxfs_eth_init(&nd_table[0], 0x30034000, 1, &dma_eth[0], &dma_eth[1]);

    if (nb_nics > 1) {

        etraxfs_eth_init(&nd_table[1], 0x30036000, 2, &dma_eth[2], &dma_eth[3]);

    }

    /* The DMA Connector block is missing, hardwire things for now.  */

    etraxfs_dmac_connect_client(etraxfs_dmac, 0, &dma_eth[0]);

    etraxfs_dmac_connect_client(etraxfs_dmac, 1, &dma_eth[1]);

    if (nb_nics > 1) {

        etraxfs_dmac_connect_client(etraxfs_dmac, 6, &dma_eth[2]);

        etraxfs_dmac_connect_client(etraxfs_dmac, 7, &dma_eth[3]);

    }

    /* 2 timers.  */

    sysbus_create_varargs("etraxfs,timer", 0x3001e000, irq[0x1b], nmi[1], NULL);

    sysbus_create_varargs("etraxfs,timer", 0x3005e000, irq[0x1b], nmi[1], NULL);

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

        sysbus_create_simple("etraxfs,serial", 0x30026000 + i * 0x2000,

                             irq[0x14 + i]);

    }

    if (kernel_filename) {

        li.image_filename = kernel_filename;

        li.cmdline = kernel_cmdline;

        cris_load_image(cpu, &li);

    } else if (!qtest_enabled()) {

        fprintf(stderr, "Kernel image must be specified\n");

        exit(1);

    }

}


static int mjpeg_decode_app(MJpegDecodeContext *s)

{

    int len, id, i;

    len = get_bits(&s->gb, 16);

    if (len < 6)

        return AVERROR_INVALIDDATA;

    if (8 * len > get_bits_left(&s->gb))

        return AVERROR_INVALIDDATA;

    id   = get_bits_long(&s->gb, 32);

    len -= 6;

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

        char id_str[32];

        av_get_codec_tag_string(id_str, sizeof(id_str), av_bswap32(id));

        av_log(s->avctx, AV_LOG_DEBUG, "APPx (%s / %8X) len=%d\n", id_str, id, len);

    }

    /* Buggy AVID, it puts EOI only at every 10th frame. */

    /* Also, this fourcc is used by non-avid files too, it holds some

       information, but it's always present in AVID-created files. */

    if (id == AV_RB32("AVI1")) {

        /* structure:

            4bytes      AVI1

            1bytes      polarity

            1bytes      always zero

            4bytes      field_size

            4bytes      field_size_less_padding

        */

            s->buggy_avid = 1;

        i = get_bits(&s->gb, 8); len--;

        av_log(s->avctx, AV_LOG_DEBUG, "polarity %d\n", i);

#if 0

        skip_bits(&s->gb, 8);

        skip_bits(&s->gb, 32);

        skip_bits(&s->gb, 32);

        len -= 10;

#endif

    }

//    len -= 2;

    if (id == AV_RB32("JFIF")) {

        int t_w, t_h, v1, v2;

        skip_bits(&s->gb, 8); /* the trailing zero-byte */

        v1 = get_bits(&s->gb, 8);

        v2 = get_bits(&s->gb, 8);

        skip_bits(&s->gb, 8);

        s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 16);

        s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 16);

        if (   s->avctx->sample_aspect_ratio.num <= 0

            || s->avctx->sample_aspect_ratio.den <= 0) {

            s->avctx->sample_aspect_ratio.num = 0;

            s->avctx->sample_aspect_ratio.den = 1;

        }

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO,

                   "mjpeg: JFIF header found (version: %x.%x) SAR=%d/%d\n",

                   v1, v2,

                   s->avctx->sample_aspect_ratio.num,

                   s->avctx->sample_aspect_ratio.den);

        len -= 8;

        if (len >= 2) {

            t_w = get_bits(&s->gb, 8);

            t_h = get_bits(&s->gb, 8);

            if (t_w && t_h) {

                /* skip thumbnail */

                if (len -10 - (t_w * t_h * 3) > 0)

                    len -= t_w * t_h * 3;

            }

            len -= 2;

        }

    }

    if (   id == AV_RB32("Adob")

        && len >= 7

        && show_bits(&s->gb, 8) == 'e'

        && show_bits_long(&s->gb, 32) != AV_RB32("e_CM")) {

        skip_bits(&s->gb,  8); /* 'e' */

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

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

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

        s->adobe_transform = get_bits(&s->gb,  8);

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO, "mjpeg: Adobe header found, transform=%d\n", s->adobe_transform);

        len -= 7;

    }

    if (id == AV_RB32("LJIF")) {

        int rgb = s->rgb;

        int pegasus_rct = s->pegasus_rct;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO,

                   "Pegasus lossless jpeg header found\n");

        skip_bits(&s->gb, 16); /* version ? */

        skip_bits(&s->gb, 16); /* unknown always 0? */

        skip_bits(&s->gb, 16); /* unknown always 0? */

        skip_bits(&s->gb, 16); /* unknown always 0? */

        switch (i=get_bits(&s->gb, 8)) {

        case 1:

            rgb         = 1;

            pegasus_rct = 0;

            break;

        case 2:

            rgb         = 1;

            pegasus_rct = 1;

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "unknown colorspace %d\n", i);

        }

        len -= 9;

        if (s->got_picture)

            if (rgb != s->rgb || pegasus_rct != s->pegasus_rct) {

                av_log(s->avctx, AV_LOG_WARNING, "Mismatching LJIF tag\n");

            }

        s->rgb = rgb;

        s->pegasus_rct = pegasus_rct;

    }

    if (id == AV_RL32("colr") && len > 0) {

        s->colr = get_bits(&s->gb, 8);

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO, "COLR %d\n", s->colr);

        len --;

    }

    if (id == AV_RL32("xfrm") && len > 0) {

        s->xfrm = get_bits(&s->gb, 8);

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO, "XFRM %d\n", s->xfrm);

        len --;

    }

    /* JPS extension by VRex */

    if (s->start_code == APP3 && id == AV_RB32("_JPS") && len >= 10) {

        int flags, layout, type;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_INFO, "_JPSJPS_\n");

        skip_bits(&s->gb, 32); len -= 4;  /* JPS_ */

        skip_bits(&s->gb, 16); len -= 2;  /* block length */

        skip_bits(&s->gb, 8);             /* reserved */

        flags  = get_bits(&s->gb, 8);

        layout = get_bits(&s->gb, 8);

        type   = get_bits(&s->gb, 8);

        len -= 4;

        s->stereo3d = av_stereo3d_alloc();

        if (!s->stereo3d) {

        }

        if (type == 0) {

            s->stereo3d->type = AV_STEREO3D_2D;

        } else if (type == 1) {

            switch (layout) {

            case 0x01:

                s->stereo3d->type = AV_STEREO3D_LINES;

                break;

            case 0x02:

                s->stereo3d->type = AV_STEREO3D_SIDEBYSIDE;

                break;

            case 0x03:

                s->stereo3d->type = AV_STEREO3D_TOPBOTTOM;

                break;

            }

            if (!(flags & 0x04)) {

                s->stereo3d->flags = AV_STEREO3D_FLAG_INVERT;

            }

        }

    }

    /* EXIF metadata */

    if (s->start_code == APP1 && id == AV_RB32("Exif") && len >= 2) {

        GetByteContext gbytes;

        int ret, le, ifd_offset, bytes_read;

        const uint8_t *aligned;

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

        len -= 2;

        // init byte wise reading

        aligned = align_get_bits(&s->gb);

        bytestream2_init(&gbytes, aligned, len);

        // read TIFF header

        ret = ff_tdecode_header(&gbytes, &le, &ifd_offset);

        if (ret) {

            av_log(s->avctx, AV_LOG_ERROR, "mjpeg: invalid TIFF header in EXIF data\n");

        } else {

            bytestream2_seek(&gbytes, ifd_offset, SEEK_SET);

            // read 0th IFD and store the metadata

            // (return values > 0 indicate the presence of subimage metadata)

            ret = avpriv_exif_decode_ifd(s->avctx, &gbytes, le, 0, &s->exif_metadata);

            if (ret < 0) {

                av_log(s->avctx, AV_LOG_ERROR, "mjpeg: error decoding EXIF data\n");

            }

        }

        bytes_read = bytestream2_tell(&gbytes);

        skip_bits(&s->gb, bytes_read << 3);

        len -= bytes_read;

    }

    /* Apple MJPEG-A */

    if ((s->start_code == APP1) && (len > (0x28 - 8))) {

        id   = get_bits_long(&s->gb, 32);

        len -= 4;

        /* Apple MJPEG-A */

        if (id == AV_RB32("mjpg")) {

#if 0

            skip_bits(&s->gb, 32); /* field size */

            skip_bits(&s->gb, 32); /* pad field size */

            skip_bits(&s->gb, 32); /* next off */

            skip_bits(&s->gb, 32); /* quant off */

            skip_bits(&s->gb, 32); /* huff off */

            skip_bits(&s->gb, 32); /* image off */

            skip_bits(&s->gb, 32); /* scan off */

            skip_bits(&s->gb, 32); /* data off */

#endif

            if (s->avctx->debug & FF_DEBUG_PICT_INFO)

                av_log(s->avctx, AV_LOG_INFO, "mjpeg: Apple MJPEG-A header found\n");

        }

    }

out:

    /* slow but needed for extreme adobe jpegs */

    if (len < 0)

        av_log(s->avctx, AV_LOG_ERROR,

               "mjpeg: error, decode_app parser read over the end\n");

    while (--len > 0)

        skip_bits(&s->gb, 8);

    return 0;

}


static int do_decode(AVCodecContext *avctx, AVPacket *pkt)

{

    int got_frame;

    int ret;

    av_assert0(!avctx->internal->buffer_frame->buf[0]);

    if (!pkt)

        pkt = avctx->internal->buffer_pkt;

    // This is the lesser evil. The field is for compatibility with legacy users

    // of the legacy API, and users using the new API should not be forced to

    // even know about this field.

    avctx->refcounted_frames = 1;

    // Some codecs (at least wma lossless) will crash when feeding drain packets

    // after EOF was signaled.

    if (avctx->internal->draining_done)

        return AVERROR_EOF;

    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {

        ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame,

                                    &got_frame, pkt);

        if (ret >= 0 && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))

            ret = pkt->size;

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

        ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame,

                                    &got_frame, pkt);

    } else {

        ret = AVERROR(EINVAL);

    }

    if (ret == AVERROR(EAGAIN))

        ret = pkt->size;

    if (avctx->internal->draining && !got_frame)

        avctx->internal->draining_done = 1;

    if (ret < 0)

        return ret;

    if (ret >= pkt->size) {

        av_packet_unref(avctx->internal->buffer_pkt);

    } else {

        int consumed = ret;

        if (pkt != avctx->internal->buffer_pkt) {

            av_packet_unref(avctx->internal->buffer_pkt);

            if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0)

                return ret;

        }

        avctx->internal->buffer_pkt->data += consumed;

        avctx->internal->buffer_pkt->size -= consumed;

        avctx->internal->buffer_pkt->pts   = AV_NOPTS_VALUE;

        avctx->internal->buffer_pkt->dts   = AV_NOPTS_VALUE;

    }

    if (got_frame)

        av_assert0(avctx->internal->buffer_frame->buf[0]);

    return 0;

}


void ff_h264_free_tables(H264Context *h, int free_rbsp)

{

    int i;

    av_freep(&h->intra4x4_pred_mode);

    av_freep(&h->chroma_pred_mode_table);

    av_freep(&h->cbp_table);

    av_freep(&h->mvd_table[0]);

    av_freep(&h->mvd_table[1]);

    av_freep(&h->direct_table);

    av_freep(&h->non_zero_count);

    av_freep(&h->slice_table_base);

    h->slice_table = NULL;

    av_freep(&h->list_counts);

    av_freep(&h->mb2b_xy);

    av_freep(&h->mb2br_xy);

    av_buffer_pool_uninit(&h->qscale_table_pool);

    av_buffer_pool_uninit(&h->mb_type_pool);

    av_buffer_pool_uninit(&h->motion_val_pool);

    av_buffer_pool_uninit(&h->ref_index_pool);

    if (free_rbsp && h->DPB) {

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

            ff_h264_unref_picture(h, &h->DPB[i]);

        av_freep(&h->DPB);

    }

    h->cur_pic_ptr = NULL;

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

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

        av_freep(&sl->dc_val_base);

        av_freep(&sl->er.mb_index2xy);

        av_freep(&sl->er.error_status_table);

        av_freep(&sl->er.er_temp_buffer);

        av_freep(&sl->bipred_scratchpad);

        av_freep(&sl->edge_emu_buffer);

        av_freep(&sl->top_borders[0]);

        av_freep(&sl->top_borders[1]);

        sl->bipred_scratchpad_allocated = 0;

        sl->edge_emu_buffer_allocated   = 0;

        sl->top_borders_allocated[0]    = 0;

        sl->top_borders_allocated[1]    = 0;

        if (free_rbsp) {

            av_freep(&sl->rbsp_buffer);

            sl->rbsp_buffer_size            = 0;

        }

    }

}


static bool s390_gen_initial_iplb(S390IPLState *ipl)
{
    DeviceState *dev_st;
    dev_st = get_boot_device(0);
    if (dev_st) {
        VirtioCcwDevice *virtio_ccw_dev = (VirtioCcwDevice *)
            object_dynamic_cast(OBJECT(qdev_get_parent_bus(dev_st)->parent),
                TYPE_VIRTIO_CCW_DEVICE);
        SCSIDevice *sd = (SCSIDevice *) object_dynamic_cast(OBJECT(dev_st),
                                                            TYPE_SCSI_DEVICE);
        if (virtio_ccw_dev) {
            CcwDevice *ccw_dev = CCW_DEVICE(virtio_ccw_dev);
            ipl->iplb.len = cpu_to_be32(S390_IPLB_MIN_CCW_LEN);
            ipl->iplb.blk0_len =
                cpu_to_be32(S390_IPLB_MIN_CCW_LEN - S390_IPLB_HEADER_LEN);
            ipl->iplb.pbt = S390_IPL_TYPE_CCW;
            ipl->iplb.ccw.devno = cpu_to_be16(ccw_dev->sch->devno);
            ipl->iplb.ccw.ssid = ccw_dev->sch->ssid & 3;
            return true;
        } else if (sd) {
            SCSIBus *bus = scsi_bus_from_device(sd);
            VirtIOSCSI *vdev = container_of(bus, VirtIOSCSI, bus);
            VirtIOSCSICcw *scsi_ccw = container_of(vdev, VirtIOSCSICcw, vdev);
            CcwDevice *ccw_dev = CCW_DEVICE(scsi_ccw);
            ipl->iplb.len = cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN);
            ipl->iplb.blk0_len =
                cpu_to_be32(S390_IPLB_MIN_QEMU_SCSI_LEN - S390_IPLB_HEADER_LEN);
            ipl->iplb.pbt = S390_IPL_TYPE_QEMU_SCSI;
            ipl->iplb.scsi.lun = cpu_to_be32(sd->lun);
            ipl->iplb.scsi.target = cpu_to_be16(sd->id);
            ipl->iplb.scsi.channel = cpu_to_be16(sd->channel);
            ipl->iplb.scsi.devno = cpu_to_be16(ccw_dev->sch->devno);
            ipl->iplb.scsi.ssid = ccw_dev->sch->ssid & 3;
            return true;
    return false;


static void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch)

{

    int bin, blk, gs;

    int end_bap, gaq_mode;

    GetBitContext *gbc = &s->gbc;

    int gaq_gain[AC3_MAX_COEFS];

    gaq_mode = get_bits(gbc, 2);

    end_bap = (gaq_mode < 2) ? 12 : 17;

    /* if GAQ gain is used, decode gain codes for bins with hebap between

       8 and end_bap */

    gs = 0;

    if (gaq_mode == EAC3_GAQ_12 || gaq_mode == EAC3_GAQ_14) {

        /* read 1-bit GAQ gain codes */

        for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

            if (s->bap[ch][bin] > 7 && s->bap[ch][bin] < end_bap)

                gaq_gain[gs++] = get_bits1(gbc) << (gaq_mode-1);

        }

    } else if (gaq_mode == EAC3_GAQ_124) {

        /* read 1.67-bit GAQ gain codes (3 codes in 5 bits) */

        int gc = 2;

        for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

            if (s->bap[ch][bin] > 7 && s->bap[ch][bin] < 17) {

                if (gc++ == 2) {

                    int group_code = get_bits(gbc, 5);

                    if (group_code > 26) {

                        av_log(s->avctx, AV_LOG_WARNING, "GAQ gain group code out-of-range\n");

                        group_code = 26;

                    }

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][0];

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][1];

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][2];

                    gc = 0;

                }

            }

        }

    }

    gs=0;

    for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

        int hebap = s->bap[ch][bin];

        int bits = ff_eac3_bits_vs_hebap[hebap];

        if (!hebap) {

            /* zero-mantissa dithering */

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

                s->pre_mantissa[ch][bin][blk] = (av_lfg_get(&s->dith_state) & 0x7FFFFF) - 0x400000;

            }

        } else if (hebap < 8) {

            /* Vector Quantization */

            int v = get_bits(gbc, bits);

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

                s->pre_mantissa[ch][bin][blk] = ff_eac3_mantissa_vq[hebap][v][blk] << 8;

            }

        } else {

            /* Gain Adaptive Quantization */

            int gbits, log_gain;

            if (gaq_mode != EAC3_GAQ_NO && hebap < end_bap) {

                log_gain = gaq_gain[gs++];

            } else {

                log_gain = 0;

            }

            gbits = bits - log_gain;

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

                int mant = get_sbits(gbc, gbits);

                if (log_gain && mant == -(1 << (gbits-1))) {

                    /* large mantissa */

                    int b;

                    int mbits = bits - (2 - log_gain);

                    mant = get_sbits(gbc, mbits);

                    mant <<= (23 - (mbits - 1));

                    /* remap mantissa value to correct for asymmetric quantization */

                    if (mant >= 0)

                        b = 1 << (23 - log_gain);

                    else

                        b = ff_eac3_gaq_remap_2_4_b[hebap-8][log_gain-1] << 8;

                    mant += ((ff_eac3_gaq_remap_2_4_a[hebap-8][log_gain-1] * (int64_t)mant) >> 15) + b;

                } else {

                    /* small mantissa, no GAQ, or Gk=1 */

                    mant <<= 24 - bits;

                    if (!log_gain) {

                        /* remap mantissa value for no GAQ or Gk=1 */

                        mant += (ff_eac3_gaq_remap_1[hebap-8] * (int64_t)mant) >> 15;

                    }

                }

                s->pre_mantissa[ch][bin][blk] = mant;

            }

        }

        idct6(s->pre_mantissa[ch][bin]);

    }

}


int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count)

{

    Coroutine *co;

    DiscardCo rwco = {

        .bs = bs,

        .offset = offset,

        .count = count,

        .ret = NOT_DONE,

    };

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_pdiscard_co_entry(&rwco);

    } else {

        co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);

        qemu_coroutine_enter(co);

        BDRV_POLL_WHILE(bs, rwco.ret == NOT_DONE);

    }

    return rwco.ret;

}


static void alpha_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    AlphaCPU *cpu = ALPHA_CPU(obj);

    CPUAlphaState *env = &cpu->env;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    tlb_flush(cs, 1);

    alpha_translate_init();

#if defined(CONFIG_USER_ONLY)

    env->ps = PS_USER_MODE;

    cpu_alpha_store_fpcr(env, (FPCR_INVD | FPCR_DZED | FPCR_OVFD

                               | FPCR_UNFD | FPCR_INED | FPCR_DNOD

                               | FPCR_DYN_NORMAL));

#endif

    env->lock_addr = -1;

    env->fen = 1;

}


static void render_line(int x0, int y0, int x1, int y1, float *buf)

{

    int dy  = y1 - y0;

    int adx = x1 - x0;

    int ady = FFABS(dy);

    int sy  = dy < 0 ? -1 : 1;

    buf[x0] = ff_vorbis_floor1_inverse_db_table[y0];

    if (ady*2 <= adx) { // optimized common case

        render_line_unrolled(x0, y0, x1, sy, ady, adx, buf);

    } else {

        int base = dy / adx;

        int x    = x0;

        int y    = y0;

        int err  = -adx;

        ady -= FFABS(base) * adx;

        while (++x < x1) {

            y += base;

            err += ady;

            if (err >= 0) {

                err -= adx;

                y   += sy;

            }

            buf[x] = ff_vorbis_floor1_inverse_db_table[y];

        }

    }

}


void ram_control_after_iterate(QEMUFile *f, uint64_t flags)

{

    int ret = 0;

    if (f->ops->after_ram_iterate) {

        ret = f->ops->after_ram_iterate(f, f->opaque, flags);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

        }

    }

}


void ff_rtsp_close_streams(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    int i;

    RTSPStream *rtsp_st;

    ff_rtsp_undo_setup(s);

    for (i = 0; i < rt->nb_rtsp_streams; i++) {

        rtsp_st = rt->rtsp_streams[i];

        if (rtsp_st) {

            if (rtsp_st->dynamic_handler && rtsp_st->dynamic_protocol_context)

                rtsp_st->dynamic_handler->close(

                    rtsp_st->dynamic_protocol_context);

        }

    }

    av_free(rt->rtsp_streams);

    if (rt->asf_ctx) {

        av_close_input_stream (rt->asf_ctx);

        rt->asf_ctx = NULL;

    }

    av_free(rt->p);

    av_free(rt->recvbuf);

}


static void aarch64_tr_insn_start(DisasContextBase *dcbase, CPUState *cpu)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    dc->insn_start_idx = tcg_op_buf_count();

    tcg_gen_insn_start(dc->pc, 0, 0);

}


int ff_xvid_rate_control_init(MpegEncContext *s){

    char *tmp_name;

    int fd, i;

    xvid_plg_create_t xvid_plg_create = { 0 };

    xvid_plugin_2pass2_t xvid_2pass2  = { 0 };

    fd=av_tempfile("xvidrc.", &tmp_name, 0, s->avctx);

    if (fd == -1) {

        av_log(NULL, AV_LOG_ERROR, "Can't create temporary pass2 file.\n");

        return -1;

    }

    for(i=0; i<s->rc_context.num_entries; i++){

        static const char frame_types[] = " ipbs";

        char tmp[256];

        RateControlEntry *rce;

        rce= &s->rc_context.entry[i];

        snprintf(tmp, sizeof(tmp), "%c %d %d %d %d %d %d\n",

            frame_types[rce->pict_type], (int)lrintf(rce->qscale / FF_QP2LAMBDA), rce->i_count, s->mb_num - rce->i_count - rce->skip_count,

            rce->skip_count, (rce->i_tex_bits + rce->p_tex_bits + rce->misc_bits+7)/8, (rce->header_bits+rce->mv_bits+7)/8);

        if (write(fd, tmp, strlen(tmp)) < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error %s writing 2pass logfile\n", strerror(errno));

            return AVERROR(errno);

        }

    }

    xvid_2pass2.version= XVID_MAKE_VERSION(1,1,0);

    xvid_2pass2.filename= tmp_name;

    xvid_2pass2.bitrate= s->avctx->bit_rate;

    xvid_2pass2.vbv_size= s->avctx->rc_buffer_size;

    xvid_2pass2.vbv_maxrate= s->avctx->rc_max_rate;

    xvid_2pass2.vbv_initial= s->avctx->rc_initial_buffer_occupancy;

    xvid_plg_create.version= XVID_MAKE_VERSION(1,1,0);

    xvid_plg_create.fbase= s->avctx->time_base.den;

    xvid_plg_create.fincr= s->avctx->time_base.num;

    xvid_plg_create.param= &xvid_2pass2;

    if(xvid_plugin_2pass2(NULL, XVID_PLG_CREATE, &xvid_plg_create, &s->rc_context.non_lavc_opaque)<0){

        av_log(NULL, AV_LOG_ERROR, "xvid_plugin_2pass2 failed\n");

        return -1;

    }

    return 0;

}


void *fw_cfg_modify_file(FWCfgState *s, const char *filename,

                        void *data, size_t len)

{

    int i, index;

    void *ptr = NULL;

    assert(s->files);

    index = be32_to_cpu(s->files->count);

    assert(index < fw_cfg_file_slots(s));

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

        if (strcmp(filename, s->files->f[i].name) == 0) {

            ptr = fw_cfg_modify_bytes_read(s, FW_CFG_FILE_FIRST + i,

                                           data, len);

            s->files->f[i].size   = cpu_to_be32(len);

            return ptr;

        }

    }

    /* add new one */

    fw_cfg_add_file_callback(s, filename, NULL, NULL, NULL, data, len, true);

    return NULL;

}


int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

    BlockDriverState *bs;

    bs = bdrv_find(id);

    if (!bs) {

        qerror_report(QERR_DEVICE_NOT_FOUND, id);

        return -1;

    }

    if (bdrv_in_use(bs)) {

        qerror_report(QERR_DEVICE_IN_USE, id);

        return -1;

    }

    /* quiesce block driver; prevent further io */

    qemu_aio_flush();

    bdrv_flush(bs);

    bdrv_close(bs);

    /* if we have a device attached to this BlockDriverState

     * then we need to make the drive anonymous until the device

     * can be removed.  If this is a drive with no device backing

     * then we can just get rid of the block driver state right here.

     */

    if (bdrv_get_attached_dev(bs)) {

        bdrv_make_anon(bs);

    } else {

        drive_uninit(drive_get_by_blockdev(bs));

    }

    return 0;

}


static void init_proc_970FX (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 POWERPC970_HID5_INIT);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

    spr_register(env, SPR_HIOR, "SPR_HIOR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_hior, &spr_write_hior,

                 0x00000000);

    spr_register(env, SPR_CTRL, "SPR_CTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 SPR_NOACCESS, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_UCTRL, "SPR_UCTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    spr_register(env, SPR_VRSAVE, "SPR_VRSAVE",

                 &spr_read_generic, &spr_write_generic,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

#if !defined(CONFIG_USER_ONLY)

    env->slb_nr = 64;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

    /* Can't find information on what this should be on reset.  This

     * value is the one used by 74xx processors. */

    vscr_init(env, 0x00010000);

}


static QPCIBus *pci_test_start(int socket)

{

    char *cmdline;

    cmdline = g_strdup_printf("-netdev socket,fd=%d,id=hs0 -device "

                              "virtio-net-pci,netdev=hs0", socket);

    qtest_start(cmdline);

    g_free(cmdline);

    return qpci_init_pc(NULL);

}