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

{

    AVIContext *avi = s->priv_data;

    ByteIOContext *pb = &s->pb;

    uint32_t tag, tag1, handler;

    int codec_type, stream_index, frame_period, bit_rate, scale, rate;

    unsigned int size, nb_frames;

    int i, n;

    AVStream *st;

    AVIStream *ast;

    int xan_video = 0;  /* hack to support Xan A/V */

    if (get_riff(avi, pb) < 0)

        return -1;

    /* first list tag */

    stream_index = -1;

    codec_type = -1;

    frame_period = 0;

    for(;;) {

        if (url_feof(pb))

            goto fail;

        tag = get_le32(pb);

        size = get_le32(pb);

#ifdef DEBUG

        print_tag("tag", tag, size);

#endif

        switch(tag) {

        case MKTAG('L', 'I', 'S', 'T'):

            /* ignored, except when start of video packets */

            tag1 = get_le32(pb);

#ifdef DEBUG

            print_tag("list", tag1, 0);

#endif

            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {

                avi->movi_list = url_ftell(pb) - 4;

                if(size) avi->movi_end = avi->movi_list + size;

                else     avi->movi_end = url_filesize(url_fileno(pb));

#ifdef DEBUG

                printf("movi end=%Lx\n", avi->movi_end);

#endif

                goto end_of_header;

            }

            break;

        case MKTAG('d', 'm', 'l', 'h'):

	    avi->is_odml = 1;

	    url_fskip(pb, size + (size & 1));

	    break;

        case MKTAG('a', 'v', 'i', 'h'):

	    /* avi header */

            /* using frame_period is bad idea */

            frame_period = get_le32(pb);

            bit_rate = get_le32(pb) * 8;

	    url_fskip(pb, 4 * 4);

            n = get_le32(pb);

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

                AVIStream *ast;

                st = av_new_stream(s, i);

                if (!st)

                    goto fail;

                ast = av_mallocz(sizeof(AVIStream));

                if (!ast)

                    goto fail;

                st->priv_data = ast;

	    }

            url_fskip(pb, size - 7 * 4);

            break;

        case MKTAG('s', 't', 'r', 'h'):

            /* stream header */

            stream_index++;

            tag1 = get_le32(pb);

            handler = get_le32(pb); /* codec tag */

#ifdef DEBUG

        print_tag("strh", tag1, -1);

#endif

            switch(tag1) {

            case MKTAG('i', 'a', 'v', 's'):

	    case MKTAG('i', 'v', 'a', 's'):

                /*

	         * After some consideration -- I don't think we

	         * have to support anything but DV in a type1 AVIs.

	         */

	        if (s->nb_streams != 1)

		    goto fail;

		if (handler != MKTAG('d', 'v', 's', 'd') &&

	            handler != MKTAG('d', 'v', 'h', 'd') &&

		    handler != MKTAG('d', 'v', 's', 'l'))

	           goto fail;

		ast = s->streams[0]->priv_data;

		av_freep(&s->streams[0]->codec.extradata);

		av_freep(&s->streams[0]);

		s->nb_streams = 0;

	        avi->dv_demux = dv_init_demux(s);

		if (!avi->dv_demux)

		    goto fail;

		s->streams[0]->priv_data = ast;

		url_fskip(pb, 3 * 4);

		ast->scale = get_le32(pb);

		ast->rate = get_le32(pb);

	        stream_index = s->nb_streams - 1;

		url_fskip(pb, size - 7*4);

		break;

	    case MKTAG('v', 'i', 'd', 's'):

                codec_type = CODEC_TYPE_VIDEO;

                if (stream_index >= s->nb_streams) {

                    url_fskip(pb, size - 8);

                    break;

                }

                st = s->streams[stream_index];

                ast = st->priv_data;

                st->codec.stream_codec_tag= handler;

                get_le32(pb); /* flags */

                get_le16(pb); /* priority */

                get_le16(pb); /* language */

                get_le32(pb); /* XXX: initial frame ? */

                scale = get_le32(pb); /* scale */

                rate = get_le32(pb); /* rate */

                if(scale && rate){

                }else if(frame_period){

                    rate = 1000000;

                    scale = frame_period;

                }else{

                    rate = 25;

                    scale = 1;

                }

                ast->rate = rate;

                ast->scale = scale;

                av_set_pts_info(st, 64, scale, rate);

                st->codec.frame_rate = rate;

                st->codec.frame_rate_base = scale;

                get_le32(pb); /* start */

                nb_frames = get_le32(pb);

                st->start_time = 0;

                st->duration = av_rescale(nb_frames,

                    st->codec.frame_rate_base * AV_TIME_BASE,

                    st->codec.frame_rate);

		url_fskip(pb, size - 9 * 4);

                break;

            case MKTAG('a', 'u', 'd', 's'):

                {

                    unsigned int length;

                    codec_type = CODEC_TYPE_AUDIO;

                    if (stream_index >= s->nb_streams) {

                        url_fskip(pb, size - 8);

                        break;

                    }

                    st = s->streams[stream_index];

                    ast = st->priv_data;

                    get_le32(pb); /* flags */

                    get_le16(pb); /* priority */

                    get_le16(pb); /* language */

                    get_le32(pb); /* initial frame */

                    ast->scale = get_le32(pb); /* scale */

                    ast->rate = get_le32(pb);

                    if(!ast->rate)

                        ast->rate= 1; //wrong but better then 1/0

                    if(!ast->scale)

                        ast->scale= 1; //wrong but better then 1/0

                    av_set_pts_info(st, 64, ast->scale, ast->rate);

                    ast->start= get_le32(pb); /* start */

                    length = get_le32(pb); /* length, in samples or bytes */

                    get_le32(pb); /* buffer size */

                    get_le32(pb); /* quality */

                    ast->sample_size = get_le32(pb); /* sample ssize */

//av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->scale, ast->rate, ast->sample_size, ast->start);

                    st->start_time = 0;

                    if (ast->rate != 0)

                        st->duration = (int64_t)length * AV_TIME_BASE / ast->rate;

                    url_fskip(pb, size - 12 * 4);

                }

                break;

            case MKTAG('t', 'x', 't', 's'):

                //FIXME

                codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME

                url_fskip(pb, size - 8);

                break;

            case MKTAG('p', 'a', 'd', 's'):

                codec_type = CODEC_TYPE_UNKNOWN;

                url_fskip(pb, size - 8);

                stream_index--;

                break;

            default:

                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);

                goto fail;

            }

            break;

        case MKTAG('s', 't', 'r', 'f'):

            /* stream header */

            if (stream_index >= s->nb_streams || avi->dv_demux) {

                url_fskip(pb, size);

            } else {

                st = s->streams[stream_index];

                switch(codec_type) {

                case CODEC_TYPE_VIDEO:

                    get_le32(pb); /* size */

                    st->codec.width = get_le32(pb);

                    st->codec.height = get_le32(pb);

                    get_le16(pb); /* panes */

                    st->codec.bits_per_sample= get_le16(pb); /* depth */

                    tag1 = get_le32(pb);

                    get_le32(pb); /* ImageSize */

                    get_le32(pb); /* XPelsPerMeter */

                    get_le32(pb); /* YPelsPerMeter */

                    get_le32(pb); /* ClrUsed */

                    get_le32(pb); /* ClrImportant */

                 if(size > 10*4 && size<(1<<30)){

                    st->codec.extradata_size= size - 10*4;

                    st->codec.extradata= av_malloc(st->codec.extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                    get_buffer(pb, st->codec.extradata, st->codec.extradata_size);

                 }

                    if(st->codec.extradata_size & 1) //FIXME check if the encoder really did this correctly

                        get_byte(pb);

                    /* Extract palette from extradata if bpp <= 8 */

                    /* This code assumes that extradata contains only palette */

                    /* This is true for all paletted codecs implemented in ffmpeg */

                    if (st->codec.extradata_size && (st->codec.bits_per_sample <= 8)) {

                        st->codec.palctrl = av_mallocz(sizeof(AVPaletteControl));

#ifdef WORDS_BIGENDIAN

                        for (i = 0; i < FFMIN(st->codec.extradata_size, AVPALETTE_SIZE)/4; i++)

                            st->codec.palctrl->palette[i] = bswap_32(((uint32_t*)st->codec.extradata)[i]);

#else

                        memcpy(st->codec.palctrl->palette, st->codec.extradata,

                               FFMIN(st->codec.extradata_size, AVPALETTE_SIZE));

#endif

                        st->codec.palctrl->palette_changed = 1;

                    }

#ifdef DEBUG

                    print_tag("video", tag1, 0);

#endif

                    st->codec.codec_type = CODEC_TYPE_VIDEO;

                    st->codec.codec_tag = tag1;

                    st->codec.codec_id = codec_get_id(codec_bmp_tags, tag1);

                    if (st->codec.codec_id == CODEC_ID_XAN_WC4)

                        xan_video = 1;

//                    url_fskip(pb, size - 5 * 4);

                    break;

                case CODEC_TYPE_AUDIO:

                    get_wav_header(pb, &st->codec, size);

                    if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */

                        url_fskip(pb, 1);

                    /* special case time: To support Xan DPCM, hardcode

                     * the format if Xxan is the video codec */

                    st->need_parsing = 1;

                    /* force parsing as several audio frames can be in

                       one packet */

                    if (xan_video)

                        st->codec.codec_id = CODEC_ID_XAN_DPCM;

                    break;

                default:

                    st->codec.codec_type = CODEC_TYPE_DATA;

                    st->codec.codec_id= CODEC_ID_NONE;

                    st->codec.codec_tag= 0;

                    url_fskip(pb, size);

                    break;

                }

            }

            break;

        default:

            /* skip tag */

            size += (size & 1);

            url_fskip(pb, size);

            break;

        }

    }

 end_of_header:

    /* check stream number */

    if (stream_index != s->nb_streams - 1) {

    fail:

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

            av_freep(&s->streams[i]->codec.extradata);

            av_freep(&s->streams[i]);

        }

        return -1;

    }

    assert(!avi->index_loaded);

    avi_load_index(s);

    avi->index_loaded = 1;

    return 0;

}


static void test_io(void)

{

#ifndef _WIN32

/* socketpair(PF_UNIX) which does not exist on windows */

    int sv[2];

    int r;

    unsigned i, j, k, s, t;

    fd_set fds;

    unsigned niov;

    struct iovec *iov, *siov;

    unsigned char *buf;

    size_t sz;

    iov_random(&iov, &niov);

    sz = iov_size(iov, niov);

    buf = g_malloc(sz);

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

        buf[i] = i & 255;

    }

    iov_from_buf(iov, niov, 0, buf, sz);

    siov = g_malloc(sizeof(*iov) * niov);

    memcpy(siov, iov, sizeof(*iov) * niov);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {

       perror("socketpair");

       exit(1);

    }

    FD_ZERO(&fds);

    t = 0;

    if (fork() == 0) {

       /* writer */

       close(sv[0]);

       FD_SET(sv[1], &fds);

       fcntl(sv[1], F_SETFL, O_RDWR|O_NONBLOCK);

       r = g_test_rand_int_range(sz / 2, sz);

       setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &r, sizeof(r));

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

           for (j = i; j <= sz; ++j) {

               k = i;

               do {

                   s = g_test_rand_int_range(0, j - k + 1);

                   r = iov_send(sv[1], iov, niov, k, s);

                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);

                   if (r >= 0) {

                       k += r;

                       t += r;

                       usleep(g_test_rand_int_range(0, 30));

                   } else if (errno == EAGAIN) {

                       select(sv[1]+1, NULL, &fds, NULL, NULL);

                       continue;

                   } else {

                       perror("send");

                       exit(1);

                   }

               } while(k < j);

           }

       }

       exit(0);

    } else {

       /* reader & verifier */

       close(sv[1]);

       FD_SET(sv[0], &fds);

       fcntl(sv[0], F_SETFL, O_RDWR|O_NONBLOCK);

       r = g_test_rand_int_range(sz / 2, sz);

       setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &r, sizeof(r));

       usleep(500000);

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

           for (j = i; j <= sz; ++j) {

               k = i;

               iov_memset(iov, niov, 0, 0xff, -1);

               do {

                   s = g_test_rand_int_range(0, j - k + 1);

                   r = iov_recv(sv[0], iov, niov, k, s);

                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);

                   if (r > 0) {

                       k += r;

                       t += r;

                   } else if (!r) {

                       if (s) {

                           break;

                       }

                   } else if (errno == EAGAIN) {

                       select(sv[0]+1, &fds, NULL, NULL, NULL);

                       continue;

                   } else {

                       perror("recv");

                       exit(1);

                   }

               } while(k < j);

               test_iov_bytes(iov, niov, i, j - i);

           }

        }

     }

#endif

}


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

                                 int *got_frame, AVPacket *avpkt)

{

    Jpeg2000DecoderContext *s = avctx->priv_data;

    ThreadFrame frame = { .f = data };

    AVFrame *picture = data;

    int tileno, ret;

    s->avctx     = avctx;

    s->buf       = s->buf_start = avpkt->data;

    s->buf_end   = s->buf_start + avpkt->size;

    s->curtileno = 0; // TODO: only one tile in DCI JP2K. to implement for more tiles

    // reduction factor, i.e number of resolution levels to skip

    s->reduction_factor = s->lowres;

    if (s->buf_end - s->buf < 2)

        return AVERROR_INVALIDDATA;

    // check if the image is in jp2 format

    if ((AV_RB32(s->buf) == 12) &&

        (AV_RB32(s->buf + 4) == JP2_SIG_TYPE) &&

        (AV_RB32(s->buf + 8) == JP2_SIG_VALUE)) {

        if (!jp2_find_codestream(s)) {

            av_log(avctx, AV_LOG_ERROR,

                   "Could not find Jpeg2000 codestream atom.\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if (bytestream_get_be16(&s->buf) != JPEG2000_SOC) {

        av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");

        return AVERROR_INVALIDDATA;

    }

    if (ret = jpeg2000_read_main_headers(s))

        goto end;

    /* get picture buffer */

    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed.\n");

        goto end;

    }

    picture->pict_type = AV_PICTURE_TYPE_I;

    picture->key_frame = 1;

    if (ret = jpeg2000_read_bitstream_packets(s))

        goto end;

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)

        if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))

            goto end;

    *got_frame = 1;

end:

    jpeg2000_dec_cleanup(s);

    return ret ? ret : s->buf - s->buf_start;

}


static HotpluggableCPUList *spapr_query_hotpluggable_cpus(MachineState *machine)

{

    int i;

    HotpluggableCPUList *head = NULL;

    sPAPRMachineState *spapr = SPAPR_MACHINE(machine);

    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);

    int spapr_max_cores = max_cpus / smp_threads;

    g_assert(smc->dr_cpu_enabled);

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

        HotpluggableCPUList *list_item = g_new0(typeof(*list_item), 1);

        HotpluggableCPU *cpu_item = g_new0(typeof(*cpu_item), 1);

        CpuInstanceProperties *cpu_props = g_new0(typeof(*cpu_props), 1);

        cpu_item->type = spapr_get_cpu_core_type(machine->cpu_model);

        cpu_item->vcpus_count = smp_threads;

        cpu_props->has_core_id = true;

        cpu_props->core_id = i * smp_threads;

        /* TODO: add 'has_node/node' here to describe

           to which node core belongs */

        cpu_item->props = cpu_props;

        if (spapr->cores[i]) {

            cpu_item->has_qom_path = true;

            cpu_item->qom_path = object_get_canonical_path(spapr->cores[i]);

        }

        list_item->value = cpu_item;

        list_item->next = head;

        head = list_item;

    }

    return head;

}


static int matroska_ebmlnum_uint(MatroskaDemuxContext *matroska,

                                 uint8_t *data, uint32_t size, uint64_t *num)

{

    ByteIOContext pb;

    init_put_byte(&pb, data, size, 0, NULL, NULL, NULL, NULL);

    return ebml_read_num(matroska, &pb, 8, num);

}


static int check(AVIOContext *pb, int64_t pos)

{

    int64_t ret = avio_seek(pb, pos, SEEK_SET);

    unsigned header;

    MPADecodeHeader sd;

    if (ret < 0)

        return ret;

    header = avio_rb32(pb);

    if (ff_mpa_check_header(header) < 0)

        return -1;

    if (avpriv_mpegaudio_decode_header(&sd, header) == 1)

        return -1;

    return sd.frame_size;

}


static void slavio_timer_get_out(SLAVIO_TIMERState *s)

{

    uint64_t count;

    count = s->limit - PERIODS_TO_LIMIT(ptimer_get_count(s->timer));

    DPRINTF("get_out: limit %" PRIx64 " count %x%08x\n", s->limit,

            s->counthigh, s->count);

    s->count = count & TIMER_COUNT_MASK32;

    s->counthigh = count >> 32;

}


void acpi_pm1_cnt_reset(ACPIREGS *ar)

{

    ar->pm1.cnt.cnt = 0;

    if (ar->pm1.cnt.cmos_s3) {

        qemu_irq_lower(ar->pm1.cnt.cmos_s3);

    }

}


static uint16_t pci_req_id_cache_extract(PCIReqIDCache *cache)

{

    uint8_t bus_n;

    uint16_t result;

    switch (cache->type) {

    case PCI_REQ_ID_BDF:

        result = pci_get_bdf(cache->dev);

        break;

    case PCI_REQ_ID_SECONDARY_BUS:

        bus_n = pci_bus_num(cache->dev->bus);

        result = PCI_BUILD_BDF(bus_n, 0);

        break;

    default:

        error_printf("Invalid PCI requester ID cache type: %d\n",

                     cache->type);

        exit(1);

        break;

    }

    return result;

}


int qio_channel_readv_all(QIOChannel *ioc,

                          const struct iovec *iov,

                          size_t niov,

                          Error **errp)

{

    int ret = -1;

    struct iovec *local_iov = g_new(struct iovec, niov);

    struct iovec *local_iov_head = local_iov;

    unsigned int nlocal_iov = niov;

    nlocal_iov = iov_copy(local_iov, nlocal_iov,

                          iov, niov,

                          0, iov_size(iov, niov));

    while (nlocal_iov > 0) {

        ssize_t len;

        len = qio_channel_readv(ioc, local_iov, nlocal_iov, errp);

        if (len == QIO_CHANNEL_ERR_BLOCK) {

            qio_channel_wait(ioc, G_IO_IN);

            continue;

        } else if (len < 0) {

            goto cleanup;

        } else if (len == 0) {

            error_setg(errp,

                       "Unexpected end-of-file before all bytes were read");

            goto cleanup;

        }

        iov_discard_front(&local_iov, &nlocal_iov, len);

    }

    ret = 0;

 cleanup:

    g_free(local_iov_head);

    return ret;

}


static void ioreq_unmap(struct ioreq *ioreq)

{

    int gnt = ioreq->blkdev->xendev.gnttabdev;

    int i;

    if (ioreq->v.niov == 0) {

        return;

    }

    if (batch_maps) {

        if (!ioreq->pages) {

            return;

        }

        if (xc_gnttab_munmap(gnt, ioreq->pages, ioreq->v.niov) != 0) {

            xen_be_printf(&ioreq->blkdev->xendev, 0, "xc_gnttab_munmap failed: %s\n",

                          strerror(errno));

        }

        ioreq->blkdev->cnt_map -= ioreq->v.niov;

        ioreq->pages = NULL;

    } else {

        for (i = 0; i < ioreq->v.niov; i++) {

            if (!ioreq->page[i]) {

                continue;

            }

            if (xc_gnttab_munmap(gnt, ioreq->page[i], 1) != 0) {

                xen_be_printf(&ioreq->blkdev->xendev, 0, "xc_gnttab_munmap failed: %s\n",

                              strerror(errno));

            }

            ioreq->blkdev->cnt_map--;

            ioreq->page[i] = NULL;

        }

    }

}


static struct omap_mpuio_s *omap_mpuio_init(MemoryRegion *memory,

                target_phys_addr_t base,

                qemu_irq kbd_int, qemu_irq gpio_int, qemu_irq wakeup,

                omap_clk clk)

{

    struct omap_mpuio_s *s = (struct omap_mpuio_s *)

            g_malloc0(sizeof(struct omap_mpuio_s));

    s->irq = gpio_int;

    s->kbd_irq = kbd_int;

    s->wakeup = wakeup;

    s->in = qemu_allocate_irqs(omap_mpuio_set, s, 16);

    omap_mpuio_reset(s);

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

                          "omap-mpuio", 0x800);

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

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_mpuio_onoff, s, 1)[0]);

    return s;

}


static target_ulong h_read(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                           target_ulong opcode, target_ulong *args)

{

    CPUPPCState *env = &cpu->env;

    target_ulong flags = args[0];

    target_ulong ptex = args[1];

    uint8_t *hpte;

    int i, ridx, n_entries = 1;

    if (!valid_ptex(cpu, ptex)) {

        return H_PARAMETER;

    }

    if (flags & H_READ_4) {

        /* Clear the two low order bits */

        ptex &= ~(3ULL);

        n_entries = 4;

    }

    hpte = env->external_htab + (ptex * HASH_PTE_SIZE_64);

    for (i = 0, ridx = 0; i < n_entries; i++) {

        args[ridx++] = ldq_p(hpte);

        args[ridx++] = ldq_p(hpte + (HASH_PTE_SIZE_64/2));

        hpte += HASH_PTE_SIZE_64;

    }

    return H_SUCCESS;

}


static void dec_pattern(DisasContext *dc)

{

    unsigned int mode;

    int l1;

    if ((dc->tb_flags & MSR_EE_FLAG)

          && !(dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

          && !((dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR))) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

    }

    mode = dc->opcode & 3;

    switch (mode) {

        case 0:

            /* pcmpbf.  */

            LOG_DIS("pcmpbf r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            if (dc->rd)

                gen_helper_pcmpbf(cpu_R[dc->rd], cpu_R[dc->ra], cpu_R[dc->rb]);

            break;

        case 2:

            LOG_DIS("pcmpeq r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            if (dc->rd) {

                TCGv t0 = tcg_temp_local_new();

                l1 = gen_new_label();

                tcg_gen_movi_tl(t0, 1);

                tcg_gen_brcond_tl(TCG_COND_EQ,

                                  cpu_R[dc->ra], cpu_R[dc->rb], l1);

                tcg_gen_movi_tl(t0, 0);

                gen_set_label(l1);

                tcg_gen_mov_tl(cpu_R[dc->rd], t0);

                tcg_temp_free(t0);

            }

            break;

        case 3:

            LOG_DIS("pcmpne r%d r%d r%d\n", dc->rd, dc->ra, dc->rb);

            l1 = gen_new_label();

            if (dc->rd) {

                TCGv t0 = tcg_temp_local_new();

                tcg_gen_movi_tl(t0, 1);

                tcg_gen_brcond_tl(TCG_COND_NE,

                                  cpu_R[dc->ra], cpu_R[dc->rb], l1);

                tcg_gen_movi_tl(t0, 0);

                gen_set_label(l1);

                tcg_gen_mov_tl(cpu_R[dc->rd], t0);

                tcg_temp_free(t0);

            }

            break;

        default:

            cpu_abort(dc->env,

                      "unsupported pattern insn opcode=%x\n", dc->opcode);

            break;

    }

}


static MemoryRegionSection phys_page_find(target_phys_addr_t index)

{

    uint16_t *p = phys_page_find_alloc(index, 0);

    uint16_t s_index = phys_section_unassigned;

    MemoryRegionSection section;

    target_phys_addr_t delta;

    if (p) {

        s_index = *p;

    }

    section = phys_sections[s_index];

    index <<= TARGET_PAGE_BITS;

    assert(section.offset_within_address_space <= index

           && index <= section.offset_within_address_space + section.size-1);

    delta = index - section.offset_within_address_space;

    section.offset_within_address_space += delta;

    section.offset_within_region += delta;

    section.size -= delta;

    return section;

}


static void qmp_output_end_struct(Visitor *v, Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    qmp_output_pop(qov);

}


static av_cold int MP3lame_encode_init(AVCodecContext *avctx)

{

    Mp3AudioContext *s = avctx->priv_data;

    if (avctx->channels > 2)

        return -1;

    s->stereo = avctx->channels > 1 ? 1 : 0;

    if ((s->gfp = lame_init()) == NULL)

        goto err;

    lame_set_in_samplerate(s->gfp, avctx->sample_rate);

    lame_set_out_samplerate(s->gfp, avctx->sample_rate);

    lame_set_num_channels(s->gfp, avctx->channels);

    if(avctx->compression_level == FF_COMPRESSION_DEFAULT) {

        lame_set_quality(s->gfp, 5);

    } else {

        lame_set_quality(s->gfp, avctx->compression_level);

    }

    lame_set_mode(s->gfp, s->stereo ? JOINT_STEREO : MONO);

    lame_set_brate(s->gfp, avctx->bit_rate/1000);

    if(avctx->flags & CODEC_FLAG_QSCALE) {

        lame_set_brate(s->gfp, 0);

        lame_set_VBR(s->gfp, vbr_default);

        lame_set_VBR_quality(s->gfp, avctx->global_quality/(float)FF_QP2LAMBDA);

    }

    lame_set_bWriteVbrTag(s->gfp,0);

#if FF_API_LAME_GLOBAL_OPTS

    s->reservoir = avctx->flags2 & CODEC_FLAG2_BIT_RESERVOIR;

#endif

    lame_set_disable_reservoir(s->gfp, !s->reservoir);

    if (lame_init_params(s->gfp) < 0)

        goto err_close;

    avctx->frame_size = lame_get_framesize(s->gfp);

    if(!(avctx->coded_frame= avcodec_alloc_frame())) {

        lame_close(s->gfp);

        return AVERROR(ENOMEM);

    }

    avctx->coded_frame->key_frame= 1;

    if(AV_SAMPLE_FMT_S32 == avctx->sample_fmt && s->stereo) {

        int nelem = 2 * avctx->frame_size;

        if(! (s->s32_data.left = av_malloc(nelem * sizeof(int)))) {

            av_freep(&avctx->coded_frame);

            lame_close(s->gfp);

            return AVERROR(ENOMEM);

        }

        s->s32_data.right = s->s32_data.left + avctx->frame_size;

    }

    return 0;

err_close:

    lame_close(s->gfp);

err:

    return -1;

}


static void string_cleanup(void *datap)

{

    StringSerializeData *d = datap;

    visit_free(string_output_get_visitor(d->sov));

    visit_free(d->siv);

    g_free(d->string);

    g_free(d);

}


static int n8x0_atag_setup(void *p, int model)

{

    uint8_t *b;

    uint16_t *w;

    uint32_t *l;

    struct omap_gpiosw_info_s *gpiosw;

    struct omap_partition_info_s *partition;

    const char *tag;

    w = p;

    stw_p(w++, OMAP_TAG_UART);			/* u16 tag */

    stw_p(w++, 4);				/* u16 len */

    stw_p(w++, (1 << 2) | (1 << 1) | (1 << 0)); /* uint enabled_uarts */

    w++;

#if 0

    stw_p(w++, OMAP_TAG_SERIAL_CONSOLE);	/* u16 tag */

    stw_p(w++, 4);				/* u16 len */

    stw_p(w++, XLDR_LL_UART + 1);		/* u8 console_uart */

    stw_p(w++, 115200);				/* u32 console_speed */

#endif

    stw_p(w++, OMAP_TAG_LCD);			/* u16 tag */

    stw_p(w++, 36);				/* u16 len */

    strcpy((void *) w, "QEMU LCD panel");	/* char panel_name[16] */

    w += 8;

    strcpy((void *) w, "blizzard");		/* char ctrl_name[16] */

    w += 8;

    stw_p(w++, N810_BLIZZARD_RESET_GPIO);	/* TODO: n800 s16 nreset_gpio */

    stw_p(w++, 24);				/* u8 data_lines */

    stw_p(w++, OMAP_TAG_CBUS);			/* u16 tag */

    stw_p(w++, 8);				/* u16 len */

    stw_p(w++, N8X0_CBUS_CLK_GPIO);		/* s16 clk_gpio */

    stw_p(w++, N8X0_CBUS_DAT_GPIO);		/* s16 dat_gpio */

    stw_p(w++, N8X0_CBUS_SEL_GPIO);		/* s16 sel_gpio */

    w++;

    stw_p(w++, OMAP_TAG_EM_ASIC_BB5);		/* u16 tag */

    stw_p(w++, 4);				/* u16 len */

    stw_p(w++, N8X0_RETU_GPIO);			/* s16 retu_irq_gpio */

    stw_p(w++, N8X0_TAHVO_GPIO);		/* s16 tahvo_irq_gpio */

    gpiosw = (model == 810) ? n810_gpiosw_info : n800_gpiosw_info;

    for (; gpiosw->name; gpiosw++) {

        stw_p(w++, OMAP_TAG_GPIO_SWITCH);	/* u16 tag */

        stw_p(w++, 20);				/* u16 len */

        strcpy((void *) w, gpiosw->name);	/* char name[12] */

        w += 6;

        stw_p(w++, gpiosw->line);		/* u16 gpio */

        stw_p(w++, gpiosw->type);

        stw_p(w++, 0);

        stw_p(w++, 0);

    }

    stw_p(w++, OMAP_TAG_NOKIA_BT);		/* u16 tag */

    stw_p(w++, 12);				/* u16 len */

    b = (void *) w;

    stb_p(b++, 0x01);				/* u8 chip_type	(CSR) */

    stb_p(b++, N8X0_BT_WKUP_GPIO);		/* u8 bt_wakeup_gpio */

    stb_p(b++, N8X0_BT_HOST_WKUP_GPIO);		/* u8 host_wakeup_gpio */

    stb_p(b++, N8X0_BT_RESET_GPIO);		/* u8 reset_gpio */

    stb_p(b++, BT_UART + 1);			/* u8 bt_uart */

    memcpy(b, &n8x0_bd_addr, 6);		/* u8 bd_addr[6] */

    b += 6;

    stb_p(b++, 0x02);				/* u8 bt_sysclk (38.4) */

    w = (void *) b;

    stw_p(w++, OMAP_TAG_WLAN_CX3110X);		/* u16 tag */

    stw_p(w++, 8);				/* u16 len */

    stw_p(w++, 0x25);				/* u8 chip_type */

    stw_p(w++, N8X0_WLAN_PWR_GPIO);		/* s16 power_gpio */

    stw_p(w++, N8X0_WLAN_IRQ_GPIO);		/* s16 irq_gpio */

    stw_p(w++, -1);				/* s16 spi_cs_gpio */

    stw_p(w++, OMAP_TAG_MMC);			/* u16 tag */

    stw_p(w++, 16);				/* u16 len */

    if (model == 810) {

        stw_p(w++, 0x23f);			/* unsigned flags */

        stw_p(w++, -1);				/* s16 power_pin */

        stw_p(w++, -1);				/* s16 switch_pin */

        stw_p(w++, -1);				/* s16 wp_pin */

        stw_p(w++, 0x240);			/* unsigned flags */

        stw_p(w++, 0xc000);			/* s16 power_pin */

        stw_p(w++, 0x0248);			/* s16 switch_pin */

        stw_p(w++, 0xc000);			/* s16 wp_pin */

    } else {

        stw_p(w++, 0xf);			/* unsigned flags */

        stw_p(w++, -1);				/* s16 power_pin */

        stw_p(w++, -1);				/* s16 switch_pin */

        stw_p(w++, -1);				/* s16 wp_pin */

        stw_p(w++, 0);				/* unsigned flags */

        stw_p(w++, 0);				/* s16 power_pin */

        stw_p(w++, 0);				/* s16 switch_pin */

        stw_p(w++, 0);				/* s16 wp_pin */

    }

    stw_p(w++, OMAP_TAG_TEA5761);		/* u16 tag */

    stw_p(w++, 4);				/* u16 len */

    stw_p(w++, N8X0_TEA5761_CS_GPIO);		/* u16 enable_gpio */

    w++;

    partition = (model == 810) ? n810_part_info : n800_part_info;

    for (; partition->name; partition++) {

        stw_p(w++, OMAP_TAG_PARTITION);		/* u16 tag */

        stw_p(w++, 28);				/* u16 len */

        strcpy((void *) w, partition->name);	/* char name[16] */

        l = (void *) (w + 8);

        stl_p(l++, partition->size);		/* unsigned int size */

        stl_p(l++, partition->offset);		/* unsigned int offset */

        stl_p(l++, partition->mask);		/* unsigned int mask_flags */

        w = (void *) l;

    }

    stw_p(w++, OMAP_TAG_BOOT_REASON);		/* u16 tag */

    stw_p(w++, 12);				/* u16 len */

#if 0

    strcpy((void *) w, "por");			/* char reason_str[12] */

    strcpy((void *) w, "charger");		/* char reason_str[12] */

    strcpy((void *) w, "32wd_to");		/* char reason_str[12] */

    strcpy((void *) w, "sw_rst");		/* char reason_str[12] */

    strcpy((void *) w, "mbus");			/* char reason_str[12] */

    strcpy((void *) w, "unknown");		/* char reason_str[12] */

    strcpy((void *) w, "swdg_to");		/* char reason_str[12] */

    strcpy((void *) w, "sec_vio");		/* char reason_str[12] */

    strcpy((void *) w, "pwr_key");		/* char reason_str[12] */

    strcpy((void *) w, "rtc_alarm");		/* char reason_str[12] */

#else

    strcpy((void *) w, "pwr_key");		/* char reason_str[12] */

#endif

    w += 6;

    tag = (model == 810) ? "RX-44" : "RX-34";

    stw_p(w++, OMAP_TAG_VERSION_STR);		/* u16 tag */

    stw_p(w++, 24);				/* u16 len */

    strcpy((void *) w, "product");		/* char component[12] */

    w += 6;

    strcpy((void *) w, tag);			/* char version[12] */

    w += 6;

    stw_p(w++, OMAP_TAG_VERSION_STR);		/* u16 tag */

    stw_p(w++, 24);				/* u16 len */

    strcpy((void *) w, "hw-build");		/* char component[12] */

    w += 6;

    strcpy((void *) w, "QEMU ");

    pstrcat((void *) w, 12, qemu_get_version()); /* char version[12] */

    w += 6;

    tag = (model == 810) ? "1.1.10-qemu" : "1.1.6-qemu";

    stw_p(w++, OMAP_TAG_VERSION_STR);		/* u16 tag */

    stw_p(w++, 24);				/* u16 len */

    strcpy((void *) w, "nolo");			/* char component[12] */

    w += 6;

    strcpy((void *) w, tag);			/* char version[12] */

    w += 6;

    return (void *) w - p;

}


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

              QEMUIOVector *qiov, int flags)

{

    BDRVVdiState *s = bs->opaque;

    QEMUIOVector local_qiov;

    uint32_t bmap_entry;

    uint32_t block_index;

    uint32_t offset_in_block;

    uint32_t n_bytes;

    uint64_t bytes_done = 0;

    int ret = 0;

    logout("\n");

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (ret >= 0 && bytes > 0) {

        block_index = offset / s->block_size;

        offset_in_block = offset % s->block_size;

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

        logout("will read %u bytes starting at offset %" PRIu64 "\n",

               n_bytes, offset);

        /* prepare next AIO request */

        bmap_entry = le32_to_cpu(s->bmap[block_index]);

        if (!VDI_IS_ALLOCATED(bmap_entry)) {

            /* Block not allocated, return zeros, no need to wait. */

            qemu_iovec_memset(qiov, bytes_done, 0, n_bytes);

            ret = 0;

        } else {

            uint64_t data_offset = s->header.offset_data +

                                   (uint64_t)bmap_entry * s->block_size +

                                   offset_in_block;

            qemu_iovec_reset(&local_qiov);

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

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

                                 &local_qiov, 0);

        }

        logout("%u bytes read\n", n_bytes);

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    qemu_iovec_destroy(&local_qiov);

    return ret;

}


static void spapr_core_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                            Error **errp)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));

    MachineClass *mc = MACHINE_GET_CLASS(spapr);

    sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);

    sPAPRCPUCore *core = SPAPR_CPU_CORE(OBJECT(dev));

    CPUCore *cc = CPU_CORE(dev);

    CPUState *cs = CPU(core->threads);

    sPAPRDRConnector *drc;

    Error *local_err = NULL;

    void *fdt = NULL;

    int fdt_offset = 0;

    int smt = kvmppc_smt_threads();

    CPUArchId *core_slot;

    int index;

    core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);

    if (!core_slot) {

        error_setg(errp, "Unable to find CPU core with core-id: %d",

                   cc->core_id);

        return;

    }

    drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index * smt);

    g_assert(drc || !mc->has_hotpluggable_cpus);

    /*

     * Setup CPU DT entries only for hotplugged CPUs. For boot time or

     * coldplugged CPUs DT entries are setup in spapr_build_fdt().

     */

    if (dev->hotplugged) {

        fdt = spapr_populate_hotplug_cpu_dt(cs, &fdt_offset, spapr);

    }

    if (drc) {

        spapr_drc_attach(drc, dev, fdt, fdt_offset, !dev->hotplugged,

                         &local_err);

        if (local_err) {

            g_free(fdt);

            error_propagate(errp, local_err);

            return;

        }

    }

    if (dev->hotplugged) {

        /*

         * Send hotplug notification interrupt to the guest only in case

         * of hotplugged CPUs.

         */

        spapr_hotplug_req_add_by_index(drc);

    } else {

        /*

         * Set the right DRC states for cold plugged CPU.

         */

        if (drc) {

            sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

            drck->set_allocation_state(drc, SPAPR_DR_ALLOCATION_STATE_USABLE);

            drck->set_isolation_state(drc, SPAPR_DR_ISOLATION_STATE_UNISOLATED);

        }

    }

    core_slot->cpu = OBJECT(dev);

    if (smc->pre_2_10_has_unused_icps) {

        sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc));

        const char *typename = object_class_get_name(scc->cpu_class);

        size_t size = object_type_get_instance_size(typename);

        int i;

        for (i = 0; i < cc->nr_threads; i++) {

            sPAPRCPUCore *sc = SPAPR_CPU_CORE(dev);

            void *obj = sc->threads + i * size;

            cs = CPU(obj);

            pre_2_10_vmstate_unregister_dummy_icp(cs->cpu_index);

        }

    }

}


static void bt_dummy_lmp_acl_resp(struct bt_link_s *link,

                const uint8_t *data, int start, int len)

{

    fprintf(stderr, "%s: stray ACL response PDU, fixme\n", __FUNCTION__);

    exit(-1);

}


static bool msix_vector_masked(PCIDevice *dev, int vector, bool fmask)

{

    unsigned offset = vector * PCI_MSIX_ENTRY_SIZE + PCI_MSIX_ENTRY_VECTOR_CTRL;

    return fmask || dev->msix_table[offset] & PCI_MSIX_ENTRY_CTRL_MASKBIT;

}


static void virtio_blk_dma_restart_bh(void *opaque)

{

    VirtIOBlock *s = opaque;

    VirtIOBlockReq *req = s->rq;

    MultiReqBuffer mrb = {

        .num_writes = 0,

    };

    qemu_bh_delete(s->bh);

    s->bh = NULL;

    s->rq = NULL;

    while (req) {

        virtio_blk_handle_request(req, &mrb);

        req = req->next;

    }

    if (mrb.num_writes > 0) {

        do_multiwrite(s->bs, mrb.blkreq, mrb.num_writes);

    }

}


iscsi_aio_readv(BlockDriverState *bs, int64_t sector_num,

                QEMUIOVector *qiov, int nb_sectors,

                BlockDriverCompletionFunc *cb,

                void *opaque)

{

    IscsiLun *iscsilun = bs->opaque;

    struct iscsi_context *iscsi = iscsilun->iscsi;

    IscsiAIOCB *acb;

    size_t qemu_read_size;

    int i;

    uint64_t lba;

    uint32_t num_sectors;

    qemu_read_size = BDRV_SECTOR_SIZE * (size_t)nb_sectors;

    acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);

    trace_iscsi_aio_readv(iscsi, sector_num, nb_sectors, opaque, acb);

    acb->iscsilun = iscsilun;

    acb->qiov     = qiov;

    acb->canceled    = 0;

    acb->bh          = NULL;

    acb->status      = -EINPROGRESS;

    acb->read_size   = qemu_read_size;

    acb->buf         = NULL;

    /* If LUN blocksize is bigger than BDRV_BLOCK_SIZE a read from QEMU

     * may be misaligned to the LUN, so we may need to read some extra

     * data.

     */

    acb->read_offset = 0;

    if (iscsilun->block_size > BDRV_SECTOR_SIZE) {

        uint64_t bdrv_offset = BDRV_SECTOR_SIZE * sector_num;

        acb->read_offset  = bdrv_offset % iscsilun->block_size;

    }

    num_sectors  = (qemu_read_size + iscsilun->block_size

                    + acb->read_offset - 1)

                    / iscsilun->block_size;

    acb->task = malloc(sizeof(struct scsi_task));

    if (acb->task == NULL) {

        error_report("iSCSI: Failed to allocate task for scsi READ16 "

                     "command. %s", iscsi_get_error(iscsi));

        qemu_aio_release(acb);

        return NULL;

    }

    memset(acb->task, 0, sizeof(struct scsi_task));

    acb->task->xfer_dir = SCSI_XFER_READ;

    lba = sector_qemu2lun(sector_num, iscsilun);

    acb->task->expxferlen = qemu_read_size;

    switch (iscsilun->type) {

    case TYPE_DISK:

        acb->task->cdb_size = 16;

        acb->task->cdb[0]  = 0x88;

        *(uint32_t *)&acb->task->cdb[2]  = htonl(lba >> 32);

        *(uint32_t *)&acb->task->cdb[6]  = htonl(lba & 0xffffffff);

        *(uint32_t *)&acb->task->cdb[10] = htonl(num_sectors);

        break;

    default:

        acb->task->cdb_size = 10;

        acb->task->cdb[0]  = 0x28;

        *(uint32_t *)&acb->task->cdb[2] = htonl(lba);

        *(uint16_t *)&acb->task->cdb[7] = htons(num_sectors);

        break;

    }

    if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,

                                 iscsi_aio_read16_cb,

                                 NULL,

                                 acb) != 0) {

        scsi_free_scsi_task(acb->task);

        qemu_aio_release(acb);

        return NULL;

    }

    for (i = 0; i < acb->qiov->niov; i++) {

        scsi_task_add_data_in_buffer(acb->task,

                acb->qiov->iov[i].iov_len,

                acb->qiov->iov[i].iov_base);

    }

    iscsi_set_events(iscsilun);

    return &acb->common;

}


static void vmsvga_reset(struct vmsvga_state_s *s)

{

    s->index = 0;

    s->enable = 0;

    s->config = 0;

    s->width = -1;

    s->height = -1;

    s->svgaid = SVGA_ID;

    s->depth = 24;

    s->bypp = (s->depth + 7) >> 3;

    s->cursor.on = 0;

    s->redraw_fifo_first = 0;

    s->redraw_fifo_last = 0;

    switch (s->depth) {

    case 8:

        s->wred   = 0x00000007;

        s->wgreen = 0x00000038;

        s->wblue  = 0x000000c0;

        break;

    case 15:

        s->wred   = 0x0000001f;

        s->wgreen = 0x000003e0;

        s->wblue  = 0x00007c00;

        break;

    case 16:

        s->wred   = 0x0000001f;

        s->wgreen = 0x000007e0;

        s->wblue  = 0x0000f800;

        break;

    case 24:

        s->wred   = 0x00ff0000;

        s->wgreen = 0x0000ff00;

        s->wblue  = 0x000000ff;

        break;

    case 32:

        s->wred   = 0x00ff0000;

        s->wgreen = 0x0000ff00;

        s->wblue  = 0x000000ff;

        break;

    }

    s->syncing = 0;

}


static MpegTSService *mpegts_add_service(MpegTSWrite *ts, int sid,

                                         const char *provider_name,

                                         const char *name)

{

    MpegTSService *service;

    service = av_mallocz(sizeof(MpegTSService));

    if (!service)

        return NULL;

    service->pmt.pid       = ts->pmt_start_pid + ts->nb_services;

    service->sid           = sid;

    service->provider_name = av_strdup(provider_name);

    service->name          = av_strdup(name);

    service->pcr_pid       = 0x1fff;

    dynarray_add(&ts->services, &ts->nb_services, service);

    return service;

}


static const uint8_t *read_huffman_tables(FourXContext *f,

                                          const uint8_t * const buf, int buf_size)

{

    int frequency[512] = { 0 };

    uint8_t flag[512];

    int up[512];

    uint8_t len_tab[257];

    int bits_tab[257];

    int start, end;

    const uint8_t *ptr = buf;

    const uint8_t *ptr_end = buf + buf_size;

    int j;

    memset(up, -1, sizeof(up));

    start = *ptr++;

    end   = *ptr++;

    for (;;) {

        int i;

        if (start <= end && ptr_end - ptr < end - start + 1 + 1)

            return NULL;

        for (i = start; i <= end; i++)

            frequency[i] = *ptr++;

        start = *ptr++;

        if (start == 0)

            break;

        end = *ptr++;

    }

    frequency[256] = 1;

    while ((ptr - buf) & 3)

        ptr++; // 4byte align

    for (j = 257; j < 512; j++) {

        int min_freq[2] = { 256 * 256, 256 * 256 };

        int smallest[2] = { 0, 0 };

        int i;

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

            if (frequency[i] == 0)

                continue;

            if (frequency[i] < min_freq[1]) {

                if (frequency[i] < min_freq[0]) {

                    min_freq[1] = min_freq[0];

                    smallest[1] = smallest[0];

                    min_freq[0] = frequency[i];

                    smallest[0] = i;

                } else {

                    min_freq[1] = frequency[i];

                    smallest[1] = i;

                }

            }

        }

        if (min_freq[1] == 256 * 256)

            break;

        frequency[j]           = min_freq[0] + min_freq[1];

        flag[smallest[0]]      = 0;

        flag[smallest[1]]      = 1;

        up[smallest[0]]        =

        up[smallest[1]]        = j;

        frequency[smallest[0]] = frequency[smallest[1]] = 0;

    }

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

        int node, len = 0, bits = 0;

        for (node = j; up[node] != -1; node = up[node]) {

            bits += flag[node] << len;

            len++;

            if (len > 31)

                // can this happen at all ?

                av_log(f->avctx, AV_LOG_ERROR,

                       "vlc length overflow\n");

        }

        bits_tab[j] = bits;

        len_tab[j]  = len;

    }

    if (init_vlc(&f->pre_vlc, ACDC_VLC_BITS, 257, len_tab, 1, 1,

                 bits_tab, 4, 4, 0))

        return NULL;

    return ptr;

}


static const uint8_t *parse_opus_ts_header(const uint8_t *start, int *payload_len, int buf_len)

{

    const uint8_t *buf = start + 1;

    int start_trim_flag, end_trim_flag, control_extension_flag, control_extension_length;

    uint8_t flags;

    GetByteContext gb;

    bytestream2_init(&gb, buf, buf_len);

    flags = bytestream2_get_byte(&gb);

    start_trim_flag        = (flags >> 4) & 1;

    end_trim_flag          = (flags >> 3) & 1;

    control_extension_flag = (flags >> 2) & 1;

    *payload_len = 0;

    while (bytestream2_peek_byte(&gb) == 0xff)

        *payload_len += bytestream2_get_byte(&gb);

    *payload_len += bytestream2_get_byte(&gb);

    if (start_trim_flag)

        bytestream2_skip(&gb, 2);

    if (end_trim_flag)

        bytestream2_skip(&gb, 2);

    if (control_extension_flag) {

        control_extension_length = bytestream2_get_byte(&gb);

        bytestream2_skip(&gb, control_extension_length);

    }

    return buf + bytestream2_tell(&gb);

}


int qemu_file_rate_limit(QEMUFile *f)

{

    if (qemu_file_get_error(f)) {

        return 1;

    }

    if (f->xfer_limit > 0 && f->bytes_xfer > f->xfer_limit) {

        return 1;

    }

    return 0;

}


GenericList *visit_next_list(Visitor *v, GenericList **list, Error **errp)

{

    if (!error_is_set(errp)) {

        return v->next_list(v, list, errp);

    }

    return 0;

}


static int handle_ping(URLContext *s, RTMPPacket *pkt)

{

    RTMPContext *rt = s->priv_data;

    int t, ret;

    if (pkt->data_size < 2) {

        av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",

               pkt->data_size);

        return AVERROR_INVALIDDATA;

    t = AV_RB16(pkt->data);

    if (t == 6) {

        if ((ret = gen_pong(s, rt, pkt)) < 0)

    return 0;


static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)

{

    AVFilterContext *ctx = inlink->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    AVFilterBufferRef *outpicref = outlink->out_buf;

    OverlayContext *over = ctx->priv;

    if (over->overpicref &&

        !(over->x >= outpicref->video->w || over->y >= outpicref->video->h ||

          y+h < over->y || y >= over->y + over->overpicref->video->h)) {

        blend_slice(ctx, outpicref, over->overpicref, over->x, over->y,

                    over->overpicref->video->w, over->overpicref->video->h,

                    y, outpicref->video->w, h);

    }

    avfilter_draw_slice(outlink, y, h, slice_dir);

}


static void handle_sys(DisasContext *s, uint32_t insn, bool isread,
                       unsigned int op0, unsigned int op1, unsigned int op2,
                       unsigned int crn, unsigned int crm, unsigned int rt)
{
    const ARMCPRegInfo *ri;
    TCGv_i64 tcg_rt;
    ri = get_arm_cp_reginfo(s->cp_regs,
                            ENCODE_AA64_CP_REG(CP_REG_ARM64_SYSREG_CP,
                                               crn, crm, op0, op1, op2));
    if (!ri) {
        /* Unknown register; this might be a guest error or a QEMU
         * unimplemented feature.
        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch64 "
                      "system register op0:%d op1:%d crn:%d crm:%d op2:%d\n",
                      isread ? "read" : "write", op0, op1, crn, crm, op2);
        unallocated_encoding(s);
        return;
    /* Check access permissions */
    if (!cp_access_ok(s->current_pl, ri, isread)) {
        unallocated_encoding(s);
        return;
    /* Handle special cases first */
    switch (ri->type & ~(ARM_CP_FLAG_MASK & ~ARM_CP_SPECIAL)) {
    case ARM_CP_NOP:
        return;
    case ARM_CP_NZCV:
        tcg_rt = cpu_reg(s, rt);
        if (isread) {
            gen_get_nzcv(tcg_rt);
        } else {
            gen_set_nzcv(tcg_rt);
        return;
    default:
        break;
    if (use_icount && (ri->type & ARM_CP_IO)) {
        gen_io_start();
    tcg_rt = cpu_reg(s, rt);
    if (isread) {
        if (ri->type & ARM_CP_CONST) {
            tcg_gen_movi_i64(tcg_rt, ri->resetvalue);
        } else if (ri->readfn) {
            gen_helper_get_cp_reg64(tcg_rt, cpu_env, tmpptr);
        } else {
            tcg_gen_ld_i64(tcg_rt, cpu_env, ri->fieldoffset);
    } else {
        if (ri->type & ARM_CP_CONST) {
            /* If not forbidden by access permissions, treat as WI */
            return;
        } else if (ri->writefn) {
            gen_helper_set_cp_reg64(cpu_env, tmpptr, tcg_rt);
        } else {
            tcg_gen_st_i64(tcg_rt, cpu_env, ri->fieldoffset);
    if (use_icount && (ri->type & ARM_CP_IO)) {
        /* I/O operations must end the TB here (whether read or write) */
        gen_io_end();
        s->is_jmp = DISAS_UPDATE;
    } else if (!isread && !(ri->type & ARM_CP_SUPPRESS_TB_END)) {
        /* We default to ending the TB on a coprocessor register write,
         * but allow this to be suppressed by the register definition
         * (usually only necessary to work around guest bugs).
        s->is_jmp = DISAS_UPDATE;


static void gic_cpu_write(gic_state *s, int cpu, int offset, uint32_t value)

{

    switch (offset) {

    case 0x00: /* Control */

        s->cpu_enabled[cpu] = (value & 1);

        DPRINTF("CPU %d %sabled\n", cpu, s->cpu_enabled ? "En" : "Dis");

        break;

    case 0x04: /* Priority mask */

        s->priority_mask[cpu] = (value & 0xff);

        break;

    case 0x08: /* Binary Point */

        /* ??? Not implemented.  */

        break;

    case 0x10: /* End Of Interrupt */

        return gic_complete_irq(s, cpu, value & 0x3ff);

    default:

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

        return;

    }

    gic_update(s);

}


int avpicture_get_size(enum PixelFormat pix_fmt, int width, int height)

{

    AVPicture dummy_pict;

    if(av_image_check_size(width, height, 0, NULL))

        return -1;

    switch (pix_fmt) {

    case PIX_FMT_RGB8:

    case PIX_FMT_BGR8:

    case PIX_FMT_RGB4_BYTE:

    case PIX_FMT_BGR4_BYTE:

    case PIX_FMT_GRAY8:

        // do not include palette for these pseudo-paletted formats

        return width * height;

    }

    return avpicture_fill(&dummy_pict, NULL, pix_fmt, width, height);

}


static void qemu_rdma_cleanup(RDMAContext *rdma)

{

    struct rdma_cm_event *cm_event;

    int ret, idx;

    if (rdma->cm_id && rdma->connected) {

        if (rdma->error_state) {

            RDMAControlHeader head = { .len = 0,

                                       .type = RDMA_CONTROL_ERROR,

                                       .repeat = 1,

                                     };

            error_report("Early error. Sending error.");

            qemu_rdma_post_send_control(rdma, NULL, &head);

        }

        ret = rdma_disconnect(rdma->cm_id);

        if (!ret) {

            trace_qemu_rdma_cleanup_waiting_for_disconnect();

            ret = rdma_get_cm_event(rdma->channel, &cm_event);

            if (!ret) {

                rdma_ack_cm_event(cm_event);

            }

        }

        trace_qemu_rdma_cleanup_disconnect();

        rdma->connected = false;

    }

    g_free(rdma->block);

    rdma->block = NULL;

    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {

        if (rdma->wr_data[idx].control_mr) {

            rdma->total_registrations--;

            ibv_dereg_mr(rdma->wr_data[idx].control_mr);

        }

        rdma->wr_data[idx].control_mr = NULL;

    }

    if (rdma->local_ram_blocks.block) {

        while (rdma->local_ram_blocks.nb_blocks) {

            rdma_delete_block(rdma, rdma->local_ram_blocks.block->offset);

        }

    }

    if (rdma->cq) {

        ibv_destroy_cq(rdma->cq);

        rdma->cq = NULL;

    }

    if (rdma->comp_channel) {

        ibv_destroy_comp_channel(rdma->comp_channel);

        rdma->comp_channel = NULL;

    }

    if (rdma->pd) {

        ibv_dealloc_pd(rdma->pd);

        rdma->pd = NULL;

    }

    if (rdma->listen_id) {

        rdma_destroy_id(rdma->listen_id);

        rdma->listen_id = NULL;

    }

    if (rdma->cm_id) {

        if (rdma->qp) {

            rdma_destroy_qp(rdma->cm_id);

            rdma->qp = NULL;

        }

        rdma_destroy_id(rdma->cm_id);

        rdma->cm_id = NULL;

    }

    if (rdma->channel) {

        rdma_destroy_event_channel(rdma->channel);

        rdma->channel = NULL;

    }

    g_free(rdma->host);

    rdma->host = NULL;

}


static void write_picture(AVFormatContext *s, int index, AVPicture *picture,

                          int pix_fmt, int w, int h)

{

    UINT8 *buf, *src, *dest;

    int size, j, i;

    size = avpicture_get_size(pix_fmt, w, h);

    buf = malloc(size);

    if (!buf)

        return;

    /* XXX: not efficient, should add test if we can take

       directly the AVPicture */

    switch(pix_fmt) {

    case PIX_FMT_YUV420P:

        dest = buf;

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

            if (i == 1) {

                w >>= 1;

                h >>= 1;

            }

            src = picture->data[i];

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

                memcpy(dest, src, w);

                dest += w;

                src += picture->linesize[i];

            }

        }

        break;

    case PIX_FMT_YUV422P:

        size = (w * h) * 2;

        buf = malloc(size);

        dest = buf;

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

            if (i == 1) {

                w >>= 1;

            }

            src = picture->data[i];

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

                memcpy(dest, src, w);

                dest += w;

                src += picture->linesize[i];

            }

        }

        break;

    case PIX_FMT_YUV444P:

        size = (w * h) * 3;

        buf = malloc(size);

        dest = buf;

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

            src = picture->data[i];

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

                memcpy(dest, src, w);

                dest += w;

                src += picture->linesize[i];

            }

        }

        break;

    case PIX_FMT_YUV422:

        size = (w * h) * 2;

        buf = malloc(size);

        dest = buf;

        src = picture->data[0];

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

            memcpy(dest, src, w * 2);

            dest += w * 2;

            src += picture->linesize[0];

        }

        break;

    case PIX_FMT_RGB24:

    case PIX_FMT_BGR24:

        size = (w * h) * 3;

        buf = malloc(size);

        dest = buf;

        src = picture->data[0];

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

            memcpy(dest, src, w * 3);

            dest += w * 3;

            src += picture->linesize[0];

        }

        break;

    default:

        return;

    }

    s->format->write_packet(s, index, buf, size);

    free(buf);

}


static int drawgrid_filter_frame(AVFilterLink *inlink, AVFrame *frame)

{

    DrawBoxContext *drawgrid = inlink->dst->priv;

    int plane, x, y;

    uint8_t *row[4];

    if (drawgrid->have_alpha) {

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

            row[0] = frame->data[0] + y * frame->linesize[0];

            row[3] = frame->data[3] + y * frame->linesize[3];

            for (plane = 1; plane < 3; plane++)

                row[plane] = frame->data[plane] +

                     frame->linesize[plane] * (y >> drawgrid->vsub);

            if (drawgrid->invert_color) {

                for (x = 0; x < frame->width; x++)

                    if (pixel_belongs_to_grid(drawgrid, x, y))

                        row[0][x] = 0xff - row[0][x];

            } else {

                for (x = 0; x < frame->width; x++) {

                    if (pixel_belongs_to_grid(drawgrid, x, y)) {

                        row[0][x                  ] = drawgrid->yuv_color[Y];

                        row[1][x >> drawgrid->hsub] = drawgrid->yuv_color[U];

                        row[2][x >> drawgrid->hsub] = drawgrid->yuv_color[V];

                        row[3][x                  ] = drawgrid->yuv_color[A];

                    }

                }

            }

        }

    } else {

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

            row[0] = frame->data[0] + y * frame->linesize[0];

            for (plane = 1; plane < 3; plane++)

                row[plane] = frame->data[plane] +

                     frame->linesize[plane] * (y >> drawgrid->vsub);

            if (drawgrid->invert_color) {

                for (x = 0; x < frame->width; x++)

                    if (pixel_belongs_to_grid(drawgrid, x, y))

                        row[0][x] = 0xff - row[0][x];

            } else {

                for (x = 0; x < frame->width; x++) {

                    double alpha = (double)drawgrid->yuv_color[A] / 255;

                    if (pixel_belongs_to_grid(drawgrid, x, y)) {

                        row[0][x                  ] = (1 - alpha) * row[0][x                  ] + alpha * drawgrid->yuv_color[Y];

                        row[1][x >> drawgrid->hsub] = (1 - alpha) * row[1][x >> drawgrid->hsub] + alpha * drawgrid->yuv_color[U];

                        row[2][x >> drawgrid->hsub] = (1 - alpha) * row[2][x >> drawgrid->hsub] + alpha * drawgrid->yuv_color[V];

                    }

                }

            }

        }

    }

    return ff_filter_frame(inlink->dst->outputs[0], frame);

}


void backup_start(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *target, int64_t speed,

                  MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,

                  BlockdevOnError on_source_error,

                  BlockdevOnError on_target_error,

                  BlockCompletionFunc *cb, void *opaque,

                  BlockJobTxn *txn, Error **errp)

{

    int64_t len;

    BlockDriverInfo bdi;

    BackupBlockJob *job = NULL;

    int ret;

    assert(bs);

    assert(target);

    if (bs == target) {

        error_setg(errp, "Source and target cannot be the same");

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(bs));

        return;

    }

    if (!bdrv_is_inserted(target)) {

        error_setg(errp, "Device is not inserted: %s",

                   bdrv_get_device_name(target));

        return;

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        return;

    }

    if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {

        return;

    }

    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {

        if (!sync_bitmap) {

            error_setg(errp, "must provide a valid bitmap name for "

                             "\"incremental\" sync mode");

            return;

        }

        /* Create a new bitmap, and freeze/disable this one. */

        if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {

            return;

        }

    } else if (sync_bitmap) {

        error_setg(errp,

                   "a sync_bitmap was provided to backup_run, "

                   "but received an incompatible sync_mode (%s)",

                   MirrorSyncMode_lookup[sync_mode]);

        return;

    }

    len = bdrv_getlength(bs);

    if (len < 0) {

        error_setg_errno(errp, -len, "unable to get length for '%s'",

                         bdrv_get_device_name(bs));

        goto error;

    }

    job = block_job_create(job_id, &backup_job_driver, bs, speed,

                           cb, opaque, errp);

    if (!job) {

        goto error;

    }

    job->target = blk_new();

    blk_insert_bs(job->target, target);

    job->on_source_error = on_source_error;

    job->on_target_error = on_target_error;

    job->sync_mode = sync_mode;

    job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?

                       sync_bitmap : NULL;

    /* If there is no backing file on the target, we cannot rely on COW if our

     * backup cluster size is smaller than the target cluster size. Even for

     * targets with a backing file, try to avoid COW if possible. */

    ret = bdrv_get_info(target, &bdi);

    if (ret < 0 && !target->backing) {

        error_setg_errno(errp, -ret,

            "Couldn't determine the cluster size of the target image, "

            "which has no backing file");

        error_append_hint(errp,

            "Aborting, since this may create an unusable destination image\n");

        goto error;

    } else if (ret < 0 && target->backing) {

        /* Not fatal; just trudge on ahead. */

        job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;

    } else {

        job->cluster_size = MAX(BACKUP_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);

    }

    bdrv_op_block_all(target, job->common.blocker);

    job->common.len = len;

    job->common.co = qemu_coroutine_create(backup_run);

    block_job_txn_add_job(txn, &job->common);

    qemu_coroutine_enter(job->common.co, job);

    return;

 error:

    if (sync_bitmap) {

        bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);

    }

    if (job) {

        blk_unref(job->target);

        block_job_unref(&job->common);

    }

}


void OPPROTO op_POWER_srea (void)

{

    T1 &= 0x1FUL;

    env->spr[SPR_MQ] = T0 >> T1;

    T0 = Ts0 >> T1;

    RETURN();

}


void qmp_memchar_write(const char *device, const char *data,
                       bool has_format, enum DataFormat format,
                       Error **errp)
{
    CharDriverState *chr;
    const uint8_t *write_data;
    int ret;
    size_t write_count;
    chr = qemu_chr_find(device);
    if (!chr) {
        error_setg(errp, "Device '%s' not found", device);
        return;
    if (qemu_is_chr(chr, "memory")) {
        error_setg(errp,"%s is not memory char device", device);
        return;
    if (has_format && (format == DATA_FORMAT_BASE64)) {
        write_data = g_base64_decode(data, &write_count);
    } else {
        write_data = (uint8_t *)data;
        write_count = strlen(data);
    ret = cirmem_chr_write(chr, write_data, write_count);
    if (ret < 0) {
        error_setg(errp, "Failed to write to device %s", device);
        return;


static void avc_biwgt_16width_msa(uint8_t *src, int32_t src_stride,

                                  uint8_t *dst, int32_t dst_stride,

                                  int32_t height, int32_t log2_denom,

                                  int32_t src_weight, int32_t dst_weight,

                                  int32_t offset_in)

{

    uint8_t cnt;

    v16i8 src_wgt, dst_wgt, wgt;

    v16i8 src0, src1, src2, src3;

    v16i8 dst0, dst1, dst2, dst3;

    v16i8 vec0, vec1, vec2, vec3, vec4, vec5, vec6, vec7;

    v8i16 temp0, temp1, temp2, temp3, temp4, temp5, temp6, temp7;

    v8i16 denom, offset, add_val;

    int32_t val = 128 * (src_weight + dst_weight);

    offset_in = ((offset_in + 1) | 1) << log2_denom;

    src_wgt = __msa_fill_b(src_weight);

    dst_wgt = __msa_fill_b(dst_weight);

    offset = __msa_fill_h(offset_in);

    denom = __msa_fill_h(log2_denom + 1);

    add_val = __msa_fill_h(val);

    offset += add_val;

    wgt = __msa_ilvev_b(dst_wgt, src_wgt);

    for (cnt = height / 4; cnt--;) {

        LOAD_4VECS_SB(src, src_stride, src0, src1, src2, src3);

        src += (4 * src_stride);

        LOAD_4VECS_SB(dst, dst_stride, dst0, dst1, dst2, dst3);

        XORI_B_4VECS_SB(src0, src1, src2, src3, src0, src1, src2, src3, 128);

        XORI_B_4VECS_SB(dst0, dst1, dst2, dst3, dst0, dst1, dst2, dst3, 128);

        ILV_B_LRLR_SB(src0, dst0, src1, dst1, vec1, vec0, vec3, vec2);

        ILV_B_LRLR_SB(src2, dst2, src3, dst3, vec5, vec4, vec7, vec6);

        temp0 = __msa_dpadd_s_h(offset, wgt, vec0);

        temp1 = __msa_dpadd_s_h(offset, wgt, vec1);

        temp2 = __msa_dpadd_s_h(offset, wgt, vec2);

        temp3 = __msa_dpadd_s_h(offset, wgt, vec3);

        temp4 = __msa_dpadd_s_h(offset, wgt, vec4);

        temp5 = __msa_dpadd_s_h(offset, wgt, vec5);

        temp6 = __msa_dpadd_s_h(offset, wgt, vec6);

        temp7 = __msa_dpadd_s_h(offset, wgt, vec7);

        SRA_4VECS(temp0, temp1, temp2, temp3,

                  temp0, temp1, temp2, temp3, denom);

        SRA_4VECS(temp4, temp5, temp6, temp7,

                  temp4, temp5, temp6, temp7, denom);

        temp0 = CLIP_UNSIGNED_CHAR_H(temp0);

        temp1 = CLIP_UNSIGNED_CHAR_H(temp1);

        temp2 = CLIP_UNSIGNED_CHAR_H(temp2);

        temp3 = CLIP_UNSIGNED_CHAR_H(temp3);

        temp4 = CLIP_UNSIGNED_CHAR_H(temp4);

        temp5 = CLIP_UNSIGNED_CHAR_H(temp5);

        temp6 = CLIP_UNSIGNED_CHAR_H(temp6);

        temp7 = CLIP_UNSIGNED_CHAR_H(temp7);

        PCKEV_B_4VECS_SB(temp1, temp3, temp5, temp7, temp0, temp2, temp4, temp6,

                         dst0, dst1, dst2, dst3);

        STORE_4VECS_SB(dst, dst_stride, dst0, dst1, dst2, dst3);

        dst += 4 * dst_stride;

    }

}


int net_init_dump(const NetClientOptions *opts, const char *name,

                  NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    int len;

    const char *file;

    char def_file[128];

    const NetdevDumpOptions *dump;

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_DUMP);

    dump = opts->dump;

    assert(peer);

    if (dump->has_file) {

        file = dump->file;

    } else {

        int id;

        int ret;

        ret = net_hub_id_for_client(peer, &id);

        assert(ret == 0); /* peer must be on a hub */

        snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", id);

        file = def_file;

    }

    if (dump->has_len) {

        if (dump->len > INT_MAX) {

            error_report("invalid length: %"PRIu64, dump->len);

            return -1;

        }

        len = dump->len;

    } else {

        len = 65536;

    }

    return net_dump_init(peer, "dump", name, file, len);

}


int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)

{

    if (*spec <= '9' && *spec >= '0') /* opt:index */

        return strtol(spec, NULL, 0) == st->index;

    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||

             *spec == 't') { /* opt:[vasdt] */

        enum AVMediaType type;

        switch (*spec++) {

        case 'v': type = AVMEDIA_TYPE_VIDEO;      break;

        case 'a': type = AVMEDIA_TYPE_AUDIO;      break;

        case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;

        case 'd': type = AVMEDIA_TYPE_DATA;       break;

        case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;

        }

        if (type != st->codec->codec_type)

            return 0;

        if (*spec++ == ':') { /* possibly followed by :index */

            int i, index = strtol(spec, NULL, 0);

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

                if (s->streams[i]->codec->codec_type == type && index-- == 0)

                   return i == st->index;

            return 0;

        }

        return 1;

    } else if (*spec == 'p' && *(spec + 1) == ':') {

        int prog_id, i, j;

        char *endptr;

        spec += 2;

        prog_id = strtol(spec, &endptr, 0);

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

            if (s->programs[i]->id != prog_id)

                continue;

            if (*endptr++ == ':') {

                int stream_idx = strtol(endptr, NULL, 0);

                return stream_idx >= 0 &&

                    stream_idx < s->programs[i]->nb_stream_indexes &&

                    st->index == s->programs[i]->stream_index[stream_idx];

            }

            for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)

                if (st->index == s->programs[i]->stream_index[j])

                    return 1;

        }

        return 0;

    } else if (!*spec) /* empty specifier, matches everything */

        return 1;

    av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);

    return AVERROR(EINVAL);

}


static void rm_read_metadata(AVFormatContext *s, int wide)

{

    char buf[1024];

    int i;

    for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {

        int len = wide ? avio_rb16(s->pb) : avio_r8(s->pb);

        get_strl(s->pb, buf, sizeof(buf), len);

        av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0);

    }

}


void qmp_migrate(const char *uri, bool has_blk, bool blk,
                 bool has_inc, bool inc, bool has_detach, bool detach,
                 Error **errp)
{
    Error *local_err = NULL;
    MigrationState *s = migrate_get_current();
    MigrationParams params;
    const char *p;
    params.blk = has_blk && blk;
    params.shared = has_inc && inc;
    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP ||
        s->state == MIG_STATE_CANCELLING) {
        error_set(errp, QERR_MIGRATION_ACTIVE);
    if (qemu_savevm_state_blocked(errp)) {
    if (migration_blockers) {
        *errp = error_copy(migration_blockers->data);
    s = migrate_init(&params);
    if (strstart(uri, "tcp:", &p)) {
        tcp_start_outgoing_migration(s, p, &local_err);
#ifdef CONFIG_RDMA
    } else if (strstart(uri, "rdma:", &p)) {
        rdma_start_outgoing_migration(s, p, &local_err);
#endif
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
        exec_start_outgoing_migration(s, p, &local_err);
    } else if (strstart(uri, "unix:", &p)) {
        unix_start_outgoing_migration(s, p, &local_err);
    } else if (strstart(uri, "fd:", &p)) {
        fd_start_outgoing_migration(s, p, &local_err);
#endif
    } else {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
        s->state = MIG_STATE_ERROR;
    if (local_err) {
        migrate_fd_error(s);
        error_propagate(errp, local_err);


static void stm32f2xx_timer_write(void *opaque, hwaddr offset,

                        uint64_t val64, unsigned size)

{

    STM32F2XXTimerState *s = opaque;

    uint32_t value = val64;

    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    uint32_t timer_val = 0;

    DB_PRINT("Write 0x%x, 0x%"HWADDR_PRIx"\n", value, offset);

    switch (offset) {

    case TIM_CR1:

        s->tim_cr1 = value;

        return;

    case TIM_CR2:

        s->tim_cr2 = value;

        return;

    case TIM_SMCR:

        s->tim_smcr = value;

        return;

    case TIM_DIER:

        s->tim_dier = value;

        return;

    case TIM_SR:

        /* This is set by hardware and cleared by software */

        s->tim_sr &= value;

        return;

    case TIM_EGR:

        s->tim_egr = value;

        if (s->tim_egr & TIM_EGR_UG) {

            timer_val = 0;

            break;

        }

        return;

    case TIM_CCMR1:

        s->tim_ccmr1 = value;

        return;

    case TIM_CCMR2:

        s->tim_ccmr2 = value;

        return;

    case TIM_CCER:

        s->tim_ccer = value;

        return;

    case TIM_PSC:

        timer_val = stm32f2xx_ns_to_ticks(s, now) - s->tick_offset;

        s->tim_psc = value;

        value = timer_val;

        break;

    case TIM_CNT:

        timer_val = value;

        break;

    case TIM_ARR:

        s->tim_arr = value;

        stm32f2xx_timer_set_alarm(s, now);

        return;

    case TIM_CCR1:

        s->tim_ccr1 = value;

        return;

    case TIM_CCR2:

        s->tim_ccr2 = value;

        return;

    case TIM_CCR3:

        s->tim_ccr3 = value;

        return;

    case TIM_CCR4:

        s->tim_ccr4 = value;

        return;

    case TIM_DCR:

        s->tim_dcr = value;

        return;

    case TIM_DMAR:

        s->tim_dmar = value;

        return;

    case TIM_OR:

        s->tim_or = value;

        return;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "%s: Bad offset 0x%"HWADDR_PRIx"\n", __func__, offset);

        return;

    }

    /* This means that a register write has affected the timer in a way that

     * requires a refresh of both tick_offset and the alarm.

     */

    s->tick_offset = stm32f2xx_ns_to_ticks(s, now) - timer_val;

    stm32f2xx_timer_set_alarm(s, now);

}


av_cold void ff_vp8dsp_init(VP8DSPContext *dsp)

{

    dsp->vp8_luma_dc_wht    = vp8_luma_dc_wht_c;

    dsp->vp8_luma_dc_wht_dc = vp8_luma_dc_wht_dc_c;

    dsp->vp8_idct_add       = vp8_idct_add_c;

    dsp->vp8_idct_dc_add    = vp8_idct_dc_add_c;

    dsp->vp8_idct_dc_add4y  = vp8_idct_dc_add4y_c;

    dsp->vp8_idct_dc_add4uv = vp8_idct_dc_add4uv_c;

    dsp->vp8_v_loop_filter16y = vp8_v_loop_filter16_c;

    dsp->vp8_h_loop_filter16y = vp8_h_loop_filter16_c;

    dsp->vp8_v_loop_filter8uv = vp8_v_loop_filter8uv_c;

    dsp->vp8_h_loop_filter8uv = vp8_h_loop_filter8uv_c;

    dsp->vp8_v_loop_filter16y_inner = vp8_v_loop_filter16_inner_c;

    dsp->vp8_h_loop_filter16y_inner = vp8_h_loop_filter16_inner_c;

    dsp->vp8_v_loop_filter8uv_inner = vp8_v_loop_filter8uv_inner_c;

    dsp->vp8_h_loop_filter8uv_inner = vp8_h_loop_filter8uv_inner_c;

    dsp->vp8_v_loop_filter_simple = vp8_v_loop_filter_simple_c;

    dsp->vp8_h_loop_filter_simple = vp8_h_loop_filter_simple_c;

    VP8_MC_FUNC(0, 16);

    VP8_MC_FUNC(1, 8);

    VP8_MC_FUNC(2, 4);

    VP8_BILINEAR_MC_FUNC(0, 16);

    VP8_BILINEAR_MC_FUNC(1, 8);

    VP8_BILINEAR_MC_FUNC(2, 4);

    if (ARCH_ARM)

        ff_vp8dsp_init_arm(dsp);

    if (ARCH_PPC)

        ff_vp8dsp_init_ppc(dsp);

    if (ARCH_X86)

        ff_vp8dsp_init_x86(dsp);

}


static void test_qga_file_ops(gconstpointer fix)

{

    const TestFixture *fixture = fix;

    const unsigned char helloworld[] = "Hello World!\n";

    const char *b64;

    gchar *cmd, *path, *enc;

    unsigned char *dec;

    QDict *ret, *val;

    int64_t id, eof;

    gsize count;

    FILE *f;

    char tmp[100];

    /* open */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"

                 " 'arguments': { 'path': 'foo', 'mode': 'w+' } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    id = qdict_get_int(ret, "return");

    QDECREF(ret);

    enc = g_base64_encode(helloworld, sizeof(helloworld));

    /* write */

    cmd = g_strdup_printf("{'execute': 'guest-file-write',"

                          " 'arguments': { 'handle': %" PRId64 ","

                          " 'buf-b64': '%s' } }", id, enc);

    ret = qmp_fd(fixture->fd, cmd);

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    g_assert_cmpint(count, ==, sizeof(helloworld));

    g_assert_cmpint(eof, ==, 0);

    QDECREF(ret);

    g_free(cmd);

    /* flush */

    cmd = g_strdup_printf("{'execute': 'guest-file-flush',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

    /* close */

    cmd = g_strdup_printf("{'execute': 'guest-file-close',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

    /* check content */

    path = g_build_filename(fixture->test_dir, "foo", NULL);

    f = fopen(path, "r");

    g_assert_nonnull(f);

    count = fread(tmp, 1, sizeof(tmp), f);

    g_assert_cmpint(count, ==, sizeof(helloworld));

    tmp[count] = 0;

    g_assert_cmpstr(tmp, ==, (char *)helloworld);

    fclose(f);

    /* open */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-file-open',"

                 " 'arguments': { 'path': 'foo', 'mode': 'r' } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    id = qdict_get_int(ret, "return");

    QDECREF(ret);

    /* read */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, sizeof(helloworld));

    g_assert(eof);

    g_assert_cmpstr(b64, ==, enc);

    QDECREF(ret);

    g_free(cmd);

    g_free(enc);

    /* read eof */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, 0);

    g_assert(eof);

    g_assert_cmpstr(b64, ==, "");

    QDECREF(ret);

    g_free(cmd);

    /* seek */

    cmd = g_strdup_printf("{'execute': 'guest-file-seek',"

                          " 'arguments': { 'handle': %" PRId64 ", "

                          " 'offset': %d, 'whence': '%s' } }",

                          id, 6, "set");

    ret = qmp_fd(fixture->fd, cmd);

    qmp_assert_no_error(ret);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "position");

    eof = qdict_get_bool(val, "eof");

    g_assert_cmpint(count, ==, 6);

    g_assert(!eof);

    QDECREF(ret);

    g_free(cmd);

    /* partial read */

    cmd = g_strdup_printf("{'execute': 'guest-file-read',"

                          " 'arguments': { 'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    val = qdict_get_qdict(ret, "return");

    count = qdict_get_int(val, "count");

    eof = qdict_get_bool(val, "eof");

    b64 = qdict_get_str(val, "buf-b64");

    g_assert_cmpint(count, ==, sizeof(helloworld) - 6);

    g_assert(eof);

    dec = g_base64_decode(b64, &count);

    g_assert_cmpint(count, ==, sizeof(helloworld) - 6);

    g_assert_cmpmem(dec, count, helloworld + 6, sizeof(helloworld) - 6);

    g_free(dec);

    QDECREF(ret);

    g_free(cmd);

    /* close */

    cmd = g_strdup_printf("{'execute': 'guest-file-close',"

                          " 'arguments': {'handle': %" PRId64 "} }",

                          id);

    ret = qmp_fd(fixture->fd, cmd);

    QDECREF(ret);

    g_free(cmd);

}


static bool vexpress_cfgctrl_write(arm_sysctl_state *s, unsigned int dcc,

                                   unsigned int function, unsigned int site,

                                   unsigned int position, unsigned int device,

                                   uint32_t val)

{

    /* We don't support anything other than DCC 0, board stack position 0

     * or sites other than motherboard/daughterboard:

     */

    if (dcc != 0 || position != 0 ||

        (site != SYS_CFG_SITE_MB && site != SYS_CFG_SITE_DB1)) {

        goto cfgctrl_unimp;

    }

    switch (function) {

    case SYS_CFG_OSC:

        if (site == SYS_CFG_SITE_MB && device < sizeof(s->mb_clock)) {

            /* motherboard clock */

            s->mb_clock[device] = val;

            return true;

        }

        if (site == SYS_CFG_SITE_DB1 && device < s->db_num_clocks) {

            /* daughterboard clock */

            s->db_clock[device] = val;

            return true;

        }

        break;

    case SYS_CFG_MUXFPGA:

        if (site == SYS_CFG_SITE_MB && device == 0) {

            /* Select whether video output comes from motherboard

             * or daughterboard: log and ignore as QEMU doesn't

             * support this.

             */

            qemu_log_mask(LOG_UNIMP, "arm_sysctl: selection of video output "

                          "not supported, ignoring\n");

            return true;

        }

        break;

    case SYS_CFG_SHUTDOWN:

        if (site == SYS_CFG_SITE_MB && device == 0) {

            qemu_system_shutdown_request();

            return true;

        }

        break;

    case SYS_CFG_REBOOT:

        if (site == SYS_CFG_SITE_MB && device == 0) {

            qemu_system_reset_request();

            return true;

        }

        break;

    case SYS_CFG_DVIMODE:

        if (site == SYS_CFG_SITE_MB && device == 0) {

            /* Selecting DVI mode is meaningless for QEMU: we will

             * always display the output correctly according to the

             * pixel height/width programmed into the CLCD controller.

             */

            return true;

        }

    default:

        break;

    }

cfgctrl_unimp:

    qemu_log_mask(LOG_UNIMP,

                  "arm_sysctl: Unimplemented SYS_CFGCTRL write of function "

                  "0x%x DCC 0x%x site 0x%x position 0x%x device 0x%x\n",

                  function, dcc, site, position, device);

    return false;

}


pci_ebus_init1(PCIDevice *s)

{

    isa_bus_new(&s->qdev);

    s->config[0x04] = 0x06; // command = bus master, pci mem

    s->config[0x05] = 0x00;

    s->config[0x06] = 0xa0; // status = fast back-to-back, 66MHz, no error

    s->config[0x07] = 0x03; // status = medium devsel

    s->config[0x09] = 0x00; // programming i/f

    s->config[0x0D] = 0x0a; // latency_timer

    pci_register_bar(s, 0, 0x1000000, PCI_BASE_ADDRESS_SPACE_MEMORY,

                           ebus_mmio_mapfunc);

    pci_register_bar(s, 1, 0x800000,  PCI_BASE_ADDRESS_SPACE_MEMORY,

                           ebus_mmio_mapfunc);

    return 0;

}


static int print_uint32(DeviceState *dev, Property *prop, char *dest, size_t len)

{

    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);

    return snprintf(dest, len, "%" PRIu32, *ptr);

}


static inline int pic_is_unused(H264Context *h, Picture *pic)

{

    if (pic->f.data[0] == NULL)

        return 1;

    if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))

        return 1;

    return 0;

}


static int vdpau_alloc(AVCodecContext *s)

{

    InputStream  *ist = s->opaque;

    int loglevel = (ist->hwaccel_id == HWACCEL_AUTO) ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    AVVDPAUContext *vdpau_ctx;

    VDPAUContext *ctx;

    const char *display, *vendor;

    VdpStatus err;

    int i;

    ctx = av_mallocz(sizeof(*ctx));

    if (!ctx)

        return AVERROR(ENOMEM);

    ist->hwaccel_ctx           = ctx;

    ist->hwaccel_uninit        = vdpau_uninit;

    ist->hwaccel_get_buffer    = vdpau_get_buffer;

    ist->hwaccel_retrieve_data = vdpau_retrieve_data;

    ctx->tmp_frame = av_frame_alloc();

    if (!ctx->tmp_frame)

        goto fail;

    ctx->dpy = XOpenDisplay(ist->hwaccel_device);

    if (!ctx->dpy) {

        av_log(NULL, loglevel, "Cannot open the X11 display %s.\n",

               XDisplayName(ist->hwaccel_device));

        goto fail;

    }

    display = XDisplayString(ctx->dpy);

    err = vdp_device_create_x11(ctx->dpy, XDefaultScreen(ctx->dpy), &ctx->device,

                                &ctx->get_proc_address);

    if (err != VDP_STATUS_OK) {

        av_log(NULL, loglevel, "VDPAU device creation on X11 display %s failed.\n",

               display);

        goto fail;

    }

#define GET_CALLBACK(id, result)                                                \

do {                                                                            \

    void *tmp;                                                                  \

    err = ctx->get_proc_address(ctx->device, id, &tmp);                         \

    if (err != VDP_STATUS_OK) {                                                 \

        av_log(NULL, loglevel, "Error getting the " #id " callback.\n");        \

        goto fail;                                                              \

    }                                                                           \

    ctx->result = tmp;                                                          \

} while (0)

    GET_CALLBACK(VDP_FUNC_ID_GET_ERROR_STRING,               get_error_string);

    GET_CALLBACK(VDP_FUNC_ID_GET_INFORMATION_STRING,         get_information_string);

    GET_CALLBACK(VDP_FUNC_ID_DEVICE_DESTROY,                 device_destroy);

    if (vdpau_api_ver == 1) {

        GET_CALLBACK(VDP_FUNC_ID_DECODER_CREATE,                 decoder_create);

        GET_CALLBACK(VDP_FUNC_ID_DECODER_DESTROY,                decoder_destroy);

        GET_CALLBACK(VDP_FUNC_ID_DECODER_RENDER,                 decoder_render);

    }

    GET_CALLBACK(VDP_FUNC_ID_VIDEO_SURFACE_CREATE,           video_surface_create);

    GET_CALLBACK(VDP_FUNC_ID_VIDEO_SURFACE_DESTROY,          video_surface_destroy);

    GET_CALLBACK(VDP_FUNC_ID_VIDEO_SURFACE_GET_BITS_Y_CB_CR, video_surface_get_bits);

    GET_CALLBACK(VDP_FUNC_ID_VIDEO_SURFACE_GET_PARAMETERS,   video_surface_get_parameters);

    GET_CALLBACK(VDP_FUNC_ID_VIDEO_SURFACE_QUERY_GET_PUT_BITS_Y_CB_CR_CAPABILITIES,

                 video_surface_query);

    for (i = 0; i < FF_ARRAY_ELEMS(vdpau_formats); i++) {

        VdpBool supported;

        err = ctx->video_surface_query(ctx->device, VDP_CHROMA_TYPE_420,

                                       vdpau_formats[i][0], &supported);

        if (err != VDP_STATUS_OK) {

            av_log(NULL, loglevel,

                   "Error querying VDPAU surface capabilities: %s\n",

                   ctx->get_error_string(err));

            goto fail;

        }

        if (supported)

            break;

    }

    if (i == FF_ARRAY_ELEMS(vdpau_formats)) {

        av_log(NULL, loglevel,

               "No supported VDPAU format for retrieving the data.\n");

        return AVERROR(EINVAL);

    }

    ctx->vdpau_format = vdpau_formats[i][0];

    ctx->pix_fmt      = vdpau_formats[i][1];

    if (vdpau_api_ver == 1) {

        vdpau_ctx = av_vdpau_alloc_context();

        if (!vdpau_ctx)

            goto fail;

        vdpau_ctx->render = ctx->decoder_render;

        s->hwaccel_context = vdpau_ctx;

    } else

    if (av_vdpau_bind_context(s, ctx->device, ctx->get_proc_address, 0))

        goto fail;

    ctx->get_information_string(&vendor);

    av_log(NULL, AV_LOG_VERBOSE, "Using VDPAU -- %s -- on X11 display %s, "

           "to decode input stream #%d:%d.\n", vendor,

           display, ist->file_index, ist->st->index);

    return 0;

fail:

    av_log(NULL, loglevel, "VDPAU init failed for stream #%d:%d.\n",

           ist->file_index, ist->st->index);

    vdpau_uninit(s);

    return AVERROR(EINVAL);

}


void ff_h263_encode_mb(MpegEncContext * s,

                       int16_t block[6][64],

                       int motion_x, int motion_y)

{

    int cbpc, cbpy, i, cbp, pred_x, pred_y;

    int16_t pred_dc;

    int16_t rec_intradc[6];

    int16_t *dc_ptr[6];

    const int interleaved_stats= (s->flags&CODEC_FLAG_PASS1);

    if (!s->mb_intra) {

        /* compute cbp */

        cbp= get_p_cbp(s, block, motion_x, motion_y);

        if ((cbp | motion_x | motion_y | s->dquant | (s->mv_type - MV_TYPE_16X16)) == 0) {

            /* skip macroblock */

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

            if(interleaved_stats){

                s->misc_bits++;

                s->last_bits++;

            }

            s->skip_count++;

            return;

        }

        put_bits(&s->pb, 1, 0);         /* mb coded */

        cbpc = cbp & 3;

        cbpy = cbp >> 2;

        if(s->alt_inter_vlc==0 || cbpc!=3)

            cbpy ^= 0xF;

        if(s->dquant) cbpc+= 8;

        if(s->mv_type==MV_TYPE_16X16){

            put_bits(&s->pb,

                    ff_h263_inter_MCBPC_bits[cbpc],

                    ff_h263_inter_MCBPC_code[cbpc]);

            put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);

            if(s->dquant)

                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);

            if(interleaved_stats){

                s->misc_bits+= get_bits_diff(s);

            }

            /* motion vectors: 16x16 mode */

            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);

            if (!s->umvplus) {

                ff_h263_encode_motion_vector(s, motion_x - pred_x,

                                                motion_y - pred_y, 1);

            }

            else {

                h263p_encode_umotion(s, motion_x - pred_x);

                h263p_encode_umotion(s, motion_y - pred_y);

                if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))

                    /* To prevent Start Code emulation */

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

            }

        }else{

            put_bits(&s->pb,

                    ff_h263_inter_MCBPC_bits[cbpc+16],

                    ff_h263_inter_MCBPC_code[cbpc+16]);

            put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);

            if(s->dquant)

                put_bits(&s->pb, 2, dquant_code[s->dquant+2]);

            if(interleaved_stats){

                s->misc_bits+= get_bits_diff(s);

            }

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

                /* motion vectors: 8x8 mode*/

                ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);

                motion_x = s->current_picture.motion_val[0][s->block_index[i]][0];

                motion_y = s->current_picture.motion_val[0][s->block_index[i]][1];

                if (!s->umvplus) {

                    ff_h263_encode_motion_vector(s, motion_x - pred_x,

                                                    motion_y - pred_y, 1);

                }

                else {

                    h263p_encode_umotion(s, motion_x - pred_x);

                    h263p_encode_umotion(s, motion_y - pred_y);

                    if (((motion_x - pred_x) == 1) && ((motion_y - pred_y) == 1))

                        /* To prevent Start Code emulation */

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

                }

            }

        }

        if(interleaved_stats){

            s->mv_bits+= get_bits_diff(s);

        }

    } else {

        assert(s->mb_intra);

        cbp = 0;

        if (s->h263_aic) {

            /* Predict DC */

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

                int16_t level = block[i][0];

                int scale;

                if(i<4) scale= s->y_dc_scale;

                else    scale= s->c_dc_scale;

                pred_dc = ff_h263_pred_dc(s, i, &dc_ptr[i]);

                level -= pred_dc;

                /* Quant */

                if (level >= 0)

                    level = (level + (scale>>1))/scale;

                else

                    level = (level - (scale>>1))/scale;

                /* AIC can change CBP */

                if (level == 0 && s->block_last_index[i] == 0)

                    s->block_last_index[i] = -1;

                if(!s->modified_quant){

                    if (level < -127)

                        level = -127;

                    else if (level > 127)

                        level = 127;

                }

                block[i][0] = level;

                /* Reconstruction */

                rec_intradc[i] = scale*level + pred_dc;

                /* Oddify */

                rec_intradc[i] |= 1;

                //if ((rec_intradc[i] % 2) == 0)

                //    rec_intradc[i]++;

                /* Clipping */

                if (rec_intradc[i] < 0)

                    rec_intradc[i] = 0;

                else if (rec_intradc[i] > 2047)

                    rec_intradc[i] = 2047;

                /* Update AC/DC tables */

                *dc_ptr[i] = rec_intradc[i];

                if (s->block_last_index[i] >= 0)

                    cbp |= 1 << (5 - i);

            }

        }else{

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

                /* compute cbp */

                if (s->block_last_index[i] >= 1)

                    cbp |= 1 << (5 - i);

            }

        }

        cbpc = cbp & 3;

        if (s->pict_type == AV_PICTURE_TYPE_I) {

            if(s->dquant) cbpc+=4;

            put_bits(&s->pb,

                ff_h263_intra_MCBPC_bits[cbpc],

                ff_h263_intra_MCBPC_code[cbpc]);

        } else {

            if(s->dquant) cbpc+=8;

            put_bits(&s->pb, 1, 0);     /* mb coded */

            put_bits(&s->pb,

                ff_h263_inter_MCBPC_bits[cbpc + 4],

                ff_h263_inter_MCBPC_code[cbpc + 4]);

        }

        if (s->h263_aic) {

            /* XXX: currently, we do not try to use ac prediction */

            put_bits(&s->pb, 1, 0);     /* no AC prediction */

        }

        cbpy = cbp >> 2;

        put_bits(&s->pb, ff_h263_cbpy_tab[cbpy][1], ff_h263_cbpy_tab[cbpy][0]);

        if(s->dquant)

            put_bits(&s->pb, 2, dquant_code[s->dquant+2]);

        if(interleaved_stats){

            s->misc_bits+= get_bits_diff(s);

        }

    }

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

        /* encode each block */

        h263_encode_block(s, block[i], i);

        /* Update INTRADC for decoding */

        if (s->h263_aic && s->mb_intra) {

            block[i][0] = rec_intradc[i];

        }

    }

    if(interleaved_stats){

        if (!s->mb_intra) {

            s->p_tex_bits+= get_bits_diff(s);

            s->f_count++;

        }else{

            s->i_tex_bits+= get_bits_diff(s);

            s->i_count++;

        }

    }

}


static int hls_mux_init(AVFormatContext *s)

{

    HLSContext *hls = s->priv_data;

    AVFormatContext *oc;

    AVFormatContext *vtt_oc;

    int i, ret;

    ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);

    if (ret < 0)

        return ret;

    oc = hls->avf;

    oc->oformat            = hls->oformat;

    oc->interrupt_callback = s->interrupt_callback;

    oc->max_delay          = s->max_delay;

    av_dict_copy(&oc->metadata, s->metadata, 0);

    if(hls->vtt_oformat) {

        ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);

        if (ret < 0)

            return ret;

        vtt_oc          = hls->vtt_avf;

        vtt_oc->oformat = hls->vtt_oformat;

        av_dict_copy(&vtt_oc->metadata, s->metadata, 0);

    }

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

        AVStream *st;

        AVFormatContext *loc;

        if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)

            loc = vtt_oc;

        else

            loc = oc;

        if (!(st = avformat_new_stream(loc, NULL)))

            return AVERROR(ENOMEM);

        avcodec_copy_context(st->codec, s->streams[i]->codec);

        st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;

        st->time_base = s->streams[i]->time_base;

    }

    hls->start_pos = 0;

    return 0;

}


void idct_put_altivec(uint8_t* dest, int stride, vector_s16_t* block)

{

POWERPC_TBL_DECLARE(altivec_idct_put_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

POWERPC_TBL_START_COUNT(altivec_idct_put_num, 1);

    void simple_idct_put(uint8_t *dest, int line_size, int16_t *block);

    simple_idct_put(dest, stride, (int16_t*)block);

POWERPC_TBL_STOP_COUNT(altivec_idct_put_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    vector_u8_t tmp;

POWERPC_TBL_START_COUNT(altivec_idct_put_num, 1);

    IDCT

#define COPY(dest,src)						\

    tmp = vec_packsu (src, src);				\

    vec_ste ((vector_u32_t)tmp, 0, (unsigned int *)dest);	\

    vec_ste ((vector_u32_t)tmp, 4, (unsigned int *)dest);

    COPY (dest, vx0)	dest += stride;

    COPY (dest, vx1)	dest += stride;

    COPY (dest, vx2)	dest += stride;

    COPY (dest, vx3)	dest += stride;

    COPY (dest, vx4)	dest += stride;

    COPY (dest, vx5)	dest += stride;

    COPY (dest, vx6)	dest += stride;

    COPY (dest, vx7)

POWERPC_TBL_STOP_COUNT(altivec_idct_put_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


static void opt_top_field_first(const char *arg)

{

    top_field_first= atoi(arg);

}