static inline void gen_movcf_d (DisasContext *ctx, int fs, int fd, int cc, int tf)

{

    int cond;

    TCGv_i32 t0 = tcg_temp_new_i32();

    TCGv_i64 fp0;

    int l1 = gen_new_label();

    if (tf)

        cond = TCG_COND_EQ;

    else

        cond = TCG_COND_NE;

    tcg_gen_andi_i32(t0, fpu_fcr31, 1 << get_fp_bit(cc));

    tcg_gen_brcondi_i32(cond, t0, 0, l1);

    tcg_temp_free_i32(t0);

    fp0 = tcg_temp_new_i64();

    gen_load_fpr64(ctx, fp0, fs);

    gen_store_fpr64(ctx, fp0, fd);

    tcg_temp_free_i64(fp0);

    gen_set_label(l1);

}


int kvm_irqchip_remove_irqfd(KVMState *s, int fd, int virq)

{

    return -ENOSYS;

}


static void noop_conv (st_sample_t *dst, const void *src,

                       int samples, volume_t *vol)

{

    (void) src;

    (void) dst;

    (void) samples;

    (void) vol;

}


static void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)

{

    CirrusVGAState *s = opaque;

    int index;

    /* check port range access depending on color/monochrome mode */

    if ((addr >= 0x3b0 && addr <= 0x3bf && (s->msr & MSR_COLOR_EMULATION))

	|| (addr >= 0x3d0 && addr <= 0x3df

	    && !(s->msr & MSR_COLOR_EMULATION)))

	return;

#ifdef DEBUG_VGA

    printf("VGA: write addr=0x%04x data=0x%02x\n", addr, val);

#endif

    switch (addr) {

    case 0x3c0:

	if (s->ar_flip_flop == 0) {

	    val &= 0x3f;

	    s->ar_index = val;

	} else {

	    index = s->ar_index & 0x1f;

	    switch (index) {

	    case 0x00 ... 0x0f:

		s->ar[index] = val & 0x3f;

		break;

	    case 0x10:

		s->ar[index] = val & ~0x10;

		break;

	    case 0x11:

		s->ar[index] = val;

		break;

	    case 0x12:

		s->ar[index] = val & ~0xc0;

		break;

	    case 0x13:

		s->ar[index] = val & ~0xf0;

		break;

	    case 0x14:

		s->ar[index] = val & ~0xf0;

		break;

	    default:

		break;

	    }

	}

	s->ar_flip_flop ^= 1;

	break;

    case 0x3c2:

	s->msr = val & ~0x10;

	break;

    case 0x3c4:

	s->sr_index = val;

	break;

    case 0x3c5:

	if (cirrus_hook_write_sr(s, s->sr_index, val))

	    break;

#ifdef DEBUG_VGA_REG

	printf("vga: write SR%x = 0x%02x\n", s->sr_index, val);

#endif

	s->sr[s->sr_index] = val & sr_mask[s->sr_index];

	break;

    case 0x3c6:

	cirrus_write_hidden_dac(s, val);

	break;

    case 0x3c7:

	s->dac_read_index = val;

	s->dac_sub_index = 0;

	s->dac_state = 3;

	break;

    case 0x3c8:

	s->dac_write_index = val;

	s->dac_sub_index = 0;

	s->dac_state = 0;

	break;

    case 0x3c9:

	if (cirrus_hook_write_palette(s, val))

	    break;

	s->dac_cache[s->dac_sub_index] = val;

	if (++s->dac_sub_index == 3) {

	    memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);

	    s->dac_sub_index = 0;

	    s->dac_write_index++;

	}

	break;

    case 0x3ce:

	s->gr_index = val;

	break;

    case 0x3cf:

	if (cirrus_hook_write_gr(s, s->gr_index, val))

	    break;

#ifdef DEBUG_VGA_REG

	printf("vga: write GR%x = 0x%02x\n", s->gr_index, val);

#endif

	s->gr[s->gr_index] = val & gr_mask[s->gr_index];

	break;

    case 0x3b4:

    case 0x3d4:

	s->cr_index = val;

	break;

    case 0x3b5:

    case 0x3d5:

	if (cirrus_hook_write_cr(s, s->cr_index, val))

	    break;

#ifdef DEBUG_VGA_REG

	printf("vga: write CR%x = 0x%02x\n", s->cr_index, val);

#endif

	/* handle CR0-7 protection */

	if ((s->cr[11] & 0x80) && s->cr_index <= 7) {

	    /* can always write bit 4 of CR7 */

	    if (s->cr_index == 7)

		s->cr[7] = (s->cr[7] & ~0x10) | (val & 0x10);

	    return;

	}

	switch (s->cr_index) {

	case 0x01:		/* horizontal display end */

	case 0x07:

	case 0x09:

	case 0x0c:

	case 0x0d:

	case 0x12:		/* veritcal display end */

	    s->cr[s->cr_index] = val;

	    break;

	default:

	    s->cr[s->cr_index] = val;

	    break;

	}

	break;

    case 0x3ba:

    case 0x3da:

	s->fcr = val & 0x10;

	break;

    }

}


static int xen_pt_cmd_reg_read(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                               uint16_t *value, uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint16_t valid_emu_mask = 0;

    uint16_t emu_mask = reg->emu_mask;

    if (s->is_virtfn) {

        emu_mask |= PCI_COMMAND_MEMORY;

    }

    /* emulate word register */

    valid_emu_mask = emu_mask & valid_mask;

    *value = XEN_PT_MERGE_VALUE(*value, cfg_entry->data, ~valid_emu_mask);

    return 0;

}


static int virtio_net_has_buffers(VirtIONet *n, int bufsize)

{

    if (virtio_queue_empty(n->rx_vq) ||

        (n->mergeable_rx_bufs &&

         !virtqueue_avail_bytes(n->rx_vq, bufsize, 0))) {

        virtio_queue_set_notification(n->rx_vq, 1);

        return 0;

    }

    virtio_queue_set_notification(n->rx_vq, 0);

    return 1;

}


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

{

    c->chapter_track = avio_rb32(pb);

    return 0;

}


static void qbus_initfn(Object *obj)

{

    BusState *bus = BUS(obj);

    QTAILQ_INIT(&bus->children);

    object_property_add_link(obj, QDEV_HOTPLUG_HANDLER_PROPERTY,

                             TYPE_HOTPLUG_HANDLER,

                             (Object **)&bus->hotplug_handler, NULL);

    object_property_add_bool(obj, "realized",

                             bus_get_realized, bus_set_realized, NULL);

}


static void final(Real144_internal *glob, short *i1, short *i2, void *out,

                  int *statbuf, int len)

{

    int x, sum;

    int buffer[10];

    short *ptr;

    short *ptr2;

    memcpy(glob->work, statbuf,20);

    memcpy(glob->work + 10, i2, len * 2);

    buffer[9] = i1[0];

    buffer[8] = i1[1];

    buffer[7] = i1[2];

    buffer[6] = i1[3];

    buffer[5] = i1[4];

    buffer[4] = i1[5];

    buffer[3] = i1[6];

    buffer[2] = i1[7];

    buffer[1] = i1[8];

    buffer[0] = i1[9];

    ptr2 = (ptr = glob->work) + len;

    while (ptr < ptr2) {

        for(sum=0, x=0; x<=9; x++)

            sum += buffer[x] * (ptr[x]);

        sum = sum >> 12;

        x = ptr[10] - sum;

        if (x<-32768 || x>32767) {

            memset(out, 0, len * 2);

            memset(statbuf, 0, 20);

            return;

        }

        ptr[10] = x;

        ptr++;

    }

    memcpy(out, ptr+10 - len, len * 2);

    memcpy(statbuf, ptr, 20);

}


static ssize_t mipsnet_receive(NetClientState *nc, const uint8_t *buf, size_t size)

{

    MIPSnetState *s = qemu_get_nic_opaque(nc);

    trace_mipsnet_receive(size);

    if (!mipsnet_can_receive(nc))

    s->busy = 1;

    /* Just accept everything. */

    /* Write packet data. */

    memcpy(s->rx_buffer, buf, size);

    s->rx_count = size;

    s->rx_read = 0;

    /* Now we can signal we have received something. */

    s->intctl |= MIPSNET_INTCTL_RXDONE;

    mipsnet_update_irq(s);

    return size;


static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,

                                                     int size)

{

    AVCodecContext   *avctx = opaque;

    VAAPIEncodeContext *ctx = avctx->priv_data;

    VABufferID buffer_id;

    VAStatus vas;

    AVBufferRef *ref;

    // The output buffer size is fixed, so it needs to be large enough

    // to hold the largest possible compressed frame.  We assume here

    // that the uncompressed frame plus some header data is an upper

    // bound on that.

    vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,

                         VAEncCodedBufferType,

                         3 * ctx->aligned_width * ctx->aligned_height +

                         (1 << 16), 1, 0, &buffer_id);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "

               "output buffer: %d (%s).\n", vas, vaErrorStr(vas));

        return NULL;

    }

    av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);

    ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,

                           sizeof(buffer_id),

                           &vaapi_encode_free_output_buffer,

                           avctx, AV_BUFFER_FLAG_READONLY);

    if (!ref) {

        vaDestroyBuffer(ctx->hwctx->display, buffer_id);

        return NULL;

    }

    return ref;

}


static struct omap_tipb_bridge_s *omap_tipb_bridge_init(

    MemoryRegion *memory, target_phys_addr_t base,

    qemu_irq abort_irq, omap_clk clk)

{

    struct omap_tipb_bridge_s *s = (struct omap_tipb_bridge_s *)

            g_malloc0(sizeof(struct omap_tipb_bridge_s));

    s->abort = abort_irq;

    omap_tipb_bridge_reset(s);

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

                          "omap-tipb-bridge", 0x100);

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

    return s;

}


void thread_pool_submit(ThreadPool *pool, ThreadPoolFunc *func, void *arg)

{

    thread_pool_submit_aio(pool, func, arg, NULL, NULL);

}


int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)

{

    BlockDriver *drv = bs->drv;

    if (!drv) {

        return -ENOMEDIUM;

    } else if (drv->bdrv_save_vmstate) {

        return drv->bdrv_save_vmstate(bs, qiov, pos);

    } else if (bs->file) {

        return bdrv_writev_vmstate(bs->file, qiov, pos);

    }

    return -ENOTSUP;

}


static int local_statfs(FsContext *s, V9fsPath *fs_path, struct statfs *stbuf)

{

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    return statfs(rpath(s, path, buffer), stbuf);

}


static void init_multbl2(uint8_t tbl[1024], const int c[4],

                         const uint8_t *log8, const uint8_t *alog8,

                         const uint8_t *sbox)

{

    int i, j;

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

        int x = sbox[i >> 2];

        if (x)

            tbl[i] = alog8[log8[x] + log8[c[i & 3]]];

    }

#if !CONFIG_SMALL

    for (j = 256; j < 1024; j++)

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

            tbl[4*j + i] = tbl[4*j + ((i - 1) & 3) - 1024];

#endif

}


static int kvm_get_msr(CPUState *env, struct kvm_msr_entry *msrs, int n)

{

    struct kvm_msrs *kmsrs = qemu_malloc(sizeof *kmsrs + n * sizeof *msrs);

    int r;

    kmsrs->nmsrs = n;

    memcpy(kmsrs->entries, msrs, n * sizeof *msrs);

    r = kvm_vcpu_ioctl(env, KVM_GET_MSRS, kmsrs);

    memcpy(msrs, kmsrs->entries, n * sizeof *msrs);

    free(kmsrs);

    return r;

}


static void do_balloon(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

    ram_addr_t target = value;

    qemu_balloon(target << 20);

}


static void blur(uint8_t       *dst, const int dst_linesize,

                 const uint8_t *src, const int src_linesize,

                 const int w, const int h, FilterParam *fp)

{

    int x, y;

    FilterParam f = *fp;

    const int radius = f.dist_width/2;

    const uint8_t * const src2[NB_PLANES] = { src };

    int          src2_linesize[NB_PLANES] = { src_linesize };

    uint8_t     *dst2[NB_PLANES] = { f.pre_filter_buf };

    int dst2_linesize[NB_PLANES] = { f.pre_filter_linesize };

    sws_scale(f.pre_filter_context, src2, src2_linesize, 0, h, dst2, dst2_linesize);

#define UPDATE_FACTOR do {                                              \

        int factor;                                                     \

        factor = f.color_diff_coeff[COLOR_DIFF_COEFF_SIZE/2 + pre_val - \

                 f.pre_filter_buf[ix + iy*f.pre_filter_linesize]] * f.dist_coeff[dx + dy*f.dist_linesize]; \

        sum += src[ix + iy*src_linesize] * factor;                      \

        div += factor;                                                  \

    } while (0)

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

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

            int sum = 0;

            int div = 0;

            int dy;

            const int pre_val = f.pre_filter_buf[x + y*f.pre_filter_linesize];

            if (x >= radius && x < w - radius) {

                for (dy = 0; dy < radius*2 + 1; dy++) {

                    int dx;

                    int iy = y+dy - radius;

                    if      (iy < 0)  iy = -iy;

                    else if (iy >= h) iy = h+h-iy-1;

                    for (dx = 0; dx < radius*2 + 1; dx++) {

                        const int ix = x+dx - radius;

                        UPDATE_FACTOR;

                    }

                }

            } else {

                for (dy = 0; dy < radius*2+1; dy++) {

                    int dx;

                    int iy = y+dy - radius;

                    if      (iy <  0) iy = -iy;

                    else if (iy >= h) iy = h+h-iy-1;

                    for (dx = 0; dx < radius*2 + 1; dx++) {

                        int ix = x+dx - radius;

                        if      (ix < 0)  ix = -ix;

                        else if (ix >= w) ix = w+w-ix-1;

                        UPDATE_FACTOR;

                    }

                }

            }

            dst[x + y*dst_linesize] = (sum + div/2) / div;

        }

    }

}


FWCfgState *pc_memory_init(PCMachineState *pcms,

                           MemoryRegion *system_memory,

                           MemoryRegion *rom_memory,

                           MemoryRegion **ram_memory,

                           PcGuestInfo *guest_info)

{

    int linux_boot, i;

    MemoryRegion *ram, *option_rom_mr;

    MemoryRegion *ram_below_4g, *ram_above_4g;

    FWCfgState *fw_cfg;

    MachineState *machine = MACHINE(pcms);

    assert(machine->ram_size == pcms->below_4g_mem_size +

                                pcms->above_4g_mem_size);

    linux_boot = (machine->kernel_filename != NULL);

    /* Allocate RAM.  We allocate it as a single memory region and use

     * aliases to address portions of it, mostly for backwards compatibility

     * with older qemus that used qemu_ram_alloc().

     */

    ram = g_malloc(sizeof(*ram));

    memory_region_allocate_system_memory(ram, NULL, "pc.ram",

                                         machine->ram_size);

    *ram_memory = ram;

    ram_below_4g = g_malloc(sizeof(*ram_below_4g));

    memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram,

                             0, pcms->below_4g_mem_size);

    memory_region_add_subregion(system_memory, 0, ram_below_4g);

    e820_add_entry(0, pcms->below_4g_mem_size, E820_RAM);

    if (pcms->above_4g_mem_size > 0) {

        ram_above_4g = g_malloc(sizeof(*ram_above_4g));

        memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g", ram,

                                 pcms->below_4g_mem_size,

                                 pcms->above_4g_mem_size);

        memory_region_add_subregion(system_memory, 0x100000000ULL,

                                    ram_above_4g);

        e820_add_entry(0x100000000ULL, pcms->above_4g_mem_size, E820_RAM);

    }

    if (!guest_info->has_reserved_memory &&

        (machine->ram_slots ||

         (machine->maxram_size > machine->ram_size))) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",

                     mc->name);

        exit(EXIT_FAILURE);

    }

    /* initialize hotplug memory address space */

    if (guest_info->has_reserved_memory &&

        (machine->ram_size < machine->maxram_size)) {

        ram_addr_t hotplug_mem_size =

            machine->maxram_size - machine->ram_size;

        if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {

            error_report("unsupported amount of memory slots: %"PRIu64,

                         machine->ram_slots);

            exit(EXIT_FAILURE);

        }

        if (QEMU_ALIGN_UP(machine->maxram_size,

                          TARGET_PAGE_SIZE) != machine->maxram_size) {

            error_report("maximum memory size must by aligned to multiple of "

                         "%d bytes", TARGET_PAGE_SIZE);

            exit(EXIT_FAILURE);

        }

        pcms->hotplug_memory.base =

            ROUND_UP(0x100000000ULL + pcms->above_4g_mem_size, 1ULL << 30);

        if (pcms->enforce_aligned_dimm) {

            /* size hotplug region assuming 1G page max alignment per slot */

            hotplug_mem_size += (1ULL << 30) * machine->ram_slots;

        }

        if ((pcms->hotplug_memory.base + hotplug_mem_size) <

            hotplug_mem_size) {

            error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,

                         machine->maxram_size);

            exit(EXIT_FAILURE);

        }

        memory_region_init(&pcms->hotplug_memory.mr, OBJECT(pcms),

                           "hotplug-memory", hotplug_mem_size);

        memory_region_add_subregion(system_memory, pcms->hotplug_memory.base,

                                    &pcms->hotplug_memory.mr);

    }

    /* Initialize PC system firmware */

    pc_system_firmware_init(rom_memory, guest_info->isapc_ram_fw);

    option_rom_mr = g_malloc(sizeof(*option_rom_mr));

    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,

                           &error_abort);

    vmstate_register_ram_global(option_rom_mr);

    memory_region_add_subregion_overlap(rom_memory,

                                        PC_ROM_MIN_VGA,

                                        option_rom_mr,

                                        1);

    fw_cfg = bochs_bios_init();

    rom_set_fw(fw_cfg);

    if (guest_info->has_reserved_memory && pcms->hotplug_memory.base) {

        uint64_t *val = g_malloc(sizeof(*val));

        PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);

        uint64_t res_mem_end = pcms->hotplug_memory.base;

        if (!pcmc->broken_reserved_end) {

            res_mem_end += memory_region_size(&pcms->hotplug_memory.mr);

        }

        *val = cpu_to_le64(ROUND_UP(res_mem_end, 0x1ULL << 30));

        fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));

    }

    if (linux_boot) {

        load_linux(pcms, fw_cfg);

    }

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

        rom_add_option(option_rom[i].name, option_rom[i].bootindex);

    }

    guest_info->fw_cfg = fw_cfg;

    return fw_cfg;

}


static void migrate_fd_cancel(MigrationState *s)
{
    int old_state ;
    QEMUFile *f = migrate_get_current()->to_dst_file;
    trace_migrate_fd_cancel();
    if (s->rp_state.from_dst_file) {
        /* shutdown the rp socket, so causing the rp thread to shutdown */
        qemu_file_shutdown(s->rp_state.from_dst_file);
    do {
        old_state = s->state;
        if (!migration_is_setup_or_active(old_state)) {
            break;
        migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
    } while (s->state != MIGRATION_STATUS_CANCELLING);
    /*
     * If we're unlucky the migration code might be stuck somewhere in a
     * send/write while the network has failed and is waiting to timeout;
     * if we've got shutdown(2) available then we can force it to quit.
     * The outgoing qemu file gets closed in migrate_fd_cleanup that is
     * called in a bh, so there is no race against this cancel.
     */
    if (s->state == MIGRATION_STATUS_CANCELLING && f) {
        qemu_file_shutdown(f);


static int decode_init_thread_copy(AVCodecContext *avctx)

{

    H264Context *h = avctx->priv_data;

    int ret;

    if (!avctx->internal->is_copy)

        return 0;

    memset(h->sps_buffers, 0, sizeof(h->sps_buffers));

    memset(h->pps_buffers, 0, sizeof(h->pps_buffers));

    ret = h264_init_context(avctx, h);

    if (ret < 0)

        return ret;

    h->context_initialized = 0;

    return 0;

}


static IOMMUTLBEntry vtd_iommu_translate(MemoryRegion *iommu, hwaddr addr,

                                         bool is_write)

{

    VTDAddressSpace *vtd_as = container_of(iommu, VTDAddressSpace, iommu);

    IntelIOMMUState *s = vtd_as->iommu_state;

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = addr,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE,

    };

    if (!s->dmar_enabled) {

        /* DMAR disabled, passthrough, use 4k-page*/

        ret.iova = addr & VTD_PAGE_MASK_4K;

        ret.translated_addr = addr & VTD_PAGE_MASK_4K;

        ret.addr_mask = ~VTD_PAGE_MASK_4K;

        ret.perm = IOMMU_RW;

        return ret;

    }

    vtd_do_iommu_translate(vtd_as, vtd_as->bus, vtd_as->devfn, addr,

                           is_write, &ret);

    VTD_DPRINTF(MMU,

                "bus %"PRIu8 " slot %"PRIu8 " func %"PRIu8 " devfn %"PRIu8

                " iova 0x%"PRIx64 " hpa 0x%"PRIx64, pci_bus_num(vtd_as->bus),

                VTD_PCI_SLOT(vtd_as->devfn), VTD_PCI_FUNC(vtd_as->devfn),

                vtd_as->devfn, addr, ret.translated_addr);

    return ret;

}


static gboolean io_watch_poll_check(GSource *source)

{

    IOWatchPoll *iwp = io_watch_poll_from_source(source);

    if (iwp->max_size == 0) {

        return FALSE;

    }

    return g_io_watch_funcs.check(source);

}


static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,

                                        AVFilterInOut *in)

{

    AVFilterContext *last_filter;

    const AVFilter *abuffer_filt = avfilter_get_by_name("abuffer");

    InputStream *ist = ifilter->ist;

    InputFile     *f = input_files[ist->file_index];

    char args[255], name[255];

    int ret, pad_idx = 0;

    snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"

             ":channel_layout=0x%"PRIx64,

             1, ist->st->codec->sample_rate,

             ist->st->codec->sample_rate,

             av_get_sample_fmt_name(ist->st->codec->sample_fmt),

             ist->st->codec->channel_layout);

    snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,

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

    if ((ret = avfilter_graph_create_filter(&ifilter->filter, abuffer_filt,

                                            name, args, NULL,

                                            fg->graph)) < 0)

        return ret;

    last_filter = ifilter->filter;

    if (audio_sync_method > 0) {

        AVFilterContext *async;

        int  len = 0;

        av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "

               "asyncts audio filter instead.\n");

        if (audio_sync_method > 1)

            len += snprintf(args + len, sizeof(args) - len, "compensate=1:"

                            "max_comp=%d:", audio_sync_method);

        snprintf(args + len, sizeof(args) - len, "min_delta=%f",

                 audio_drift_threshold);

        snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",

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

        ret = avfilter_graph_create_filter(&async,

                                           avfilter_get_by_name("asyncts"),

                                           name, args, NULL, fg->graph);

        if (ret < 0)

            return ret;

        ret = avfilter_link(last_filter, 0, async, 0);

        if (ret < 0)

            return ret;

        last_filter = async;

    }

    if (audio_volume != 256) {

        AVFilterContext *volume;

        av_log(NULL, AV_LOG_WARNING, "-vol has been deprecated. Use the volume "

               "audio filter instead.\n");

        snprintf(args, sizeof(args), "volume=%f", audio_volume / 256.0);

        snprintf(name, sizeof(name), "graph %d volume for input stream %d:%d",

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

        ret = avfilter_graph_create_filter(&volume,

                                           avfilter_get_by_name("volume"),

                                           name, args, NULL, fg->graph);

        if (ret < 0)

            return ret;

        ret = avfilter_link(last_filter, 0, volume, 0);

        if (ret < 0)

            return ret;

        last_filter = volume;

    }

    snprintf(name, sizeof(name), "trim for input stream %d:%d",

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

    ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?

                      AV_NOPTS_VALUE : 0, INT64_MAX, &last_filter, &pad_idx, name);

    if (ret < 0)

        return ret;

    if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)

        return ret;

    return 0;

}


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

{

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

    int size = pkt->size;

    uint8_t *buf = pkt->data;

    uint8_t *data = NULL;

    MpegTSWrite *ts = s->priv_data;

    MpegTSWriteStream *ts_st = st->priv_data;

    const uint64_t delay = av_rescale(s->max_delay, 90000, AV_TIME_BASE) * 2;

    int64_t dts = AV_NOPTS_VALUE, pts = AV_NOPTS_VALUE;

    if (ts->reemit_pat_pmt) {

        av_log(s, AV_LOG_WARNING,

               "resend_headers option is deprecated, use -mpegts_flags resend_headers\n");

        ts->reemit_pat_pmt = 0;

        ts->flags         |= MPEGTS_FLAG_REEMIT_PAT_PMT;

    }

    if (ts->flags & MPEGTS_FLAG_REEMIT_PAT_PMT) {

        ts->pat_packet_count = ts->pat_packet_period - 1;

        ts->sdt_packet_count = ts->sdt_packet_period - 1;

        ts->flags           &= ~MPEGTS_FLAG_REEMIT_PAT_PMT;

    }

    if (pkt->pts != AV_NOPTS_VALUE)

        pts = pkt->pts + delay;

    if (pkt->dts != AV_NOPTS_VALUE)

        dts = pkt->dts + delay;

    if (ts_st->first_pts_check && pts == AV_NOPTS_VALUE) {

        av_log(s, AV_LOG_ERROR, "first pts value must set\n");

        return AVERROR(EINVAL);

    }

    ts_st->first_pts_check = 0;

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

        const uint8_t *p = buf, *buf_end = p + size;

        uint32_t state = -1;

        if (pkt->size < 5 || AV_RB32(pkt->data) != 0x0000001) {

            av_log(s, AV_LOG_ERROR, "H.264 bitstream malformed, "

                   "no startcode found, use -bsf h264_mp4toannexb\n");

            return AVERROR(EINVAL);

        }

        do {

            p = avpriv_find_start_code(p, buf_end, &state);

            av_dlog(s, "nal %d\n", state & 0x1f);

        } while (p < buf_end && (state & 0x1f) != 9 &&

                 (state & 0x1f) != 5 && (state & 0x1f) != 1);

        if ((state & 0x1f) != 9) { // AUD NAL

            data = av_malloc(pkt->size + 6);

            if (!data)

                return AVERROR(ENOMEM);

            memcpy(data + 6, pkt->data, pkt->size);

            AV_WB32(data, 0x00000001);

            data[4] = 0x09;

            data[5] = 0xf0; // any slice type (0xe) + rbsp stop one bit

            buf     = data;

            size    = pkt->size + 6;

        }

    } else if (st->codec->codec_id == AV_CODEC_ID_AAC) {

        if (pkt->size < 2) {

            av_log(s, AV_LOG_ERROR, "AAC packet too short\n");

            return AVERROR(EINVAL);

        }

        if ((AV_RB16(pkt->data) & 0xfff0) != 0xfff0) {

            int ret;

            AVPacket pkt2;

            if (!ts_st->amux) {

                av_log(s, AV_LOG_ERROR, "AAC bitstream not in ADTS format "

                                        "and extradata missing\n");

                return AVERROR(EINVAL);

            }

            av_init_packet(&pkt2);

            pkt2.data = pkt->data;

            pkt2.size = pkt->size;

            ret = avio_open_dyn_buf(&ts_st->amux->pb);

            if (ret < 0)

                return AVERROR(ENOMEM);

            ret = av_write_frame(ts_st->amux, &pkt2);

            if (ret < 0) {

                avio_close_dyn_buf(ts_st->amux->pb, &data);

                ts_st->amux->pb = NULL;

                av_free(data);

                return ret;

            }

            size            = avio_close_dyn_buf(ts_st->amux->pb, &data);

            ts_st->amux->pb = NULL;

            buf             = data;

        }

    }

    if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {

        // for video and subtitle, write a single pes packet

        mpegts_write_pes(s, st, buf, size, pts, dts,

                         pkt->flags & AV_PKT_FLAG_KEY);

        av_free(data);

        return 0;

    }

    if (ts_st->payload_size + size > ts->pes_payload_size) {

        if (ts_st->payload_size) {

            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_size,

                             ts_st->payload_pts, ts_st->payload_dts,

                             ts_st->payload_flags & AV_PKT_FLAG_KEY);

            ts_st->payload_size = 0;

        }

        if (size > ts->pes_payload_size) {

            mpegts_write_pes(s, st, buf, size, pts, dts,

                             pkt->flags & AV_PKT_FLAG_KEY);

            av_free(data);

            return 0;

        }

    }

    if (!ts_st->payload_size) {

        ts_st->payload_pts   = pts;

        ts_st->payload_dts   = dts;

        ts_st->payload_flags = pkt->flags;

    }

    memcpy(ts_st->payload + ts_st->payload_size, buf, size);

    ts_st->payload_size += size;

    av_free(data);

    return 0;

}


void qmp_object_add(const char *type, const char *id,

                    bool has_props, QObject *props, Error **errp)

{

    const QDict *pdict = NULL;

    QmpInputVisitor *qiv;

    Object *obj;

    if (props) {

        pdict = qobject_to_qdict(props);

        if (!pdict) {

            error_setg(errp, QERR_INVALID_PARAMETER_TYPE, "props", "dict");

            return;

        }

    }

    qiv = qmp_input_visitor_new(props, false);

    obj = user_creatable_add_type(type, id, pdict,

                                  qmp_input_get_visitor(qiv), errp);

    qmp_input_visitor_cleanup(qiv);

    if (obj) {

        object_unref(obj);

    }

}


static inline TranslationBlock *tb_find(CPUState *cpu,

                                        TranslationBlock *last_tb,

                                        int tb_exit)

{

    CPUArchState *env = (CPUArchState *)cpu->env_ptr;

    TranslationBlock *tb;

    target_ulong cs_base, pc;

    uint32_t flags;

    bool acquired_tb_lock = false;

    /* we record a subset of the CPU state. It will

       always be the same before a given translated block

       is executed. */

    cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);

    tb = atomic_rcu_read(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)]);

    if (unlikely(!tb || tb->pc != pc || tb->cs_base != cs_base ||

                 tb->flags != flags ||

                 tb->trace_vcpu_dstate != *cpu->trace_dstate)) {

        tb = tb_htable_lookup(cpu, pc, cs_base, flags);

        if (!tb) {

            /* mmap_lock is needed by tb_gen_code, and mmap_lock must be

             * taken outside tb_lock. As system emulation is currently

             * single threaded the locks are NOPs.

             */

            mmap_lock();

            tb_lock();

            acquired_tb_lock = true;

            /* There's a chance that our desired tb has been translated while

             * taking the locks so we check again inside the lock.

             */

            tb = tb_htable_lookup(cpu, pc, cs_base, flags);

            if (!tb) {

                /* if no translated code available, then translate it now */

                tb = tb_gen_code(cpu, pc, cs_base, flags, 0);

            }

            mmap_unlock();

        }

        /* We add the TB in the virtual pc hash table for the fast lookup */

        atomic_set(&cpu->tb_jmp_cache[tb_jmp_cache_hash_func(pc)], tb);

    }

#ifndef CONFIG_USER_ONLY

    /* We don't take care of direct jumps when address mapping changes in

     * system emulation. So it's not safe to make a direct jump to a TB

     * spanning two pages because the mapping for the second page can change.

     */

    if (tb->page_addr[1] != -1) {

        last_tb = NULL;

    }

#endif

    /* See if we can patch the calling TB. */

    if (last_tb && !qemu_loglevel_mask(CPU_LOG_TB_NOCHAIN)) {

        if (!acquired_tb_lock) {

            tb_lock();

            acquired_tb_lock = true;

        }

        if (!tb->invalid) {

            tb_add_jump(last_tb, tb_exit, tb);

        }

    }

    if (acquired_tb_lock) {

        tb_unlock();

    }

    return tb;

}


static inline void RENAME(hyscale_fast)(SwsContext *c, int16_t *dst,

                                        int dstWidth, const uint8_t *src, int srcW,

                                        int xInc)

{

#if ARCH_X86

#if COMPILE_TEMPLATE_MMX2

    int32_t *filterPos = c->hLumFilterPos;

    int16_t *filter    = c->hLumFilter;

    int     canMMX2BeUsed  = c->canMMX2BeUsed;

    void    *mmx2FilterCode= c->lumMmx2FilterCode;

    int i;

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

    if (canMMX2BeUsed) {

        __asm__ volatile(

#if defined(PIC)

            "mov               %%"REG_b", %5        \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"

#if ARCH_X86_64

#define CALL_MMX2_FILTER_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 CALL_MMX2_FILTER_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 */

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

#if defined(PIC)

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

#endif

            :: "m" (src), "m" (dst), "m" (filter), "m" (filterPos),

            "m" (mmx2FilterCode)

#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--) dst[i] = src[srcW-1]*128;

    } else {

#endif /* COMPILE_TEMPLATE_MMX2 */

    x86_reg dstWidth_reg = dstWidth;

    x86_reg xInc_shr16 = xInc >> 16;

    uint16_t xInc_mask = xInc & 0xffff;

    //NO MMX just normal asm ...

    __asm__ volatile(

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

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

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

        ASMALIGN(4)

        "1:                                  \n\t"

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

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

        FAST_BILINEAR_X86

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

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

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

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

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

        FAST_BILINEAR_X86

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

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

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

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

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

        " jb        1b                       \n\t"

        :: "r" (src), "m" (dst), "m" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask)

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

    );

#if COMPILE_TEMPLATE_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]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

        xpos+=xInc;

    }

#endif /* ARCH_X86 */

}


static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header)

{

    OMAContext *oc = s->priv_data;

    ID3v2ExtraMetaGEOB *geob = NULL;

    uint8_t *gdata;

    oc->encrypted = 1;

    av_log(s, AV_LOG_INFO, "File is encrypted\n");

    /* find GEOB metadata */

    while (em) {

        if (!strcmp(em->tag, "GEOB") &&

            (geob = em->data) &&

            (!strcmp(geob->description, "OMG_LSI") ||

             !strcmp(geob->description, "OMG_BKLSI"))) {

            break;

        }

        em = em->next;

    }

    if (!em) {

        av_log(s, AV_LOG_ERROR, "No encryption header found\n");

        return AVERROR_INVALIDDATA;

    }

    if (geob->datasize < 64) {

        av_log(s, AV_LOG_ERROR,

               "Invalid GEOB data size: %u\n", geob->datasize);

        return AVERROR_INVALIDDATA;

    }

    gdata = geob->data;

    if (AV_RB16(gdata) != 1)

        av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n");

    oc->k_size = AV_RB16(&gdata[2]);

    oc->e_size = AV_RB16(&gdata[4]);

    oc->i_size = AV_RB16(&gdata[6]);

    oc->s_size = AV_RB16(&gdata[8]);

    if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING     ", 12)) {

        av_log(s, AV_LOG_ERROR, "Invalid encryption header\n");

        return AVERROR_INVALIDDATA;

    }

    oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]);

    av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid);

    memcpy(oc->iv, &header[0x58], 8);

    hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8);

    hex_log(s, AV_LOG_DEBUG, "CBC-MAC",

            &gdata[OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size + oc->i_size],

            8);

    if (s->keylen > 0) {

        kset(s, s->key, s->key, s->keylen);

    }

    if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) ||

        rprobe(s, gdata, oc->r_val) < 0 &&

        nprobe(s, gdata, geob->datasize, oc->n_val) < 0) {

        int i;

        for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) {

            uint8_t buf[16];

            AV_WL64(buf,     leaf_table[i]);

            AV_WL64(&buf[8], leaf_table[i + 1]);

            kset(s, buf, buf, 16);

            if (!rprobe(s, gdata, oc->r_val) ||

                !nprobe(s, gdata, geob->datasize, oc->n_val))

                break;

        }

        if (i >= sizeof(leaf_table)) {

            av_log(s, AV_LOG_ERROR, "Invalid key\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* e_val */

    av_des_init(&oc->av_des, oc->m_val, 64, 0);

    av_des_crypt(&oc->av_des, oc->e_val,

                 &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0);

    hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8);

    /* init e_val */

    av_des_init(&oc->av_des, oc->e_val, 64, 1);

    return 0;

}


void superh_cpu_do_interrupt(CPUState *cs)

{

    SuperHCPU *cpu = SUPERH_CPU(cs);

    CPUSH4State *env = &cpu->env;

    int do_irq = cs->interrupt_request & CPU_INTERRUPT_HARD;

    int do_exp, irq_vector = cs->exception_index;

    /* prioritize exceptions over interrupts */

    do_exp = cs->exception_index != -1;

    do_irq = do_irq && (cs->exception_index == -1);

    if (env->sr & (1u << SR_BL)) {

        if (do_exp && cs->exception_index != 0x1e0) {

            cs->exception_index = 0x000; /* masked exception -> reset */

        }

        if (do_irq && !env->in_sleep) {

            return; /* masked */

        }

    }

    env->in_sleep = 0;

    if (do_irq) {

        irq_vector = sh_intc_get_pending_vector(env->intc_handle,

						(env->sr >> 4) & 0xf);

        if (irq_vector == -1) {

            return; /* masked */

	}

    }

    if (qemu_loglevel_mask(CPU_LOG_INT)) {

	const char *expname;

        switch (cs->exception_index) {

	case 0x0e0:

	    expname = "addr_error";

	    break;

	case 0x040:

	    expname = "tlb_miss";

	    break;

	case 0x0a0:

	    expname = "tlb_violation";

	    break;

	case 0x180:

	    expname = "illegal_instruction";

	    break;

	case 0x1a0:

	    expname = "slot_illegal_instruction";

	    break;

	case 0x800:

	    expname = "fpu_disable";

	    break;

	case 0x820:

	    expname = "slot_fpu";

	    break;

	case 0x100:

	    expname = "data_write";

	    break;

	case 0x060:

	    expname = "dtlb_miss_write";

	    break;

	case 0x0c0:

	    expname = "dtlb_violation_write";

	    break;

	case 0x120:

	    expname = "fpu_exception";

	    break;

	case 0x080:

	    expname = "initial_page_write";

	    break;

	case 0x160:

	    expname = "trapa";

	    break;

	default:

            expname = do_irq ? "interrupt" : "???";

            break;

	}

	qemu_log("exception 0x%03x [%s] raised\n",

		  irq_vector, expname);

        log_cpu_state(cs, 0);

    }

    env->ssr = cpu_read_sr(env);

    env->spc = env->pc;

    env->sgr = env->gregs[15];

    env->sr |= (1u << SR_BL) | (1u << SR_MD) | (1u << SR_RB);

    if (env->flags & (DELAY_SLOT | DELAY_SLOT_CONDITIONAL)) {

        /* Branch instruction should be executed again before delay slot. */

	env->spc -= 2;

	/* Clear flags for exception/interrupt routine. */

        env->flags &= ~(DELAY_SLOT | DELAY_SLOT_CONDITIONAL);

    }

    if (do_exp) {

        env->expevt = cs->exception_index;

        switch (cs->exception_index) {

        case 0x000:

        case 0x020:

        case 0x140:

            env->sr &= ~(1u << SR_FD);

            env->sr |= 0xf << 4; /* IMASK */

            env->pc = 0xa0000000;

            break;

        case 0x040:

        case 0x060:

            env->pc = env->vbr + 0x400;

            break;

        case 0x160:

            env->spc += 2; /* special case for TRAPA */

            /* fall through */

        default:

            env->pc = env->vbr + 0x100;

            break;

        }

        return;

    }

    if (do_irq) {

        env->intevt = irq_vector;

        env->pc = env->vbr + 0x600;

        return;

    }

}


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

{

    SmackerContext *smk = s->priv_data;

    int flags;

    int ret;

    int i;

    int frame_size = 0;

    int palchange = 0;

    if (s->pb->eof_reached || smk->cur_frame >= smk->frames)

        return AVERROR_EOF;

    /* if we demuxed all streams, pass another frame */

    if(smk->curstream < 0) {

        avio_seek(s->pb, smk->nextpos, 0);

        frame_size = smk->frm_size[smk->cur_frame] & (~3);

        flags = smk->frm_flags[smk->cur_frame];

        /* handle palette change event */

        if(flags & SMACKER_PAL){

            int size, sz, t, off, j, pos;

            uint8_t *pal = smk->pal;

            uint8_t oldpal[768];

            memcpy(oldpal, pal, 768);

            size = avio_r8(s->pb);

            size = size * 4 - 1;

            frame_size -= size;

            frame_size--;

            sz = 0;

            pos = avio_tell(s->pb) + size;

            while(sz < 256){

                t = avio_r8(s->pb);

                if(t & 0x80){ /* skip palette entries */

                    sz += (t & 0x7F) + 1;

                    pal += ((t & 0x7F) + 1) * 3;

                } else if(t & 0x40){ /* copy with offset */

                    off = avio_r8(s->pb);

                    j = (t & 0x3F) + 1;

                    if (off + j > 0x100) {

                        av_log(s, AV_LOG_ERROR,

                               "Invalid palette update, offset=%d length=%d extends beyond palette size\n",

                               off, j);

                        return AVERROR_INVALIDDATA;

                    }

                    off *= 3;

                    while(j-- && sz < 256) {

                        *pal++ = oldpal[off + 0];

                        *pal++ = oldpal[off + 1];

                        *pal++ = oldpal[off + 2];

                        sz++;

                        off += 3;

                    }

                } else { /* new entries */

                    *pal++ = smk_pal[t];

                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];

                    *pal++ = smk_pal[avio_r8(s->pb) & 0x3F];

                    sz++;

                }

            }

            avio_seek(s->pb, pos, 0);

            palchange |= 1;

        }

        flags >>= 1;

        smk->curstream = -1;

        /* if audio chunks are present, put them to stack and retrieve later */

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

            if(flags & 1) {

                int size;

                uint8_t *tmpbuf;

                size = avio_rl32(s->pb) - 4;

                frame_size -= size;

                frame_size -= 4;

                smk->curstream++;

                tmpbuf = av_realloc(smk->bufs[smk->curstream], size);

                if (!tmpbuf)

                    return AVERROR(ENOMEM);

                smk->bufs[smk->curstream] = tmpbuf;

                smk->buf_sizes[smk->curstream] = size;

                ret = avio_read(s->pb, smk->bufs[smk->curstream], size);

                if(ret != size)

                    return AVERROR(EIO);

                smk->stream_id[smk->curstream] = smk->indexes[i];

            }

            flags >>= 1;

        }

        if (frame_size < 0)

            return AVERROR_INVALIDDATA;

        if (av_new_packet(pkt, frame_size + 769))

            return AVERROR(ENOMEM);

        if(smk->frm_size[smk->cur_frame] & 1)

            palchange |= 2;

        pkt->data[0] = palchange;

        memcpy(pkt->data + 1, smk->pal, 768);

        ret = avio_read(s->pb, pkt->data + 769, frame_size);

        if(ret != frame_size)

            return AVERROR(EIO);

        pkt->stream_index = smk->videoindex;

        pkt->pts          = smk->cur_frame;

        pkt->size = ret + 769;

        smk->cur_frame++;

        smk->nextpos = avio_tell(s->pb);

    } else {

        if (av_new_packet(pkt, smk->buf_sizes[smk->curstream]))

            return AVERROR(ENOMEM);

        memcpy(pkt->data, smk->bufs[smk->curstream], smk->buf_sizes[smk->curstream]);

        pkt->size = smk->buf_sizes[smk->curstream];

        pkt->stream_index = smk->stream_id[smk->curstream];

        pkt->pts = smk->aud_pts[smk->curstream];

        smk->aud_pts[smk->curstream] += AV_RL32(pkt->data);

        smk->curstream--;

    }

    return 0;

}


static void parse_type_size(Visitor *v, const char *name, uint64_t *obj,

                            Error **errp)

{

    StringInputVisitor *siv = to_siv(v);

    Error *err = NULL;

    uint64_t val;

    if (siv->string) {

        parse_option_size(name, siv->string, &val, &err);

    } else {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "size");

        return;

    }

    if (err) {

        error_propagate(errp, err);

        return;

    }

    *obj = val;

}


static int parse_fragment(AVFormatContext *s, const char *filename, int64_t *start_ts, int64_t *duration, int64_t *moof_size, int64_t size)

{

    AVIOContext *in;

    int ret;

    uint32_t len;

    if ((ret = avio_open2(&in, filename, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)

        return ret;

    ret = AVERROR(EIO);

    *moof_size = avio_rb32(in);

    if (*moof_size < 8 || *moof_size > size)

        goto fail;

    if (avio_rl32(in) != MKTAG('m','o','o','f'))

        goto fail;

    len = avio_rb32(in);

    if (len > *moof_size)

        goto fail;

    if (avio_rl32(in) != MKTAG('m','f','h','d'))

        goto fail;

    avio_seek(in, len - 8, SEEK_CUR);

    avio_rb32(in); /* traf size */

    if (avio_rl32(in) != MKTAG('t','r','a','f'))

        goto fail;

    while (avio_tell(in) < *moof_size) {

        uint32_t len = avio_rb32(in);

        uint32_t tag = avio_rl32(in);

        int64_t end = avio_tell(in) + len - 8;

        if (len < 8 || len >= *moof_size)

            goto fail;

        if (tag == MKTAG('u','u','i','d')) {

            const uint8_t tfxd[] = {

                0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,

                0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2

            };

            uint8_t uuid[16];

            avio_read(in, uuid, 16);

            if (!memcmp(uuid, tfxd, 16) && len >= 8 + 16 + 4 + 16) {

                avio_seek(in, 4, SEEK_CUR);

                *start_ts = avio_rb64(in);

                *duration = avio_rb64(in);

                ret = 0;

                break;

            }

        }

        avio_seek(in, end, SEEK_SET);

    }

fail:

    avio_close(in);

    return ret;

}


void acpi_pm1_cnt_init(ACPIREGS *ar, qemu_irq cmos_s3)

{

    ar->pm1.cnt.cmos_s3 = cmos_s3;

}


static void console_refresh(QemuConsole *s)

{

    DisplaySurface *surface = qemu_console_surface(s);

    TextCell *c;

    int x, y, y1;

    if (s->ds->have_text) {

        s->text_x[0] = 0;

        s->text_y[0] = 0;

        s->text_x[1] = s->width - 1;

        s->text_y[1] = s->height - 1;

        s->cursor_invalidate = 1;

    }

    vga_fill_rect(s, 0, 0, surface_width(surface), surface_height(surface),

                  color_table_rgb[0][COLOR_BLACK]);

    y1 = s->y_displayed;

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

        c = s->cells + y1 * s->width;

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

            vga_putcharxy(s, x, y, c->ch,

                          &(c->t_attrib));

            c++;

        }

        if (++y1 == s->total_height) {

            y1 = 0;

        }

    }

    console_show_cursor(s, 1);

    dpy_gfx_update(s, 0, 0,

                   surface_width(surface), surface_height(surface));

}


static void qemu_init_child_watch(void)

{

    struct sigaction act;

    sigchld_bh = qemu_bh_new(sigchld_bh_handler, NULL);

    memset(&act, 0, sizeof(act));

    act.sa_handler = sigchld_handler;

    act.sa_flags = SA_NOCLDSTOP;

    sigaction(SIGCHLD, &act, NULL);

}


int av_packet_split_side_data(AVPacket *pkt){

    if (!pkt->side_data_elems && pkt->size >12 && AV_RB64(pkt->data + pkt->size - 8) == FF_MERGE_MARKER){

        int i;

        unsigned int size, orig_pktsize = pkt->size;

        uint8_t *p;

        p = pkt->data + pkt->size - 8 - 5;

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

            size = AV_RB32(p);

            if (size>INT_MAX || p - pkt->data < size)

                return 0;

            if (p[4]&128)

                break;

            p-= size+5;

        }

        pkt->side_data = av_malloc(i * sizeof(*pkt->side_data));

        if (!pkt->side_data)

            return AVERROR(ENOMEM);

        p= pkt->data + pkt->size - 8 - 5;

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

            size= AV_RB32(p);

            av_assert0(size<=INT_MAX && p - pkt->data >= size);

            pkt->side_data[i].data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

            pkt->side_data[i].size = size;

            pkt->side_data[i].type = p[4]&127;

            if (!pkt->side_data[i].data)

                return AVERROR(ENOMEM);

            memcpy(pkt->side_data[i].data, p-size, size);

            pkt->size -= size + 5;

            if(p[4]&128)

                break;

            p-= size+5;

        }

        pkt->size -= 8;

        /* FFMIN() prevents overflow in case the packet wasn't allocated with

         * proper padding.

         * If the side data is smaller than the buffer padding size, the

         * remaining bytes should have already been filled with zeros by the

         * original packet allocation anyway. */

        memset(pkt->data + pkt->size, 0,

               FFMIN(orig_pktsize - pkt->size, FF_INPUT_BUFFER_PADDING_SIZE));

        pkt->side_data_elems = i+1;

        return 1;

    }

    return 0;

}


int vnc_tls_client_setup(VncState *vs,

                         int needX509Creds) {

    VNC_DEBUG("Do TLS setup\n");

    if (vnc_tls_initialize() < 0) {

        VNC_DEBUG("Failed to init TLS\n");

        vnc_client_error(vs);

        return -1;

    }

    if (vs->tls.session == NULL) {

        if (gnutls_init(&vs->tls.session, GNUTLS_SERVER) < 0) {

            vnc_client_error(vs);

            return -1;

        }

        if (gnutls_set_default_priority(vs->tls.session) < 0) {

            gnutls_deinit(vs->tls.session);

            vs->tls.session = NULL;

            vnc_client_error(vs);

            return -1;

        }

        if (vnc_set_gnutls_priority(vs->tls.session, needX509Creds) < 0) {

            gnutls_deinit(vs->tls.session);

            vs->tls.session = NULL;

            vnc_client_error(vs);

            return -1;

        }

        if (needX509Creds) {

            gnutls_certificate_server_credentials x509_cred =

                vnc_tls_initialize_x509_cred(vs->vd);

            if (!x509_cred) {

                gnutls_deinit(vs->tls.session);

                vs->tls.session = NULL;

                vnc_client_error(vs);

                return -1;

            }

            if (gnutls_credentials_set(vs->tls.session,

                                       GNUTLS_CRD_CERTIFICATE, x509_cred) < 0) {

                gnutls_deinit(vs->tls.session);

                vs->tls.session = NULL;

                gnutls_certificate_free_credentials(x509_cred);

                vnc_client_error(vs);

                return -1;

            }

            if (vs->vd->tls.x509verify) {

                VNC_DEBUG("Requesting a client certificate\n");

                gnutls_certificate_server_set_request(vs->tls.session,

                                                      GNUTLS_CERT_REQUEST);

            }

        } else {

            gnutls_anon_server_credentials_t anon_cred =

                vnc_tls_initialize_anon_cred();

            if (!anon_cred) {

                gnutls_deinit(vs->tls.session);

                vs->tls.session = NULL;

                vnc_client_error(vs);

                return -1;

            }

            if (gnutls_credentials_set(vs->tls.session,

                                       GNUTLS_CRD_ANON, anon_cred) < 0) {

                gnutls_deinit(vs->tls.session);

                vs->tls.session = NULL;

                gnutls_anon_free_server_credentials(anon_cred);

                vnc_client_error(vs);

                return -1;

            }

        }

        gnutls_transport_set_ptr(vs->tls.session, (gnutls_transport_ptr_t)vs);

        gnutls_transport_set_push_function(vs->tls.session, vnc_tls_push);

        gnutls_transport_set_pull_function(vs->tls.session, vnc_tls_pull);

    }

    return 0;

}


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

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

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

    const int alpha = alpha_table[index_a];

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

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

    if( bS[0] < 4 || !intra ) {

        int8_t tc[4];

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

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

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

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

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

    } else {

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

    }

}


static inline void bt_hci_lmp_acl_data(struct bt_hci_s *hci, uint16_t handle,

                const uint8_t *data, int start, int len)

{

    struct hci_acl_hdr *pkt = (void *) hci->acl_buf;

    /* TODO: packet flags */

    /* TODO: avoid memcpy'ing */

    if (len + HCI_ACL_HDR_SIZE > sizeof(hci->acl_buf)) {

        fprintf(stderr, "%s: can't take ACL packets %i bytes long\n",

                        __FUNCTION__, len);

        return;

    }

    memcpy(hci->acl_buf + HCI_ACL_HDR_SIZE, data, len);

    pkt->handle = cpu_to_le16(

                    acl_handle_pack(handle, start ? ACL_START : ACL_CONT));

    pkt->dlen = cpu_to_le16(len);

    hci->info.acl_recv(hci->info.opaque,

                    hci->acl_buf, len + HCI_ACL_HDR_SIZE);

}


static void xilinx_enet_init(Object *obj)

{

    XilinxAXIEnet *s = XILINX_AXI_ENET(obj);

    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    Error *errp = NULL;

    object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SLAVE,

                             (Object **) &s->tx_dev, &errp);

    assert_no_error(errp);

    object_initialize(&s->rx_data_dev, TYPE_XILINX_AXI_ENET_DATA_STREAM);

    object_property_add_child(OBJECT(s), "axistream-connected-target",

                              (Object *)&s->rx_data_dev, &errp);

    assert_no_error(errp);

    sysbus_init_irq(sbd, &s->irq);

    memory_region_init_io(&s->iomem, &enet_ops, s, "enet", 0x40000);

    sysbus_init_mmio(sbd, &s->iomem);

}


bool address_space_rw(AddressSpace *as, hwaddr addr, uint8_t *buf,

                      int len, bool is_write)

{

    hwaddr l;

    uint8_t *ptr;

    uint64_t val;

    hwaddr addr1;

    MemoryRegion *mr;

    bool error = false;

    while (len > 0) {

        l = len;

        mr = address_space_translate(as, addr, &addr1, &l, is_write);

        if (is_write) {

            if (!memory_access_is_direct(mr, is_write)) {

                l = memory_access_size(mr, l, addr1);

                /* XXX: could force current_cpu to NULL to avoid

                   potential bugs */

                if (l == 4) {

                    /* 32 bit write access */

                    val = ldl_p(buf);

                    error |= io_mem_write(mr, addr1, val, 4);

                } else if (l == 2) {

                    /* 16 bit write access */

                    val = lduw_p(buf);

                    error |= io_mem_write(mr, addr1, val, 2);

                } else {

                    /* 8 bit write access */

                    val = ldub_p(buf);

                    error |= io_mem_write(mr, addr1, val, 1);

                }

            } else {

                addr1 += memory_region_get_ram_addr(mr);

                /* RAM case */

                ptr = qemu_get_ram_ptr(addr1);

                memcpy(ptr, buf, l);

                invalidate_and_set_dirty(addr1, l);

            }

        } else {

            if (!memory_access_is_direct(mr, is_write)) {

                /* I/O case */

                l = memory_access_size(mr, l, addr1);

                if (l == 4) {

                    /* 32 bit read access */

                    error |= io_mem_read(mr, addr1, &val, 4);

                    stl_p(buf, val);

                } else if (l == 2) {

                    /* 16 bit read access */

                    error |= io_mem_read(mr, addr1, &val, 2);

                    stw_p(buf, val);

                } else {

                    /* 8 bit read access */

                    error |= io_mem_read(mr, addr1, &val, 1);

                    stb_p(buf, val);

                }

            } else {

                /* RAM case */

                ptr = qemu_get_ram_ptr(mr->ram_addr + addr1);

                memcpy(buf, ptr, l);

            }

        }

        len -= l;

        buf += l;

        addr += l;

    }

    return error;

}


static int create_ppc_opcodes (CPUPPCState *env, const ppc_def_t *def)

{

    opcode_t *opc, *start, *end;

    fill_new_table(env->opcodes, 0x40);

    if (&opc_start < &opc_end) {

        start = &opc_start;

        end = &opc_end;

    } else {

        start = &opc_end;

        end = &opc_start;

    }

    for (opc = start + 1; opc != end; opc++) {

        if ((opc->handler.type & def->insns_flags) != 0) {

            if (register_insn(env->opcodes, opc) < 0) {

                printf("*** ERROR initializing PowerPC instruction "

                       "0x%02x 0x%02x 0x%02x\n", opc->opc1, opc->opc2,

                       opc->opc3);

                return -1;

            }

        }

    }

    fix_opcode_tables(env->opcodes);

    fflush(stdout);

    fflush(stderr);

    return 0;

}


Object *object_dynamic_cast_assert(Object *obj, const char *typename)

{

    Object *inst;

    inst = object_dynamic_cast(obj, typename);

    if (!inst) {

        fprintf(stderr, "Object %p is not an instance of type %s\n",

                obj, typename);

        abort();

    }

    return inst;

}


static inline int gen_intermediate_code_internal(CPUState *env,

                                                 TranslationBlock *tb,

                                                 int search_pc)

{

    DisasContext dc1, *dc = &dc1;

    uint16_t *gen_opc_end;

    int j, lj;

    target_ulong pc_start;

    uint32_t next_page_start;

    /* generate intermediate code */

    pc_start = tb->pc;

    dc->tb = tb;

    gen_opc_ptr = gen_opc_buf;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    gen_opparam_ptr = gen_opparam_buf;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = env->singlestep_enabled;

    dc->condjmp = 0;

    dc->thumb = env->thumb;

#if !defined(CONFIG_USER_ONLY)

    dc->user = (env->uncached_cpsr & 0x1f) == ARM_CPU_MODE_USR;

#endif

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    nb_gen_labels = 0;

    lj = -1;

    do {

        if (env->nb_breakpoints > 0) {

            for(j = 0; j < env->nb_breakpoints; j++) {

                if (env->breakpoints[j] == dc->pc) {

                    gen_op_movl_T0_im((long)dc->pc);

                    gen_op_movl_reg_TN[0][15]();

                    gen_op_debug();

                    dc->is_jmp = DISAS_JUMP;

                    break;

                }

            }

        }

        if (search_pc) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

            }

            gen_opc_pc[lj] = dc->pc;

            gen_opc_instr_start[lj] = 1;

        }

        if (env->thumb)

          disas_thumb_insn(dc);

        else

          disas_arm_insn(env, dc);

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        /* Terminate the TB on memory ops if watchpoints are present.  */

        /* FIXME: This should be replacd by the deterministic execution

         * IRQ raising bits.  */

        if (dc->is_mem && env->nb_watchpoints)

            break;

        /* Translation stops when a conditional branch is enoutered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefech aborts occur at the right place.  */

    } while (!dc->is_jmp && gen_opc_ptr < gen_opc_end &&

             !env->singlestep_enabled &&

             dc->pc < next_page_start);

    /* At this stage dc->condjmp will only be set when the skipped

     * instruction was a conditional branch, and the PC has already been

     * written.  */

    if (__builtin_expect(env->singlestep_enabled, 0)) {

        /* Make sure the pc is updated, and raise a debug exception.  */

        if (dc->condjmp) {

            gen_op_debug();

            gen_set_label(dc->condlabel);

        }

        if (dc->condjmp || !dc->is_jmp) {

            gen_op_movl_T0_im((long)dc->pc);

            gen_op_movl_reg_TN[0][15]();

            dc->condjmp = 0;

        }

        gen_op_debug();

    } else {

        switch(dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used to find the next TB */

            gen_op_movl_T0_0();

            gen_op_exit_tb();

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        }

        if (dc->condjmp) {

            gen_set_label(dc->condlabel);

            gen_goto_tb(dc, 1, dc->pc);

            dc->condjmp = 0;

        }

    }

    *gen_opc_ptr = INDEX_op_end;

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "----------------\n");

        fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start));

        target_disas(logfile, pc_start, dc->pc - pc_start, env->thumb);

        fprintf(logfile, "\n");

        if (loglevel & (CPU_LOG_TB_OP)) {

            fprintf(logfile, "OP:\n");

            dump_ops(gen_opc_buf, gen_opparam_buf);

            fprintf(logfile, "\n");

        }

    }

#endif

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

        tb->size = 0;

    } else {

        tb->size = dc->pc - pc_start;

    }

    return 0;

}


static void qcow_aio_read_cb(void *opaque, int ret)

{

    QCowAIOCB *acb = opaque;

    BlockDriverState *bs = acb->common.bs;

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n1;

    acb->hd_aiocb = NULL;

    if (ret < 0)

        goto done;

    /* post process the read buffer */

    if (!acb->cluster_offset) {

        /* nothing to do */

    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {

        /* nothing to do */

    } else {

        if (s->crypt_method) {

            qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,

                            acb->cur_nr_sectors, 0,

                            &s->aes_decrypt_key);

        }

    }

    acb->remaining_sectors -= acb->cur_nr_sectors;

    acb->sector_num += acb->cur_nr_sectors;

    acb->buf += acb->cur_nr_sectors * 512;

    if (acb->remaining_sectors == 0) {

        /* request completed */

        ret = 0;

        goto done;

    }

    /* prepare next AIO request */

    acb->cur_nr_sectors = acb->remaining_sectors;

    acb->cluster_offset = qcow2_get_cluster_offset(bs, acb->sector_num << 9,

                                                   &acb->cur_nr_sectors);

    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);

    if (!acb->cluster_offset) {

        if (bs->backing_hd) {

            /* read from the base image */

            n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,

                               acb->buf, acb->cur_nr_sectors);

            if (n1 > 0) {

                acb->hd_iov.iov_base = (void *)acb->buf;

                acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;

                qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);

                BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);

                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,

                                    &acb->hd_qiov, acb->cur_nr_sectors,

				    qcow_aio_read_cb, acb);

                if (acb->hd_aiocb == NULL)

                    goto done;

            } else {

                ret = qcow_schedule_bh(qcow_aio_read_bh, acb);

                if (ret < 0)

                    goto done;

            }

        } else {

            /* Note: in this case, no need to wait */

            memset(acb->buf, 0, 512 * acb->cur_nr_sectors);

            ret = qcow_schedule_bh(qcow_aio_read_bh, acb);

            if (ret < 0)

                goto done;

        }

    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {

        /* add AIO support for compressed blocks ? */

        if (qcow2_decompress_cluster(bs, acb->cluster_offset) < 0)

            goto done;

        memcpy(acb->buf, s->cluster_cache + index_in_cluster * 512,

               512 * acb->cur_nr_sectors);

        ret = qcow_schedule_bh(qcow_aio_read_bh, acb);

        if (ret < 0)

            goto done;

    } else {

        if ((acb->cluster_offset & 511) != 0) {

            ret = -EIO;

            goto done;

        }

        acb->hd_iov.iov_base = (void *)acb->buf;

        acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;

        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);

        BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);

        acb->hd_aiocb = bdrv_aio_readv(bs->file,

                            (acb->cluster_offset >> 9) + index_in_cluster,

                            &acb->hd_qiov, acb->cur_nr_sectors,

                            qcow_aio_read_cb, acb);

        if (acb->hd_aiocb == NULL) {

            ret = -EIO;

            goto done;

        }

    }

    return;

done:

    if (acb->qiov->niov > 1) {

        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);

        qemu_vfree(acb->orig_buf);

    }

    acb->common.cb(acb->common.opaque, ret);

    qemu_aio_release(acb);

}


opts_end_list(Visitor *v, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    assert(ov->list_mode == LM_STARTED || ov->list_mode == LM_IN_PROGRESS);

    ov->repeated_opts = NULL;

    ov->list_mode = LM_NONE;

}


static CaptureVoiceOut *audio_pcm_capture_find_specific (

    AudioState *s,

    audsettings_t *as

    )

{

    CaptureVoiceOut *cap;

    for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {

        if (audio_pcm_info_eq (&cap->hw.info, as)) {

            return cap;

        }

    }

    return NULL;

}


AVBufferRef *av_buffer_pool_get(AVBufferPool *pool)

{

    AVBufferRef *ret;

    BufferPoolEntry *buf;

    /* check whether the pool is empty */

    buf = get_pool(pool);

    if (!buf)

        return pool_alloc_buffer(pool);

    /* keep the first entry, return the rest of the list to the pool */

    add_to_pool(buf->next);

    buf->next = NULL;

    ret = av_buffer_create(buf->data, pool->size, pool_release_buffer,

                           buf, 0);

    if (!ret) {

        add_to_pool(buf);

        return NULL;

    }

    avpriv_atomic_int_add_and_fetch(&pool->refcount, 1);

    return ret;

}


static void QEMU_NORETURN force_sig(int target_sig)

{

    CPUState *cpu = thread_cpu;

    CPUArchState *env = cpu->env_ptr;

    TaskState *ts = (TaskState *)cpu->opaque;

    int host_sig, core_dumped = 0;

    struct sigaction act;

    host_sig = target_to_host_signal(target_sig);

    trace_user_force_sig(env, target_sig, host_sig);

    gdb_signalled(env, target_sig);

    /* dump core if supported by target binary format */

    if (core_dump_signal(target_sig) && (ts->bprm->core_dump != NULL)) {

        stop_all_tasks();

        core_dumped =

            ((*ts->bprm->core_dump)(target_sig, env) == 0);

    }

    if (core_dumped) {

        /* we already dumped the core of target process, we don't want

         * a coredump of qemu itself */

        struct rlimit nodump;

        getrlimit(RLIMIT_CORE, &nodump);

        nodump.rlim_cur=0;

        setrlimit(RLIMIT_CORE, &nodump);

        (void) fprintf(stderr, "qemu: uncaught target signal %d (%s) - %s\n",

            target_sig, strsignal(host_sig), "core dumped" );

    }

    /* The proper exit code for dying from an uncaught signal is

     * -<signal>.  The kernel doesn't allow exit() or _exit() to pass

     * a negative value.  To get the proper exit code we need to

     * actually die from an uncaught signal.  Here the default signal

     * handler is installed, we send ourself a signal and we wait for

     * it to arrive. */

    sigfillset(&act.sa_mask);

    act.sa_handler = SIG_DFL;

    act.sa_flags = 0;

    sigaction(host_sig, &act, NULL);

    /* For some reason raise(host_sig) doesn't send the signal when

     * statically linked on x86-64. */

    kill(getpid(), host_sig);

    /* Make sure the signal isn't masked (just reuse the mask inside

    of act) */

    sigdelset(&act.sa_mask, host_sig);

    sigsuspend(&act.sa_mask);

    /* unreachable */

    abort();

}


static int scale_vector(int16_t *dst, const int16_t *vector, int length)

{

    int bits, max = 0;

    int i;

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

        max |= FFABS(vector[i]);

    bits  = normalize_bits(max, 15);

    if (bits == 15)

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

            dst[i] = vector[i] * 0x7fff >> 3;

    else

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

            dst[i] = vector[i] << bits >> 3;

    return bits - 3;

}


static int virtio_ccw_hcall_notify(const uint64_t *args)

{

    uint64_t subch_id = args[0];

    uint64_t queue = args[1];

    SubchDev *sch;

    int cssid, ssid, schid, m;

    if (ioinst_disassemble_sch_ident(subch_id, &m, &cssid, &ssid, &schid)) {

        return -EINVAL;

    }

    sch = css_find_subch(m, cssid, ssid, schid);

    if (!sch || !css_subch_visible(sch)) {

        return -EINVAL;

    }

    if (queue >= VIRTIO_PCI_QUEUE_MAX) {

        return -EINVAL;

    }

    virtio_queue_notify(virtio_ccw_get_vdev(sch), queue);

    return 0;

}


void prepare_grab(void)

{

    int has_video, has_audio, i, j;

    AVFormatContext *oc;

    AVFormatContext *ic;

    AVFormatParameters ap1, *ap = &ap1;

    /* see if audio/video inputs are needed */

    has_video = 0;

    has_audio = 0;

    memset(ap, 0, sizeof(*ap));

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

        oc = output_files[j];

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

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

            switch(enc->codec_type) {

            case CODEC_TYPE_AUDIO:

                if (enc->sample_rate > ap->sample_rate)

                    ap->sample_rate = enc->sample_rate;

                if (enc->channels > ap->channels)

                    ap->channels = enc->channels;

                has_audio = 1;

                break;

            case CODEC_TYPE_VIDEO:

                if (enc->width > ap->width)

                    ap->width = enc->width;

                if (enc->height > ap->height)

                    ap->height = enc->height;

                if (enc->frame_rate > ap->frame_rate)

                    ap->frame_rate = enc->frame_rate;

                has_video = 1;

                break;

            default:

                abort();

            }

        }

    }

    if (has_video == 0 && has_audio == 0) {

        fprintf(stderr, "Output file must have at least one audio or video stream\n");

        exit(1);

    }

    if (has_video) {

        AVInputFormat *fmt1;

        fmt1 = av_find_input_format("video_grab_device");

        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {

            fprintf(stderr, "Could not find video grab device\n");

            exit(1);

        }

        /* by now video grab has one stream */

        ic->streams[0]->r_frame_rate = ap->frame_rate;

        input_files[nb_input_files] = ic;

        dump_format(ic, nb_input_files, v4l_device, 0);

        nb_input_files++;

    }

    if (has_audio) {

        AVInputFormat *fmt1;

        fmt1 = av_find_input_format("audio_device");

        if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {

            fprintf(stderr, "Could not find audio grab device\n");

            exit(1);

        }

        input_files[nb_input_files] = ic;

        dump_format(ic, nb_input_files, audio_device, 0);

        nb_input_files++;

    }

}


static void ipvideo_decode_opcodes(IpvideoContext *s)

{

    int x, y;

    unsigned char opcode;

    int ret;

    static int frame = 0;

    GetBitContext gb;

    debug_interplay("------------------ frame %d\n", frame);

    frame++;

    /* this is PAL8, so make the palette available */

    memcpy(s->current_frame.data[1], s->avctx->palctrl->palette, PALETTE_COUNT * 4);

    s->stride = s->current_frame.linesize[0];

    s->stream_ptr = s->buf + 14;  /* data starts 14 bytes in */

    s->stream_end = s->buf + s->size;

    s->line_inc = s->stride - 8;

    s->upper_motion_limit_offset = (s->avctx->height - 8) * s->stride

        + s->avctx->width - 8;

    init_get_bits(&gb, s->decoding_map, s->decoding_map_size * 8);

    for (y = 0; y < (s->stride * s->avctx->height); y += s->stride * 8) {

        for (x = y; x < y + s->avctx->width; x += 8) {

            opcode = get_bits(&gb, 4);

            debug_interplay("  block @ (%3d, %3d): encoding 0x%X, data ptr @ %p\n",

                            x - y, y / s->stride, opcode, s->stream_ptr);

            s->pixel_ptr = s->current_frame.data[0] + x;

            ret = ipvideo_decode_block[opcode](s);

            if (ret != 0) {

                av_log(s->avctx, AV_LOG_ERROR, " Interplay video: decode problem on frame %d, @ block (%d, %d)\n",

                       frame, x - y, y / s->stride);

                return;

            }

        }

    }

    if (s->stream_end - s->stream_ptr > 1) {

        av_log(s->avctx, AV_LOG_ERROR, " Interplay video: decode finished with %td bytes left over\n",

               s->stream_end - s->stream_ptr);

    }

}


static inline void cris_fidx_i(unsigned int x)

{

	register unsigned int v asm("$r10") = x;

	asm ("fidxi\t[%0]\n" : : "r" (v) );

}


static void test_nested_struct_list(gconstpointer opaque)

{

    TestArgs *args = (TestArgs *) opaque;

    const SerializeOps *ops = args->ops;

    UserDefNestedList *listp = NULL, *tmp, *tmp_copy, *listp_copy = NULL;

    Error *err = NULL;

    void *serialize_data;

    int i = 0;

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

        tmp = g_malloc0(sizeof(UserDefNestedList));

        tmp->value = nested_struct_create();

        tmp->next = listp;

        listp = tmp;

    }

    ops->serialize(listp, &serialize_data, visit_nested_struct_list, &err);

    ops->deserialize((void **)&listp_copy, serialize_data,

                     visit_nested_struct_list, &err);

    g_assert(err == NULL);

    tmp = listp;

    tmp_copy = listp_copy;

    while (listp_copy) {

        g_assert(listp);

        nested_struct_compare(listp->value, listp_copy->value);

        listp = listp->next;

        listp_copy = listp_copy->next;

    }

    qapi_free_UserDefNestedList(tmp);

    qapi_free_UserDefNestedList(tmp_copy);

    ops->cleanup(serialize_data);

    g_free(args);

}


static void handle_char(CCaptionSubContext *ctx, char hi, char lo, int64_t pts)

{

    struct Screen *screen = get_writing_screen(ctx);

    char *row = screen->characters[ctx->cursor_row];

    int ret;

    SET_FLAG(screen->row_used,ctx->cursor_row);

    ret = write_char(ctx, row, ctx->cursor_column, hi);

    if( ret == 0 )

        ctx->cursor_column++;

    if(lo) {

        ret = write_char(ctx, row, ctx->cursor_column, lo);

        if ( ret == 0 )

            ctx->cursor_column++;

    }

    write_char(ctx, row, ctx->cursor_column, 0);

    /* reset prev command since character can repeat */

    ctx->prev_cmd[0] = 0;

    ctx->prev_cmd[1] = 0;

    if (lo)

       av_dlog(ctx, "(%c,%c)\n",hi,lo);

    else

       av_dlog(ctx, "(%c)\n",hi);

}


int qemu_cpu_is_self(void *env)

{

    return 1;

}


BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
                                  QEMUIOVector *iov, int nb_sectors,
                                  BlockDriverCompletionFunc *cb, void *opaque)
{
    return bdrv_aio_rw_vector(bs, sector_num, iov, nb_sectors,
                              cb, opaque, 1);
}


static void omap_mcbsp_writeh(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    switch (offset) {

    case 0x00:	/* DRR2 */

    case 0x02:	/* DRR1 */

        OMAP_RO_REG(addr);

        return;

    case 0x04:	/* DXR2 */

        if (((s->xcr[0] >> 5) & 7) < 3)			/* XWDLEN1 */

            return;

        /* Fall through.  */

    case 0x06:	/* DXR1 */

        if (s->tx_req > 1) {

            s->tx_req -= 2;

            if (s->codec && s->codec->cts) {

                s->codec->out.fifo[s->codec->out.len ++] = (value >> 8) & 0xff;

                s->codec->out.fifo[s->codec->out.len ++] = (value >> 0) & 0xff;

            }

            if (s->tx_req < 2)

                omap_mcbsp_tx_done(s);

        } else

            printf("%s: Tx FIFO overrun\n", __FUNCTION__);

        return;

    case 0x08:	/* SPCR2 */

        s->spcr[1] &= 0x0002;

        s->spcr[1] |= 0x03f9 & value;

        s->spcr[1] |= 0x0004 & (value << 2);		/* XEMPTY := XRST */

        if (~value & 1)					/* XRST */

            s->spcr[1] &= ~6;

        omap_mcbsp_req_update(s);

        return;

    case 0x0a:	/* SPCR1 */

        s->spcr[0] &= 0x0006;

        s->spcr[0] |= 0xf8f9 & value;

        if (value & (1 << 15))				/* DLB */

            printf("%s: Digital Loopback mode enable attempt\n", __FUNCTION__);

        if (~value & 1) {				/* RRST */

            s->spcr[0] &= ~6;

            s->rx_req = 0;

            omap_mcbsp_rx_done(s);

        }

        omap_mcbsp_req_update(s);

        return;

    case 0x0c:	/* RCR2 */

        s->rcr[1] = value & 0xffff;

        return;

    case 0x0e:	/* RCR1 */

        s->rcr[0] = value & 0x7fe0;

        return;

    case 0x10:	/* XCR2 */

        s->xcr[1] = value & 0xffff;

        return;

    case 0x12:	/* XCR1 */

        s->xcr[0] = value & 0x7fe0;

        return;

    case 0x14:	/* SRGR2 */

        s->srgr[1] = value & 0xffff;

        omap_mcbsp_req_update(s);

        return;

    case 0x16:	/* SRGR1 */

        s->srgr[0] = value & 0xffff;

        omap_mcbsp_req_update(s);

        return;

    case 0x18:	/* MCR2 */

        s->mcr[1] = value & 0x03e3;

        if (value & 3)					/* XMCM */

            printf("%s: Tx channel selection mode enable attempt\n",

                            __FUNCTION__);

        return;

    case 0x1a:	/* MCR1 */

        s->mcr[0] = value & 0x03e1;

        if (value & 1)					/* RMCM */

            printf("%s: Rx channel selection mode enable attempt\n",

                            __FUNCTION__);

        return;

    case 0x1c:	/* RCERA */

        s->rcer[0] = value & 0xffff;

        return;

    case 0x1e:	/* RCERB */

        s->rcer[1] = value & 0xffff;

        return;

    case 0x20:	/* XCERA */

        s->xcer[0] = value & 0xffff;

        return;

    case 0x22:	/* XCERB */

        s->xcer[1] = value & 0xffff;

        return;

    case 0x24:	/* PCR0 */

        s->pcr = value & 0x7faf;

        return;

    case 0x26:	/* RCERC */

        s->rcer[2] = value & 0xffff;

        return;

    case 0x28:	/* RCERD */

        s->rcer[3] = value & 0xffff;

        return;

    case 0x2a:	/* XCERC */

        s->xcer[2] = value & 0xffff;

        return;

    case 0x2c:	/* XCERD */

        s->xcer[3] = value & 0xffff;

        return;

    case 0x2e:	/* RCERE */

        s->rcer[4] = value & 0xffff;

        return;

    case 0x30:	/* RCERF */

        s->rcer[5] = value & 0xffff;

        return;

    case 0x32:	/* XCERE */

        s->xcer[4] = value & 0xffff;

        return;

    case 0x34:	/* XCERF */

        s->xcer[5] = value & 0xffff;

        return;

    case 0x36:	/* RCERG */

        s->rcer[6] = value & 0xffff;

        return;

    case 0x38:	/* RCERH */

        s->rcer[7] = value & 0xffff;

        return;

    case 0x3a:	/* XCERG */

        s->xcer[6] = value & 0xffff;

        return;

    case 0x3c:	/* XCERH */

        s->xcer[7] = value & 0xffff;

        return;

    }

    OMAP_BAD_REG(addr);

}


static int filter_frame(AVFilterLink *inlink, AVFrame *buf)

{

    AVFilterContext *ctx = inlink->dst;

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

    DeflickerContext *s = ctx->priv;

    AVDictionary **metadata;

    AVFrame *out, *in;

    float f;

    int y;

    if (s->q.available < s->size && !s->eof) {

        s->luminance[s->available] = s->calc_avgy(ctx, buf);

        ff_bufqueue_add(ctx, &s->q, buf);

        s->available++;

        return 0;

    }

    in = ff_bufqueue_peek(&s->q, 0);

    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);

    if (!out) {

        av_frame_free(&buf);

        return AVERROR(ENOMEM);

    }

    s->get_factor(ctx, &f);

    s->deflicker(ctx, in->data[0], in->linesize[0], out->data[0], out->linesize[0],

                 outlink->w, outlink->h, f);

    for (y = 1; y < s->nb_planes; y++) {

        av_image_copy_plane(out->data[y], out->linesize[y],

                            in->data[y], in->linesize[y],

                            s->planewidth[y] * (1 + (s->depth > 8)), s->planeheight[y]);

    }

    av_frame_copy_props(out, in);

    metadata = &out->metadata;

    if (metadata) {

        uint8_t value[128];

        snprintf(value, sizeof(value), "%f", s->luminance[0]);

        av_dict_set(metadata, "lavfi.deflicker.luminance", value, 0);

        snprintf(value, sizeof(value), "%f", s->luminance[0] * f);

        av_dict_set(metadata, "lavfi.deflicker.new_luminance", value, 0);

        snprintf(value, sizeof(value), "%f", f - 1.0f);

        av_dict_set(metadata, "lavfi.deflicker.relative_change", value, 0);

    }

    in = ff_bufqueue_get(&s->q);

    av_frame_free(&in);

    memmove(&s->luminance[0], &s->luminance[1], sizeof(*s->luminance) * (s->size - 1));

    s->luminance[s->available - 1] = s->calc_avgy(ctx, buf);

    ff_bufqueue_add(ctx, &s->q, buf);

    return ff_filter_frame(outlink, out);

}


static DriveInfo *blockdev_init(QDict *bs_opts,

                                BlockInterfaceType type,

                                Error **errp)

{

    const char *buf;

    const char *file = NULL;

    const char *serial;

    int ro = 0;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    DriveInfo *dinfo;

    ThrottleConfig cfg;

    int snapshot = 0;

    bool copy_on_read;

    int ret;

    Error *error = NULL;

    QemuOpts *opts;

    const char *id;

    bool has_driver_specific_opts;

    BlockDriver *drv = NULL;

    /* Check common options by copying from bs_opts to opts, all other options

     * stay in bs_opts for processing by bdrv_open(). */

    id = qdict_get_try_str(bs_opts, "id");

    opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);

    if (error_is_set(&error)) {

        error_propagate(errp, error);

        return NULL;

    }

    qemu_opts_absorb_qdict(opts, bs_opts, &error);

    if (error_is_set(&error)) {

        error_propagate(errp, error);

        return NULL;

    }

    if (id) {

        qdict_del(bs_opts, "id");

    }

    has_driver_specific_opts = !!qdict_size(bs_opts);

    /* extract parameters */

    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);

    ro = qemu_opt_get_bool(opts, "read-only", 0);

    copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);

    file = qemu_opt_get(opts, "file");

    serial = qemu_opt_get(opts, "serial");

    if ((buf = qemu_opt_get(opts, "discard")) != NULL) {

        if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {

            error_setg(errp, "invalid discard option");

            return NULL;

        }

    }

    if (qemu_opt_get_bool(opts, "cache.writeback", true)) {

        bdrv_flags |= BDRV_O_CACHE_WB;

    }

    if (qemu_opt_get_bool(opts, "cache.direct", false)) {

        bdrv_flags |= BDRV_O_NOCACHE;

    }

    if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {

        bdrv_flags |= BDRV_O_NO_FLUSH;

    }

#ifdef CONFIG_LINUX_AIO

    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {

        if (!strcmp(buf, "native")) {

            bdrv_flags |= BDRV_O_NATIVE_AIO;

        } else if (!strcmp(buf, "threads")) {

            /* this is the default */

        } else {

           error_setg(errp, "invalid aio option");

           return NULL;

        }

    }

#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {

        if (is_help_option(buf)) {

            error_printf("Supported formats:");

            bdrv_iterate_format(bdrv_format_print, NULL);

            error_printf("\n");

            return NULL;

        }

        drv = bdrv_find_format(buf);

        if (!drv) {

            error_setg(errp, "'%s' invalid format", buf);

            return NULL;

        }

    }

    /* disk I/O throttling */

    memset(&cfg, 0, sizeof(cfg));

    cfg.buckets[THROTTLE_BPS_TOTAL].avg =

        qemu_opt_get_number(opts, "throttling.bps-total", 0);

    cfg.buckets[THROTTLE_BPS_READ].avg  =

        qemu_opt_get_number(opts, "throttling.bps-read", 0);

    cfg.buckets[THROTTLE_BPS_WRITE].avg =

        qemu_opt_get_number(opts, "throttling.bps-write", 0);

    cfg.buckets[THROTTLE_OPS_TOTAL].avg =

        qemu_opt_get_number(opts, "throttling.iops-total", 0);

    cfg.buckets[THROTTLE_OPS_READ].avg =

        qemu_opt_get_number(opts, "throttling.iops-read", 0);

    cfg.buckets[THROTTLE_OPS_WRITE].avg =

        qemu_opt_get_number(opts, "throttling.iops-write", 0);

    cfg.buckets[THROTTLE_BPS_TOTAL].max =

        qemu_opt_get_number(opts, "throttling.bps-total-max", 0);

    cfg.buckets[THROTTLE_BPS_READ].max  =

        qemu_opt_get_number(opts, "throttling.bps-read-max", 0);

    cfg.buckets[THROTTLE_BPS_WRITE].max =

        qemu_opt_get_number(opts, "throttling.bps-write-max", 0);

    cfg.buckets[THROTTLE_OPS_TOTAL].max =

        qemu_opt_get_number(opts, "throttling.iops-total-max", 0);

    cfg.buckets[THROTTLE_OPS_READ].max =

        qemu_opt_get_number(opts, "throttling.iops-read-max", 0);

    cfg.buckets[THROTTLE_OPS_WRITE].max =

        qemu_opt_get_number(opts, "throttling.iops-write-max", 0);

    cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);

    if (!check_throttle_config(&cfg, &error)) {

        error_propagate(errp, error);

        return NULL;

    }

    on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;

    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {

            error_setg(errp, "werror is not supported by this bus type");

            return NULL;

        }

        on_write_error = parse_block_error_action(buf, 0, &error);

        if (error_is_set(&error)) {

            error_propagate(errp, error);

            return NULL;

        }

    }

    on_read_error = BLOCKDEV_ON_ERROR_REPORT;

    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {

        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {

            error_report("rerror is not supported by this bus type");

            return NULL;

        }

        on_read_error = parse_block_error_action(buf, 1, &error);

        if (error_is_set(&error)) {

            error_propagate(errp, error);

            return NULL;

        }

    }

    /* init */

    dinfo = g_malloc0(sizeof(*dinfo));

    dinfo->id = g_strdup(qemu_opts_id(opts));

    dinfo->bdrv = bdrv_new(dinfo->id);

    dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;

    dinfo->bdrv->read_only = ro;

    dinfo->type = type;

    dinfo->refcount = 1;

    if (serial != NULL) {

        dinfo->serial = g_strdup(serial);

    }

    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

    /* disk I/O throttling */

    if (throttle_enabled(&cfg)) {

        bdrv_io_limits_enable(dinfo->bdrv);

        bdrv_set_io_limits(dinfo->bdrv, &cfg);

    }

    if (!file || !*file) {

        if (has_driver_specific_opts) {

            file = NULL;

        } else {

            return dinfo;

        }

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    if (copy_on_read) {

        bdrv_flags |= BDRV_O_COPY_ON_READ;

    }

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        bdrv_flags |= BDRV_O_INCOMING;

    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

    QINCREF(bs_opts);

    ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv, &error);

    if (ret < 0) {

        error_setg(errp, "could not open disk image %s: %s",

                   file ?: dinfo->id, error_get_pretty(error));

        error_free(error);

        goto err;

    }

    if (bdrv_key_required(dinfo->bdrv))

        autostart = 0;

    QDECREF(bs_opts);

    qemu_opts_del(opts);

    return dinfo;

err:

    qemu_opts_del(opts);

    QDECREF(bs_opts);

    bdrv_unref(dinfo->bdrv);

    g_free(dinfo->id);

    QTAILQ_REMOVE(&drives, dinfo, next);

    g_free(dinfo);

    return NULL;

}


inline static void RENAME(hcscale)(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)

{

    if(srcFormat==IMGFMT_YUY2)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_UYVY)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR32)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR24)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR16)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR15)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_RGB32)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_RGB24)

    {

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

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(isGray(srcFormat))

    {

    	return;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if the mmx2 can't be used (its faster than the x86asm 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+2048, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#if defined(ARCH_X86) || defined(ARCH_X86_64)

#ifdef HAVE_MMX2

	int i;

	if(canMMX2BeUsed)

	{

		asm volatile(

			"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

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 $4096, %%"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

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

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

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

		);

		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+2048] = src2[srcW-1]*128;

		}

	}

	else

	{

#endif

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

	uint16_t xInc_mask = xInc & 0xffff;

	asm volatile(

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

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

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

		ASMALIGN16

		"1:				\n\t"

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

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

		"movzbl 1(%%"REG_S", %%"REG_b"), %%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_b"), %%edi	\n\t" //src[xx]

		"movzbl 1(%5, %%"REG_b"), %%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, 4096(%%"REG_D", %%"REG_a", 2)\n\t"

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

		"adc %3, %%"REG_b"		\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_b, "%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+2048]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

/* slower

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

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

*/

		xpos+=xInc;

	}

#endif

   }

}