static void pflash_cfi01_realize(DeviceState *dev, Error **errp)
{
    pflash_t *pfl = CFI_PFLASH01(dev);
    uint64_t total_len;
    int ret;
    uint64_t blocks_per_device, device_len;
    int num_devices;
    Error *local_err = NULL;
    total_len = pfl->sector_len * pfl->nb_blocs;
    /* These are only used to expose the parameters of each device
     * in the cfi_table[].
     */
    num_devices = pfl->device_width ? (pfl->bank_width / pfl->device_width) : 1;
    blocks_per_device = pfl->nb_blocs / num_devices;
    device_len = pfl->sector_len * blocks_per_device;
    /* XXX: to be fixed */
#if 0
    if (total_len != (8 * 1024 * 1024) && total_len != (16 * 1024 * 1024) &&
        total_len != (32 * 1024 * 1024) && total_len != (64 * 1024 * 1024))
        return NULL;
#endif
    memory_region_init_rom_device(
        &pfl->mem, OBJECT(dev),
        &pflash_cfi01_ops,
        pfl,
        pfl->name, total_len, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
    vmstate_register_ram(&pfl->mem, DEVICE(pfl));
    pfl->storage = memory_region_get_ram_ptr(&pfl->mem);
    sysbus_init_mmio(SYS_BUS_DEVICE(dev), &pfl->mem);
    if (pfl->blk) {
        /* read the initial flash content */
        ret = blk_pread(pfl->blk, 0, pfl->storage, total_len);
        if (ret < 0) {
            vmstate_unregister_ram(&pfl->mem, DEVICE(pfl));
            error_setg(errp, "failed to read the initial flash content");
    if (pfl->blk) {
        pfl->ro = blk_is_read_only(pfl->blk);
    } else {
        pfl->ro = 0;
    /* Default to devices being used at their maximum device width. This was
     * assumed before the device_width support was added.
     */
    if (!pfl->max_device_width) {
        pfl->max_device_width = pfl->device_width;
    pfl->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, pflash_timer, pfl);
    pfl->wcycle = 0;
    pfl->cmd = 0;
    pfl->status = 0;
    /* Hardcoded CFI table */
    pfl->cfi_len = 0x52;
    /* Standard "QRY" string */
    pfl->cfi_table[0x10] = 'Q';
    pfl->cfi_table[0x11] = 'R';
    pfl->cfi_table[0x12] = 'Y';
    /* Command set (Intel) */
    pfl->cfi_table[0x13] = 0x01;
    pfl->cfi_table[0x14] = 0x00;
    /* Primary extended table address (none) */
    pfl->cfi_table[0x15] = 0x31;
    pfl->cfi_table[0x16] = 0x00;
    /* Alternate command set (none) */
    pfl->cfi_table[0x17] = 0x00;
    pfl->cfi_table[0x18] = 0x00;
    /* Alternate extended table (none) */
    pfl->cfi_table[0x19] = 0x00;
    pfl->cfi_table[0x1A] = 0x00;
    /* Vcc min */
    pfl->cfi_table[0x1B] = 0x45;
    /* Vcc max */
    pfl->cfi_table[0x1C] = 0x55;
    /* Vpp min (no Vpp pin) */
    pfl->cfi_table[0x1D] = 0x00;
    /* Vpp max (no Vpp pin) */
    pfl->cfi_table[0x1E] = 0x00;
    /* Reserved */
    pfl->cfi_table[0x1F] = 0x07;
    /* Timeout for min size buffer write */
    pfl->cfi_table[0x20] = 0x07;
    /* Typical timeout for block erase */
    pfl->cfi_table[0x21] = 0x0a;
    /* Typical timeout for full chip erase (4096 ms) */
    pfl->cfi_table[0x22] = 0x00;
    /* Reserved */
    pfl->cfi_table[0x23] = 0x04;
    /* Max timeout for buffer write */
    pfl->cfi_table[0x24] = 0x04;
    /* Max timeout for block erase */
    pfl->cfi_table[0x25] = 0x04;
    /* Max timeout for chip erase */
    pfl->cfi_table[0x26] = 0x00;
    /* Device size */
    pfl->cfi_table[0x27] = ctz32(device_len); /* + 1; */
    /* Flash device interface (8 & 16 bits) */
    pfl->cfi_table[0x28] = 0x02;
    pfl->cfi_table[0x29] = 0x00;
    /* Max number of bytes in multi-bytes write */
    if (pfl->bank_width == 1) {
        pfl->cfi_table[0x2A] = 0x08;
    } else {
        pfl->cfi_table[0x2A] = 0x0B;
    pfl->writeblock_size = 1 << pfl->cfi_table[0x2A];
    pfl->cfi_table[0x2B] = 0x00;
    /* Number of erase block regions (uniform) */
    pfl->cfi_table[0x2C] = 0x01;
    /* Erase block region 1 */
    pfl->cfi_table[0x2D] = blocks_per_device - 1;
    pfl->cfi_table[0x2E] = (blocks_per_device - 1) >> 8;
    pfl->cfi_table[0x2F] = pfl->sector_len >> 8;
    pfl->cfi_table[0x30] = pfl->sector_len >> 16;
    /* Extended */
    pfl->cfi_table[0x31] = 'P';
    pfl->cfi_table[0x32] = 'R';
    pfl->cfi_table[0x33] = 'I';
    pfl->cfi_table[0x34] = '1';
    pfl->cfi_table[0x35] = '0';
    pfl->cfi_table[0x36] = 0x00;
    pfl->cfi_table[0x37] = 0x00;
    pfl->cfi_table[0x38] = 0x00;
    pfl->cfi_table[0x39] = 0x00;
    pfl->cfi_table[0x3a] = 0x00;
    pfl->cfi_table[0x3b] = 0x00;
    pfl->cfi_table[0x3c] = 0x00;
    pfl->cfi_table[0x3f] = 0x01; /* Number of protection fields */


static int vaapi_mpeg2_start_frame(AVCodecContext *avctx, av_unused const uint8_t *buffer, av_unused uint32_t size)

{

    struct MpegEncContext * const s = avctx->priv_data;

    struct vaapi_context * const vactx = avctx->hwaccel_context;

    VAPictureParameterBufferMPEG2 *pic_param;

    VAIQMatrixBufferMPEG2 *iq_matrix;

    int i;

    av_dlog(avctx, "vaapi_mpeg2_start_frame()\n");

    vactx->slice_param_size = sizeof(VASliceParameterBufferMPEG2);

    /* Fill in VAPictureParameterBufferMPEG2 */

    pic_param = ff_vaapi_alloc_pic_param(vactx, sizeof(VAPictureParameterBufferMPEG2));

    if (!pic_param)

        return -1;

    pic_param->horizontal_size                                  = s->width;

    pic_param->vertical_size                                    = s->height;

    pic_param->forward_reference_picture                        = VA_INVALID_ID;

    pic_param->backward_reference_picture                       = VA_INVALID_ID;

    pic_param->picture_coding_type                              = s->pict_type;

    pic_param->f_code                                           = mpeg2_get_f_code(s);

    pic_param->picture_coding_extension.value                   = 0; /* reset all bits */

    pic_param->picture_coding_extension.bits.intra_dc_precision = s->intra_dc_precision;

    pic_param->picture_coding_extension.bits.picture_structure  = s->picture_structure;

    pic_param->picture_coding_extension.bits.top_field_first    = s->top_field_first;

    pic_param->picture_coding_extension.bits.frame_pred_frame_dct = s->frame_pred_frame_dct;

    pic_param->picture_coding_extension.bits.concealment_motion_vectors = s->concealment_motion_vectors;

    pic_param->picture_coding_extension.bits.q_scale_type       = s->q_scale_type;

    pic_param->picture_coding_extension.bits.intra_vlc_format   = s->intra_vlc_format;

    pic_param->picture_coding_extension.bits.alternate_scan     = s->alternate_scan;

    pic_param->picture_coding_extension.bits.repeat_first_field = s->repeat_first_field;

    pic_param->picture_coding_extension.bits.progressive_frame  = s->progressive_frame;

    pic_param->picture_coding_extension.bits.is_first_field     = mpeg2_get_is_frame_start(s);

    switch (s->pict_type) {

    case AV_PICTURE_TYPE_B:

        pic_param->backward_reference_picture = ff_vaapi_get_surface_id(&s->next_picture.f);

        // fall-through

    case AV_PICTURE_TYPE_P:

        pic_param->forward_reference_picture = ff_vaapi_get_surface_id(&s->last_picture.f);

        break;

    }

    /* Fill in VAIQMatrixBufferMPEG2 */

    iq_matrix = ff_vaapi_alloc_iq_matrix(vactx, sizeof(VAIQMatrixBufferMPEG2));

    if (!iq_matrix)

        return -1;

    iq_matrix->load_intra_quantiser_matrix              = 1;

    iq_matrix->load_non_intra_quantiser_matrix          = 1;

    iq_matrix->load_chroma_intra_quantiser_matrix       = 1;

    iq_matrix->load_chroma_non_intra_quantiser_matrix   = 1;

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

        int n = s->dsp.idct_permutation[ff_zigzag_direct[i]];

        iq_matrix->intra_quantiser_matrix[i]            = s->intra_matrix[n];

        iq_matrix->non_intra_quantiser_matrix[i]        = s->inter_matrix[n];

        iq_matrix->chroma_intra_quantiser_matrix[i]     = s->chroma_intra_matrix[n];

        iq_matrix->chroma_non_intra_quantiser_matrix[i] = s->chroma_inter_matrix[n];

    }

    return 0;

}


int qemu_config_parse(FILE *fp, QemuOptsList **lists, const char *fname)

{

    char line[1024], group[64], id[64], arg[64], value[1024];

    Location loc;

    QemuOptsList *list = NULL;

    QemuOpts *opts = NULL;

    int res = -1, lno = 0;

    loc_push_none(&loc);

    while (fgets(line, sizeof(line), fp) != NULL) {

        loc_set_file(fname, ++lno);

        if (line[0] == '\n') {

            /* skip empty lines */

            continue;

        }

        if (line[0] == '#') {

            /* comment */

            continue;

        }

        if (sscanf(line, "[%63s \"%63[^\"]\"]", group, id) == 2) {

            /* group with id */

            list = find_list(lists, group);

            if (list == NULL)

                goto out;

            opts = qemu_opts_create(list, id, 1);

            continue;

        }

        if (sscanf(line, "[%63[^]]]", group) == 1) {

            /* group without id */

            list = find_list(lists, group);

            if (list == NULL)

                goto out;

            opts = qemu_opts_create(list, NULL, 0);

            continue;

        }

        if (sscanf(line, " %63s = \"%1023[^\"]\"", arg, value) == 2) {

            /* arg = value */

            if (opts == NULL) {

                error_report("no group defined");

                goto out;

            }

            if (qemu_opt_set(opts, arg, value) != 0) {

                goto out;

            }

            continue;

        }

        error_report("parse error");

        goto out;

    }

    if (ferror(fp)) {

        error_report("error reading file");

        goto out;

    }

    res = 0;

out:

    loc_pop(&loc);

    return res;

}


static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,

                             socklen_t *addr_len, const char *localaddr)

{

    int udp_fd = -1;

    struct addrinfo *res0 = NULL, *res = NULL;

    int family = AF_UNSPEC;

    if (((struct sockaddr *) &s->dest_addr)->sa_family)

        family = ((struct sockaddr *) &s->dest_addr)->sa_family;

    res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,

                            SOCK_DGRAM, family, AI_PASSIVE);

    if (res0 == 0)

        goto fail;

    for (res = res0; res; res=res->ai_next) {

        udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);

        if (udp_fd != -1) break;

        log_net_error(NULL, AV_LOG_ERROR, "socket");

    }

    if (udp_fd < 0)

        goto fail;

    memcpy(addr, res->ai_addr, res->ai_addrlen);

    *addr_len = res->ai_addrlen;

    freeaddrinfo(res0);

    return udp_fd;

 fail:

    if (udp_fd >= 0)

        closesocket(udp_fd);

    if(res0)

        freeaddrinfo(res0);

    return -1;

}


static inline void RENAME(yuv2yuv1)(int16_t *lumSrc, int16_t *chrSrc,

                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, long dstW, long chrDstW)

{

#ifdef HAVE_MMX

    if (uDest)

    {

        asm volatile(

            YSCALEYUV2YV121

            :: "r" (chrSrc + chrDstW), "r" (uDest + chrDstW),

            "g" (-chrDstW)

            : "%"REG_a

        );

        asm volatile(

            YSCALEYUV2YV121

            :: "r" (chrSrc + 2048 + chrDstW), "r" (vDest + chrDstW),

            "g" (-chrDstW)

            : "%"REG_a

        );

    }

    asm volatile(

        YSCALEYUV2YV121

        :: "r" (lumSrc + dstW), "r" (dest + dstW),

        "g" (-dstW)

        : "%"REG_a

    );

#else

    int i;

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

    {

        int val= lumSrc[i]>>7;

        if (val&256){

            if (val<0) val=0;

            else       val=255;

        }

        dest[i]= val;

    }

    if (uDest)

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

        {

            int u=chrSrc[i]>>7;

            int v=chrSrc[i + 2048]>>7;

            if ((u|v)&256){

                if (u<0)        u=0;

                else if (u>255) u=255;

                if (v<0)        v=0;

                else if (v>255) v=255;

            }

            uDest[i]= u;

            vDest[i]= v;

        }

#endif

}


static ssize_t qsb_grow(QEMUSizedBuffer *qsb, size_t new_size)

{

    size_t needed_chunks, i;

    if (qsb->size < new_size) {

        struct iovec *new_iov;

        size_t size_diff = new_size - qsb->size;

        size_t chunk_size = (size_diff > QSB_MAX_CHUNK_SIZE)

                             ? QSB_MAX_CHUNK_SIZE : QSB_CHUNK_SIZE;

        needed_chunks = DIV_ROUND_UP(size_diff, chunk_size);

        new_iov = g_try_new(struct iovec, qsb->n_iov + needed_chunks);

        if (new_iov == NULL) {

            return -ENOMEM;

        }

        /* Allocate new chunks as needed into new_iov */

        for (i = qsb->n_iov; i < qsb->n_iov + needed_chunks; i++) {

            new_iov[i].iov_base = g_try_malloc0(chunk_size);

            new_iov[i].iov_len = chunk_size;

            if (!new_iov[i].iov_base) {

                size_t j;

                /* Free previously allocated new chunks */

                for (j = qsb->n_iov; j < i; j++) {

                    g_free(new_iov[j].iov_base);

                }

                g_free(new_iov);

                return -ENOMEM;

            }

        }

        /*

         * Now we can't get any allocation errors, copy over to new iov

         * and switch.

         */

        for (i = 0; i < qsb->n_iov; i++) {

            new_iov[i] = qsb->iov[i];

        }

        qsb->n_iov += needed_chunks;

        g_free(qsb->iov);

        qsb->iov = new_iov;

        qsb->size += (needed_chunks * chunk_size);

    }

    return qsb->size;

}


vmxnet3_init_msix(VMXNET3State *s)

{

    PCIDevice *d = PCI_DEVICE(s);

    int res = msix_init(d, VMXNET3_MAX_INTRS,

                        &s->msix_bar,

                        VMXNET3_MSIX_BAR_IDX, VMXNET3_OFF_MSIX_TABLE,

                        &s->msix_bar,

                        VMXNET3_MSIX_BAR_IDX, VMXNET3_OFF_MSIX_PBA(s),

                        VMXNET3_MSIX_OFFSET(s));

    if (0 > res) {

        VMW_WRPRN("Failed to initialize MSI-X, error %d", res);

        s->msix_used = false;

    } else {

        if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {

            VMW_WRPRN("Failed to use MSI-X vectors, error %d", res);

            msix_uninit(d, &s->msix_bar, &s->msix_bar);

            s->msix_used = false;

        } else {

            s->msix_used = true;

        }

    }

    return s->msix_used;

}


static int build_feed_streams(void)

{

    FFServerStream *stream, *feed;

    int i;

    /* gather all streams */

    for(stream = config.first_stream; stream; stream = stream->next) {

        feed = stream->feed;

        if (!feed)

            continue;

        if (stream->is_feed) {

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

                stream->feed_streams[i] = i;

        } else {

            /* we handle a stream coming from a feed */

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

                stream->feed_streams[i] = add_av_stream(feed,

                                                        stream->streams[i]);

        }

    }

    /* create feed files if needed */

    for(feed = config.first_feed; feed; feed = feed->next_feed) {

        int fd;

        if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {

            /* See if it matches */

            AVFormatContext *s = NULL;

            int matches = 0;

            if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) >= 0) {

                /* set buffer size */

                int ret = ffio_set_buf_size(s->pb, FFM_PACKET_SIZE);

                if (ret < 0) {

                    http_log("Failed to set buffer size\n");

                    goto bail;

                }

                /* Now see if it matches */

                if (s->nb_streams == feed->nb_streams) {

                    matches = 1;

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

                        AVStream *sf, *ss;

                        sf = feed->streams[i];

                        ss = s->streams[i];

                        if (sf->index != ss->index ||

                            sf->id != ss->id) {

                            http_log("Index & Id do not match for stream %d (%s)\n",

                                   i, feed->feed_filename);

                            matches = 0;

                        } else {

                            AVCodecContext *ccf, *ccs;

                            ccf = sf->codec;

                            ccs = ss->codec;

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

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

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

                                matches = 0;

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

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

                                matches = 0;

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

                                if (CHECK_CODEC(time_base.den) ||

                                    CHECK_CODEC(time_base.num) ||

                                    CHECK_CODEC(width) ||

                                    CHECK_CODEC(height)) {

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

                                    matches = 0;

                                }

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

                                if (CHECK_CODEC(sample_rate) ||

                                    CHECK_CODEC(channels) ||

                                    CHECK_CODEC(frame_size)) {

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

                                    matches = 0;

                                }

                            } else {

                                http_log("Unknown codec type\n");

                                matches = 0;

                            }

                        }

                        if (!matches)

                            break;

                    }

                } else

                    http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",

                        feed->feed_filename, s->nb_streams, feed->nb_streams);

                avformat_close_input(&s);

            } else

                http_log("Deleting feed file '%s' as it appears to be corrupt\n",

                        feed->feed_filename);

            if (!matches) {

                if (feed->readonly) {

                    http_log("Unable to delete feed file '%s' as it is marked readonly\n",

                        feed->feed_filename);

                    goto bail;

                }

                unlink(feed->feed_filename);

            }

        }

        if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {

            AVFormatContext *s = avformat_alloc_context();

            if (!s) {

                http_log("Failed to allocate context\n");

                goto bail;

            }

            if (feed->readonly) {

                http_log("Unable to create feed file '%s' as it is marked readonly\n",

                    feed->feed_filename);

                goto bail;

            }

            /* only write the header of the ffm file */

            if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {

                http_log("Could not open output feed file '%s'\n",

                         feed->feed_filename);

                goto bail;

            }

            s->oformat = feed->fmt;

            s->nb_streams = feed->nb_streams;

            s->streams = feed->streams;

            if (avformat_write_header(s, NULL) < 0) {

                http_log("Container doesn't support the required parameters\n");

                goto bail;

            }

            /* XXX: need better API */

            av_freep(&s->priv_data);

            avio_closep(&s->pb);

            s->streams = NULL;

            s->nb_streams = 0;

            avformat_free_context(s);

        }

        /* get feed size and write index */

        fd = open(feed->feed_filename, O_RDONLY);

        if (fd < 0) {

            http_log("Could not open output feed file '%s'\n",

                    feed->feed_filename);

            goto bail;

        }

        feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);

        feed->feed_size = lseek(fd, 0, SEEK_END);

        /* ensure that we do not wrap before the end of file */

        if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)

            feed->feed_max_size = feed->feed_size;

        close(fd);

    }

    return 0;

bail:

    return -1;

}


static always_inline void dv_encode_ac(EncBlockInfo* bi, PutBitContext* pb_pool,

                                       int pb_size)

{

    int run;

    int bits_left;

    PutBitContext* pb = pb_pool;

    int size = bi->partial_bit_count;

    uint32_t vlc = bi->partial_bit_buffer;

    bi->partial_bit_count = bi->partial_bit_buffer = 0;

vlc_loop:

       /* Find suitable storage space */

       for (; size > (bits_left = put_bits_left(pb)); pb++) {

          if (bits_left) {

              size -= bits_left;

	      put_bits(pb, bits_left, vlc >> size);

	      vlc = vlc & ((1<<size)-1);

	  }

	  if (pb_size == 1) {

	      bi->partial_bit_count = size;

	      bi->partial_bit_buffer = vlc;

	      return;

	  }

	  --pb_size;

       }

       /* Store VLC */

       put_bits(pb, size, vlc);

       /* Construct the next VLC */

       run = 0;

       for (; bi->cur_ac < 64; bi->cur_ac++, run++) {

           if (bi->mb[bi->cur_ac]) {

	       size = dv_rl2vlc(run, bi->mb[bi->cur_ac], &vlc);

	       bi->cur_ac++;

	       goto vlc_loop;

	   }

       }

       if (bi->cur_ac == 64) {

           size = 4; vlc = 6; /* End Of Block stamp */

	   bi->cur_ac++;

	   goto vlc_loop;

       }

}


static uint64_t mipsnet_ioport_read(void *opaque, target_phys_addr_t addr,

                                    unsigned int size)

{

    MIPSnetState *s = opaque;

    int ret = 0;

    addr &= 0x3f;

    switch (addr) {

    case MIPSNET_DEV_ID:

	ret = be32_to_cpu(0x4d495053);		/* MIPS */

        break;

    case MIPSNET_DEV_ID + 4:

	ret = be32_to_cpu(0x4e455430);		/* NET0 */

        break;

    case MIPSNET_BUSY:

	ret = s->busy;

        break;

    case MIPSNET_RX_DATA_COUNT:

	ret = s->rx_count;

        break;

    case MIPSNET_TX_DATA_COUNT:

	ret = s->tx_count;

        break;

    case MIPSNET_INT_CTL:

	ret = s->intctl;

        s->intctl &= ~MIPSNET_INTCTL_TESTBIT;

        break;

    case MIPSNET_INTERRUPT_INFO:

        /* XXX: This seems to be a per-VPE interrupt number. */

	ret = 0;

        break;

    case MIPSNET_RX_DATA_BUFFER:

        if (s->rx_count) {

            s->rx_count--;

            ret = s->rx_buffer[s->rx_read++];

        }

        break;

    /* Reads as zero. */

    case MIPSNET_TX_DATA_BUFFER:

    default:

        break;

    }

    trace_mipsnet_read(addr, ret);

    return ret;

}


static uint32_t get_generic_seed(void)

{

    uint8_t tmp[120];

    struct AVSHA *sha = (void*)tmp;

    clock_t last_t  = 0;

    static uint64_t i = 0;

    static uint32_t buffer[512] = { 0 };

    unsigned char digest[20];

    uint64_t last_i = i;

    av_assert0(sizeof(tmp) >= av_sha_size);

    if(TEST){

        memset(buffer, 0, sizeof(buffer));

        last_i = i = 0;

    }else{

#ifdef AV_READ_TIME

        buffer[13] ^= AV_READ_TIME();

        buffer[41] ^= AV_READ_TIME()>>32;

#endif

    }

    for (;;) {

        clock_t t = clock();

        if (last_t == t) {

            buffer[i & 511]++;

        } else {

            buffer[++i & 511] += (t - last_t) % 3294638521U;

            if (last_i && i - last_i > 4 || i - last_i > 64 || TEST && i - last_i > 8)

                break;

        }

        last_t = t;

    }

    if(TEST)

        buffer[0] = buffer[1] = 0;

    av_sha_init(sha, 160);

    av_sha_update(sha, (const uint8_t *)buffer, sizeof(buffer));

    av_sha_final(sha, digest);

    return AV_RB32(digest) + AV_RB32(digest + 16);

}


int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint32_t *flags,

                          off_t *size, Error **errp)

{

    char buf[256];

    uint64_t magic, s;

    int rc;

    TRACE("Receiving negotiation.");

    rc = -EINVAL;

    if (read_sync(ioc, buf, 8) != 8) {

        error_setg(errp, "Failed to read data");

        goto fail;

    }

    buf[8] = '\0';

    if (strlen(buf) == 0) {

        error_setg(errp, "Server connection closed unexpectedly");

        goto fail;

    }

    TRACE("Magic is %c%c%c%c%c%c%c%c",

          qemu_isprint(buf[0]) ? buf[0] : '.',

          qemu_isprint(buf[1]) ? buf[1] : '.',

          qemu_isprint(buf[2]) ? buf[2] : '.',

          qemu_isprint(buf[3]) ? buf[3] : '.',

          qemu_isprint(buf[4]) ? buf[4] : '.',

          qemu_isprint(buf[5]) ? buf[5] : '.',

          qemu_isprint(buf[6]) ? buf[6] : '.',

          qemu_isprint(buf[7]) ? buf[7] : '.');

    if (memcmp(buf, "NBDMAGIC", 8) != 0) {

        error_setg(errp, "Invalid magic received");

        goto fail;

    }

    if (read_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {

        error_setg(errp, "Failed to read magic");

        goto fail;

    }

    magic = be64_to_cpu(magic);

    TRACE("Magic is 0x%" PRIx64, magic);

    if (magic == NBD_OPTS_MAGIC) {

        uint32_t clientflags = 0;

        uint32_t opt;

        uint32_t namesize;

        uint16_t globalflags;

        uint16_t exportflags;

        if (read_sync(ioc, &globalflags, sizeof(globalflags)) !=

            sizeof(globalflags)) {

            error_setg(errp, "Failed to read server flags");

            goto fail;

        }

        *flags = be16_to_cpu(globalflags) << 16;

        if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {

            TRACE("Server supports fixed new style");

            clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;

        }

        /* client requested flags */

        if (write_sync(ioc, &clientflags, sizeof(clientflags)) !=

            sizeof(clientflags)) {

            error_setg(errp, "Failed to send clientflags field");

            goto fail;

        }

        /* write the export name */

        if (!name) {

            error_setg(errp, "Server requires an export name");

            goto fail;

        }

        magic = cpu_to_be64(magic);

        if (write_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {

            error_setg(errp, "Failed to send export name magic");

            goto fail;

        }

        opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);

        if (write_sync(ioc, &opt, sizeof(opt)) != sizeof(opt)) {

            error_setg(errp, "Failed to send export name option number");

            goto fail;

        }

        namesize = cpu_to_be32(strlen(name));

        if (write_sync(ioc, &namesize, sizeof(namesize)) !=

            sizeof(namesize)) {

            error_setg(errp, "Failed to send export name length");

            goto fail;

        }

        if (write_sync(ioc, (char *)name, strlen(name)) != strlen(name)) {

            error_setg(errp, "Failed to send export name");

            goto fail;

        }

        if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {

            error_setg(errp, "Failed to read export length");

            goto fail;

        }

        *size = be64_to_cpu(s);

        TRACE("Size is %" PRIu64, *size);

        if (read_sync(ioc, &exportflags, sizeof(exportflags)) !=

            sizeof(exportflags)) {

            error_setg(errp, "Failed to read export flags");

            goto fail;

        }

        *flags |= be16_to_cpu(exportflags);

    } else if (magic == NBD_CLIENT_MAGIC) {

        if (name) {

            error_setg(errp, "Server does not support export names");

            goto fail;

        }

        if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {

            error_setg(errp, "Failed to read export length");

            goto fail;

        }

        *size = be64_to_cpu(s);

        TRACE("Size is %" PRIu64, *size);

        if (read_sync(ioc, flags, sizeof(*flags)) != sizeof(*flags)) {

            error_setg(errp, "Failed to read export flags");

            goto fail;

        }

        *flags = be32_to_cpup(flags);

    } else {

        error_setg(errp, "Bad magic received");

        goto fail;

    }

    if (read_sync(ioc, &buf, 124) != 124) {

        error_setg(errp, "Failed to read reserved block");

        goto fail;

    }

    rc = 0;

fail:

    return rc;

}


static inline void gen_op_evsrws(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2)

{

    TCGv_i32 t0;

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    t0 = tcg_temp_local_new_i32();

    /* No error here: 6 bits are used */

    tcg_gen_andi_i32(t0, arg2, 0x3F);

    tcg_gen_brcondi_i32(TCG_COND_GE, t0, 32, l1);

    tcg_gen_sar_i32(ret, arg1, t0);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_movi_i32(ret, 0);

    gen_set_label(l2);

    tcg_temp_free_i32(t0);

}


void hd_geometry_guess(BlockDriverState *bs,

                       uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,

                       int *ptrans)

{

    int cylinders, heads, secs, translation;

    if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {

        /* no LCHS guess: use a standard physical disk geometry  */

        guess_chs_for_size(bs, pcyls, pheads, psecs);

        translation = hd_bios_chs_auto_trans(*pcyls, *pheads, *psecs);

    } else if (heads > 16) {

        /* LCHS guess with heads > 16 means that a BIOS LBA

           translation was active, so a standard physical disk

           geometry is OK */

        guess_chs_for_size(bs, pcyls, pheads, psecs);

        translation = *pcyls * *pheads <= 131072

            ? BIOS_ATA_TRANSLATION_LARGE

            : BIOS_ATA_TRANSLATION_LBA;

    } else {

        /* LCHS guess with heads <= 16: use as physical geometry */

        *pcyls = cylinders;

        *pheads = heads;

        *psecs = secs;

        /* disable any translation to be in sync with

           the logical geometry */

        translation = BIOS_ATA_TRANSLATION_NONE;

    }

    if (ptrans) {

        *ptrans = translation;

    }

    trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);

}


static MemoryRegion *acpi_add_rom_blob(AcpiBuildState *build_state,

                                       GArray *blob, const char *name,

                                       uint64_t max_size)

{

    return rom_add_blob(name, blob->data, acpi_data_len(blob), max_size, -1,

                        name, virt_acpi_build_update, build_state);

}


static int versatile_pci_host_init(PCIDevice *d)

{

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_XILINX);

    /* Both boards have the same device ID.  Oh well.  */

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_XILINX_XC2VP30);

    pci_set_word(d->config + PCI_STATUS,

		 PCI_STATUS_66MHZ | PCI_STATUS_DEVSEL_MEDIUM);

    pci_config_set_class(d->config, PCI_CLASS_PROCESSOR_CO);

    pci_set_byte(d->config + PCI_LATENCY_TIMER, 0x10);

    return 0;

}


vcard_emul_replay_insertion_events(void)

{

    VReaderListEntry *current_entry;

    VReaderListEntry *next_entry = NULL;

    VReaderList *list = vreader_get_reader_list();

    for (current_entry = vreader_list_get_first(list); current_entry;

            current_entry = next_entry) {

        VReader *vreader = vreader_list_get_reader(current_entry);

        next_entry = vreader_list_get_next(current_entry);

        vreader_queue_card_event(vreader);

    }

    vreader_list_delete(list);

}


static int read_config(BDRVBlkdebugState *s, const char *filename, Error **errp)

{

    FILE *f;

    int ret;

    struct add_rule_data d;

    f = fopen(filename, "r");

    if (f == NULL) {

        error_setg_errno(errp, errno, "Could not read blkdebug config file");

        return -errno;

    }

    ret = qemu_config_parse(f, config_groups, filename);

    if (ret < 0) {

        error_setg(errp, "Could not parse blkdebug config file");

        ret = -EINVAL;

        goto fail;

    }

    d.s = s;

    d.action = ACTION_INJECT_ERROR;

    qemu_opts_foreach(&inject_error_opts, add_rule, &d, 0);

    d.action = ACTION_SET_STATE;

    qemu_opts_foreach(&set_state_opts, add_rule, &d, 0);

    ret = 0;

fail:

    qemu_opts_reset(&inject_error_opts);

    qemu_opts_reset(&set_state_opts);

    fclose(f);

    return ret;

}


static int vnc_update_client(VncState *vs, int has_dirty)

{

    if (vs->need_update && vs->csock != -1) {

        VncDisplay *vd = vs->vd;

        int y;

        int n_rectangles;

        int saved_offset;

        int n;

        if (vs->output.offset && !vs->audio_cap && !vs->force_update)

            /* kernel send buffers are full -> drop frames to throttle */

            return 0;

        if (!has_dirty && !vs->audio_cap && !vs->force_update)

            return 0;

        /*

         * Send screen updates to the vnc client using the server

         * surface and server dirty map.  guest surface updates

         * happening in parallel don't disturb us, the next pass will

         * send them to the client.

         */

        n_rectangles = 0;

        vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);

        vnc_write_u8(vs, 0);

        saved_offset = vs->output.offset;

        vnc_write_u16(vs, 0);

        for (y = 0; y < vd->server->height; y++) {

            int x;

            int last_x = -1;

            for (x = 0; x < vd->server->width / 16; x++) {

                if (vnc_get_bit(vs->dirty[y], x)) {

                    if (last_x == -1) {

                        last_x = x;

                    }

                    vnc_clear_bit(vs->dirty[y], x);

                } else {

                    if (last_x != -1) {

                        int h = find_and_clear_dirty_height(vs, y, last_x, x);

                        n = send_framebuffer_update(vs, last_x * 16, y,

                                                    (x - last_x) * 16, h);

                        n_rectangles += n;

                    }

                    last_x = -1;

                }

            }

            if (last_x != -1) {

                int h = find_and_clear_dirty_height(vs, y, last_x, x);

                n = send_framebuffer_update(vs, last_x * 16, y,

                                            (x - last_x) * 16, h);

                n_rectangles += n;

            }

        }

        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;

        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;

        vnc_flush(vs);

        vs->force_update = 0;

        return n_rectangles;

    }

    if (vs->csock == -1)

        vnc_disconnect_finish(vs);

    return 0;

}


int ff_vorbiscomment_write(uint8_t **p, AVDictionary **m,

                           const char *vendor_string)

{

    bytestream_put_le32(p, strlen(vendor_string));

    bytestream_put_buffer(p, vendor_string, strlen(vendor_string));

    if (*m) {

        int count = av_dict_count(*m);

        AVDictionaryEntry *tag = NULL;

        bytestream_put_le32(p, count);

        while ((tag = av_dict_get(*m, "", tag, AV_DICT_IGNORE_SUFFIX))) {

            unsigned int len1 = strlen(tag->key);

            unsigned int len2 = strlen(tag->value);

            bytestream_put_le32(p, len1+1+len2);

            bytestream_put_buffer(p, tag->key, len1);

            bytestream_put_byte(p, '=');

            bytestream_put_buffer(p, tag->value, len2);

        }

    } else

        bytestream_put_le32(p, 0);

    return 0;

}


void qemu_input_event_send_key_qcode(QemuConsole *src, QKeyCode q, bool down)

{

    KeyValue *key = g_new0(KeyValue, 1);

    key->kind = KEY_VALUE_KIND_QCODE;

    key->qcode = q;

    qemu_input_event_send_key(src, key, down);

}


static QVirtIOSCSI *qvirtio_scsi_pci_init(int slot)

{

    QVirtIOSCSI *vs;

    QVirtioPCIDevice *dev;

    void *addr;

    int i;

    vs = g_new0(QVirtIOSCSI, 1);

    vs->alloc = pc_alloc_init();

    vs->bus = qpci_init_pc();

    dev = qvirtio_pci_device_find(vs->bus, QVIRTIO_SCSI_DEVICE_ID);

    vs->dev = (QVirtioDevice *)dev;

    g_assert(dev != NULL);

    g_assert_cmphex(vs->dev->device_type, ==, QVIRTIO_SCSI_DEVICE_ID);

    qvirtio_pci_device_enable(dev);

    qvirtio_reset(&qvirtio_pci, vs->dev);

    qvirtio_set_acknowledge(&qvirtio_pci, vs->dev);

    qvirtio_set_driver(&qvirtio_pci, vs->dev);

    addr = dev->addr + QVIRTIO_PCI_DEVICE_SPECIFIC_NO_MSIX;

    vs->num_queues = qvirtio_config_readl(&qvirtio_pci, vs->dev,

                                          (uint64_t)(uintptr_t)addr);

    g_assert_cmpint(vs->num_queues, <, MAX_NUM_QUEUES);

    for (i = 0; i < vs->num_queues + 2; i++) {

        vs->vq[i] = qvirtqueue_setup(&qvirtio_pci, vs->dev, vs->alloc, i);

    }

    return vs;

}


static MachineClass *machine_parse(const char *name)

{

    MachineClass *mc = NULL;

    GSList *el, *machines = object_class_get_list(TYPE_MACHINE, false);

    if (name) {

        mc = find_machine(name);

    }

    if (mc) {

        return mc;

    }

    if (name && !is_help_option(name)) {

        error_report("Unsupported machine type");

        error_printf("Use -machine help to list supported machines!\n");

    } else {

        printf("Supported machines are:\n");

        for (el = machines; el; el = el->next) {

            MachineClass *mc = el->data;

            if (mc->alias) {

                printf("%-20s %s (alias of %s)\n", mc->alias, mc->desc, mc->name);

            }

            printf("%-20s %s%s\n", mc->name, mc->desc,

                   mc->is_default ? " (default)" : "");

        }

    }

    g_slist_free(machines);

    exit(!name || !is_help_option(name));

}


M48t59State *m48t59_init(qemu_irq IRQ, target_phys_addr_t mem_base,

                         uint32_t io_base, uint16_t size, int model)

{

    DeviceState *dev;

    SysBusDevice *s;

    M48t59SysBusState *d;

    M48t59State *state;

    dev = qdev_create(NULL, "m48t59");

    qdev_prop_set_uint32(dev, "model", model);

    qdev_prop_set_uint32(dev, "size", size);

    qdev_prop_set_uint32(dev, "io_base", io_base);

    qdev_init_nofail(dev);

    s = sysbus_from_qdev(dev);

    d = FROM_SYSBUS(M48t59SysBusState, s);

    state = &d->state;

    sysbus_connect_irq(s, 0, IRQ);

    if (io_base != 0) {

        register_ioport_read(io_base, 0x04, 1, NVRAM_readb, state);

        register_ioport_write(io_base, 0x04, 1, NVRAM_writeb, state);

    }

    if (mem_base != 0) {

        sysbus_mmio_map(s, 0, mem_base);

    }

    return state;

}


static void virtio_gpu_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)

{

    VirtIOGPUPCI *vgpu = VIRTIO_GPU_PCI(vpci_dev);

    VirtIOGPU *g = &vgpu->vdev;

    DeviceState *vdev = DEVICE(&vgpu->vdev);

    int i;

    qdev_set_parent_bus(vdev, BUS(&vpci_dev->bus));

    /* force virtio-1.0 */

    vpci_dev->flags &= ~VIRTIO_PCI_FLAG_DISABLE_MODERN;

    vpci_dev->flags |= VIRTIO_PCI_FLAG_DISABLE_LEGACY;

    object_property_set_bool(OBJECT(vdev), true, "realized", errp);

    for (i = 0; i < g->conf.max_outputs; i++) {

        object_property_set_link(OBJECT(g->scanout[i].con),

                                 OBJECT(vpci_dev),

                                 "device", errp);

    }

}


void program_interrupt(CPUS390XState *env, uint32_t code, int ilen)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    qemu_log_mask(CPU_LOG_INT, "program interrupt at %#" PRIx64 "\n",

                  env->psw.addr);

    if (kvm_enabled()) {

        kvm_s390_program_interrupt(cpu, code);

    } else if (tcg_enabled()) {

        tcg_s390_program_interrupt(env, code, ilen);

    } else {

        g_assert_not_reached();

    }

}


static void address_space_update_ioeventfds(AddressSpace *as)

{

    FlatView *view;

    FlatRange *fr;

    unsigned ioeventfd_nb = 0;

    MemoryRegionIoeventfd *ioeventfds = NULL;

    AddrRange tmp;

    unsigned i;

    view = as->current_map;

    FOR_EACH_FLAT_RANGE(fr, view) {

        for (i = 0; i < fr->mr->ioeventfd_nb; ++i) {

            tmp = addrrange_shift(fr->mr->ioeventfds[i].addr,

                                  int128_sub(fr->addr.start,

                                             int128_make64(fr->offset_in_region)));

            if (addrrange_intersects(fr->addr, tmp)) {

                ++ioeventfd_nb;

                ioeventfds = g_realloc(ioeventfds,

                                          ioeventfd_nb * sizeof(*ioeventfds));

                ioeventfds[ioeventfd_nb-1] = fr->mr->ioeventfds[i];

                ioeventfds[ioeventfd_nb-1].addr = tmp;

            }

        }

    }

    address_space_add_del_ioeventfds(as, ioeventfds, ioeventfd_nb,

                                     as->ioeventfds, as->ioeventfd_nb);

    g_free(as->ioeventfds);

    as->ioeventfds = ioeventfds;

    as->ioeventfd_nb = ioeventfd_nb;

}


static int configure_filters(AVInputStream *ist, AVOutputStream *ost)

{

    AVFilterContext *curr_filter;

    /** filter graph containing all filters including input & output */

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

    AVCodecContext *icodec = ist->st->codec;

    char args[255];

    filt_graph_all = av_mallocz(sizeof(AVFilterGraph));

    if(!(ist->input_video_filter = avfilter_open(avfilter_get_by_name("buffer"), "src")))

        return -1;

    if(!(ist->out_video_filter = avfilter_open(&output_filter, "out")))

        return -1;

    snprintf(args, 255, "%d:%d:%d", ist->st->codec->width,

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

    if(avfilter_init_filter(ist->input_video_filter, args, NULL))

        return -1;

    if(avfilter_init_filter(ist->out_video_filter, NULL, &codec->pix_fmt))

        return -1;

    /* add input and output filters to the overall graph */

    avfilter_graph_add_filter(filt_graph_all, ist->input_video_filter);

    avfilter_graph_add_filter(filt_graph_all, ist->out_video_filter);

    curr_filter = ist->input_video_filter;

    if(ost->video_crop) {

        char crop_args[255];

        AVFilterContext *filt_crop;

        snprintf(crop_args, 255, "%d:%d:%d:%d", ost->leftBand, ost->topBand,

                 codec->width -  (frame_padleft + frame_padright),

                 codec->height - (frame_padtop + frame_padbottom));

        filt_crop = avfilter_open(avfilter_get_by_name("crop"), NULL);

        if (!filt_crop)

            return -1;

        if (avfilter_init_filter(filt_crop, crop_args, NULL))

            return -1;

        if (avfilter_link(curr_filter, 0, filt_crop, 0))

            return -1;

        curr_filter = filt_crop;

        avfilter_graph_add_filter(filt_graph_all, curr_filter);

    }

    if((codec->width !=

        icodec->width - (frame_leftBand + frame_rightBand) +

        (frame_padleft + frame_padright)) ||

       (codec->height != icodec->height - (frame_topBand  + frame_bottomBand) +

        (frame_padtop + frame_padbottom))) {

        char scale_args[255];

        AVFilterContext *filt_scale;

        snprintf(scale_args, 255, "%d:%d:flags=0x%X",

                 codec->width  - (frame_padleft + frame_padright),

                 codec->height - (frame_padtop  + frame_padbottom),

                 (int)av_get_int(sws_opts, "sws_flags", NULL));

        filt_scale = avfilter_open(avfilter_get_by_name("scale"), NULL);

        if (!filt_scale)

            return -1;

        if (avfilter_init_filter(filt_scale, scale_args, NULL))

            return -1;

        if (avfilter_link(curr_filter, 0, filt_scale, 0))

            return -1;

        curr_filter = filt_scale;

        avfilter_graph_add_filter(filt_graph_all, curr_filter);

    }

    if(vfilters) {

        AVFilterInOut *outputs = av_malloc(sizeof(AVFilterInOut));

        AVFilterInOut *inputs  = av_malloc(sizeof(AVFilterInOut));

        outputs->name    = av_strdup("in");

        outputs->filter  = curr_filter;

        outputs->pad_idx = 0;

        outputs->next    = NULL;

        inputs->name    = av_strdup("out");

        inputs->filter  = ist->out_video_filter;

        inputs->pad_idx = 0;

        inputs->next    = NULL;

        if (avfilter_graph_parse(filt_graph_all, vfilters, inputs, outputs, NULL) < 0)

            return -1;

        av_freep(&vfilters);

    } else {

        if(avfilter_link(curr_filter, 0, ist->out_video_filter, 0) < 0)

            return -1;

    }

    {

        char scale_sws_opts[128];

        snprintf(scale_sws_opts, sizeof(scale_sws_opts), "flags=0x%X", (int)av_get_int(sws_opts, "sws_flags", NULL));

        filt_graph_all->scale_sws_opts = av_strdup(scale_sws_opts);

    }

    /* configure all the filter links */

    if(avfilter_graph_check_validity(filt_graph_all, NULL))

        return -1;

    if(avfilter_graph_config_formats(filt_graph_all, NULL))

        return -1;

    if(avfilter_graph_config_links(filt_graph_all, NULL))

        return -1;

    codec->width = ist->out_video_filter->inputs[0]->w;

    codec->height = ist->out_video_filter->inputs[0]->h;

    return 0;

}


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

{

    QObject *data;

    int devfn;

    if (do_pcie_aer_inject_error(mon, qdict, &data) < 0) {

        return;

    }

    assert(qobject_type(data) == QTYPE_QDICT);

    qdict = qobject_to_qdict(data);

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

    monitor_printf(mon, "OK id: %s root bus: %s, bus: %x devfn: %x.%x\n",

                   qdict_get_str(qdict, "id"),

                   qdict_get_str(qdict, "root_bus"),

                   (int) qdict_get_int(qdict, "bus"),

                   PCI_SLOT(devfn), PCI_FUNC(devfn));

}


static void spapr_reallocate_hpt(sPAPRMachineState *spapr, int shift,

                                 Error **errp)

{

    long rc;

    /* Clean up any HPT info from a previous boot */

    g_free(spapr->htab);

    spapr->htab = NULL;

    spapr->htab_shift = 0;

    close_htab_fd(spapr);

    rc = kvmppc_reset_htab(shift);

    if (rc < 0) {

        /* kernel-side HPT needed, but couldn't allocate one */

        error_setg_errno(errp, errno,

                         "Failed to allocate KVM HPT of order %d (try smaller maxmem?)",

                         shift);

        /* This is almost certainly fatal, but if the caller really

         * wants to carry on with shift == 0, it's welcome to try */

    } else if (rc > 0) {

        /* kernel-side HPT allocated */

        if (rc != shift) {

            error_setg(errp,

                       "Requested order %d HPT, but kernel allocated order %ld (try smaller maxmem?)",

                       shift, rc);

        }

        spapr->htab_shift = shift;

        kvmppc_kern_htab = true;

    } else {

        /* kernel-side HPT not needed, allocate in userspace instead */

        size_t size = 1ULL << shift;

        int i;

        spapr->htab = qemu_memalign(size, size);

        if (!spapr->htab) {

            error_setg_errno(errp, errno,

                             "Could not allocate HPT of order %d", shift);

            return;

        }

        memset(spapr->htab, 0, size);

        spapr->htab_shift = shift;

        kvmppc_kern_htab = false;

        for (i = 0; i < size / HASH_PTE_SIZE_64; i++) {

            DIRTY_HPTE(HPTE(spapr->htab, i));

        }

    }

}


static av_cold int atrac3_decode_init(AVCodecContext *avctx)

{

    int i, ret;

    int version, delay, samples_per_frame, frame_factor;

    const uint8_t *edata_ptr = avctx->extradata;

    ATRAC3Context *q = avctx->priv_data;

    if (avctx->channels <= 0 || avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Channel configuration error!\n");

        return AVERROR(EINVAL);

    }

    /* Take care of the codec-specific extradata. */

    if (avctx->extradata_size == 14) {

        /* Parse the extradata, WAV format */

        av_log(avctx, AV_LOG_DEBUG, "[0-1] %d\n",

               bytestream_get_le16(&edata_ptr));  // Unknown value always 1

        edata_ptr += 4;                             // samples per channel

        q->coding_mode = bytestream_get_le16(&edata_ptr);

        av_log(avctx, AV_LOG_DEBUG,"[8-9] %d\n",

               bytestream_get_le16(&edata_ptr));  //Dupe of coding mode

        frame_factor = bytestream_get_le16(&edata_ptr);  // Unknown always 1

        av_log(avctx, AV_LOG_DEBUG,"[12-13] %d\n",

               bytestream_get_le16(&edata_ptr));  // Unknown always 0

        /* setup */

        samples_per_frame    = SAMPLES_PER_FRAME * avctx->channels;

        version              = 4;

        delay                = 0x88E;

        q->coding_mode       = q->coding_mode ? JOINT_STEREO : STEREO;

        q->scrambled_stream  = 0;

        if (avctx->block_align !=  96 * avctx->channels * frame_factor &&

            avctx->block_align != 152 * avctx->channels * frame_factor &&

            avctx->block_align != 192 * avctx->channels * frame_factor) {

            av_log(avctx, AV_LOG_ERROR, "Unknown frame/channel/frame_factor "

                   "configuration %d/%d/%d\n", avctx->block_align,

                   avctx->channels, frame_factor);

            return AVERROR_INVALIDDATA;

        }

    } else if (avctx->extradata_size == 10) {

        /* Parse the extradata, RM format. */

        version                = bytestream_get_be32(&edata_ptr);

        samples_per_frame      = bytestream_get_be16(&edata_ptr);

        delay                  = bytestream_get_be16(&edata_ptr);

        q->coding_mode         = bytestream_get_be16(&edata_ptr);

        q->scrambled_stream    = 1;

    } else {

        av_log(NULL, AV_LOG_ERROR, "Unknown extradata size %d.\n",

               avctx->extradata_size);

        return AVERROR(EINVAL);

    }

    /* Check the extradata */

    if (version != 4) {

        av_log(avctx, AV_LOG_ERROR, "Version %d != 4.\n", version);

        return AVERROR_INVALIDDATA;

    }

    if (samples_per_frame != SAMPLES_PER_FRAME &&

        samples_per_frame != SAMPLES_PER_FRAME * 2) {

        av_log(avctx, AV_LOG_ERROR, "Unknown amount of samples per frame %d.\n",

               samples_per_frame);

        return AVERROR_INVALIDDATA;

    }

    if (delay != 0x88E) {

        av_log(avctx, AV_LOG_ERROR, "Unknown amount of delay %x != 0x88E.\n",

               delay);

        return AVERROR_INVALIDDATA;

    }

    if (q->coding_mode == STEREO)

        av_log(avctx, AV_LOG_DEBUG, "Normal stereo detected.\n");

    else if (q->coding_mode == JOINT_STEREO) {

        if (avctx->channels != 2)

            return AVERROR_INVALIDDATA;

        av_log(avctx, AV_LOG_DEBUG, "Joint stereo detected.\n");

    } else {

        av_log(avctx, AV_LOG_ERROR, "Unknown channel coding mode %x!\n",

               q->coding_mode);

        return AVERROR_INVALIDDATA;

    }

    if (avctx->block_align >= UINT_MAX / 2)

        return AVERROR(EINVAL);

    q->decoded_bytes_buffer = av_mallocz(FFALIGN(avctx->block_align, 4) +

                                         FF_INPUT_BUFFER_PADDING_SIZE);

    if (q->decoded_bytes_buffer == NULL)

        return AVERROR(ENOMEM);

    avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;

    /* initialize the MDCT transform */

    if ((ret = ff_mdct_init(&q->mdct_ctx, 9, 1, 1.0 / 32768)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing MDCT\n");

        av_freep(&q->decoded_bytes_buffer);

        return ret;

    }

    /* init the joint-stereo decoding data */

    q->weighting_delay[0] = 0;

    q->weighting_delay[1] = 7;

    q->weighting_delay[2] = 0;

    q->weighting_delay[3] = 7;

    q->weighting_delay[4] = 0;

    q->weighting_delay[5] = 7;

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

        q->matrix_coeff_index_prev[i] = 3;

        q->matrix_coeff_index_now[i]  = 3;

        q->matrix_coeff_index_next[i] = 3;

    }

    ff_atrac_init_gain_compensation(&q->gainc_ctx, 4, 3);

    avpriv_float_dsp_init(&q->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    ff_fmt_convert_init(&q->fmt_conv, avctx);

    q->units = av_mallocz(sizeof(*q->units) * avctx->channels);

    if (!q->units) {

        atrac3_decode_close(avctx);

        return AVERROR(ENOMEM);

    }

    return 0;

}


static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)

{

    OutputStream *ost;

    AVStream *st = avformat_new_stream(oc, NULL);

    int idx      = oc->nb_streams - 1, ret = 0;

    const char *bsfs = NULL, *time_base = NULL;

    char *next, *codec_tag = NULL;

    double qscale = -1;

    int i;

    if (!st) {

        av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");

        exit_program(1);

    }

    if (oc->nb_streams - 1 < o->nb_streamid_map)

        st->id = o->streamid_map[oc->nb_streams - 1];

    GROW_ARRAY(output_streams, nb_output_streams);

    if (!(ost = av_mallocz(sizeof(*ost))))

        exit_program(1);

    output_streams[nb_output_streams - 1] = ost;

    ost->file_index = nb_output_files - 1;

    ost->index      = idx;

    ost->st         = st;

    st->codecpar->codec_type = type;

    ret = choose_encoder(o, oc, ost);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error selecting an encoder for stream "

               "%d:%d\n", ost->file_index, ost->index);

        exit_program(1);

    }

    ost->enc_ctx = avcodec_alloc_context3(ost->enc);

    if (!ost->enc_ctx) {

        av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding context.\n");

        exit_program(1);

    }

    ost->enc_ctx->codec_type = type;

    ost->ref_par = avcodec_parameters_alloc();

    if (!ost->ref_par) {

        av_log(NULL, AV_LOG_ERROR, "Error allocating the encoding parameters.\n");

        exit_program(1);

    }

    if (ost->enc) {

        AVIOContext *s = NULL;

        char *buf = NULL, *arg = NULL, *preset = NULL;

        ost->encoder_opts  = filter_codec_opts(o->g->codec_opts, ost->enc->id, oc, st, ost->enc);

        MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);

        if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {

            do  {

                buf = get_line(s);

                if (!buf[0] || buf[0] == '#') {

                    av_free(buf);

                    continue;

                }

                if (!(arg = strchr(buf, '='))) {

                    av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");

                    exit_program(1);

                }

                *arg++ = 0;

                av_dict_set(&ost->encoder_opts, buf, arg, AV_DICT_DONT_OVERWRITE);

                av_free(buf);

            } while (!s->eof_reached);

            avio_closep(&s);

        }

        if (ret) {

            av_log(NULL, AV_LOG_FATAL,

                   "Preset %s specified for stream %d:%d, but could not be opened.\n",

                   preset, ost->file_index, ost->index);

            exit_program(1);

        }

    } else {

        ost->encoder_opts = filter_codec_opts(o->g->codec_opts, AV_CODEC_ID_NONE, oc, st, NULL);

    }

    MATCH_PER_STREAM_OPT(time_bases, str, time_base, oc, st);

    if (time_base) {

        AVRational q;

        if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||

            q.num <= 0 || q.den <= 0) {

            av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);

            exit_program(1);

        }

        st->time_base = q;

    }

    MATCH_PER_STREAM_OPT(enc_time_bases, str, time_base, oc, st);

    if (time_base) {

        AVRational q;

        if (av_parse_ratio(&q, time_base, INT_MAX, 0, NULL) < 0 ||

            q.den <= 0) {

            av_log(NULL, AV_LOG_FATAL, "Invalid time base: %s\n", time_base);

            exit_program(1);

        }

        ost->enc_timebase = q;

    }

    ost->max_frames = INT64_MAX;

    MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);

    for (i = 0; i<o->nb_max_frames; i++) {

        char *p = o->max_frames[i].specifier;

        if (!*p && type != AVMEDIA_TYPE_VIDEO) {

            av_log(NULL, AV_LOG_WARNING, "Applying unspecific -frames to non video streams, maybe you meant -vframes ?\n");

            break;

        }

    }

    ost->copy_prior_start = -1;

    MATCH_PER_STREAM_OPT(copy_prior_start, i, ost->copy_prior_start, oc ,st);

    MATCH_PER_STREAM_OPT(bitstream_filters, str, bsfs, oc, st);

    while (bsfs && *bsfs) {

        const AVBitStreamFilter *filter;

        char *bsf, *bsf_options_str, *bsf_name;

        bsf = av_get_token(&bsfs, ",");

        if (!bsf)

            exit_program(1);

        bsf_name = av_strtok(bsf, "=", &bsf_options_str);

        if (!bsf_name)

            exit_program(1);

        filter = av_bsf_get_by_name(bsf_name);

        if (!filter) {

            av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf_name);

            exit_program(1);

        }

        ost->bsf_ctx = av_realloc_array(ost->bsf_ctx,

                                        ost->nb_bitstream_filters + 1,

                                        sizeof(*ost->bsf_ctx));

        if (!ost->bsf_ctx)

            exit_program(1);

        ret = av_bsf_alloc(filter, &ost->bsf_ctx[ost->nb_bitstream_filters]);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error allocating a bitstream filter context\n");

            exit_program(1);

        }

        ost->nb_bitstream_filters++;

        if (bsf_options_str && filter->priv_class) {

            const AVOption *opt = av_opt_next(ost->bsf_ctx[ost->nb_bitstream_filters-1]->priv_data, NULL);

            const char * shorthand[2] = {NULL};

            if (opt)

                shorthand[0] = opt->name;

            ret = av_opt_set_from_string(ost->bsf_ctx[ost->nb_bitstream_filters-1]->priv_data, bsf_options_str, shorthand, "=", ":");

            if (ret < 0) {

                av_log(NULL, AV_LOG_ERROR, "Error parsing options for bitstream filter %s\n", bsf_name);

                exit_program(1);

            }

        }

        av_freep(&bsf);

        if (*bsfs)

            bsfs++;

    }

    if (ost->nb_bitstream_filters) {

        ost->bsf_extradata_updated = av_mallocz_array(ost->nb_bitstream_filters, sizeof(*ost->bsf_extradata_updated));

        if (!ost->bsf_extradata_updated) {

            av_log(NULL, AV_LOG_FATAL, "Bitstream filter memory allocation failed\n");

            exit_program(1);

        }

    }

    MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);

    if (codec_tag) {

        uint32_t tag = strtol(codec_tag, &next, 0);

        if (*next)

            tag = AV_RL32(codec_tag);

        ost->st->codecpar->codec_tag =

        ost->enc_ctx->codec_tag = tag;

    }

    MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);

    if (qscale >= 0) {

        ost->enc_ctx->flags |= AV_CODEC_FLAG_QSCALE;

        ost->enc_ctx->global_quality = FF_QP2LAMBDA * qscale;

    }

    MATCH_PER_STREAM_OPT(disposition, str, ost->disposition, oc, st);

    ost->disposition = av_strdup(ost->disposition);

    ost->max_muxing_queue_size = 128;

    MATCH_PER_STREAM_OPT(max_muxing_queue_size, i, ost->max_muxing_queue_size, oc, st);

    ost->max_muxing_queue_size *= sizeof(AVPacket);

    if (oc->oformat->flags & AVFMT_GLOBALHEADER)

        ost->enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    av_dict_copy(&ost->sws_dict, o->g->sws_dict, 0);

    av_dict_copy(&ost->swr_opts, o->g->swr_opts, 0);

    if (ost->enc && av_get_exact_bits_per_sample(ost->enc->id) == 24)

        av_dict_set(&ost->swr_opts, "output_sample_bits", "24", 0);

    av_dict_copy(&ost->resample_opts, o->g->resample_opts, 0);

    ost->source_index = source_index;

    if (source_index >= 0) {

        ost->sync_ist = input_streams[source_index];

        input_streams[source_index]->discard = 0;

        input_streams[source_index]->st->discard = input_streams[source_index]->user_set_discard;

    }

    ost->last_mux_dts = AV_NOPTS_VALUE;

    ost->muxing_queue = av_fifo_alloc(8 * sizeof(AVPacket));

    if (!ost->muxing_queue)

        exit_program(1);

    return ost;

}


static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,

                                      void *data, int *data_size,

                                      uint8_t *buf, int buf_size)

{

    /* Note, the only difference between the 15Bpp and 16Bpp */

    /* Format is the pixel format, the packets are processed the same. */

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

    int stream_ptr = 0;

    int pixel_ptr;

    unsigned char palette_idx1;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j;

    int lines;

    int compressed_lines;

    signed short line_packets;

    int y_ptr;

    int byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    int pixel;

    int pixel_limit;

    s->frame.reference = 1;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame) < 0) {

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

        return -1;

    }

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

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

    frame_size = LE_32(&buf[stream_ptr]);

    stream_ptr += 6;  /* skip the magic number */

    num_chunks = LE_16(&buf[stream_ptr]);

    stream_ptr += 10;  /* skip padding */

    frame_size -= 16;

    /* iterate through the chunks */

    while ((frame_size > 0) && (num_chunks > 0)) {

        chunk_size = LE_32(&buf[stream_ptr]);

        stream_ptr += 4;

        chunk_type = LE_16(&buf[stream_ptr]);

        stream_ptr += 2;

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

            /* For some reason, it seems that non-paletised flics do include one of these */

            /* chunks in their first frame.  Why i do not know, it seems rather extraneous */

/*            av_log(avctx, AV_LOG_ERROR, "Unexpected Palette chunk %d in non-paletised FLC\n",chunk_type);*/

            stream_ptr = stream_ptr + chunk_size - 6;

            break;

        case FLI_DELTA:

        case FLI_DTA_LC:

            y_ptr = 0;

            compressed_lines = LE_16(&buf[stream_ptr]);

            stream_ptr += 2;

            while (compressed_lines > 0) {

                line_packets = LE_16(&buf[stream_ptr]);

                stream_ptr += 2;

                if (line_packets < 0) {

                    line_packets = -line_packets;

                    y_ptr += line_packets * s->frame.linesize[0];

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    pixel_countdown = s->avctx->width;

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

                        /* account for the skip bytes */

                        pixel_skip = buf[stream_ptr++];

                        pixel_ptr += (pixel_skip*2); /* Pixel is 2 bytes wide */

                        pixel_countdown -= pixel_skip;

                        byte_run = (signed char)(buf[stream_ptr++]);

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            pixel    = LE_16(&buf[stream_ptr]);

                            stream_ptr += 2;

                            CHECK_PIXEL_PTR(byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {

                                *((signed short*)(&pixels[pixel_ptr])) = pixel;

                                pixel_ptr += 2;

                            }

                        } else {

                            CHECK_PIXEL_PTR(byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                *((signed short*)(&pixels[pixel_ptr])) = LE_16(&buf[stream_ptr]);

                                stream_ptr += 2;

                                pixel_ptr += 2;

                            }

                        }

                    }

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

                }

            }

            break;

        case FLI_LC:

            av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-paletised FLC\n");

            stream_ptr = stream_ptr + chunk_size - 6;

            break;

        case FLI_BLACK:

            /* set the whole frame to 0x0000 which is balck in both 15Bpp and 16Bpp modes. */

            memset(pixels, 0x0000,

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

            break;

        case FLI_BRUN:

            y_ptr = 0;

            for (lines = 0; lines < s->avctx->height; lines++) {

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                stream_ptr++;

                pixel_countdown = (s->avctx->width * 2);

                while (pixel_countdown > 0) {

                    byte_run = (signed char)(buf[stream_ptr++]);

                    if (byte_run > 0) {

                        palette_idx1 = buf[stream_ptr++];

                        CHECK_PIXEL_PTR(byte_run);

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    } else {  /* copy bytes if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(byte_run);

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

                            palette_idx1 = buf[stream_ptr++];

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    }

                }

                /* Now FLX is strange, in that it is "byte" as opposed to "pixel" run length compressed.

                 * This doesnt give us any good oportunity to perform word endian conversion

                 * during decompression. So if its requried (ie, this isnt a LE target, we do

                 * a second pass over the line here, swapping the bytes.

                 */

                pixel = 0xFF00;

                if (0xFF00 != LE_16(&pixel)) /* Check if its not an LE Target */

                {

                  pixel_ptr = y_ptr;

                  pixel_countdown = s->avctx->width;

                  while (pixel_countdown > 0) {

                    *((signed short*)(&pixels[pixel_ptr])) = LE_16(&buf[pixel_ptr]);

                    pixel_ptr += 2;

                  }

                }

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

            }

            break;

        case FLI_DTA_BRUN:

            y_ptr = 0;

            for (lines = 0; lines < s->avctx->height; lines++) {

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                stream_ptr++;

                pixel_countdown = s->avctx->width; /* Width is in pixels, not bytes */

                while (pixel_countdown > 0) {

                    byte_run = (signed char)(buf[stream_ptr++]);

                    if (byte_run > 0) {

                        pixel    = LE_16(&buf[stream_ptr]);

                        stream_ptr += 2;

                        CHECK_PIXEL_PTR(byte_run);

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

                            *((signed short*)(&pixels[pixel_ptr])) = pixel;

                            pixel_ptr += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    } else {  /* copy pixels if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(byte_run);

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

                            *((signed short*)(&pixels[pixel_ptr])) = LE_16(&buf[stream_ptr]);

                            stream_ptr += 2;

                            pixel_ptr  += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    }

                }

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

            }

            break;

        case FLI_COPY:

        case FLI_DTA_COPY:

            /* copy the chunk (uncompressed frame) */

            if (chunk_size - 6 > (unsigned int)(s->avctx->width * s->avctx->height)*2) {

                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \

                       "bigger than image, skipping chunk\n", chunk_size - 6);

                stream_ptr += chunk_size - 6;

            } else {

                for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;

                     y_ptr += s->frame.linesize[0]) {

                    pixel_countdown = s->avctx->width;

                    pixel_ptr = 0;

                    while (pixel_countdown > 0) {

                      *((signed short*)(&pixels[y_ptr + pixel_ptr])) = LE_16(&buf[stream_ptr+pixel_ptr]);

                      pixel_ptr += 2;

                      pixel_countdown--;

                    }

                    stream_ptr += s->avctx->width*2;

                }

            }

            break;

        case FLI_MINI:

            /* some sort of a thumbnail? disregard this chunk... */

            stream_ptr += chunk_size - 6;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);

            break;

        }

        frame_size -= chunk_size;

        num_chunks--;

    }

    /* by the end of the chunk, the stream ptr should equal the frame

     * size (minus 1, possibly); if it doesn't, issue a warning */

    if ((stream_ptr != buf_size) && (stream_ptr != buf_size - 1))

        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \

               "and final chunk ptr = %d\n", buf_size, stream_ptr);

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    return buf_size;

}


static void *qemu_tcg_rr_cpu_thread_fn(void *arg)

{

    CPUState *cpu = arg;

    rcu_register_thread();

    qemu_thread_get_self(cpu->thread);

    CPU_FOREACH(cpu) {

        cpu->thread_id = qemu_get_thread_id();

        cpu->created = true;

        cpu->can_do_io = 1;

    }

    qemu_cond_signal(&qemu_cpu_cond);

    /* wait for initial kick-off after machine start */

    while (first_cpu->stopped) {

        qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);

        /* process any pending work */

        CPU_FOREACH(cpu) {

            current_cpu = cpu;

            qemu_wait_io_event_common(cpu);

        }

    }

    start_tcg_kick_timer();

    cpu = first_cpu;

    /* process any pending work */

    cpu->exit_request = 1;

    while (1) {

        /* Account partial waits to QEMU_CLOCK_VIRTUAL.  */

        qemu_account_warp_timer();

        if (!cpu) {

            cpu = first_cpu;

        }

        while (cpu && !cpu->queued_work_first && !cpu->exit_request) {

            atomic_mb_set(&tcg_current_rr_cpu, cpu);

            current_cpu = cpu;

            qemu_clock_enable(QEMU_CLOCK_VIRTUAL,

                              (cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);

            if (cpu_can_run(cpu)) {

                int r;

                r = tcg_cpu_exec(cpu);

                if (r == EXCP_DEBUG) {

                    cpu_handle_guest_debug(cpu);

                }

            } else if (cpu->stop) {

                if (cpu->unplug) {

                    cpu = CPU_NEXT(cpu);

                }

            }

            cpu = CPU_NEXT(cpu);

        } /* while (cpu && !cpu->exit_request).. */

        /* Does not need atomic_mb_set because a spurious wakeup is okay.  */

        atomic_set(&tcg_current_rr_cpu, NULL);

        if (cpu && cpu->exit_request) {

            atomic_mb_set(&cpu->exit_request, 0);

        }

        handle_icount_deadline();

        qemu_tcg_wait_io_event(cpu ? cpu : QTAILQ_FIRST(&cpus));

        deal_with_unplugged_cpus();

    }

    return NULL;

}


static int decode_slice_header(H264Context *h){

    MpegEncContext * const s = &h->s;

    int first_mb_in_slice, pps_id;

    int num_ref_idx_active_override_flag;

    static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};

    int slice_type;

    int default_ref_list_done = 0;

    s->current_picture.reference= h->nal_ref_idc != 0;

    s->dropable= h->nal_ref_idc == 0;

    first_mb_in_slice= get_ue_golomb(&s->gb);

    slice_type= get_ue_golomb(&s->gb);

    if(slice_type > 9){

        av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);

        return -1;

    }

    if(slice_type > 4){

        slice_type -= 5;

        h->slice_type_fixed=1;

    }else

        h->slice_type_fixed=0;

    slice_type= slice_type_map[ slice_type ];

    if (slice_type == I_TYPE

        || (h->slice_num != 0 && slice_type == h->slice_type) ) {

        default_ref_list_done = 1;

    }

    h->slice_type= slice_type;

    s->pict_type= h->slice_type; // to make a few old func happy, it's wrong though

    pps_id= get_ue_golomb(&s->gb);

    if(pps_id>255){

        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");

        return -1;

    }

    h->pps= h->pps_buffer[pps_id];

    if(h->pps.slice_group_count == 0){

        av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");

        return -1;

    }

    h->sps= h->sps_buffer[ h->pps.sps_id ];

    if(h->sps.log2_max_frame_num == 0){

        av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");

        return -1;

    }

    if(h->dequant_coeff_pps != pps_id){

        h->dequant_coeff_pps = pps_id;

        init_dequant_tables(h);

    }

    s->mb_width= h->sps.mb_width;

    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);

    h->b_stride=  s->mb_width*4;

    h->b8_stride= s->mb_width*2;

    s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );

    if(h->sps.frame_mbs_only_flag)

        s->height= 16*s->mb_height - 2*(h->sps.crop_top  + h->sps.crop_bottom);

    else

        s->height= 16*s->mb_height - 4*(h->sps.crop_top  + h->sps.crop_bottom); //FIXME recheck

    if (s->context_initialized

        && (   s->width != s->avctx->width || s->height != s->avctx->height)) {

        free_tables(h);

        MPV_common_end(s);

    }

    if (!s->context_initialized) {

        if (MPV_common_init(s) < 0)

            return -1;

        if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly

            memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));

            memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));

        }else{

            int i;

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

#define T(x) (x>>2) | ((x<<2) & 0xF)

                h->zigzag_scan[i] = T(zigzag_scan[i]);

                h-> field_scan[i] = T( field_scan[i]);

#undef T

            }

        }

        if(s->dsp.h264_idct8_add == ff_h264_idct8_add_c){

            memcpy(h->zigzag_scan8x8,       zigzag_scan8x8,       64*sizeof(uint8_t));

            memcpy(h->zigzag_scan8x8_cavlc, zigzag_scan8x8_cavlc, 64*sizeof(uint8_t));

            memcpy(h->field_scan8x8,        field_scan8x8,        64*sizeof(uint8_t));

            memcpy(h->field_scan8x8_cavlc,  field_scan8x8_cavlc,  64*sizeof(uint8_t));

        }else{

            int i;

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

#define T(x) (x>>3) | ((x&7)<<3)

                h->zigzag_scan8x8[i]       = T(zigzag_scan8x8[i]);

                h->zigzag_scan8x8_cavlc[i] = T(zigzag_scan8x8_cavlc[i]);

                h->field_scan8x8[i]        = T(field_scan8x8[i]);

                h->field_scan8x8_cavlc[i]  = T(field_scan8x8_cavlc[i]);

#undef T

            }

        }

        if(h->sps.transform_bypass){ //FIXME same ugly

            h->zigzag_scan_q0          = zigzag_scan;

            h->zigzag_scan8x8_q0       = zigzag_scan8x8;

            h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;

            h->field_scan_q0           = field_scan;

            h->field_scan8x8_q0        = field_scan8x8;

            h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;

        }else{

            h->zigzag_scan_q0          = h->zigzag_scan;

            h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;

            h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;

            h->field_scan_q0           = h->field_scan;

            h->field_scan8x8_q0        = h->field_scan8x8;

            h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;

        }

        alloc_tables(h);

        s->avctx->width = s->width;

        s->avctx->height = s->height;

        s->avctx->sample_aspect_ratio= h->sps.sar;

        if(!s->avctx->sample_aspect_ratio.den)

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

        if(h->sps.timing_info_present_flag){

            s->avctx->time_base= (AVRational){h->sps.num_units_in_tick * 2, h->sps.time_scale};

            if(h->x264_build > 0 && h->x264_build < 44)

                s->avctx->time_base.den *= 2;

            av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,

                      s->avctx->time_base.num, s->avctx->time_base.den, 1<<30);

        }

    }

    if(h->slice_num == 0){

        if(frame_start(h) < 0)

            return -1;

    }

    s->current_picture_ptr->frame_num= //FIXME frame_num cleanup

    h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);

    h->mb_mbaff = 0;

    h->mb_aff_frame = 0;

    if(h->sps.frame_mbs_only_flag){

        s->picture_structure= PICT_FRAME;

    }else{

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

            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag

            av_log(h->s.avctx, AV_LOG_ERROR, "PAFF interlacing is not implemented\n");

        } else {

            s->picture_structure= PICT_FRAME;

            h->mb_aff_frame = h->sps.mb_aff;

        }

    }

    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;

    s->resync_mb_y = s->mb_y = (first_mb_in_slice / s->mb_width) << h->mb_aff_frame;

    if(s->mb_y >= s->mb_height){

        return -1;

    }

    if(s->picture_structure==PICT_FRAME){

        h->curr_pic_num=   h->frame_num;

        h->max_pic_num= 1<< h->sps.log2_max_frame_num;

    }else{

        h->curr_pic_num= 2*h->frame_num;

        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);

    }

    if(h->nal_unit_type == NAL_IDR_SLICE){

        get_ue_golomb(&s->gb); /* idr_pic_id */

    }

    if(h->sps.poc_type==0){

        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);

        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){

            h->delta_poc_bottom= get_se_golomb(&s->gb);

        }

    }

    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){

        h->delta_poc[0]= get_se_golomb(&s->gb);

        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)

            h->delta_poc[1]= get_se_golomb(&s->gb);

    }

    init_poc(h);

    if(h->pps.redundant_pic_cnt_present){

        h->redundant_pic_count= get_ue_golomb(&s->gb);

    }

    //set defaults, might be overriden a few line later

    h->ref_count[0]= h->pps.ref_count[0];

    h->ref_count[1]= h->pps.ref_count[1];

    if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){

        if(h->slice_type == B_TYPE){

            h->direct_spatial_mv_pred= get_bits1(&s->gb);

            if(h->sps.mb_aff && h->direct_spatial_mv_pred)

                av_log(h->s.avctx, AV_LOG_ERROR, "MBAFF + spatial direct mode is not implemented\n");

        }

        num_ref_idx_active_override_flag= get_bits1(&s->gb);

        if(num_ref_idx_active_override_flag){

            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;

            if(h->slice_type==B_TYPE)

                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;

            if(h->ref_count[0] > 32 || h->ref_count[1] > 32){

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

                return -1;

            }

        }

    }

    if(!default_ref_list_done){

        fill_default_ref_list(h);

    }

    if(decode_ref_pic_list_reordering(h) < 0)

        return -1;

    if(   (h->pps.weighted_pred          && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE ))

       || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )

        pred_weight_table(h);

    else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)

        implicit_weight_table(h);

    else

        h->use_weight = 0;

    if(s->current_picture.reference)

        decode_ref_pic_marking(h);

    if(FRAME_MBAFF)

        fill_mbaff_ref_list(h);

    if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac )

        h->cabac_init_idc = get_ue_golomb(&s->gb);

    h->last_qscale_diff = 0;

    s->qscale = h->pps.init_qp + get_se_golomb(&s->gb);

    if(s->qscale<0 || s->qscale>51){

        av_log(s->avctx, AV_LOG_ERROR, "QP %d out of range\n", s->qscale);

        return -1;

    }

    h->chroma_qp = get_chroma_qp(h->pps.chroma_qp_index_offset, s->qscale);

    //FIXME qscale / qp ... stuff

    if(h->slice_type == SP_TYPE){

        get_bits1(&s->gb); /* sp_for_switch_flag */

    }

    if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){

        get_se_golomb(&s->gb); /* slice_qs_delta */

    }

    h->deblocking_filter = 1;

    h->slice_alpha_c0_offset = 0;

    h->slice_beta_offset = 0;

    if( h->pps.deblocking_filter_parameters_present ) {

        h->deblocking_filter= get_ue_golomb(&s->gb);

        if(h->deblocking_filter < 2)

            h->deblocking_filter^= 1; // 1<->0

        if( h->deblocking_filter ) {

            h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;

            h->slice_beta_offset = get_se_golomb(&s->gb) << 1;

        }

    }

    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL

       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type != I_TYPE)

       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type == B_TYPE)

       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))

        h->deblocking_filter= 0;

#if 0 //FMO

    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)

        slice_group_change_cycle= get_bits(&s->gb, ?);

#endif

    h->slice_num++;

    h->emu_edge_width= (s->flags&CODEC_FLAG_EMU_EDGE) ? 0 : 16;

    h->emu_edge_height= FRAME_MBAFF ? 0 : h->emu_edge_width;

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

        av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c pps:%d frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s\n",

               h->slice_num,

               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),

               first_mb_in_slice,

               av_get_pict_type_char(h->slice_type),

               pps_id, h->frame_num,

               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],

               h->ref_count[0], h->ref_count[1],

               s->qscale,

               h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,

               h->use_weight,

               h->use_weight==1 && h->use_weight_chroma ? "c" : ""

               );

    }

    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && !s->current_picture.reference){

        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;

        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;

    }else{

        s->me.qpel_put= s->dsp.put_h264_qpel_pixels_tab;

        s->me.qpel_avg= s->dsp.avg_h264_qpel_pixels_tab;

    }

    return 0;

}


static int output_packet(AVInputStream *ist, int ist_index,

                         AVOutputStream **ost_table, int nb_ostreams,

                         const AVPacket *pkt)

{

    AVFormatContext *os;

    AVOutputStream *ost;

    uint8_t *ptr;

    int len, ret, i;

    uint8_t *data_buf;

    int data_size, got_picture;

    AVFrame picture;

    short samples[pkt && pkt->size > AVCODEC_MAX_AUDIO_FRAME_SIZE/2 ? pkt->size : AVCODEC_MAX_AUDIO_FRAME_SIZE/2];

    void *buffer_to_free;

    if (pkt && pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too

        ist->next_pts = ist->pts = pkt->dts;

    } else {

        assert(ist->pts == ist->next_pts);

    }

    if (pkt == NULL) {

        /* EOF handling */

        ptr = NULL;

        len = 0;

        goto handle_eof;

    }

    len = pkt->size;

    ptr = pkt->data;

    while (len > 0) {

    handle_eof:

        /* decode the packet if needed */

        data_buf = NULL; /* fail safe */

        data_size = 0;

        if (ist->decoding_needed) {

            switch(ist->st->codec.codec_type) {

            case CODEC_TYPE_AUDIO:

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,

                                           ptr, len);

                if (ret < 0)

                    goto fail_decode;

                ptr += ret;

                len -= ret;

                /* Some bug in mpeg audio decoder gives */

                /* data_size < 0, it seems they are overflows */

                if (data_size <= 0) {

                    /* no audio frame */

                    continue;

                }

                data_buf = (uint8_t *)samples;

                ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /

                    (ist->st->codec.sample_rate * ist->st->codec.channels);

                break;

            case CODEC_TYPE_VIDEO:

                    data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;

                    /* XXX: allocate picture correctly */

                    avcodec_get_frame_defaults(&picture);

                    ret = avcodec_decode_video(&ist->st->codec,

                                               &picture, &got_picture, ptr, len);

                    ist->st->quality= picture.quality;

                    if (ret < 0)

                        goto fail_decode;

                    if (!got_picture) {

                        /* no picture yet */

                        goto discard_packet;

                    }

                    if (ist->st->codec.frame_rate_base != 0) {

                        ist->next_pts += ((int64_t)AV_TIME_BASE *

                                          ist->st->codec.frame_rate_base) /

                            ist->st->codec.frame_rate;

                    }

                    len = 0;

                    break;

                default:

                    goto fail_decode;

                }

            } else {

                data_buf = ptr;

                data_size = len;

                ret = len;

                len = 0;

            }

            buffer_to_free = NULL;

            if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO) {

                pre_process_video_frame(ist, (AVPicture *)&picture,

                                        &buffer_to_free);

            }

            /* frame rate emulation */

            if (ist->st->codec.rate_emu) {

                int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec.frame_rate_base, 1000000, ist->st->codec.frame_rate);

                int64_t now = av_gettime() - ist->start;

                if (pts > now)

                    usleep(pts - now);

                ist->frame++;

            }

#if 0

            /* mpeg PTS deordering : if it is a P or I frame, the PTS

               is the one of the next displayed one */

            /* XXX: add mpeg4 too ? */

            if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {

                if (ist->st->codec.pict_type != B_TYPE) {

                    int64_t tmp;

                    tmp = ist->last_ip_pts;

                    ist->last_ip_pts  = ist->frac_pts.val;

                    ist->frac_pts.val = tmp;

                }

            }

#endif

            /* if output time reached then transcode raw format,

	       encode packets and output them */

            if (start_time == 0 || ist->pts >= start_time)

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

                    int frame_size;

                    ost = ost_table[i];

                    if (ost->source_index == ist_index) {

                        os = output_files[ost->file_index];

#if 0

                        printf("%d: got pts=%0.3f %0.3f\n", i,

                               (double)pkt->pts / AV_TIME_BASE,

                               ((double)ist->pts / AV_TIME_BASE) -

                               ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));

#endif

                        /* set the input output pts pairs */

                        ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index])/ AV_TIME_BASE;

                        if (ost->encoding_needed) {

                            switch(ost->st->codec.codec_type) {

                            case CODEC_TYPE_AUDIO:

                                do_audio_out(os, ost, ist, data_buf, data_size);

                                break;

                            case CODEC_TYPE_VIDEO:

                                /* find an audio stream for synchro */

                                {

                                    int i;

                                    AVOutputStream *audio_sync, *ost1;

                                    audio_sync = NULL;

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

                                        ost1 = ost_table[i];

                                        if (ost1->file_index == ost->file_index &&

                                            ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {

                                            audio_sync = ost1;

                                            break;

                                        }

                                    }

                                    do_video_out(os, ost, ist, &picture, &frame_size);

                                    video_size += frame_size;

                                    if (do_vstats && frame_size)

                                        do_video_stats(os, ost, frame_size);

                                }

                                break;

                            default:

                                av_abort();

                            }

                        } else {

                            AVFrame avframe; //FIXME/XXX remove this

                            AVPacket opkt;

                            av_init_packet(&opkt);

                            /* no reencoding needed : output the packet directly */

                            /* force the input stream PTS */

                            avcodec_get_frame_defaults(&avframe);

                            ost->st->codec.coded_frame= &avframe;

                            avframe.key_frame = pkt->flags & PKT_FLAG_KEY;

                            if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO)

                                audio_size += data_size;

                            else if (ost->st->codec.codec_type == CODEC_TYPE_VIDEO)

                                video_size += data_size;

                            opkt.stream_index= ost->index;

                            opkt.data= data_buf;

                            opkt.size= data_size;

                            opkt.pts= pkt->pts + input_files_ts_offset[ist->file_index];

                            opkt.dts= pkt->dts + input_files_ts_offset[ist->file_index];

                            opkt.flags= pkt->flags;

                            av_interleaved_write_frame(os, &opkt);

                            ost->st->codec.frame_number++;

                            ost->frame_number++;

                        }

                    }

                }

            av_free(buffer_to_free);

        }

 discard_packet:

    if (pkt == NULL) {

        /* EOF handling */

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

            ost = ost_table[i];

            if (ost->source_index == ist_index) {

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

                os = output_files[ost->file_index];

                if(ost->st->codec.codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)

                    continue;

                if(ost->st->codec.codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))

                    continue;

                if (ost->encoding_needed) {

                    for(;;) {

                        AVPacket pkt;

                        av_init_packet(&pkt);

                        pkt.stream_index= ost->index;

                        switch(ost->st->codec.codec_type) {

                        case CODEC_TYPE_AUDIO:

                            ret = avcodec_encode_audio(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);

                            audio_size += ret;

                            pkt.flags |= PKT_FLAG_KEY;

                            break;

                        case CODEC_TYPE_VIDEO:

                            ret = avcodec_encode_video(enc, bit_buffer, VIDEO_BUFFER_SIZE, NULL);

                            video_size += ret;

                            if(enc->coded_frame && enc->coded_frame->key_frame)

                                pkt.flags |= PKT_FLAG_KEY;

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

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

                            }

                            break;

                        default:

                            ret=-1;

                        }

                        if(ret<=0)

                            break;

                        pkt.data= bit_buffer;

                        pkt.size= ret;

                        if(enc->coded_frame)

                            pkt.pts= enc->coded_frame->pts;

                        av_interleaved_write_frame(os, &pkt);

                    }

                }

            }

        }

    }

    return 0;

 fail_decode:

    return -1;

}


static void yuv2yuv1_c(SwsContext *c, const int16_t *lumSrc,

                       const int16_t *chrUSrc, const int16_t *chrVSrc,

                       const int16_t *alpSrc,

                       uint8_t *dest, uint8_t *uDest, uint8_t *vDest,

                       uint8_t *aDest, int dstW, int chrDstW)

{

    int i;

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

        int val= (lumSrc[i]+64)>>7;

        dest[i]= av_clip_uint8(val);

    }

    if (uDest)

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

            int u=(chrUSrc[i]+64)>>7;

            int v=(chrVSrc[i]+64)>>7;

            uDest[i]= av_clip_uint8(u);

            vDest[i]= av_clip_uint8(v);

        }

    if (CONFIG_SWSCALE_ALPHA && aDest)

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

            int val= (alpSrc[i]+64)>>7;

            aDest[i]= av_clip_uint8(val);

        }

}


static int teletext_close_decoder(AVCodecContext *avctx)

{

    TeletextContext *ctx = avctx->priv_data;

    av_dlog(avctx, "lines_total=%u\n", ctx->lines_processed);

    while (ctx->nb_pages)

        subtitle_rect_free(&ctx->pages[--ctx->nb_pages].sub_rect);

    av_freep(&ctx->pages);

    vbi_decoder_delete(ctx->vbi);

    ctx->vbi = NULL;

    ctx->pts = AV_NOPTS_VALUE;

    return 0;

}


MigrationState *tcp_start_outgoing_migration(const char *host_port,

					     int64_t bandwidth_limit,

					     int async)

{

    struct sockaddr_in addr;

    FdMigrationState *s;

    int ret;

    if (parse_host_port(&addr, host_port) < 0)

        return NULL;

    s = qemu_mallocz(sizeof(*s));

    if (s == NULL)

        return NULL;

    s->mig_state.cancel = tcp_cancel;

    s->mig_state.get_status = tcp_get_status;

    s->mig_state.release = tcp_release;

    s->state = MIG_STATE_ACTIVE;

    s->detach = !async;

    s->bandwidth_limit = bandwidth_limit;

    s->fd = socket(PF_INET, SOCK_STREAM, 0);

    if (s->fd == -1) {

        qemu_free(s);

	return NULL;

    }

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

    if (s->detach == 1) {

        dprintf("detaching from monitor\n");

        monitor_suspend();

	s->detach = 2;

    }

    do {

        ret = connect(s->fd, (struct sockaddr *)&addr, sizeof(addr));

        if (ret == -1)

            ret = -errno;

        if (ret == -EINPROGRESS)

            qemu_set_fd_handler2(s->fd, NULL, NULL, tcp_wait_for_connect, s);

    } while (ret == -EINTR);

    if (ret < 0 && ret != -EINPROGRESS) {

        dprintf("connect failed\n");

        close(s->fd);

        qemu_free(s);

	s = NULL;

    } else if (ret >= 0)

        tcp_connect_migrate(s);

    return &s->mig_state;

}