static void jump_to_IPL_code(uint64_t address)

{

    /* store the subsystem information _after_ the bootmap was loaded */

    write_subsystem_identification();

    /*

     * The IPL PSW is at address 0. We also must not overwrite the

     * content of non-BIOS memory after we loaded the guest, so we

     * save the original content and restore it in jump_to_IPL_2.

     */

    ResetInfo *current = 0;

    save = *current;

    current->ipl_addr = (uint32_t) (uint64_t) &jump_to_IPL_2;

    current->ipl_continue = address & 0x7fffffff;

    debug_print_int("set IPL addr to", current->ipl_continue);

    /* Ensure the guest output starts fresh */

    sclp_print("\n");

    /*

     * HACK ALERT.

     * We use the load normal reset to keep r15 unchanged. jump_to_IPL_2

     * can then use r15 as its stack pointer.

     */

    asm volatile("lghi 1,1\n\t"

                 "diag 1,1,0x308\n\t"

                 : : : "1", "memory");

    virtio_panic("\n! IPL returns !\n");

}


static void wdt_ib700_realize(DeviceState *dev, Error **errp)

{

    IB700State *s = IB700(dev);

    PortioList *port_list = g_new(PortioList, 1);

    ib700_debug("watchdog init\n");

    s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ib700_timer_expired, s);

    portio_list_init(port_list, OBJECT(s), wdt_portio_list, s, "ib700");

    portio_list_add(port_list, isa_address_space_io(&s->parent_obj), 0);

}


static int ffm_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    FFMContext *ffm = s->priv_data;

    AVStream *st = s->streams[pkt->stream_index];

    int64_t pts;

    uint8_t header[FRAME_HEADER_SIZE];

    pts = ffm->start_time + pkt->pts;

    /* packet size & key_frame */

    header[0] = pkt->stream_index;

    header[1] = 0;

    if (pkt->flags & PKT_FLAG_KEY)

        header[1] |= FLAG_KEY_FRAME;

    AV_WB24(header+2, pkt->size);

    AV_WB24(header+5, pkt->duration);

    ffm_write_data(s, header, FRAME_HEADER_SIZE, pts, 1);

    ffm_write_data(s, pkt->data, pkt->size, pts, 0);

    return 0;

}


static inline void range_dec_normalize(APEContext * ctx)

{

    while (ctx->rc.range <= BOTTOM_VALUE) {

        ctx->rc.buffer = (ctx->rc.buffer << 8) | bytestream_get_byte(&ctx->ptr);

        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);

        ctx->rc.range  <<= 8;

    }

}


static int read_rle_sgi(uint8_t *out_buf, SgiState *s)

{

    uint8_t *dest_row;

    unsigned int len = s->height * s->depth * 4;

    GetByteContext g_table = s->g;

    unsigned int y, z;

    unsigned int start_offset;

    int linesize, ret;

    /* size of  RLE offset and length tables */

    if (len * 2 > bytestream2_get_bytes_left(&s->g)) {

        return AVERROR_INVALIDDATA;

    }

    for (z = 0; z < s->depth; z++) {

        dest_row = out_buf;

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

            linesize = s->width * s->depth * s->bytes_per_channel;

            dest_row -= s->linesize;

            start_offset = bytestream2_get_be32(&g_table);

            bytestream2_seek(&s->g, start_offset, SEEK_SET);

            if (s->bytes_per_channel == 1)

                ret = expand_rle_row8(s, dest_row + z, linesize, s->depth);

            else

                ret = expand_rle_row16(s, (uint16_t *)dest_row + z, linesize, s->depth);

            if (ret != s->width)

                return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static int xvid_ff_2pass_destroy(struct xvid_context *ref,

                                xvid_plg_destroy_t *param) {

    /* Currently cannot think of anything to do on destruction */

    /* Still, the framework should be here for reference/use */

    if( ref->twopassbuffer != NULL )

        ref->twopassbuffer[0] = 0;

    return 0;

}


cpu_mips_check_sign_extensions (CPUMIPSState *env, FILE *f,

                                fprintf_function cpu_fprintf,

                                int flags)

{

    int i;

    if (!SIGN_EXT_P(env->active_tc.PC))

        cpu_fprintf(f, "BROKEN: pc=0x" TARGET_FMT_lx "\n", env->active_tc.PC);

    if (!SIGN_EXT_P(env->active_tc.HI[0]))

        cpu_fprintf(f, "BROKEN: HI=0x" TARGET_FMT_lx "\n", env->active_tc.HI[0]);

    if (!SIGN_EXT_P(env->active_tc.LO[0]))

        cpu_fprintf(f, "BROKEN: LO=0x" TARGET_FMT_lx "\n", env->active_tc.LO[0]);

    if (!SIGN_EXT_P(env->btarget))

        cpu_fprintf(f, "BROKEN: btarget=0x" TARGET_FMT_lx "\n", env->btarget);

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

        if (!SIGN_EXT_P(env->active_tc.gpr[i]))

            cpu_fprintf(f, "BROKEN: %s=0x" TARGET_FMT_lx "\n", regnames[i], env->active_tc.gpr[i]);

    }

    if (!SIGN_EXT_P(env->CP0_EPC))

        cpu_fprintf(f, "BROKEN: EPC=0x" TARGET_FMT_lx "\n", env->CP0_EPC);

    if (!SIGN_EXT_P(env->lladdr))

        cpu_fprintf(f, "BROKEN: LLAddr=0x" TARGET_FMT_lx "\n", env->lladdr);

}


void put_no_rnd_h264_chroma_mc8_altivec(uint8_t * dst, uint8_t * src, int stride, int h, int x, int y) {

   DECLARE_ALIGNED_16(signed int, ABCD[4]) =

                        {((8 - x) * (8 - y)),

                             ((x) * (8 - y)),

                         ((8 - x) * (y)),

                             ((x) * (y))};

    register int i;

    vec_u8 fperm;

    const vec_s32 vABCD = vec_ld(0, ABCD);

    const vec_s16 vA = vec_splat((vec_s16)vABCD, 1);

    const vec_s16 vB = vec_splat((vec_s16)vABCD, 3);

    const vec_s16 vC = vec_splat((vec_s16)vABCD, 5);

    const vec_s16 vD = vec_splat((vec_s16)vABCD, 7);

    LOAD_ZERO;

    const vec_s16 v28ss = vec_sub(vec_sl(vec_splat_s16(1),vec_splat_u16(5)),vec_splat_s16(4));

    const vec_u16 v6us  = vec_splat_u16(6);

    register int loadSecond     = (((unsigned long)src) % 16) <= 7 ? 0 : 1;

    register int reallyBadAlign = (((unsigned long)src) % 16) == 15 ? 1 : 0;

    vec_u8 vsrcAuc, vsrcBuc, vsrcperm0, vsrcperm1;

    vec_u8 vsrc0uc, vsrc1uc;

    vec_s16 vsrc0ssH, vsrc1ssH;

    vec_u8 vsrcCuc, vsrc2uc, vsrc3uc;

    vec_s16 vsrc2ssH, vsrc3ssH, psum;

    vec_u8 vdst, ppsum, fsum;

    if (((unsigned long)dst) % 16 == 0) {

        fperm = (vec_u8){0x10, 0x11, 0x12, 0x13,

                           0x14, 0x15, 0x16, 0x17,

                           0x08, 0x09, 0x0A, 0x0B,

                           0x0C, 0x0D, 0x0E, 0x0F};

    } else {

        fperm = (vec_u8){0x00, 0x01, 0x02, 0x03,

                           0x04, 0x05, 0x06, 0x07,

                           0x18, 0x19, 0x1A, 0x1B,

                           0x1C, 0x1D, 0x1E, 0x1F};

    }

    vsrcAuc = vec_ld(0, src);

    if (loadSecond)

        vsrcBuc = vec_ld(16, src);

    vsrcperm0 = vec_lvsl(0, src);

    vsrcperm1 = vec_lvsl(1, src);

    vsrc0uc = vec_perm(vsrcAuc, vsrcBuc, vsrcperm0);

    if (reallyBadAlign)

        vsrc1uc = vsrcBuc;

    else

        vsrc1uc = vec_perm(vsrcAuc, vsrcBuc, vsrcperm1);

    vsrc0ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc0uc);

    vsrc1ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc1uc);

    if (!loadSecond) {// -> !reallyBadAlign

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

            vsrcCuc = vec_ld(stride + 0, src);

            vsrc2uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm0);

            vsrc3uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm1);

            vsrc2ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc2uc);

            vsrc3ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc3uc);

            psum = vec_mladd(vA, vsrc0ssH, vec_splat_s16(0));

            psum = vec_mladd(vB, vsrc1ssH, psum);

            psum = vec_mladd(vC, vsrc2ssH, psum);

            psum = vec_mladd(vD, vsrc3ssH, psum);

            psum = vec_add(v28ss, psum);

            psum = vec_sra(psum, v6us);

            vdst = vec_ld(0, dst);

            ppsum = (vec_u8)vec_packsu(psum, psum);

            fsum = vec_perm(vdst, ppsum, fperm);

            vec_st(fsum, 0, dst);

            vsrc0ssH = vsrc2ssH;

            vsrc1ssH = vsrc3ssH;

            dst += stride;

            src += stride;

        }

    } else {

        vec_u8 vsrcDuc;

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

            vsrcCuc = vec_ld(stride + 0, src);

            vsrcDuc = vec_ld(stride + 16, src);

            vsrc2uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm0);

            if (reallyBadAlign)

                vsrc3uc = vsrcDuc;

            else

                vsrc3uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm1);

            vsrc2ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc2uc);

            vsrc3ssH = (vec_s16)vec_mergeh(zero_u8v, (vec_u8)vsrc3uc);

            psum = vec_mladd(vA, vsrc0ssH, vec_splat_s16(0));

            psum = vec_mladd(vB, vsrc1ssH, psum);

            psum = vec_mladd(vC, vsrc2ssH, psum);

            psum = vec_mladd(vD, vsrc3ssH, psum);

            psum = vec_add(v28ss, psum);

            psum = vec_sr(psum, v6us);

            vdst = vec_ld(0, dst);

            ppsum = (vec_u8)vec_pack(psum, psum);

            fsum = vec_perm(vdst, ppsum, fperm);

            vec_st(fsum, 0, dst);

            vsrc0ssH = vsrc2ssH;

            vsrc1ssH = vsrc3ssH;

            dst += stride;

            src += stride;

        }

    }

}


static int sol_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    int ret;

    if (s->pb->eof_reached)

        return AVERROR(EIO);

    ret= av_get_packet(s->pb, pkt, MAX_SIZE);

    pkt->stream_index = 0;

    /* note: we need to modify the packet size here to handle the last

       packet */

    pkt->size = ret;

    return 0;

}


static inline TCGv gen_ld32(TCGv addr, int index)

{

    TCGv tmp = new_tmp();

    tcg_gen_qemu_ld32u(tmp, addr, index);

    return tmp;

}


static int kvm_irqchip_get_virq(KVMState *s)

{

    uint32_t *word = s->used_gsi_bitmap;

    int max_words = ALIGN(s->gsi_count, 32) / 32;

    int i, zeroes;

    bool retry = true;

again:

    /* Return the lowest unused GSI in the bitmap */

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

        zeroes = ctz32(~word[i]);

        if (zeroes == 32) {

            continue;

        }

        return zeroes + i * 32;

    }

    if (!s->direct_msi && retry) {

        retry = false;

        kvm_flush_dynamic_msi_routes(s);

        goto again;

    }

    return -ENOSPC;

}


void bdrv_drain_all(void)

{

    /* Always run first iteration so any pending completion BHs run */

    bool busy = true;

    BlockDriverState *bs = NULL;

    GSList *aio_ctxs = NULL, *ctx;

    while ((bs = bdrv_next(bs))) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        aio_context_acquire(aio_context);

        if (bs->job) {

            block_job_pause(bs->job);

        }

        bdrv_no_throttling_begin(bs);

        bdrv_drain_recurse(bs);

        aio_context_release(aio_context);

        if (!g_slist_find(aio_ctxs, aio_context)) {

            aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);

        }

    }

    /* Note that completion of an asynchronous I/O operation can trigger any

     * number of other I/O operations on other devices---for example a

     * coroutine can submit an I/O request to another device in response to

     * request completion.  Therefore we must keep looping until there was no

     * more activity rather than simply draining each device independently.

     */

    while (busy) {

        busy = false;

        for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {

            AioContext *aio_context = ctx->data;

            bs = NULL;

            aio_context_acquire(aio_context);

            while ((bs = bdrv_next(bs))) {

                if (aio_context == bdrv_get_aio_context(bs)) {

                    bdrv_flush_io_queue(bs);

                    if (bdrv_requests_pending(bs)) {

                        busy = true;

                        aio_poll(aio_context, busy);

                    }

                }

            }

            busy |= aio_poll(aio_context, false);

            aio_context_release(aio_context);

        }

    }

    bs = NULL;

    while ((bs = bdrv_next(bs))) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        aio_context_acquire(aio_context);

        bdrv_no_throttling_end(bs);

        if (bs->job) {

            block_job_resume(bs->job);

        }

        aio_context_release(aio_context);

    }

    g_slist_free(aio_ctxs);

}


static int net_socket_mcast_create(struct sockaddr_in *mcastaddr, struct in_addr *localaddr)

{

    struct ip_mreq imr;

    int fd;

    int val, ret;

    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {

	fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",

		inet_ntoa(mcastaddr->sin_addr),

                (int)ntohl(mcastaddr->sin_addr.s_addr));

	return -1;

    }

    fd = qemu_socket(PF_INET, SOCK_DGRAM, 0);

    if (fd < 0) {

        perror("socket(PF_INET, SOCK_DGRAM)");

        return -1;

    }

    val = 1;

    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,

                   (const char *)&val, sizeof(val));

    if (ret < 0) {

	perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");

	goto fail;

    }

    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));

    if (ret < 0) {

        perror("bind");

        goto fail;

    }

    /* Add host to multicast group */

    imr.imr_multiaddr = mcastaddr->sin_addr;

    if (localaddr) {

        imr.imr_interface = *localaddr;

    } else {

        imr.imr_interface.s_addr = htonl(INADDR_ANY);

    }

    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,

                     (const char *)&imr, sizeof(struct ip_mreq));

    if (ret < 0) {

	perror("setsockopt(IP_ADD_MEMBERSHIP)");

	goto fail;

    }

    /* Force mcast msgs to loopback (eg. several QEMUs in same host */

    val = 1;

    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,

                   (const char *)&val, sizeof(val));

    if (ret < 0) {

	perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");

	goto fail;

    }

    /* If a bind address is given, only send packets from that address */

    if (localaddr != NULL) {

        ret = setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF,

                         (const char *)localaddr, sizeof(*localaddr));

        if (ret < 0) {

            perror("setsockopt(IP_MULTICAST_IF)");

            goto fail;

        }

    }

    socket_set_nonblock(fd);

    return fd;

fail:

    if (fd >= 0)

        closesocket(fd);

    return -1;

}


ram_addr_t last_ram_offset(void)

{

    RAMBlock *block;

    ram_addr_t last = 0;

    QTAILQ_FOREACH(block, &ram_list.blocks, next)

        last = MAX(last, block->offset + block->length);

    return last;

}


void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,

                            Error **errp)

{

    if (!has_force) {

        force = false;

    }

    do_open_tray(device, force, errp);

}


void pci_register_vga(PCIDevice *pci_dev, MemoryRegion *mem,

                      MemoryRegion *io_lo, MemoryRegion *io_hi)

{

    assert(!pci_dev->has_vga);

    assert(memory_region_size(mem) == QEMU_PCI_VGA_MEM_SIZE);

    pci_dev->vga_regions[QEMU_PCI_VGA_MEM] = mem;

    memory_region_add_subregion_overlap(pci_dev->bus->address_space_mem,

                                        QEMU_PCI_VGA_MEM_BASE, mem, 1);

    assert(memory_region_size(io_lo) == QEMU_PCI_VGA_IO_LO_SIZE);

    pci_dev->vga_regions[QEMU_PCI_VGA_IO_LO] = io_lo;

    memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,

                                        QEMU_PCI_VGA_IO_LO_BASE, io_lo, 1);

    assert(memory_region_size(io_hi) == QEMU_PCI_VGA_IO_HI_SIZE);

    pci_dev->vga_regions[QEMU_PCI_VGA_IO_HI] = io_hi;

    memory_region_add_subregion_overlap(pci_dev->bus->address_space_io,

                                        QEMU_PCI_VGA_IO_HI_BASE, io_hi, 1);

    pci_dev->has_vga = true;

    pci_update_vga(pci_dev);

}


static int qmp_check_client_args(const mon_cmd_t *cmd, QDict *client_args)

{

    int flags, err;

    QDict *cmd_args;

    cmd_args = qdict_from_args_type(cmd->args_type);

    flags = 0;

    err = check_mandatory_args(cmd_args, client_args, &flags);

    if (err) {

        goto out;

    }

    /* TODO: Check client args type */

out:

    QDECREF(cmd_args);

    return err;

}


bool aio_prepare(AioContext *ctx)

{

    /* Poll mode cannot be used with glib's event loop, disable it. */

    poll_set_started(ctx, false);

    return false;

}


static void sigp_initial_cpu_reset(void *arg)

{

    CPUState *cpu = arg;

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    cpu_synchronize_state(cpu);

    scc->initial_cpu_reset(cpu);

    cpu_synchronize_post_reset(cpu);

}


static void mcf_fec_cleanup(NetClientState *nc)

{

    mcf_fec_state *s = qemu_get_nic_opaque(nc);

    g_free(s);

}


static void hid_keyboard_event(DeviceState *dev, QemuConsole *src,

                               InputEvent *evt)

{

    HIDState *hs = (HIDState *)dev;

    int scancodes[3], i, count;

    int slot;

    count = qemu_input_key_value_to_scancode(evt->key->key,

                                             evt->key->down,

                                             scancodes);

    if (hs->n + count > QUEUE_LENGTH) {

        fprintf(stderr, "usb-kbd: warning: key event queue full\n");

        return;

    }

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

        slot = (hs->head + hs->n) & QUEUE_MASK; hs->n++;

        hs->kbd.keycodes[slot] = scancodes[i];

    }

    hs->event(hs);

}


static void pci_vpb_unmap(SysBusDevice *dev, target_phys_addr_t base)

{

    PCIVPBState *s = (PCIVPBState *)dev;

    /* Selfconfig area.  */

    memory_region_del_subregion(get_system_memory(), &s->mem_config);

    /* Normal config area.  */

    memory_region_del_subregion(get_system_memory(), &s->mem_config2);

    if (s->realview) {

        /* IO memory area.  */

        memory_region_del_subregion(get_system_memory(), &s->isa);

    }

}


static int v9fs_synth_init(FsContext *ctx)

{

    QLIST_INIT(&v9fs_synth_root.child);

    qemu_mutex_init(&v9fs_synth_mutex);

    /* Add "." and ".." entries for root */

    v9fs_add_dir_node(&v9fs_synth_root, v9fs_synth_root.attr->mode,

                      "..", v9fs_synth_root.attr, v9fs_synth_root.attr->inode);

    v9fs_add_dir_node(&v9fs_synth_root, v9fs_synth_root.attr->mode,

                      ".", v9fs_synth_root.attr, v9fs_synth_root.attr->inode);

    /* Mark the subsystem is ready for use */

    v9fs_synth_fs = 1;

    return 0;

}


const char *get_feature_xml(CPUState *env, const char *p, const char **newp)

{

    extern const char *const xml_builtin[][2];

    size_t len;

    int i;

    const char *name;

    static char target_xml[1024];

    len = 0;

    while (p[len] && p[len] != ':')

        len++;

    *newp = p + len;

    name = NULL;

    if (strncmp(p, "target.xml", len) == 0) {

        /* Generate the XML description for this CPU.  */

        if (!target_xml[0]) {

            GDBRegisterState *r;

            sprintf(target_xml,

                    "<?xml version=\"1.0\"?>"

                    "<!DOCTYPE target SYSTEM \"gdb-target.dtd\">"

                    "<target>"

                    "<xi:include href=\"%s\"/>",

                    GDB_CORE_XML);

            for (r = env->gdb_regs; r; r = r->next) {

                strcat(target_xml, "<xi:include href=\"");

                strcat(target_xml, r->xml);

                strcat(target_xml, "\"/>");

            }

            strcat(target_xml, "</target>");

        }

        return target_xml;

    }

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

        name = xml_builtin[i][0];

        if (!name || (strncmp(name, p, len) == 0 && strlen(name) == len))

            break;

    }

    return name ? xml_builtin[i][1] : NULL;

}


static int ppc_hash32_translate(CPUPPCState *env, struct mmu_ctx_hash32 *ctx,

                                target_ulong eaddr, int rwx)

{

    int ret;

    target_ulong sr;

    /* 1. Handle real mode accesses */

    if (((rwx == 2) && (msr_ir == 0)) || ((rwx != 2) && (msr_dr == 0))) {

        /* Translation is off */

        ctx->raddr = eaddr;

        ctx->prot = PAGE_READ | PAGE_EXEC | PAGE_WRITE;

        return 0;

    }

    /* 2. Check Block Address Translation entries (BATs) */

    if (env->nb_BATs != 0) {

        ret = ppc_hash32_get_bat(env, ctx, eaddr, rwx);

        if (ret == 0) {

            return 0;

        }

    }

    /* 3. Look up the Segment Register */

    sr = env->sr[eaddr >> 28];

    /* 4. Handle direct store segments */

    if (sr & SR32_T) {

        return ppc_hash32_direct_store(env, sr, eaddr, rwx,

                                       &ctx->raddr, &ctx->prot);

    }

    /* 5. Check for segment level no-execute violation */

    ctx->nx = !!(sr & SR32_NX);

    if ((rwx == 2) && ctx->nx) {

        return -3;

    }

    ret = find_pte32(env, ctx, sr, eaddr, rwx);

    return ret;

}


static int flv_write_trailer(AVFormatContext *s)

{

    int64_t file_size;

    AVIOContext *pb = s->pb;

    FLVContext *flv = s->priv_data;

    int i;

    /* Add EOS tag */

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

        AVCodecContext *enc = s->streams[i]->codec;

        if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&

                enc->codec_id == CODEC_ID_H264) {

            put_avc_eos_tag(pb, flv->last_video_ts);

        }

    }

    file_size = avio_tell(pb);

    /* update informations */

    avio_seek(pb, flv->duration_offset, SEEK_SET);

    put_amf_double(pb, flv->duration / (double)1000);

    avio_seek(pb, flv->filesize_offset, SEEK_SET);

    put_amf_double(pb, file_size);

    avio_seek(pb, file_size, SEEK_SET);

    return 0;

}


static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,

        const char *desc_file_path)

{

    int ret;

    char access[11];

    char type[11];

    char fname[512];

    const char *p = desc;

    int64_t sectors = 0;

    int64_t flat_offset;

    char extent_path[PATH_MAX];

    BlockDriverState *extent_file;

    while (*p) {

        /* parse extent line:

         * RW [size in sectors] FLAT "file-name.vmdk" OFFSET

         * or

         * RW [size in sectors] SPARSE "file-name.vmdk"

         */

        flat_offset = -1;

        ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,

                access, &sectors, type, fname, &flat_offset);

        if (ret < 4 || strcmp(access, "RW")) {

            goto next_line;

        } else if (!strcmp(type, "FLAT")) {

            if (ret != 5 || flat_offset < 0) {

                return -EINVAL;

            }

        } else if (ret != 4) {

            return -EINVAL;

        }

        if (sectors <= 0 ||

            (strcmp(type, "FLAT") && strcmp(type, "SPARSE")) ||

            (strcmp(access, "RW"))) {

            goto next_line;

        }

        path_combine(extent_path, sizeof(extent_path),

                desc_file_path, fname);

        ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags);

        if (ret) {

            return ret;

        }

        /* save to extents array */

        if (!strcmp(type, "FLAT")) {

            /* FLAT extent */

            VmdkExtent *extent;

            extent = vmdk_add_extent(bs, extent_file, true, sectors,

                            0, 0, 0, 0, sectors);

            extent->flat_start_offset = flat_offset << 9;

        } else if (!strcmp(type, "SPARSE")) {

            /* SPARSE extent */

            ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);

            if (ret) {

                bdrv_delete(extent_file);

                return ret;

            }

        } else {

            fprintf(stderr,

                "VMDK: Not supported extent type \"%s\""".\n", type);

            return -ENOTSUP;

        }

next_line:

        /* move to next line */

        while (*p && *p != '\n') {

            p++;

        }

        p++;

    }

    return 0;

}


static int kvm_irqchip_get_virq(KVMState *s)

{

    uint32_t *word = s->used_gsi_bitmap;

    int max_words = ALIGN(s->gsi_count, 32) / 32;

    int i, bit;

    bool retry = true;

again:

    /* Return the lowest unused GSI in the bitmap */

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

        bit = ffs(~word[i]);

        if (!bit) {

            continue;

        }

        return bit - 1 + i * 32;

    }

    if (retry) {

        retry = false;

        kvm_flush_dynamic_msi_routes(s);

        goto again;

    }

    return -ENOSPC;

}


static int check_empty_sectors(BlockBackend *blk, int64_t sect_num,

                               int sect_count, const char *filename,

                               uint8_t *buffer, bool quiet)

{

    int pnum, ret = 0;

    ret = blk_pread(blk, sect_num << BDRV_SECTOR_BITS, buffer,

                    sect_count << BDRV_SECTOR_BITS);

    if (ret < 0) {

        error_report("Error while reading offset %" PRId64 " of %s: %s",

                     sectors_to_bytes(sect_num), filename, strerror(-ret));

        return ret;

    }

    ret = is_allocated_sectors(buffer, sect_count, &pnum);

    if (ret || pnum != sect_count) {

        qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",

                sectors_to_bytes(ret ? sect_num : sect_num + pnum));

        return 1;

    }

    return 0;

}


static int migration_put_buffer(void *opaque, const uint8_t *buf,

                               int64_t pos, int size)

{

    MigrationState *s = opaque;

    int ret;

    DPRINTF("putting %d bytes at %" PRId64 "\n", size, pos);

    if (size <= 0) {

        return size;

    }

    qemu_put_buffer(s->migration_file, buf, size);

    ret = qemu_file_get_error(s->migration_file);

    if (ret) {

        return ret;

    }

    s->bytes_xfer += size;

    return size;

}


void bdrv_delete(BlockDriverState *bs)

{

    assert(!bs->peer);

    /* remove from list, if necessary */

    bdrv_make_anon(bs);

    bdrv_close(bs);

    if (bs->file != NULL) {

        bdrv_delete(bs->file);

    }

    assert(bs != bs_snapshots);

    g_free(bs);

}


static av_always_inline void mc_chroma_unscaled(VP9Context *s, vp9_mc_func (*mc)[2],

                                                uint8_t *dst_u, uint8_t *dst_v,

                                                ptrdiff_t dst_stride,

                                                const uint8_t *ref_u, ptrdiff_t src_stride_u,

                                                const uint8_t *ref_v, ptrdiff_t src_stride_v,

                                                ThreadFrame *ref_frame,

                                                ptrdiff_t y, ptrdiff_t x, const VP56mv *mv,

                                                int bw, int bh, int w, int h, int bytesperpixel)

{

    int mx = mv->x * (1 << !s->ss_h), my = mv->y * (1 << !s->ss_v), th;

    y += my >> 4;

    x += mx >> 4;

    ref_u += y * src_stride_u + x * bytesperpixel;

    ref_v += y * src_stride_v + x * bytesperpixel;

    mx &= 15;

    my &= 15;

    // FIXME bilinear filter only needs 0/1 pixels, not 3/4

    // we use +7 because the last 7 pixels of each sbrow can be changed in

    // the longest loopfilter of the next sbrow

    th = (y + bh + 4 * !!my + 7) >> (6 - s->ss_v);

    ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);

    if (x < !!mx * 3 || y < !!my * 3 ||

        x + !!mx * 4 > w - bw || y + !!my * 4 > h - bh) {

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_u - !!my * 3 * src_stride_u - !!mx * 3 * bytesperpixel,

                                 160, src_stride_u,

                                 bw + !!mx * 7, bh + !!my * 7,

                                 x - !!mx * 3, y - !!my * 3, w, h);

        ref_u = s->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;

        mc[!!mx][!!my](dst_u, dst_stride, ref_u, 160, bh, mx, my);

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer,

                                 ref_v - !!my * 3 * src_stride_v - !!mx * 3 * bytesperpixel,

                                 160, src_stride_v,

                                 bw + !!mx * 7, bh + !!my * 7,

                                 x - !!mx * 3, y - !!my * 3, w, h);

        ref_v = s->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;

        mc[!!mx][!!my](dst_v, dst_stride, ref_v, 160, bh, mx, my);

    } else {

        mc[!!mx][!!my](dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my);

        mc[!!mx][!!my](dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my);

    }

}


static void m48t59_isa_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = m48t59_isa_realize;

    dc->no_user = 1;

    dc->reset = m48t59_reset_isa;

    dc->props = m48t59_isa_properties;

}


static int svq3_decode_mb(SVQ3Context *svq3, unsigned int mb_type)

{

    H264Context *h = &svq3->h;

    int i, j, k, m, dir, mode;

    int cbp = 0;

    uint32_t vlc;

    int8_t *top, *left;

    MpegEncContext *const s = (MpegEncContext *) h;

    const int mb_xy = h->mb_xy;

    const int b_xy  = 4*s->mb_x + 4*s->mb_y*h->b_stride;

    h->top_samples_available      = (s->mb_y == 0) ? 0x33FF : 0xFFFF;

    h->left_samples_available     = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

    h->topright_samples_available = 0xFFFF;

    if (mb_type == 0) {           /* SKIP */

        if (s->pict_type == AV_PICTURE_TYPE_P || s->next_picture.f.mb_type[mb_xy] == -1) {

            svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 0, 0);

            if (s->pict_type == AV_PICTURE_TYPE_B) {

                svq3_mc_dir_part(s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 1, 1);

            }

            mb_type = MB_TYPE_SKIP;

        } else {

            mb_type = FFMIN(s->next_picture.f.mb_type[mb_xy], 6);

            if (svq3_mc_dir(h, mb_type, PREDICT_MODE, 0, 0) < 0)

                return -1;

            if (svq3_mc_dir(h, mb_type, PREDICT_MODE, 1, 1) < 0)

                return -1;

            mb_type = MB_TYPE_16x16;

        }

    } else if (mb_type < 8) {     /* INTER */

        if (svq3->thirdpel_flag && svq3->halfpel_flag == !get_bits1 (&s->gb)) {

            mode = THIRDPEL_MODE;

        } else if (svq3->halfpel_flag && svq3->thirdpel_flag == !get_bits1 (&s->gb)) {

            mode = HALFPEL_MODE;

        } else {

            mode = FULLPEL_MODE;

        }

        /* fill caches */

        /* note ref_cache should contain here:

            ????????

            ???11111

            N??11111

            N??11111

            N??11111

        */

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

            if (s->mb_x > 0 && h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1]+6] != -1) {

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

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - 1 + i*h->b_stride];

                }

            } else {

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

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = 0;

                }

            }

            if (s->mb_y > 0) {

                memcpy(h->mv_cache[m][scan8[0] - 1*8], s->current_picture.f.motion_val[m][b_xy - h->b_stride], 4*2*sizeof(int16_t));

                memset(&h->ref_cache[m][scan8[0] - 1*8], (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]] == -1) ? PART_NOT_AVAILABLE : 1, 4);

                if (s->mb_x < (s->mb_width - 1)) {

                    *(uint32_t *) h->mv_cache[m][scan8[0] + 4 - 1*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - h->b_stride + 4];

                    h->ref_cache[m][scan8[0] + 4 - 1*8] =

                        (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride + 1]+6] == -1 ||

                         h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride    ]  ] == -1) ? PART_NOT_AVAILABLE : 1;

                }else

                    h->ref_cache[m][scan8[0] + 4 - 1*8] = PART_NOT_AVAILABLE;

                if (s->mb_x > 0) {

                    *(uint32_t *) h->mv_cache[m][scan8[0] - 1 - 1*8] = *(uint32_t *) s->current_picture.f.motion_val[m][b_xy - h->b_stride - 1];

                    h->ref_cache[m][scan8[0] - 1 - 1*8] = (h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1]+3] == -1) ? PART_NOT_AVAILABLE : 1;

                }else

                    h->ref_cache[m][scan8[0] - 1 - 1*8] = PART_NOT_AVAILABLE;

            }else

                memset(&h->ref_cache[m][scan8[0] - 1*8 - 1], PART_NOT_AVAILABLE, 8);

            if (s->pict_type != AV_PICTURE_TYPE_B)

                break;

        }

        /* decode motion vector(s) and form prediction(s) */

        if (s->pict_type == AV_PICTURE_TYPE_P) {

            if (svq3_mc_dir(h, (mb_type - 1), mode, 0, 0) < 0)

                return -1;

        } else {        /* AV_PICTURE_TYPE_B */

            if (mb_type != 2) {

                if (svq3_mc_dir(h, 0, mode, 0, 0) < 0)

                    return -1;

            } else {

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

                    memset(s->current_picture.f.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

                }

            }

            if (mb_type != 1) {

                if (svq3_mc_dir(h, 0, mode, 1, (mb_type == 3)) < 0)

                    return -1;

            } else {

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

                    memset(s->current_picture.f.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

                }

            }

        }

        mb_type = MB_TYPE_16x16;

    } else if (mb_type == 8 || mb_type == 33) {   /* INTRA4x4 */

        memset(h->intra4x4_pred_mode_cache, -1, 8*5*sizeof(int8_t));

        if (mb_type == 8) {

            if (s->mb_x > 0) {

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

                    h->intra4x4_pred_mode_cache[scan8[0] - 1 + i*8] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - 1]+6-i];

                }

                if (h->intra4x4_pred_mode_cache[scan8[0] - 1] == -1) {

                    h->left_samples_available = 0x5F5F;

                }

            }

            if (s->mb_y > 0) {

                h->intra4x4_pred_mode_cache[4+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+0];

                h->intra4x4_pred_mode_cache[5+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+1];

                h->intra4x4_pred_mode_cache[6+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+2];

                h->intra4x4_pred_mode_cache[7+8*0] = h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride]+3];

                if (h->intra4x4_pred_mode_cache[4+8*0] == -1) {

                    h->top_samples_available = 0x33FF;

                }

            }

            /* decode prediction codes for luma blocks */

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

                vlc = svq3_get_ue_golomb(&s->gb);

                if (vlc >= 25){

                    av_log(h->s.avctx, AV_LOG_ERROR, "luma prediction:%d\n", vlc);

                    return -1;

                }

                left    = &h->intra4x4_pred_mode_cache[scan8[i] - 1];

                top     = &h->intra4x4_pred_mode_cache[scan8[i] - 8];

                left[1] = svq3_pred_1[top[0] + 1][left[0] + 1][svq3_pred_0[vlc][0]];

                left[2] = svq3_pred_1[top[1] + 1][left[1] + 1][svq3_pred_0[vlc][1]];

                if (left[1] == -1 || left[2] == -1){

                    av_log(h->s.avctx, AV_LOG_ERROR, "weird prediction\n");

                    return -1;

                }

            }

        } else {    /* mb_type == 33, DC_128_PRED block type */

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

                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_PRED, 4);

            }

        }

        write_back_intra_pred_mode(h);

        if (mb_type == 8) {

            ff_h264_check_intra4x4_pred_mode(h);

            h->top_samples_available  = (s->mb_y == 0) ? 0x33FF : 0xFFFF;

            h->left_samples_available = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

        } else {

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

                memset(&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_128_PRED, 4);

            }

            h->top_samples_available  = 0x33FF;

            h->left_samples_available = 0x5F5F;

        }

        mb_type = MB_TYPE_INTRA4x4;

    } else {                      /* INTRA16x16 */

        dir = i_mb_type_info[mb_type - 8].pred_mode;

        dir = (dir >> 1) ^ 3*(dir & 1) ^ 1;

        if ((h->intra16x16_pred_mode = ff_h264_check_intra_pred_mode(h, dir)) == -1){

            av_log(h->s.avctx, AV_LOG_ERROR, "check_intra_pred_mode = -1\n");

            return -1;

        }

        cbp = i_mb_type_info[mb_type - 8].cbp;

        mb_type = MB_TYPE_INTRA16x16;

    }

    if (!IS_INTER(mb_type) && s->pict_type != AV_PICTURE_TYPE_I) {

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

            memset(s->current_picture.f.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

        }

        if (s->pict_type == AV_PICTURE_TYPE_B) {

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

                memset(s->current_picture.f.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

            }

        }

    }

    if (!IS_INTRA4x4(mb_type)) {

        memset(h->intra4x4_pred_mode+h->mb2br_xy[mb_xy], DC_PRED, 8);

    }

    if (!IS_SKIP(mb_type) || s->pict_type == AV_PICTURE_TYPE_B) {

        memset(h->non_zero_count_cache + 8, 0, 14*8*sizeof(uint8_t));

        s->dsp.clear_blocks(h->mb+  0);

        s->dsp.clear_blocks(h->mb+384);

    }

    if (!IS_INTRA16x16(mb_type) && (!IS_SKIP(mb_type) || s->pict_type == AV_PICTURE_TYPE_B)) {

        if ((vlc = svq3_get_ue_golomb(&s->gb)) >= 48){

            av_log(h->s.avctx, AV_LOG_ERROR, "cbp_vlc=%d\n", vlc);

            return -1;

        }

        cbp = IS_INTRA(mb_type) ? golomb_to_intra4x4_cbp[vlc] : golomb_to_inter_cbp[vlc];

    }

    if (IS_INTRA16x16(mb_type) || (s->pict_type != AV_PICTURE_TYPE_I && s->adaptive_quant && cbp)) {

        s->qscale += svq3_get_se_golomb(&s->gb);

        if (s->qscale > 31){

            av_log(h->s.avctx, AV_LOG_ERROR, "qscale:%d\n", s->qscale);

            return -1;

        }

    }

    if (IS_INTRA16x16(mb_type)) {

        AV_ZERO128(h->mb_luma_dc[0]+0);

        AV_ZERO128(h->mb_luma_dc[0]+8);

        if (svq3_decode_block(&s->gb, h->mb_luma_dc, 0, 1)){

            av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding intra luma dc\n");

            return -1;

        }

    }

    if (cbp) {

        const int index = IS_INTRA16x16(mb_type) ? 1 : 0;

        const int type = ((s->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);

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

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

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

                    k = index ? ((j&1) + 2*(i&1) + 2*(j&2) + 4*(i&2)) : (4*i + j);

                    h->non_zero_count_cache[ scan8[k] ] = 1;

                    if (svq3_decode_block(&s->gb, &h->mb[16*k], index, type)){

                        av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding block\n");

                        return -1;

                    }

                }

            }

        }

        if ((cbp & 0x30)) {

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

              if (svq3_decode_block(&s->gb, &h->mb[16*16*i], 0, 3)){

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma dc block\n");

                return -1;

              }

            }

            if ((cbp & 0x20)) {

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

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

                        k = 16*i + j;

                        h->non_zero_count_cache[ scan8[k] ] = 1;

                        if (svq3_decode_block(&s->gb, &h->mb[16*k], 1, 1)){

                            av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding chroma ac block\n");

                            return -1;

                        }

                    }

                }

            }

        }

    }

    h->cbp= cbp;

    s->current_picture.f.mb_type[mb_xy] = mb_type;

    if (IS_INTRA(mb_type)) {

        h->chroma_pred_mode = ff_h264_check_intra_pred_mode(h, DC_PRED8x8);

    }

    return 0;

}


static void kvm_cpu_fill_host(x86_def_t *x86_cpu_def)

{

#ifdef CONFIG_KVM

    KVMState *s = kvm_state;

    uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;

    assert(kvm_enabled());

    x86_cpu_def->name = "host";

    host_cpuid(0x0, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_vendor_words2str(x86_cpu_def->vendor, ebx, edx, ecx);

    host_cpuid(0x1, 0, &eax, &ebx, &ecx, &edx);

    x86_cpu_def->family = ((eax >> 8) & 0x0F) + ((eax >> 20) & 0xFF);

    x86_cpu_def->model = ((eax >> 4) & 0x0F) | ((eax & 0xF0000) >> 12);

    x86_cpu_def->stepping = eax & 0x0F;

    x86_cpu_def->level = kvm_arch_get_supported_cpuid(s, 0x0, 0, R_EAX);

    x86_cpu_def->features[FEAT_1_EDX] =

        kvm_arch_get_supported_cpuid(s, 0x1, 0, R_EDX);

    x86_cpu_def->features[FEAT_1_ECX] =

        kvm_arch_get_supported_cpuid(s, 0x1, 0, R_ECX);

    if (x86_cpu_def->level >= 7) {

        x86_cpu_def->features[FEAT_7_0_EBX] =

                    kvm_arch_get_supported_cpuid(s, 0x7, 0, R_EBX);

    } else {

        x86_cpu_def->features[FEAT_7_0_EBX] = 0;

    }

    x86_cpu_def->xlevel = kvm_arch_get_supported_cpuid(s, 0x80000000, 0, R_EAX);

    x86_cpu_def->features[FEAT_8000_0001_EDX] =

                kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_EDX);

    x86_cpu_def->features[FEAT_8000_0001_ECX] =

                kvm_arch_get_supported_cpuid(s, 0x80000001, 0, R_ECX);

    cpu_x86_fill_model_id(x86_cpu_def->model_id);

    /* Call Centaur's CPUID instruction. */

    if (!strcmp(x86_cpu_def->vendor, CPUID_VENDOR_VIA)) {

        host_cpuid(0xC0000000, 0, &eax, &ebx, &ecx, &edx);

        eax = kvm_arch_get_supported_cpuid(s, 0xC0000000, 0, R_EAX);

        if (eax >= 0xC0000001) {

            /* Support VIA max extended level */

            x86_cpu_def->xlevel2 = eax;

            host_cpuid(0xC0000001, 0, &eax, &ebx, &ecx, &edx);

            x86_cpu_def->features[FEAT_C000_0001_EDX] =

                    kvm_arch_get_supported_cpuid(s, 0xC0000001, 0, R_EDX);

        }

    }

    /* Other KVM-specific feature fields: */

    x86_cpu_def->features[FEAT_SVM] =

        kvm_arch_get_supported_cpuid(s, 0x8000000A, 0, R_EDX);

    x86_cpu_def->features[FEAT_KVM] =

        kvm_arch_get_supported_cpuid(s, KVM_CPUID_FEATURES, 0, R_EAX);

#endif /* CONFIG_KVM */

}


static void test_validate_fail_struct(TestInputVisitorData *data,

                                       const void *unused)

{

    TestStruct *p = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo', 'extra': 42 }");

    visit_type_TestStruct(v, &p, NULL, &err);

    g_assert(err);

    error_free(err);

    if (p) {

        g_free(p->string);

    }

    g_free(p);

}


static int dv_read_header(AVFormatContext *s,

                          AVFormatParameters *ap)

{

    unsigned state;

    RawDVContext *c = s->priv_data;

    c->dv_demux = dv_init_demux(s);

    if (!c->dv_demux)

        return -1;

    state = get_be32(s->pb);

    while ((state & 0xffffff7f) != 0x1f07003f) {

        if (url_feof(s->pb)) {

            av_log(s, AV_LOG_ERROR, "Cannot find DV header.\n");

            return -1;

        }

        state = (state << 8) | get_byte(s->pb);

    }

    AV_WB32(c->buf, state);

    if (get_buffer(s->pb, c->buf + 4, DV_PROFILE_BYTES - 4) <= 0 ||

        url_fseek(s->pb, -DV_PROFILE_BYTES, SEEK_CUR) < 0)

        return AVERROR(EIO);

    c->dv_demux->sys = dv_frame_profile(c->buf);

    if (!c->dv_demux->sys) {

        av_log(s, AV_LOG_ERROR, "Can't determine profile of DV input stream.\n");

        return -1;

    }

    s->bit_rate = av_rescale_q(c->dv_demux->sys->frame_size, (AVRational){8,1},

                               c->dv_demux->sys->time_base);

    return 0;

}


int ff_mjpeg_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    int start_code;

    AVFrame *picture = data;

    s->got_picture = 0; // picture from previous image can not be reused

    buf_ptr = buf;

    buf_end = buf + buf_size;

    while (buf_ptr < buf_end) {

        /* find start next marker */

        start_code = find_marker(&buf_ptr, buf_end);

        {

            /* EOF */

            if (start_code < 0) {

                goto the_end;

            } else {

                av_log(avctx, AV_LOG_DEBUG, "marker=%x avail_size_in_buf=%td\n", start_code, buf_end - buf_ptr);

                if ((buf_end - buf_ptr) > s->buffer_size)

                {

                    av_free(s->buffer);

                    s->buffer_size = buf_end-buf_ptr;

                    s->buffer = av_malloc(s->buffer_size + FF_INPUT_BUFFER_PADDING_SIZE);

                    av_log(avctx, AV_LOG_DEBUG, "buffer too small, expanding to %d bytes\n",

                        s->buffer_size);

                /* unescape buffer of SOS, use special treatment for JPEG-LS */

                if (start_code == SOS && !s->ls)

                {

                    const uint8_t *src = buf_ptr;

                    uint8_t *dst = s->buffer;

                    while (src<buf_end)

                    {

                        uint8_t x = *(src++);

                        *(dst++) = x;

                        if (avctx->codec_id != CODEC_ID_THP)

                        {

                            if (x == 0xff) {

                                while (src < buf_end && x == 0xff)

                                    x = *(src++);

                                if (x >= 0xd0 && x <= 0xd7)

                                    *(dst++) = x;

                                else if (x)

                    init_get_bits(&s->gb, s->buffer, (dst - s->buffer)*8);

                    av_log(avctx, AV_LOG_DEBUG, "escaping removed %td bytes\n",

                           (buf_end - buf_ptr) - (dst - s->buffer));

                else if(start_code == SOS && s->ls){

                    const uint8_t *src = buf_ptr;

                    uint8_t *dst = s->buffer;

                    int bit_count = 0;

                    int t = 0, b = 0;

                    PutBitContext pb;

                    s->cur_scan++;

                    /* find marker */

                    while (src + t < buf_end){

                        uint8_t x = src[t++];

                        if (x == 0xff){

                            while((src + t < buf_end) && x == 0xff)

                                x = src[t++];

                            if (x & 0x80) {

                                t -= 2;

                    bit_count = t * 8;

                    init_put_bits(&pb, dst, t);

                    /* unescape bitstream */

                    while(b < t){

                        uint8_t x = src[b++];

                        put_bits(&pb, 8, x);

                        if(x == 0xFF){

                            x = src[b++];

                            put_bits(&pb, 7, x);

                            bit_count--;

                    flush_put_bits(&pb);

                    init_get_bits(&s->gb, dst, bit_count);

                else

                    init_get_bits(&s->gb, buf_ptr, (buf_end - buf_ptr)*8);

                s->start_code = start_code;

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

                    av_log(avctx, AV_LOG_DEBUG, "startcode: %X\n", start_code);

                /* process markers */

                if (start_code >= 0xd0 && start_code <= 0xd7) {

                    av_log(avctx, AV_LOG_DEBUG, "restart marker: %d\n", start_code&0x0f);

                    /* APP fields */

                } else if (start_code >= APP0 && start_code <= APP15) {

                    mjpeg_decode_app(s);

                    /* Comment */

                } else if (start_code == COM){

                    mjpeg_decode_com(s);

                switch(start_code) {

                case SOI:

                    s->restart_interval = 0;

                    s->restart_count = 0;

                    /* nothing to do on SOI */

                case DQT:

                    ff_mjpeg_decode_dqt(s);

                case DHT:

                    if(ff_mjpeg_decode_dht(s) < 0){

                        av_log(avctx, AV_LOG_ERROR, "huffman table decode error\n");

                        return -1;

                case SOF0:

                    s->lossless=0;

                    s->ls=0;

                    s->progressive=0;

                    if (ff_mjpeg_decode_sof(s) < 0)

                        return -1;

                case SOF2:

                    s->lossless=0;

                    s->ls=0;

                    s->progressive=1;

                    if (ff_mjpeg_decode_sof(s) < 0)

                        return -1;

                case SOF3:

                    s->lossless=1;

                    s->ls=0;

                    s->progressive=0;

                    if (ff_mjpeg_decode_sof(s) < 0)

                        return -1;

                case SOF48:

                    s->lossless=1;

                    s->ls=1;

                    s->progressive=0;

                    if (ff_mjpeg_decode_sof(s) < 0)

                        return -1;

                case LSE:

                    if (!CONFIG_JPEGLS_DECODER || ff_jpegls_decode_lse(s) < 0)

                        return -1;

                case EOI:

                    s->cur_scan = 0;

                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)

eoi_parser:

                        av_log(avctx, AV_LOG_WARNING, "Found EOI before any SOF, ignoring\n");

                    {

                        if (s->interlaced) {

                            s->bottom_field ^= 1;

                            /* if not bottom field, do not output image yet */

                            if (s->bottom_field == !s->interlace_polarity)

                                goto not_the_end;

                        *picture = s->picture;

                        *data_size = sizeof(AVFrame);

                        if(!s->lossless){

                            picture->quality= FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]);

                            picture->qstride= 0;

                            picture->qscale_table= s->qscale_table;

                            memset(picture->qscale_table, picture->quality, (s->width+15)/16);

                            if(avctx->debug & FF_DEBUG_QP)

                                av_log(avctx, AV_LOG_DEBUG, "QP: %d\n", picture->quality);

                            picture->quality*= FF_QP2LAMBDA;

                        goto the_end;

                case SOS:

                    ff_mjpeg_decode_sos(s);

                    /* buggy avid puts EOI every 10-20th frame */

                    /* if restart period is over process EOI */

                    if ((s->buggy_avid && !s->interlaced) || s->restart_interval)

                        goto eoi_parser;

                case DRI:

                    mjpeg_decode_dri(s);

                case SOF1:

                case SOF5:

                case SOF6:

                case SOF7:

                case SOF9:

                case SOF10:

                case SOF11:

                case SOF13:

                case SOF14:

                case SOF15:

                case JPG:

                    av_log(avctx, AV_LOG_ERROR, "mjpeg: unsupported coding type (%x)\n", start_code);

//                default:

//                    printf("mjpeg: unsupported marker (%x)\n", start_code);

//                    break;

not_the_end:

                /* eof process start code */

                buf_ptr += (get_bits_count(&s->gb)+7)/8;

                av_log(avctx, AV_LOG_DEBUG, "marker parser used %d bytes (%d bits)\n",

                       (get_bits_count(&s->gb)+7)/8, get_bits_count(&s->gb));

the_end:

    av_log(avctx, AV_LOG_DEBUG, "mjpeg decode frame unused %td bytes\n", buf_end - buf_ptr);

//    return buf_end - buf_ptr;

    return buf_ptr - buf;


static int raw_write(BlockDriverState *bs, int64_t sector_num,

                     const uint8_t *buf, int nb_sectors)

{

    if (check_write_unsafe(bs, sector_num, buf, nb_sectors)) {

        int ret;

        ret = raw_write_scrubbed_bootsect(bs, buf);

        if (ret < 0) {

            return ret;

        }

        ret = bdrv_write(bs->file, 1, buf + 512, nb_sectors - 1);

        if (ret < 0) {

            return ret;

        }

        return ret + 512;

    }

    return bdrv_write(bs->file, sector_num, buf, nb_sectors);

}


void av_read_image_line(uint16_t *dst, const uint8_t *data[4], const int linesize[4],

                        const AVPixFmtDescriptor *desc, int x, int y, int c, int w, int read_pal_component)

{

    AVComponentDescriptor comp= desc->comp[c];

    int plane= comp.plane;

    int depth= comp.depth_minus1+1;

    int mask = (1<<depth)-1;

    int shift= comp.shift;

    int step = comp.step_minus1+1;

    int flags= desc->flags;

    if (flags & PIX_FMT_BITSTREAM){

        int skip = x*step + comp.offset_plus1-1;

        const uint8_t *p = data[plane] + y*linesize[plane] + (skip>>3);

        int shift = 8 - depth - (skip&7);

        while(w--){

            int val = (*p >> shift) & mask;

            if(read_pal_component)

                val= data[1][4*val + c];

            shift -= step;

            p -= shift>>3;

            shift &= 7;

            *dst++= val;

        }

    } else {

        const uint8_t *p = data[plane]+ y*linesize[plane] + x*step + comp.offset_plus1-1;

        while(w--){

            int val = flags & PIX_FMT_BE ? AV_RB16(p) : AV_RL16(p);

            val = (val>>shift) & mask;

            if(read_pal_component)

                val= data[1][4*val + c];

            p+= step;

            *dst++= val;

        }

    }

}


void set_system_io_map(MemoryRegion *mr)

{

    memory_region_transaction_begin();

    address_space_io.root = mr;

    memory_region_transaction_commit();

}


int attribute_align_arg av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)

{

    BufferSinkContext *buf = ctx->priv;

    AVFilterLink *inlink = ctx->inputs[0];

    int ret;

    AVFrame *cur_frame;

    /* no picref available, fetch it from the filterchain */

    if (!av_fifo_size(buf->fifo)) {

        if (inlink->closed)

            return AVERROR_EOF;

        if (flags & AV_BUFFERSINK_FLAG_NO_REQUEST)

            return AVERROR(EAGAIN);

        if ((ret = ff_request_frame(inlink)) < 0)

            return ret;

    }

    if (!av_fifo_size(buf->fifo))

        return AVERROR(EINVAL);

    if (flags & AV_BUFFERSINK_FLAG_PEEK) {

        cur_frame = *((AVFrame **)av_fifo_peek2(buf->fifo, 0));

        if ((ret = av_frame_ref(frame, cur_frame)) < 0)

            return ret;

    } else {

        av_fifo_generic_read(buf->fifo, &cur_frame, sizeof(cur_frame), NULL);

        av_frame_move_ref(frame, cur_frame);

        av_frame_free(&cur_frame);

    }

    return 0;

}


static float wv_get_value_float(WavpackFrameContext *s, uint32_t *crc, int S)

{

    union {

        float    f;

        uint32_t u;

    } value;

    int sign;

    int exp = s->float_max_exp;

    if (s->got_extra_bits) {

        const int max_bits  = 1 + 23 + 8 + 1;

        const int left_bits = get_bits_left(&s->gb_extra_bits);

        if (left_bits + 8 * FF_INPUT_BUFFER_PADDING_SIZE < max_bits)

            return 0.0;

    }

    if (S) {

        S <<= s->float_shift;

        sign = S < 0;

        if (sign)

            S = -S;

        if (S >= 0x1000000) {

            if (s->got_extra_bits && get_bits1(&s->gb_extra_bits))

                S = get_bits(&s->gb_extra_bits, 23);

            else

                S = 0;

            exp = 255;

        } else if (exp) {

            int shift = 23 - av_log2(S);

            exp = s->float_max_exp;

            if (exp <= shift)

                shift = --exp;

            exp -= shift;

            if (shift) {

                S <<= shift;

                if ((s->float_flag & WV_FLT_SHIFT_ONES) ||

                    (s->got_extra_bits && (s->float_flag & WV_FLT_SHIFT_SAME) &&

                     get_bits1(&s->gb_extra_bits))) {

                    S |= (1 << shift) - 1;

                } else if (s->got_extra_bits &&

                           (s->float_flag & WV_FLT_SHIFT_SENT)) {

                    S |= get_bits(&s->gb_extra_bits, shift);

                }

            }

        } else {

            exp = s->float_max_exp;

        }

        S &= 0x7fffff;

    } else {

        sign = 0;

        exp = 0;

        if (s->got_extra_bits && (s->float_flag & WV_FLT_ZERO_SENT)) {

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

                S = get_bits(&s->gb_extra_bits, 23);

                if (s->float_max_exp >= 25)

                    exp = get_bits(&s->gb_extra_bits, 8);

                sign = get_bits1(&s->gb_extra_bits);

            } else {

                if (s->float_flag & WV_FLT_ZERO_SIGN)

                    sign = get_bits1(&s->gb_extra_bits);

            }

        }

    }

    *crc = *crc * 27 + S * 9 + exp * 3 + sign;

    value.u = (sign << 31) | (exp << 23) | S;

    return value.f;

}


static gboolean ga_channel_open(GAChannel *c, const gchar *path, GAChannelMethod method)

{

    int ret;

    c->method = method;

    switch (c->method) {

    case GA_CHANNEL_VIRTIO_SERIAL: {

        int fd = qemu_open(path, O_RDWR | O_NONBLOCK

#ifndef CONFIG_SOLARIS

                           | O_ASYNC

#endif

                           );

        if (fd == -1) {

            g_critical("error opening channel: %s", strerror(errno));

            exit(EXIT_FAILURE);

        }

#ifdef CONFIG_SOLARIS

        ret = ioctl(fd, I_SETSIG, S_OUTPUT | S_INPUT | S_HIPRI);

        if (ret == -1) {

            g_critical("error setting event mask for channel: %s",

                       strerror(errno));

            exit(EXIT_FAILURE);

        }

#endif

        ret = ga_channel_client_add(c, fd);

        if (ret) {

            g_critical("error adding channel to main loop");

            return false;

        }

        break;

    }

    case GA_CHANNEL_ISA_SERIAL: {

        struct termios tio;

        int fd = qemu_open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);

        if (fd == -1) {

            g_critical("error opening channel: %s", strerror(errno));

            exit(EXIT_FAILURE);

        }

        tcgetattr(fd, &tio);

        /* set up serial port for non-canonical, dumb byte streaming */

        tio.c_iflag &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |

                         INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY |

                         IMAXBEL);

        tio.c_oflag = 0;

        tio.c_lflag = 0;

        tio.c_cflag |= GA_CHANNEL_BAUDRATE_DEFAULT;

        /* 1 available byte min or reads will block (we'll set non-blocking

         * elsewhere, else we have to deal with read()=0 instead)

         */

        tio.c_cc[VMIN] = 1;

        tio.c_cc[VTIME] = 0;

        /* flush everything waiting for read/xmit, it's garbage at this point */

        tcflush(fd, TCIFLUSH);

        tcsetattr(fd, TCSANOW, &tio);

        ret = ga_channel_client_add(c, fd);

        if (ret) {

            g_error("error adding channel to main loop");

        }

        break;

    }

    case GA_CHANNEL_UNIX_LISTEN: {

        Error *local_err = NULL;

        int fd = unix_listen(path, NULL, strlen(path), &local_err);

        if (local_err != NULL) {

            g_critical("%s", error_get_pretty(local_err));

            error_free(local_err);

            return false;

        }

        ga_channel_listen_add(c, fd, true);

        break;

    }

    default:

        g_critical("error binding/listening to specified socket");

        return false;

    }

    return true;

}


static void init_qxl_rom(PCIQXLDevice *d)

{

    QXLRom *rom = memory_region_get_ram_ptr(&d->rom_bar);

    QXLModes *modes = (QXLModes *)(rom + 1);

    uint32_t ram_header_size;

    uint32_t surface0_area_size;

    uint32_t num_pages;

    uint32_t fb, maxfb = 0;

    int i;

    memset(rom, 0, d->rom_size);

    rom->magic         = cpu_to_le32(QXL_ROM_MAGIC);

    rom->id            = cpu_to_le32(d->id);

    rom->log_level     = cpu_to_le32(d->guestdebug);

    rom->modes_offset  = cpu_to_le32(sizeof(QXLRom));

    rom->slot_gen_bits = MEMSLOT_GENERATION_BITS;

    rom->slot_id_bits  = MEMSLOT_SLOT_BITS;

    rom->slots_start   = 1;

    rom->slots_end     = NUM_MEMSLOTS - 1;

    rom->n_surfaces    = cpu_to_le32(NUM_SURFACES);

    modes->n_modes     = cpu_to_le32(ARRAY_SIZE(qxl_modes));

    for (i = 0; i < modes->n_modes; i++) {

        fb = qxl_modes[i].y_res * qxl_modes[i].stride;

        if (maxfb < fb) {

            maxfb = fb;

        }

        modes->modes[i].id          = cpu_to_le32(i);

        modes->modes[i].x_res       = cpu_to_le32(qxl_modes[i].x_res);

        modes->modes[i].y_res       = cpu_to_le32(qxl_modes[i].y_res);

        modes->modes[i].bits        = cpu_to_le32(qxl_modes[i].bits);

        modes->modes[i].stride      = cpu_to_le32(qxl_modes[i].stride);

        modes->modes[i].x_mili      = cpu_to_le32(qxl_modes[i].x_mili);

        modes->modes[i].y_mili      = cpu_to_le32(qxl_modes[i].y_mili);

        modes->modes[i].orientation = cpu_to_le32(qxl_modes[i].orientation);

    }

    if (maxfb < VGA_RAM_SIZE && d->id == 0)

        maxfb = VGA_RAM_SIZE;

    ram_header_size    = ALIGN(sizeof(QXLRam), 4096);

    surface0_area_size = ALIGN(maxfb, 4096);

    num_pages          = d->vga.vram_size;

    num_pages         -= ram_header_size;

    num_pages         -= surface0_area_size;

    num_pages          = num_pages / TARGET_PAGE_SIZE;

    rom->draw_area_offset   = cpu_to_le32(0);

    rom->surface0_area_size = cpu_to_le32(surface0_area_size);

    rom->pages_offset       = cpu_to_le32(surface0_area_size);

    rom->num_pages          = cpu_to_le32(num_pages);

    rom->ram_header_offset  = cpu_to_le32(d->vga.vram_size - ram_header_size);

    d->shadow_rom = *rom;

    d->rom        = rom;

    d->modes      = modes;

}


 roundAndPackFloat128(

     flag zSign, int32 zExp, uint64_t zSig0, uint64_t zSig1, uint64_t zSig2 STATUS_PARAM)

{

    int8 roundingMode;

    flag roundNearestEven, increment, isTiny;

    roundingMode = STATUS(float_rounding_mode);

    roundNearestEven = ( roundingMode == float_round_nearest_even );

    increment = ( (int64_t) zSig2 < 0 );

    if ( ! roundNearestEven ) {

        if ( roundingMode == float_round_to_zero ) {

            increment = 0;

        }

        else {

            if ( zSign ) {

                increment = ( roundingMode == float_round_down ) && zSig2;

            }

            else {

                increment = ( roundingMode == float_round_up ) && zSig2;

            }

        }

    }

    if ( 0x7FFD <= (uint32_t) zExp ) {

        if (    ( 0x7FFD < zExp )

             || (    ( zExp == 0x7FFD )

                  && eq128(

                         LIT64( 0x0001FFFFFFFFFFFF ),

                         LIT64( 0xFFFFFFFFFFFFFFFF ),

                         zSig0,

                         zSig1

                     )

                  && increment

                )

           ) {

            float_raise( float_flag_overflow | float_flag_inexact STATUS_VAR);

            if (    ( roundingMode == float_round_to_zero )

                 || ( zSign && ( roundingMode == float_round_up ) )

                 || ( ! zSign && ( roundingMode == float_round_down ) )

               ) {

                return

                    packFloat128(

                        zSign,

                        0x7FFE,

                        LIT64( 0x0000FFFFFFFFFFFF ),

                        LIT64( 0xFFFFFFFFFFFFFFFF )

                    );

            }

            return packFloat128( zSign, 0x7FFF, 0, 0 );

        }

        if ( zExp < 0 ) {

            if ( STATUS(flush_to_zero) ) return packFloat128( zSign, 0, 0, 0 );

            isTiny =

                   ( STATUS(float_detect_tininess) == float_tininess_before_rounding )

                || ( zExp < -1 )

                || ! increment

                || lt128(

                       zSig0,

                       zSig1,

                       LIT64( 0x0001FFFFFFFFFFFF ),

                       LIT64( 0xFFFFFFFFFFFFFFFF )

                   );

            shift128ExtraRightJamming(

                zSig0, zSig1, zSig2, - zExp, &zSig0, &zSig1, &zSig2 );

            zExp = 0;

            if ( isTiny && zSig2 ) float_raise( float_flag_underflow STATUS_VAR);

            if ( roundNearestEven ) {

                increment = ( (int64_t) zSig2 < 0 );

            }

            else {

                if ( zSign ) {

                    increment = ( roundingMode == float_round_down ) && zSig2;

                }

                else {

                    increment = ( roundingMode == float_round_up ) && zSig2;

                }

            }

        }

    }

    if ( zSig2 ) STATUS(float_exception_flags) |= float_flag_inexact;

    if ( increment ) {

        add128( zSig0, zSig1, 0, 1, &zSig0, &zSig1 );

        zSig1 &= ~ ( ( zSig2 + zSig2 == 0 ) & roundNearestEven );

    }

    else {

        if ( ( zSig0 | zSig1 ) == 0 ) zExp = 0;

    }

    return packFloat128( zSign, zExp, zSig0, zSig1 );

}


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

	uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

	unsigned int width, unsigned int height, int lumStride, int chromStride)

{

	/* Y Plane */

	memcpy(ydst, ysrc, width*height);

	/* XXX: implement upscaling for U,V */

}


int ff_msmpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded, const uint8_t *scan_table)

{

    int level, i, last, run, run_diff;

    int dc_pred_dir;

    RLTable *rl;

    RL_VLC_ELEM *rl_vlc;

    int qmul, qadd;

    if (s->mb_intra) {

        qmul=1;

        qadd=0;

        /* DC coef */

        level = msmpeg4_decode_dc(s, n, &dc_pred_dir);

        if (level < 0){

            av_log(s->avctx, AV_LOG_ERROR, "dc overflow- block: %d qscale: %d//\n", n, s->qscale);

            if(s->inter_intra_pred) level=0;

            else                    return -1;

        }

        if (n < 4) {

            rl = &rl_table[s->rl_table_index];

            if(level > 256*s->y_dc_scale){

                av_log(s->avctx, AV_LOG_ERROR, "dc overflow+ L qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        } else {

            rl = &rl_table[3 + s->rl_chroma_table_index];

            if(level > 256*s->c_dc_scale){

                av_log(s->avctx, AV_LOG_ERROR, "dc overflow+ C qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        }

        block[0] = level;

        run_diff = s->msmpeg4_version >= 4;

        i = 0;

        if (!coded) {

            goto not_coded;

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        rl_vlc= rl->rl_vlc[0];

    } else {

        qmul = s->qscale << 1;

        qadd = (s->qscale - 1) | 1;

        i = -1;

        rl = &rl_table[3 + s->rl_table_index];

        if(s->msmpeg4_version==2)

            run_diff = 0;

        else

            run_diff = 1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        if(!scan_table)

            scan_table = s->inter_scantable.permutated;

        rl_vlc= rl->rl_vlc[s->qscale];

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);

        if (level==0) {

            int cache;

            cache= GET_CACHE(re, &s->gb);

            /* escape */

            if (s->msmpeg4_version==1 || (cache&0x80000000)==0) {

                if (s->msmpeg4_version==1 || (cache&0x40000000)==0) {

                    /* third escape */

                    if(s->msmpeg4_version!=1) LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

                    if(s->msmpeg4_version<=3){

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                        run=   SHOW_UBITS(re, &s->gb, 6); SKIP_CACHE(re, &s->gb, 6);

                        level= SHOW_SBITS(re, &s->gb, 8); LAST_SKIP_CACHE(re, &s->gb, 8);

                        SKIP_COUNTER(re, &s->gb, 1+6+8);

                    }else{

                        int sign;

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_BITS(re, &s->gb, 1);

                        if(!s->esc3_level_length){

                            int ll;

                            //printf("ESC-3 %X at %d %d\n", show_bits(&s->gb, 24), s->mb_x, s->mb_y);

                            if(s->qscale<8){

                                ll= SHOW_UBITS(re, &s->gb, 3); SKIP_BITS(re, &s->gb, 3);

                                if(ll==0){

                                    if(SHOW_UBITS(re, &s->gb, 1)) av_log(s->avctx, AV_LOG_ERROR, "cool a new vlc code ,contact the ffmpeg developers and upload the file\n");

                                    SKIP_BITS(re, &s->gb, 1);

                                    ll=8;

                                }

                            }else{

                                ll=2;

                                while(ll<8 && SHOW_UBITS(re, &s->gb, 1)==0){

                                    ll++;

                                    SKIP_BITS(re, &s->gb, 1);

                                }

                                if(ll<8) SKIP_BITS(re, &s->gb, 1);

                            }

                            s->esc3_level_length= ll;

                            s->esc3_run_length= SHOW_UBITS(re, &s->gb, 2) + 3; SKIP_BITS(re, &s->gb, 2);

//printf("level length:%d, run length: %d\n", ll, s->esc3_run_length);

                            UPDATE_CACHE(re, &s->gb);

                        }

                        run=   SHOW_UBITS(re, &s->gb, s->esc3_run_length);

                        SKIP_BITS(re, &s->gb, s->esc3_run_length);

                        sign=  SHOW_UBITS(re, &s->gb, 1);

                        SKIP_BITS(re, &s->gb, 1);

                        level= SHOW_UBITS(re, &s->gb, s->esc3_level_length);

                        SKIP_BITS(re, &s->gb, s->esc3_level_length);

                        if(sign) level= -level;

                    }

//printf("level: %d, run: %d at %d %d\n", level, run, s->mb_x, s->mb_y);

#if 0 // waste of time / this will detect very few errors

                    {

                        const int abs_level= FFABS(level);

                        const int run1= run - rl->max_run[last][abs_level] - run_diff;

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            if(abs_level <= rl->max_level[last][run]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(abs_level <= rl->max_level[last][run]*2){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(run1>=0 && abs_level <= rl->max_level[last][run1]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                        }

                    }

#endif

                    //level = level * qmul + (level>0) * qadd - (level<=0) * qadd ;

                    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

#if 0 // waste of time too :(

                    if(level>2048 || level<-2048){

                        av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc\n");

                        return DECODING_AC_LOST;

                    }

#endif

                    i+= run + 1;

                    if(last) i+=192;

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC3 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC3 i=%d run=%d level=%d\n", i, run, level);

#endif

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 23

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                    i+= run + rl->max_run[run>>7][level/qmul] + run_diff; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC2 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC2 i=%d run=%d level=%d\n", i, run, level);

#endif

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 22

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC1 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC1 i=%d run=%d level=%d\n", i, run, level);

#endif

            }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow i=%d run=%d level=%d\n", i, run, level);

#endif

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                const int left= s->gb.size_in_bits - get_bits_count(&s->gb);

                if(((i+192 == 64 && level/qmul==-1) || s->error_recognition<=1) && left>=0){

                    av_log(s->avctx, AV_LOG_ERROR, "ignoring overflow at %d %d\n", s->mb_x, s->mb_y);

                    break;

                }else{

                    av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                    return -1;

                }

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (s->mb_intra) {

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    if(s->msmpeg4_version>=4 && i>0) i=63; //FIXME/XXX optimize

    s->block_last_index[n] = i;

    return 0;

}


static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,

                                AVSubtitleRect *r)

{

    uint32_t *pal, *dst2;

    uint8_t *src, *src2;

    int x, y;

    if (r->type != SUBTITLE_BITMAP) {

        av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");

        return;

    }

    if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {

        av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");

        return;

    }

    dst += r->y * dst_linesize + r->x * 4;

    src = r->pict.data[0];

    pal = (uint32_t *)r->pict.data[1];

    for (y = 0; y < r->h; y++) {

        dst2 = (uint32_t *)dst;

        src2 = src;

        for (x = 0; x < r->w; x++)

            *(dst2++) = pal[*(src2++)];

        dst += dst_linesize;

        src += r->pict.linesize[0];

    }

}


SchroVideoFormatEnum ff_get_schro_video_format_preset(AVCodecContext *avctx)

{

    unsigned int num_formats = sizeof(ff_schro_video_formats) /

                               sizeof(ff_schro_video_formats[0]);

    unsigned int idx = get_video_format_idx(avctx);

    return (idx < num_formats) ? ff_schro_video_formats[idx] :

                                 SCHRO_VIDEO_FORMAT_CUSTOM;

}


void qemu_console_copy(QemuConsole *con, int src_x, int src_y,

                       int dst_x, int dst_y, int w, int h)

{

    assert(con->console_type == GRAPHIC_CONSOLE);

    dpy_gfx_copy(con, src_x, src_y, dst_x, dst_y, w, h);

}


static int aac_adtstoasc_init(AVBSFContext *ctx)

{

    av_freep(&ctx->par_out->extradata);

    ctx->par_out->extradata_size = 0;

    return 0;

}


static int dmg_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVDMGState *s = bs->opaque;

    uint64_t info_begin, info_end, last_in_offset, last_out_offset;

    uint32_t count, tmp;

    uint32_t max_compressed_size = 1, max_sectors_per_chunk = 1, i;

    int64_t offset;

    int ret;

    bs->read_only = 1;

    s->n_chunks = 0;

    s->offsets = s->lengths = s->sectors = s->sectorcounts = NULL;

    /* read offset of info blocks */

    offset = bdrv_getlength(bs->file);

    if (offset < 0) {

        ret = offset;

        goto fail;

    }

    offset -= 0x1d8;

    ret = read_uint64(bs, offset, &info_begin);

    if (ret < 0) {

        goto fail;

    } else if (info_begin == 0) {

        ret = -EINVAL;

        goto fail;

    }

    ret = read_uint32(bs, info_begin, &tmp);

    if (ret < 0) {

        goto fail;

    } else if (tmp != 0x100) {

        ret = -EINVAL;

        goto fail;

    }

    ret = read_uint32(bs, info_begin + 4, &count);

    if (ret < 0) {

        goto fail;

    } else if (count == 0) {

        ret = -EINVAL;

        goto fail;

    }

    info_end = info_begin + count;

    offset = info_begin + 0x100;

    /* read offsets */

    last_in_offset = last_out_offset = 0;

    while (offset < info_end) {

        uint32_t type;

        ret = read_uint32(bs, offset, &count);

        if (ret < 0) {

            goto fail;

        } else if (count == 0) {

            ret = -EINVAL;

            goto fail;

        }

        offset += 4;

        ret = read_uint32(bs, offset, &type);

        if (ret < 0) {

            goto fail;

        }

        if (type == 0x6d697368 && count >= 244) {

            size_t new_size;

            uint32_t chunk_count;

            offset += 4;

            offset += 200;

            chunk_count = (count - 204) / 40;

            new_size = sizeof(uint64_t) * (s->n_chunks + chunk_count);

            s->types = g_realloc(s->types, new_size / 2);

            s->offsets = g_realloc(s->offsets, new_size);

            s->lengths = g_realloc(s->lengths, new_size);

            s->sectors = g_realloc(s->sectors, new_size);

            s->sectorcounts = g_realloc(s->sectorcounts, new_size);

            for (i = s->n_chunks; i < s->n_chunks + chunk_count; i++) {

                ret = read_uint32(bs, offset, &s->types[i]);

                if (ret < 0) {

                    goto fail;

                }

                offset += 4;

                if (s->types[i] != 0x80000005 && s->types[i] != 1 &&

                    s->types[i] != 2) {

                    if (s->types[i] == 0xffffffff && i > 0) {

                        last_in_offset = s->offsets[i - 1] + s->lengths[i - 1];

                        last_out_offset = s->sectors[i - 1] +

                                          s->sectorcounts[i - 1];

                    }

                    chunk_count--;

                    i--;

                    offset += 36;

                    continue;

                }

                offset += 4;

                ret = read_uint64(bs, offset, &s->sectors[i]);

                if (ret < 0) {

                    goto fail;

                }

                s->sectors[i] += last_out_offset;

                offset += 8;

                ret = read_uint64(bs, offset, &s->sectorcounts[i]);

                if (ret < 0) {

                    goto fail;

                }

                offset += 8;

                if (s->sectorcounts[i] > DMG_SECTORCOUNTS_MAX) {

                    error_report("sector count %" PRIu64 " for chunk %" PRIu32

                                 " is larger than max (%u)",

                                 s->sectorcounts[i], i, DMG_SECTORCOUNTS_MAX);

                    ret = -EINVAL;

                    goto fail;

                }

                ret = read_uint64(bs, offset, &s->offsets[i]);

                if (ret < 0) {

                    goto fail;

                }

                s->offsets[i] += last_in_offset;

                offset += 8;

                ret = read_uint64(bs, offset, &s->lengths[i]);

                if (ret < 0) {

                    goto fail;

                }

                offset += 8;

                if (s->lengths[i] > DMG_LENGTHS_MAX) {

                    error_report("length %" PRIu64 " for chunk %" PRIu32

                                 " is larger than max (%u)",

                                 s->lengths[i], i, DMG_LENGTHS_MAX);

                    ret = -EINVAL;

                    goto fail;

                }

                update_max_chunk_size(s, i, &max_compressed_size,

                                      &max_sectors_per_chunk);

            }

            s->n_chunks += chunk_count;

        }

    }

    /* initialize zlib engine */

    s->compressed_chunk = qemu_try_blockalign(bs->file,

                                              max_compressed_size + 1);

    s->uncompressed_chunk = qemu_try_blockalign(bs->file,

                                                512 * max_sectors_per_chunk);

    if (s->compressed_chunk == NULL || s->uncompressed_chunk == NULL) {

        ret = -ENOMEM;

        goto fail;

    }

    if (inflateInit(&s->zstream) != Z_OK) {

        ret = -EINVAL;

        goto fail;

    }

    s->current_chunk = s->n_chunks;

    qemu_co_mutex_init(&s->lock);

    return 0;

fail:

    g_free(s->types);

    g_free(s->offsets);

    g_free(s->lengths);

    g_free(s->sectors);

    g_free(s->sectorcounts);

    qemu_vfree(s->compressed_chunk);

    qemu_vfree(s->uncompressed_chunk);

    return ret;

}


static int ea_read_header(AVFormatContext *s)

{

    EaDemuxContext *ea = s->priv_data;

    AVStream *st;

    if (process_ea_header(s)<=0)

        return AVERROR(EIO);

    if (init_video_stream(s, &ea->video) || init_video_stream(s, &ea->alpha))

        return AVERROR(ENOMEM);

    if (ea->audio_codec) {

        if (ea->num_channels <= 0 || ea->num_channels > 2) {

            av_log(s, AV_LOG_WARNING,

                   "Unsupported number of channels: %d\n", ea->num_channels);

            ea->audio_codec = 0;

            return 1;

        }

        if (ea->sample_rate <= 0) {

            av_log(s, AV_LOG_ERROR,

                   "Unsupported sample rate: %d\n", ea->sample_rate);

            ea->audio_codec = 0;

            return 1;

        }

        if (ea->bytes <= 0) {

            av_log(s, AV_LOG_ERROR,

                   "Invalid number of bytes per sample: %d\n", ea->bytes);

            ea->audio_codec = AV_CODEC_ID_NONE;

            return 1;

        }

        /* initialize the audio decoder stream */

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        avpriv_set_pts_info(st, 33, 1, ea->sample_rate);

        st->codecpar->codec_type            = AVMEDIA_TYPE_AUDIO;

        st->codecpar->codec_id              = ea->audio_codec;

        st->codecpar->codec_tag             = 0;   /* no tag */

        st->codecpar->channels              = ea->num_channels;

        st->codecpar->sample_rate           = ea->sample_rate;

        st->codecpar->bits_per_coded_sample = ea->bytes * 8;

        st->codecpar->bit_rate              = (int64_t)st->codecpar->channels *

                                              st->codecpar->sample_rate *

                                              st->codecpar->bits_per_coded_sample / 4;

        st->codecpar->block_align           = st->codecpar->channels *

                                              st->codecpar->bits_per_coded_sample;

        ea->audio_stream_index           = st->index;

        st->start_time                   = 0;

    }

    return 1;

}


static void armv7m_bitband_init(void)

{

    DeviceState *dev;

    dev = qdev_create(NULL, "ARM,bitband-memory");

    qdev_prop_set_uint32(dev, "base", 0x20000000);

    qdev_init(dev);

    sysbus_mmio_map(sysbus_from_qdev(dev), 0, 0x22000000);

    dev = qdev_create(NULL, "ARM,bitband-memory");

    qdev_prop_set_uint32(dev, "base", 0x40000000);

    qdev_init(dev);

    sysbus_mmio_map(sysbus_from_qdev(dev), 0, 0x42000000);

}


static void mpegts_write_section(MpegTSSection *s, uint8_t *buf, int len)

{

    unsigned int crc;

    unsigned char packet[TS_PACKET_SIZE];

    const unsigned char *buf_ptr;

    unsigned char *q;

    int first, b, len1, left;

    crc = av_bswap32(av_crc(av_crc_get_table(AV_CRC_32_IEEE),

                            -1, buf, len - 4));

    buf[len - 4] = (crc >> 24) & 0xff;

    buf[len - 3] = (crc >> 16) & 0xff;

    buf[len - 2] = (crc >>  8) & 0xff;

    buf[len - 1] =  crc        & 0xff;

    /* send each packet */

    buf_ptr = buf;

    while (len > 0) {

        first = buf == buf_ptr;

        q     = packet;

        *q++  = 0x47;

        b     = s->pid >> 8;

        if (first)

            b |= 0x40;

        *q++  = b;

        *q++  = s->pid;

        s->cc = s->cc + 1 & 0xf;

        *q++  = 0x10 | s->cc;

        if (first)

            *q++ = 0; /* 0 offset */

        len1 = TS_PACKET_SIZE - (q - packet);

        if (len1 > len)

            len1 = len;

        memcpy(q, buf_ptr, len1);

        q += len1;

        /* add known padding data */

        left = TS_PACKET_SIZE - (q - packet);

        if (left > 0)

            memset(q, 0xff, left);

        s->write_packet(s, packet);

        buf_ptr += len1;

        len     -= len1;


void address_space_init(AddressSpace *as, MemoryRegion *root, const char *name)

{

    memory_region_transaction_begin();

    as->root = root;

    as->current_map = g_new(FlatView, 1);

    flatview_init(as->current_map);

    as->ioeventfd_nb = 0;

    as->ioeventfds = NULL;

    QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);

    as->name = g_strdup(name ? name : "anonymous");

    address_space_init_dispatch(as);

    memory_region_update_pending |= root->enabled;

    memory_region_transaction_commit();

}


static gboolean fd_trampoline(GIOChannel *chan, GIOCondition cond, gpointer opaque)

{

    IOTrampoline *tramp = opaque;

    if (tramp->opaque == NULL) {

        return FALSE;

    }

    if ((cond & G_IO_IN) && tramp->fd_read) {

        tramp->fd_read(tramp->opaque);

    }

    if ((cond & G_IO_OUT) && tramp->fd_write) {

        tramp->fd_write(tramp->opaque);

    }

    return TRUE;

}


static void test_flush_event_notifier(void)

{

    EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };

    event_notifier_init(&data.e, false);

    aio_set_event_notifier(ctx, &data.e, event_ready_cb, event_active_cb);

    g_assert(aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 0);

    g_assert_cmpint(data.active, ==, 10);

    event_notifier_set(&data.e);

    g_assert(aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 9);

    g_assert(aio_poll(ctx, false));

    wait_for_aio();

    g_assert_cmpint(data.n, ==, 10);

    g_assert_cmpint(data.active, ==, 0);

    g_assert(!aio_poll(ctx, false));

    aio_set_event_notifier(ctx, &data.e, NULL, NULL);

    g_assert(!aio_poll(ctx, false));

    event_notifier_cleanup(&data.e);

}


static int protocol_client_auth_sasl_mechname(VncState *vs, uint8_t *data, size_t len)

{

    char *mechname = malloc(len + 1);

    if (!mechname) {

        VNC_DEBUG("Out of memory reading mechname\n");

        vnc_client_error(vs);

    }

    strncpy(mechname, (char*)data, len);

    mechname[len] = '\0';

    VNC_DEBUG("Got client mechname '%s' check against '%s'\n",

              mechname, vs->sasl.mechlist);

    if (strncmp(vs->sasl.mechlist, mechname, len) == 0) {

        if (vs->sasl.mechlist[len] != '\0' &&

            vs->sasl.mechlist[len] != ',') {

            VNC_DEBUG("One %d", vs->sasl.mechlist[len]);

            vnc_client_error(vs);

            return -1;

        }

    } else {

        char *offset = strstr(vs->sasl.mechlist, mechname);

        VNC_DEBUG("Two %p\n", offset);

        if (!offset) {

            vnc_client_error(vs);

            return -1;

        }

        VNC_DEBUG("Two '%s'\n", offset);

        if (offset[-1] != ',' ||

            (offset[len] != '\0'&&

             offset[len] != ',')) {

            vnc_client_error(vs);

            return -1;

        }

    }

    free(vs->sasl.mechlist);

    vs->sasl.mechlist = mechname;

    VNC_DEBUG("Validated mechname '%s'\n", mechname);

    vnc_read_when(vs, protocol_client_auth_sasl_start_len, 4);

    return 0;

}


static void qxl_send_events(PCIQXLDevice *d, uint32_t events)

{

    uint32_t old_pending;

    uint32_t le_events = cpu_to_le32(events);

    trace_qxl_send_events(d->id, events);

    assert(qemu_spice_display_is_running(&d->ssd));

    old_pending = __sync_fetch_and_or(&d->ram->int_pending, le_events);

    if ((old_pending & le_events) == le_events) {

        return;

    }

    if (qemu_thread_is_self(&d->main)) {

        qxl_update_irq(d);

    } else {

        if (write(d->pipe[1], d, 1) != 1) {

            dprint(d, 1, "%s: write to pipe failed\n", __func__);

        }

    }

}


static void decode_blocks(SnowContext *s){

    int x, y;

    int w= s->b_width;

    int h= s->b_height;

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

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

            decode_q_branch(s, 0, x, y);

        }

    }

}


static int img_read_header(AVFormatContext *s1, AVFormatParameters *ap)

{

    VideoData *s = s1->priv_data;

    int ret, first_index, last_index;

    char buf[1024];

    ByteIOContext pb1, *f = &pb1;

    AVStream *st;

    st = av_new_stream(s1, 0);

    if (!st) {

        av_free(s);

        return -ENOMEM;

    }

    if (ap->image_format)

        s->img_fmt = ap->image_format;

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

    s->img_number = 0;

    s->img_count = 0;

    /* find format */

    if (s1->iformat->flags & AVFMT_NOFILE)

        s->is_pipe = 0;

    else

        s->is_pipe = 1;

    if (!ap->time_base.num) {

        st->codec->time_base= (AVRational){1,25};

    } else {

        st->codec->time_base= ap->time_base;

    }

    if (!s->is_pipe) {

        if (find_image_range(&first_index, &last_index, s->path) < 0)

            goto fail;

        s->img_first = first_index;

        s->img_last = last_index;

        s->img_number = first_index;

        /* compute duration */

        st->start_time = 0;

        st->duration = last_index - first_index + 1;

        if (get_frame_filename(buf, sizeof(buf), s->path, s->img_number) < 0)

            goto fail;

        if (url_fopen(f, buf, URL_RDONLY) < 0)

            goto fail;

    } else {

        f = &s1->pb;

    }

    ret = av_read_image(f, s1->filename, s->img_fmt, read_header_alloc_cb, s);

    if (ret < 0)

        goto fail1;

    if (!s->is_pipe) {

        url_fclose(f);

    } else {

        url_fseek(f, 0, SEEK_SET);

    }

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_RAWVIDEO;

    st->codec->width = s->width;

    st->codec->height = s->height;

    st->codec->pix_fmt = s->pix_fmt;

    s->img_size = avpicture_get_size(s->pix_fmt, (s->width+15)&(~15), (s->height+15)&(~15));

    return 0;

 fail1:

    if (!s->is_pipe)

        url_fclose(f);

 fail:

    av_free(s);

    return AVERROR_IO;

}


static void mpeg4_encode_gop_header(MpegEncContext *s)

{

    int hours, minutes, seconds;

    int64_t time;

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

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

    time = s->current_picture_ptr->f.pts;

    if (s->reordered_input_picture[1])

        time = FFMIN(time, s->reordered_input_picture[1]->f.pts);

    time = time * s->avctx->time_base.num;

    seconds  = time / s->avctx->time_base.den;

    minutes  = seconds / 60;

    seconds %= 60;

    hours    = minutes / 60;

    minutes %= 60;

    hours   %= 24;

    put_bits(&s->pb, 5, hours);

    put_bits(&s->pb, 6, minutes);

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

    put_bits(&s->pb, 6, seconds);

    put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));

    put_bits(&s->pb, 1, 0);  // broken link == NO

    s->last_time_base = time / s->avctx->time_base.den;

    ff_mpeg4_stuffing(&s->pb);

}