static int process_cc608(CCaptionSubContext *ctx, int64_t pts, uint8_t hi, uint8_t lo)

{

    int ret = 0;

#define COR3(var, with1, with2, with3)  ( (var) == (with1) ||  (var) == (with2) || (var) == (with3) )

    if ( hi == ctx->prev_cmd[0] && lo == ctx->prev_cmd[1]) {

    /* ignore redundant command */

    } else if ( (hi == 0x10 && (lo >= 0x40 || lo <= 0x5f)) ||

              ( (hi >= 0x11 && hi <= 0x17) && (lo >= 0x40 && lo <= 0x7f) ) ) {

        handle_pac(ctx, hi, lo);

    } else if ( ( hi == 0x11 && lo >= 0x20 && lo <= 0x2f ) ||

                ( hi == 0x17 && lo >= 0x2e && lo <= 0x2f) ) {

        handle_textattr(ctx, hi, lo);

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x20 ) {

    /* resume caption loading */

        ctx->mode = CCMODE_POPON;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x24 ) {

        handle_delete_end_of_row(ctx, hi, lo);

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x25 ) {

        ctx->rollup = 2;

        ctx->mode = CCMODE_ROLLUP_2;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x26 ) {

        ctx->rollup = 3;

        ctx->mode = CCMODE_ROLLUP_3;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x27 ) {

        ctx->rollup = 4;

        ctx->mode = CCMODE_ROLLUP_4;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x29 ) {

    /* resume direct captioning */

        ctx->mode = CCMODE_PAINTON;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2B ) {

    /* resume text display */

        ctx->mode = CCMODE_TEXT;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2C ) {

    /* erase display memory */

        ret = handle_edm(ctx, pts);

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2D ) {

    /* carriage return */

        av_dlog(ctx, "carriage return\n");

        reap_screen(ctx, pts);

        roll_up(ctx);

        ctx->screen_changed = 1;

        ctx->cursor_column = 0;

    } else if ( COR3(hi, 0x14, 0x15, 0x1C) && lo == 0x2F ) {

    /* end of caption */

        av_dlog(ctx, "handle_eoc\n");

        ret = handle_eoc(ctx, pts);

    } else if (hi>=0x20) {

    /* Standard characters (always in pairs) */

        handle_char(ctx, hi, lo, pts);

    } else {

    /* Ignoring all other non data code */

        av_dlog(ctx, "Unknown command 0x%hhx 0x%hhx\n", hi, lo);

    }

    /* set prev command */

     ctx->prev_cmd[0] = hi;

     ctx->prev_cmd[1] = lo;

#undef COR3

    return ret;

}


static uint32_t vmsvga_value_read(void *opaque, uint32_t address)

{

    uint32_t caps;

    struct vmsvga_state_s *s = opaque;

    switch (s->index) {

    case SVGA_REG_ID:

        return s->svgaid;

    case SVGA_REG_ENABLE:

        return s->enable;

    case SVGA_REG_WIDTH:

        return s->width;

    case SVGA_REG_HEIGHT:

        return s->height;

    case SVGA_REG_MAX_WIDTH:

        return SVGA_MAX_WIDTH;

    case SVGA_REG_MAX_HEIGHT:

        return SVGA_MAX_HEIGHT;

    case SVGA_REG_DEPTH:

        return s->depth;

    case SVGA_REG_BITS_PER_PIXEL:

        return (s->depth + 7) & ~7;

    case SVGA_REG_PSEUDOCOLOR:

        return 0x0;

    case SVGA_REG_RED_MASK:

        return s->wred;

    case SVGA_REG_GREEN_MASK:

        return s->wgreen;

    case SVGA_REG_BLUE_MASK:

        return s->wblue;

    case SVGA_REG_BYTES_PER_LINE:

        return ((s->depth + 7) >> 3) * s->new_width;

    case SVGA_REG_FB_START: {

        struct pci_vmsvga_state_s *pci_vmsvga

            = container_of(s, struct pci_vmsvga_state_s, chip);

        return pci_get_bar_addr(&pci_vmsvga->card, 1);

    }

    case SVGA_REG_FB_OFFSET:

        return 0x0;

    case SVGA_REG_VRAM_SIZE:

        return s->vga.vram_size;

    case SVGA_REG_FB_SIZE:

        return s->fb_size;

    case SVGA_REG_CAPABILITIES:

        caps = SVGA_CAP_NONE;

#ifdef HW_RECT_ACCEL

        caps |= SVGA_CAP_RECT_COPY;

#endif

#ifdef HW_FILL_ACCEL

        caps |= SVGA_CAP_RECT_FILL;

#endif

#ifdef HW_MOUSE_ACCEL

        if (dpy_cursor_define_supported(s->vga.ds)) {

            caps |= SVGA_CAP_CURSOR | SVGA_CAP_CURSOR_BYPASS_2 |

                    SVGA_CAP_CURSOR_BYPASS;

        }

#endif

        return caps;

    case SVGA_REG_MEM_START: {

        struct pci_vmsvga_state_s *pci_vmsvga

            = container_of(s, struct pci_vmsvga_state_s, chip);

        return pci_get_bar_addr(&pci_vmsvga->card, 2);

    }

    case SVGA_REG_MEM_SIZE:

        return s->fifo_size;

    case SVGA_REG_CONFIG_DONE:

        return s->config;

    case SVGA_REG_SYNC:

    case SVGA_REG_BUSY:

        return s->syncing;

    case SVGA_REG_GUEST_ID:

        return s->guest;

    case SVGA_REG_CURSOR_ID:

        return s->cursor.id;

    case SVGA_REG_CURSOR_X:

        return s->cursor.x;

    case SVGA_REG_CURSOR_Y:

        return s->cursor.x;

    case SVGA_REG_CURSOR_ON:

        return s->cursor.on;

    case SVGA_REG_HOST_BITS_PER_PIXEL:

        return (s->depth + 7) & ~7;

    case SVGA_REG_SCRATCH_SIZE:

        return s->scratch_size;

    case SVGA_REG_MEM_REGS:

    case SVGA_REG_NUM_DISPLAYS:

    case SVGA_REG_PITCHLOCK:

    case SVGA_PALETTE_BASE ... SVGA_PALETTE_END:

        return 0;

    default:

        if (s->index >= SVGA_SCRATCH_BASE &&

                s->index < SVGA_SCRATCH_BASE + s->scratch_size)

            return s->scratch[s->index - SVGA_SCRATCH_BASE];

        printf("%s: Bad register %02x\n", __FUNCTION__, s->index);

    }

    return 0;

}


static void qemu_chr_parse_file_out(QemuOpts *opts, ChardevBackend *backend,

                                    Error **errp)

{

    const char *path = qemu_opt_get(opts, "path");

    ChardevFile *file;

    if (path == NULL) {

        error_setg(errp, "chardev: file: no filename given");

        return;

    }

    file = backend->u.file = g_new0(ChardevFile, 1);

    qemu_chr_parse_common(opts, qapi_ChardevFile_base(file));

    file->out = g_strdup(path);

    file->has_append = true;

    file->append = qemu_opt_get_bool(opts, "append", false);

}


nvdimm_dsm_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)

{

    AcpiNVDIMMState *state = opaque;

    NvdimmDsmIn *in;

    hwaddr dsm_mem_addr = val;

    nvdimm_debug("dsm memory address %#" HWADDR_PRIx ".\n", dsm_mem_addr);

    /*

     * The DSM memory is mapped to guest address space so an evil guest

     * can change its content while we are doing DSM emulation. Avoid

     * this by copying DSM memory to QEMU local memory.

     */

    in = g_new(NvdimmDsmIn, 1);

    cpu_physical_memory_read(dsm_mem_addr, in, sizeof(*in));

    le32_to_cpus(&in->revision);

    le32_to_cpus(&in->function);

    le32_to_cpus(&in->handle);

    nvdimm_debug("Revision %#x Handler %#x Function %#x.\n", in->revision,

                 in->handle, in->function);

    if (in->revision != 0x1 /* Currently we only support DSM Spec Rev1. */) {

        nvdimm_debug("Revision %#x is not supported, expect %#x.\n",

                     in->revision, 0x1);

        nvdimm_dsm_no_payload(1 /* Not Supported */, dsm_mem_addr);

        goto exit;

    }

    if (in->handle == NVDIMM_QEMU_RSVD_HANDLE_ROOT) {

        nvdimm_dsm_reserved_root(state, in, dsm_mem_addr);

        goto exit;

    }

     /* Handle 0 is reserved for NVDIMM Root Device. */

    if (!in->handle) {

        nvdimm_dsm_root(in, dsm_mem_addr);

        goto exit;

    }

    nvdimm_dsm_device(in, dsm_mem_addr);

exit:

    g_free(in);

}


static BlockDriverAIOCB *hdev_aio_ioctl(BlockDriverState *bs,

        unsigned long int req, void *buf,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVRawState *s = bs->opaque;

    if (fd_open(bs) < 0)

        return NULL;

    return paio_ioctl(bs, s->fd, req, buf, cb, opaque);

}


static void qxl_init_ramsize(PCIQXLDevice *qxl)

{

    /* vga mode framebuffer / primary surface (bar 0, first part) */

    if (qxl->vgamem_size_mb < 8) {

        qxl->vgamem_size_mb = 8;

    }

    /* XXX: we round vgamem_size_mb up to a nearest power of two and it must be

     * less than vga_common_init()'s maximum on qxl->vga.vram_size (512 now).

     */

    if (qxl->vgamem_size_mb > 256) {

        qxl->vgamem_size_mb = 256;

    }

    qxl->vgamem_size = qxl->vgamem_size_mb * 1024 * 1024;

    /* vga ram (bar 0, total) */

    if (qxl->ram_size_mb != -1) {

        qxl->vga.vram_size = qxl->ram_size_mb * 1024 * 1024;

    }

    if (qxl->vga.vram_size < qxl->vgamem_size * 2) {

        qxl->vga.vram_size = qxl->vgamem_size * 2;

    }

    /* vram32 (surfaces, 32bit, bar 1) */

    if (qxl->vram32_size_mb != -1) {

        qxl->vram32_size = qxl->vram32_size_mb * 1024 * 1024;

    }

    if (qxl->vram32_size < 4096) {

        qxl->vram32_size = 4096;

    }

    /* vram (surfaces, 64bit, bar 4+5) */

    if (qxl->vram_size_mb != -1) {

        qxl->vram_size = qxl->vram_size_mb * 1024 * 1024;

    }

    if (qxl->vram_size < qxl->vram32_size) {

        qxl->vram_size = qxl->vram32_size;

    }

    if (qxl->revision == 1) {

        qxl->vram32_size = 4096;

        qxl->vram_size = 4096;

    }

    qxl->vgamem_size = pow2ceil(qxl->vgamem_size);

    qxl->vga.vram_size = pow2ceil(qxl->vga.vram_size);

    qxl->vram32_size = pow2ceil(qxl->vram32_size);

    qxl->vram_size = pow2ceil(qxl->vram_size);

}


static int rtl8139_config_writable(RTL8139State *s)

{

    if (s->Cfg9346 & Cfg9346_Unlock)

    {

        return 1;

    }

    DPRINTF("Configuration registers are write-protected\n");

    return 0;

}


static int vfio_container_do_ioctl(AddressSpace *as, int32_t groupid,

                                   int req, void *param)

{

    VFIOGroup *group;

    VFIOContainer *container;

    int ret = -1;

    group = vfio_get_group(groupid, as);

    if (!group) {

        error_report("vfio: group %d not registered", groupid);

        return ret;

    }

    container = group->container;

    if (group->container) {

        ret = ioctl(container->fd, req, param);

        if (ret < 0) {

            error_report("vfio: failed to ioctl %d to container: ret=%d, %s",

                         _IOC_NR(req) - VFIO_BASE, ret, strerror(errno));

        }

    }

    vfio_put_group(group);

    return ret;

}


void vnc_flush(VncState *vs)

{

    vnc_lock_output(vs);

    if (vs->csock != -1 && (vs->output.offset

#ifdef CONFIG_VNC_WS

                || vs->ws_output.offset

#endif

                )) {

        vnc_client_write_locked(vs);

    }

    vnc_unlock_output(vs);

}


static float32 roundAndPackFloat32( flag zSign, int16 zExp, bits32 zSig STATUS_PARAM)

{

    int8 roundingMode;

    flag roundNearestEven;

    int8 roundIncrement, roundBits;

    flag isTiny;

    roundingMode = STATUS(float_rounding_mode);

    roundNearestEven = ( roundingMode == float_round_nearest_even );

    roundIncrement = 0x40;

    if ( ! roundNearestEven ) {

        if ( roundingMode == float_round_to_zero ) {

            roundIncrement = 0;

        }

        else {

            roundIncrement = 0x7F;

            if ( zSign ) {

                if ( roundingMode == float_round_up ) roundIncrement = 0;

            }

            else {

                if ( roundingMode == float_round_down ) roundIncrement = 0;

            }

        }

    }

    roundBits = zSig & 0x7F;

    if ( 0xFD <= (bits16) zExp ) {

        if (    ( 0xFD < zExp )

             || (    ( zExp == 0xFD )

                  && ( (sbits32) ( zSig + roundIncrement ) < 0 ) )

           ) {

            float_raise( float_flag_overflow | float_flag_inexact STATUS_VAR);

            return packFloat32( zSign, 0xFF, 0 ) - ( roundIncrement == 0 );

        }

        if ( zExp < 0 ) {

            isTiny =

                   ( STATUS(float_detect_tininess) == float_tininess_before_rounding )

                || ( zExp < -1 )

                || ( zSig + roundIncrement < 0x80000000 );

            shift32RightJamming( zSig, - zExp, &zSig );

            zExp = 0;

            roundBits = zSig & 0x7F;

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

        }

    }

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

    zSig = ( zSig + roundIncrement )>>7;

    zSig &= ~ ( ( ( roundBits ^ 0x40 ) == 0 ) & roundNearestEven );

    if ( zSig == 0 ) zExp = 0;

    return packFloat32( zSign, zExp, zSig );

}


static void omap_lpg_write(void *opaque, target_phys_addr_t addr,

                           uint64_t value, unsigned size)

{

    struct omap_lpg_s *s = (struct omap_lpg_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 1) {

        return omap_badwidth_write8(opaque, addr, value);

    }

    switch (offset) {

    case 0x00:	/* LCR */

        if (~value & (1 << 6))					/* LPGRES */

            omap_lpg_reset(s);

        s->control = value & 0xff;

        omap_lpg_update(s);

        return;

    case 0x04:	/* PMR */

        s->power = value & 0x01;

        omap_lpg_update(s);

        return;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


static int h264_find_frame_end(H264ParseContext *p, const uint8_t *buf,

                               int buf_size)

{

    int i;

    uint32_t state;

    ParseContext *pc = &p->pc;

//    mb_addr= pc->mb_addr - 1;

    state = pc->state;

    if (state > 13)

        state = 7;

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

        if (state == 7) {

            i += p->h264dsp.startcode_find_candidate(buf + i, buf_size - i);

            if (i < buf_size)

                state = 2;

        } else if (state <= 2) {

            if (buf[i] == 1)

                state ^= 5;            // 2->7, 1->4, 0->5

            else if (buf[i])

                state = 7;

            else

                state >>= 1;           // 2->1, 1->0, 0->0

        } else if (state <= 5) {

            int nalu_type = buf[i] & 0x1F;

            if (nalu_type == NAL_SEI || nalu_type == NAL_SPS ||

                nalu_type == NAL_PPS || nalu_type == NAL_AUD) {

                if (pc->frame_start_found) {

                    i++;

                    goto found;

                }

            } else if (nalu_type == NAL_SLICE || nalu_type == NAL_DPA ||

                       nalu_type == NAL_IDR_SLICE) {

                if (pc->frame_start_found) {

                    state += 8;

                    continue;

                } else

                    pc->frame_start_found = 1;

            }

            state = 7;

        } else {

            // first_mb_in_slice is 0, probably the first nal of a new slice

            if (buf[i] & 0x80)

                goto found;

            state = 7;

        }

    }

    pc->state = state;

    return END_NOT_FOUND;

found:

    pc->state             = 7;

    pc->frame_start_found = 0;

    return i - (state & 5);

}


static uint64_t omap_mpu_timer_read(void *opaque, target_phys_addr_t addr,

                                    unsigned size)

{

    struct omap_mpu_timer_s *s = (struct omap_mpu_timer_s *) opaque;

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* CNTL_TIMER */

        return (s->enable << 5) | (s->ptv << 2) | (s->ar << 1) | s->st;

    case 0x04:	/* LOAD_TIM */

        break;

    case 0x08:	/* READ_TIM */

        return omap_timer_read(s);

    }

    OMAP_BAD_REG(addr);

    return 0;

}


void bdrv_close(BlockDriverState *bs)

{

    BdrvAioNotifier *ban, *ban_next;

    if (bs->job) {

        block_job_cancel_sync(bs->job);

    }

    /* Disable I/O limits and drain all pending throttled requests */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_disable(bs);

    }

    bdrv_drain(bs); /* complete I/O */

    bdrv_flush(bs);

    bdrv_drain(bs); /* in case flush left pending I/O */

    notifier_list_notify(&bs->close_notifiers, bs);

    if (bs->drv) {

        BdrvChild *child, *next;

        bs->drv->bdrv_close(bs);

        bs->drv = NULL;

        bdrv_set_backing_hd(bs, NULL);

        if (bs->file != NULL) {

            bdrv_unref_child(bs, bs->file);

            bs->file = NULL;

        }

        QLIST_FOREACH_SAFE(child, &bs->children, next, next) {

            /* TODO Remove bdrv_unref() from drivers' close function and use

             * bdrv_unref_child() here */

            if (child->bs->inherits_from == bs) {

                child->bs->inherits_from = NULL;

            }

            bdrv_detach_child(child);

        }

        g_free(bs->opaque);

        bs->opaque = NULL;

        bs->copy_on_read = 0;

        bs->backing_file[0] = '\0';

        bs->backing_format[0] = '\0';

        bs->total_sectors = 0;

        bs->encrypted = 0;

        bs->valid_key = 0;

        bs->sg = 0;

        bs->zero_beyond_eof = false;

        QDECREF(bs->options);

        bs->options = NULL;

        QDECREF(bs->full_open_options);

        bs->full_open_options = NULL;

    }

    if (bs->blk) {

        blk_dev_change_media_cb(bs->blk, false);

    }

    QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {

        g_free(ban);

    }

    QLIST_INIT(&bs->aio_notifiers);

}


void slirp_select_poll(fd_set *readfds, fd_set *writefds,

                       fd_set *xfds, int select_error)

{

}


struct omap_mcbsp_s *omap_mcbsp_init(MemoryRegion *system_memory,

                target_phys_addr_t base,

                qemu_irq *irq, qemu_irq *dma, omap_clk clk)

{

    struct omap_mcbsp_s *s = (struct omap_mcbsp_s *)

            g_malloc0(sizeof(struct omap_mcbsp_s));

    s->txirq = irq[0];

    s->rxirq = irq[1];

    s->txdrq = dma[0];

    s->rxdrq = dma[1];

    s->sink_timer = qemu_new_timer_ns(vm_clock, omap_mcbsp_sink_tick, s);

    s->source_timer = qemu_new_timer_ns(vm_clock, omap_mcbsp_source_tick, s);

    omap_mcbsp_reset(s);

    memory_region_init_io(&s->iomem, &omap_mcbsp_ops, s, "omap-mcbsp", 0x800);

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

    return s;

}


static target_ulong h_rtas(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                           target_ulong opcode, target_ulong *args)

{

    target_ulong rtas_r3 = args[0];

    uint32_t token = ldl_be_phys(rtas_r3);

    uint32_t nargs = ldl_be_phys(rtas_r3 + 4);

    uint32_t nret = ldl_be_phys(rtas_r3 + 8);

    return spapr_rtas_call(spapr, token, nargs, rtas_r3 + 12,

                           nret, rtas_r3 + 12 + 4*nargs);

}


static void do_info_balloon(Monitor *mon, QObject **ret_data)

{

    ram_addr_t actual;

    actual = qemu_balloon_status();

    if (kvm_enabled() && !kvm_has_sync_mmu())

        qemu_error_new(QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");

    else if (actual == 0)

        qemu_error_new(QERR_DEVICE_NOT_ACTIVE, "balloon");

    else

        *ret_data = qobject_from_jsonf("{ 'balloon': %" PRId64 "}",

                                       (int64_t) actual);

}


static void virtio_scsi_hotplug(SCSIBus *bus, SCSIDevice *dev)

{

    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);

    if (((s->vdev.guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) &&

        (s->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_TRANSPORT_RESET,

                               VIRTIO_SCSI_EVT_RESET_RESCAN);

    }

}


void qio_channel_socket_listen_async(QIOChannelSocket *ioc,

                                     SocketAddressLegacy *addr,

                                     QIOTaskFunc callback,

                                     gpointer opaque,

                                     GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

        OBJECT(ioc), callback, opaque, destroy);

    SocketAddressLegacy *addrCopy;

    addrCopy = QAPI_CLONE(SocketAddressLegacy, addr);

    /* socket_listen() blocks in DNS lookups, so we must use a thread */

    trace_qio_channel_socket_listen_async(ioc, addr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_listen_worker,

                           addrCopy,

                           (GDestroyNotify)qapi_free_SocketAddressLegacy);

}


static void bmdma_write(void *opaque, target_phys_addr_t addr,

                        uint64_t val, unsigned size)

{

    BMDMAState *bm = opaque;

    if (size != 1) {

        return;

    }

#ifdef DEBUG_IDE

    printf("bmdma: writeb 0x%02x : 0x%02x\n", addr, val);

#endif

    switch (addr & 3) {

    case 0:

        bmdma_cmd_writeb(bm, val);

        break;

    case 2:

        bm->status = (val & 0x60) | (bm->status & 1) | (bm->status & ~val & 0x06);

        break;

    default:;

    }

}


int bdrv_open(BlockDriverState *bs, const char *filename, int flags,

              BlockDriver *drv)

{

    int ret, open_flags;

    char tmp_filename[PATH_MAX];

    char backing_filename[PATH_MAX];

    bs->is_temporary = 0;

    bs->encrypted = 0;

    bs->valid_key = 0;

    bs->open_flags = flags;

    /* buffer_alignment defaulted to 512, drivers can change this value */

    bs->buffer_alignment = 512;

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        int is_protocol = 0;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *options;

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open(bs1, filename, 0, drv);

        if (ret < 0) {

            bdrv_delete(bs1);

            return ret;

        }

        total_size = bdrv_getlength(bs1) >> BDRV_SECTOR_BITS;

        if (bs1->drv && bs1->drv->protocol_name)

            is_protocol = 1;

        bdrv_delete(bs1);

        get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        /* Real path is meaningless for protocols */

        if (is_protocol)

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        else if (!realpath(filename, backing_filename))

            return -errno;

        bdrv_qcow2 = bdrv_find_format("qcow2");

        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);

        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);

        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);

        if (drv) {

            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);

        if (ret < 0) {

            return ret;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    pstrcpy(bs->filename, sizeof(bs->filename), filename);

    if (!drv) {

        drv = find_hdev_driver(filename);

        if (!drv) {

            drv = find_image_format(filename);

        }

    }

    if (!drv) {

        ret = -ENOENT;

        goto unlink_and_fail;

    }

    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {

        ret = -ENOTSUP;

        goto unlink_and_fail;

    }

    bs->drv = drv;

    bs->opaque = qemu_mallocz(drv->instance_size);

    /*

     * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a

     * write cache to the guest.  We do need the fdatasync to flush

     * out transactions for block allocations, and we maybe have a

     * volatile write cache in our backing device to deal with.

     */

    if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))

        bs->enable_write_cache = 1;

    /*

     * Clear flags that are internal to the block layer before opening the

     * image.

     */

    open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);

    /*

     * Snapshots should be writeable.

     */

    if (bs->is_temporary) {

        open_flags |= BDRV_O_RDWR;

    }

    ret = drv->bdrv_open(bs, filename, open_flags);

    if (ret < 0) {

        goto free_and_fail;

    }

    bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);

    if (drv->bdrv_getlength) {

        bs->total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;

    }

#ifndef _WIN32

    if (bs->is_temporary) {

        unlink(filename);

    }

#endif

    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {

        /* if there is a backing file, use it */

        BlockDriver *back_drv = NULL;

        bs->backing_hd = bdrv_new("");

        path_combine(backing_filename, sizeof(backing_filename),

                     filename, bs->backing_file);

        if (bs->backing_format[0] != '\0')

            back_drv = bdrv_find_format(bs->backing_format);

        /* backing files always opened read-only */

        open_flags &= ~BDRV_O_RDWR;

        ret = bdrv_open(bs->backing_hd, backing_filename, open_flags, back_drv);

        if (ret < 0) {

            bdrv_close(bs);

            return ret;

        }

        if (bs->is_temporary) {

            bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);

        } else {

            /* base image inherits from "parent" */

            bs->backing_hd->keep_read_only = bs->keep_read_only;

        }

    }

    if (!bdrv_key_required(bs)) {

        /* call the change callback */

        bs->media_changed = 1;

        if (bs->change_cb)

            bs->change_cb(bs->change_opaque);

    }

    return 0;

free_and_fail:

    qemu_free(bs->opaque);

    bs->opaque = NULL;

    bs->drv = NULL;

unlink_and_fail:

    if (bs->is_temporary)

        unlink(filename);

    return ret;

}


static uint32_t omap_l4_io_readw(void *opaque, target_phys_addr_t addr)

{

    unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;

    return omap_l4_io_readw_fn[i](omap_l4_io_opaque[i], addr);

}


PCIBus *typhoon_init(ram_addr_t ram_size, ISABus **isa_bus,

                     qemu_irq *p_rtc_irq,

                     AlphaCPU *cpus[4], pci_map_irq_fn sys_map_irq)

{

    const uint64_t MB = 1024 * 1024;

    const uint64_t GB = 1024 * MB;

    MemoryRegion *addr_space = get_system_memory();

    DeviceState *dev;

    TyphoonState *s;

    PCIHostState *phb;

    PCIBus *b;

    int i;

    dev = qdev_create(NULL, TYPE_TYPHOON_PCI_HOST_BRIDGE);

    qdev_init_nofail(dev);

    s = TYPHOON_PCI_HOST_BRIDGE(dev);

    phb = PCI_HOST_BRIDGE(dev);

    /* Remember the CPUs so that we can deliver interrupts to them.  */

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

        AlphaCPU *cpu = cpus[i];

        s->cchip.cpu[i] = cpu;

        if (cpu != NULL) {

            cpu->alarm_timer = qemu_new_timer_ns(rtc_clock,

                                                 typhoon_alarm_timer,

                                                 (void *)((uintptr_t)s + i));

        }

    }

    *p_rtc_irq = *qemu_allocate_irqs(typhoon_set_timer_irq, s, 1);

    /* Main memory region, 0x00.0000.0000.  Real hardware supports 32GB,

       but the address space hole reserved at this point is 8TB.  */

    memory_region_init_ram(&s->ram_region, OBJECT(s), "ram", ram_size);

    vmstate_register_ram_global(&s->ram_region);

    memory_region_add_subregion(addr_space, 0, &s->ram_region);

    /* TIGbus, 0x801.0000.0000, 1GB.  */

    /* ??? The TIGbus is used for delivering interrupts, and access to

       the flash ROM.  I'm not sure that we need to implement it at all.  */

    /* Pchip0 CSRs, 0x801.8000.0000, 256MB.  */

    memory_region_init_io(&s->pchip.region, OBJECT(s), &pchip_ops, s, "pchip0",

                          256*MB);

    memory_region_add_subregion(addr_space, 0x80180000000ULL,

                                &s->pchip.region);

    /* Cchip CSRs, 0x801.A000.0000, 256MB.  */

    memory_region_init_io(&s->cchip.region, OBJECT(s), &cchip_ops, s, "cchip0",

                          256*MB);

    memory_region_add_subregion(addr_space, 0x801a0000000ULL,

                                &s->cchip.region);

    /* Dchip CSRs, 0x801.B000.0000, 256MB.  */

    memory_region_init_io(&s->dchip_region, OBJECT(s), &dchip_ops, s, "dchip0",

                          256*MB);

    memory_region_add_subregion(addr_space, 0x801b0000000ULL,

                                &s->dchip_region);

    /* Pchip0 PCI memory, 0x800.0000.0000, 4GB.  */

    memory_region_init(&s->pchip.reg_mem, OBJECT(s), "pci0-mem", 4*GB);

    memory_region_add_subregion(addr_space, 0x80000000000ULL,

                                &s->pchip.reg_mem);

    /* Pchip0 PCI I/O, 0x801.FC00.0000, 32MB.  */

    memory_region_init(&s->pchip.reg_io, OBJECT(s), "pci0-io", 32*MB);

    memory_region_add_subregion(addr_space, 0x801fc000000ULL,

                                &s->pchip.reg_io);

    b = pci_register_bus(dev, "pci",

                         typhoon_set_irq, sys_map_irq, s,

                         &s->pchip.reg_mem, &s->pchip.reg_io,

                         0, 64, TYPE_PCI_BUS);

    phb->bus = b;

    /* Pchip0 PCI special/interrupt acknowledge, 0x801.F800.0000, 64MB.  */

    memory_region_init_io(&s->pchip.reg_iack, OBJECT(s), &alpha_pci_iack_ops,

                          b, "pci0-iack", 64*MB);

    memory_region_add_subregion(addr_space, 0x801f8000000ULL,

                                &s->pchip.reg_iack);

    /* Pchip0 PCI configuration, 0x801.FE00.0000, 16MB.  */

    memory_region_init_io(&s->pchip.reg_conf, OBJECT(s), &alpha_pci_conf1_ops,

                          b, "pci0-conf", 16*MB);

    memory_region_add_subregion(addr_space, 0x801fe000000ULL,

                                &s->pchip.reg_conf);

    /* For the record, these are the mappings for the second PCI bus.

       We can get away with not implementing them because we indicate

       via the Cchip.CSC<PIP> bit that Pchip1 is not present.  */

    /* Pchip1 PCI memory, 0x802.0000.0000, 4GB.  */

    /* Pchip1 CSRs, 0x802.8000.0000, 256MB.  */

    /* Pchip1 PCI special/interrupt acknowledge, 0x802.F800.0000, 64MB.  */

    /* Pchip1 PCI I/O, 0x802.FC00.0000, 32MB.  */

    /* Pchip1 PCI configuration, 0x802.FE00.0000, 16MB.  */

    /* Init the ISA bus.  */

    /* ??? Technically there should be a cy82c693ub pci-isa bridge.  */

    {

        qemu_irq isa_pci_irq, *isa_irqs;

        *isa_bus = isa_bus_new(NULL, &s->pchip.reg_io);

        isa_pci_irq = *qemu_allocate_irqs(typhoon_set_isa_irq, s, 1);

        isa_irqs = i8259_init(*isa_bus, isa_pci_irq);

        isa_bus_irqs(*isa_bus, isa_irqs);

    }

    return b;

}


static void qmp_output_end_struct(Visitor *v, void **obj)

{

    QmpOutputVisitor *qov = to_qov(v);

    QObject *value = qmp_output_pop(qov, obj);

    assert(qobject_type(value) == QTYPE_QDICT);

}


static void pmuserenr_write(CPUARMState *env, const ARMCPRegInfo *ri,

                            uint64_t value)

{

    env->cp15.c9_pmuserenr = value & 1;

}


static int parse_drive(DeviceState *dev, Property *prop, const char *str)

{

    DriveInfo **ptr = qdev_get_prop_ptr(dev, prop);

    *ptr = drive_get_by_id(str);

    if (*ptr == NULL)

        return -ENOENT;

    return 0;

}


void put_pixels8_xy2_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h)

{

POWERPC_TBL_DECLARE(altivec_put_pixels8_xy2_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    int j;

POWERPC_TBL_START_COUNT(altivec_put_pixels8_xy2_num, 1);

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

      int i;

      const uint32_t a = (((const struct unaligned_32 *) (pixels))->l);

      const uint32_t b =

        (((const struct unaligned_32 *) (pixels + 1))->l);

      uint32_t l0 =

        (a & 0x03030303UL) + (b & 0x03030303UL) + 0x02020202UL;

      uint32_t h0 =

        ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

      uint32_t l1, h1;

      pixels += line_size;

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

        uint32_t a = (((const struct unaligned_32 *) (pixels))->l);

        uint32_t b = (((const struct unaligned_32 *) (pixels + 1))->l);

        l1 = (a & 0x03030303UL) + (b & 0x03030303UL);

        h1 = ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

        *((uint32_t *) block) =

          h0 + h1 + (((l0 + l1) >> 2) & 0x0F0F0F0FUL);

        pixels += line_size;

        block += line_size;

        a = (((const struct unaligned_32 *) (pixels))->l);

        b = (((const struct unaligned_32 *) (pixels + 1))->l);

        l0 = (a & 0x03030303UL) + (b & 0x03030303UL) + 0x02020202UL;

        h0 = ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

        *((uint32_t *) block) =

          h0 + h1 + (((l0 + l1) >> 2) & 0x0F0F0F0FUL);

        pixels += line_size;

        block += line_size;

      } pixels += 4 - line_size * (h + 1);

      block += 4 - line_size * h;

    }

POWERPC_TBL_STOP_COUNT(altivec_put_pixels8_xy2_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

   register int i;

   register vector unsigned char

     pixelsv1, pixelsv2,

     pixelsavg;

   register vector unsigned char

     blockv, temp1, temp2;

   register vector unsigned short

     pixelssum1, pixelssum2, temp3;

   register const vector unsigned char vczero = (const vector unsigned char)vec_splat_u8(0);

   register const vector unsigned short vctwo = (const vector unsigned short)vec_splat_u16(2);

   temp1 = vec_ld(0, pixels);

   temp2 = vec_ld(16, pixels);

   pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(0, pixels));

   if ((((unsigned long)pixels) & 0x0000000F) ==  0x0000000F)

   {

     pixelsv2 = temp2;

   }

   else

   {

     pixelsv2 = vec_perm(temp1, temp2, vec_lvsl(1, pixels));

   }

   pixelsv1 = vec_mergeh(vczero, pixelsv1);

   pixelsv2 = vec_mergeh(vczero, pixelsv2);

   pixelssum1 = vec_add((vector unsigned short)pixelsv1,

                        (vector unsigned short)pixelsv2);

   pixelssum1 = vec_add(pixelssum1, vctwo);

POWERPC_TBL_START_COUNT(altivec_put_pixels8_xy2_num, 1);

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

     int rightside = ((unsigned long)block & 0x0000000F);

     blockv = vec_ld(0, block);

     temp1 = vec_ld(line_size, pixels);

     temp2 = vec_ld(line_size + 16, pixels);

     pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(line_size, pixels));

     if (((((unsigned long)pixels) + line_size) & 0x0000000F) ==  0x0000000F)

     {

       pixelsv2 = temp2;

     }

     else

     {

       pixelsv2 = vec_perm(temp1, temp2, vec_lvsl(line_size + 1, pixels));

     }

     pixelsv1 = vec_mergeh(vczero, pixelsv1);

     pixelsv2 = vec_mergeh(vczero, pixelsv2);

     pixelssum2 = vec_add((vector unsigned short)pixelsv1,

                          (vector unsigned short)pixelsv2);

     temp3 = vec_add(pixelssum1, pixelssum2);

     temp3 = vec_sra(temp3, vctwo);

     pixelssum1 = vec_add(pixelssum2, vctwo);

     pixelsavg = vec_packsu(temp3, (vector unsigned short) vczero);

     if (rightside)

     {

       blockv = vec_perm(blockv, pixelsavg, vcprm(0, 1, s0, s1));

     }

     else

     {

       blockv = vec_perm(blockv, pixelsavg, vcprm(s0, s1, 2, 3));

     }

     vec_st(blockv, 0, block);

     block += line_size;

     pixels += line_size;

   }

POWERPC_TBL_STOP_COUNT(altivec_put_pixels8_xy2_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


void cpu_x86_interrupt(CPUX86State *s)

{

    s->interrupt_request = 1;

}


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

{

    Error *error = NULL;

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

    const char *base = qdict_get_try_str(qdict, "base");

    qmp_block_stream(device, base != NULL, base, &error);

    hmp_handle_error(mon, &error);

}


static int flic_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

    FlicDemuxContext *flic = (FlicDemuxContext *)s->priv_data;

    ByteIOContext *pb = &s->pb;

    int packet_read = 0;

    unsigned int size;

    int magic;

    int ret = 0;

    unsigned char preamble[FLIC_PREAMBLE_SIZE];

    while (!packet_read) {

        if ((ret = get_buffer(pb, preamble, FLIC_PREAMBLE_SIZE)) !=

            FLIC_PREAMBLE_SIZE) {

            ret = AVERROR_IO;

            break;

        }

        size = LE_32(&preamble[0]);

        magic = LE_16(&preamble[4]);

        if ((magic == FLIC_CHUNK_MAGIC_1) || (magic == FLIC_CHUNK_MAGIC_2)) {

            if (av_new_packet(pkt, size)) {

                ret = AVERROR_IO;

                break;

            }

            pkt->stream_index = flic->video_stream_index;

            pkt->pts = flic->pts;

            memcpy(pkt->data, preamble, FLIC_PREAMBLE_SIZE);

            ret = get_buffer(pb, pkt->data + FLIC_PREAMBLE_SIZE,

                size - FLIC_PREAMBLE_SIZE);

            if (ret != size - FLIC_PREAMBLE_SIZE) {

                av_free_packet(pkt);

                ret = AVERROR_IO;

            }

            flic->pts += flic->frame_pts_inc;

            packet_read = 1;

        } else {

            /* not interested in this chunk */

            url_fseek(pb, size - 6, SEEK_CUR);

        }

    }

    return ret;

}


static int get_ref_idx(AVFrame *frame)

{

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    if (!frame || !frame->private_ref)

        return -1;

    fdd = (FrameDecodeData*)frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    return cf->idx;

}


static int put_packetheader(NUTContext *nut, ByteIOContext *bc, int max_size, int calculate_checksum)

{

    put_flush_packet(bc);

    nut->packet_start[2]= url_ftell(bc) - 8;

    nut->written_packet_size = max_size;

    if(calculate_checksum)

        init_checksum(bc, update_adler32, 0);

    /* packet header */

    put_v(bc, nut->written_packet_size); /* forward ptr */

    return 0;

}


inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long dstWidth, uint8_t *src1, uint8_t *src2,

                                   int srcW, int xInc, int flags, int canMMX2BeUsed, int16_t *hChrFilter,

                                   int16_t *hChrFilterPos, int hChrFilterSize, void *funnyUVCode,

                                   int srcFormat, uint8_t *formatConvBuffer, int16_t *mmx2Filter,

                                   int32_t *mmx2FilterPos, uint8_t *pal)

{

    if (srcFormat==PIX_FMT_YUYV422)

    {

        RENAME(yuy2ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_UYVY422)

    {

        RENAME(uyvyToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB32)

    {

        if(c->chrSrcHSubSample)

            RENAME(bgr32ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(bgr32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB32_1)

    {

        if(c->chrSrcHSubSample)

            RENAME(bgr32ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        else

            RENAME(bgr32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR24)

    {

        if(c->chrSrcHSubSample)

            RENAME(bgr24ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(bgr24ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR565)

    {

        if(c->chrSrcHSubSample)

            RENAME(bgr16ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(bgr16ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR555)

    {

        if(c->chrSrcHSubSample)

            RENAME(bgr15ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(bgr15ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR32)

    {

        if(c->chrSrcHSubSample)

            RENAME(rgb32ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(rgb32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR32_1)

    {

        if(c->chrSrcHSubSample)

            RENAME(rgb32ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        else

            RENAME(rgb32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB24)

    {

        if(c->chrSrcHSubSample)

            RENAME(rgb24ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(rgb24ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB565)

    {

        if(c->chrSrcHSubSample)

            RENAME(rgb16ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(rgb16ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB555)

    {

        if(c->chrSrcHSubSample)

            RENAME(rgb15ToUV_half)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        else

            RENAME(rgb15ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (isGray(srcFormat) || srcFormat==PIX_FMT_MONOBLACK || PIX_FMT_MONOWHITE)

    {

        return;

    }

    else if (srcFormat==PIX_FMT_RGB8 || srcFormat==PIX_FMT_BGR8 || srcFormat==PIX_FMT_PAL8 || srcFormat==PIX_FMT_BGR4_BYTE  || srcFormat==PIX_FMT_RGB4_BYTE)

    {

        RENAME(palToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW, (uint32_t*)pal);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

#ifdef HAVE_MMX

    // Use the new MMX scaler if the MMX2 one can't be used (it is faster than the x86 ASM one).

    if (!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if (!(flags&SWS_FAST_BILINEAR))

#endif

    {

        RENAME(hScale)(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

        RENAME(hScale)(dst+VOFW, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    }

    else // fast bilinear upscale / crap downscale

    {

#if defined(ARCH_X86)

#ifdef HAVE_MMX2

        int i;

#if defined(PIC)

        uint64_t ebxsave __attribute__((aligned(8)));

#endif

        if (canMMX2BeUsed)

        {

            asm volatile(

#if defined(PIC)

            "mov          %%"REG_b", %6         \n\t"

#endif

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

            "mov                 %0, %%"REG_c"  \n\t"

            "mov                 %1, %%"REG_D"  \n\t"

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

            "mov                 %3, %%"REG_b"  \n\t"

            "xor          %%"REG_a", %%"REG_a"  \n\t" // i

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

#ifdef ARCH_X86_64

#define FUNNY_UV_CODE \

            "movl       (%%"REG_b"), %%esi      \n\t"\

            "call               *%4             \n\t"\

            "movl (%%"REG_b", %%"REG_a"), %%esi \n\t"\

            "add          %%"REG_S", %%"REG_c"  \n\t"\

            "add          %%"REG_a", %%"REG_D"  \n\t"\

            "xor          %%"REG_a", %%"REG_a"  \n\t"\

#else

#define FUNNY_UV_CODE \

            "movl       (%%"REG_b"), %%esi      \n\t"\

            "call               *%4             \n\t"\

            "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\

            "add          %%"REG_a", %%"REG_D"  \n\t"\

            "xor          %%"REG_a", %%"REG_a"  \n\t"\

#endif /* ARCH_X86_64 */

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

            "xor          %%"REG_a", %%"REG_a"  \n\t" // i

            "mov                 %5, %%"REG_c"  \n\t" // src

            "mov                 %1, %%"REG_D"  \n\t" // buf1

            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

#if defined(PIC)

            "mov %6, %%"REG_b"    \n\t"

#endif

            :: "m" (src1), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

            "m" (funnyUVCode), "m" (src2)

#if defined(PIC)

            ,"m" (ebxsave)

#endif

            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

             ,"%"REG_b

#endif

            );

            for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--)

            {

                //printf("%d %d %d\n", dstWidth, i, srcW);

                dst[i] = src1[srcW-1]*128;

                dst[i+VOFW] = src2[srcW-1]*128;

            }

        }

        else

        {

#endif /* HAVE_MMX2 */

            long xInc_shr16 = (long) (xInc >> 16);

            uint16_t xInc_mask = xInc & 0xffff;

            asm volatile(

            "xor %%"REG_a", %%"REG_a"               \n\t" // i

            "xor %%"REG_d", %%"REG_d"               \n\t" // xx

            "xorl    %%ecx, %%ecx                   \n\t" // 2*xalpha

            ASMALIGN(4)

            "1:                                     \n\t"

            "mov        %0, %%"REG_S"               \n\t"

            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]

            "movzbl 1(%%"REG_S", %%"REG_d"), %%esi  \n\t" //src[xx+1]

            "subl    %%edi, %%esi                   \n\t" //src[xx+1] - src[xx]

            "imull   %%ecx, %%esi                   \n\t" //(src[xx+1] - src[xx])*2*xalpha

            "shll      $16, %%edi                   \n\t"

            "addl    %%edi, %%esi                   \n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

            "mov        %1, %%"REG_D"               \n\t"

            "shrl       $9, %%esi                   \n\t"

            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"

            "movzbl    (%5, %%"REG_d"), %%edi       \n\t" //src[xx]

            "movzbl   1(%5, %%"REG_d"), %%esi       \n\t" //src[xx+1]

            "subl    %%edi, %%esi                   \n\t" //src[xx+1] - src[xx]

            "imull   %%ecx, %%esi                   \n\t" //(src[xx+1] - src[xx])*2*xalpha

            "shll      $16, %%edi                   \n\t"

            "addl    %%edi, %%esi                   \n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

            "mov        %1, %%"REG_D"               \n\t"

            "shrl       $9, %%esi                   \n\t"

            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"

            "addw       %4, %%cx                    \n\t" //2*xalpha += xInc&0xFF

            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>8 + carry

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

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

            " jb        1b                          \n\t"

/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,

   which is needed to support GCC 4.0. */

#if defined(ARCH_X86_64) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))

            :: "m" (src1), "m" (dst), "g" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#else

            :: "m" (src1), "m" (dst), "m" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#endif

            "r" (src2)

            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

            );

#ifdef HAVE_MMX2

        } //if MMX2 can't be used

#endif

#else

        int i;

        unsigned int xpos=0;

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

        {

            register unsigned int xx=xpos>>16;

            register unsigned int xalpha=(xpos&0xFFFF)>>9;

            dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

            dst[i+VOFW]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

            /* slower

            dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;

            dst[i+VOFW]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;

            */

            xpos+=xInc;

        }

#endif /* defined(ARCH_X86) */

    }

    if(c->srcRange != c->dstRange && !(isRGB(c->dstFormat) || isBGR(c->dstFormat))){

        int i;

        //FIXME all pal and rgb srcFormats could do this convertion as well

        //FIXME all scalers more complex than bilinear could do half of this transform

        if(c->srcRange){

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

                dst[i     ]= (dst[i     ]*1799 + 4081085)>>11; //1469

                dst[i+VOFW]= (dst[i+VOFW]*1799 + 4081085)>>11; //1469

            }

        }else{

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

                dst[i     ]= (FFMIN(dst[i     ],30775)*4663 - 9289992)>>12; //-264

                dst[i+VOFW]= (FFMIN(dst[i+VOFW],30775)*4663 - 9289992)>>12; //-264

            }

        }

    }

}


int avpriv_unlock_avformat(void)

{

    if (lockmgr_cb) {

        if ((*lockmgr_cb)(&avformat_mutex, AV_LOCK_RELEASE))

            return -1;

    }

    return 0;

}


static int disas_neon_ls_insn(CPUState * env, DisasContext *s, uint32_t insn)

{

    int rd, rn, rm;

    int op;

    int nregs;

    int interleave;

    int spacing;

    int stride;

    int size;

    int reg;

    int pass;

    int load;

    int shift;

    int n;

    TCGv addr;

    TCGv tmp;

    TCGv tmp2;

    TCGv_i64 tmp64;

    if (!s->vfp_enabled)

      return 1;

    VFP_DREG_D(rd, insn);

    rn = (insn >> 16) & 0xf;

    rm = insn & 0xf;

    load = (insn & (1 << 21)) != 0;

    addr = tcg_temp_new_i32();

    if ((insn & (1 << 23)) == 0) {

        /* Load store all elements.  */

        op = (insn >> 8) & 0xf;

        size = (insn >> 6) & 3;

        if (op > 10)

            return 1;

        nregs = neon_ls_element_type[op].nregs;

        interleave = neon_ls_element_type[op].interleave;

        spacing = neon_ls_element_type[op].spacing;

        if (size == 3 && (interleave | spacing) != 1)

            return 1;

        load_reg_var(s, addr, rn);

        stride = (1 << size) * interleave;

        for (reg = 0; reg < nregs; reg++) {

            if (interleave > 2 || (interleave == 2 && nregs == 2)) {

                load_reg_var(s, addr, rn);

                tcg_gen_addi_i32(addr, addr, (1 << size) * reg);

            } else if (interleave == 2 && nregs == 4 && reg == 2) {

                load_reg_var(s, addr, rn);

                tcg_gen_addi_i32(addr, addr, 1 << size);

            }

            if (size == 3) {

                if (load) {

                    tmp64 = gen_ld64(addr, IS_USER(s));

                    neon_store_reg64(tmp64, rd);

                    tcg_temp_free_i64(tmp64);

                } else {

                    tmp64 = tcg_temp_new_i64();

                    neon_load_reg64(tmp64, rd);

                    gen_st64(tmp64, addr, IS_USER(s));

                }

                tcg_gen_addi_i32(addr, addr, stride);

            } else {

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

                    if (size == 2) {

                        if (load) {

                            tmp = gen_ld32(addr, IS_USER(s));

                            neon_store_reg(rd, pass, tmp);

                        } else {

                            tmp = neon_load_reg(rd, pass);

                            gen_st32(tmp, addr, IS_USER(s));

                        }

                        tcg_gen_addi_i32(addr, addr, stride);

                    } else if (size == 1) {

                        if (load) {

                            tmp = gen_ld16u(addr, IS_USER(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                            tmp2 = gen_ld16u(addr, IS_USER(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                            tcg_gen_shli_i32(tmp2, tmp2, 16);

                            tcg_gen_or_i32(tmp, tmp, tmp2);

                            tcg_temp_free_i32(tmp2);

                            neon_store_reg(rd, pass, tmp);

                        } else {

                            tmp = neon_load_reg(rd, pass);

                            tmp2 = tcg_temp_new_i32();

                            tcg_gen_shri_i32(tmp2, tmp, 16);

                            gen_st16(tmp, addr, IS_USER(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                            gen_st16(tmp2, addr, IS_USER(s));

                            tcg_gen_addi_i32(addr, addr, stride);

                        }

                    } else /* size == 0 */ {

                        if (load) {

                            TCGV_UNUSED(tmp2);

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

                                tmp = gen_ld8u(addr, IS_USER(s));

                                tcg_gen_addi_i32(addr, addr, stride);

                                if (n == 0) {

                                    tmp2 = tmp;

                                } else {

                                    tcg_gen_shli_i32(tmp, tmp, n * 8);

                                    tcg_gen_or_i32(tmp2, tmp2, tmp);

                                    tcg_temp_free_i32(tmp);

                                }

                            }

                            neon_store_reg(rd, pass, tmp2);

                        } else {

                            tmp2 = neon_load_reg(rd, pass);

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

                                tmp = tcg_temp_new_i32();

                                if (n == 0) {

                                    tcg_gen_mov_i32(tmp, tmp2);

                                } else {

                                    tcg_gen_shri_i32(tmp, tmp2, n * 8);

                                }

                                gen_st8(tmp, addr, IS_USER(s));

                                tcg_gen_addi_i32(addr, addr, stride);

                            }

                            tcg_temp_free_i32(tmp2);

                        }

                    }

                }

            }

            rd += spacing;

        }

        stride = nregs * 8;

    } else {

        size = (insn >> 10) & 3;

        if (size == 3) {

            /* Load single element to all lanes.  */

            int a = (insn >> 4) & 1;

            if (!load) {

                return 1;

            }

            size = (insn >> 6) & 3;

            nregs = ((insn >> 8) & 3) + 1;

            if (size == 3) {

                if (nregs != 4 || a == 0) {

                    return 1;

                }

                /* For VLD4 size==3 a == 1 means 32 bits at 16 byte alignment */

                size = 2;

            }

            if (nregs == 1 && a == 1 && size == 0) {

                return 1;

            }

            if (nregs == 3 && a == 1) {

                return 1;

            }

            load_reg_var(s, addr, rn);

            if (nregs == 1) {

                /* VLD1 to all lanes: bit 5 indicates how many Dregs to write */

                tmp = gen_load_and_replicate(s, addr, size);

                tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 0));

                tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 1));

                if (insn & (1 << 5)) {

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd + 1, 0));

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd + 1, 1));

                }

                tcg_temp_free_i32(tmp);

            } else {

                /* VLD2/3/4 to all lanes: bit 5 indicates register stride */

                stride = (insn & (1 << 5)) ? 2 : 1;

                for (reg = 0; reg < nregs; reg++) {

                    tmp = gen_load_and_replicate(s, addr, size);

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 0));

                    tcg_gen_st_i32(tmp, cpu_env, neon_reg_offset(rd, 1));

                    tcg_temp_free_i32(tmp);

                    tcg_gen_addi_i32(addr, addr, 1 << size);

                    rd += stride;

                }

            }

            stride = (1 << size) * nregs;

        } else {

            /* Single element.  */

            pass = (insn >> 7) & 1;

            switch (size) {

            case 0:

                shift = ((insn >> 5) & 3) * 8;

                stride = 1;

                break;

            case 1:

                shift = ((insn >> 6) & 1) * 16;

                stride = (insn & (1 << 5)) ? 2 : 1;

                break;

            case 2:

                shift = 0;

                stride = (insn & (1 << 6)) ? 2 : 1;

                break;

            default:

                abort();

            }

            nregs = ((insn >> 8) & 3) + 1;

            load_reg_var(s, addr, rn);

            for (reg = 0; reg < nregs; reg++) {

                if (load) {

                    switch (size) {

                    case 0:

                        tmp = gen_ld8u(addr, IS_USER(s));

                        break;

                    case 1:

                        tmp = gen_ld16u(addr, IS_USER(s));

                        break;

                    case 2:

                        tmp = gen_ld32(addr, IS_USER(s));

                        break;

                    default: /* Avoid compiler warnings.  */

                        abort();

                    }

                    if (size != 2) {

                        tmp2 = neon_load_reg(rd, pass);

                        gen_bfi(tmp, tmp2, tmp, shift, size ? 0xffff : 0xff);

                        tcg_temp_free_i32(tmp2);

                    }

                    neon_store_reg(rd, pass, tmp);

                } else { /* Store */

                    tmp = neon_load_reg(rd, pass);

                    if (shift)

                        tcg_gen_shri_i32(tmp, tmp, shift);

                    switch (size) {

                    case 0:

                        gen_st8(tmp, addr, IS_USER(s));

                        break;

                    case 1:

                        gen_st16(tmp, addr, IS_USER(s));

                        break;

                    case 2:

                        gen_st32(tmp, addr, IS_USER(s));

                        break;

                    }

                }

                rd += stride;

                tcg_gen_addi_i32(addr, addr, 1 << size);

            }

            stride = nregs * (1 << size);

        }

    }

    tcg_temp_free_i32(addr);

    if (rm != 15) {

        TCGv base;

        base = load_reg(s, rn);

        if (rm == 13) {

            tcg_gen_addi_i32(base, base, stride);

        } else {

            TCGv index;

            index = load_reg(s, rm);

            tcg_gen_add_i32(base, base, index);

            tcg_temp_free_i32(index);

        }

        store_reg(s, rn, base);

    }

    return 0;

}


vu_queue_empty(VuDev *dev, VuVirtq *vq)

{

    if (vq->shadow_avail_idx != vq->last_avail_idx) {

        return 0;

    }

    return vring_avail_idx(vq) == vq->last_avail_idx;

}


static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)

{

    CURLState *state = NULL;

    int i, j;

    do {

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

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

                if (s->states[i].acb[j])

                    continue;

            if (s->states[i].in_use)

                continue;

            state = &s->states[i];

            state->in_use = 1;

            break;

        }

        if (!state) {

            qemu_mutex_unlock(&s->mutex);

            aio_poll(bdrv_get_aio_context(bs), true);

            qemu_mutex_lock(&s->mutex);

        }

    } while(!state);

    if (!state->curl) {

        state->curl = curl_easy_init();

        if (!state->curl) {

            return NULL;

        }

        curl_easy_setopt(state->curl, CURLOPT_URL, s->url);

        curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,

                         (long) s->sslverify);

        if (s->cookie) {

            curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);

        }

        curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);

        curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,

                         (void *)curl_read_cb);

        curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);

        curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);

        curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);

        curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);

        curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);

        curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);

        curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);

        if (s->username) {

            curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);

        }

        if (s->password) {

            curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);

        }

        if (s->proxyusername) {

            curl_easy_setopt(state->curl,

                             CURLOPT_PROXYUSERNAME, s->proxyusername);

        }

        if (s->proxypassword) {

            curl_easy_setopt(state->curl,

                             CURLOPT_PROXYPASSWORD, s->proxypassword);

        }

        /* Restrict supported protocols to avoid security issues in the more

         * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see

         * CVE-2013-0249.

         *

         * Restricting protocols is only supported from 7.19.4 upwards.

         */

#if LIBCURL_VERSION_NUM >= 0x071304

        curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);

        curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);

#endif

#ifdef DEBUG_VERBOSE

        curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);

#endif

    }

    QLIST_INIT(&state->sockets);

    state->s = s;

    return state;

}


static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id)

{

    SSISlave *ss = SSI_SLAVE(opaque);

    ssi_sd_state *s = (ssi_sd_state *)opaque;

    int i;

    if (version_id != 1)

    s->mode = qemu_get_be32(f);

    s->cmd = qemu_get_be32(f);

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

        s->cmdarg[i] = qemu_get_be32(f);

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

        s->response[i] = qemu_get_be32(f);

    s->arglen = qemu_get_be32(f);

    s->response_pos = qemu_get_be32(f);

    s->stopping = qemu_get_be32(f);

    ss->cs = qemu_get_be32(f);

    return 0;


static inline uint8_t *ram_chunk_end(const RDMALocalBlock *rdma_ram_block,

                                     uint64_t i)

{

    uint8_t *result = ram_chunk_start(rdma_ram_block, i) +

                                         (1UL << RDMA_REG_CHUNK_SHIFT);

    if (result > (rdma_ram_block->local_host_addr + rdma_ram_block->length)) {

        result = rdma_ram_block->local_host_addr + rdma_ram_block->length;

    }

    return result;

}


static int build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,

                      int nb_codes)

{

    uint8_t huff_size[256];

    uint16_t huff_code[256];

    memset(huff_size, 0, sizeof(huff_size));

    build_huffman_codes(huff_size, huff_code, bits_table, val_table);

    return init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2);

}


static int lavfi_read_packet(AVFormatContext *avctx, AVPacket *pkt)

{

    LavfiContext *lavfi = avctx->priv_data;

    double min_pts = DBL_MAX;

    int stream_idx, min_pts_sink_idx = 0;

    AVFilterBufferRef *ref;

    AVPicture pict;

    int ret, i;

    int size = 0;

    /* iterate through all the graph sinks. Select the sink with the

     * minimum PTS */

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

        AVRational tb = lavfi->sinks[i]->inputs[0]->time_base;

        double d;

        int ret;

        if (lavfi->sink_eof[i])

            continue;

        ret = av_buffersink_get_buffer_ref(lavfi->sinks[i],

                                       &ref, AV_BUFFERSINK_FLAG_PEEK);

        if (ret == AVERROR_EOF) {

            av_dlog(avctx, "EOF sink_idx:%d\n", i);

            lavfi->sink_eof[i] = 1;

            continue;

        } else if (ret < 0)

            return ret;

        d = av_rescale_q(ref->pts, tb, AV_TIME_BASE_Q);

        av_dlog(avctx, "sink_idx:%d time:%f\n", i, d);

        if (d < min_pts) {

            min_pts = d;

            min_pts_sink_idx = i;

        }

    }

    if (min_pts == DBL_MAX)

        return AVERROR_EOF;

    av_dlog(avctx, "min_pts_sink_idx:%i\n", min_pts_sink_idx);

    av_buffersink_get_buffer_ref(lavfi->sinks[min_pts_sink_idx], &ref, 0);

    stream_idx = lavfi->sink_stream_map[min_pts_sink_idx];

    if (ref->video) {

        size = avpicture_get_size(ref->format, ref->video->w, ref->video->h);

        if ((ret = av_new_packet(pkt, size)) < 0)

            return ret;

        memcpy(pict.data,     ref->data,     4*sizeof(ref->data[0]));

        memcpy(pict.linesize, ref->linesize, 4*sizeof(ref->linesize[0]));

        avpicture_layout(&pict, ref->format, ref->video->w,

                         ref->video->h, pkt->data, size);

    } else if (ref->audio) {

        size = ref->audio->nb_samples *

            av_get_bytes_per_sample(ref->format) *

            av_get_channel_layout_nb_channels(ref->audio->channel_layout);

        if ((ret = av_new_packet(pkt, size)) < 0)

            return ret;

        memcpy(pkt->data, ref->data[0], size);

    }

    if (ref->metadata) {

        uint8_t *metadata;

        AVDictionaryEntry *e = NULL;

        AVBPrint meta_buf;

        av_bprint_init(&meta_buf, 0, AV_BPRINT_SIZE_UNLIMITED);

        while ((e = av_dict_get(ref->metadata, "", e, AV_DICT_IGNORE_SUFFIX))) {

            av_bprintf(&meta_buf, "%s", e->key);

            av_bprint_chars(&meta_buf, '\0', 1);

            av_bprintf(&meta_buf, "%s", e->value);

            av_bprint_chars(&meta_buf, '\0', 1);

        }

        if (!av_bprint_is_complete(&meta_buf) ||

            !(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA,

                                                 meta_buf.len))) {

            av_bprint_finalize(&meta_buf, NULL);

            return AVERROR(ENOMEM);

        }

        memcpy(metadata, meta_buf.str, meta_buf.len);

        av_bprint_finalize(&meta_buf, NULL);

    }

    pkt->stream_index = stream_idx;

    pkt->pts = ref->pts;

    pkt->pos = ref->pos;

    pkt->size = size;

    avfilter_unref_buffer(ref);

    return size;

}


static inline void qtrle_decode_2n4bpp(QtrleContext *s, int stream_ptr,

                             int row_ptr, int lines_to_change, int bpp)

{

    int rle_code, i;

    int pixel_ptr;

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

    unsigned char pi[16];  /* 16 palette indices */

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

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

    int num_pixels = (bpp == 4) ? 8 : 16;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (num_pixels * (s->buf[stream_ptr++] - 1));

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (num_pixels * (s->buf[stream_ptr++] - 1));

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                /* get the next 4 bytes from the stream, treat them as palette

                 * indexes, and output them rle_code times */

                CHECK_STREAM_PTR(4);

                for (i = num_pixels-1; i >= 0; i--) {

                    pi[num_pixels-1-i] = (s->buf[stream_ptr] >> ((i*bpp) & 0x07)) & ((1<<bpp)-1);

                    stream_ptr+= ((i & ((num_pixels>>2)-1)) == 0);

                }

                CHECK_PIXEL_PTR(rle_code * num_pixels);

                while (rle_code--) {

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

                        rgb[pixel_ptr++] = pi[i];

                }

            } else {

                /* copy the same pixel directly to output 4 times */

                rle_code *= 4;

                CHECK_STREAM_PTR(rle_code);

                CHECK_PIXEL_PTR(rle_code*(num_pixels>>2));

                while (rle_code--) {

                    if(bpp == 4) {

                        rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 4) & 0x0f;

                        rgb[pixel_ptr++] = (s->buf[stream_ptr++]) & 0x0f;

                    } else {

                        rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 6) & 0x03;

                        rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 4) & 0x03;

                        rgb[pixel_ptr++] = ((s->buf[stream_ptr]) >> 2) & 0x03;

                        rgb[pixel_ptr++] = (s->buf[stream_ptr++]) & 0x03;

                    }

                }

            }

        }

        row_ptr += row_inc;

    }

}


static void display_picref(AVFilterBufferRef *picref, AVRational time_base)

{

    int x, y;

    uint8_t *p0, *p;

    int64_t delay;

    if (picref->pts != AV_NOPTS_VALUE) {

        if (last_pts != AV_NOPTS_VALUE) {

            /* sleep roughly the right amount of time;

             * usleep is in microseconds, just like AV_TIME_BASE. */

            delay = av_rescale_q(picref->pts - last_pts,

                                 time_base, AV_TIME_BASE_Q);

            if (delay > 0 && delay < 1000000)

                usleep(delay);

        }

        last_pts = picref->pts;

    }

    /* Trivial ASCII grayscale display. */

    p0 = picref->data[0];

    puts("\033c");

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

        p = p0;

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

            putchar(" .-+#"[*(p++) / 52]);

        putchar('\n');

        p0 += picref->linesize[0];

    }

    fflush(stdout);

}


static int colo_packet_compare_udp(Packet *spkt, Packet *ppkt)

{

    int ret;

    int network_header_length = ppkt->ip->ip_hl * 4;

    trace_colo_compare_main("compare udp");

    /*

     * Because of ppkt and spkt are both in the same connection,

     * The ppkt's src ip, dst ip, src port, dst port, ip_proto all are

     * same with spkt. In addition, IP header's Identification is a random

     * field, we can handle it in IP fragmentation function later.

     * COLO just concern the response net packet payload from primary guest

     * and secondary guest are same or not, So we ignored all IP header include

     * other field like TOS,TTL,IP Checksum. we only need to compare

     * the ip payload here.

     */

    ret = colo_packet_compare_common(ppkt, spkt,

                                     network_header_length + ETH_HLEN);

    if (ret) {

        trace_colo_compare_udp_miscompare("primary pkt size", ppkt->size);

        trace_colo_compare_udp_miscompare("Secondary pkt size", spkt->size);

        if (trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) {

            qemu_hexdump((char *)ppkt->data, stderr, "colo-compare pri pkt",

                         ppkt->size);

            qemu_hexdump((char *)spkt->data, stderr, "colo-compare sec pkt",

                         spkt->size);

        }

    }

    return ret;

}


void vga_mem_writeb(VGACommonState *s, hwaddr addr, uint32_t val)

{

    int memory_map_mode, plane, write_mode, b, func_select, mask;

    uint32_t write_mask, bit_mask, set_mask;

#ifdef DEBUG_VGA_MEM

    printf("vga: [0x" TARGET_FMT_plx "] = 0x%02x\n", addr, val);

#endif

    /* convert to VGA memory offset */

    memory_map_mode = (s->gr[VGA_GFX_MISC] >> 2) & 3;

    addr &= 0x1ffff;

    switch(memory_map_mode) {

    case 0:

        break;

    case 1:

        if (addr >= 0x10000)

            return;

        addr += s->bank_offset;

        break;

    case 2:

        addr -= 0x10000;

        if (addr >= 0x8000)

            return;

        break;

    default:

    case 3:

        addr -= 0x18000;

        if (addr >= 0x8000)

            return;

        break;

    }

    if (s->sr[VGA_SEQ_MEMORY_MODE] & VGA_SR04_CHN_4M) {

        /* chain 4 mode : simplest access */

        plane = addr & 3;

        mask = (1 << plane);

        if (s->sr[VGA_SEQ_PLANE_WRITE] & mask) {

            assert(addr < s->vram_size);

            s->vram_ptr[addr] = val;

#ifdef DEBUG_VGA_MEM

            printf("vga: chain4: [0x" TARGET_FMT_plx "]\n", addr);

#endif

            s->plane_updated |= mask; /* only used to detect font change */

            memory_region_set_dirty(&s->vram, addr, 1);

        }

    } else if (s->gr[VGA_GFX_MODE] & 0x10) {

        /* odd/even mode (aka text mode mapping) */

        plane = (s->gr[VGA_GFX_PLANE_READ] & 2) | (addr & 1);

        mask = (1 << plane);

        if (s->sr[VGA_SEQ_PLANE_WRITE] & mask) {

            addr = ((addr & ~1) << 1) | plane;

            if (addr >= s->vram_size) {

                return;

            }

            s->vram_ptr[addr] = val;

#ifdef DEBUG_VGA_MEM

            printf("vga: odd/even: [0x" TARGET_FMT_plx "]\n", addr);

#endif

            s->plane_updated |= mask; /* only used to detect font change */

            memory_region_set_dirty(&s->vram, addr, 1);

        }

    } else {

        /* standard VGA latched access */

        write_mode = s->gr[VGA_GFX_MODE] & 3;

        switch(write_mode) {

        default:

        case 0:

            /* rotate */

            b = s->gr[VGA_GFX_DATA_ROTATE] & 7;

            val = ((val >> b) | (val << (8 - b))) & 0xff;

            val |= val << 8;

            val |= val << 16;

            /* apply set/reset mask */

            set_mask = mask16[s->gr[VGA_GFX_SR_ENABLE]];

            val = (val & ~set_mask) |

                (mask16[s->gr[VGA_GFX_SR_VALUE]] & set_mask);

            bit_mask = s->gr[VGA_GFX_BIT_MASK];

            break;

        case 1:

            val = s->latch;

            goto do_write;

        case 2:

            val = mask16[val & 0x0f];

            bit_mask = s->gr[VGA_GFX_BIT_MASK];

            break;

        case 3:

            /* rotate */

            b = s->gr[VGA_GFX_DATA_ROTATE] & 7;

            val = (val >> b) | (val << (8 - b));

            bit_mask = s->gr[VGA_GFX_BIT_MASK] & val;

            val = mask16[s->gr[VGA_GFX_SR_VALUE]];

            break;

        }

        /* apply logical operation */

        func_select = s->gr[VGA_GFX_DATA_ROTATE] >> 3;

        switch(func_select) {

        case 0:

        default:

            /* nothing to do */

            break;

        case 1:

            /* and */

            val &= s->latch;

            break;

        case 2:

            /* or */

            val |= s->latch;

            break;

        case 3:

            /* xor */

            val ^= s->latch;

            break;

        }

        /* apply bit mask */

        bit_mask |= bit_mask << 8;

        bit_mask |= bit_mask << 16;

        val = (val & bit_mask) | (s->latch & ~bit_mask);

    do_write:

        /* mask data according to sr[2] */

        mask = s->sr[VGA_SEQ_PLANE_WRITE];

        s->plane_updated |= mask; /* only used to detect font change */

        write_mask = mask16[mask];

        if (addr * sizeof(uint32_t) >= s->vram_size) {

            return;

        }

        ((uint32_t *)s->vram_ptr)[addr] =

            (((uint32_t *)s->vram_ptr)[addr] & ~write_mask) |

            (val & write_mask);

#ifdef DEBUG_VGA_MEM

        printf("vga: latch: [0x" TARGET_FMT_plx "] mask=0x%08x val=0x%08x\n",

               addr * 4, write_mask, val);

#endif

        memory_region_set_dirty(&s->vram, addr << 2, sizeof(uint32_t));

    }

}


static int read_channel_params(MLPDecodeContext *m, unsigned int substr,

                               GetBitContext *gbp, unsigned int ch)

{

    SubStream *s = &m->substream[substr];

    ChannelParams *cp = &s->channel_params[ch];

    FilterParams *fir = &cp->filter_params[FIR];

    FilterParams *iir = &cp->filter_params[IIR];

    int ret;

    if (s->param_presence_flags & PARAM_FIR)

        if (get_bits1(gbp))

            if ((ret = read_filter_params(m, gbp, substr, ch, FIR)) < 0)

                return ret;

    if (s->param_presence_flags & PARAM_IIR)

        if (get_bits1(gbp))

            if ((ret = read_filter_params(m, gbp, substr, ch, IIR)) < 0)

                return ret;

    if (fir->order + iir->order > 8) {

        av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");

        return AVERROR_INVALIDDATA;

    }

    if (fir->order && iir->order &&

        fir->shift != iir->shift) {

        av_log(m->avctx, AV_LOG_ERROR,

                "FIR and IIR filters must use the same precision.\n");

        return AVERROR_INVALIDDATA;

    }

    /* The FIR and IIR filters must have the same precision.

     * To simplify the filtering code, only the precision of the

     * FIR filter is considered. If only the IIR filter is employed,

     * the FIR filter precision is set to that of the IIR filter, so

     * that the filtering code can use it. */

    if (!fir->order && iir->order)

        fir->shift = iir->shift;

    if (s->param_presence_flags & PARAM_HUFFOFFSET)

        if (get_bits1(gbp))

            cp->huff_offset = get_sbits(gbp, 15);

    cp->codebook  = get_bits(gbp, 2);

    cp->huff_lsbs = get_bits(gbp, 5);

    if (cp->huff_lsbs > 24) {

        av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");

        cp->huff_lsbs = 0;

        return AVERROR_INVALIDDATA;

    }

    cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);

    return 0;

}


static int wsvqa_read_packet(AVFormatContext *s,

                             AVPacket *pkt)

{

    WsVqaDemuxContext *wsvqa = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret = -1;

    unsigned char preamble[VQA_PREAMBLE_SIZE];

    unsigned int chunk_type;

    unsigned int chunk_size;

    int skip_byte;

    while (avio_read(pb, preamble, VQA_PREAMBLE_SIZE) == VQA_PREAMBLE_SIZE) {

        chunk_type = AV_RB32(&preamble[0]);

        chunk_size = AV_RB32(&preamble[4]);

        skip_byte = chunk_size & 0x01;

        if ((chunk_type == SND0_TAG) || (chunk_type == SND1_TAG) ||

            (chunk_type == SND2_TAG) || (chunk_type == VQFR_TAG)) {

            ret= av_get_packet(pb, pkt, chunk_size);

            if (ret<0)

                return AVERROR(EIO);

            switch (chunk_type) {

            case SND0_TAG:

            case SND1_TAG:

            case SND2_TAG:

                if (wsvqa->audio_stream_index == -1) {

                    AVStream *st = avformat_new_stream(s, NULL);

                    if (!st)

                        return AVERROR(ENOMEM);

                    wsvqa->audio_stream_index = st->index;

                    if (!wsvqa->sample_rate)

                        wsvqa->sample_rate = 22050;

                    if (!wsvqa->channels)

                        wsvqa->channels = 1;

                    if (!wsvqa->bps)

                        wsvqa->bps = 8;

                    st->codec->sample_rate = wsvqa->sample_rate;

                    st->codec->bits_per_coded_sample = wsvqa->bps;

                    st->codec->channels = wsvqa->channels;

                    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

                    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

                    switch (chunk_type) {

                    case SND0_TAG:

                        if (wsvqa->bps == 16)

                            st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;

                        else

                            st->codec->codec_id = AV_CODEC_ID_PCM_U8;

                        break;

                    case SND1_TAG:

                        st->codec->codec_id = AV_CODEC_ID_WESTWOOD_SND1;

                        break;

                    case SND2_TAG:

                        st->codec->codec_id = AV_CODEC_ID_ADPCM_IMA_WS;

                        st->codec->extradata_size = 2;

                        st->codec->extradata = av_mallocz(2 + FF_INPUT_BUFFER_PADDING_SIZE);

                        if (!st->codec->extradata)

                            return AVERROR(ENOMEM);

                        AV_WL16(st->codec->extradata, wsvqa->version);

                        break;

                    }

                }

                pkt->stream_index = wsvqa->audio_stream_index;

                switch (chunk_type) {

                case SND1_TAG:

                    /* unpacked size is stored in header */

                    pkt->duration = AV_RL16(pkt->data) / wsvqa->channels;

                    break;

                case SND2_TAG:

                    /* 2 samples/byte, 1 or 2 samples per frame depending on stereo */

                    pkt->duration = (chunk_size * 2) / wsvqa->channels;

                    break;

                }

                break;

            case VQFR_TAG:

                pkt->stream_index = wsvqa->video_stream_index;

                pkt->duration = 1;

                break;

            }

            /* stay on 16-bit alignment */

            if (skip_byte)

                avio_skip(pb, 1);

            return ret;

        } else {

            switch(chunk_type){

            case CMDS_TAG:

                break;

            default:

                av_log(s, AV_LOG_INFO, "Skipping unknown chunk 0x%08X\n", chunk_type);

            }

            avio_skip(pb, chunk_size + skip_byte);

        }

    }

    return ret;

}


static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,

                         const char *filt_name, const char *args, void *log_ctx)

{

    AVFilter *filt;

    char inst_name[30];

    char tmp_args[256];

    int ret;

    snprintf(inst_name, sizeof(inst_name), "Parsed_%s_%d", filt_name, index);

    filt = avfilter_get_by_name(filt_name);

    if (!filt) {

        av_log(log_ctx, AV_LOG_ERROR,

               "No such filter: '%s'\n", filt_name);

        return AVERROR(EINVAL);

    }

    *filt_ctx = avfilter_graph_alloc_filter(ctx, filt, inst_name);

    if (!*filt_ctx) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Error creating filter '%s'\n", filt_name);

        return AVERROR(ENOMEM);

    }

    if (!strcmp(filt_name, "scale") && args && !strstr(args, "flags") &&

        ctx->scale_sws_opts) {

        snprintf(tmp_args, sizeof(tmp_args), "%s:%s",

                 args, ctx->scale_sws_opts);

        args = tmp_args;

    }

    ret = avfilter_init_str(*filt_ctx, args);

    if (ret < 0) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Error initializing filter '%s'", filt_name);

        if (args)

            av_log(log_ctx, AV_LOG_ERROR, " with args '%s'", args);

        av_log(log_ctx, AV_LOG_ERROR, "\n");

        return ret;

    }

    return 0;

}


static void flush_packet(AVFormatContext *ctx, int stream_index,

                         int64_t pts, int64_t dts, int64_t scr)

{

    MpegMuxContext *s = ctx->priv_data;

    StreamInfo *stream = ctx->streams[stream_index]->priv_data;

    uint8_t *buf_ptr;

    int size, payload_size, startcode, id, stuffing_size, i, header_len;

    int packet_size;

    uint8_t buffer[128];

    int zero_trail_bytes = 0;

    int pad_packet_bytes = 0;

    id = stream->id;

#if 0

    printf("packet ID=%2x PTS=%0.3f\n",

           id, pts / 90000.0);

#endif

    buf_ptr = buffer;

    if (((s->packet_number % s->pack_header_freq) == 0)) {

        /* output pack and systems header if needed */

        size = put_pack_header(ctx, buf_ptr, scr);

        buf_ptr += size;

        if (s->is_vcd) {

            /* there is exactly one system header for each stream in a VCD MPEG,

               One in the very first video packet and one in the very first

               audio packet (see VCD standard p. IV-7 and IV-8).*/

            if (stream->packet_number==0) {

                size = put_system_header(ctx, buf_ptr, id);

                buf_ptr += size;

            }

        } else {

            if ((s->packet_number % s->system_header_freq) == 0) {

                size = put_system_header(ctx, buf_ptr, 0);

                buf_ptr += size;

            }

        }

    }

    size = buf_ptr - buffer;

    put_buffer(&ctx->pb, buffer, size);

    packet_size = s->packet_size - size;

    if (s->is_vcd && id == AUDIO_ID)

        /* The VCD standard demands that 20 zero bytes follow

           each audio pack (see standard p. IV-8).*/

        zero_trail_bytes += 20;

    if (s->is_vcd && stream->packet_number==0) {

        /* the first pack of each stream contains only the pack header,

           the system header and lots of padding (see VCD standard p. IV-6).

           In the case of an audio pack, 20 zero bytes are also added at

           the end.*/

        pad_packet_bytes = packet_size - zero_trail_bytes;

    }

    packet_size -= pad_packet_bytes + zero_trail_bytes;

    if (packet_size > 0) {

        /* packet header size */

        packet_size -= 6;

        /* packet header */

        if (s->is_mpeg2) {

            header_len = 3;

        } else {

            header_len = 0;

        }

        if (pts != AV_NOPTS_VALUE) {

            if (dts != pts)

                header_len += 5 + 5;

            else

                header_len += 5;

        } else {

            if (!s->is_mpeg2)

                header_len++;

        }

        payload_size = packet_size - header_len;

        if (id < 0xc0) {

            startcode = PRIVATE_STREAM_1;

            payload_size -= 4;

            if (id >= 0xa0)

                payload_size -= 3;

        } else {

            startcode = 0x100 + id;

        }

        stuffing_size = payload_size - stream->buffer_ptr;

        if (stuffing_size < 0)

            stuffing_size = 0;

        put_be32(&ctx->pb, startcode);

        put_be16(&ctx->pb, packet_size);

        if (!s->is_mpeg2)

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

                put_byte(&ctx->pb, 0xff);

        if (s->is_mpeg2) {

            put_byte(&ctx->pb, 0x80); /* mpeg2 id */

            if (pts != AV_NOPTS_VALUE) {

                if (dts != pts) {

                    put_byte(&ctx->pb, 0xc0); /* flags */

                    put_byte(&ctx->pb, header_len - 3 + stuffing_size);

                    put_timestamp(&ctx->pb, 0x03, pts);

                    put_timestamp(&ctx->pb, 0x01, dts);

                } else {

                    put_byte(&ctx->pb, 0x80); /* flags */

                    put_byte(&ctx->pb, header_len - 3 + stuffing_size);

                    put_timestamp(&ctx->pb, 0x02, pts);

                }

            } else {

                put_byte(&ctx->pb, 0x00); /* flags */

                put_byte(&ctx->pb, header_len - 3 + stuffing_size);

            }

        } else {

            if (pts != AV_NOPTS_VALUE) {

                if (dts != pts) {

                    put_timestamp(&ctx->pb, 0x03, pts);

                    put_timestamp(&ctx->pb, 0x01, dts);

                } else {

                    put_timestamp(&ctx->pb, 0x02, pts);

                }

            } else {

                put_byte(&ctx->pb, 0x0f);

            }

        }

        if (startcode == PRIVATE_STREAM_1) {

            put_byte(&ctx->pb, id);

            if (id >= 0xa0) {

                /* LPCM (XXX: check nb_frames) */

                put_byte(&ctx->pb, 7);

                put_be16(&ctx->pb, 4); /* skip 3 header bytes */

                put_byte(&ctx->pb, stream->lpcm_header[0]);

                put_byte(&ctx->pb, stream->lpcm_header[1]);

                put_byte(&ctx->pb, stream->lpcm_header[2]);

            } else {

                /* AC3 */

                put_byte(&ctx->pb, stream->nb_frames);

                put_be16(&ctx->pb, stream->frame_start_offset);

            }

        }

        if (s->is_mpeg2)

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

                put_byte(&ctx->pb, 0xff);

        /* output data */

        put_buffer(&ctx->pb, stream->buffer, payload_size - stuffing_size);

    }

    if (pad_packet_bytes > 0)

        put_padding_packet(ctx,&ctx->pb, pad_packet_bytes);

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

        put_byte(&ctx->pb, 0x00);

    put_flush_packet(&ctx->pb);

    s->packet_number++;

    stream->packet_number++;

    stream->nb_frames = 0;

    stream->frame_start_offset = 0;

}


void ff_xvmc_init_block(MpegEncContext *s)

{

    struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)s->current_picture.f->data[2];

    assert(render && render->xvmc_id == AV_XVMC_ID);

    s->block = (int16_t (*)[64])(render->data_blocks + render->next_free_data_block_num * 64);

}


static inline void set_p_mv_tables(MpegEncContext * s, int mx, int my)

{

    const int xy= s->mb_x + 1 + (s->mb_y + 1)*(s->mb_width + 2);

    s->p_mv_table[xy][0] = mx;

    s->p_mv_table[xy][1] = my;

    /* has allready been set to the 4 MV if 4MV is done */

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

        int mot_xy= s->block_index[0];

        s->motion_val[mot_xy  ][0]= mx;

        s->motion_val[mot_xy  ][1]= my;

        s->motion_val[mot_xy+1][0]= mx;

        s->motion_val[mot_xy+1][1]= my;

        mot_xy += s->block_wrap[0];

        s->motion_val[mot_xy  ][0]= mx;

        s->motion_val[mot_xy  ][1]= my;

        s->motion_val[mot_xy+1][0]= mx;

        s->motion_val[mot_xy+1][1]= my;

    }

}


static int hds_flush(AVFormatContext *s, OutputStream *os, int final,

                     int64_t end_ts)

{

    HDSContext *c = s->priv_data;

    int i, ret = 0;

    char target_filename[1024];

    int index = s->streams[os->first_stream]->id;

    if (!os->packets_written)

        return 0;

    avio_flush(os->ctx->pb);

    os->packets_written = 0;

    close_file(os);

    snprintf(target_filename, sizeof(target_filename),

             "%s/stream%dSeg1-Frag%d", s->filename, index, os->fragment_index);

    ret = ff_rename(os->temp_filename, target_filename);

    if (ret < 0)

        return ret;

    add_fragment(os, target_filename, os->frag_start_ts, end_ts - os->frag_start_ts);

    if (!final) {

        ret = init_file(s, os, end_ts);

        if (ret < 0)

            return ret;

    }

    if (c->window_size || (final && c->remove_at_exit)) {

        int remove = os->nb_fragments - c->window_size - c->extra_window_size;

        if (final && c->remove_at_exit)

            remove = os->nb_fragments;

        if (remove > 0) {

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

                unlink(os->fragments[i]->file);

                av_free(os->fragments[i]);

            }

            os->nb_fragments -= remove;

            memmove(os->fragments, os->fragments + remove,

                    os->nb_fragments * sizeof(*os->fragments));

        }

    }

    if (ret >= 0)

        ret = write_abst(s, os, final);

    return ret;

}