static void pc_init1(MachineState *machine,

                     int pci_enabled,

                     int kvmclock_enabled)

{

    PCMachineState *pc_machine = PC_MACHINE(machine);

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq *smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    ISADevice *floppy;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    DeviceState *icc_bridge;

    FWCfgState *fw_cfg = NULL;

    PcGuestInfo *guest_info;

    ram_addr_t lowmem;

    /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory).

     * If it doesn't, we need to split it in chunks below and above 4G.

     * In any case, try to make sure that guest addresses aligned at

     * 1G boundaries get mapped to host addresses aligned at 1G boundaries.

     * For old machine types, use whatever split we used historically to avoid

     * breaking migration.

     */

    if (machine->ram_size >= 0xe0000000) {

        lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000;

    } else {

        lowmem = 0xe0000000;

    }

    /* Handle the machine opt max-ram-below-4g.  It is basically doing

     * min(qemu limit, user limit).

     */

    if (lowmem > pc_machine->max_ram_below_4g) {

        lowmem = pc_machine->max_ram_below_4g;

        if (machine->ram_size - lowmem > lowmem &&

            lowmem & ((1ULL << 30) - 1)) {

            error_report("Warning: Large machine and max_ram_below_4g(%"PRIu64

                         ") not a multiple of 1G; possible bad performance.",

                         pc_machine->max_ram_below_4g);

        }

    }

    if (machine->ram_size >= lowmem) {

        above_4g_mem_size = machine->ram_size - lowmem;

        below_4g_mem_size = lowmem;

    } else {

        above_4g_mem_size = 0;

        below_4g_mem_size = machine->ram_size;

    }

    if (xen_enabled() && xen_hvm_init(&below_4g_mem_size, &above_4g_mem_size,

                                      &ram_memory) != 0) {

        fprintf(stderr, "xen hardware virtual machine initialisation failed\n");

        exit(1);

    }

    icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE);

    object_property_add_child(qdev_get_machine(), "icc-bridge",

                              OBJECT(icc_bridge), NULL);

    pc_cpus_init(machine->cpu_model, icc_bridge);

    if (kvm_enabled() && kvmclock_enabled) {

        kvmclock_create();

    }

    if (pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size);

    guest_info->has_acpi_build = has_acpi_build;

    guest_info->legacy_acpi_table_size = legacy_acpi_table_size;

    guest_info->isapc_ram_fw = !pci_enabled;

    guest_info->has_reserved_memory = has_reserved_memory;

    if (smbios_defaults) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            mc->name, smbios_legacy_mode);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        fw_cfg = pc_memory_init(machine, system_memory,

                                below_4g_mem_size, above_4g_mem_size,

                                rom_memory, &ram_memory, guest_info);

    } else if (machine->kernel_filename != NULL) {

        /* For xen HVM direct kernel boot, load linux here */

        fw_cfg = xen_load_linux(machine->kernel_filename,

                                machine->kernel_cmdline,

                                machine->initrd_filename,

                                below_4g_mem_size,

                                guest_info);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_irqchip_in_kernel()) {

        kvm_pc_setup_irq_routing(pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, machine->ram_size,

                              below_4g_mem_size,

                              above_4g_mem_size,

                              pci_memory, ram_memory);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, system_io);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_irqchip_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        cpu_irq = pc_allocate_cpu_irq();

        i8259 = i8259_init(isa_bus, cpu_irq[0]);

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    if (pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    qdev_init_nofail(icc_bridge);

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL);

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, xen_enabled(),

        0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, MAX_IDE_BUS);

    if (pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, machine->boot_order,

                 floppy, idebus[0], idebus[1], rtc_state);

    if (pci_enabled && usb_enabled(false)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pci_enabled && acpi_enabled) {

        DeviceState *piix4_pm;

        I2CBus *smbus;

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], *smi_irq,

                              kvm_enabled(), fw_cfg, &piix4_pm);

        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,

                                 TYPE_HOTPLUG_HANDLER,

                                 (Object **)&pc_machine->acpi_dev,

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),

                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

}


int ffio_rewind_with_probe_data(AVIOContext *s, unsigned char *buf, int buf_size)

{

    int64_t buffer_start;

    int buffer_size;

    int overlap, new_size, alloc_size;

    if (s->write_flag)

        return AVERROR(EINVAL);

    buffer_size = s->buf_end - s->buffer;

    /* the buffers must touch or overlap */

    if ((buffer_start = s->pos - buffer_size) > buf_size)

        return AVERROR(EINVAL);

    overlap = buf_size - buffer_start;

    new_size = buf_size + buffer_size - overlap;

    alloc_size = FFMAX(s->buffer_size, new_size);

    if (alloc_size > buf_size)

        if (!(buf = av_realloc_f(buf, 1, alloc_size)))

            return AVERROR(ENOMEM);

    if (new_size > buf_size) {

        memcpy(buf + buf_size, s->buffer + overlap, buffer_size - overlap);

        buf_size = new_size;

    }

    av_free(s->buffer);

    s->buf_ptr = s->buffer = buf;

    s->buffer_size = alloc_size;

    s->pos = buf_size;

    s->buf_end = s->buf_ptr + buf_size;

    s->eof_reached = 0;

    s->must_flush = 0;

    return 0;

}


static int url_connect(struct playlist *pls, AVDictionary *opts, AVDictionary *opts2)

{

    AVDictionary *tmp = NULL;

    int ret;

    av_dict_copy(&tmp, opts, 0);

    av_dict_copy(&tmp, opts2, 0);

    av_opt_set_dict(pls->input, &tmp);

    if ((ret = ffurl_connect(pls->input, NULL)) < 0) {

        ffurl_close(pls->input);

        pls->input = NULL;

    }

    av_dict_free(&tmp);

    return ret;

}


void ff_insert_pad(unsigned idx, unsigned *count, size_t padidx_off,

                   AVFilterPad **pads, AVFilterLink ***links,

                   AVFilterPad *newpad)

{

    unsigned i;

    idx = FFMIN(idx, *count);

    *pads  = av_realloc(*pads,  sizeof(AVFilterPad)   * (*count + 1));

    *links = av_realloc(*links, sizeof(AVFilterLink*) * (*count + 1));

    memmove(*pads  + idx + 1, *pads  + idx, sizeof(AVFilterPad)   * (*count - idx));

    memmove(*links + idx + 1, *links + idx, sizeof(AVFilterLink*) * (*count - idx));

    memcpy(*pads + idx, newpad, sizeof(AVFilterPad));

    (*links)[idx] = NULL;

    (*count)++;

    for (i = idx + 1; i < *count; i++)

        if (*links[i])

            (*(unsigned *)((uint8_t *) *links[i] + padidx_off))++;

}


static int spapr_cpu_core_realize_child(Object *child, void *opaque)

{

    Error **errp = opaque, *local_err = NULL;

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    CPUState *cs = CPU(child);

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    object_property_set_bool(child, true, "realized", &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return 1;

    }

    spapr_cpu_init(spapr, cpu, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return 1;

    }

    return 0;

}


static void blkverify_aio_cb(void *opaque, int ret)

{

    BlkverifyAIOCB *acb = opaque;

    switch (++acb->done) {

    case 1:

        acb->ret = ret;

        break;

    case 2:

        if (acb->ret != ret) {

            blkverify_err(acb, "return value mismatch %d != %d", acb->ret, ret);

        }

        if (acb->verify) {

            acb->verify(acb);

        }

        aio_bh_schedule_oneshot(bdrv_get_aio_context(acb->common.bs),

                                blkverify_aio_bh, acb);

        break;

    }

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *in_picture,

                         int *frame_size)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->st->codec;

    *frame_size = 0;

    format_video_sync = video_sync_method;

    if (format_video_sync == VSYNC_AUTO)

        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :

                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;

    if (format_video_sync != VSYNC_PASSTHROUGH &&

        ost->frame_number &&

        in_picture->pts != AV_NOPTS_VALUE &&

        in_picture->pts < ost->sync_opts) {

        nb_frames_drop++;

        av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");

        return;

    }

    if (in_picture->pts == AV_NOPTS_VALUE)

        in_picture->pts = ost->sync_opts;

    ost->sync_opts = in_picture->pts;

    if (!ost->frame_number)

        ost->first_pts = in_picture->pts;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (ost->frame_number >= ost->max_frames)

        return;

    if (s->oformat->flags & AVFMT_RAWPICTURE &&

        enc->codec->id == AV_CODEC_ID_RAWVIDEO) {

        /* raw pictures are written as AVPicture structure to

           avoid any copies. We support temporarily the older

           method. */

        enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;

        enc->coded_frame->top_field_first  = in_picture->top_field_first;

        pkt.data   = (uint8_t *)in_picture;

        pkt.size   =  sizeof(AVPicture);

        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= AV_PKT_FLAG_KEY;

        write_frame(s, &pkt, ost);

    } else {

        int got_packet;

        if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&

            ost->top_field_first >= 0)

            in_picture->top_field_first = !!ost->top_field_first;

        in_picture->quality = ost->st->codec->global_quality;

        if (!enc->me_threshold)

            in_picture->pict_type = 0;

        if (ost->forced_kf_index < ost->forced_kf_count &&

            in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

            in_picture->pict_type = AV_PICTURE_TYPE_I;

            ost->forced_kf_index++;

        }

        ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);

        if (ret < 0) {

            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

            exit(1);

        }

        if (got_packet) {

            if (pkt.pts != AV_NOPTS_VALUE)

                pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);

            if (pkt.dts != AV_NOPTS_VALUE)

                pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);

            write_frame(s, &pkt, ost);

            *frame_size = pkt.size;

            video_size += pkt.size;

            /* if two pass, output log */

            if (ost->logfile && enc->stats_out) {

                fprintf(ost->logfile, "%s", enc->stats_out);

            }

        }

    }

    ost->sync_opts++;

    /*

     * For video, number of frames in == number of packets out.

     * But there may be reordering, so we can't throw away frames on encoder

     * flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

}


static void pc_init_pci_1_4(QEMUMachineInitArgs *args)

{

    pc_sysfw_flash_vs_rom_bug_compatible = true;

    has_pvpanic = false;

    x86_cpu_compat_set_features("n270", FEAT_1_ECX, 0, CPUID_EXT_MOVBE);

    pc_init_pci(args);

}


void cpu_dump_state (CPUState *env, FILE *f, fprintf_function cpu_fprintf,
                     int flags)
{
#define RGPL  4
#define RFPL  4
    int i;
    cpu_fprintf(f, "NIP " TARGET_FMT_lx "   LR " TARGET_FMT_lx " CTR "
                TARGET_FMT_lx " XER " TARGET_FMT_lx "\n",
                env->nip, env->lr, env->ctr, env->xer);
    cpu_fprintf(f, "MSR " TARGET_FMT_lx " HID0 " TARGET_FMT_lx "  HF "
                TARGET_FMT_lx " idx %d\n", env->msr, env->spr[SPR_HID0],
                env->hflags, env->mmu_idx);
#if !defined(NO_TIMER_DUMP)
    cpu_fprintf(f, "TB %08" PRIu32 " %08" PRIu64
#if !defined(CONFIG_USER_ONLY)
                " DECR %08" PRIu32
                "\n",
                cpu_ppc_load_tbu(env), cpu_ppc_load_tbl(env)
#if !defined(CONFIG_USER_ONLY)
                , cpu_ppc_load_decr(env)
                );
    for (i = 0; i < 32; i++) {
        if ((i & (RGPL - 1)) == 0)
            cpu_fprintf(f, "GPR%02d", i);
        cpu_fprintf(f, " %016" PRIx64, ppc_dump_gpr(env, i));
        if ((i & (RGPL - 1)) == (RGPL - 1))
            cpu_fprintf(f, "\n");
    cpu_fprintf(f, "CR ");
    for (i = 0; i < 8; i++)
        cpu_fprintf(f, "%01x", env->crf[i]);
    cpu_fprintf(f, "  [");
    for (i = 0; i < 8; i++) {
        char a = '-';
        if (env->crf[i] & 0x08)
            a = 'L';
        else if (env->crf[i] & 0x04)
            a = 'G';
        else if (env->crf[i] & 0x02)
            a = 'E';
        cpu_fprintf(f, " %c%c", a, env->crf[i] & 0x01 ? 'O' : ' ');
    cpu_fprintf(f, " ]             RES " TARGET_FMT_lx "\n",
                env->reserve_addr);
    for (i = 0; i < 32; i++) {
        if ((i & (RFPL - 1)) == 0)
            cpu_fprintf(f, "FPR%02d", i);
        cpu_fprintf(f, " %016" PRIx64, *((uint64_t *)&env->fpr[i]));
        if ((i & (RFPL - 1)) == (RFPL - 1))
            cpu_fprintf(f, "\n");
    cpu_fprintf(f, "FPSCR %08x\n", env->fpscr);
#if !defined(CONFIG_USER_ONLY)
    cpu_fprintf(f, " SRR0 " TARGET_FMT_lx "  SRR1 " TARGET_FMT_lx
                   "    PVR " TARGET_FMT_lx " VRSAVE " TARGET_FMT_lx "\n",
                env->spr[SPR_SRR0], env->spr[SPR_SRR1],
                env->spr[SPR_PVR], env->spr[SPR_VRSAVE]);
    cpu_fprintf(f, "SPRG0 " TARGET_FMT_lx " SPRG1 " TARGET_FMT_lx
                   "  SPRG2 " TARGET_FMT_lx "  SPRG3 " TARGET_FMT_lx "\n",
                env->spr[SPR_SPRG0], env->spr[SPR_SPRG1],
                env->spr[SPR_SPRG2], env->spr[SPR_SPRG3]);
    cpu_fprintf(f, "SPRG4 " TARGET_FMT_lx " SPRG5 " TARGET_FMT_lx
                   "  SPRG6 " TARGET_FMT_lx "  SPRG7 " TARGET_FMT_lx "\n",
                env->spr[SPR_SPRG4], env->spr[SPR_SPRG5],
                env->spr[SPR_SPRG6], env->spr[SPR_SPRG7]);
    if (env->excp_model == POWERPC_EXCP_BOOKE) {
        cpu_fprintf(f, "CSRR0 " TARGET_FMT_lx " CSRR1 " TARGET_FMT_lx
                       " MCSRR0 " TARGET_FMT_lx " MCSRR1 " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_CSRR0], env->spr[SPR_BOOKE_CSRR1],
                    env->spr[SPR_BOOKE_MCSRR0], env->spr[SPR_BOOKE_MCSRR1]);
        cpu_fprintf(f, "  TCR " TARGET_FMT_lx "   TSR " TARGET_FMT_lx
                       "    ESR " TARGET_FMT_lx "   DEAR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_TCR], env->spr[SPR_BOOKE_TSR],
                    env->spr[SPR_BOOKE_ESR], env->spr[SPR_BOOKE_DEAR]);
        cpu_fprintf(f, "  PIR " TARGET_FMT_lx " DECAR " TARGET_FMT_lx
                       "   IVPR " TARGET_FMT_lx "   EPCR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_PIR], env->spr[SPR_BOOKE_DECAR],
                    env->spr[SPR_BOOKE_IVPR], env->spr[SPR_BOOKE_EPCR]);
        cpu_fprintf(f, " MCSR " TARGET_FMT_lx " SPRG8 " TARGET_FMT_lx
                       "    EPR " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MCSR], env->spr[SPR_BOOKE_SPRG8],
                    env->spr[SPR_BOOKE_EPR]);
        /* FSL-specific */
        cpu_fprintf(f, " MCAR " TARGET_FMT_lx "  PID1 " TARGET_FMT_lx
                       "   PID2 " TARGET_FMT_lx "    SVR " TARGET_FMT_lx "\n",
                    env->spr[SPR_Exxx_MCAR], env->spr[SPR_BOOKE_PID1],
                    env->spr[SPR_BOOKE_PID2], env->spr[SPR_E500_SVR]);
        /*
         * IVORs are left out as they are large and do not change often --
         * they can be read with "p $ivor0", "p $ivor1", etc.
         */
    switch (env->mmu_model) {
    case POWERPC_MMU_32B:
    case POWERPC_MMU_601:
    case POWERPC_MMU_SOFT_6xx:
    case POWERPC_MMU_SOFT_74xx:
    case POWERPC_MMU_620:
    case POWERPC_MMU_64B:
        cpu_fprintf(f, " SDR1 " TARGET_FMT_lx "\n", env->spr[SPR_SDR1]);
        break;
    case POWERPC_MMU_BOOKE206:
        cpu_fprintf(f, " MAS0 " TARGET_FMT_lx "  MAS1 " TARGET_FMT_lx
                       "   MAS2 " TARGET_FMT_lx "   MAS3 " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MAS0], env->spr[SPR_BOOKE_MAS1],
                    env->spr[SPR_BOOKE_MAS2], env->spr[SPR_BOOKE_MAS3]);
        cpu_fprintf(f, " MAS4 " TARGET_FMT_lx "  MAS6 " TARGET_FMT_lx
                       "   MAS7 " TARGET_FMT_lx "    PID " TARGET_FMT_lx "\n",
                    env->spr[SPR_BOOKE_MAS4], env->spr[SPR_BOOKE_MAS6],
                    env->spr[SPR_BOOKE_MAS7], env->spr[SPR_BOOKE_PID]);
        cpu_fprintf(f, "MMUCFG " TARGET_FMT_lx " TLB0CFG " TARGET_FMT_lx
                       " TLB1CFG " TARGET_FMT_lx "\n",
                    env->spr[SPR_MMUCFG], env->spr[SPR_BOOKE_TLB0CFG],
                    env->spr[SPR_BOOKE_TLB1CFG]);
        break;
    default:
        break;
#undef RGPL
#undef RFPL


static void tcg_out_setcond_i32(TCGContext *s, TCGCond cond, TCGReg ret,

                                TCGReg c1, int32_t c2, int c2const)

{

    /* For 32-bit comparisons, we can play games with ADDX/SUBX.  */

    switch (cond) {

    case TCG_COND_LTU:

    case TCG_COND_GEU:

        /* The result of the comparison is in the carry bit.  */

        break;

    case TCG_COND_EQ:

    case TCG_COND_NE:

        /* For equality, we can transform to inequality vs zero.  */

        if (c2 != 0) {

            tcg_out_arithc(s, ret, c1, c2, c2const, ARITH_XOR);

        }

        c1 = TCG_REG_G0, c2 = ret, c2const = 0;

        cond = (cond == TCG_COND_EQ ? TCG_COND_GEU : TCG_COND_LTU);

	break;

    case TCG_COND_GTU:

    case TCG_COND_LEU:

        /* If we don't need to load a constant into a register, we can

           swap the operands on GTU/LEU.  There's no benefit to loading

           the constant into a temporary register.  */

        if (!c2const || c2 == 0) {

            TCGReg t = c1;

            c1 = c2;

            c2 = t;

            c2const = 0;

            cond = tcg_swap_cond(cond);

            break;

        }

        /* FALLTHRU */

    default:

        tcg_out_cmp(s, c1, c2, c2const);

        tcg_out_movi_imm13(s, ret, 0);

        tcg_out_movcc(s, cond, MOVCC_ICC, ret, 1, 1);

        return;

    }

    tcg_out_cmp(s, c1, c2, c2const);

    if (cond == TCG_COND_LTU) {

        tcg_out_arithi(s, ret, TCG_REG_G0, 0, ARITH_ADDX);

    } else {

        tcg_out_arithi(s, ret, TCG_REG_G0, -1, ARITH_SUBX);

    }

}


static inline void RENAME(yuv2rgb1)(uint16_t *buf0, uint16_t *uvbuf0, uint16_t *uvbuf1,

			    uint8_t *dest, int dstW, int uvalpha, int dstbpp)

{

	int uvalpha1=uvalpha^4095;

	const int yalpha1=0;

	if(fullUVIpol || allwaysIpol)

	{

		RENAME(yuv2rgb2)(buf0, buf0, uvbuf0, uvbuf1, dest, dstW, 0, uvalpha, dstbpp);

		return;

	}

#ifdef HAVE_MMX

	if( uvalpha < 2048 ) // note this is not correct (shifts chrominance by 0.5 pixels) but its a bit faster

	{

		if(dstbpp == 32)

		{

			asm volatile(

				YSCALEYUV2RGB1

				WRITEBGR32

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

		else if(dstbpp==24)

		{

			asm volatile(

				"movl %4, %%ebx			\n\t"

				YSCALEYUV2RGB1

				WRITEBGR24

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "m" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax", "%ebx"

			);

		}

		else if(dstbpp==15)

		{

			asm volatile(

				YSCALEYUV2RGB1

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g5Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR15

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

		else if(dstbpp==16)

		{

			asm volatile(

				YSCALEYUV2RGB1

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g6Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR16

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

	}

	else

	{

		if(dstbpp == 32)

		{

			asm volatile(

				YSCALEYUV2RGB1b

				WRITEBGR32

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

		else if(dstbpp==24)

		{

			asm volatile(

				"movl %4, %%ebx			\n\t"

				YSCALEYUV2RGB1b

				WRITEBGR24

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "m" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax", "%ebx"

			);

		}

		else if(dstbpp==15)

		{

			asm volatile(

				YSCALEYUV2RGB1b

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g5Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR15

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

		else if(dstbpp==16)

		{

			asm volatile(

				YSCALEYUV2RGB1b

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g6Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

				WRITEBGR16

			:: "r" (buf0), "r" (buf0), "r" (uvbuf0), "r" (uvbuf1), "r" (dest), "m" (dstW),

			"m" (yalpha1), "m" (uvalpha1)

			: "%eax"

			);

		}

	}

#else

//FIXME write 2 versions (for even & odd lines)

	if(dstbpp==32)

	{

		int i;

		for(i=0; i<dstW-1; i+=2){

			// vertical linear interpolation && yuv2rgb in a single step:

			int Y1=yuvtab_2568[buf0[i]>>7];

			int Y2=yuvtab_2568[buf0[i+1]>>7];

			int U=((uvbuf0[i>>1]*uvalpha1+uvbuf1[i>>1]*uvalpha)>>19);

			int V=((uvbuf0[(i>>1)+2048]*uvalpha1+uvbuf1[(i>>1)+2048]*uvalpha)>>19);

			int Cb= yuvtab_40cf[U];

			int Cg= yuvtab_1a1e[V] + yuvtab_0c92[U];

			int Cr= yuvtab_3343[V];

			dest[4*i+0]=clip_table[((Y1 + Cb) >>13)];

			dest[4*i+1]=clip_table[((Y1 + Cg) >>13)];

			dest[4*i+2]=clip_table[((Y1 + Cr) >>13)];

			dest[4*i+4]=clip_table[((Y2 + Cb) >>13)];

			dest[4*i+5]=clip_table[((Y2 + Cg) >>13)];

			dest[4*i+6]=clip_table[((Y2 + Cr) >>13)];

		}

	}

	else if(dstbpp==24)

	{

		int i;

		for(i=0; i<dstW-1; i+=2){

			// vertical linear interpolation && yuv2rgb in a single step:

			int Y1=yuvtab_2568[buf0[i]>>7];

			int Y2=yuvtab_2568[buf0[i+1]>>7];

			int U=((uvbuf0[i>>1]*uvalpha1+uvbuf1[i>>1]*uvalpha)>>19);

			int V=((uvbuf0[(i>>1)+2048]*uvalpha1+uvbuf1[(i>>1)+2048]*uvalpha)>>19);

			int Cb= yuvtab_40cf[U];

			int Cg= yuvtab_1a1e[V] + yuvtab_0c92[U];

			int Cr= yuvtab_3343[V];

			dest[0]=clip_table[((Y1 + Cb) >>13)];

			dest[1]=clip_table[((Y1 + Cg) >>13)];

			dest[2]=clip_table[((Y1 + Cr) >>13)];

			dest[3]=clip_table[((Y2 + Cb) >>13)];

			dest[4]=clip_table[((Y2 + Cg) >>13)];

			dest[5]=clip_table[((Y2 + Cr) >>13)];

			dest+=6;

		}

	}

	else if(dstbpp==16)

	{

		int i;

		for(i=0; i<dstW-1; i+=2){

			// vertical linear interpolation && yuv2rgb in a single step:

			int Y1=yuvtab_2568[buf0[i]>>7];

			int Y2=yuvtab_2568[buf0[i+1]>>7];

			int U=((uvbuf0[i>>1]*uvalpha1+uvbuf1[i>>1]*uvalpha)>>19);

			int V=((uvbuf0[(i>>1)+2048]*uvalpha1+uvbuf1[(i>>1)+2048]*uvalpha)>>19);

			int Cb= yuvtab_40cf[U];

			int Cg= yuvtab_1a1e[V] + yuvtab_0c92[U];

			int Cr= yuvtab_3343[V];

			((uint16_t*)dest)[i] =

				clip_table16b[(Y1 + Cb) >>13] |

				clip_table16g[(Y1 + Cg) >>13] |

				clip_table16r[(Y1 + Cr) >>13];

			((uint16_t*)dest)[i+1] =

				clip_table16b[(Y2 + Cb) >>13] |

				clip_table16g[(Y2 + Cg) >>13] |

				clip_table16r[(Y2 + Cr) >>13];

		}

	}

	else if(dstbpp==15)

	{

		int i;

		for(i=0; i<dstW-1; i+=2){

			// vertical linear interpolation && yuv2rgb in a single step:

			int Y1=yuvtab_2568[buf0[i]>>7];

			int Y2=yuvtab_2568[buf0[i+1]>>7];

			int U=((uvbuf0[i>>1]*uvalpha1+uvbuf1[i>>1]*uvalpha)>>19);

			int V=((uvbuf0[(i>>1)+2048]*uvalpha1+uvbuf1[(i>>1)+2048]*uvalpha)>>19);

			int Cb= yuvtab_40cf[U];

			int Cg= yuvtab_1a1e[V] + yuvtab_0c92[U];

			int Cr= yuvtab_3343[V];

			((uint16_t*)dest)[i] =

				clip_table15b[(Y1 + Cb) >>13] |

				clip_table15g[(Y1 + Cg) >>13] |

				clip_table15r[(Y1 + Cr) >>13];

			((uint16_t*)dest)[i+1] =

				clip_table15b[(Y2 + Cb) >>13] |

				clip_table15g[(Y2 + Cg) >>13] |

				clip_table15r[(Y2 + Cr) >>13];

		}

	}

#endif

}


static void receive_from_chr_layer(SCLPConsoleLM *scon, const uint8_t *buf,

                                   int size)

{

    assert(size == 1);

    if (*buf == '\r' || *buf == '\n') {

        scon->event.event_pending = true;

        return;

    }

    scon->buf[scon->length] = *buf;

    scon->length += 1;

    if (scon->echo) {

        qemu_chr_fe_write(scon->chr, buf, size);

    }

}


static void write_strip_header(CinepakEncContext *s, int y, int h, int keyframe, unsigned char *buf, int strip_size)

{

    buf[0] = keyframe ? 0x11: 0x10;

    AV_WB24(&buf[1], strip_size + STRIP_HEADER_SIZE);

    AV_WB16(&buf[4], y);

    AV_WB16(&buf[6], 0);

    AV_WB16(&buf[8], h);

    AV_WB16(&buf[10], s->w);

}


int kvm_arch_pre_run(CPUState *env, struct kvm_run *run)
{
    int r;
    unsigned irq;
    /* PowerPC Qemu tracks the various core input pins (interrupt, critical
     * interrupt, reset, etc) in PPC-specific env->irq_input_state. */
    if (run->ready_for_interrupt_injection &&
        (env->interrupt_request & CPU_INTERRUPT_HARD) &&
        (env->irq_input_state & (1<<PPC_INPUT_INT)))
    {
        /* For now KVM disregards the 'irq' argument. However, in the
         * future KVM could cache it in-kernel to avoid a heavyweight exit
         * when reading the UIC.
         */
        irq = -1U;
        dprintf("injected interrupt %d\n", irq);
        r = kvm_vcpu_ioctl(env, KVM_INTERRUPT, &irq);
        if (r < 0)
            printf("cpu %d fail inject %x\n", env->cpu_index, irq);
    /* We don't know if there are more interrupts pending after this. However,
     * the guest will return to userspace in the course of handling this one
     * anyways, so we will get a chance to deliver the rest. */
    return 0;


static void ppc_spapr_reset(void)

{

    /* flush out the hash table */

    memset(spapr->htab, 0, spapr->htab_size);

    qemu_devices_reset();

    /* Load the fdt */

    spapr_finalize_fdt(spapr, spapr->fdt_addr, spapr->rtas_addr,

                       spapr->rtas_size);

    /* Set up the entry state */

    first_cpu->gpr[3] = spapr->fdt_addr;

    first_cpu->gpr[5] = 0;

    first_cpu->halted = 0;

    first_cpu->nip = spapr->entry_point;

}


static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,

                                 int32_t *data, int n, int pred_order)

{

    int i;

    uint32_t bits[MAX_PARTITION_ORDER+1];

    int opt_porder;

    RiceContext tmp_rc;

    uint32_t *udata;

    uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];

    assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);

    assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);

    assert(pmin <= pmax);

    udata = av_malloc(n * sizeof(uint32_t));

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

        udata[i] = (2*data[i]) ^ (data[i]>>31);

    calc_sums(pmin, pmax, udata, n, pred_order, sums);

    opt_porder = pmin;

    bits[pmin] = UINT32_MAX;

    for (i = pmin; i <= pmax; i++) {

        bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);

        if (bits[i] <= bits[opt_porder]) {

            opt_porder = i;

            *rc = tmp_rc;

        }

    }

    av_freep(&udata);

    return bits[opt_porder];

}


static int decode_header(PSDContext * s)

{

    int signature, version, color_mode, compression;

    int64_t len_section;

    int ret = 0;

    if (bytestream2_get_bytes_left(&s->gb) < 30) {/* File header section + color map data section length */

        av_log(s->avctx, AV_LOG_ERROR, "Header too short to parse.\n");

        return AVERROR_INVALIDDATA;

    }

    signature = bytestream2_get_le32(&s->gb);

    if (signature != MKTAG('8','B','P','S')) {

        av_log(s->avctx, AV_LOG_ERROR, "Wrong signature %d.\n", signature);

        return AVERROR_INVALIDDATA;

    }

    version = bytestream2_get_be16(&s->gb);

    if (version != 1) {

        av_log(s->avctx, AV_LOG_ERROR, "Wrong version %d.\n", version);

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skip(&s->gb, 6);/* reserved */

    s->channel_count = bytestream2_get_be16(&s->gb);

    if ((s->channel_count < 1) || (s->channel_count > 56)) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid channel count %d.\n", s->channel_count);

        return AVERROR_INVALIDDATA;

    }

    s->height = bytestream2_get_be32(&s->gb);

    if ((s->height > 30000) && (s->avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Height > 30000 is experimental, add "

               "'-strict %d' if you want to try to decode the picture.\n",

               FF_COMPLIANCE_EXPERIMENTAL);

        return AVERROR_EXPERIMENTAL;

    }

    s->width = bytestream2_get_be32(&s->gb);

    if ((s->width > 30000) && (s->avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)) {

        av_log(s->avctx, AV_LOG_ERROR,

               "Width > 30000 is experimental, add "

               "'-strict %d' if you want to try to decode the picture.\n",

               FF_COMPLIANCE_EXPERIMENTAL);

        return AVERROR_EXPERIMENTAL;

    }

    if ((ret = ff_set_dimensions(s->avctx, s->width, s->height)) < 0)

        return ret;

    s->channel_depth = bytestream2_get_be16(&s->gb);

    color_mode = bytestream2_get_be16(&s->gb);

    switch (color_mode) {

    case 0:

        s->color_mode = PSD_BITMAP;

        break;

    case 1:

        s->color_mode = PSD_GRAYSCALE;

        break;

    case 2:

        s->color_mode = PSD_INDEXED;

        break;

    case 3:

        s->color_mode = PSD_RGB;

        break;

    case 4:

        s->color_mode = PSD_CMYK;

        break;

    case 7:

        s->color_mode = PSD_MULTICHANNEL;

        break;

    case 8:

        s->color_mode = PSD_DUOTONE;

        break;

    case 9:

        s->color_mode = PSD_LAB;

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "Unknown color mode %d.\n", color_mode);

        return AVERROR_INVALIDDATA;

    }

    /* color map data */

    len_section = bytestream2_get_be32(&s->gb);

    if (len_section < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Negative size for color map data section.\n");

        return AVERROR_INVALIDDATA;

    }

    if (bytestream2_get_bytes_left(&s->gb) < (len_section + 4)) { /* section and len next section */

        av_log(s->avctx, AV_LOG_ERROR, "Incomplete file.\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skip(&s->gb, len_section);

    /* image ressources */

    len_section = bytestream2_get_be32(&s->gb);

    if (len_section < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Negative size for image ressources section.\n");

        return AVERROR_INVALIDDATA;

    }

    if (bytestream2_get_bytes_left(&s->gb) < (len_section + 4)) { /* section and len next section */

        av_log(s->avctx, AV_LOG_ERROR, "Incomplete file.\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skip(&s->gb, len_section);

    /* layers and masks */

    len_section = bytestream2_get_be32(&s->gb);

    if (len_section < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Negative size for layers and masks data section.\n");

        return AVERROR_INVALIDDATA;

    }

    if (bytestream2_get_bytes_left(&s->gb) < len_section) {

        av_log(s->avctx, AV_LOG_ERROR, "Incomplete file.\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skip(&s->gb, len_section);

    /* image section */

    if (bytestream2_get_bytes_left(&s->gb) < 2) {

        av_log(s->avctx, AV_LOG_ERROR, "File without image data section.\n");

        return AVERROR_INVALIDDATA;

    }

    s->compression = bytestream2_get_be16(&s->gb);

    switch (s->compression) {

    case 0:

    case 1:

        break;

    case 2:

        avpriv_request_sample(s->avctx, "ZIP without predictor compression");

        return AVERROR_PATCHWELCOME;

        break;

    case 3:

        avpriv_request_sample(s->avctx, "ZIP with predictor compression");

        return AVERROR_PATCHWELCOME;

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "Unknown compression %d.\n", compression);

        return AVERROR_INVALIDDATA;

    }

    return ret;

}


static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)

{

    int isv34, unsync;

    unsigned tlen;

    char tag[5];

    int64_t next, end = avio_tell(s->pb) + len;

    int taghdrlen;

    const char *reason = NULL;

    AVIOContext pb;

    unsigned char *buffer = NULL;

    int buffer_size = 0;

    switch (version) {

    case 2:

        if (flags & 0x40) {

            reason = "compression";

            goto error;

        }

        isv34 = 0;

        taghdrlen = 6;

    case 3:

    case 4:

        isv34 = 1;

        taghdrlen = 10;

    default:

        reason = "version";

        goto error;

    }

    unsync = flags & 0x80;

    if (isv34 && flags & 0x40) /* Extended header present, just skip over it */

        avio_skip(s->pb, get_size(s->pb, 4));

    while (len >= taghdrlen) {

        unsigned int tflags;

        int tunsync = 0;

        if (isv34) {

            avio_read(s->pb, tag, 4);

            tag[4] = 0;

            if(version==3){

                tlen = avio_rb32(s->pb);

            }else

                tlen = get_size(s->pb, 4);

            tflags = avio_rb16(s->pb);

            tunsync = tflags & ID3v2_FLAG_UNSYNCH;

        } else {

            avio_read(s->pb, tag, 3);

            tag[3] = 0;

            tlen = avio_rb24(s->pb);

        }

        if (tlen > (1<<28))

        len -= taghdrlen + tlen;

        if (len < 0)

        next = avio_tell(s->pb) + tlen;

        if (tflags & ID3v2_FLAG_DATALEN) {

            avio_rb32(s->pb);

            tlen -= 4;

        }

        if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {

            av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);

            avio_skip(s->pb, tlen);

        } else if (tag[0] == 'T') {

            if (unsync || tunsync) {

                int i, j;

                av_fast_malloc(&buffer, &buffer_size, tlen);

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

                    buffer[j] = avio_r8(s->pb);

                    if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {

                        /* Unsynchronised byte, skip it */

                        j--;

                    }

                }

                ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);

                read_ttag(s, &pb, j, tag);

            } else {

                read_ttag(s, s->pb, tlen, tag);

            }

        }

        else if (!tag[0]) {

            if (tag[1])

                av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");

            avio_skip(s->pb, tlen);

        }

        /* Skip to end of tag */

        avio_seek(s->pb, next, SEEK_SET);

    }

    if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */

        end += 10;

  error:

    if (reason)

        av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);

    avio_seek(s->pb, end, SEEK_SET);

    av_free(buffer);

    return;

}


static int mpeg_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             UINT8 *buf, int buf_size)

{

    Mpeg1Context *s = avctx->priv_data;

    UINT8 *buf_end, *buf_ptr, *buf_start;

    int len, start_code_found, ret, code, start_code, input_size;

    AVPicture *picture = data;

    MpegEncContext *s2 = &s->mpeg_enc_ctx;

    dprintf("fill_buffer\n");

    *data_size = 0;

    /* special case for last picture */

    if (buf_size == 0) {

        if (s2->picture_number > 0) {

            picture->data[0] = s2->next_picture[0];

            picture->data[1] = s2->next_picture[1];

            picture->data[2] = s2->next_picture[2];

            picture->linesize[0] = s2->linesize;

            picture->linesize[1] = s2->linesize / 2;

            picture->linesize[2] = s2->linesize / 2;

            *data_size = sizeof(AVPicture);

        }

        return 0;

    }

    buf_ptr = buf;

    buf_end = buf + buf_size;

    if (s->repeat_field % 2 == 1) {

        s->repeat_field++;

        //fprintf(stderr,"\nRepeating last frame: %d -> %d! pict: %d %d", avctx->frame_number-1, avctx->frame_number,

        //                                                         s2->picture_number, s->repeat_field);

        *data_size = sizeof(AVPicture);

        goto the_end;

    }

    while (buf_ptr < buf_end) {

        buf_start = buf_ptr;

        /* find start next code */

        code = find_start_code(&buf_ptr, buf_end, &s->header_state);

        if (code >= 0) {

            start_code_found = 1;

        } else {

            start_code_found = 0;

        }

        /* copy to buffer */

        len = buf_ptr - buf_start;

        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {

            /* data too big : flush */

            s->buf_ptr = s->buffer;

            if (start_code_found)

                s->start_code = code;

        } else {

            memcpy(s->buf_ptr, buf_start, len);

            s->buf_ptr += len;

            if (start_code_found) {

                /* prepare data for next start code */

                input_size = s->buf_ptr - s->buffer;

                start_code = s->start_code;

                s->buf_ptr = s->buffer;

                s->start_code = code;

                switch(start_code) {

                case SEQ_START_CODE:

                    mpeg1_decode_sequence(avctx, s->buffer,

                                          input_size);

                    break;

                case PICTURE_START_CODE:

                    /* we have a complete image : we try to decompress it */

                    mpeg1_decode_picture(avctx,

                                         s->buffer, input_size);

                    break;

                case EXT_START_CODE:

                    mpeg_decode_extension(avctx,

                                          s->buffer, input_size);

                    break;

                default:

                    if (start_code >= SLICE_MIN_START_CODE &&

                        start_code <= SLICE_MAX_START_CODE) {

                        ret = mpeg_decode_slice(avctx, picture,

                                                start_code, s->buffer, input_size);

                        if (ret == 1) {

                            /* got a picture: exit */

                            /* first check if we must repeat the frame */

                            if (s2->progressive_frame && s2->repeat_first_field) {

                                //fprintf(stderr,"\nRepeat this frame: %d! pict: %d",avctx->frame_number,s2->picture_number);

                                s2->repeat_first_field = 0;

                                s2->progressive_frame = 0;

                                if (++s->repeat_field > 2)

                                    s->repeat_field = 0;

                            }

                            *data_size = sizeof(AVPicture);

                            goto the_end;

                        }

                    }

                    break;

                }

            }

        }

    }

 the_end:

    return buf_ptr - buf;

}


static int mp_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MotionPixelsContext *mp = avctx->priv_data;

    GetBitContext gb;

    int i, count1, count2, sz;

    mp->frame.reference = 1;

    mp->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &mp->frame)) {

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

        return -1;

    }

    /* le32 bitstream msb first */

    av_fast_malloc(&mp->bswapbuf, &mp->bswapbuf_size, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!mp->bswapbuf)

        return AVERROR(ENOMEM);

    mp->dsp.bswap_buf((uint32_t *)mp->bswapbuf, (const uint32_t *)buf, buf_size / 4);

    if (buf_size & 3)

        memcpy(mp->bswapbuf + (buf_size & ~3), buf + (buf_size & ~3), buf_size & 3);

    init_get_bits(&gb, mp->bswapbuf, buf_size * 8);

    memset(mp->changes_map, 0, avctx->width * avctx->height);

    for (i = !(avctx->extradata[1] & 2); i < 2; ++i) {

        count1 = get_bits(&gb, 12);

        count2 = get_bits(&gb, 12);

        mp_read_changes_map(mp, &gb, count1, 8, i);

        mp_read_changes_map(mp, &gb, count2, 4, i);

    }

    mp->codes_count = get_bits(&gb, 4);

    if (mp->codes_count == 0)

        goto end;

    if (mp->changes_map[0] == 0) {

        *(uint16_t *)mp->frame.data[0] = get_bits(&gb, 15);

        mp->changes_map[0] = 1;

    }

    mp_read_codes_table(mp, &gb);

    sz = get_bits(&gb, 18);

    if (avctx->extradata[0] != 5)

        sz += get_bits(&gb, 18);

    if (sz == 0)

        goto end;

    init_vlc(&mp->vlc, mp->max_codes_bits, mp->codes_count, &mp->codes[0].size, sizeof(HuffCode), 1, &mp->codes[0].code, sizeof(HuffCode), 4, 0);

    mp_decode_frame_helper(mp, &gb);

    free_vlc(&mp->vlc);

end:

    *data_size = sizeof(AVFrame);

    *(AVFrame *)data = mp->frame;

    return buf_size;

}


static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
                      int nb_sectors, bool is_write, BdrvRequestFlags flags)
{
    QEMUIOVector qiov;
    struct iovec iov = {
        .iov_base = (void *)buf,
        .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
    };
    qemu_iovec_init_external(&qiov, &iov, 1);
    return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
                        &qiov, is_write, flags);


int qemu_set_fd_handler(int fd,

                        IOHandler *fd_read,

                        IOHandler *fd_write,

                        void *opaque)

{

    static IOTrampoline fd_trampolines[FD_SETSIZE];

    IOTrampoline *tramp = &fd_trampolines[fd];

    if (tramp->tag != 0) {

        g_io_channel_unref(tramp->chan);

        g_source_remove(tramp->tag);

    }

    if (opaque) {

        GIOCondition cond = 0;

        tramp->fd_read = fd_read;

        tramp->fd_write = fd_write;

        tramp->opaque = opaque;

        if (fd_read) {

            cond |= G_IO_IN | G_IO_ERR;

        }

        if (fd_write) {

            cond |= G_IO_OUT | G_IO_ERR;

        }

        tramp->chan = g_io_channel_unix_new(fd);

        tramp->tag = g_io_add_watch(tramp->chan, cond, fd_trampoline, tramp);

    }

    return 0;

}


static void adb_register_types(void)

{

    type_register_static(&adb_bus_type_info);

    type_register_static(&adb_device_type_info);

    type_register_static(&adb_kbd_type_info);

    type_register_static(&adb_mouse_type_info);

}


uint32_t nand_getio(DeviceState *dev)

{

    int offset;

    uint32_t x = 0;

    NANDFlashState *s = (NANDFlashState *) dev;

    /* Allow sequential reading */

    if (!s->iolen && s->cmd == NAND_CMD_READ0) {

        offset = (int) (s->addr & ((1 << s->addr_shift) - 1)) + s->offset;

        s->offset = 0;

        s->blk_load(s, s->addr, offset);

        if (s->gnd)

            s->iolen = (1 << s->page_shift) - offset;

        else

            s->iolen = (1 << s->page_shift) + (1 << s->oob_shift) - offset;

    }

    if (s->ce || s->iolen <= 0)

        return 0;

    for (offset = s->buswidth; offset--;) {

        x |= s->ioaddr[offset] << (offset << 3);

    }

    /* after receiving READ STATUS command all subsequent reads will

     * return the status register value until another command is issued

     */

    if (s->cmd != NAND_CMD_READSTATUS) {

        s->addr   += s->buswidth;

        s->ioaddr += s->buswidth;

        s->iolen  -= s->buswidth;

    }

    return x;

}


char *vnc_display_local_addr(DisplayState *ds)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    return vnc_socket_local_addr("%s:%s", vs->lsock);

}


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

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

    const int alpha = alpha_table[index_a];

    const int beta  = (beta_table+52)[qp + h->slice_beta_offset];

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

    if( bS[0] < 4 ) {

        int8_t tc[4];

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

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

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

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

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

    } else {

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

    }

}


static inline void RENAME(dering)(uint8_t src[], int stride, PPContext *c)

{

#if HAVE_7REGS && (TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW)

    DECLARE_ALIGNED(8, uint64_t, tmp)[3];

    __asm__ volatile(

        "pxor %%mm6, %%mm6                      \n\t"

        "pcmpeqb %%mm7, %%mm7                   \n\t"

        "movq %2, %%mm0                         \n\t"

        "punpcklbw %%mm6, %%mm0                 \n\t"

        "psrlw $1, %%mm0                        \n\t"

        "psubw %%mm7, %%mm0                     \n\t"

        "packuswb %%mm0, %%mm0                  \n\t"

        "movq %%mm0, %3                         \n\t"

        "lea (%0, %1), %%"REG_a"                \n\t"

        "lea (%%"REG_a", %1, 4), %%"REG_d"      \n\t"

//        0        1        2        3        4        5        6        7        8        9

//        %0        eax        eax+%1        eax+2%1        %0+4%1        edx        edx+%1        edx+2%1        %0+8%1        edx+4%1

#undef REAL_FIND_MIN_MAX

#undef FIND_MIN_MAX

#if TEMPLATE_PP_MMXEXT

#define REAL_FIND_MIN_MAX(addr)\

        "movq " #addr ", %%mm0                  \n\t"\

        "pminub %%mm0, %%mm7                    \n\t"\

        "pmaxub %%mm0, %%mm6                    \n\t"

#else

#define REAL_FIND_MIN_MAX(addr)\

        "movq " #addr ", %%mm0                  \n\t"\

        "movq %%mm7, %%mm1                      \n\t"\

        "psubusb %%mm0, %%mm6                   \n\t"\

        "paddb %%mm0, %%mm6                     \n\t"\

        "psubusb %%mm0, %%mm1                   \n\t"\

        "psubb %%mm1, %%mm7                     \n\t"

#endif

#define FIND_MIN_MAX(addr)  REAL_FIND_MIN_MAX(addr)

FIND_MIN_MAX((%%REGa))

FIND_MIN_MAX((%%REGa, %1))

FIND_MIN_MAX((%%REGa, %1, 2))

FIND_MIN_MAX((%0, %1, 4))

FIND_MIN_MAX((%%REGd))

FIND_MIN_MAX((%%REGd, %1))

FIND_MIN_MAX((%%REGd, %1, 2))

FIND_MIN_MAX((%0, %1, 8))

        "movq %%mm7, %%mm4                      \n\t"

        "psrlq $8, %%mm7                        \n\t"

#if TEMPLATE_PP_MMXEXT

        "pminub %%mm4, %%mm7                    \n\t" // min of pixels

        "pshufw $0xF9, %%mm7, %%mm4             \n\t"

        "pminub %%mm4, %%mm7                    \n\t" // min of pixels

        "pshufw $0xFE, %%mm7, %%mm4             \n\t"

        "pminub %%mm4, %%mm7                    \n\t"

#else

        "movq %%mm7, %%mm1                      \n\t"

        "psubusb %%mm4, %%mm1                   \n\t"

        "psubb %%mm1, %%mm7                     \n\t"

        "movq %%mm7, %%mm4                      \n\t"

        "psrlq $16, %%mm7                       \n\t"

        "movq %%mm7, %%mm1                      \n\t"

        "psubusb %%mm4, %%mm1                   \n\t"

        "psubb %%mm1, %%mm7                     \n\t"

        "movq %%mm7, %%mm4                      \n\t"

        "psrlq $32, %%mm7                       \n\t"

        "movq %%mm7, %%mm1                      \n\t"

        "psubusb %%mm4, %%mm1                   \n\t"

        "psubb %%mm1, %%mm7                     \n\t"

#endif

        "movq %%mm6, %%mm4                      \n\t"

        "psrlq $8, %%mm6                        \n\t"

#if TEMPLATE_PP_MMXEXT

        "pmaxub %%mm4, %%mm6                    \n\t" // max of pixels

        "pshufw $0xF9, %%mm6, %%mm4             \n\t"

        "pmaxub %%mm4, %%mm6                    \n\t"

        "pshufw $0xFE, %%mm6, %%mm4             \n\t"

        "pmaxub %%mm4, %%mm6                    \n\t"

#else

        "psubusb %%mm4, %%mm6                   \n\t"

        "paddb %%mm4, %%mm6                     \n\t"

        "movq %%mm6, %%mm4                      \n\t"

        "psrlq $16, %%mm6                       \n\t"

        "psubusb %%mm4, %%mm6                   \n\t"

        "paddb %%mm4, %%mm6                     \n\t"

        "movq %%mm6, %%mm4                      \n\t"

        "psrlq $32, %%mm6                       \n\t"

        "psubusb %%mm4, %%mm6                   \n\t"

        "paddb %%mm4, %%mm6                     \n\t"

#endif

        "movq %%mm6, %%mm0                      \n\t" // max

        "psubb %%mm7, %%mm6                     \n\t" // max - min

        "push %4                              \n\t"

        "movd %%mm6, %k4                        \n\t"

        "cmpb "MANGLE(deringThreshold)", %b4    \n\t"

        "pop %4                               \n\t"

        " jb 1f                                 \n\t"

        PAVGB(%%mm0, %%mm7)                           // a=(max + min)/2

        "punpcklbw %%mm7, %%mm7                 \n\t"

        "punpcklbw %%mm7, %%mm7                 \n\t"

        "punpcklbw %%mm7, %%mm7                 \n\t"

        "movq %%mm7, (%4)                       \n\t"

        "movq (%0), %%mm0                       \n\t" // L10

        "movq %%mm0, %%mm1                      \n\t" // L10

        "movq %%mm0, %%mm2                      \n\t" // L10

        "psllq $8, %%mm1                        \n\t"

        "psrlq $8, %%mm2                        \n\t"

        "movd -4(%0), %%mm3                     \n\t"

        "movd 8(%0), %%mm4                      \n\t"

        "psrlq $24, %%mm3                       \n\t"

        "psllq $56, %%mm4                       \n\t"

        "por %%mm3, %%mm1                       \n\t" // L00

        "por %%mm4, %%mm2                       \n\t" // L20

        "movq %%mm1, %%mm3                      \n\t" // L00

        PAVGB(%%mm2, %%mm1)                           // (L20 + L00)/2

        PAVGB(%%mm0, %%mm1)                           // (L20 + L00 + 2L10)/4

        "psubusb %%mm7, %%mm0                   \n\t"

        "psubusb %%mm7, %%mm2                   \n\t"

        "psubusb %%mm7, %%mm3                   \n\t"

        "pcmpeqb "MANGLE(b00)", %%mm0           \n\t" // L10 > a ? 0 : -1

        "pcmpeqb "MANGLE(b00)", %%mm2           \n\t" // L20 > a ? 0 : -1

        "pcmpeqb "MANGLE(b00)", %%mm3           \n\t" // L00 > a ? 0 : -1

        "paddb %%mm2, %%mm0                     \n\t"

        "paddb %%mm3, %%mm0                     \n\t"

        "movq (%%"REG_a"), %%mm2                \n\t" // L11

        "movq %%mm2, %%mm3                      \n\t" // L11

        "movq %%mm2, %%mm4                      \n\t" // L11

        "psllq $8, %%mm3                        \n\t"

        "psrlq $8, %%mm4                        \n\t"

        "movd -4(%%"REG_a"), %%mm5              \n\t"

        "movd 8(%%"REG_a"), %%mm6               \n\t"

        "psrlq $24, %%mm5                       \n\t"

        "psllq $56, %%mm6                       \n\t"

        "por %%mm5, %%mm3                       \n\t" // L01

        "por %%mm6, %%mm4                       \n\t" // L21

        "movq %%mm3, %%mm5                      \n\t" // L01

        PAVGB(%%mm4, %%mm3)                           // (L21 + L01)/2

        PAVGB(%%mm2, %%mm3)                           // (L21 + L01 + 2L11)/4

        "psubusb %%mm7, %%mm2                   \n\t"

        "psubusb %%mm7, %%mm4                   \n\t"

        "psubusb %%mm7, %%mm5                   \n\t"

        "pcmpeqb "MANGLE(b00)", %%mm2           \n\t" // L11 > a ? 0 : -1

        "pcmpeqb "MANGLE(b00)", %%mm4           \n\t" // L21 > a ? 0 : -1

        "pcmpeqb "MANGLE(b00)", %%mm5           \n\t" // L01 > a ? 0 : -1

        "paddb %%mm4, %%mm2                     \n\t"

        "paddb %%mm5, %%mm2                     \n\t"

// 0, 2, 3, 1

#define REAL_DERING_CORE(dst,src,ppsx,psx,sx,pplx,plx,lx,t0,t1) \

        "movq " #src ", " #sx "                 \n\t" /* src[0] */\

        "movq " #sx ", " #lx "                  \n\t" /* src[0] */\

        "movq " #sx ", " #t0 "                  \n\t" /* src[0] */\

        "psllq $8, " #lx "                      \n\t"\

        "psrlq $8, " #t0 "                      \n\t"\

        "movd -4" #src ", " #t1 "               \n\t"\

        "psrlq $24, " #t1 "                     \n\t"\

        "por " #t1 ", " #lx "                   \n\t" /* src[-1] */\

        "movd 8" #src ", " #t1 "                \n\t"\

        "psllq $56, " #t1 "                     \n\t"\

        "por " #t1 ", " #t0 "                   \n\t" /* src[+1] */\

        "movq " #lx ", " #t1 "                  \n\t" /* src[-1] */\

        PAVGB(t0, lx)                                 /* (src[-1] + src[+1])/2 */\

        PAVGB(sx, lx)                                 /* (src[-1] + 2src[0] + src[+1])/4 */\

        PAVGB(lx, pplx)                                     \

        "movq " #lx ", 8(%4)                    \n\t"\

        "movq (%4), " #lx "                     \n\t"\

        "psubusb " #lx ", " #t1 "               \n\t"\

        "psubusb " #lx ", " #t0 "               \n\t"\

        "psubusb " #lx ", " #sx "               \n\t"\

        "movq "MANGLE(b00)", " #lx "            \n\t"\

        "pcmpeqb " #lx ", " #t1 "               \n\t" /* src[-1] > a ? 0 : -1*/\

        "pcmpeqb " #lx ", " #t0 "               \n\t" /* src[+1] > a ? 0 : -1*/\

        "pcmpeqb " #lx ", " #sx "               \n\t" /* src[0]  > a ? 0 : -1*/\

        "paddb " #t1 ", " #t0 "                 \n\t"\

        "paddb " #t0 ", " #sx "                 \n\t"\

\

        PAVGB(plx, pplx)                              /* filtered */\

        "movq " #dst ", " #t0 "                 \n\t" /* dst */\

        "movq " #t0 ", " #t1 "                  \n\t" /* dst */\

        "psubusb %3, " #t0 "                    \n\t"\

        "paddusb %3, " #t1 "                    \n\t"\

        PMAXUB(t0, pplx)\

        PMINUB(t1, pplx, t0)\

        "paddb " #sx ", " #ppsx "               \n\t"\

        "paddb " #psx ", " #ppsx "              \n\t"\

        "#paddb "MANGLE(b02)", " #ppsx "        \n\t"\

        "pand "MANGLE(b08)", " #ppsx "          \n\t"\

        "pcmpeqb " #lx ", " #ppsx "             \n\t"\

        "pand " #ppsx ", " #pplx "              \n\t"\

        "pandn " #dst ", " #ppsx "              \n\t"\

        "por " #pplx ", " #ppsx "               \n\t"\

        "movq " #ppsx ", " #dst "               \n\t"\

        "movq 8(%4), " #lx "                    \n\t"

#define DERING_CORE(dst,src,ppsx,psx,sx,pplx,plx,lx,t0,t1) \

   REAL_DERING_CORE(dst,src,ppsx,psx,sx,pplx,plx,lx,t0,t1)

/*

0000000

1111111

1111110

1111101

1111100

1111011

1111010

1111001

1111000

1110111

*/

//DERING_CORE(dst          ,src            ,ppsx ,psx  ,sx   ,pplx ,plx  ,lx   ,t0   ,t1)

DERING_CORE((%%REGa)       ,(%%REGa, %1)   ,%%mm0,%%mm2,%%mm4,%%mm1,%%mm3,%%mm5,%%mm6,%%mm7)

DERING_CORE((%%REGa, %1)   ,(%%REGa, %1, 2),%%mm2,%%mm4,%%mm0,%%mm3,%%mm5,%%mm1,%%mm6,%%mm7)

DERING_CORE((%%REGa, %1, 2),(%0, %1, 4)    ,%%mm4,%%mm0,%%mm2,%%mm5,%%mm1,%%mm3,%%mm6,%%mm7)

DERING_CORE((%0, %1, 4)    ,(%%REGd)       ,%%mm0,%%mm2,%%mm4,%%mm1,%%mm3,%%mm5,%%mm6,%%mm7)

DERING_CORE((%%REGd)       ,(%%REGd, %1)   ,%%mm2,%%mm4,%%mm0,%%mm3,%%mm5,%%mm1,%%mm6,%%mm7)

DERING_CORE((%%REGd, %1)   ,(%%REGd, %1, 2),%%mm4,%%mm0,%%mm2,%%mm5,%%mm1,%%mm3,%%mm6,%%mm7)

DERING_CORE((%%REGd, %1, 2),(%0, %1, 8)    ,%%mm0,%%mm2,%%mm4,%%mm1,%%mm3,%%mm5,%%mm6,%%mm7)

DERING_CORE((%0, %1, 8)    ,(%%REGd, %1, 4),%%mm2,%%mm4,%%mm0,%%mm3,%%mm5,%%mm1,%%mm6,%%mm7)

        "1:                        \n\t"

        : : "r" (src), "r" ((x86_reg)stride), "m" (c->pQPb), "m"(c->pQPb2), "q"(tmp)

        : "%"REG_a, "%"REG_d

    );

#else // HAVE_7REGS && (TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW)

    int y;

    int min=255;

    int max=0;

    int avg;

    uint8_t *p;

    int s[10];

    const int QP2= c->QP/2 + 1;

    src --;

    for(y=1; y<9; y++){

        int x;

        p= src + stride*y;

        for(x=1; x<9; x++){

            p++;

            if(*p > max) max= *p;

            if(*p < min) min= *p;

        }

    }

    avg= (min + max + 1)>>1;

    if(max - min <deringThreshold) return;

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

        int t = 0;

        if(src[stride*y + 0] > avg) t+= 1;

        if(src[stride*y + 1] > avg) t+= 2;

        if(src[stride*y + 2] > avg) t+= 4;

        if(src[stride*y + 3] > avg) t+= 8;

        if(src[stride*y + 4] > avg) t+= 16;

        if(src[stride*y + 5] > avg) t+= 32;

        if(src[stride*y + 6] > avg) t+= 64;

        if(src[stride*y + 7] > avg) t+= 128;

        if(src[stride*y + 8] > avg) t+= 256;

        if(src[stride*y + 9] > avg) t+= 512;

        t |= (~t)<<16;

        t &= (t<<1) & (t>>1);

        s[y] = t;

    }

    for(y=1; y<9; y++){

        int t = s[y-1] & s[y] & s[y+1];

        t|= t>>16;

        s[y-1]= t;

    }

    for(y=1; y<9; y++){

        int x;

        int t = s[y-1];

        p= src + stride*y;

        for(x=1; x<9; x++){

            p++;

            if(t & (1<<x)){

                int f= (*(p-stride-1)) + 2*(*(p-stride)) + (*(p-stride+1))

                      +2*(*(p     -1)) + 4*(*p         ) + 2*(*(p     +1))

                      +(*(p+stride-1)) + 2*(*(p+stride)) + (*(p+stride+1));

                f= (f + 8)>>4;

#ifdef DEBUG_DERING_THRESHOLD

                    __asm__ volatile("emms\n\t":);

                    {

                    static long long numPixels=0;

                    if(x!=1 && x!=8 && y!=1 && y!=8) numPixels++;

//                    if((max-min)<20 || (max-min)*QP<200)

//                    if((max-min)*QP < 500)

//                    if(max-min<QP/2)

                    if(max-min < 20){

                        static int numSkipped=0;

                        static int errorSum=0;

                        static int worstQP=0;

                        static int worstRange=0;

                        static int worstDiff=0;

                        int diff= (f - *p);

                        int absDiff= FFABS(diff);

                        int error= diff*diff;

                        if(x==1 || x==8 || y==1 || y==8) continue;

                        numSkipped++;

                        if(absDiff > worstDiff){

                            worstDiff= absDiff;

                            worstQP= QP;

                            worstRange= max-min;

                        }

                        errorSum+= error;

                        if(1024LL*1024LL*1024LL % numSkipped == 0){

                            av_log(c, AV_LOG_INFO, "sum:%1.3f, skip:%d, wQP:%d, "

                                   "wRange:%d, wDiff:%d, relSkip:%1.3f\n",

                                   (float)errorSum/numSkipped, numSkipped, worstQP, worstRange,

                                   worstDiff, (float)numSkipped/numPixels);

                        }

                    }

                    }

#endif

                    if     (*p + QP2 < f) *p= *p + QP2;

                    else if(*p - QP2 > f) *p= *p - QP2;

                    else *p=f;

            }

        }

    }

#ifdef DEBUG_DERING_THRESHOLD

    if(max-min < 20){

        for(y=1; y<9; y++){

            int x;

            int t = 0;

            p= src + stride*y;

            for(x=1; x<9; x++){

                p++;

                *p = FFMIN(*p + 20, 255);

            }

        }

//        src[0] = src[7]=src[stride*7]=src[stride*7 + 7]=255;

    }

#endif

#endif //TEMPLATE_PP_MMXEXT || TEMPLATE_PP_3DNOW

}


static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,

                          SBRData *ch_data, const int e_a[2])

{

    int e, k, m;

    // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)

    static const SoftFloat limgain[4] = { { 760155524,  0 }, { 0x20000000,  1 },

                                            { 758351638,  1 }, { 625000000, 34 } };

    for (e = 0; e < ch_data->bs_num_env; e++) {

        int delta = !((e == e_a[1]) || (e == e_a[0]));

        for (k = 0; k < sbr->n_lim; k++) {

            SoftFloat gain_boost, gain_max;

            SoftFloat sum[2] = { FLOAT_0, FLOAT_0 };

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                const SoftFloat temp = av_div_sf(sbr->e_origmapped[e][m],

                                            av_add_sf(FLOAT_1, sbr->q_mapped[e][m]));

                sbr->q_m[e][m] = av_sqrt_sf(av_mul_sf(temp, sbr->q_mapped[e][m]));

                sbr->s_m[e][m] = av_sqrt_sf(av_mul_sf(temp, av_int2sf(ch_data->s_indexmapped[e + 1][m], 0)));

                if (!sbr->s_mapped[e][m]) {

                    if (delta) {

                      sbr->gain[e][m] = av_sqrt_sf(av_div_sf(sbr->e_origmapped[e][m],

                                            av_mul_sf(av_add_sf(FLOAT_1, sbr->e_curr[e][m]),

                                            av_add_sf(FLOAT_1, sbr->q_mapped[e][m]))));

                    } else {

                      sbr->gain[e][m] = av_sqrt_sf(av_div_sf(sbr->e_origmapped[e][m],

                                            av_add_sf(FLOAT_1, sbr->e_curr[e][m])));

                    }

                } else {

                    sbr->gain[e][m] = av_sqrt_sf(

                                        av_div_sf(

                                            av_mul_sf(sbr->e_origmapped[e][m], sbr->q_mapped[e][m]),

                                            av_mul_sf(

                                                av_add_sf(FLOAT_1, sbr->e_curr[e][m]),

                                                av_add_sf(FLOAT_1, sbr->q_mapped[e][m]))));

                }

            }

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sum[0] = av_add_sf(sum[0], sbr->e_origmapped[e][m]);

                sum[1] = av_add_sf(sum[1], sbr->e_curr[e][m]);

            }

            gain_max = av_mul_sf(limgain[sbr->bs_limiter_gains],

                            av_sqrt_sf(

                                av_div_sf(

                                    av_add_sf(FLOAT_EPSILON, sum[0]),

                                    av_add_sf(FLOAT_EPSILON, sum[1]))));

            if (av_gt_sf(gain_max, FLOAT_100000))

              gain_max = FLOAT_100000;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                SoftFloat q_m_max = av_div_sf(

                                        av_mul_sf(sbr->q_m[e][m], gain_max),

                                        sbr->gain[e][m]);

                if (av_gt_sf(sbr->q_m[e][m], q_m_max))

                  sbr->q_m[e][m] = q_m_max;

                if (av_gt_sf(sbr->gain[e][m], gain_max))

                  sbr->gain[e][m] = gain_max;

            }

            sum[0] = sum[1] = FLOAT_0;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sum[0] = av_add_sf(sum[0], sbr->e_origmapped[e][m]);

                sum[1] = av_add_sf(sum[1],

                            av_mul_sf(

                                av_mul_sf(sbr->e_curr[e][m],

                                          sbr->gain[e][m]),

                                sbr->gain[e][m]));

                sum[1] = av_add_sf(sum[1],

                            av_mul_sf(sbr->s_m[e][m], sbr->s_m[e][m]));

                if (delta && !sbr->s_m[e][m].mant)

                  sum[1] = av_add_sf(sum[1],

                                av_mul_sf(sbr->q_m[e][m], sbr->q_m[e][m]));

            }

            gain_boost = av_sqrt_sf(

                            av_div_sf(

                                av_add_sf(FLOAT_EPSILON, sum[0]),

                                av_add_sf(FLOAT_EPSILON, sum[1])));

            if (av_gt_sf(gain_boost, FLOAT_1584893192))

              gain_boost = FLOAT_1584893192;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sbr->gain[e][m] = av_mul_sf(sbr->gain[e][m], gain_boost);

                sbr->q_m[e][m]  = av_mul_sf(sbr->q_m[e][m], gain_boost);

                sbr->s_m[e][m]  = av_mul_sf(sbr->s_m[e][m], gain_boost);

            }

        }

    }

}


x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    struct x11_grab *s = s1->priv_data;

    Display *dpy = s->dpy;

    XImage *image = s->image;

    int x_off = s->x_off;

    int y_off = s->y_off;

    int64_t curtime, delay;

    struct timespec ts;

    /* Calculate the time of the next frame */

    s->time_frame += INT64_C(1000000);

    /* wait based on the frame rate */

    for(;;) {

        curtime = av_gettime();

        delay = s->time_frame * av_q2d(s->time_base) - curtime;

        if (delay <= 0) {

            if (delay < INT64_C(-1000000) * av_q2d(s->time_base)) {

                s->time_frame += INT64_C(1000000);

            }

            break;

        }

        ts.tv_sec = delay / 1000000;

        ts.tv_nsec = (delay % 1000000) * 1000;

        nanosleep(&ts, NULL);

    }

    av_init_packet(pkt);

    pkt->data = image->data;

    pkt->size = s->frame_size;

    pkt->pts = curtime;

    if(s->use_shm) {

        if (!XShmGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off, AllPlanes)) {

            av_log (s1, AV_LOG_INFO, "XShmGetImage() failed\n");

        }

    } else {

        if (!xget_zpixmap(dpy, RootWindow(dpy, DefaultScreen(dpy)), image, x_off, y_off)) {

            av_log (s1, AV_LOG_INFO, "XGetZPixmap() failed\n");

        }

    }

    if(!s->nomouse){

        paint_mouse_pointer(image, s);

    }

    return s->frame_size;

}


static int svq3_decode_slice_header(H264Context *h)

{

    MpegEncContext *const s = (MpegEncContext *) h;

    const int mb_xy = h->mb_xy;

    int i, header;

    header = get_bits(&s->gb, 8);

    if (((header & 0x9F) != 1 && (header & 0x9F) != 2) || (header & 0x60) == 0) {

        /* TODO: what? */

        av_log(h->s.avctx, AV_LOG_ERROR, "unsupported slice header (%02X)\n", header);

        return -1;

    } else {

        int length = (header >> 5) & 3;

        h->next_slice_index = get_bits_count(&s->gb) + 8*show_bits(&s->gb, 8*length) + 8*length;

        if (h->next_slice_index > s->gb.size_in_bits) {

            av_log(h->s.avctx, AV_LOG_ERROR, "slice after bitstream end\n");

            return -1;

    }

        s->gb.size_in_bits = h->next_slice_index - 8*(length - 1);

        skip_bits(&s->gb, 8);

        if (h->svq3_watermark_key) {

            uint32_t header = AV_RL32(&s->gb.buffer[(get_bits_count(&s->gb)>>3)+1]);

            AV_WL32(&s->gb.buffer[(get_bits_count(&s->gb)>>3)+1], header ^ h->svq3_watermark_key);

        }

        if (length > 0) {

            memcpy((uint8_t *) &s->gb.buffer[get_bits_count(&s->gb) >> 3],

                   &s->gb.buffer[s->gb.size_in_bits >> 3], (length - 1));

        }

        skip_bits_long(&s->gb, 0);

    }

    if ((i = svq3_get_ue_golomb(&s->gb)) == INVALID_VLC || i >= 3){

        av_log(h->s.avctx, AV_LOG_ERROR, "illegal slice type %d \n", i);

        return -1;

    }

    h->slice_type = golomb_to_pict_type[i];

    if ((header & 0x9F) == 2) {

        i = (s->mb_num < 64) ? 6 : (1 + av_log2 (s->mb_num - 1));

        s->mb_skip_run = get_bits(&s->gb, i) - (s->mb_x + (s->mb_y * s->mb_width));

    } else {

        skip_bits1(&s->gb);

        s->mb_skip_run = 0;

    }

    h->slice_num = get_bits(&s->gb, 8);

    s->qscale = get_bits(&s->gb, 5);

    s->adaptive_quant = get_bits1(&s->gb);

    /* unknown fields */

    skip_bits1(&s->gb);

    if (h->unknown_svq3_flag) {

        skip_bits1(&s->gb);

    }

    skip_bits1(&s->gb);

    skip_bits(&s->gb, 2);

    while (get_bits1(&s->gb)) {

        skip_bits(&s->gb, 8);

    }

    /* reset intra predictors and invalidate motion vector references */

    if (s->mb_x > 0) {

        memset(h->intra4x4_pred_mode+8*h->mb2br_xy[mb_xy - 1      ]+3, -1, 4*sizeof(int8_t));

        memset(h->intra4x4_pred_mode+8*h->mb2br_xy[mb_xy - s->mb_x]  , -1, 8*sizeof(int8_t)*s->mb_x);

    }

    if (s->mb_y > 0) {

        memset(h->intra4x4_pred_mode+8*h->mb2br_xy[mb_xy - s->mb_stride], -1, 8*sizeof(int8_t)*(s->mb_width - s->mb_x));

        if (s->mb_x > 0) {

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

        }

    }

    return 0;

}


POWERPC_FAMILY(POWER7P)(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);

    dc->fw_name = "PowerPC,POWER7+";

    dc->desc = "POWER7+";

    pcc->pvr = CPU_POWERPC_POWER7P_BASE;

    pcc->pvr_mask = CPU_POWERPC_POWER7P_MASK;

    pcc->init_proc = init_proc_POWER7;

    pcc->check_pow = check_pow_nocheck;

    pcc->insns_flags = PPC_INSNS_BASE | PPC_ISEL | PPC_STRING | PPC_MFTB |

                       PPC_FLOAT | PPC_FLOAT_FSEL | PPC_FLOAT_FRES |

                       PPC_FLOAT_FSQRT | PPC_FLOAT_FRSQRTE |

                       PPC_FLOAT_FRSQRTES |

                       PPC_FLOAT_STFIWX |

                       PPC_FLOAT_EXT |

                       PPC_CACHE | PPC_CACHE_ICBI | PPC_CACHE_DCBZ |

                       PPC_MEM_SYNC | PPC_MEM_EIEIO |

                       PPC_MEM_TLBIE | PPC_MEM_TLBSYNC |

                       PPC_64B | PPC_ALTIVEC |

                       PPC_SEGMENT_64B | PPC_SLBI |

                       PPC_POPCNTB | PPC_POPCNTWD;

    pcc->insns_flags2 = PPC2_VSX | PPC2_DFP | PPC2_DBRX | PPC2_ISA205 |

                        PPC2_PERM_ISA206 | PPC2_DIVE_ISA206 |

                        PPC2_ATOMIC_ISA206 | PPC2_FP_CVT_ISA206 |

                        PPC2_FP_TST_ISA206;

    pcc->msr_mask = (1ull << MSR_SF) |

                    (1ull << MSR_VR) |

                    (1ull << MSR_VSX) |

                    (1ull << MSR_EE) |

                    (1ull << MSR_PR) |

                    (1ull << MSR_FP) |

                    (1ull << MSR_ME) |

                    (1ull << MSR_FE0) |

                    (1ull << MSR_SE) |

                    (1ull << MSR_DE) |

                    (1ull << MSR_FE1) |

                    (1ull << MSR_IR) |

                    (1ull << MSR_DR) |

                    (1ull << MSR_PMM) |

                    (1ull << MSR_RI) |

                    (1ull << MSR_LE);

    pcc->mmu_model = POWERPC_MMU_2_06;

#if defined(CONFIG_SOFTMMU)

    pcc->handle_mmu_fault = ppc_hash64_handle_mmu_fault;

#endif

    pcc->excp_model = POWERPC_EXCP_POWER7;

    pcc->bus_model = PPC_FLAGS_INPUT_POWER7;

    pcc->bfd_mach = bfd_mach_ppc64;

    pcc->flags = POWERPC_FLAG_VRE | POWERPC_FLAG_SE |

                 POWERPC_FLAG_BE | POWERPC_FLAG_PMM |

                 POWERPC_FLAG_BUS_CLK | POWERPC_FLAG_CFAR |

                 POWERPC_FLAG_VSX;

    pcc->l1_dcache_size = 0x8000;

    pcc->l1_icache_size = 0x8000;

    pcc->interrupts_big_endian = ppc_cpu_interrupts_big_endian_lpcr;

}


static uint16_t phys_section_add(MemoryRegionSection *section)
{
    if (phys_sections_nb == phys_sections_nb_alloc) {
        phys_sections_nb_alloc = MAX(phys_sections_nb_alloc * 2, 16);
        phys_sections = g_renew(MemoryRegionSection, phys_sections,
                                phys_sections_nb_alloc);
    }
    phys_sections[phys_sections_nb] = *section;
    return phys_sections_nb++;
}


static int tta_read_header(AVFormatContext *s)

{

    TTAContext *c = s->priv_data;

    AVStream *st;

    int i, channels, bps, samplerate;

    uint64_t framepos, start_offset;

    uint32_t datalen;

    if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX))

        ff_id3v1_read(s);

    start_offset = avio_tell(s->pb);

    if (avio_rl32(s->pb) != AV_RL32("TTA1"))

        return -1; // not tta file

    avio_skip(s->pb, 2); // FIXME: flags

    channels = avio_rl16(s->pb);

    bps = avio_rl16(s->pb);

    samplerate = avio_rl32(s->pb);

    if(samplerate <= 0 || samplerate > 1000000){

        av_log(s, AV_LOG_ERROR, "nonsense samplerate\n");

        return -1;

    }

    datalen = avio_rl32(s->pb);

    if (!datalen) {

        av_log(s, AV_LOG_ERROR, "invalid datalen\n");

        return AVERROR_INVALIDDATA;

    }

    avio_skip(s->pb, 4); // header crc

    c->frame_size      = samplerate * 256 / 245;

    c->last_frame_size = datalen % c->frame_size;

    if (!c->last_frame_size)

        c->last_frame_size = c->frame_size;

    c->totalframes = datalen / c->frame_size + (c->last_frame_size < c->frame_size);

    c->currentframe = 0;

    if(c->totalframes >= UINT_MAX/sizeof(uint32_t) || c->totalframes <= 0){

        av_log(s, AV_LOG_ERROR, "totalframes %d invalid\n", c->totalframes);

        return -1;

    }

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 64, 1, samplerate);

    st->start_time = 0;

    st->duration = datalen;

    framepos = avio_tell(s->pb) + 4*c->totalframes + 4;

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

        uint32_t size = avio_rl32(s->pb);

        av_add_index_entry(st, framepos, i * c->frame_size, size, 0,

                           AVINDEX_KEYFRAME);

        framepos += size;

    }

    avio_skip(s->pb, 4); // seektable crc

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id = AV_CODEC_ID_TTA;

    st->codec->channels = channels;

    st->codec->sample_rate = samplerate;

    st->codec->bits_per_coded_sample = bps;

    st->codec->extradata_size = avio_tell(s->pb) - start_offset;

    if(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){

        //this check is redundant as avio_read should fail

        av_log(s, AV_LOG_ERROR, "extradata_size too large\n");

        return -1;

    }

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

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

        st->codec->extradata_size = 0;

        return AVERROR(ENOMEM);

    }

    avio_seek(s->pb, start_offset, SEEK_SET);

    avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);

    return 0;

}


static void sub2video_update(InputStream *ist, AVSubtitle *sub)

{

    int w = ist->sub2video.w, h = ist->sub2video.h;

    AVFrame *frame = ist->sub2video.frame;

    int8_t *dst;

    int     dst_linesize;

    int num_rects, i;

    int64_t pts, end_pts;

    if (!frame)

        return;

    if (sub) {

        pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000,

                                 AV_TIME_BASE_Q, ist->st->time_base);

        end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000,

                                 AV_TIME_BASE_Q, ist->st->time_base);

        num_rects = sub->num_rects;

    } else {

        pts       = ist->sub2video.end_pts;

        end_pts   = INT64_MAX;

        num_rects = 0;

    }

    if (sub2video_get_blank_frame(ist) < 0) {

        av_log(ist->dec_ctx, AV_LOG_ERROR,

               "Impossible to get a blank canvas.\n");

        return;

    }

    dst          = frame->data    [0];

    dst_linesize = frame->linesize[0];

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

        sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);

    sub2video_push_ref(ist, pts);

    ist->sub2video.end_pts = end_pts;

}


void helper_movcal(CPUSH4State *env, uint32_t address, uint32_t value)

{

    if (cpu_sh4_is_cached (env, address))

    {

	memory_content *r = malloc (sizeof(memory_content));

	r->address = address;

	r->value = value;

	r->next = NULL;

	*(env->movcal_backup_tail) = r;

	env->movcal_backup_tail = &(r->next);

    }

}


static inline uint16_t mipsdsp_lshift16(uint16_t a, uint8_t s,

                                        CPUMIPSState *env)

{

    uint8_t  sign;

    uint16_t discard;

    if (s == 0) {

        return a;

    } else {

        sign = (a >> 15) & 0x01;

        if (sign != 0) {

            discard = (((0x01 << (16 - s)) - 1) << s) |

                      ((a >> (14 - (s - 1))) & ((0x01 << s) - 1));

        } else {

            discard = a >> (14 - (s - 1));

        }

        if ((discard != 0x0000) && (discard != 0xFFFF)) {

            set_DSPControl_overflow_flag(1, 22, env);

        }

        return a << s;

    }

}


static ssize_t dump_receive(VLANClientState *vc, const uint8_t *buf, size_t size)

{

    DumpState *s = vc->opaque;

    struct pcap_sf_pkthdr hdr;

    int64_t ts;

    int caplen;

    /* Early return in case of previous error. */

    if (s->fd < 0) {

        return size;

    }

    ts = muldiv64(qemu_get_clock(vm_clock), 1000000, get_ticks_per_sec());

    caplen = size > s->pcap_caplen ? s->pcap_caplen : size;

    hdr.ts.tv_sec = ts / 1000000;

    hdr.ts.tv_usec = ts % 1000000;

    hdr.caplen = caplen;

    hdr.len = size;

    if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||

        write(s->fd, buf, caplen) != caplen) {

        qemu_log("-net dump write error - stop dump\n");

        close(s->fd);

        s->fd = -1;

    }

    return size;

}


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

{

    OpenPICState *opp = (OpenPICState *)opaque;

    unsigned int i;

    if (version_id != 1) {

        return -EINVAL;

    }

    qemu_get_be32s(f, &opp->gcr);

    qemu_get_be32s(f, &opp->vir);

    qemu_get_be32s(f, &opp->pir);

    qemu_get_be32s(f, &opp->spve);

    qemu_get_be32s(f, &opp->tfrr);

    qemu_get_be32s(f, &opp->nb_cpus);

    for (i = 0; i < opp->nb_cpus; i++) {

        qemu_get_sbe32s(f, &opp->dst[i].ctpr);

        openpic_load_IRQ_queue(f, &opp->dst[i].raised);

        openpic_load_IRQ_queue(f, &opp->dst[i].servicing);

        qemu_get_buffer(f, (uint8_t *)&opp->dst[i].outputs_active,

                        sizeof(opp->dst[i].outputs_active));

    }

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

        qemu_get_be32s(f, &opp->timers[i].tccr);

        qemu_get_be32s(f, &opp->timers[i].tbcr);

    }

    for (i = 0; i < opp->max_irq; i++) {

        uint32_t val;

        val = qemu_get_be32(f);

        write_IRQreg_idr(opp, i, val);

        val = qemu_get_be32(f);

        write_IRQreg_ivpr(opp, i, val);

        qemu_get_be32s(f, &opp->src[i].ivpr);

        qemu_get_be32s(f, &opp->src[i].idr);

        qemu_get_be32s(f, &opp->src[i].destmask);

        qemu_get_sbe32s(f, &opp->src[i].last_cpu);

        qemu_get_sbe32s(f, &opp->src[i].pending);

    }

    return 0;

}


int vnc_tight_send_framebuffer_update(VncState *vs, int x, int y,

                                      int w, int h)

{

    int max_rows;

    if (vs->clientds.pf.bytes_per_pixel == 4 && vs->clientds.pf.rmax == 0xFF &&

        vs->clientds.pf.bmax == 0xFF && vs->clientds.pf.gmax == 0xFF) {

        vs->tight_pixel24 = true;

    } else {

        vs->tight_pixel24 = false;

    }

    if (w * h < VNC_TIGHT_MIN_SPLIT_RECT_SIZE)

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

    /* Calculate maximum number of rows in one non-solid rectangle. */

    max_rows = tight_conf[vs->tight_compression].max_rect_size;

    max_rows /= MIN(tight_conf[vs->tight_compression].max_rect_width, w);

    return find_large_solid_color_rect(vs, x, y, w, h, max_rows);

}


static uint64_t fw_cfg_data_mem_read(void *opaque, hwaddr addr,

                                     unsigned size)

{

    return fw_cfg_read(opaque);

}


static IOMMUTLBEntry amdvi_translate(MemoryRegion *iommu, hwaddr addr,

                                     bool is_write)

{

    AMDVIAddressSpace *as = container_of(iommu, AMDVIAddressSpace, iommu);

    AMDVIState *s = as->iommu_state;

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = addr,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE

    };

    if (!s->enabled) {

        /* AMDVI disabled - corresponds to iommu=off not

         * failure to provide any parameter

         */

        ret.iova = addr & AMDVI_PAGE_MASK_4K;

        ret.translated_addr = addr & AMDVI_PAGE_MASK_4K;

        ret.addr_mask = ~AMDVI_PAGE_MASK_4K;

        ret.perm = IOMMU_RW;

        return ret;

    } else if (amdvi_is_interrupt_addr(addr)) {

        ret.iova = addr & AMDVI_PAGE_MASK_4K;

        ret.translated_addr = addr & AMDVI_PAGE_MASK_4K;

        ret.addr_mask = ~AMDVI_PAGE_MASK_4K;

        ret.perm = IOMMU_WO;

        return ret;

    }

    amdvi_do_translate(as, addr, is_write, &ret);

    trace_amdvi_translation_result(as->bus_num, PCI_SLOT(as->devfn),

            PCI_FUNC(as->devfn), addr, ret.translated_addr);

    return ret;

}


void ahci_command_wait(AHCIQState *ahci, AHCICommand *cmd)

{

    /* We can't rely on STS_BSY until the command has started processing.

     * Therefore, we also use the Command Issue bit as indication of

     * a command in-flight. */

    while (BITSET(ahci_px_rreg(ahci, cmd->port, AHCI_PX_TFD),

                  AHCI_PX_TFD_STS_BSY) ||

           BITSET(ahci_px_rreg(ahci, cmd->port, AHCI_PX_CI), (1 << cmd->slot))) {

        usleep(50);

    }

}


static inline int gen_intermediate_code_internal(TranslationBlock * tb,

						 int spc, CPUSPARCState *env)

{

    target_ulong pc_start, last_pc;

    uint16_t *gen_opc_end;

    DisasContext dc1, *dc = &dc1;

    int j, lj = -1;

    memset(dc, 0, sizeof(DisasContext));

    dc->tb = tb;

    pc_start = tb->pc;

    dc->pc = pc_start;

    dc->npc = (target_ulong) tb->cs_base;

#if defined(CONFIG_USER_ONLY)

    dc->mem_idx = 0;

#else

    dc->mem_idx = ((env->psrs) != 0);

#endif

    gen_opc_ptr = gen_opc_buf;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    gen_opparam_ptr = gen_opparam_buf;

    env->access_type = ACCESS_CODE;

    do {

        if (env->nb_breakpoints > 0) {

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

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

                    gen_debug(dc, dc->pc);

                    break;

                }

            }

        }

        if (spc) {

            if (loglevel > 0)

                fprintf(logfile, "Search PC...\n");

            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_npc[lj] = dc->npc;

                gen_opc_instr_start[lj] = 1;

            }

        }

	last_pc = dc->pc;

	disas_sparc_insn(dc);

	if (dc->is_br)

	    break;

	/* if the next PC is different, we abort now */

	if (dc->pc != (last_pc + 4))

	    break;

    } while ((gen_opc_ptr < gen_opc_end) &&

	     (dc->pc - pc_start) < (TARGET_PAGE_SIZE - 32));

    if (!dc->is_br) {

        if (dc->pc != DYNAMIC_PC &&

            (dc->npc != DYNAMIC_PC && dc->npc != JUMP_PC)) {

            /* static PC and NPC: we can use direct chaining */

            gen_op_branch((long)tb, dc->pc, dc->npc);

        } else {

            if (dc->pc != DYNAMIC_PC)

                gen_op_jmp_im(dc->pc);

            save_npc(dc);

            gen_op_movl_T0_0();

            gen_op_exit_tb();

        }

    }

    *gen_opc_ptr = INDEX_op_end;

    if (spc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

        tb->size = 0;

#if 0

        if (loglevel > 0) {

            page_dump(logfile);

        }

#endif

    } else {

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

    }

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

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

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

	disas(logfile, (uint8_t *)pc_start, last_pc + 4 - pc_start, 0, 0);

	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

    env->access_type = ACCESS_DATA;

    return 0;

}


static void term_hist_add(const char *cmdline)

{

    char *hist_entry, *new_entry;

    int idx;

    if (cmdline[0] == '\0')

	return;

    new_entry = NULL;

    if (term_hist_entry != -1) {

	/* We were editing an existing history entry: replace it */

	hist_entry = term_history[term_hist_entry];

	idx = term_hist_entry;

	if (strcmp(hist_entry, cmdline) == 0) {

	    goto same_entry;

	}

    }

    /* Search cmdline in history buffers */

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

	hist_entry = term_history[idx];

	if (hist_entry == NULL)

	    break;

	if (strcmp(hist_entry, cmdline) == 0) {

	same_entry:

	    new_entry = hist_entry;

	    /* Put this entry at the end of history */

	    memmove(&term_history[idx], &term_history[idx + 1],

		    &term_history[TERM_MAX_CMDS] - &term_history[idx + 1]);

	    term_history[TERM_MAX_CMDS - 1] = NULL;

	    for (; idx < TERM_MAX_CMDS; idx++) {

		if (term_history[idx] == NULL)

		    break;

	    }

	    break;

	}

    }

    if (idx == TERM_MAX_CMDS) {

	/* Need to get one free slot */

	free(term_history[0]);

	memcpy(term_history, &term_history[1],

	       &term_history[TERM_MAX_CMDS] - &term_history[1]);

	term_history[TERM_MAX_CMDS - 1] = NULL;

	idx = TERM_MAX_CMDS - 1;

    }

    if (new_entry == NULL)

	new_entry = strdup(cmdline);

    term_history[idx] = new_entry;

    term_hist_entry = -1;

}


static av_cold int flic_decode_init(AVCodecContext *avctx)

{

    FlicDecodeContext *s = avctx->priv_data;

    unsigned char *fli_header = (unsigned char *)avctx->extradata;

    int depth;

    if (avctx->extradata_size != 12 &&

        avctx->extradata_size != 128) {

        av_log(avctx, AV_LOG_ERROR, "Expected extradata of 12 or 128 bytes\n");

        return AVERROR_INVALIDDATA;

    }

    s->avctx = avctx;

    s->fli_type = AV_RL16(&fli_header[4]); /* Might be overridden if a Magic Carpet FLC */

    depth = 0;

    if (s->avctx->extradata_size == 12) {

        /* special case for magic carpet FLIs */

        s->fli_type = FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE;

        depth = 8;

    } else {

        depth = AV_RL16(&fli_header[12]);

    }

    if (depth == 0) {

        depth = 8; /* Some FLC generators set depth to zero, when they mean 8Bpp. Fix up here */

    }

    if ((s->fli_type == FLC_FLX_TYPE_CODE) && (depth == 16)) {

        depth = 15; /* Original Autodesk FLX's say the depth is 16Bpp when it is really 15Bpp */

    }

    switch (depth) {

        case 8  : avctx->pix_fmt = AV_PIX_FMT_PAL8; break;

        case 15 : avctx->pix_fmt = AV_PIX_FMT_RGB555; break;

        case 16 : avctx->pix_fmt = AV_PIX_FMT_RGB565; break;

        case 24 : avctx->pix_fmt = AV_PIX_FMT_BGR24; /* Supposedly BGR, but havent any files to test with */

                  av_log(avctx, AV_LOG_ERROR, "24Bpp FLC/FLX is unsupported due to no test files.\n");

                  return AVERROR_PATCHWELCOME;

        default :

                  av_log(avctx, AV_LOG_ERROR, "Unknown FLC/FLX depth of %d Bpp is unsupported.\n",depth);

                  return AVERROR_INVALIDDATA;

    }

    s->frame.data[0] = NULL;

    s->new_palette = 0;

    return 0;

}


static int mmu_translate_region(CPUS390XState *env, target_ulong vaddr,

                                uint64_t asc, uint64_t entry, int level,

                                target_ulong *raddr, int *flags, int rw,

                                bool exc)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    uint64_t origin, offs, new_entry;

    const int pchks[4] = {

        PGM_SEGMENT_TRANS, PGM_REG_THIRD_TRANS,

        PGM_REG_SEC_TRANS, PGM_REG_FIRST_TRANS

    };

    PTE_DPRINTF("%s: 0x%" PRIx64 "\n", __func__, entry);

    origin = entry & _REGION_ENTRY_ORIGIN;

    offs = (vaddr >> (17 + 11 * level / 4)) & 0x3ff8;

    new_entry = ldq_phys(cs->as, origin + offs);

    PTE_DPRINTF("%s: 0x%" PRIx64 " + 0x%" PRIx64 " => 0x%016" PRIx64 "\n",

                __func__, origin, offs, new_entry);

    if ((new_entry & _REGION_ENTRY_INV) != 0) {

        DPRINTF("%s: invalid region\n", __func__);

        trigger_page_fault(env, vaddr, pchks[level / 4], asc, rw, exc);

        return -1;

    }

    if ((new_entry & _REGION_ENTRY_TYPE_MASK) != level) {

        trigger_page_fault(env, vaddr, PGM_TRANS_SPEC, asc, rw, exc);

        return -1;

    }

    /* XXX region protection flags */

    /* *flags &= ~PAGE_WRITE */

    if (level == _ASCE_TYPE_SEGMENT) {

        return mmu_translate_segment(env, vaddr, asc, new_entry, raddr, flags,

                                     rw, exc);

    }

    /* Check region table offset and length */

    offs = (vaddr >> (28 + 11 * (level - 4) / 4)) & 3;

    if (offs < ((new_entry & _REGION_ENTRY_TF) >> 6)

        || offs > (new_entry & _REGION_ENTRY_LENGTH)) {

        DPRINTF("%s: invalid offset or len (%lx)\n", __func__, new_entry);

        trigger_page_fault(env, vaddr, pchks[level / 4 - 1], asc, rw, exc);

        return -1;

    }

    /* yet another region */

    return mmu_translate_region(env, vaddr, asc, new_entry, level - 4,

                                raddr, flags, rw, exc);

}


static const char *rpath(FsContext *ctx, const char *path)

{

    /* FIXME: so wrong... */

    static char buffer[4096];

    snprintf(buffer, sizeof(buffer), "%s/%s", ctx->fs_root, path);

    return buffer;

}


uint32_t HELPER(mvcl)(CPUS390XState *env, uint32_t r1, uint32_t r2)

{

    uintptr_t ra = GETPC();

    uint64_t destlen = env->regs[r1 + 1] & 0xffffff;

    uint64_t dest = get_address(env, r1);

    uint64_t srclen = env->regs[r2 + 1] & 0xffffff;

    uint64_t src = get_address(env, r2);

    uint8_t pad = env->regs[r2 + 1] >> 24;

    uint8_t v;

    uint32_t cc;

    if (destlen == srclen) {

        cc = 0;

    } else if (destlen < srclen) {

        cc = 1;

    } else {

        cc = 2;

    }

    if (srclen > destlen) {

        srclen = destlen;

    }

    for (; destlen && srclen; src++, dest++, destlen--, srclen--) {

        v = cpu_ldub_data_ra(env, src, ra);

        cpu_stb_data_ra(env, dest, v, ra);

    }

    for (; destlen; dest++, destlen--) {

        cpu_stb_data_ra(env, dest, pad, ra);

    }

    env->regs[r1 + 1] = destlen;

    /* can't use srclen here, we trunc'ed it */

    env->regs[r2 + 1] -= src - env->regs[r2];

    set_address(env, r1, dest);

    set_address(env, r2, src);

    return cc;

}


static int do_compress_ram_page(CompressParam *param)

{

    int bytes_sent, blen;

    uint8_t *p;

    RAMBlock *block = param->block;

    ram_addr_t offset = param->offset;

    p = block->host + (offset & TARGET_PAGE_MASK);

    bytes_sent = save_page_header(param->file, block, offset |

                                  RAM_SAVE_FLAG_COMPRESS_PAGE);

    blen = qemu_put_compression_data(param->file, p, TARGET_PAGE_SIZE,

                                     migrate_compress_level());

    bytes_sent += blen;

    return bytes_sent;

}


static int get_fw_cfg_order(FWCfgState *s, const char *name)

{

    int i;

    if (s->fw_cfg_order_override > 0) {

        return s->fw_cfg_order_override;

    }

    for (i = 0; i < ARRAY_SIZE(fw_cfg_order); i++) {

        if (fw_cfg_order[i].name == NULL) {

            continue;

        }

        if (strcmp(name, fw_cfg_order[i].name) == 0) {

            return fw_cfg_order[i].order;

        }

    }

    /* Stick unknown stuff at the end. */

    error_report("warning: Unknown firmware file in legacy mode: %s", name);

    return FW_CFG_ORDER_OVERRIDE_LAST;

}


int qemu_strtol(const char *nptr, const char **endptr, int base,

                long *result)

{

    char *ep;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        *result = strtol(nptr, &ep, base);

        err = check_strtox_error(nptr, ep, endptr, errno);

    }

    return err;

}


void ff_sbr_apply(AACContext *ac, SpectralBandReplication *sbr, int id_aac,

                  float* L, float* R)

{

    int downsampled = ac->m4ac.ext_sample_rate < sbr->sample_rate;

    int ch;

    int nch = (id_aac == TYPE_CPE) ? 2 : 1;

    if (sbr->start) {

        sbr_dequant(sbr, id_aac);

    }

    for (ch = 0; ch < nch; ch++) {

        /* decode channel */

        sbr_qmf_analysis(&ac->dsp, &sbr->mdct_ana, ch ? R : L, sbr->data[ch].analysis_filterbank_samples,

                         (float*)sbr->qmf_filter_scratch,

                         sbr->data[ch].W);

        sbr_lf_gen(ac, sbr, sbr->X_low, sbr->data[ch].W);

        if (sbr->start) {

            sbr_hf_inverse_filter(sbr->alpha0, sbr->alpha1, sbr->X_low, sbr->k[0]);

            sbr_chirp(sbr, &sbr->data[ch]);

            sbr_hf_gen(ac, sbr, sbr->X_high, sbr->X_low, sbr->alpha0, sbr->alpha1,

                       sbr->data[ch].bw_array, sbr->data[ch].t_env,

                       sbr->data[ch].bs_num_env);

            // hf_adj

            sbr_mapping(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);

            sbr_env_estimate(sbr->e_curr, sbr->X_high, sbr, &sbr->data[ch]);

            sbr_gain_calc(ac, sbr, &sbr->data[ch], sbr->data[ch].e_a);

            sbr_hf_assemble(sbr->data[ch].Y, sbr->X_high, sbr, &sbr->data[ch],

                            sbr->data[ch].e_a);

        }

        /* synthesis */

        sbr_x_gen(sbr, sbr->X[ch], sbr->X_low, sbr->data[ch].Y, ch);

    }

    if (ac->m4ac.ps == 1) {

        if (sbr->ps.start) {

            ff_ps_apply(ac->avctx, &sbr->ps, sbr->X[0], sbr->X[1], sbr->kx[1] + sbr->m[1]);

        } else {

            memcpy(sbr->X[1], sbr->X[0], sizeof(sbr->X[0]));

        }

        nch = 2;

    }

    sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, L, sbr->X[0], sbr->qmf_filter_scratch,

                      sbr->data[0].synthesis_filterbank_samples,

                      &sbr->data[0].synthesis_filterbank_samples_offset,

                      downsampled);

    if (nch == 2)

        sbr_qmf_synthesis(&ac->dsp, &sbr->mdct, R, sbr->X[1], sbr->qmf_filter_scratch,

                          sbr->data[1].synthesis_filterbank_samples,

                          &sbr->data[1].synthesis_filterbank_samples_offset,

                          downsampled);

}