static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    AVIContext *avi = s->priv_data;
    ByteIOContext *pb = s->pb;
    int n, d[8], size;
    offset_t i, sync;
    void* dstr;
    if (ENABLE_DV_DEMUXER && avi->dv_demux) {
        size = dv_get_packet(avi->dv_demux, pkt);
        if (size >= 0)
            return size;
    }
    if(avi->non_interleaved){
        int best_stream_index = 0;
        AVStream *best_st= NULL;
        AVIStream *best_ast;
        int64_t best_ts= INT64_MAX;
        int i;
        for(i=0; i<s->nb_streams; i++){
            AVStream *st = s->streams[i];
            AVIStream *ast = st->priv_data;
            int64_t ts= ast->frame_offset;
            if(ast->sample_size)
                ts /= ast->sample_size;
            ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
//            av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
            if(ts < best_ts && st->nb_index_entries){
                best_ts= ts;
                best_st= st;
                best_stream_index= i;
            }
        }
        best_ast = best_st->priv_data;
        best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
        if(best_ast->remaining)
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
        else
            i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
//        av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
        if(i>=0){
            int64_t pos= best_st->index_entries[i].pos;
            pos += best_ast->packet_size - best_ast->remaining;
            url_fseek(s->pb, pos + 8, SEEK_SET);
//        av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
            assert(best_ast->remaining <= best_ast->packet_size);
            avi->stream_index= best_stream_index;
            if(!best_ast->remaining)
                best_ast->packet_size=
                best_ast->remaining= best_st->index_entries[i].size;
        }
    }
resync:
    if(avi->stream_index >= 0){
        AVStream *st= s->streams[ avi->stream_index ];
        AVIStream *ast= st->priv_data;
        int size;
        if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
            size= INT_MAX;
        else if(ast->sample_size < 32)
            size= 64*ast->sample_size;
        else
            size= ast->sample_size;
        if(size > ast->remaining)
            size= ast->remaining;
        av_get_packet(pb, pkt, size);
        if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
            ast->has_pal=0;
            pkt->size += 4*256;
            pkt->data = av_realloc(pkt->data, pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
            if(pkt->data)
                memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
        }
        if (ENABLE_DV_DEMUXER && avi->dv_demux) {
            dstr = pkt->destruct;
            size = dv_produce_packet(avi->dv_demux, pkt,
                                    pkt->data, pkt->size);
            pkt->destruct = dstr;
            pkt->flags |= PKT_FLAG_KEY;
        } else {
            /* XXX: how to handle B frames in avi ? */
            pkt->dts = ast->frame_offset;
//                pkt->dts += ast->start;
            if(ast->sample_size)
                pkt->dts /= ast->sample_size;
//av_log(NULL, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
            pkt->stream_index = avi->stream_index;
            if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
                AVIndexEntry *e;
                int index;
                assert(st->index_entries);
                index= av_index_search_timestamp(st, pkt->dts, 0);
                e= &st->index_entries[index];
                if(index >= 0 && e->timestamp == ast->frame_offset){
                    if (e->flags & AVINDEX_KEYFRAME)
                        pkt->flags |= PKT_FLAG_KEY;
                }
            } else {
                pkt->flags |= PKT_FLAG_KEY;
            }
            if(ast->sample_size)
                ast->frame_offset += pkt->size;
            else
                ast->frame_offset++;
        }
        ast->remaining -= size;
        if(!ast->remaining){
            avi->stream_index= -1;
            ast->packet_size= 0;
        }
        return size;
    }
    memset(d, -1, sizeof(int)*8);
    for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
        int j;
        for(j=0; j<7; j++)
            d[j]= d[j+1];
        d[7]= get_byte(pb);
        size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
        if(    d[2] >= '0' && d[2] <= '9'
            && d[3] >= '0' && d[3] <= '9'){
            n= (d[2] - '0') * 10 + (d[3] - '0');
        }else{
            n= 100; //invalid stream id
        }
//av_log(NULL, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
        if(i + size > avi->fsize || d[0]<0)
            continue;
        //parse ix##
        if(  (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
        //parse JUNK
           ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
           ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
            url_fskip(pb, size);
//av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
            goto resync;
        }
        if(    d[0] >= '0' && d[0] <= '9'
            && d[1] >= '0' && d[1] <= '9'){
            n= (d[0] - '0') * 10 + (d[1] - '0');
        }else{
            n= 100; //invalid stream id
        }
        //parse ##dc/##wb
        if(n < s->nb_streams){
            AVStream *st;
            AVIStream *ast;
            st = s->streams[n];
            ast = st->priv_data;
            if(s->nb_streams>=2){
                AVStream *st1  = s->streams[1];
                AVIStream *ast1= st1->priv_data;
                //workaround for broken small-file-bug402.avi
                if(   d[2] == 'w' && d[3] == 'b'
                   && n==0
                   && st ->codec->codec_type == CODEC_TYPE_VIDEO
                   && st1->codec->codec_type == CODEC_TYPE_AUDIO
                   && ast->prefix == 'd'*256+'c'
                   && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
                  ){
                    n=1;
                    st = st1;
                    ast = ast1;
                    av_log(s, AV_LOG_WARNING, "Invalid stream+prefix combination, assuming audio\n");
                }
            }
            if(   (st->discard >= AVDISCARD_DEFAULT && size==0)
               /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
               || st->discard >= AVDISCARD_ALL){
                if(ast->sample_size) ast->frame_offset += pkt->size;
                else                 ast->frame_offset++;
                url_fskip(pb, size);
                goto resync;
            }
            if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
                int k = get_byte(pb);
                int last = (k + get_byte(pb) - 1) & 0xFF;
                get_le16(pb); //flags
                for (; k <= last; k++)
                    ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
                ast->has_pal= 1;
                goto resync;
            } else if(   ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
                         d[2]*256+d[3] == ast->prefix /*||
                         (d[2] == 'd' && d[3] == 'c') ||
                         (d[2] == 'w' && d[3] == 'b')*/) {
//av_log(NULL, AV_LOG_DEBUG, "OK\n");
                if(d[2]*256+d[3] == ast->prefix)
                    ast->prefix_count++;
                else{
                    ast->prefix= d[2]*256+d[3];
                    ast->prefix_count= 0;
                }
                avi->stream_index= n;
                ast->packet_size= size + 8;
                ast->remaining= size;
                {
                    uint64_t pos= url_ftell(pb) - 8;
                    if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
                        av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
                    }
                }
                goto resync;
            }
        }
    }
}


static bool is_zero_cluster_top_locked(BlockDriverState *bs, int64_t start)

{

    BDRVQcow2State *s = bs->opaque;

    int nr = s->cluster_sectors;

    uint64_t off;

    int ret;

    ret = qcow2_get_cluster_offset(bs, start << BDRV_SECTOR_BITS, &nr, &off);

    assert(nr == s->cluster_sectors);

    return ret == QCOW2_CLUSTER_UNALLOCATED || ret == QCOW2_CLUSTER_ZERO;

}


void spapr_lmb_release(DeviceState *dev)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_hotplug_handler(dev));

    PCDIMMDevice *dimm = PC_DIMM(dev);

    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);

    MemoryRegion *mr = ddc->get_memory_region(dimm);

    sPAPRDIMMState *ds = spapr_pending_dimm_unplugs_find(spapr, PC_DIMM(dev));

    /* This information will get lost if a migration occurs

     * during the unplug process. In this case recover it. */

    if (ds == NULL) {

        ds = spapr_recover_pending_dimm_state(spapr, PC_DIMM(dev));

        g_assert(ds);

        /* The DRC being examined by the caller at least must be counted */

        g_assert(ds->nr_lmbs);

    }

    if (--ds->nr_lmbs) {

        return;

    }

    spapr_pending_dimm_unplugs_remove(spapr, ds);

    /*

     * Now that all the LMBs have been removed by the guest, call the

     * pc-dimm unplug handler to cleanup up the pc-dimm device.

     */

    pc_dimm_memory_unplug(dev, &spapr->hotplug_memory, mr);

    object_unparent(OBJECT(dev));

}


static void pc_xen_hvm_init(MachineState *machine)
{
    PCIBus *bus;
    pc_xen_hvm_init_pci(machine);
    bus = pci_find_primary_bus();
    if (bus != NULL) {
        pci_create_simple(bus, -1, "xen-platform");


static int usb_xhci_post_load(void *opaque, int version_id)

{

    XHCIState *xhci = opaque;

    PCIDevice *pci_dev = PCI_DEVICE(xhci);

    XHCISlot *slot;

    XHCIEPContext *epctx;

    dma_addr_t dcbaap, pctx;

    uint32_t slot_ctx[4];

    uint32_t ep_ctx[5];

    int slotid, epid, state, intr;

    dcbaap = xhci_addr64(xhci->dcbaap_low, xhci->dcbaap_high);

    for (slotid = 1; slotid <= xhci->numslots; slotid++) {

        slot = &xhci->slots[slotid-1];

        if (!slot->addressed) {

        slot->ctx =

            xhci_mask64(ldq_le_pci_dma(pci_dev, dcbaap + 8 * slotid));

        xhci_dma_read_u32s(xhci, slot->ctx, slot_ctx, sizeof(slot_ctx));

        slot->uport = xhci_lookup_uport(xhci, slot_ctx);

        assert(slot->uport && slot->uport->dev);

        for (epid = 1; epid <= 31; epid++) {

            pctx = slot->ctx + 32 * epid;

            xhci_dma_read_u32s(xhci, pctx, ep_ctx, sizeof(ep_ctx));

            state = ep_ctx[0] & EP_STATE_MASK;

            if (state == EP_DISABLED) {

            epctx = xhci_alloc_epctx(xhci, slotid, epid);

            slot->eps[epid-1] = epctx;

            xhci_init_epctx(epctx, pctx, ep_ctx);

            epctx->state = state;

            if (state == EP_RUNNING) {

                /* kick endpoint after vmload is finished */

                timer_mod(epctx->kick_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));

    for (intr = 0; intr < xhci->numintrs; intr++) {

        if (xhci->intr[intr].msix_used) {

            msix_vector_use(pci_dev, intr);

        } else {

            msix_vector_unuse(pci_dev, intr);

    return 0;


void acpi_pm_tmr_init(ACPIREGS *ar, acpi_update_sci_fn update_sci,

                      MemoryRegion *parent)

{

    ar->tmr.update_sci = update_sci;

    ar->tmr.timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, acpi_pm_tmr_timer, ar);

    memory_region_init_io(&ar->tmr.io, memory_region_owner(parent),

                          &acpi_pm_tmr_ops, ar, "acpi-tmr", 4);

    memory_region_clear_global_locking(&ar->tmr.io);

    memory_region_add_subregion(parent, 8, &ar->tmr.io);

}


INLINE int16 extractFloat32Exp( float32 a )

{

    return ( a>>23 ) & 0xFF;

}


START_TEST(simple_string)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

    } test_cases[] = {

        { "\"hello world\"", "hello world" },

        { "\"the quick brown fox jumped over the fence\"",

          "the quick brown fox jumped over the fence" },

        {}

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QSTRING);

        str = qobject_to_qstring(obj);

        fail_unless(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        str = qobject_to_json(obj);

        fail_unless(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

        qobject_decref(obj);

        QDECREF(str);

    }

}


int decode_luma_residual(const H264Context *h, H264SliceContext *sl,

                         GetBitContext *gb, const uint8_t *scan,

                         const uint8_t *scan8x8, int pixel_shift,

                         int mb_type, int cbp, int p)

{

    int i4x4, i8x8;

    int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1];

    if(IS_INTRA16x16(mb_type)){

        AV_ZERO128(sl->mb_luma_dc[p]+0);

        AV_ZERO128(sl->mb_luma_dc[p]+8);

        AV_ZERO128(sl->mb_luma_dc[p]+16);

        AV_ZERO128(sl->mb_luma_dc[p]+24);

        if (decode_residual(h, sl, gb, sl->mb_luma_dc[p], LUMA_DC_BLOCK_INDEX + p, scan, NULL, 16) < 0) {

            return -1; //FIXME continue if partitioned and other return -1 too

        }

        assert((cbp&15) == 0 || (cbp&15) == 15);

        if(cbp&15){

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

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

                    const int index= i4x4 + 4*i8x8 + p*16;

                    if( decode_residual(h, sl, gb, sl->mb + (16*index << pixel_shift),

                        index, scan + 1, h->dequant4_coeff[p][qscale], 15) < 0 ){

                        return -1;

                    }

                }

            }

            return 0xf;

        }else{

            fill_rectangle(&sl->non_zero_count_cache[scan8[p*16]], 4, 4, 8, 0, 1);

            return 0;

        }

    }else{

        int cqm = (IS_INTRA( mb_type ) ? 0:3)+p;

        /* For CAVLC 4:4:4, we need to keep track of the luma 8x8 CBP for deblocking nnz purposes. */

        int new_cbp = 0;

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

            if(cbp & (1<<i8x8)){

                if(IS_8x8DCT(mb_type)){

                    int16_t *buf = &sl->mb[64*i8x8+256*p << pixel_shift];

                    uint8_t *nnz;

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

                        const int index= i4x4 + 4*i8x8 + p*16;

                        if( decode_residual(h, sl, gb, buf, index, scan8x8+16*i4x4,

                                            h->dequant8_coeff[cqm][qscale], 16) < 0 )

                            return -1;

                    }

                    nnz = &sl->non_zero_count_cache[scan8[4 * i8x8 + p * 16]];

                    nnz[0] += nnz[1] + nnz[8] + nnz[9];

                    new_cbp |= !!nnz[0] << i8x8;

                }else{

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

                        const int index= i4x4 + 4*i8x8 + p*16;

                        if( decode_residual(h, sl, gb, sl->mb + (16*index << pixel_shift), index,

                                            scan, h->dequant4_coeff[cqm][qscale], 16) < 0 ){

                            return -1;

                        }

                        new_cbp |= sl->non_zero_count_cache[scan8[index]] << i8x8;

                    }

                }

            }else{

                uint8_t * const nnz = &sl->non_zero_count_cache[scan8[4 * i8x8 + p * 16]];

                nnz[0] = nnz[1] = nnz[8] = nnz[9] = 0;

            }

        }

        return new_cbp;

    }

}


static int get_codec_data(AVIOContext *pb, AVStream *vst,

                          AVStream *ast, int myth)

{

    nuv_frametype frametype;

    if (!vst && !myth)

        return 1; // no codec data needed

    while (!avio_feof(pb)) {

        int size, subtype;

        frametype = avio_r8(pb);

        switch (frametype) {

        case NUV_EXTRADATA:

            subtype = avio_r8(pb);

            avio_skip(pb, 6);

            size = PKTSIZE(avio_rl32(pb));

            if (vst && subtype == 'R') {

                if (vst->codecpar->extradata) {

                    av_freep(&vst->codecpar->extradata);

                    vst->codecpar->extradata_size = 0;

                }

                if (ff_get_extradata(NULL, vst->codecpar, pb, size) < 0)

                    return AVERROR(ENOMEM);

                size = 0;

                if (!myth)

                    return 0;

            }

            break;

        case NUV_MYTHEXT:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            if (size != 128 * 4)

                break;

            avio_rl32(pb); // version

            if (vst) {

                vst->codecpar->codec_tag = avio_rl32(pb);

                vst->codecpar->codec_id =

                    ff_codec_get_id(ff_codec_bmp_tags, vst->codecpar->codec_tag);

                if (vst->codecpar->codec_tag == MKTAG('R', 'J', 'P', 'G'))

                    vst->codecpar->codec_id = AV_CODEC_ID_NUV;

            } else

                avio_skip(pb, 4);

            if (ast) {

                int id;

                ast->codecpar->codec_tag             = avio_rl32(pb);

                ast->codecpar->sample_rate           = avio_rl32(pb);

                ast->codecpar->bits_per_coded_sample = avio_rl32(pb);

                ast->codecpar->channels              = avio_rl32(pb);

                ast->codecpar->channel_layout        = 0;

                id = ff_wav_codec_get_id(ast->codecpar->codec_tag,

                                         ast->codecpar->bits_per_coded_sample);

                if (id == AV_CODEC_ID_NONE) {

                    id = ff_codec_get_id(nuv_audio_tags, ast->codecpar->codec_tag);

                    if (id == AV_CODEC_ID_PCM_S16LE)

                        id = ff_get_pcm_codec_id(ast->codecpar->bits_per_coded_sample,

                                                 0, 0, ~1);

                }

                ast->codecpar->codec_id = id;

                ast->need_parsing = AVSTREAM_PARSE_FULL;

            } else

                avio_skip(pb, 4 * 4);

            size -= 6 * 4;

            avio_skip(pb, size);

            return 0;

        case NUV_SEEKP:

            size = 11;

            break;

        default:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            break;

        }

        avio_skip(pb, size);

    }

    return 0;

}


ram_addr_t migration_bitmap_find_and_reset_dirty(MemoryRegion *mr,

                                                 ram_addr_t start)

{

    unsigned long base = mr->ram_addr >> TARGET_PAGE_BITS;

    unsigned long nr = base + (start >> TARGET_PAGE_BITS);

    uint64_t mr_size = TARGET_PAGE_ALIGN(memory_region_size(mr));

    unsigned long size = base + (mr_size >> TARGET_PAGE_BITS);

    unsigned long next;

    if (ram_bulk_stage && nr > base) {

        next = nr + 1;

    } else {

        next = find_next_bit(migration_bitmap, size, nr);

    }

    if (next < size) {

        clear_bit(next, migration_bitmap);

        migration_dirty_pages--;

    }

    return (next - base) << TARGET_PAGE_BITS;

}


static uint64_t unassigned_mem_read(void *opaque, target_phys_addr_t addr,

                                    unsigned size)

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem read " TARGET_FMT_plx "\n", addr);

#endif

#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)

    cpu_unassigned_access(cpu_single_env, addr, 0, 0, 0, size);

#endif

    return 0;

}


build_rsdt(GArray *table_data, GArray *linker, GArray *table_offsets,

           const char *oem_id, const char *oem_table_id)

{

    AcpiRsdtDescriptorRev1 *rsdt;

    size_t rsdt_len;

    int i;

    const int table_data_len = (sizeof(uint32_t) * table_offsets->len);

    rsdt_len = sizeof(*rsdt) + table_data_len;

    rsdt = acpi_data_push(table_data, rsdt_len);

    memcpy(rsdt->table_offset_entry, table_offsets->data, table_data_len);

    for (i = 0; i < table_offsets->len; ++i) {

        /* rsdt->table_offset_entry to be filled by Guest linker */

        bios_linker_loader_add_pointer(linker,

                                       ACPI_BUILD_TABLE_FILE,

                                       ACPI_BUILD_TABLE_FILE,

                                       table_data, &rsdt->table_offset_entry[i],

                                       sizeof(uint32_t));

    }

    build_header(linker, table_data,

                 (void *)rsdt, "RSDT", rsdt_len, 1, oem_id, oem_table_id);

}


static uint32_t pflash_read (pflash_t *pfl, target_phys_addr_t offset,

                             int width, int be)

{

    target_phys_addr_t boff;

    uint32_t ret;

    uint8_t *p;

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

    ret = -1;

    if (pfl->rom_mode) {

        /* Lazy reset of to ROMD mode */

        if (pfl->wcycle == 0)

            pflash_register_memory(pfl, 1);

    }

    offset &= pfl->chip_len - 1;

    boff = offset & 0xFF;

    if (pfl->width == 2)

        boff = boff >> 1;

    else if (pfl->width == 4)

        boff = boff >> 2;

    switch (pfl->cmd) {

    default:

        /* This should never happen : reset state & treat it as a read*/

        DPRINTF("%s: unknown command state: %x\n", __func__, pfl->cmd);

        pfl->wcycle = 0;

        pfl->cmd = 0;

    case 0x80:

        /* We accept reads during second unlock sequence... */

    case 0x00:

    flash_read:

        /* Flash area read */

        p = pfl->storage;

        switch (width) {

        case 1:

            ret = p[offset];

//            DPRINTF("%s: data offset %08x %02x\n", __func__, offset, ret);

            break;

        case 2:

            if (be) {

                ret = p[offset] << 8;

                ret |= p[offset + 1];

            } else {

                ret = p[offset];

                ret |= p[offset + 1] << 8;

            }

//            DPRINTF("%s: data offset %08x %04x\n", __func__, offset, ret);

            break;

        case 4:

            if (be) {

                ret = p[offset] << 24;

                ret |= p[offset + 1] << 16;

                ret |= p[offset + 2] << 8;

                ret |= p[offset + 3];

            } else {

                ret = p[offset];

                ret |= p[offset + 1] << 8;

                ret |= p[offset + 2] << 16;

                ret |= p[offset + 3] << 24;

            }

//            DPRINTF("%s: data offset %08x %08x\n", __func__, offset, ret);

            break;

        }

        break;

    case 0x90:

        /* flash ID read */

        switch (boff) {

        case 0x00:

        case 0x01:

            ret = pfl->ident[boff & 0x01];

            break;

        case 0x02:

            ret = 0x00; /* Pretend all sectors are unprotected */

            break;

        case 0x0E:

        case 0x0F:

            if (pfl->ident[2 + (boff & 0x01)] == (uint8_t)-1)

                goto flash_read;

            ret = pfl->ident[2 + (boff & 0x01)];

            break;

        default:

            goto flash_read;

        }

        DPRINTF("%s: ID " TARGET_FMT_pld " %x\n", __func__, boff, ret);

        break;

    case 0xA0:

    case 0x10:

    case 0x30:

        /* Status register read */

        ret = pfl->status;

        DPRINTF("%s: status %x\n", __func__, ret);

        /* Toggle bit 6 */

        pfl->status ^= 0x40;

        break;

    case 0x98:

        /* CFI query mode */

        if (boff > pfl->cfi_len)

            ret = 0;

        else

            ret = pfl->cfi_table[boff];

        break;

    }

    return ret;

}


static void disable_logging(void)

{

    ga_disable_logging(ga_state);

}


int r4k_map_address (CPUMIPSState *env, hwaddr *physical, int *prot,

                     target_ulong address, int rw, int access_type)

{

    uint8_t ASID = env->CP0_EntryHi & 0xFF;

    int i;

    for (i = 0; i < env->tlb->tlb_in_use; i++) {

        r4k_tlb_t *tlb = &env->tlb->mmu.r4k.tlb[i];

        /* 1k pages are not supported. */

        target_ulong mask = tlb->PageMask | ~(TARGET_PAGE_MASK << 1);

        target_ulong tag = address & ~mask;

        target_ulong VPN = tlb->VPN & ~mask;

#if defined(TARGET_MIPS64)

        tag &= env->SEGMask;

#endif

        /* Check ASID, virtual page number & size */

        if ((tlb->G == 1 || tlb->ASID == ASID) && VPN == tag) {

            /* TLB match */

            int n = !!(address & mask & ~(mask >> 1));

            /* Check access rights */

            if (!(n ? tlb->V1 : tlb->V0)) {

                return TLBRET_INVALID;

            }

            if (rw == MMU_INST_FETCH && (n ? tlb->XI1 : tlb->XI0)) {

                return TLBRET_XI;

            }

            if (rw == MMU_DATA_LOAD && (n ? tlb->RI1 : tlb->RI0)) {

                return TLBRET_RI;

            }

            if (rw != MMU_DATA_STORE || (n ? tlb->D1 : tlb->D0)) {

                *physical = tlb->PFN[n] | (address & (mask >> 1));

                *prot = PAGE_READ;

                if (n ? tlb->D1 : tlb->D0)

                    *prot |= PAGE_WRITE;

                return TLBRET_MATCH;

            }

            return TLBRET_DIRTY;

        }

    }

    return TLBRET_NOMATCH;

}


GArray *bios_linker_loader_init(void)

{

    return g_array_new(false, true /* clear */, 1);

}


static void exynos4210_fimd_update(void *opaque)

{

    Exynos4210fimdState *s = (Exynos4210fimdState *)opaque;

    Exynos4210fimdWindow *w;

    int i, line;

    target_phys_addr_t fb_line_addr, inc_size;

    int scrn_height;

    int first_line = -1, last_line = -1, scrn_width;

    bool blend = false;

    uint8_t *host_fb_addr;

    bool is_dirty = false;

    const int global_width = (s->vidtcon[2] & FIMD_VIDTCON2_SIZE_MASK) + 1;

    const int global_height = ((s->vidtcon[2] >> FIMD_VIDTCON2_VER_SHIFT) &

            FIMD_VIDTCON2_SIZE_MASK) + 1;

    if (!s || !s->console || !ds_get_bits_per_pixel(s->console) ||

            !s->enabled) {

        return;

    }

    exynos4210_update_resolution(s);

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

        w = &s->window[i];

        if ((w->wincon & FIMD_WINCON_ENWIN) && w->host_fb_addr) {

            scrn_height = w->rightbot_y - w->lefttop_y + 1;

            scrn_width = w->virtpage_width;

            /* Total width of virtual screen page in bytes */

            inc_size = scrn_width + w->virtpage_offsize;

            memory_region_sync_dirty_bitmap(w->mem_section.mr);

            host_fb_addr = w->host_fb_addr;

            fb_line_addr = w->mem_section.offset_within_region;

            for (line = 0; line < scrn_height; line++) {

                is_dirty = memory_region_get_dirty(w->mem_section.mr,

                            fb_line_addr, scrn_width, DIRTY_MEMORY_VGA);

                if (s->invalidate || is_dirty) {

                    if (first_line == -1) {

                        first_line = line;

                    }

                    last_line = line;

                    w->draw_line(w, host_fb_addr, s->ifb +

                        w->lefttop_x * RGBA_SIZE + (w->lefttop_y + line) *

                        global_width * RGBA_SIZE, blend);

                }

                host_fb_addr += inc_size;

                fb_line_addr += inc_size;

                is_dirty = false;

            }

            memory_region_reset_dirty(w->mem_section.mr,

                w->mem_section.offset_within_region,

                w->fb_len, DIRTY_MEMORY_VGA);

            blend = true;

        }

    }

    /* Copy resulting image to QEMU_CONSOLE. */

    if (first_line >= 0) {

        uint8_t *d;

        int bpp;

        bpp = ds_get_bits_per_pixel(s->console);

        fimd_update_putpix_qemu(bpp);

        bpp = (bpp + 1) >> 3;

        d = ds_get_data(s->console);

        for (line = first_line; line <= last_line; line++) {

            fimd_copy_line_toqemu(global_width, s->ifb + global_width * line *

                    RGBA_SIZE, d + global_width * line * bpp);

        }

        dpy_update(s->console, 0, 0, global_width, global_height);

    }

    s->invalidate = false;

    s->vidintcon[1] |= FIMD_VIDINT_INTFRMPEND;

    if ((s->vidcon[0] & FIMD_VIDCON0_ENVID_F) == 0) {

        exynos4210_fimd_enable(s, false);

    }

    exynos4210_fimd_update_irq(s);

}


static int find_large_solid_color_rect(VncState *vs, int x, int y,

                                       int w, int h, int max_rows)

{

    int dx, dy, dw, dh;

    int n = 0;

    /* Try to find large solid-color areas and send them separately. */

    for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {

        /* If a rectangle becomes too large, send its upper part now. */

        if (dy - y >= max_rows) {

            n += send_rect_simple(vs, x, y, w, max_rows);

            y += max_rows;

            h -= max_rows;

        }

        dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (y + h - dy));

        for (dx = x; dx < x + w; dx += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {

            uint32_t color_value;

            int x_best, y_best, w_best, h_best;

            dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, (x + w - dx));

            if (!check_solid_tile(vs, dx, dy, dw, dh, &color_value, false)) {

                continue ;

            }

            /* Get dimensions of solid-color area. */

            find_best_solid_area(vs, dx, dy, w - (dx - x), h - (dy - y),

                                 color_value, &w_best, &h_best);

            /* Make sure a solid rectangle is large enough

               (or the whole rectangle is of the same color). */

            if (w_best * h_best != w * h &&

                w_best * h_best < VNC_TIGHT_MIN_SOLID_SUBRECT_SIZE) {

                continue;

            }

            /* Try to extend solid rectangle to maximum size. */

            x_best = dx; y_best = dy;

            extend_solid_area(vs, x, y, w, h, color_value,

                              &x_best, &y_best, &w_best, &h_best);

            /* Send rectangles at top and left to solid-color area. */

            if (y_best != y) {

                n += send_rect_simple(vs, x, y, w, y_best-y);

            }

            if (x_best != x) {

                n += vnc_tight_send_framebuffer_update(vs, x, y_best,

                                                       x_best-x, h_best);

            }

            /* Send solid-color rectangle. */

            n += send_sub_rect_solid(vs, x_best, y_best, w_best, h_best);

            /* Send remaining rectangles (at right and bottom). */

            if (x_best + w_best != x + w) {

                n += vnc_tight_send_framebuffer_update(vs, x_best+w_best,

                                                       y_best,

                                                       w-(x_best-x)-w_best,

                                                       h_best);

            }

            if (y_best + h_best != y + h) {

                n += vnc_tight_send_framebuffer_update(vs, x, y_best+h_best,

                                                       w, h-(y_best-y)-h_best);

            }

            /* Return after all recursive calls are done. */

            return n;

        }

    }

    return n + send_rect_simple(vs, x, y, w, h);

}


static void iscsi_allocationmap_clear(IscsiLun *iscsilun, int64_t sector_num,

                                      int nb_sectors)

{

    int64_t cluster_num, nb_clusters;

    if (iscsilun->allocationmap == NULL) {

        return;

    }

    cluster_num = DIV_ROUND_UP(sector_num, iscsilun->cluster_sectors);

    nb_clusters = (sector_num + nb_sectors) / iscsilun->cluster_sectors

                  - cluster_num;

    if (nb_clusters > 0) {

        bitmap_clear(iscsilun->allocationmap, cluster_num, nb_clusters);

    }

}


static void h264_h_loop_filter_luma_c(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0)

{

    h264_loop_filter_luma_c(pix, 1, stride, alpha, beta, tc0);

}


static int avi_read_header(AVFormatContext *s)

{

    AVIContext *avi = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned int tag, tag1, handler;

    int codec_type, stream_index, frame_period;

    unsigned int size;

    int i;

    AVStream *st;

    AVIStream *ast      = NULL;

    int avih_width      = 0, avih_height = 0;

    int amv_file_format = 0;

    uint64_t list_end   = 0;

    int ret;

    avi->stream_index = -1;

    ret = get_riff(s, pb);

    if (ret < 0)

        return ret;

    avi->fsize = avio_size(pb);

    if (avi->fsize <= 0)

        avi->fsize = avi->riff_end == 8 ? INT64_MAX : avi->riff_end;

    /* first list tag */

    stream_index = -1;

    codec_type   = -1;

    frame_period = 0;

    for (;;) {

        if (pb->eof_reached)

            goto fail;

        tag  = avio_rl32(pb);

        size = avio_rl32(pb);

        print_tag("tag", tag, size);

        switch (tag) {

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

            list_end = avio_tell(pb) + size;

            /* Ignored, except at start of video packets. */

            tag1 = avio_rl32(pb);

            print_tag("list", tag1, 0);

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

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

                if (size)

                    avi->movi_end = avi->movi_list + size + (size & 1);

                else

                    avi->movi_end = avio_size(pb);

                av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);

                goto end_of_header;

            } else if (tag1 == MKTAG('I', 'N', 'F', 'O'))

                ff_read_riff_info(s, size - 4);

            else if (tag1 == MKTAG('n', 'c', 'd', 't'))

                avi_read_nikon(s, list_end);

            break;

        case MKTAG('I', 'D', 'I', 'T'):

        {

            unsigned char date[64] = { 0 };

            size += (size & 1);

            size -= avio_read(pb, date, FFMIN(size, sizeof(date) - 1));

            avio_skip(pb, size);

            avi_metadata_creation_time(&s->metadata, date);

            break;

        }

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

            avi->is_odml = 1;

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

            break;

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

            amv_file_format = 1;

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

            /* AVI header */

            /* using frame_period is bad idea */

            frame_period = avio_rl32(pb);

            avio_skip(pb, 4);

            avio_rl32(pb);

            avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;

            avio_skip(pb, 2 * 4);

            avio_rl32(pb);

            avio_rl32(pb);

            avih_width  = avio_rl32(pb);

            avih_height = avio_rl32(pb);

            avio_skip(pb, size - 10 * 4);

            break;

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

            /* stream header */

            tag1    = avio_rl32(pb);

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

            if (tag1 == MKTAG('p', 'a', 'd', 's')) {

                avio_skip(pb, size - 8);

                break;

            } else {

                stream_index++;

                st = avformat_new_stream(s, NULL);

                if (!st)

                    goto fail;

                st->id = stream_index;

                ast    = av_mallocz(sizeof(AVIStream));

                if (!ast)

                    goto fail;

                st->priv_data = ast;

            }

            if (amv_file_format)

                tag1 = stream_index ? MKTAG('a', 'u', 'd', 's')

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

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

            if (tag1 == MKTAG('i', 'a', 'v', 's') ||

                tag1 == MKTAG('i', 'v', 'a', 's')) {

                int64_t dv_dur;

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

                 * have to support anything but DV in 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]->codec);

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

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

                s->nb_streams = 0;

                if (CONFIG_DV_DEMUXER) {

                    avi->dv_demux = avpriv_dv_init_demux(s);

                    if (!avi->dv_demux)

                        goto fail;

                } else

                    goto fail;

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

                avio_skip(pb, 3 * 4);

                ast->scale = avio_rl32(pb);

                ast->rate  = avio_rl32(pb);

                avio_skip(pb, 4);  /* start time */

                dv_dur = avio_rl32(pb);

                if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {

                    dv_dur     *= AV_TIME_BASE;

                    s->duration = av_rescale(dv_dur, ast->scale, ast->rate);

                }

                /* else, leave duration alone; timing estimation in utils.c

                 * will make a guess based on bitrate. */

                stream_index = s->nb_streams - 1;

                avio_skip(pb, size - 9 * 4);

                break;

            }

            assert(stream_index < s->nb_streams);

            st->codec->stream_codec_tag = handler;

            avio_rl32(pb); /* flags */

            avio_rl16(pb); /* priority */

            avio_rl16(pb); /* language */

            avio_rl32(pb); /* initial frame */

            ast->scale = avio_rl32(pb);

            ast->rate  = avio_rl32(pb);

            if (!(ast->scale && ast->rate)) {

                av_log(s, AV_LOG_WARNING,

                       "scale/rate is %"PRIu32"/%"PRIu32" which is invalid. "

                       "(This file has been generated by broken software.)\n",

                       ast->scale,

                       ast->rate);

                if (frame_period) {

                    ast->rate  = 1000000;

                    ast->scale = frame_period;

                } else {

                    ast->rate  = 25;

                    ast->scale = 1;

                }

            }

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

            ast->cum_len  = avio_rl32(pb); /* start */

            st->nb_frames = avio_rl32(pb);

            st->start_time = 0;

            avio_rl32(pb); /* buffer size */

            avio_rl32(pb); /* quality */

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

            ast->cum_len    *= FFMAX(1, ast->sample_size);

            av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",

                    ast->rate, ast->scale, ast->sample_size);

            switch (tag1) {

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

                codec_type = AVMEDIA_TYPE_VIDEO;

                ast->sample_size = 0;

                break;

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

                codec_type = AVMEDIA_TYPE_AUDIO;

                break;

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

                codec_type = AVMEDIA_TYPE_SUBTITLE;

                break;

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

                codec_type = AVMEDIA_TYPE_DATA;

                break;

            default:

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

                goto fail;

            }

            if (ast->sample_size == 0)

                st->duration = st->nb_frames;

            ast->frame_offset = ast->cum_len;

            avio_skip(pb, size - 12 * 4);

            break;

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

            /* stream header */

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

                avio_skip(pb, size);

            } else {

                uint64_t cur_pos = avio_tell(pb);

                if (cur_pos < list_end)

                    size = FFMIN(size, list_end - cur_pos);

                st = s->streams[stream_index];

                switch (codec_type) {

                case AVMEDIA_TYPE_VIDEO:

                    if (amv_file_format) {

                        st->codec->width      = avih_width;

                        st->codec->height     = avih_height;

                        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                        st->codec->codec_id   = AV_CODEC_ID_AMV;

                        avio_skip(pb, size);

                        break;

                    }

                    tag1 = ff_get_bmp_header(pb, st);

                    if (tag1 == MKTAG('D', 'X', 'S', 'B') ||

                        tag1 == MKTAG('D', 'X', 'S', 'A')) {

                        st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

                        st->codec->codec_tag  = tag1;

                        st->codec->codec_id   = AV_CODEC_ID_XSUB;

                        break;

                    }

                    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);

                        if (!st->codec->extradata) {

                            st->codec->extradata_size = 0;

                            return AVERROR(ENOMEM);

                        }

                        avio_read(pb,

                                  st->codec->extradata,

                                  st->codec->extradata_size);

                    }

                    // FIXME: check if the encoder really did this correctly

                    if (st->codec->extradata_size & 1)

                        avio_r8(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

                     * Libav. */

                    if (st->codec->extradata_size &&

                        (st->codec->bits_per_coded_sample <= 8)) {

                        int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;

                        const uint8_t *pal_src;

                        pal_size = FFMIN(pal_size, st->codec->extradata_size);

                        pal_src  = st->codec->extradata +

                                   st->codec->extradata_size - pal_size;

#if HAVE_BIGENDIAN

                        for (i = 0; i < pal_size / 4; i++)

                            ast->pal[i] = av_bswap32(((uint32_t *)pal_src)[i]);

#else

                        memcpy(ast->pal, pal_src, pal_size);

#endif

                        ast->has_pal = 1;

                    }

                    print_tag("video", tag1, 0);

                    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                    st->codec->codec_tag  = tag1;

                    st->codec->codec_id   = ff_codec_get_id(ff_codec_bmp_tags,

                                                            tag1);

                    /* This is needed to get the pict type which is necessary

                     * for generating correct pts. */

                    st->need_parsing = AVSTREAM_PARSE_HEADERS;

                    // Support "Resolution 1:1" for Avid AVI Codec

                    if (tag1 == MKTAG('A', 'V', 'R', 'n') &&

                        st->codec->extradata_size >= 31   &&

                        !memcmp(&st->codec->extradata[28], "1:1", 3))

                        st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;

                    if (st->codec->codec_tag == 0 && st->codec->height > 0 &&

                        st->codec->extradata_size < 1U << 30) {

                        st->codec->extradata_size += 9;

                        if ((ret = av_reallocp(&st->codec->extradata,

                                               st->codec->extradata_size +

                                               FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {

                            st->codec->extradata_size = 0;

                            return ret;

                        } else

                            memcpy(st->codec->extradata + st->codec->extradata_size - 9,

                                   "BottomUp", 9);

                    }

                    st->codec->height = FFABS(st->codec->height);

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

                    break;

                case AVMEDIA_TYPE_AUDIO:

                    ret = ff_get_wav_header(pb, st->codec, size);

                    if (ret < 0)

                        return ret;

                    ast->dshow_block_align = st->codec->block_align;

                    if (ast->sample_size && st->codec->block_align &&

                        ast->sample_size != st->codec->block_align) {

                        av_log(s,

                               AV_LOG_WARNING,

                               "sample size (%d) != block align (%d)\n",

                               ast->sample_size,

                               st->codec->block_align);

                        ast->sample_size = st->codec->block_align;

                    }

                    /* 2-aligned

                     * (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */

                    if (size & 1)

                        avio_skip(pb, 1);

                    /* Force parsing as several audio frames can be in

                     * one packet and timestamps refer to packet start. */

                    st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;

                    /* ADTS header is in extradata, AAC without header must be

                     * stored as exact frames. Parser not needed and it will

                     * fail. */

                    if (st->codec->codec_id == AV_CODEC_ID_AAC &&

                        st->codec->extradata_size)

                        st->need_parsing = AVSTREAM_PARSE_NONE;

                    /* AVI files with Xan DPCM audio (wrongly) declare PCM

                     * audio in the header but have Axan as stream_code_tag. */

                    if (st->codec->stream_codec_tag == AV_RL32("Axan")) {

                        st->codec->codec_id  = AV_CODEC_ID_XAN_DPCM;

                        st->codec->codec_tag = 0;

                    }

                    if (amv_file_format) {

                        st->codec->codec_id    = AV_CODEC_ID_ADPCM_IMA_AMV;

                        ast->dshow_block_align = 0;

                    }

                    break;

                case AVMEDIA_TYPE_SUBTITLE:

                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

                    st->codec->codec_id   = AV_CODEC_ID_PROBE;

                    break;

                default:

                    st->codec->codec_type = AVMEDIA_TYPE_DATA;

                    st->codec->codec_id   = AV_CODEC_ID_NONE;

                    st->codec->codec_tag  = 0;

                    avio_skip(pb, size);

                    break;

                }

            }

            break;

        case MKTAG('i', 'n', 'd', 'x'):

            i = avio_tell(pb);

            if (pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) &&

                read_braindead_odml_indx(s, 0) < 0 &&

                (s->error_recognition & AV_EF_EXPLODE))

                goto fail;

            avio_seek(pb, i + size, SEEK_SET);

            break;

        case MKTAG('v', 'p', 'r', 'p'):

            if (stream_index < (unsigned)s->nb_streams && size > 9 * 4) {

                AVRational active, active_aspect;

                st = s->streams[stream_index];

                avio_rl32(pb);

                avio_rl32(pb);

                avio_rl32(pb);

                avio_rl32(pb);

                avio_rl32(pb);

                active_aspect.den = avio_rl16(pb);

                active_aspect.num = avio_rl16(pb);

                active.num        = avio_rl32(pb);

                active.den        = avio_rl32(pb);

                avio_rl32(pb); // nbFieldsPerFrame

                if (active_aspect.num && active_aspect.den &&

                    active.num && active.den) {

                    st->sample_aspect_ratio = av_div_q(active_aspect, active);

                    av_dlog(s, "vprp %d/%d %d/%d\n",

                            active_aspect.num, active_aspect.den,

                            active.num, active.den);

                }

                size -= 9 * 4;

            }

            avio_skip(pb, size);

            break;

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

            if (s->nb_streams) {

                ret = avi_read_tag(s, s->streams[s->nb_streams - 1], tag, size);

                if (ret < 0)

                    return ret;

                break;

            }

        default:

            if (size > 1000000) {

                av_log(s, AV_LOG_ERROR,

                       "Something went wrong during header parsing, "

                       "I will ignore it and try to continue anyway.\n");

                if (s->error_recognition & AV_EF_EXPLODE)

                    goto fail;

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

                avi->movi_end  = avio_size(pb);

                goto end_of_header;

            }

            /* skip tag */

            size += (size & 1);

            avio_skip(pb, size);

            break;

        }

    }

end_of_header:

    /* check stream number */

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

fail:

        return AVERROR_INVALIDDATA;

    }

    if (!avi->index_loaded && pb->seekable)

        avi_load_index(s);

    avi->index_loaded     = 1;

    avi->non_interleaved |= guess_ni_flag(s);

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

        AVStream *st = s->streams[i];

        if (st->nb_index_entries)

            break;

    }

    if (i == s->nb_streams && avi->non_interleaved) {

        av_log(s, AV_LOG_WARNING,

               "Non-interleaved AVI without index, switching to interleaved\n");

        avi->non_interleaved = 0;

    }

    if (avi->non_interleaved) {

        av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");

        clean_index(s);

    }

    ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);

    ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);

    return 0;

}


static void phys_page_set(AddressSpaceDispatch *d,

                          hwaddr index, hwaddr nb,

                          uint16_t leaf)

{

    /* Wildly overreserve - it doesn't matter much. */

    phys_map_node_reserve(3 * P_L2_LEVELS);

    phys_page_set_level(&d->phys_map, &index, &nb, leaf, P_L2_LEVELS - 1);

}


static av_cold int g726_decode_init(AVCodecContext *avctx)

{

    G726Context* c = avctx->priv_data;

    if (avctx->sample_rate <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Samplerate is invalid\n");

        return -1;

    }

    if(avctx->channels != 1){

        av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");

        return -1;

    }

    c->code_size = avctx->bits_per_coded_sample;

    if (c->code_size < 2 || c->code_size > 5) {

        av_log(avctx, AV_LOG_ERROR, "Invalid number of bits %d\n", c->code_size);

        return AVERROR(EINVAL);

    }

    g726_reset(c, c->code_size - 2);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    return 0;

}


static uint32_t isa_mmio_readw(void *opaque, target_phys_addr_t addr)

{

    return cpu_inw(addr & IOPORTS_MASK);

}


static void unassign_storage(SCLPDevice *sclp, SCCB *sccb)

{

    MemoryRegion *mr = NULL;

    AssignStorage *assign_info = (AssignStorage *) sccb;

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    assert(mhd);

    ram_addr_t unassign_addr = (assign_info->rn - 1) * mhd->rzm;

    MemoryRegion *sysmem = get_system_memory();

    /* if the addr is a multiple of 256 MB */

    if ((unassign_addr % MEM_SECTION_SIZE == 0) &&

        (unassign_addr >= mhd->padded_ram_size)) {

        mhd->standby_state_map[(unassign_addr -

                           mhd->padded_ram_size) / MEM_SECTION_SIZE] = 0;

        /* find the specified memory region and destroy it */

        mr = memory_region_find(sysmem, unassign_addr, 1).mr;

        memory_region_unref(mr);

        if (mr) {

            int i;

            int is_removable = 1;

            ram_addr_t map_offset = (unassign_addr - mhd->padded_ram_size -

                                     (unassign_addr - mhd->padded_ram_size)

                                     % mhd->standby_subregion_size);

            /* Mark all affected subregions as 'standby' once again */

            for (i = 0;

                 i < (mhd->standby_subregion_size / MEM_SECTION_SIZE);

                 i++) {

                if (mhd->standby_state_map[i + map_offset / MEM_SECTION_SIZE]) {

                    is_removable = 0;

                    break;

                }

            }

            if (is_removable) {

                memory_region_del_subregion(sysmem, mr);

                object_unref(OBJECT(mr));

            }

        }

    }

    sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION);

}


static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)

{

    return bdrv_get_info(bs->file->bs, bdi);

}


static int nbd_co_writev_1(NbdClientSession *client, int64_t sector_num,

                           int nb_sectors, QEMUIOVector *qiov,

                           int offset)

{

    struct nbd_request request = { .type = NBD_CMD_WRITE };

    struct nbd_reply reply;

    ssize_t ret;

    if (!bdrv_enable_write_cache(client->bs) &&

        (client->nbdflags & NBD_FLAG_SEND_FUA)) {

        request.type |= NBD_CMD_FLAG_FUA;

    }

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, qiov, offset);

    if (ret < 0) {

        reply.error = -ret;

    } else {

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

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


START_TEST(simple_whitespace)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = " [ 43 , 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' , 'a' : 32 }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { "a", QLIT_QINT(32) },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QLIST);

        fail_unless(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str));

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QLIST);

        fail_unless(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


gboolean qcrypto_hash_supports(QCryptoHashAlgorithm alg)

{

    if (alg < G_N_ELEMENTS(qcrypto_hash_alg_map)) {

        return true;

    }

    return false;

}


static int nvic_pending_prio(NVICState *s)

{

    /* return the priority of the current pending interrupt,

     * or NVIC_NOEXC_PRIO if no interrupt is pending

     */

    return s->vectpending ? s->vectors[s->vectpending].prio : NVIC_NOEXC_PRIO;

}


static uint64_t pci_config_get_pref_base(PCIDevice *d,

                                         uint32_t base, uint32_t upper)

{

    uint64_t val;

    val = ((uint64_t)pci_get_word(d->config + base) &

           PCI_PREF_RANGE_MASK) << 16;

    val |= (uint64_t)pci_get_long(d->config + upper) << 32;

    return val;

}


static void qmp_output_type_enum(Visitor *v, int *obj, const char *strings[],

                                 const char *kind, const char *name,

                                 Error **errp)

{

    int i = 0;

    int value = *obj;

    char *enum_str;

    assert(strings);

    while (strings[i++] != NULL);

    if (value >= i - 1) {

        error_set(errp, QERR_INVALID_PARAMETER, name ? name : "null");

        return;

    }

    enum_str = (char *)strings[value];

    qmp_output_type_str(v, &enum_str, name, errp);

}


static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    char color_parameter_type[5] = { 0 };

    int color_primaries, color_trc, color_matrix;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams - 1];

    avio_read(pb, color_parameter_type, 4);

    if (strncmp(color_parameter_type, "nclx", 4) &&

        strncmp(color_parameter_type, "nclc", 4)) {

        av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n",

               color_parameter_type);

        return 0;

    }

    color_primaries = avio_rb16(pb);

    color_trc = avio_rb16(pb);

    color_matrix = avio_rb16(pb);

    av_dlog(c->fc, "%s: pri %d trc %d matrix %d",

            color_parameter_type, color_primaries, color_trc, color_matrix);

    if (c->isom) {

        uint8_t color_range = avio_r8(pb) >> 7;

        av_dlog(c->fc, " full %"PRIu8"", color_range);

        if (color_range)

            st->codec->color_range = AVCOL_RANGE_JPEG;

        else

            st->codec->color_range = AVCOL_RANGE_MPEG;

        /* 14496-12 references JPEG XR specs (rather than the more complete

         * 23001-8) so some adjusting is required */

        if (color_primaries >= AVCOL_PRI_FILM)

            color_primaries = AVCOL_PRI_UNSPECIFIED;

        if ((color_trc >= AVCOL_TRC_LINEAR &&

             color_trc <= AVCOL_TRC_LOG_SQRT) ||

            color_trc >= AVCOL_TRC_BT2020_10)

            color_trc = AVCOL_TRC_UNSPECIFIED;

        if (color_matrix >= AVCOL_SPC_BT2020_NCL)

            color_matrix = AVCOL_SPC_UNSPECIFIED;

        st->codec->color_primaries = color_primaries;

        st->codec->color_trc = color_trc;

        st->codec->colorspace = color_matrix;

    } else {

        /* color primaries, Table 4-4 */

        switch (color_primaries) {

        case 1: st->codec->color_primaries = AVCOL_PRI_BT709; break;

        case 5: st->codec->color_primaries = AVCOL_PRI_SMPTE170M; break;

        case 6: st->codec->color_primaries = AVCOL_PRI_SMPTE240M; break;

        }

        /* color transfer, Table 4-5 */

        switch (color_trc) {

        case 1: st->codec->color_trc = AVCOL_TRC_BT709; break;

        case 7: st->codec->color_trc = AVCOL_TRC_SMPTE240M; break;

        }

        /* color matrix, Table 4-6 */

        switch (color_matrix) {

        case 1: st->codec->colorspace = AVCOL_SPC_BT709; break;

        case 6: st->codec->colorspace = AVCOL_SPC_BT470BG; break;

        case 7: st->codec->colorspace = AVCOL_SPC_SMPTE240M; break;

        }

    }

    av_dlog(c->fc, "\n");

    return 0;

}


static int v9fs_complete_rename(V9fsState *s, V9fsRenameState *vs)

{

    int err = 0;

    char *old_name, *new_name;

    char *end;

    if (vs->newdirfid != -1) {

        V9fsFidState *dirfidp;

        dirfidp = lookup_fid(s, vs->newdirfid);

        if (dirfidp == NULL) {

            err = -ENOENT;

            goto out;

        }

        BUG_ON(dirfidp->fid_type != P9_FID_NONE);

        new_name = qemu_mallocz(dirfidp->path.size + vs->name.size + 2);

        strcpy(new_name, dirfidp->path.data);

        strcat(new_name, "/");

        strcat(new_name + dirfidp->path.size, vs->name.data);

    } else {

        old_name = vs->fidp->path.data;

        end = strrchr(old_name, '/');

        if (end) {

            end++;

        } else {

            end = old_name;

        }

        new_name = qemu_mallocz(end - old_name + vs->name.size + 1);

        strncat(new_name, old_name, end - old_name);

        strncat(new_name + (end - old_name), vs->name.data, vs->name.size);

    }

    v9fs_string_free(&vs->name);

    vs->name.data = qemu_strdup(new_name);

    vs->name.size = strlen(new_name);

    if (strcmp(new_name, vs->fidp->path.data) != 0) {

        if (v9fs_do_rename(s, &vs->fidp->path, &vs->name)) {

            err = -errno;

        } else {

            V9fsFidState *fidp;

            /*

            * Fixup fid's pointing to the old name to

            * start pointing to the new name

            */

            for (fidp = s->fid_list; fidp; fidp = fidp->next) {

                if (vs->fidp == fidp) {

                    /*

                    * we replace name of this fid towards the end

                    * so that our below strcmp will work

                    */

                    continue;

                }

                if (!strncmp(vs->fidp->path.data, fidp->path.data,

                    strlen(vs->fidp->path.data))) {

                    /* replace the name */

                    v9fs_fix_path(&fidp->path, &vs->name,

                                  strlen(vs->fidp->path.data));

                }

            }

            v9fs_string_copy(&vs->fidp->path, &vs->name);

        }

    }

out:

    v9fs_string_free(&vs->name);

    return err;

}


build_srat(GArray *table_data, GArray *linker, VirtGuestInfo *guest_info)

{

    AcpiSystemResourceAffinityTable *srat;

    AcpiSratProcessorGiccAffinity *core;

    AcpiSratMemoryAffinity *numamem;

    int i, j, srat_start;

    uint64_t mem_base;

    uint32_t *cpu_node = g_malloc0(guest_info->smp_cpus * sizeof(uint32_t));

    for (i = 0; i < guest_info->smp_cpus; i++) {

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

            if (test_bit(i, numa_info[j].node_cpu)) {

                cpu_node[i] = j;

                break;

            }

        }

    }

    srat_start = table_data->len;

    srat = acpi_data_push(table_data, sizeof(*srat));

    srat->reserved1 = cpu_to_le32(1);

    for (i = 0; i < guest_info->smp_cpus; ++i) {

        core = acpi_data_push(table_data, sizeof(*core));

        core->type = ACPI_SRAT_PROCESSOR_GICC;

        core->length = sizeof(*core);

        core->proximity = cpu_to_le32(cpu_node[i]);

        core->acpi_processor_uid = cpu_to_le32(i);

        core->flags = cpu_to_le32(1);

    }

    g_free(cpu_node);

    mem_base = guest_info->memmap[VIRT_MEM].base;

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

        numamem = acpi_data_push(table_data, sizeof(*numamem));

        build_srat_memory(numamem, mem_base, numa_info[i].node_mem, i,

                          MEM_AFFINITY_ENABLED);

        mem_base += numa_info[i].node_mem;

    }

    build_header(linker, table_data,

                 (void *)(table_data->data + srat_start), "SRAT",

                 table_data->len - srat_start, 3, NULL, NULL);

}


static void tcg_out_ri64(TCGContext *s, int const_arg, TCGArg arg)

{

    if (const_arg) {

        assert(const_arg == 1);

        tcg_out8(s, TCG_CONST);

        tcg_out64(s, arg);

    } else {

        tcg_out_r(s, arg);

    }

}


static void tgen_compare_branch(TCGContext *s, S390Opcode opc, int cc,

                                TCGReg r1, TCGReg r2, int labelno)

{

    TCGLabel* l = &s->labels[labelno];

    intptr_t off;

    if (l->has_value) {

        off = l->u.value_ptr - s->code_ptr;

    } else {

        /* We need to keep the offset unchanged for retranslation.  */

        off = s->code_ptr[1];

        tcg_out_reloc(s, s->code_ptr + 1, R_390_PC16DBL, labelno, -2);

    }

    tcg_out16(s, (opc & 0xff00) | (r1 << 4) | r2);

    tcg_out16(s, off);

    tcg_out16(s, cc << 12 | (opc & 0xff));

}


void spapr_iommu_init(void)

{

    QLIST_INIT(&spapr_tce_tables);

    /* hcall-tce */

    spapr_register_hypercall(H_PUT_TCE, h_put_tce);

}


static void migration_state_notifier(Notifier *notifier, void *data)

{

    MigrationState *s = data;

    if (migration_is_active(s)) {

#ifdef SPICE_INTERFACE_MIGRATION

        spice_server_migrate_start(spice_server);

#endif

    } else if (migration_has_finished(s)) {

#if SPICE_SERVER_VERSION >= 0x000701 /* 0.7.1 */

#ifndef SPICE_INTERFACE_MIGRATION

        spice_server_migrate_switch(spice_server);

#else

        spice_server_migrate_end(spice_server, true);

    } else if (migration_has_failed(s)) {

        spice_server_migrate_end(spice_server, false);

#endif

#endif

    }

}


static inline void downmix_3f_1r_to_stereo(float *samples)

{

    int i;

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

        samples[i] += (samples[i + 256] + samples[i + 768]);

        samples[i + 256] += (samples[i + 512] + samples[i + 768]);

        samples[i + 512] = samples[i + 768] = 0;

    }

}


static int lmlm4_read_packet(AVFormatContext *s, AVPacket *pkt) {

    AVIOContext *pb = s->pb;

    int ret;

    unsigned int frame_type, packet_size, padding, frame_size;

    avio_rb16(pb);                       /* channel number */

    frame_type  = avio_rb16(pb);

    packet_size = avio_rb32(pb);

    padding     = -packet_size & 511;

    frame_size  = packet_size - 8;

    if (frame_type > LMLM4_MPEG1L2 || frame_type == LMLM4_INVALID) {

        av_log(s, AV_LOG_ERROR, "invalid or unsupported frame_type\n");

        return AVERROR(EIO);

    }

    if (packet_size > LMLM4_MAX_PACKET_SIZE) {

        av_log(s, AV_LOG_ERROR, "packet size exceeds maximum\n");

        return AVERROR(EIO);

    }

    if ((ret = av_get_packet(pb, pkt, frame_size)) <= 0)

        return AVERROR(EIO);

    avio_skip(pb, padding);

    switch (frame_type) {

        case LMLM4_I_FRAME:

            pkt->flags = AV_PKT_FLAG_KEY;

        case LMLM4_P_FRAME:

        case LMLM4_B_FRAME:

            pkt->stream_index = 0;

            break;

        case LMLM4_MPEG1L2:

            pkt->stream_index = 1;

            break;

    }

    return ret;

}


static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)

{

    BinkContext * const c = avctx->priv_data;

    GetBitContext gb;

    int plane, plane_idx, ret;

    int bits_count = pkt->size << 3;

    if (c->version > 'b') {

        if(c->pic->data[0])

            avctx->release_buffer(avctx, c->pic);

        if ((ret = ff_get_buffer(avctx, c->pic)) < 0) {

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

            return ret;

        }

    } else {

        if ((ret = avctx->reget_buffer(avctx, c->pic)) < 0) {

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

            return ret;

        }

    }

    init_get_bits(&gb, pkt->data, bits_count);

    if (c->has_alpha) {

        if (c->version >= 'i')

            skip_bits_long(&gb, 32);

        if ((ret = bink_decode_plane(c, &gb, 3, 0)) < 0)

            return ret;

    }

    if (c->version >= 'i')

        skip_bits_long(&gb, 32);

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

        plane_idx = (!plane || !c->swap_planes) ? plane : (plane ^ 3);

        if (c->version > 'b') {

            if ((ret = bink_decode_plane(c, &gb, plane_idx, !!plane)) < 0)

                return ret;

        } else {

            if ((ret = binkb_decode_plane(c, &gb, plane_idx, !pkt->pts, !!plane)) < 0)

                return ret;

        }

        if (get_bits_count(&gb) >= bits_count)

            break;

    }

    emms_c();

    *got_frame = 1;

    *(AVFrame*)data = *c->pic;

    if (c->version > 'b')

        FFSWAP(AVFrame*, c->pic, c->last);

    /* always report that the buffer was completely consumed */

    return pkt->size;

}


static int packed_16bpc_bswap(SwsContext *c, const uint8_t *src[],

                              int srcStride[], int srcSliceY, int srcSliceH,

                              uint8_t *dst[], int dstStride[])

{

    int i, j, p;

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

        int srcstr = srcStride[p] >> 1;

        int dststr = dstStride[p] >> 1;

        uint16_t       *dstPtr =       (uint16_t *) dst[p];

        const uint16_t *srcPtr = (const uint16_t *) src[p];

        int min_stride         = FFMIN(srcstr, dststr);

        if(!dstPtr || !srcPtr)

            continue;

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

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

                dstPtr[j] = av_bswap16(srcPtr[j]);

            }

            srcPtr += srcstr;

            dstPtr += dststr;

        }

    }

    return srcSliceH;

}


static void video_refresh(void *opaque)

{

    VideoState *is = opaque;

    VideoPicture *vp;

    double time;

    SubPicture *sp, *sp2;

    if (!is->paused && get_master_sync_type(is) == AV_SYNC_EXTERNAL_CLOCK && is->realtime)

        check_external_clock_speed(is);

    if (!display_disable && is->show_mode != SHOW_MODE_VIDEO && is->audio_st)

        video_display(is);

    if (is->video_st) {

        if (is->force_refresh)

            pictq_prev_picture(is);

retry:

        if (is->pictq_size == 0) {

            SDL_LockMutex(is->pictq_mutex);

            if (is->frame_last_dropped_pts != AV_NOPTS_VALUE && is->frame_last_dropped_pts > is->frame_last_pts) {

                update_video_pts(is, is->frame_last_dropped_pts, is->frame_last_dropped_pos, 0);

                is->frame_last_dropped_pts = AV_NOPTS_VALUE;

            }

            SDL_UnlockMutex(is->pictq_mutex);

            // nothing to do, no picture to display in the queue

        } else {

            double last_duration, duration, delay;

            /* dequeue the picture */

            vp = &is->pictq[is->pictq_rindex];

            if (vp->serial != is->videoq.serial) {

                pictq_next_picture(is);

                goto retry;

            }

            if (is->paused)

                goto display;

            /* compute nominal last_duration */

            last_duration = vp->pts - is->frame_last_pts;

            if (last_duration > 0 && last_duration < is->max_frame_duration) {

                /* if duration of the last frame was sane, update last_duration in video state */

                is->frame_last_duration = last_duration;

            }

            delay = compute_target_delay(is->frame_last_duration, is);

            time= av_gettime()/1000000.0;

            if (time < is->frame_timer + delay)

                return;

            if (delay > 0)

                is->frame_timer += delay * FFMAX(1, floor((time-is->frame_timer) / delay));

            SDL_LockMutex(is->pictq_mutex);

            update_video_pts(is, vp->pts, vp->pos, vp->serial);

            SDL_UnlockMutex(is->pictq_mutex);

            if (is->pictq_size > 1) {

                VideoPicture *nextvp = &is->pictq[(is->pictq_rindex + 1) % VIDEO_PICTURE_QUEUE_SIZE];

                duration = nextvp->pts - vp->pts;

                if(!is->step && (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) && time > is->frame_timer + duration){

                    is->frame_drops_late++;

                    pictq_next_picture(is);

                    goto retry;

                }

            }

            if (is->subtitle_st) {

                if (is->subtitle_stream_changed) {

                    SDL_LockMutex(is->subpq_mutex);

                    while (is->subpq_size) {

                        free_subpicture(&is->subpq[is->subpq_rindex]);

                        /* update queue size and signal for next picture */

                        if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)

                            is->subpq_rindex = 0;

                        is->subpq_size--;

                    }

                    is->subtitle_stream_changed = 0;

                    SDL_CondSignal(is->subpq_cond);

                    SDL_UnlockMutex(is->subpq_mutex);

                } else {

                    if (is->subpq_size > 0) {

                        sp = &is->subpq[is->subpq_rindex];

                        if (is->subpq_size > 1)

                            sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];

                        else

                            sp2 = NULL;

                        if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))

                                || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))

                        {

                            free_subpicture(sp);

                            /* update queue size and signal for next picture */

                            if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)

                                is->subpq_rindex = 0;

                            SDL_LockMutex(is->subpq_mutex);

                            is->subpq_size--;

                            SDL_CondSignal(is->subpq_cond);

                            SDL_UnlockMutex(is->subpq_mutex);

                        }

                    }

                }

            }

display:

            /* display picture */

            if (!display_disable && is->show_mode == SHOW_MODE_VIDEO)

                video_display(is);

            pictq_next_picture(is);

            if (is->step && !is->paused)

                stream_toggle_pause(is);

        }

    }

    is->force_refresh = 0;

    if (show_status) {

        static int64_t last_time;

        int64_t cur_time;

        int aqsize, vqsize, sqsize;

        double av_diff;

        cur_time = av_gettime();

        if (!last_time || (cur_time - last_time) >= 30000) {

            aqsize = 0;

            vqsize = 0;

            sqsize = 0;

            if (is->audio_st)

                aqsize = is->audioq.size;

            if (is->video_st)

                vqsize = is->videoq.size;

            if (is->subtitle_st)

                sqsize = is->subtitleq.size;

            av_diff = 0;

            if (is->audio_st && is->video_st)

                av_diff = get_audio_clock(is) - get_video_clock(is);

            printf("%7.2f A-V:%7.3f fd=%4d aq=%5dKB vq=%5dKB sq=%5dB f=%"PRId64"/%"PRId64"   \r",

                   get_master_clock(is),

                   av_diff,

                   is->frame_drops_early + is->frame_drops_late,

                   aqsize / 1024,

                   vqsize / 1024,

                   sqsize,

                   is->video_st ? is->video_st->codec->pts_correction_num_faulty_dts : 0,

                   is->video_st ? is->video_st->codec->pts_correction_num_faulty_pts : 0);

            fflush(stdout);

            last_time = cur_time;

        }

    }

}


static int alloc_buffer(FrameBuffer **pool, AVCodecContext *s, FrameBuffer **pbuf)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->pix_fmt);

    FrameBuffer *buf;

    int i, ret;

    int pixel_size;

    int h_chroma_shift, v_chroma_shift;

    int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1

    int w = s->width, h = s->height;

    if (!desc)

        return AVERROR(EINVAL);

    pixel_size = desc->comp[0].step_minus1 + 1;

    buf = av_mallocz(sizeof(*buf));

    if (!buf)

        return AVERROR(ENOMEM);

    if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {

        w += 2*edge;

        h += 2*edge;

    }

    avcodec_align_dimensions(s, &w, &h);

    if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,

                              s->pix_fmt, 32)) < 0) {

        av_freep(&buf);

        return ret;

    }

    /* XXX this shouldn't be needed, but some tests break without this line

     * those decoders are buggy and need to be fixed.

     * the following tests fail:

     */

    memset(buf->base[0], 128, ret);

    av_pix_fmt_get_chroma_sub_sample(s->pix_fmt,

                                     &h_chroma_shift, &v_chroma_shift);

    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {

        const int h_shift = i==0 ? 0 : h_chroma_shift;

        const int v_shift = i==0 ? 0 : v_chroma_shift;

        if (s->flags & CODEC_FLAG_EMU_EDGE)

            buf->data[i] = buf->base[i];

        else if (buf->base[i])

            buf->data[i] = buf->base[i] +

                           FFALIGN((buf->linesize[i]*edge >> v_shift) +

                                   (pixel_size*edge >> h_shift), 32);

    }

    buf->w       = s->width;

    buf->h       = s->height;

    buf->pix_fmt = s->pix_fmt;

    buf->pool    = pool;

    *pbuf = buf;

    return 0;

}


URLProtocol *ffurl_protocol_next(const URLProtocol *prev)

{

    return prev ? prev->next : first_protocol;

}


static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)

{

    int tag = track->enc->codec_tag;

    if (!tag || (track->enc->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&

                 (tag == MKTAG('d','v','c','p') ||

                  track->enc->codec_id == CODEC_ID_RAWVIDEO ||

                  track->enc->codec_id == CODEC_ID_H263 ||

                  av_get_bits_per_sample(track->enc->codec_id)))) { // pcm audio

        if (track->enc->codec_id == CODEC_ID_DVVIDEO)

            tag = mov_get_dv_codec_tag(s, track);

        else if (track->enc->codec_id == CODEC_ID_RAWVIDEO)

            tag = mov_get_rawvideo_codec_tag(s, track);

        else if (track->enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            tag = ff_codec_get_tag(codec_movvideo_tags, track->enc->codec_id);

            if (!tag) { // if no mac fcc found, try with Microsoft tags

                tag = ff_codec_get_tag(ff_codec_bmp_tags, track->enc->codec_id);

                if (tag)

                    av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, "

                           "the file may be unplayable!\n");

            }

        } else if (track->enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            tag = ff_codec_get_tag(codec_movaudio_tags, track->enc->codec_id);

            if (!tag) { // if no mac fcc found, try with Microsoft tags

                int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->enc->codec_id);

                if (ms_tag) {

                    tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));

                    av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, "

                           "the file may be unplayable!\n");

                }

            }

        } else if (track->enc->codec_type == AVMEDIA_TYPE_SUBTITLE)

            tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->enc->codec_id);

    }

    return tag;

}


static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)

{

    NvencContext *ctx = avctx->priv_data;

    int nb_surfaces = 0;

    if (ctx->rc_lookahead > 0) {

        nb_surfaces = ctx->rc_lookahead + ((ctx->encode_config.frameIntervalP > 0) ? ctx->encode_config.frameIntervalP : 0) + 1 + 4;

        if (ctx->nb_surfaces < nb_surfaces) {

            av_log(avctx, AV_LOG_WARNING,

                   "Defined rc_lookahead requires more surfaces, "

                   "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);

            ctx->nb_surfaces = nb_surfaces;

        }

    }

    ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));

    ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);

    return 0;

}


yuv2rgba64_full_2_c_template(SwsContext *c, const int32_t *buf[2],

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf[2], uint16_t *dest, int dstW,

                       int yalpha, int uvalpha, int y,

                       enum AVPixelFormat target, int hasAlpha, int eightbytes)

{

    const int32_t *buf0  = buf[0],  *buf1  = buf[1],

                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1],

                  *abuf0 = hasAlpha ? abuf[0] : NULL,

                  *abuf1 = hasAlpha ? abuf[1] : NULL;

    int  yalpha1 = 4096 - yalpha;

    int uvalpha1 = 4096 - uvalpha;

    int i;

    int A = 0xffff<<14;

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

        int Y  = (buf0[i]     * yalpha1  + buf1[i]     * yalpha) >> 14;

        int U  = (ubuf0[i]   * uvalpha1 + ubuf1[i]     * uvalpha + (-128 << 23)) >> 14;

        int V  = (vbuf0[i]   * uvalpha1 + vbuf1[i]     * uvalpha + (-128 << 23)) >> 14;

        int R, G, B;

        Y -= c->yuv2rgb_y_offset;

        Y *= c->yuv2rgb_y_coeff;

        Y += 1 << 13;

        R = V * c->yuv2rgb_v2r_coeff;

        G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

        B =                            U * c->yuv2rgb_u2b_coeff;

        if (hasAlpha) {

            A = (abuf0[i] * yalpha1 + abuf1[i] * yalpha) >> 1;

            A += 1 << 13;

        }

        output_pixel(&dest[0], av_clip_uintp2(R_B + Y, 30) >> 14);

        output_pixel(&dest[1], av_clip_uintp2(  G + Y, 30) >> 14);

        output_pixel(&dest[2], av_clip_uintp2(B_R + Y, 30) >> 14);

        if (eightbytes) {

            output_pixel(&dest[3], av_clip_uintp2(A, 30) >> 14);

            dest += 4;

        } else {

            dest += 3;

        }

    }

}


static void probe_codec(AVFormatContext *s, AVStream *st, const AVPacket *pkt)

{

    if(st->codec->codec_id == CODEC_ID_PROBE){

        AVProbeData *pd = &st->probe_data;

        av_log(s, AV_LOG_DEBUG, "probing stream %d\n", st->index);

        --st->probe_packets;

        pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);

        memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);

        pd->buf_size += pkt->size;

        memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);

        if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){

            //FIXME we do not reduce score to 0 for the case of running out of buffer space in bytes

            set_codec_from_probe_data(s, st, pd, st->probe_packets > 0 ? AVPROBE_SCORE_MAX/4 : 0);

            if(st->codec->codec_id != CODEC_ID_PROBE){

                pd->buf_size=0;

                av_freep(&pd->buf);

                av_log(s, AV_LOG_DEBUG, "probed stream %d\n", st->index);

            }

        }

    }

}


static void mpeg4_encode_vol_header(MpegEncContext * s, int vo_number, int vol_number)

{

    int vo_ver_id;

    if(s->max_b_frames || s->quarter_sample){

        vo_ver_id= 5;

        s->vo_type= ADV_SIMPLE_VO_TYPE;

    }else{

        vo_ver_id= 1;

        s->vo_type= SIMPLE_VO_TYPE;

    }

    put_bits(&s->pb, 16, 0);

    put_bits(&s->pb, 16, 0x100 + vo_number);        /* video obj */

    put_bits(&s->pb, 16, 0);

    put_bits(&s->pb, 16, 0x120 + vol_number);       /* video obj layer */

    put_bits(&s->pb, 1, 0);		/* random access vol */

    put_bits(&s->pb, 8, s->vo_type);	/* video obj type indication */

    put_bits(&s->pb, 1, 1);		/* is obj layer id= yes */

      put_bits(&s->pb, 4, vo_ver_id);	/* is obj layer ver id */

      put_bits(&s->pb, 3, 1);		/* is obj layer priority */

    aspect_to_info(s, s->avctx->sample_aspect_ratio);

    put_bits(&s->pb, 4, s->aspect_ratio_info);/* aspect ratio info */

    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED){

        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.num);

        put_bits(&s->pb, 8, s->avctx->sample_aspect_ratio.den);

    }

    if(s->low_delay){

        put_bits(&s->pb, 1, 1);		/* vol control parameters= yes */

        put_bits(&s->pb, 2, 1);		/* chroma format YUV 420/YV12 */

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

        put_bits(&s->pb, 1, 0);		/* vbv parameters= no */

    }else{

        put_bits(&s->pb, 1, 0);		/* vol control parameters= no */

    }

    put_bits(&s->pb, 2, RECT_SHAPE);	/* vol shape= rectangle */

    put_bits(&s->pb, 1, 1);		/* marker bit */

    put_bits(&s->pb, 16, s->time_increment_resolution);

    if (s->time_increment_bits < 1)

        s->time_increment_bits = 1;

    put_bits(&s->pb, 1, 1);		/* marker bit */

    put_bits(&s->pb, 1, 0);		/* fixed vop rate=no */

    put_bits(&s->pb, 1, 1);		/* marker bit */

    put_bits(&s->pb, 13, s->width);	/* vol width */

    put_bits(&s->pb, 1, 1);		/* marker bit */

    put_bits(&s->pb, 13, s->height);	/* vol height */

    put_bits(&s->pb, 1, 1);		/* marker bit */

    put_bits(&s->pb, 1, s->progressive_sequence ? 0 : 1);

    put_bits(&s->pb, 1, 1);		/* obmc disable */

    if (vo_ver_id == 1) {

        put_bits(&s->pb, 1, s->vol_sprite_usage=0);		/* sprite enable */

    }else{

        put_bits(&s->pb, 2, s->vol_sprite_usage=0);		/* sprite enable */

    }

    s->quant_precision=5;

    put_bits(&s->pb, 1, 0);		/* not 8 bit == false */

    put_bits(&s->pb, 1, s->mpeg_quant);	/* quant type= (0=h263 style)*/

    if(s->mpeg_quant){

        ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);

        ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);

    }

    if (vo_ver_id != 1)

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

    put_bits(&s->pb, 1, 1);		/* complexity estimation disable */

    s->resync_marker= s->rtp_mode;

    put_bits(&s->pb, 1, s->resync_marker ? 0 : 1);/* resync marker disable */

    put_bits(&s->pb, 1, s->data_partitioning ? 1 : 0);

    if(s->data_partitioning){

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

    }

    if (vo_ver_id != 1){

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

        put_bits(&s->pb, 1, 0);		/* reduced res vop */

    }

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

    ff_mpeg4_stuffing(&s->pb);

    /* user data */

    if(!(s->flags & CODEC_FLAG_BITEXACT)){

        put_bits(&s->pb, 16, 0);

        put_bits(&s->pb, 16, 0x1B2);	/* user_data */

	put_string(&s->pb, LIBAVCODEC_IDENT);

        ff_mpeg4_stuffing(&s->pb);

    }

}


static void ide_atapi_cmd_read_pio(IDEState *s, int lba, int nb_sectors,

                                   int sector_size)

{

    s->lba = lba;

    s->packet_transfer_size = nb_sectors * sector_size;

    s->elementary_transfer_size = 0;

    s->io_buffer_index = sector_size;

    s->cd_sector_size = sector_size;

    s->status = READY_STAT | SEEK_STAT;

    ide_atapi_cmd_reply_end(s);

}


static inline int *DEC_UPAIR(int *dst, unsigned idx, unsigned sign)

{

    dst[0] = (idx & 15) * (1 - (sign & 0xFFFFFFFE));

    dst[1] = (idx >> 4 & 15) * (1 - ((sign & 1) << 1));

    return dst + 2;

}


static void av_always_inline filter_mb_edgech( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h ) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]]+1;

        tc[1] = tc0_table[index_a][bS[1]]+1;

        tc[2] = tc0_table[index_a][bS[2]]+1;

        tc[3] = tc0_table[index_a][bS[3]]+1;

        h->h264dsp.h264_v_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_v_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


static void usbredir_configuration_status(void *priv, uint32_t id,

    struct usb_redir_configuration_status_header *config_status)

{

    USBRedirDevice *dev = priv;

    AsyncURB *aurb;

    int len = 0;

    DPRINTF("set config status %d config %d id %u\n", config_status->status,

            config_status->configuration, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        return;

    }

    if (aurb->packet) {

        if (aurb->get) {

            dev->dev.data_buf[0] = config_status->configuration;

            len = 1;

        }

        aurb->packet->len =

            usbredir_handle_status(dev, config_status->status, len);

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

    }

    async_free(dev, aurb);

}


static void gen_smul_dual(TCGv a, TCGv b)

{

    TCGv tmp1 = new_tmp();

    TCGv tmp2 = new_tmp();

    tcg_gen_ext16s_i32(tmp1, a);

    tcg_gen_ext16s_i32(tmp2, b);

    tcg_gen_mul_i32(tmp1, tmp1, tmp2);

    dead_tmp(tmp2);

    tcg_gen_sari_i32(a, a, 16);

    tcg_gen_sari_i32(b, b, 16);

    tcg_gen_mul_i32(b, b, a);

    tcg_gen_mov_i32(a, tmp1);

    dead_tmp(tmp1);

}


static int ac3_parse_bsi(AC3DecodeContext *ctx)

{

    ac3_bsi *bsi = &ctx->bsi;

    uint32_t *flags = &bsi->flags;

    GetBitContext *gb = &ctx->gb;

    *flags = 0;

    bsi->cmixlev = 0;

    bsi->surmixlev = 0;

    bsi->dsurmod = 0;

    bsi->bsid = get_bits(gb, 5);

    if (bsi->bsid > 0x08)

        return -1;

    bsi->bsmod = get_bits(gb, 3);

    bsi->acmod = get_bits(gb, 3);

    if (bsi->acmod & 0x01 && bsi->acmod != 0x01)

        bsi->cmixlev = get_bits(gb, 2);

    if (bsi->acmod & 0x04)

        bsi->surmixlev = get_bits(gb, 2);

    if (bsi->acmod == 0x02)

        bsi->dsurmod = get_bits(gb, 2);

    if (get_bits(gb, 1))

        *flags |= AC3_BSI_LFEON;

    bsi->dialnorm = get_bits(gb, 5);

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_COMPRE;

        bsi->compr = get_bits(gb, 5);

    }

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_LANGCODE;

        bsi->langcod = get_bits(gb, 8);

    }

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_AUDPRODIE;

        bsi->mixlevel = get_bits(gb, 5);

        bsi->roomtyp = get_bits(gb, 2);

    }

    if (bsi->acmod == 0x00) {

        bsi->dialnorm2 = get_bits(gb, 5);

        if (get_bits(gb, 1)) {

            *flags |= AC3_BSI_COMPR2E;

            bsi->compr2 = get_bits(gb, 5);

        }

        if (get_bits(gb, 1)) {

            *flags |= AC3_BSI_LANGCOD2E;

            bsi->langcod2 = get_bits(gb, 8);

        }

        if (get_bits(gb, 1)) {

            *flags |= AC3_BSI_AUDPRODIE;

            bsi->mixlevel2 = get_bits(gb, 5);

            bsi->roomtyp2 = get_bits(gb, 2);

        }

    }

    if (get_bits(gb, 1))

        *flags |= AC3_BSI_COPYRIGHTB;

    if (get_bits(gb, 1))

        *flags |= AC3_BSI_ORIGBS;

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_TIMECOD1E;

        bsi->timecod1 = get_bits(gb, 14);

    }

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_TIMECOD2E;

        bsi->timecod2 = get_bits(gb, 14);

    }

    if (get_bits(gb, 1)) {

        *flags |= AC3_BSI_ADDBSIE;

        bsi->addbsil = get_bits(gb, 6);

        do {

            get_bits(gb, 8);

        } while (bsi->addbsil--);

    }

    bsi->nfchans = nfchans_tbl[bsi->acmod];

    return 0;

}