static int test_vector_fmac_scalar(AVFloatDSPContext *fdsp, AVFloatDSPContext *cdsp,

                                   const float *v1, const float *src0, float scale)

{

    LOCAL_ALIGNED(32, float, cdst, [LEN]);

    LOCAL_ALIGNED(32, float, odst, [LEN]);

    int ret;

    memcpy(cdst, v1, LEN * sizeof(*v1));

    memcpy(odst, v1, LEN * sizeof(*v1));

    cdsp->vector_fmac_scalar(cdst, src0, scale, LEN);

    fdsp->vector_fmac_scalar(odst, src0, scale, LEN);

    if (ret = compare_floats(cdst, odst, LEN, ARBITRARY_FMAC_SCALAR_CONST))

        av_log(NULL, AV_LOG_ERROR, "vector_fmac_scalar failed\n");

    return ret;

}


static void add_pc_test_cases(void)

{

    QDict *response, *minfo;

    QList *list;

    const QListEntry *p;

    QObject *qobj;

    QString *qstr;

    const char *mname, *path;

    PCTestData *data;

    qtest_start("-machine none");

    response = qmp("{ 'execute': 'query-machines' }");

    g_assert(response);

    list = qdict_get_qlist(response, "return");

    g_assert(list);

    for (p = qlist_first(list); p; p = qlist_next(p)) {

        minfo = qobject_to_qdict(qlist_entry_obj(p));

        g_assert(minfo);

        qobj = qdict_get(minfo, "name");

        g_assert(qobj);

        qstr = qobject_to_qstring(qobj);

        g_assert(qstr);

        mname = qstring_get_str(qstr);

        if (!g_str_has_prefix(mname, "pc-")) {

            continue;

        }

        data = g_malloc(sizeof(PCTestData));

        data->machine = mname;

        data->cpu_model = "Haswell"; /* 1.3+ theoretically */

        data->sockets = 1;

        data->cores = 3;

        data->threads = 2;

        data->maxcpus = data->sockets * data->cores * data->threads * 2;

        if (g_str_has_suffix(mname, "-1.4") ||

            (strcmp(mname, "pc-1.3") == 0) ||

            (strcmp(mname, "pc-1.2") == 0) ||

            (strcmp(mname, "pc-1.1") == 0) ||

            (strcmp(mname, "pc-1.0") == 0) ||

            (strcmp(mname, "pc-0.15") == 0) ||

            (strcmp(mname, "pc-0.14") == 0) ||

            (strcmp(mname, "pc-0.13") == 0) ||

            (strcmp(mname, "pc-0.12") == 0) ||

            (strcmp(mname, "pc-0.11") == 0) ||

            (strcmp(mname, "pc-0.10") == 0)) {

            path = g_strdup_printf("cpu/%s/init/%ux%ux%u&maxcpus=%u",

                                   mname, data->sockets, data->cores,

                                   data->threads, data->maxcpus);

            qtest_add_data_func(path, data, test_pc_without_cpu_add);

        } else {

            path = g_strdup_printf("cpu/%s/add/%ux%ux%u&maxcpus=%u",

                                   mname, data->sockets, data->cores,

                                   data->threads, data->maxcpus);

            qtest_add_data_func(path, data, test_pc_with_cpu_add);

        }

    }

    qtest_end();

}


static void test_qga_set_time(gconstpointer fix)

{

    const TestFixture *fixture = fix;

    QDict *ret;

    int64_t current, time;

    gchar *cmd;

    /* get current time */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-time'}");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    current = qdict_get_int(ret, "return");

    g_assert_cmpint(current, >, 0);

    QDECREF(ret);

    /* set some old time */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-set-time',"

                 " 'arguments': { 'time': 1000 } }");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    QDECREF(ret);

    /* check old time */

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-get-time'}");

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    time = qdict_get_int(ret, "return");

    g_assert_cmpint(time / 1000, <, G_USEC_PER_SEC * 10);

    QDECREF(ret);

    /* set back current time */

    cmd = g_strdup_printf("{'execute': 'guest-set-time',"

                          " 'arguments': { 'time': %" PRId64 " } }",

                          current + time * 1000);

    ret = qmp_fd(fixture->fd, cmd);

    g_free(cmd);

    g_assert_nonnull(ret);

    qmp_assert_no_error(ret);

    QDECREF(ret);

}


static void bus_set_realized(Object *obj, bool value, Error **errp)

{

    BusState *bus = BUS(obj);

    BusClass *bc = BUS_GET_CLASS(bus);

    Error *local_err = NULL;

    if (value && !bus->realized) {

        if (bc->realize) {

            bc->realize(bus, &local_err);

        }

    } else if (!value && bus->realized) {

        if (bc->unrealize) {

            bc->unrealize(bus, &local_err);

        }

    }

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        return;

    }

    bus->realized = value;

}


static inline void asv2_encode_block(ASV1Context *a, int16_t block[64])

{

    int i;

    int count = 0;

    for (count = 63; count > 3; count--) {

        const int index = ff_asv_scantab[count];

        if ((block[index] * a->q_intra_matrix[index] + (1 << 15)) >> 16)

            break;

    }

    count >>= 2;

    asv2_put_bits(&a->pb, 4, count);

    asv2_put_bits(&a->pb, 8, (block[0] + 32) >> 6);

    block[0] = 0;

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

        const int index = ff_asv_scantab[4 * i];

        int ccp         = 0;

        if ((block[index + 0] = (block[index + 0] *

                                 a->q_intra_matrix[index + 0] + (1 << 15)) >> 16))

            ccp |= 8;

        if ((block[index + 8] = (block[index + 8] *

                                 a->q_intra_matrix[index + 8] + (1 << 15)) >> 16))

            ccp |= 4;

        if ((block[index + 1] = (block[index + 1] *

                                 a->q_intra_matrix[index + 1] + (1 << 15)) >> 16))

            ccp |= 2;

        if ((block[index + 9] = (block[index + 9] *

                                 a->q_intra_matrix[index + 9] + (1 << 15)) >> 16))

            ccp |= 1;

        av_assert2(i || ccp < 8);

        if (i)

            put_bits(&a->pb, ff_asv_ac_ccp_tab[ccp][1], ff_asv_ac_ccp_tab[ccp][0]);

        else

            put_bits(&a->pb, ff_asv_dc_ccp_tab[ccp][1], ff_asv_dc_ccp_tab[ccp][0]);

        if (ccp) {

            if (ccp & 8)

                asv2_put_level(&a->pb, block[index + 0]);

            if (ccp & 4)

                asv2_put_level(&a->pb, block[index + 8]);

            if (ccp & 2)

                asv2_put_level(&a->pb, block[index + 1]);

            if (ccp & 1)

                asv2_put_level(&a->pb, block[index + 9]);

        }

    }

}


static void gen_tlbilx_booke206(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    switch((ctx->opcode >> 21) & 0x3) {

    case 0:

        gen_helper_booke206_tlbilx0(cpu_env, t0);

        break;

    case 1:

        gen_helper_booke206_tlbilx1(cpu_env, t0);

        break;

    case 3:

        gen_helper_booke206_tlbilx3(cpu_env, t0);

        break;

    default:

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

        break;

    }

    tcg_temp_free(t0);

#endif

}


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

{

    if(st->request_probe>0){

        AVProbeData *pd = &st->probe_data;

        int end;

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

        --st->probe_packets;

        if (pkt) {

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

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

            pd->buf_size += pkt->size;

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

        } else {

            st->probe_packets = 0;

        }

        end=    s->raw_packet_buffer_remaining_size <= 0

                || st->probe_packets<=0;

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

            int score= set_codec_from_probe_data(s, st, pd);

            if(    (st->codec->codec_id != CODEC_ID_NONE && score > AVPROBE_SCORE_MAX/4)

                || end){

                pd->buf_size=0;

                av_freep(&pd->buf);

                st->request_probe= -1;

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

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

                }else

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

            }

        }

    }

}


static void pci_basic(void)

{

    QVirtioPCIDevice *dev;

    QPCIBus *bus;

    QVirtQueuePCI *vqpci;

    QGuestAllocator *alloc;

    void *addr;

    bus = pci_test_start();

    dev = virtio_blk_pci_init(bus, PCI_SLOT);

    alloc = pc_alloc_init();

    vqpci = (QVirtQueuePCI *)qvirtqueue_setup(&qvirtio_pci, &dev->vdev,

                                                                    alloc, 0);

    /* MSI-X is not enabled */

    addr = dev->addr + VIRTIO_PCI_CONFIG_OFF(false);

    test_basic(&qvirtio_pci, &dev->vdev, alloc, &vqpci->vq,

                                                    (uint64_t)(uintptr_t)addr);

    /* End test */

    guest_free(alloc, vqpci->vq.desc);

    pc_alloc_uninit(alloc);

    qvirtio_pci_device_disable(dev);

    g_free(dev);

    qpci_free_pc(bus);

    test_end();

}


static void gen_spr_440 (CPUPPCState *env)

{

    /* Cache control */

    /* XXX : not implemented */

    spr_register(env, SPR_440_DNV0, "DNV0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DNV1, "DNV1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DNV2, "DNV2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DNV3, "DNV3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DVT0, "DVT0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DVT1, "DVT1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DVT2, "DVT2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DVT3, "DVT3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DVLIM, "DVLIM",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_INV0, "INV0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_INV1, "INV1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_INV2, "INV2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_INV3, "INV3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_IVT0, "IVT0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_IVT1, "IVT1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_IVT2, "IVT2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_IVT3, "IVT3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_IVLIM, "IVLIM",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Cache debug */

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_DCBTRH, "DCBTRH",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_DCBTRL, "DCBTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_ICBDR, "ICBDR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_ICBTRH, "ICBTRH",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_ICBTRL, "ICBTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_440_DBDR, "DBDR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Processor control */

    spr_register(env, SPR_4xx_CCR0, "CCR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_440_RSTCFG, "RSTCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000);

    /* Storage control */

    spr_register(env, SPR_440_MMUCR, "MMUCR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

}


static void get_cpuid_vendor(CPUX86State *env, uint32_t *ebx,

                             uint32_t *ecx, uint32_t *edx)

{

    *ebx = env->cpuid_vendor1;

    *edx = env->cpuid_vendor2;

    *ecx = env->cpuid_vendor3;

    /* sysenter isn't supported on compatibility mode on AMD, syscall

     * isn't supported in compatibility mode on Intel.

     * Normally we advertise the actual cpu vendor, but you can override

     * this if you want to use KVM's sysenter/syscall emulation

     * in compatibility mode and when doing cross vendor migration

     */

    if (kvm_enabled() && env->cpuid_vendor_override) {

        host_cpuid(0, 0, NULL, ebx, ecx, edx);

    }

}


void qmp_blockdev_change_medium(const char *device, const char *filename,

                                bool has_format, const char *format,

                                bool has_read_only,

                                BlockdevChangeReadOnlyMode read_only,

                                Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *medium_bs = NULL;

    int bdrv_flags, ret;

    QDict *options = NULL;

    Error *err = NULL;

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", device);

        goto fail;

    }

    if (blk_bs(blk)) {

        blk_update_root_state(blk);

    }

    bdrv_flags = blk_get_open_flags_from_root_state(blk);

    bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |

        BDRV_O_PROTOCOL);

    if (!has_read_only) {

        read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;

    }

    switch (read_only) {

    case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:

        break;

    case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:

        bdrv_flags &= ~BDRV_O_RDWR;

        break;

    case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:

        bdrv_flags |= BDRV_O_RDWR;

        break;

    default:

        abort();

    }

    if (has_format) {

        options = qdict_new();

        qdict_put(options, "driver", qstring_from_str(format));

    }

    assert(!medium_bs);

    ret = bdrv_open(&medium_bs, filename, NULL, options, bdrv_flags, errp);

    if (ret < 0) {

        goto fail;

    }

    blk_apply_root_state(blk, medium_bs);

    bdrv_add_key(medium_bs, NULL, &err);

    if (err) {

        error_propagate(errp, err);

        goto fail;

    }

    qmp_blockdev_open_tray(device, false, false, &err);

    if (err) {

        error_propagate(errp, err);

        goto fail;

    }

    qmp_x_blockdev_remove_medium(device, &err);

    if (err) {

        error_propagate(errp, err);

        goto fail;

    }

    qmp_blockdev_insert_anon_medium(device, medium_bs, &err);

    if (err) {

        error_propagate(errp, err);

        goto fail;

    }

    qmp_blockdev_close_tray(device, errp);

fail:

    /* If the medium has been inserted, the device has its own reference, so

     * ours must be relinquished; and if it has not been inserted successfully,

     * the reference must be relinquished anyway */

    bdrv_unref(medium_bs);

}


static inline int ppcemb_tlb_check(CPUState *env, ppcemb_tlb_t *tlb,

                                   target_phys_addr_t *raddrp,

                                   target_ulong address, uint32_t pid, int ext,

                                   int i)

{

    target_ulong mask;

    /* Check valid flag */

    if (!(tlb->prot & PAGE_VALID)) {

        qemu_log("%s: TLB %d not valid\n", __func__, i);

        return -1;

    }

    mask = ~(tlb->size - 1);

    LOG_SWTLB("%s: TLB %d address " TARGET_FMT_lx " PID %u <=> " TARGET_FMT_lx

              " " TARGET_FMT_lx " %u\n", __func__, i, address, pid, tlb->EPN,

              mask, (uint32_t)tlb->PID);

    /* Check PID */

    if (tlb->PID != 0 && tlb->PID != pid)

        return -1;

    /* Check effective address */

    if ((address & mask) != tlb->EPN)

        return -1;

    *raddrp = (tlb->RPN & mask) | (address & ~mask);

#if (TARGET_PHYS_ADDR_BITS >= 36)

    if (ext) {

        /* Extend the physical address to 36 bits */

        *raddrp |= (target_phys_addr_t)(tlb->RPN & 0xF) << 32;

    }

#endif

    return 0;

}


void ppc_slb_invalidate_one (CPUPPCState *env, uint64_t T0)

{

    /* XXX: TODO */

    tlb_flush(env, 1);

}


static void validate_test_add(const char *testpath,

                               TestInputVisitorData *data,

                               void (*test_func)(TestInputVisitorData *data, const void *user_data))

{

    g_test_add(testpath, TestInputVisitorData, data, NULL, test_func,

               validate_teardown);

}


static void omap_ulpd_pm_write(void *opaque, target_phys_addr_t addr,

                               uint64_t value, unsigned size)

{

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

    int64_t now, ticks;

    int div, mult;

    static const int bypass_div[4] = { 1, 2, 4, 4 };

    uint16_t diff;

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    switch (addr) {

    case 0x00:	/* COUNTER_32_LSB */

    case 0x04:	/* COUNTER_32_MSB */

    case 0x08:	/* COUNTER_HIGH_FREQ_LSB */

    case 0x0c:	/* COUNTER_HIGH_FREQ_MSB */

    case 0x14:	/* IT_STATUS */

    case 0x40:	/* STATUS_REQ */

        OMAP_RO_REG(addr);

        break;

    case 0x10:	/* GAUGING_CTRL */

        /* Bits 0 and 1 seem to be confused in the OMAP 310 TRM */

        if ((s->ulpd_pm_regs[addr >> 2] ^ value) & 1) {

            now = qemu_get_clock_ns(vm_clock);

            if (value & 1)

                s->ulpd_gauge_start = now;

            else {

                now -= s->ulpd_gauge_start;

                /* 32-kHz ticks */

                ticks = muldiv64(now, 32768, get_ticks_per_sec());

                s->ulpd_pm_regs[0x00 >> 2] = (ticks >>  0) & 0xffff;

                s->ulpd_pm_regs[0x04 >> 2] = (ticks >> 16) & 0xffff;

                if (ticks >> 32)	/* OVERFLOW_32K */

                    s->ulpd_pm_regs[0x14 >> 2] |= 1 << 2;

                /* High frequency ticks */

                ticks = muldiv64(now, 12000000, get_ticks_per_sec());

                s->ulpd_pm_regs[0x08 >> 2] = (ticks >>  0) & 0xffff;

                s->ulpd_pm_regs[0x0c >> 2] = (ticks >> 16) & 0xffff;

                if (ticks >> 32)	/* OVERFLOW_HI_FREQ */

                    s->ulpd_pm_regs[0x14 >> 2] |= 1 << 1;

                s->ulpd_pm_regs[0x14 >> 2] |= 1 << 0;	/* IT_GAUGING */

                qemu_irq_raise(qdev_get_gpio_in(s->ih[1], OMAP_INT_GAUGE_32K));

            }

        }

        s->ulpd_pm_regs[addr >> 2] = value;

        break;

    case 0x18:	/* Reserved */

    case 0x1c:	/* Reserved */

    case 0x20:	/* Reserved */

    case 0x28:	/* Reserved */

    case 0x2c:	/* Reserved */

        OMAP_BAD_REG(addr);

    case 0x24:	/* SETUP_ANALOG_CELL3_ULPD1 */

    case 0x38:	/* COUNTER_32_FIQ */

    case 0x48:	/* LOCL_TIME */

    case 0x50:	/* POWER_CTRL */

        s->ulpd_pm_regs[addr >> 2] = value;

        break;

    case 0x30:	/* CLOCK_CTRL */

        diff = s->ulpd_pm_regs[addr >> 2] ^ value;

        s->ulpd_pm_regs[addr >> 2] = value & 0x3f;

        omap_ulpd_clk_update(s, diff, value);

        break;

    case 0x34:	/* SOFT_REQ */

        diff = s->ulpd_pm_regs[addr >> 2] ^ value;

        s->ulpd_pm_regs[addr >> 2] = value & 0x1f;

        omap_ulpd_req_update(s, diff, value);

        break;

    case 0x3c:	/* DPLL_CTRL */

        /* XXX: OMAP310 TRM claims bit 3 is PLL_ENABLE, and bit 4 is

         * omitted altogether, probably a typo.  */

        /* This register has identical semantics with DPLL(1:3) control

         * registers, see omap_dpll_write() */

        diff = s->ulpd_pm_regs[addr >> 2] & value;

        s->ulpd_pm_regs[addr >> 2] = value & 0x2fff;

        if (diff & (0x3ff << 2)) {

            if (value & (1 << 4)) {			/* PLL_ENABLE */

                div = ((value >> 5) & 3) + 1;		/* PLL_DIV */

                mult = MIN((value >> 7) & 0x1f, 1);	/* PLL_MULT */

            } else {

                div = bypass_div[((value >> 2) & 3)];	/* BYPASS_DIV */

                mult = 1;

            }

            omap_clk_setrate(omap_findclk(s, "dpll4"), div, mult);

        }

        /* Enter the desired mode.  */

        s->ulpd_pm_regs[addr >> 2] =

                (s->ulpd_pm_regs[addr >> 2] & 0xfffe) |

                ((s->ulpd_pm_regs[addr >> 2] >> 4) & 1);

        /* Act as if the lock is restored.  */

        s->ulpd_pm_regs[addr >> 2] |= 2;

        break;

    case 0x4c:	/* APLL_CTRL */

        diff = s->ulpd_pm_regs[addr >> 2] & value;

        s->ulpd_pm_regs[addr >> 2] = value & 0xf;

        if (diff & (1 << 0))				/* APLL_NDPLL_SWITCH */

            omap_clk_reparent(omap_findclk(s, "ck_48m"), omap_findclk(s,

                                    (value & (1 << 0)) ? "apll" : "dpll4"));

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


void cpu_dump_state (CPUState *env, FILE *f,

                     int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                     int flags)

{

#define RGPL  4

#define RFPL  4

    int i;

    cpu_fprintf(f, "NIP " ADDRX "   LR " ADDRX " CTR " ADDRX " XER %08x\n",

                env->nip, env->lr, env->ctr, env->xer);

    cpu_fprintf(f, "MSR " ADDRX " HID0 " ADDRX "  HF " ADDRX " idx %d\n",

                env->msr, env->spr[SPR_HID0], env->hflags, env->mmu_idx);

#if !defined(NO_TIMER_DUMP)

    cpu_fprintf(f, "TB %08x %08x "

#if !defined(CONFIG_USER_ONLY)

                "DECR %08x"

#endif

                "\n",

                cpu_ppc_load_tbu(env), cpu_ppc_load_tbl(env)

#if !defined(CONFIG_USER_ONLY)

                , cpu_ppc_load_decr(env)

#endif

                );

#endif

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

        if ((i & (RGPL - 1)) == 0)

            cpu_fprintf(f, "GPR%02d", i);

        cpu_fprintf(f, " " REGX, 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 " ADDRX "\n", env->reserve);

    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 " ADDRX " SRR1 " ADDRX " SDR1 " ADDRX "\n",

                env->spr[SPR_SRR0], env->spr[SPR_SRR1], env->sdr1);

#endif

#undef RGPL

#undef RFPL

}


static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)

{

    UnsharpContext *unsharp = ctx->priv;

    int lmsize_x = 5, cmsize_x = 0;

    int lmsize_y = 5, cmsize_y = 0;

    double lamount = 1.0f, camount = 0.0f;

    if (args)

        sscanf(args, "%d:%d:%lf:%d:%d:%lf", &lmsize_x, &lmsize_y, &lamount,

                                            &cmsize_x, &cmsize_y, &camount);

    if ((lamount && (lmsize_x < 2 || lmsize_y < 2)) ||

        (camount && (cmsize_x < 2 || cmsize_y < 2))) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid value <2 for lmsize_x:%d or lmsize_y:%d or cmsize_x:%d or cmsize_y:%d\n",

               lmsize_x, lmsize_y, cmsize_x, cmsize_y);

        return AVERROR(EINVAL);

    }

    set_filter_param(&unsharp->luma,   lmsize_x, lmsize_y, lamount);

    set_filter_param(&unsharp->chroma, cmsize_x, cmsize_y, camount);

    return 0;

}


int ff_h264_update_thread_context(AVCodecContext *dst,

                                  const AVCodecContext *src)

{

    H264Context *h = dst->priv_data, *h1 = src->priv_data;

    int inited = h->context_initialized, err = 0;

    int need_reinit = 0;

    int i, ret;

    if (dst == src || !h1->context_initialized)

        return 0;

    if (!h1->ps.sps)

        return AVERROR_INVALIDDATA;

    if (inited &&

        (h->width                 != h1->width                 ||

         h->height                != h1->height                ||

         h->mb_width              != h1->mb_width              ||

         h->mb_height             != h1->mb_height             ||

         !h->ps.sps                                            ||

         h->ps.sps->bit_depth_luma    != h1->ps.sps->bit_depth_luma    ||

         h->ps.sps->chroma_format_idc != h1->ps.sps->chroma_format_idc ||

         h->ps.sps->colorspace        != h1->ps.sps->colorspace)) {

        need_reinit = 1;

    }

    // SPS/PPS

    for (i = 0; i < FF_ARRAY_ELEMS(h->ps.sps_list); i++) {

        av_buffer_unref(&h->ps.sps_list[i]);

        if (h1->ps.sps_list[i]) {

            h->ps.sps_list[i] = av_buffer_ref(h1->ps.sps_list[i]);

            if (!h->ps.sps_list[i])

                return AVERROR(ENOMEM);

        }

    }

    for (i = 0; i < FF_ARRAY_ELEMS(h->ps.pps_list); i++) {

        av_buffer_unref(&h->ps.pps_list[i]);

        if (h1->ps.pps_list[i]) {

            h->ps.pps_list[i] = av_buffer_ref(h1->ps.pps_list[i]);

            if (!h->ps.pps_list[i])

                return AVERROR(ENOMEM);

        }

    }

    h->ps.sps = h1->ps.sps;

    if (need_reinit || !inited) {

        h->width     = h1->width;

        h->height    = h1->height;

        h->mb_height = h1->mb_height;

        h->mb_width  = h1->mb_width;

        h->mb_num    = h1->mb_num;

        h->mb_stride = h1->mb_stride;

        h->b_stride  = h1->b_stride;

        if ((err = h264_slice_header_init(h)) < 0) {

            av_log(h->avctx, AV_LOG_ERROR, "h264_slice_header_init() failed");

            return err;

        }

        /* copy block_offset since frame_start may not be called */

        memcpy(h->block_offset, h1->block_offset, sizeof(h->block_offset));

    }

    h->avctx->coded_height  = h1->avctx->coded_height;

    h->avctx->coded_width   = h1->avctx->coded_width;

    h->avctx->width         = h1->avctx->width;

    h->avctx->height        = h1->avctx->height;

    h->coded_picture_number = h1->coded_picture_number;

    h->first_field          = h1->first_field;

    h->picture_structure    = h1->picture_structure;

    h->droppable            = h1->droppable;

    h->low_delay            = h1->low_delay;

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

        ff_h264_unref_picture(h, &h->DPB[i]);

        if (h1->DPB[i].f->buf[0] &&

            (ret = ff_h264_ref_picture(h, &h->DPB[i], &h1->DPB[i])) < 0)

            return ret;

    }

    h->cur_pic_ptr = REBASE_PICTURE(h1->cur_pic_ptr, h, h1);

    ff_h264_unref_picture(h, &h->cur_pic);

    if (h1->cur_pic.f->buf[0]) {

        ret = ff_h264_ref_picture(h, &h->cur_pic, &h1->cur_pic);

        if (ret < 0)

            return ret;

    }

    h->enable_er       = h1->enable_er;

    h->workaround_bugs = h1->workaround_bugs;

    h->low_delay       = h1->low_delay;

    h->droppable       = h1->droppable;

    // extradata/NAL handling

    h->is_avc = h1->is_avc;

    h->nal_length_size = h1->nal_length_size;

    // POC timing

    copy_fields(h, h1, poc_lsb, current_slice);

    copy_picture_range(h->short_ref, h1->short_ref, 32, h, h1);

    copy_picture_range(h->long_ref, h1->long_ref, 32, h, h1);

    copy_picture_range(h->delayed_pic, h1->delayed_pic,

                       MAX_DELAYED_PIC_COUNT + 2, h, h1);

    if (!h->cur_pic_ptr)

        return 0;

    if (!h->droppable) {

        err = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index);

        h->prev_poc_msb = h->poc_msb;

        h->prev_poc_lsb = h->poc_lsb;

    }

    h->prev_frame_num_offset = h->frame_num_offset;

    h->prev_frame_num        = h->frame_num;

    h->recovery_frame        = h1->recovery_frame;

    h->frame_recovered       = h1->frame_recovered;

    return err;

}


static int find_partition(BlockDriverState *bs, int partition,

                          off_t *offset, off_t *size)

{

    struct partition_record mbr[4];

    uint8_t data[512];

    int i;

    int ext_partnum = 4;

    int ret;

    if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {

        errno = -ret;

        err(EXIT_FAILURE, "error while reading");

    }

    if (data[510] != 0x55 || data[511] != 0xaa) {

        errno = -EINVAL;

        return -1;

    }

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

        read_partition(&data[446 + 16 * i], &mbr[i]);

        if (!mbr[i].nb_sectors_abs)

            continue;

        if (mbr[i].system == 0xF || mbr[i].system == 0x5) {

            struct partition_record ext[4];

            uint8_t data1[512];

            int j;

            if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {

                errno = -ret;

                err(EXIT_FAILURE, "error while reading");

            }

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

                read_partition(&data1[446 + 16 * j], &ext[j]);

                if (!ext[j].nb_sectors_abs)

                    continue;

                if ((ext_partnum + j + 1) == partition) {

                    *offset = (uint64_t)ext[j].start_sector_abs << 9;

                    *size = (uint64_t)ext[j].nb_sectors_abs << 9;

                    return 0;

                }

            }

            ext_partnum += 4;

        } else if ((i + 1) == partition) {

            *offset = (uint64_t)mbr[i].start_sector_abs << 9;

            *size = (uint64_t)mbr[i].nb_sectors_abs << 9;

            return 0;

        }

    }

    errno = -ENOENT;

    return -1;

}


static void thread_pool_cancel(BlockDriverAIOCB *acb)

{

    ThreadPoolElement *elem = (ThreadPoolElement *)acb;

    ThreadPool *pool = elem->pool;

    trace_thread_pool_cancel(elem, elem->common.opaque);

    qemu_mutex_lock(&pool->lock);

    if (elem->state == THREAD_QUEUED &&

        /* No thread has yet started working on elem. we can try to "steal"

         * the item from the worker if we can get a signal from the

         * semaphore.  Because this is non-blocking, we can do it with

         * the lock taken and ensure that elem will remain THREAD_QUEUED.

         */

        qemu_sem_timedwait(&pool->sem, 0) == 0) {

        QTAILQ_REMOVE(&pool->request_list, elem, reqs);

        elem->state = THREAD_CANCELED;

        event_notifier_set(&pool->notifier);

    } else {

        pool->pending_cancellations++;

        while (elem->state != THREAD_CANCELED && elem->state != THREAD_DONE) {

            qemu_cond_wait(&pool->check_cancel, &pool->lock);

        }

        pool->pending_cancellations--;

    }

    qemu_mutex_unlock(&pool->lock);

    event_notifier_ready(&pool->notifier);

}


void qemu_fflush(QEMUFile *f)

{

    if (!f->is_writable)

        return;

    if (f->buf_index > 0) {

        if (f->is_file) {

            fseek(f->outfile, f->buf_offset, SEEK_SET);

            fwrite(f->buf, 1, f->buf_index, f->outfile);

        } else {

            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,

                        f->buf, f->buf_index);

        }

        f->buf_offset += f->buf_index;

        f->buf_index = 0;

    }

}


uint64_t ram_bytes_transferred(void)

{

    return bytes_transferred;

}


static void qxl_spice_destroy_surface_wait(PCIQXLDevice *qxl, uint32_t id,

                                           qxl_async_io async)

{

    if (async) {

#if SPICE_INTERFACE_QXL_MINOR < 1

        abort();

#else

        spice_qxl_destroy_surface_async(&qxl->ssd.qxl, id,

                                        (uint64_t)id);

#endif

    } else {

        qxl->ssd.worker->destroy_surface_wait(qxl->ssd.worker, id);

        qxl_spice_destroy_surface_wait_complete(qxl, id);

    }

}


static inline void copy_backptr(LZOContext *c, int back, int cnt)

{

    register const uint8_t *src = &c->out[-back];

    register uint8_t *dst       = c->out;

    if (src < c->out_start || src > dst) {

        c->error |= AV_LZO_INVALID_BACKPTR;

        return;

    }

    if (cnt > c->out_end - dst) {

        cnt       = FFMAX(c->out_end - dst, 0);

        c->error |= AV_LZO_OUTPUT_FULL;

    }

    av_memcpy_backptr(dst, back, cnt);

    c->out = dst + cnt;

}


bool guest_validate_base(unsigned long guest_base)

{

    return 1;

}


static inline int mpeg1_decode_block_intra(MpegEncContext *s, int16_t *block, int n)

{

    int level, dc, diff, i, j, run;

    int component;

    RLTable *rl = &ff_rl_mpeg1;

    uint8_t * const scantable    = s->intra_scantable.permutated;

    const uint16_t *quant_matrix = s->intra_matrix;

    const int qscale             = s->qscale;

    /* DC coefficient */

    component = (n <= 3 ? 0 : n - 4 + 1);

    diff = decode_dc(&s->gb, component);

    if (diff >= 0xffff)

        return -1;

    dc  = s->last_dc[component];

    dc += diff;

    s->last_dc[component] = dc;

    block[0] = dc * quant_matrix[0];

    av_dlog(s->avctx, "dc=%d diff=%d\n", dc, diff);

    i = 0;

    {

        OPEN_READER(re, &s->gb);

        /* now quantify & encode AC coefficients */

        for (;;) {

            UPDATE_CACHE(re, &s->gb);

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

            if (level == 127) {

                break;

            } else if (level != 0) {

                i += run;

                j = scantable[i];

                level = (level * qscale * quant_matrix[j]) >> 4;

                level = (level - 1) | 1;

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

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

            } else {

                /* escape */

                run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);

                UPDATE_CACHE(re, &s->gb);

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

                if (level == -128) {

                    level = SHOW_UBITS(re, &s->gb, 8) - 256; LAST_SKIP_BITS(re, &s->gb, 8);

                } else if (level == 0) {

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

                }

                i += run;

                j = scantable[i];

                if (level < 0) {

                    level = -level;

                    level = (level * qscale * quant_matrix[j]) >> 4;

                    level = (level - 1) | 1;

                    level = -level;

                } else {

                    level = (level * qscale * quant_matrix[j]) >> 4;

                    level = (level - 1) | 1;

                }

            }

            if (i > 63) {

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

                return -1;

            }

            block[j] = level;

        }

        CLOSE_READER(re, &s->gb);

    }

    s->block_last_index[n] = i;

   return 0;

}


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

                  uint64_t *result)

{

    char *p;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        *result = strtoull(nptr, &p, base);

        err = check_strtox_error(endptr, p, errno);

    }

    return err;

}


static void gen_rac(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    t0 = tcg_temp_new();

    gen_addr_reg_index(ctx, t0);

    gen_helper_rac(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


static void kvm_s390_stattrib_synchronize(S390StAttribState *sa)

{

    KVMS390StAttribState *sas = KVM_S390_STATTRIB(sa);

    MachineState *machine = MACHINE(qdev_get_machine());

    unsigned long max = machine->maxram_size / TARGET_PAGE_SIZE;

    unsigned long cx, len = 1 << 19;

    int r;

    struct kvm_s390_cmma_log clog = {

        .flags = 0,

        .mask = ~0ULL,

    };

    if (sas->incoming_buffer) {

        for (cx = 0; cx + len <= max; cx += len) {

            clog.start_gfn = cx;

            clog.count = len;

            clog.values = (uint64_t)(sas->incoming_buffer + cx * len);

            r = kvm_vm_ioctl(kvm_state, KVM_S390_SET_CMMA_BITS, &clog);

            if (r) {

                error_report("KVM_S390_SET_CMMA_BITS failed: %s", strerror(-r));

                return;

            }

        }

        if (cx < max) {

            clog.start_gfn = cx;

            clog.count = max - cx;

            clog.values = (uint64_t)(sas->incoming_buffer + cx * len);

            r = kvm_vm_ioctl(kvm_state, KVM_S390_SET_CMMA_BITS, &clog);

            if (r) {

                error_report("KVM_S390_SET_CMMA_BITS failed: %s", strerror(-r));

            }

        }

        g_free(sas->incoming_buffer);

        sas->incoming_buffer = NULL;

    }

}


static void handle_qmp_command(JSONMessageParser *parser, GQueue *tokens)

{

    QObject *req, *rsp = NULL, *id = NULL;

    QDict *qdict = NULL;

    const char *cmd_name;

    Monitor *mon = cur_mon;

    Error *err = NULL;

    req = json_parser_parse_err(tokens, NULL, &err);

    if (!req && !err) {

        /* json_parser_parse_err() sucks: can fail without setting @err */

        error_setg(&err, QERR_JSON_PARSING);

    }

    if (err) {

        goto err_out;

    }

    qdict = qmp_check_input_obj(req, &err);

    if (!qdict) {

        goto err_out;

    }

    id = qdict_get(qdict, "id");

    qobject_incref(id);

    qdict_del(qdict, "id");

    cmd_name = qdict_get_str(qdict, "execute");

    trace_handle_qmp_command(mon, cmd_name);

    rsp = qmp_dispatch(cur_mon->qmp.commands, req);

    if (mon->qmp.commands == &qmp_cap_negotiation_commands) {

        qdict = qdict_get_qdict(qobject_to_qdict(rsp), "error");

        if (qdict

            && !g_strcmp0(qdict_get_try_str(qdict, "class"),

                    QapiErrorClass_lookup[ERROR_CLASS_COMMAND_NOT_FOUND])) {

            /* Provide a more useful error message */

            qdict_del(qdict, "desc");

            qdict_put(qdict, "desc",

                      qstring_from_str("Expecting capabilities negotiation"

                                       " with 'qmp_capabilities'"));

        }

    }

err_out:

    if (err) {

        qdict = qdict_new();

        qdict_put_obj(qdict, "error", qmp_build_error_object(err));

        error_free(err);

        rsp = QOBJECT(qdict);

    }

    if (rsp) {

        if (id) {

            qdict_put_obj(qobject_to_qdict(rsp), "id", id);

            id = NULL;

        }

        monitor_json_emitter(mon, rsp);

    }

    qobject_decref(id);

    qobject_decref(rsp);

    qobject_decref(req);

}


static void test_blk_read(BlockBackend *blk, long pattern,

                          int64_t pattern_offset, int64_t pattern_count,

                          int64_t offset, int64_t count,

                          bool expect_failed)

{

    void *pattern_buf = NULL;

    QEMUIOVector qiov;

    void *cmp_buf = NULL;

    int async_ret = NOT_DONE;

    if (pattern) {

        cmp_buf = g_malloc(pattern_count);

        memset(cmp_buf, pattern, pattern_count);

    }

    pattern_buf = g_malloc(count);

    if (pattern) {

        memset(pattern_buf, pattern, count);

    } else {

        memset(pattern_buf, 0x00, count);

    }

    qemu_iovec_init(&qiov, 1);

    qemu_iovec_add(&qiov, pattern_buf, count);

    blk_aio_preadv(blk, offset, &qiov, 0, blk_rw_done, &async_ret);

    while (async_ret == NOT_DONE) {

        main_loop_wait(false);

    }

    if (expect_failed) {

        g_assert(async_ret != 0);

    } else {

        g_assert(async_ret == 0);

        if (pattern) {

            g_assert(memcmp(pattern_buf + pattern_offset,

                            cmp_buf, pattern_count) <= 0);

        }

    }

    g_free(pattern_buf);

}


int ff_h264_decode_seq_parameter_set(GetBitContext *gb, AVCodecContext *avctx,

                                     H264ParamSets *ps, int ignore_truncation)

{

    AVBufferRef *sps_buf;

    int profile_idc, level_idc, constraint_set_flags = 0;

    unsigned int sps_id;

    int i, log2_max_frame_num_minus4;

    SPS *sps;

    sps_buf = av_buffer_allocz(sizeof(*sps));

    if (!sps_buf)

        return AVERROR(ENOMEM);

    sps = (SPS*)sps_buf->data;

    sps->data_size = gb->buffer_end - gb->buffer;

    if (sps->data_size > sizeof(sps->data)) {

        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized SPS\n");

        sps->data_size = sizeof(sps->data);

    }

    memcpy(sps->data, gb->buffer, sps->data_size);

    profile_idc           = get_bits(gb, 8);

    constraint_set_flags |= get_bits1(gb) << 0;   // constraint_set0_flag

    constraint_set_flags |= get_bits1(gb) << 1;   // constraint_set1_flag

    constraint_set_flags |= get_bits1(gb) << 2;   // constraint_set2_flag

    constraint_set_flags |= get_bits1(gb) << 3;   // constraint_set3_flag

    constraint_set_flags |= get_bits1(gb) << 4;   // constraint_set4_flag

    constraint_set_flags |= get_bits1(gb) << 5;   // constraint_set5_flag

    skip_bits(gb, 2);                             // reserved_zero_2bits

    level_idc = get_bits(gb, 8);

    sps_id    = get_ue_golomb_31(gb);

    if (sps_id >= MAX_SPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "sps_id %u out of range\n", sps_id);

        goto fail;

    }

    sps->sps_id               = sps_id;

    sps->time_offset_length   = 24;

    sps->profile_idc          = profile_idc;

    sps->constraint_set_flags = constraint_set_flags;

    sps->level_idc            = level_idc;

    sps->full_range           = -1;

    memset(sps->scaling_matrix4, 16, sizeof(sps->scaling_matrix4));

    memset(sps->scaling_matrix8, 16, sizeof(sps->scaling_matrix8));

    sps->scaling_matrix_present = 0;

    sps->colorspace = 2; //AVCOL_SPC_UNSPECIFIED

    if (sps->profile_idc == 100 ||  // High profile

        sps->profile_idc == 110 ||  // High10 profile

        sps->profile_idc == 122 ||  // High422 profile

        sps->profile_idc == 244 ||  // High444 Predictive profile

        sps->profile_idc ==  44 ||  // Cavlc444 profile

        sps->profile_idc ==  83 ||  // Scalable Constrained High profile (SVC)

        sps->profile_idc ==  86 ||  // Scalable High Intra profile (SVC)

        sps->profile_idc == 118 ||  // Stereo High profile (MVC)

        sps->profile_idc == 128 ||  // Multiview High profile (MVC)

        sps->profile_idc == 138 ||  // Multiview Depth High profile (MVCD)

        sps->profile_idc == 144) {  // old High444 profile

        sps->chroma_format_idc = get_ue_golomb_31(gb);

        if (sps->chroma_format_idc > 3U) {

            avpriv_request_sample(avctx, "chroma_format_idc %u",

                                  sps->chroma_format_idc);

            goto fail;

        } else if (sps->chroma_format_idc == 3) {

            sps->residual_color_transform_flag = get_bits1(gb);

            if (sps->residual_color_transform_flag) {

                av_log(avctx, AV_LOG_ERROR, "separate color planes are not supported\n");

                goto fail;

            }

        }

        sps->bit_depth_luma   = get_ue_golomb(gb) + 8;

        sps->bit_depth_chroma = get_ue_golomb(gb) + 8;

        if (sps->bit_depth_chroma != sps->bit_depth_luma) {

            avpriv_request_sample(avctx,

                                  "Different chroma and luma bit depth");

            goto fail;

        }

        if (sps->bit_depth_luma   < 8 || sps->bit_depth_luma   > 14 ||

            sps->bit_depth_chroma < 8 || sps->bit_depth_chroma > 14) {

            av_log(avctx, AV_LOG_ERROR, "illegal bit depth value (%d, %d)\n",

                   sps->bit_depth_luma, sps->bit_depth_chroma);

            goto fail;

        }

        sps->transform_bypass = get_bits1(gb);

        sps->scaling_matrix_present |= decode_scaling_matrices(gb, sps, NULL, 1,

                                sps->scaling_matrix4, sps->scaling_matrix8);

    } else {

        sps->chroma_format_idc = 1;

        sps->bit_depth_luma    = 8;

        sps->bit_depth_chroma  = 8;

    }

    log2_max_frame_num_minus4 = get_ue_golomb(gb);

    if (log2_max_frame_num_minus4 < MIN_LOG2_MAX_FRAME_NUM - 4 ||

        log2_max_frame_num_minus4 > MAX_LOG2_MAX_FRAME_NUM - 4) {

        av_log(avctx, AV_LOG_ERROR,

               "log2_max_frame_num_minus4 out of range (0-12): %d\n",

               log2_max_frame_num_minus4);

        goto fail;

    }

    sps->log2_max_frame_num = log2_max_frame_num_minus4 + 4;

    sps->poc_type = get_ue_golomb_31(gb);

    if (sps->poc_type == 0) { // FIXME #define

        unsigned t = get_ue_golomb(gb);

        if (t>12) {

            av_log(avctx, AV_LOG_ERROR, "log2_max_poc_lsb (%d) is out of range\n", t);

            goto fail;

        }

        sps->log2_max_poc_lsb = t + 4;

    } else if (sps->poc_type == 1) { // FIXME #define

        sps->delta_pic_order_always_zero_flag = get_bits1(gb);

        sps->offset_for_non_ref_pic           = get_se_golomb(gb);

        sps->offset_for_top_to_bottom_field   = get_se_golomb(gb);

        sps->poc_cycle_length                 = get_ue_golomb(gb);

        if ((unsigned)sps->poc_cycle_length >=

            FF_ARRAY_ELEMS(sps->offset_for_ref_frame)) {

            av_log(avctx, AV_LOG_ERROR,

                   "poc_cycle_length overflow %d\n", sps->poc_cycle_length);

            goto fail;

        }

        for (i = 0; i < sps->poc_cycle_length; i++)

            sps->offset_for_ref_frame[i] = get_se_golomb(gb);

    } else if (sps->poc_type != 2) {

        av_log(avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);

        goto fail;

    }

    sps->ref_frame_count = get_ue_golomb_31(gb);

    if (avctx->codec_tag == MKTAG('S', 'M', 'V', '2'))

        sps->ref_frame_count = FFMAX(2, sps->ref_frame_count);

    if (sps->ref_frame_count > MAX_DELAYED_PIC_COUNT) {

        av_log(avctx, AV_LOG_ERROR,

               "too many reference frames %d\n", sps->ref_frame_count);

        goto fail;

    }

    sps->gaps_in_frame_num_allowed_flag = get_bits1(gb);

    sps->mb_width                       = get_ue_golomb(gb) + 1;

    sps->mb_height                      = get_ue_golomb(gb) + 1;

    sps->frame_mbs_only_flag = get_bits1(gb);

    if (sps->mb_height >= INT_MAX / 2) {

        av_log(avctx, AV_LOG_ERROR, "height overflow\n");

        goto fail;

    }

    sps->mb_height *= 2 - sps->frame_mbs_only_flag;

    if (!sps->frame_mbs_only_flag)

        sps->mb_aff = get_bits1(gb);

    else

        sps->mb_aff = 0;

    if ((unsigned)sps->mb_width  >= INT_MAX / 16 ||

        (unsigned)sps->mb_height >= INT_MAX / 16 ||

        av_image_check_size(16 * sps->mb_width,

                            16 * sps->mb_height, 0, avctx)) {

        av_log(avctx, AV_LOG_ERROR, "mb_width/height overflow\n");

        goto fail;

    }

    sps->direct_8x8_inference_flag = get_bits1(gb);

#ifndef ALLOW_INTERLACE

    if (sps->mb_aff)

        av_log(avctx, AV_LOG_ERROR,

               "MBAFF support not included; enable it at compile-time.\n");

#endif

    sps->crop = get_bits1(gb);

    if (sps->crop) {

        unsigned int crop_left   = get_ue_golomb(gb);

        unsigned int crop_right  = get_ue_golomb(gb);

        unsigned int crop_top    = get_ue_golomb(gb);

        unsigned int crop_bottom = get_ue_golomb(gb);

        int width  = 16 * sps->mb_width;

        int height = 16 * sps->mb_height;

        if (avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {

            av_log(avctx, AV_LOG_DEBUG, "discarding sps cropping, original "

                                           "values are l:%d r:%d t:%d b:%d\n",

                   crop_left, crop_right, crop_top, crop_bottom);

            sps->crop_left   =

            sps->crop_right  =

            sps->crop_top    =

            sps->crop_bottom = 0;

        } else {

            int vsub   = (sps->chroma_format_idc == 1) ? 1 : 0;

            int hsub   = (sps->chroma_format_idc == 1 ||

                          sps->chroma_format_idc == 2) ? 1 : 0;

            int step_x = 1 << hsub;

            int step_y = (2 - sps->frame_mbs_only_flag) << vsub;

            if (crop_left & (0x1F >> (sps->bit_depth_luma > 8)) &&

                !(avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {

                crop_left &= ~(0x1F >> (sps->bit_depth_luma > 8));

                av_log(avctx, AV_LOG_WARNING,

                       "Reducing left cropping to %d "

                       "chroma samples to preserve alignment.\n",

                       crop_left);

            }

            if (crop_left  > (unsigned)INT_MAX / 4 / step_x ||

                crop_right > (unsigned)INT_MAX / 4 / step_x ||

                crop_top   > (unsigned)INT_MAX / 4 / step_y ||

                crop_bottom> (unsigned)INT_MAX / 4 / step_y ||

                (crop_left + crop_right ) * step_x >= width ||

                (crop_top  + crop_bottom) * step_y >= height

            ) {

                av_log(avctx, AV_LOG_ERROR, "crop values invalid %d %d %d %d / %d %d\n", crop_left, crop_right, crop_top, crop_bottom, width, height);

                goto fail;

            }

            sps->crop_left   = crop_left   * step_x;

            sps->crop_right  = crop_right  * step_x;

            sps->crop_top    = crop_top    * step_y;

            sps->crop_bottom = crop_bottom * step_y;

        }

    } else {

        sps->crop_left   =

        sps->crop_right  =

        sps->crop_top    =

        sps->crop_bottom =

        sps->crop        = 0;

    }

    sps->vui_parameters_present_flag = get_bits1(gb);

    if (sps->vui_parameters_present_flag) {

        int ret = decode_vui_parameters(gb, avctx, sps);

        if (ret < 0)

            goto fail;

    }

    if (get_bits_left(gb) < 0) {

        av_log(avctx, ignore_truncation ? AV_LOG_WARNING : AV_LOG_ERROR,

               "Overread %s by %d bits\n", sps->vui_parameters_present_flag ? "VUI" : "SPS", -get_bits_left(gb));

        if (!ignore_truncation)

            goto fail;

    }

    /* if the maximum delay is not stored in the SPS, derive it based on the

     * level */

    if (!sps->bitstream_restriction_flag &&

        (sps->ref_frame_count || avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT)) {

        sps->num_reorder_frames = MAX_DELAYED_PIC_COUNT - 1;

        for (i = 0; i < FF_ARRAY_ELEMS(level_max_dpb_mbs); i++) {

            if (level_max_dpb_mbs[i][0] == sps->level_idc) {

                sps->num_reorder_frames = FFMIN(level_max_dpb_mbs[i][1] / (sps->mb_width * sps->mb_height),

                                                sps->num_reorder_frames);

                break;

            }

        }

    }

    if (!sps->sar.den)

        sps->sar.den = 1;

    if (avctx->debug & FF_DEBUG_PICT_INFO) {

        static const char csp[4][5] = { "Gray", "420", "422", "444" };

        av_log(avctx, AV_LOG_DEBUG,

               "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%u/%u/%u/%u %s %s %"PRId32"/%"PRId32" b%d reo:%d\n",

               sps_id, sps->profile_idc, sps->level_idc,

               sps->poc_type,

               sps->ref_frame_count,

               sps->mb_width, sps->mb_height,

               sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),

               sps->direct_8x8_inference_flag ? "8B8" : "",

               sps->crop_left, sps->crop_right,

               sps->crop_top, sps->crop_bottom,

               sps->vui_parameters_present_flag ? "VUI" : "",

               csp[sps->chroma_format_idc],

               sps->timing_info_present_flag ? sps->num_units_in_tick : 0,

               sps->timing_info_present_flag ? sps->time_scale : 0,

               sps->bit_depth_luma,

               sps->bitstream_restriction_flag ? sps->num_reorder_frames : -1

               );

    }

    /* check if this is a repeat of an already parsed SPS, then keep the

     * original one.

     * otherwise drop all PPSes that depend on it */

    if (ps->sps_list[sps_id] &&

        !memcmp(ps->sps_list[sps_id]->data, sps_buf->data, sps_buf->size)) {

        av_buffer_unref(&sps_buf);

    } else {

        remove_sps(ps, sps_id);

        ps->sps_list[sps_id] = sps_buf;

    }

    return 0;

fail:

    av_buffer_unref(&sps_buf);

    return AVERROR_INVALIDDATA;

}


static int vhost_user_start(VhostUserState *s)

{

    VhostNetOptions options;

    if (vhost_user_running(s)) {

        return 0;

    }

    options.backend_type = VHOST_BACKEND_TYPE_USER;

    options.net_backend = &s->nc;

    options.opaque = s->chr;

    options.force = true;

    s->vhost_net = vhost_net_init(&options);

    return vhost_user_running(s) ? 0 : -1;

}


FWCfgState *fw_cfg_init_mem_wide(hwaddr ctl_addr,

                                 hwaddr data_addr, uint32_t data_width,

                                 hwaddr dma_addr, AddressSpace *dma_as)

{

    DeviceState *dev;

    SysBusDevice *sbd;

    FWCfgState *s;

    bool dma_requested = dma_addr && dma_as;

    dev = qdev_create(NULL, TYPE_FW_CFG_MEM);

    qdev_prop_set_uint32(dev, "data_width", data_width);

    if (!dma_requested) {

        qdev_prop_set_bit(dev, "dma_enabled", false);

    }

    fw_cfg_init1(dev);

    sbd = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(sbd, 0, ctl_addr);

    sysbus_mmio_map(sbd, 1, data_addr);

    s = FW_CFG(dev);

    if (s->dma_enabled) {

        s->dma_as = dma_as;

        s->dma_addr = 0;

        sysbus_mmio_map(sbd, 2, dma_addr);

    }

    return s;

}


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

{

    uint32_t datalen = len;

    const char *serverout;

    unsigned int serveroutlen;

    int err;

    char *clientdata = NULL;

    /* NB, distinction of NULL vs "" is *critical* in SASL */

    if (datalen) {

        clientdata = (char*)data;

        clientdata[datalen-1] = '\0'; /* Wire includes '\0', but make sure */

        datalen--; /* Don't count NULL byte when passing to _start() */

    }

    VNC_DEBUG("Step using SASL Data %p (%d bytes)\n",

              clientdata, datalen);

    err = sasl_server_step(vs->sasl.conn,

                           clientdata,

                           datalen,

                           &serverout,

                           &serveroutlen);

    if (err != SASL_OK &&

        err != SASL_CONTINUE) {

        VNC_DEBUG("sasl step failed %d (%s)\n",

                  err, sasl_errdetail(vs->sasl.conn));

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    if (serveroutlen > SASL_DATA_MAX_LEN) {

        VNC_DEBUG("sasl step reply data too long %d\n",

                  serveroutlen);

        sasl_dispose(&vs->sasl.conn);

        vs->sasl.conn = NULL;

        goto authabort;

    }

    VNC_DEBUG("SASL return data %d bytes, nil; %d\n",

              serveroutlen, serverout ? 0 : 1);

    if (serveroutlen) {

        vnc_write_u32(vs, serveroutlen + 1);

        vnc_write(vs, serverout, serveroutlen + 1);

    } else {

        vnc_write_u32(vs, 0);

    }

    /* Whether auth is complete */

    vnc_write_u8(vs, err == SASL_CONTINUE ? 0 : 1);

    if (err == SASL_CONTINUE) {

        VNC_DEBUG("%s", "Authentication must continue\n");

        /* Wait for step length */

        vnc_read_when(vs, protocol_client_auth_sasl_step_len, 4);

    } else {

        if (!vnc_auth_sasl_check_ssf(vs)) {

            VNC_DEBUG("Authentication rejected for weak SSF %p\n", vs->ioc);

            goto authreject;

        }

        /* Check username whitelist ACL */

        if (vnc_auth_sasl_check_access(vs) < 0) {

            VNC_DEBUG("Authentication rejected for ACL %p\n", vs->ioc);

            goto authreject;

        }

        VNC_DEBUG("Authentication successful %p\n", vs->ioc);

        vnc_write_u32(vs, 0); /* Accept auth */

        /*

         * Delay writing in SSF encoded mode until pending output

         * buffer is written

         */

        if (vs->sasl.runSSF)

            vs->sasl.waitWriteSSF = vs->output.offset;

        start_client_init(vs);

    }

    return 0;

 authreject:

    vnc_write_u32(vs, 1); /* Reject auth */

    vnc_write_u32(vs, sizeof("Authentication failed"));

    vnc_write(vs, "Authentication failed", sizeof("Authentication failed"));

    vnc_flush(vs);

    vnc_client_error(vs);

    return -1;

 authabort:

    vnc_client_error(vs);

    return -1;

}


static void sdl_switch(DisplayChangeListener *dcl,

                       DisplaySurface *new_surface)

{

    PixelFormat pf = qemu_pixelformat_from_pixman(new_surface->format);

    /* temporary hack: allows to call sdl_switch to handle scaling changes */

    if (new_surface) {

        surface = new_surface;

    }

    if (!scaling_active) {

        do_sdl_resize(surface_width(surface), surface_height(surface), 0);

    } else if (real_screen->format->BitsPerPixel !=

               surface_bits_per_pixel(surface)) {

        do_sdl_resize(real_screen->w, real_screen->h,

                      surface_bits_per_pixel(surface));

    }

    if (guest_screen != NULL) {

        SDL_FreeSurface(guest_screen);

    }

#ifdef DEBUG_SDL

    printf("SDL: Creating surface with masks: %08x %08x %08x %08x\n",

           pf.rmask, pf.gmask, pf.bmask, pf.amask);

#endif

    guest_screen = SDL_CreateRGBSurfaceFrom

        (surface_data(surface),

         surface_width(surface), surface_height(surface),

         surface_bits_per_pixel(surface), surface_stride(surface),

         pf.rmask, pf.gmask,

         pf.bmask, pf.amask);

}


static inline uint16_t mipsdsp_sat16_sub(int16_t a, int16_t b,

                                         CPUMIPSState *env)

{

    int16_t  temp;

    temp = a - b;

    if (MIPSDSP_OVERFLOW(a, -b, temp, 0x8000)) {

        if (a > 0) {

            temp = 0x7FFF;

        } else {

            temp = 0x8000;

        }

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return temp;

}


void vhost_net_ack_features(struct vhost_net *net, unsigned features)

{

    vhost_ack_features(&net->dev, vhost_net_get_feature_bits(net), features);

}


void scsi_req_unref(SCSIRequest *req)

{

    assert(req->refcount > 0);

    if (--req->refcount == 0) {

        BusState *qbus = req->dev->qdev.parent_bus;

        SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, qbus);

        if (bus->info->free_request && req->hba_private) {

            bus->info->free_request(bus, req->hba_private);

        }

        if (req->ops->free_req) {

            req->ops->free_req(req);

        }

        object_unref(OBJECT(req->dev));

        object_unref(OBJECT(qbus->parent));

        g_free(req);

    }

}


static void gen_tlbwe_440(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    switch (rB(ctx->opcode)) {

    case 0:

    case 1:

    case 2:

        {

            TCGv_i32 t0 = tcg_const_i32(rB(ctx->opcode));

            gen_helper_440_tlbwe(cpu_env, t0, cpu_gpr[rA(ctx->opcode)],

                                 cpu_gpr[rS(ctx->opcode)]);

            tcg_temp_free_i32(t0);

        }

        break;

    default:

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

        break;

    }

#endif

}


static void tcg_out_tlb_check (TCGContext *s, int r0, int r1, int r2,

                               int addr_reg, int addr_reg2, int s_bits,

                               int offset1, int offset2, uint8_t **label_ptr)

{

    uint16_t retranst;

    tcg_out32 (s, (RLWINM

                   | RA (r0)

                   | RS (addr_reg)

                   | SH (32 - (TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS))

                   | MB (32 - (CPU_TLB_BITS + CPU_TLB_ENTRY_BITS))

                   | ME (31 - CPU_TLB_ENTRY_BITS)

                   )

        );

    tcg_out32 (s, ADD | RT (r0) | RA (r0) | RB (TCG_AREG0));

    tcg_out32 (s, (LWZU

                   | RT (r1)

                   | RA (r0)

                   | offset1

                   )

        );

    tcg_out32 (s, (RLWINM

                   | RA (r2)

                   | RS (addr_reg)

                   | SH (0)

                   | MB ((32 - s_bits) & 31)

                   | ME (31 - TARGET_PAGE_BITS)

                   )

        );

    tcg_out32 (s, CMP | BF (7) | RA (r2) | RB (r1));

#if TARGET_LONG_BITS == 64

    tcg_out32 (s, LWZ | RT (r1) | RA (r0) | 4);

    tcg_out32 (s, CMP | BF (6) | RA (addr_reg2) | RB (r1));

    tcg_out32 (s, CRAND | BT (7, CR_EQ) | BA (6, CR_EQ) | BB (7, CR_EQ));

#endif

    /* Use a conditional branch-and-link so that we load a pointer to

       somewhere within the current opcode, for passing on to the helper.

       This address cannot be used for a tail call, but it's shorter

       than forming an address from scratch.  */

    *label_ptr = s->code_ptr;

    retranst = ((uint16_t *) s->code_ptr)[1] & ~3;

    tcg_out32(s, BC | BI(7, CR_EQ) | retranst | BO_COND_FALSE | LK);

    /* r0 now contains &env->tlb_table[mem_index][index].addr_x */

    tcg_out32 (s, (LWZ

                   | RT (r0)

                   | RA (r0)

                   | offset2

                   )

        );

    /* r0 = env->tlb_table[mem_index][index].addend */

    tcg_out32 (s, ADD | RT (r0) | RA (r0) | RB (addr_reg));

    /* r0 = env->tlb_table[mem_index][index].addend + addr */

}


rgb48funcs(rgb, LE, PIX_FMT_RGB48LE)

rgb48funcs(rgb, BE, PIX_FMT_RGB48BE)

rgb48funcs(bgr, LE, PIX_FMT_BGR48LE)

rgb48funcs(bgr, BE, PIX_FMT_BGR48BE)

#define input_pixel(i) ((origin == PIX_FMT_RGBA || origin == PIX_FMT_BGRA || \

                         origin == PIX_FMT_ARGB || origin == PIX_FMT_ABGR) ? AV_RN32A(&src[(i)*4]) : \

                        (isBE(origin) ? AV_RB16(&src[(i)*2]) : AV_RL16(&src[(i)*2])))

static av_always_inline void

rgb16_32ToY_c_template(uint8_t *dst, const uint8_t *src,

                       int width, enum PixelFormat origin,

                       int shr,   int shg,   int shb, int shp,

                       int maskr, int maskg, int maskb,

                       int rsh,   int gsh,   int bsh, int S)

{

    const int ry = RY << rsh, gy = GY << gsh, by = BY << bsh,

              rnd = 33 << (S - 1);

    int i;

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

        int px = input_pixel(i) >> shp;

        int b = (px & maskb) >> shb;

        int g = (px & maskg) >> shg;

        int r = (px & maskr) >> shr;

        dst[i] = (ry * r + gy * g + by * b + rnd) >> S;

    }

}


static void patch_reloc(tcg_insn_unit *code_ptr, int type,

                        intptr_t value, intptr_t addend)

{

    tcg_insn_unit *target;

    tcg_insn_unit old;

    value += addend;

    target = (tcg_insn_unit *)value;

    switch (type) {

    case R_PPC_REL14:

        reloc_pc14(code_ptr, target);

        break;

    case R_PPC_REL24:

        reloc_pc24(code_ptr, target);

        break;

    case R_PPC_ADDR16:

        assert(value == (int16_t)value);

        old = *code_ptr;

        old = deposit32(old, 0, 16, value);

        *code_ptr = old;

        break;

    default:

        tcg_abort();

    }

}


static int decode_scalefactors(AACContext *ac, float sf[120], GetBitContext *gb,

                               unsigned int global_gain,

                               IndividualChannelStream *ics,

                               enum BandType band_type[120],

                               int band_type_run_end[120])

{

    int g, i, idx = 0;

    int offset[3] = { global_gain, global_gain - 90, 0 };

    int clipped_offset;

    int noise_flag = 1;

    static const char *const sf_str[3] = { "Global gain", "Noise gain", "Intensity stereo position" };

    for (g = 0; g < ics->num_window_groups; g++) {

        for (i = 0; i < ics->max_sfb;) {

            int run_end = band_type_run_end[idx];

            if (band_type[idx] == ZERO_BT) {

                for (; i < run_end; i++, idx++)

                    sf[idx] = 0.;

            } else if ((band_type[idx] == INTENSITY_BT) || (band_type[idx] == INTENSITY_BT2)) {

                for (; i < run_end; i++, idx++) {

                    offset[2] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;

                    clipped_offset = av_clip(offset[2], -155, 100);

                    if (offset[2] != clipped_offset) {

                        av_log_ask_for_sample(ac->avctx, "Intensity stereo "

                                "position clipped (%d -> %d).\nIf you heard an "

                                "audible artifact, there may be a bug in the "

                                "decoder. ", offset[2], clipped_offset);

                    }

                    sf[idx] = ff_aac_pow2sf_tab[-clipped_offset + POW_SF2_ZERO];

                }

            } else if (band_type[idx] == NOISE_BT) {

                for (; i < run_end; i++, idx++) {

                    if (noise_flag-- > 0)

                        offset[1] += get_bits(gb, 9) - 256;

                    else

                        offset[1] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;

                    clipped_offset = av_clip(offset[1], -100, 155);

                    if (offset[1] != clipped_offset) {

                        av_log_ask_for_sample(ac->avctx, "Noise gain clipped "

                                "(%d -> %d).\nIf you heard an audible "

                                "artifact, there may be a bug in the decoder. ",

                                offset[1], clipped_offset);

                    }

                    sf[idx] = -ff_aac_pow2sf_tab[clipped_offset + POW_SF2_ZERO];

                }

            } else {

                for (; i < run_end; i++, idx++) {

                    offset[0] += get_vlc2(gb, vlc_scalefactors.table, 7, 3) - 60;

                    if (offset[0] > 255U) {

                        av_log(ac->avctx, AV_LOG_ERROR,

                               "%s (%d) out of range.\n", sf_str[0], offset[0]);

                        return -1;

                    }

                    sf[idx] = -ff_aac_pow2sf_tab[offset[0] - 100 + POW_SF2_ZERO];

                }

            }

        }

    }

    return 0;

}


void qdev_init_gpio_out_named(DeviceState *dev, qemu_irq *pins,
                              const char *name, int n)
{
    NamedGPIOList *gpio_list = qdev_get_named_gpio_list(dev, name);
    assert(gpio_list->num_in == 0 || !name);
    assert(gpio_list->num_out == 0);
    gpio_list->num_out = n;
    gpio_list->out = pins;


static av_always_inline int check_block(SnowContext *s, int mb_x, int mb_y, int p[3], int intra, const uint8_t *obmc_edged, int *best_rd){

    const int b_stride= s->b_width << s->block_max_depth;

    BlockNode *block= &s->block[mb_x + mb_y * b_stride];

    BlockNode backup= *block;

    int rd, index, value;

    assert(mb_x>=0 && mb_y>=0);

    assert(mb_x<b_stride);

    if(intra){

        block->color[0] = p[0];

        block->color[1] = p[1];

        block->color[2] = p[2];

        block->type |= BLOCK_INTRA;

    }else{

        index= (p[0] + 31*p[1]) & (ME_CACHE_SIZE-1);

        value= s->me_cache_generation + (p[0]>>10) + (p[1]<<6) + (block->ref<<12);

        if(s->me_cache[index] == value)

            return 0;

        s->me_cache[index]= value;

        block->mx= p[0];

        block->my= p[1];

        block->type &= ~BLOCK_INTRA;

    }

    rd= get_block_rd(s, mb_x, mb_y, 0, obmc_edged);

//FIXME chroma

    if(rd < *best_rd){

        *best_rd= rd;

        return 1;

    }else{

        *block= backup;

        return 0;

    }

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    static int counter = 0;

    int i;

    init_get_bits(&gb, buf, buf_size * 8);

    if (s->theora && get_bits1(&gb))

    {

#if 1

        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");

#else

        int ptype = get_bits(&gb, 7);

        skip_bits(&gb, 6*8); /* "theora" */

        switch(ptype)

        {

            case 1:

                theora_decode_comments(avctx, &gb);

                break;

            case 2:

                theora_decode_tables(avctx, &gb);

                    init_dequantizer(s);

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype);

        return buf_size;

#endif

    s->keyframe = !get_bits1(&gb);

    if (!s->theora)

        skip_bits(&gb, 1);

    s->last_quality_index = s->quality_index;

    s->nqis=0;

    do{

        s->qis[s->nqis++]= get_bits(&gb, 6);

    } while(s->theora >= 0x030200 && s->nqis<3 && get_bits1(&gb));

    s->quality_index= s->qis[0];

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",

            s->keyframe?"key":"", counter, s->quality_index);

    counter++;

    if (s->quality_index != s->last_quality_index) {

        init_dequantizer(s);

        init_loop_filter(s);

    if (s->keyframe) {

        if (!s->theora)

        {

            skip_bits(&gb, 4); /* width code */

            skip_bits(&gb, 4); /* height code */

            if (s->version)

            {

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

                if (counter == 1)

                    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);

        if (s->version || s->theora)

        {

                if (get_bits1(&gb))

                    av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");

            skip_bits(&gb, 2); /* reserved? */

        if (s->last_frame.data[0] == s->golden_frame.data[0]) {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */

        } else {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            if (s->last_frame.data[0])

                avctx->release_buffer(avctx, &s->last_frame);

        s->golden_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

        /* golden frame is also the current frame */

        s->current_frame= s->golden_frame;

        /* time to figure out pixel addresses? */

        if (!s->pixel_addresses_inited)

        {

            if (!s->flipped_image)

                vp3_calculate_pixel_addresses(s);

            else

                theora_calculate_pixel_addresses(s);

    } else {

        /* allocate a new current frame */

        s->current_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->current_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame

    s->current_frame.qstride= 0;

    {START_TIMER

    init_frame(s, &gb);

    STOP_TIMER("init_frame")}

#if KEYFRAMES_ONLY

if (!s->keyframe) {

    memcpy(s->current_frame.data[0], s->golden_frame.data[0],

        s->current_frame.linesize[0] * s->height);

    memcpy(s->current_frame.data[1], s->golden_frame.data[1],

        s->current_frame.linesize[1] * s->height / 2);

    memcpy(s->current_frame.data[2], s->golden_frame.data[2],

        s->current_frame.linesize[2] * s->height / 2);

} else {

#endif

    {START_TIMER

    if (unpack_superblocks(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");

    STOP_TIMER("unpack_superblocks")}

    {START_TIMER

    if (unpack_modes(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");

    STOP_TIMER("unpack_modes")}

    {START_TIMER

    if (unpack_vectors(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");

    STOP_TIMER("unpack_vectors")}

    {START_TIMER

    if (unpack_dct_coeffs(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");

    STOP_TIMER("unpack_dct_coeffs")}

    {START_TIMER

    reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);

    if ((avctx->flags & CODEC_FLAG_GRAY) == 0) {

        reverse_dc_prediction(s, s->fragment_start[1],

            s->fragment_width / 2, s->fragment_height / 2);

        reverse_dc_prediction(s, s->fragment_start[2],

            s->fragment_width / 2, s->fragment_height / 2);

    STOP_TIMER("reverse_dc_prediction")}

    {START_TIMER

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

        render_slice(s, i);

    STOP_TIMER("render_fragments")}

    {START_TIMER

    apply_loop_filter(s);

    STOP_TIMER("apply_loop_filter")}

#if KEYFRAMES_ONLY

#endif

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data= s->current_frame;

    /* release the last frame, if it is allocated and if it is not the

     * golden frame */

    if ((s->last_frame.data[0]) &&

        (s->last_frame.data[0] != s->golden_frame.data[0]))

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames (last = current) */

    s->last_frame= s->current_frame;

    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */

    return buf_size;


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

                   int srcStride[], int srcSliceY,

                   int srcSliceH, uint8_t* dst[], int dstStride[])

{

    /* load a few things into local vars to make the code more readable? and faster */

    const int srcW= c->srcW;

    const int dstW= c->dstW;

    const int dstH= c->dstH;

    const int chrDstW= c->chrDstW;

    const int chrSrcW= c->chrSrcW;

    const int lumXInc= c->lumXInc;

    const int chrXInc= c->chrXInc;

    const enum PixelFormat dstFormat= c->dstFormat;

    const int flags= c->flags;

    int16_t *vLumFilterPos= c->vLumFilterPos;

    int16_t *vChrFilterPos= c->vChrFilterPos;

    int16_t *hLumFilterPos= c->hLumFilterPos;

    int16_t *hChrFilterPos= c->hChrFilterPos;

    int16_t *vLumFilter= c->vLumFilter;

    int16_t *vChrFilter= c->vChrFilter;

    int16_t *hLumFilter= c->hLumFilter;

    int16_t *hChrFilter= c->hChrFilter;

    int32_t *lumMmxFilter= c->lumMmxFilter;

    int32_t *chrMmxFilter= c->chrMmxFilter;

    const int vLumFilterSize= c->vLumFilterSize;

    const int vChrFilterSize= c->vChrFilterSize;

    const int hLumFilterSize= c->hLumFilterSize;

    const int hChrFilterSize= c->hChrFilterSize;

    int16_t **lumPixBuf= c->lumPixBuf;

    int16_t **chrUPixBuf= c->chrUPixBuf;

    int16_t **chrVPixBuf= c->chrVPixBuf;

    int16_t **alpPixBuf= c->alpPixBuf;

    const int vLumBufSize= c->vLumBufSize;

    const int vChrBufSize= c->vChrBufSize;

    uint8_t *formatConvBuffer= c->formatConvBuffer;

    const int chrSrcSliceY= srcSliceY >> c->chrSrcVSubSample;

    const int chrSrcSliceH= -((-srcSliceH) >> c->chrSrcVSubSample);

    int lastDstY;

    uint32_t *pal=c->pal_yuv;

    yuv2planar1_fn yuv2plane1 = c->yuv2plane1;

    yuv2planarX_fn yuv2planeX = c->yuv2planeX;

    yuv2interleavedX_fn yuv2nv12cX = c->yuv2nv12cX;

    yuv2packed1_fn yuv2packed1 = c->yuv2packed1;

    yuv2packed2_fn yuv2packed2 = c->yuv2packed2;

    yuv2packedX_fn yuv2packedX = c->yuv2packedX;

    int should_dither = is9_OR_10BPS(c->srcFormat) || is16BPS(c->srcFormat);

    /* vars which will change and which we need to store back in the context */

    int dstY= c->dstY;

    int lumBufIndex= c->lumBufIndex;

    int chrBufIndex= c->chrBufIndex;

    int lastInLumBuf= c->lastInLumBuf;

    int lastInChrBuf= c->lastInChrBuf;

    if (isPacked(c->srcFormat)) {

        src[0]=

        src[1]=

        src[2]=

        src[3]= src[0];

        srcStride[0]=

        srcStride[1]=

        srcStride[2]=

        srcStride[3]= srcStride[0];

    }

    srcStride[1]<<= c->vChrDrop;

    srcStride[2]<<= c->vChrDrop;

    DEBUG_BUFFERS("swScale() %p[%d] %p[%d] %p[%d] %p[%d] -> %p[%d] %p[%d] %p[%d] %p[%d]\n",

                  src[0], srcStride[0], src[1], srcStride[1], src[2], srcStride[2], src[3], srcStride[3],

                  dst[0], dstStride[0], dst[1], dstStride[1], dst[2], dstStride[2], dst[3], dstStride[3]);

    DEBUG_BUFFERS("srcSliceY: %d srcSliceH: %d dstY: %d dstH: %d\n",

                   srcSliceY,    srcSliceH,    dstY,    dstH);

    DEBUG_BUFFERS("vLumFilterSize: %d vLumBufSize: %d vChrFilterSize: %d vChrBufSize: %d\n",

                   vLumFilterSize,    vLumBufSize,    vChrFilterSize,    vChrBufSize);

    if (dstStride[0]%8 !=0 || dstStride[1]%8 !=0 || dstStride[2]%8 !=0 || dstStride[3]%8 != 0) {

        static int warnedAlready=0; //FIXME move this into the context perhaps

        if (flags & SWS_PRINT_INFO && !warnedAlready) {

            av_log(c, AV_LOG_WARNING, "Warning: dstStride is not aligned!\n"

                   "         ->cannot do aligned memory accesses anymore\n");

            warnedAlready=1;

        }

    }

    /* Note the user might start scaling the picture in the middle so this

       will not get executed. This is not really intended but works

       currently, so people might do it. */

    if (srcSliceY ==0) {

        lumBufIndex=-1;

        chrBufIndex=-1;

        dstY=0;

        lastInLumBuf= -1;

        lastInChrBuf= -1;

    }

    if (!should_dither) {

        c->chrDither8 = c->lumDither8 = ff_sws_pb_64;

    }

    lastDstY= dstY;

    for (;dstY < dstH; dstY++) {

        const int chrDstY= dstY>>c->chrDstVSubSample;

        uint8_t *dest[4] = {

            dst[0] + dstStride[0] * dstY,

            dst[1] + dstStride[1] * chrDstY,

            dst[2] + dstStride[2] * chrDstY,

            (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? dst[3] + dstStride[3] * dstY : NULL,

        };

        const int firstLumSrcY= FFMAX(1 - vLumFilterSize, vLumFilterPos[dstY]); //First line needed as input

        const int firstLumSrcY2= FFMAX(1 - vLumFilterSize, vLumFilterPos[FFMIN(dstY | ((1<<c->chrDstVSubSample) - 1), dstH-1)]);

        const int firstChrSrcY= FFMAX(1 - vChrFilterSize, vChrFilterPos[chrDstY]); //First line needed as input

        // Last line needed as input

        int lastLumSrcY  = FFMIN(c->srcH,    firstLumSrcY  + vLumFilterSize) - 1;

        int lastLumSrcY2 = FFMIN(c->srcH,    firstLumSrcY2 + vLumFilterSize) - 1;

        int lastChrSrcY  = FFMIN(c->chrSrcH, firstChrSrcY  + vChrFilterSize) - 1;

        int enough_lines;

        //handle holes (FAST_BILINEAR & weird filters)

        if (firstLumSrcY > lastInLumBuf) lastInLumBuf= firstLumSrcY-1;

        if (firstChrSrcY > lastInChrBuf) lastInChrBuf= firstChrSrcY-1;

        assert(firstLumSrcY >= lastInLumBuf - vLumBufSize + 1);

        assert(firstChrSrcY >= lastInChrBuf - vChrBufSize + 1);

        DEBUG_BUFFERS("dstY: %d\n", dstY);

        DEBUG_BUFFERS("\tfirstLumSrcY: %d lastLumSrcY: %d lastInLumBuf: %d\n",

                         firstLumSrcY,    lastLumSrcY,    lastInLumBuf);

        DEBUG_BUFFERS("\tfirstChrSrcY: %d lastChrSrcY: %d lastInChrBuf: %d\n",

                         firstChrSrcY,    lastChrSrcY,    lastInChrBuf);

        // Do we have enough lines in this slice to output the dstY line

        enough_lines = lastLumSrcY2 < srcSliceY + srcSliceH && lastChrSrcY < -((-srcSliceY - srcSliceH)>>c->chrSrcVSubSample);

        if (!enough_lines) {

            lastLumSrcY = srcSliceY + srcSliceH - 1;

            lastChrSrcY = chrSrcSliceY + chrSrcSliceH - 1;

            DEBUG_BUFFERS("buffering slice: lastLumSrcY %d lastChrSrcY %d\n",

                                            lastLumSrcY, lastChrSrcY);

        }

        //Do horizontal scaling

        while(lastInLumBuf < lastLumSrcY) {

            const uint8_t *src1[4] = {

                src[0] + (lastInLumBuf + 1 - srcSliceY) * srcStride[0],

                src[1] + (lastInLumBuf + 1 - srcSliceY) * srcStride[1],

                src[2] + (lastInLumBuf + 1 - srcSliceY) * srcStride[2],

                src[3] + (lastInLumBuf + 1 - srcSliceY) * srcStride[3],

            };

            lumBufIndex++;

            assert(lumBufIndex < 2*vLumBufSize);

            assert(lastInLumBuf + 1 - srcSliceY < srcSliceH);

            assert(lastInLumBuf + 1 - srcSliceY >= 0);

            hyscale(c, lumPixBuf[ lumBufIndex ], dstW, src1, srcW, lumXInc,

                    hLumFilter, hLumFilterPos, hLumFilterSize,

                    formatConvBuffer,

                    pal, 0);

            if (CONFIG_SWSCALE_ALPHA && alpPixBuf)

                hyscale(c, alpPixBuf[ lumBufIndex ], dstW, src1, srcW,

                        lumXInc, hLumFilter, hLumFilterPos, hLumFilterSize,

                        formatConvBuffer,

                        pal, 1);

            lastInLumBuf++;

            DEBUG_BUFFERS("\t\tlumBufIndex %d: lastInLumBuf: %d\n",

                               lumBufIndex,    lastInLumBuf);

        }

        while(lastInChrBuf < lastChrSrcY) {

            const uint8_t *src1[4] = {

                src[0] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[0],

                src[1] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[1],

                src[2] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[2],

                src[3] + (lastInChrBuf + 1 - chrSrcSliceY) * srcStride[3],

            };

            chrBufIndex++;

            assert(chrBufIndex < 2*vChrBufSize);

            assert(lastInChrBuf + 1 - chrSrcSliceY < (chrSrcSliceH));

            assert(lastInChrBuf + 1 - chrSrcSliceY >= 0);

            //FIXME replace parameters through context struct (some at least)

            if (c->needs_hcscale)

                hcscale(c, chrUPixBuf[chrBufIndex], chrVPixBuf[chrBufIndex],

                          chrDstW, src1, chrSrcW, chrXInc,

                          hChrFilter, hChrFilterPos, hChrFilterSize,

                          formatConvBuffer, pal);

            lastInChrBuf++;

            DEBUG_BUFFERS("\t\tchrBufIndex %d: lastInChrBuf: %d\n",

                               chrBufIndex,    lastInChrBuf);

        }

        //wrap buf index around to stay inside the ring buffer

        if (lumBufIndex >= vLumBufSize) lumBufIndex-= vLumBufSize;

        if (chrBufIndex >= vChrBufSize) chrBufIndex-= vChrBufSize;

        if (!enough_lines)

            break; //we can't output a dstY line so let's try with the next slice

#if HAVE_MMX

        updateMMXDitherTables(c, dstY, lumBufIndex, chrBufIndex, lastInLumBuf, lastInChrBuf);

#endif

        if (should_dither) {

            c->chrDither8 = dither_8x8_128[chrDstY & 7];

            c->lumDither8 = dither_8x8_128[dstY & 7];

        }

        if (dstY >= dstH-2) {

            // hmm looks like we can't use MMX here without overwriting this array's tail

            ff_sws_init_output_funcs(c, &yuv2plane1, &yuv2planeX,  &yuv2nv12cX,

                                     &yuv2packed1, &yuv2packed2, &yuv2packedX);

        }

        {

            const int16_t **lumSrcPtr= (const int16_t **) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;

            const int16_t **chrUSrcPtr= (const int16_t **) chrUPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

            const int16_t **chrVSrcPtr= (const int16_t **) chrVPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;

            const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;

            if (firstLumSrcY < 0 || firstLumSrcY + vLumFilterSize > c->srcH) {

                const int16_t **tmpY = (const int16_t **) lumPixBuf + 2 * vLumBufSize;

                int neg = -firstLumSrcY, i, end = FFMIN(c->srcH - firstLumSrcY, vLumFilterSize);

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

                    tmpY[i] = lumSrcPtr[neg];

                for (     ; i < end;            i++)

                    tmpY[i] = lumSrcPtr[i];

                for (     ; i < vLumFilterSize; i++)

                    tmpY[i] = tmpY[i-1];

                lumSrcPtr = tmpY;

                if (alpSrcPtr) {

                    const int16_t **tmpA = (const int16_t **) alpPixBuf + 2 * vLumBufSize;

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

                        tmpA[i] = alpSrcPtr[neg];

                    for (     ; i < end;            i++)

                        tmpA[i] = alpSrcPtr[i];

                    for (     ; i < vLumFilterSize; i++)

                        tmpA[i] = tmpA[i - 1];

                    alpSrcPtr = tmpA;

                }

            }

            if (firstChrSrcY < 0 || firstChrSrcY + vChrFilterSize > c->chrSrcH) {

                const int16_t **tmpU = (const int16_t **) chrUPixBuf + 2 * vChrBufSize,

                              **tmpV = (const int16_t **) chrVPixBuf + 2 * vChrBufSize;

                int neg = -firstChrSrcY, i, end = FFMIN(c->chrSrcH - firstChrSrcY, vChrFilterSize);

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

                    tmpU[i] = chrUSrcPtr[neg];

                    tmpV[i] = chrVSrcPtr[neg];

                }

                for (     ; i < end;            i++) {

                    tmpU[i] = chrUSrcPtr[i];

                    tmpV[i] = chrVSrcPtr[i];

                }

                for (     ; i < vChrFilterSize; i++) {

                    tmpU[i] = tmpU[i - 1];

                    tmpV[i] = tmpV[i - 1];

                }

                chrUSrcPtr = tmpU;

                chrVSrcPtr = tmpV;

            }

            if (isPlanarYUV(dstFormat) || (isGray(dstFormat) && !isALPHA(dstFormat))) { //YV12 like

                const int chrSkipMask= (1<<c->chrDstVSubSample)-1;

                if (vLumFilterSize == 1) {

                    yuv2plane1(lumSrcPtr[0], dest[0], dstW, c->lumDither8, 0);

                } else {

                    yuv2planeX(vLumFilter + dstY * vLumFilterSize, vLumFilterSize,

                               lumSrcPtr, dest[0], dstW, c->lumDither8, 0);

                }

                if (!((dstY&chrSkipMask) || isGray(dstFormat))) {

                    if (yuv2nv12cX) {

                        yuv2nv12cX(c, vChrFilter + chrDstY * vChrFilterSize, vChrFilterSize, chrUSrcPtr, chrVSrcPtr, dest[1], chrDstW);

                    } else if (vChrFilterSize == 1) {

                        yuv2plane1(chrUSrcPtr[0], dest[1], chrDstW, c->chrDither8, 0);

                        yuv2plane1(chrVSrcPtr[0], dest[2], chrDstW, c->chrDither8, 3);

                    } else {

                        yuv2planeX(vChrFilter + chrDstY * vChrFilterSize, vChrFilterSize,

                                   chrUSrcPtr, dest[1], chrDstW, c->chrDither8, 0);

                        yuv2planeX(vChrFilter + chrDstY * vChrFilterSize, vChrFilterSize,

                                   chrVSrcPtr, dest[2], chrDstW, c->chrDither8, 3);

                    }

                }

                if (CONFIG_SWSCALE_ALPHA && alpPixBuf){

                    if (vLumFilterSize == 1) {

                        yuv2plane1(alpSrcPtr[0], dest[3], dstW, c->lumDither8, 0);

                    } else {

                        yuv2planeX(vLumFilter + dstY * vLumFilterSize, vLumFilterSize,

                                   alpSrcPtr, dest[3], dstW, c->lumDither8, 0);

                    }

                }

            } else {

                assert(lumSrcPtr  + vLumFilterSize - 1 < lumPixBuf  + vLumBufSize*2);

                assert(chrUSrcPtr + vChrFilterSize - 1 < chrUPixBuf + vChrBufSize*2);

                if (c->yuv2packed1 && vLumFilterSize == 1 && vChrFilterSize <= 2) { //unscaled RGB

                    int chrAlpha = vChrFilterSize == 1 ? 0 : vChrFilter[2 * dstY + 1];

                    yuv2packed1(c, *lumSrcPtr, chrUSrcPtr, chrVSrcPtr,

                                alpPixBuf ? *alpSrcPtr : NULL,

                                dest[0], dstW, chrAlpha, dstY);

                } else if (c->yuv2packed2 && vLumFilterSize == 2 && vChrFilterSize == 2) { //bilinear upscale RGB

                    int lumAlpha = vLumFilter[2 * dstY + 1];

                    int chrAlpha = vChrFilter[2 * dstY + 1];

                    lumMmxFilter[2] =

                    lumMmxFilter[3] = vLumFilter[2 * dstY   ] * 0x10001;

                    chrMmxFilter[2] =

                    chrMmxFilter[3] = vChrFilter[2 * chrDstY] * 0x10001;

                    yuv2packed2(c, lumSrcPtr, chrUSrcPtr, chrVSrcPtr,

                                alpPixBuf ? alpSrcPtr : NULL,

                                dest[0], dstW, lumAlpha, chrAlpha, dstY);

                } else { //general RGB

                    yuv2packedX(c, vLumFilter + dstY * vLumFilterSize,

                                lumSrcPtr, vLumFilterSize,

                                vChrFilter + dstY * vChrFilterSize,

                                chrUSrcPtr, chrVSrcPtr, vChrFilterSize,

                                alpSrcPtr, dest[0], dstW, dstY);

                }

            }

        }

    }

    if (isPlanar(dstFormat) && isALPHA(dstFormat) && !alpPixBuf)

        fillPlane(dst[3], dstStride[3], dstW, dstY-lastDstY, lastDstY, 255);

#if HAVE_MMX2

    if (av_get_cpu_flags() & AV_CPU_FLAG_MMX2)

        __asm__ volatile("sfence":::"memory");

#endif

    emms_c();

    /* store changed local vars back in the context */

    c->dstY= dstY;

    c->lumBufIndex= lumBufIndex;

    c->chrBufIndex= chrBufIndex;

    c->lastInLumBuf= lastInLumBuf;

    c->lastInChrBuf= lastInChrBuf;

    return dstY - lastDstY;

}


void tcg_op_remove(TCGContext *s, TCGOp *op)

{

    int next = op->next;

    int prev = op->prev;

    /* We should never attempt to remove the list terminator.  */

    tcg_debug_assert(op != &s->gen_op_buf[0]);

    s->gen_op_buf[next].prev = prev;

    s->gen_op_buf[prev].next = next;

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

#ifdef CONFIG_PROFILER

    atomic_set(&s->prof.del_op_count, s->prof.del_op_count + 1);

#endif

}


static void avc_luma_midv_qrt_8w_msa(const uint8_t *src, int32_t src_stride,

                                     uint8_t *dst, int32_t dst_stride,

                                     int32_t height, uint8_t ver_offset)

{

    uint32_t loop_cnt;

    v16i8 src0, src1, src2, src3, src4;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, hz_out2, hz_out3;

    v8i16 hz_out4, hz_out5, hz_out6, hz_out7, hz_out8;

    v8i16 dst0, dst1, dst2, dst3, dst4, dst5, dst6, dst7;

    v16u8 out;

    LD_SB3(&luma_mask_arr[0], 16, mask0, mask1, mask2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    hz_out0 = AVC_HORZ_FILTER_SH(src0, mask0, mask1, mask2);

    hz_out1 = AVC_HORZ_FILTER_SH(src1, mask0, mask1, mask2);

    hz_out2 = AVC_HORZ_FILTER_SH(src2, mask0, mask1, mask2);

    hz_out3 = AVC_HORZ_FILTER_SH(src3, mask0, mask1, mask2);

    hz_out4 = AVC_HORZ_FILTER_SH(src4, mask0, mask1, mask2);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src0, src1, src2, src3);

        XORI_B4_128_SB(src0, src1, src2, src3);

        src += (4 * src_stride);

        hz_out5 = AVC_HORZ_FILTER_SH(src0, mask0, mask1, mask2);

        hz_out6 = AVC_HORZ_FILTER_SH(src1, mask0, mask1, mask2);

        hz_out7 = AVC_HORZ_FILTER_SH(src2, mask0, mask1, mask2);

        hz_out8 = AVC_HORZ_FILTER_SH(src3, mask0, mask1, mask2);

        dst0 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out0, hz_out1, hz_out2,

                                               hz_out3, hz_out4, hz_out5);

        dst2 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out1, hz_out2, hz_out3,

                                               hz_out4, hz_out5, hz_out6);

        dst4 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out2, hz_out3, hz_out4,

                                               hz_out5, hz_out6, hz_out7);

        dst6 = AVC_CALC_DPADD_H_6PIX_2COEFF_SH(hz_out3, hz_out4, hz_out5,

                                               hz_out6, hz_out7, hz_out8);

        if (ver_offset) {

            dst1 = __msa_srari_h(hz_out3, 5);

            dst3 = __msa_srari_h(hz_out4, 5);

            dst5 = __msa_srari_h(hz_out5, 5);

            dst7 = __msa_srari_h(hz_out6, 5);

        } else {

            dst1 = __msa_srari_h(hz_out2, 5);

            dst3 = __msa_srari_h(hz_out3, 5);

            dst5 = __msa_srari_h(hz_out4, 5);

            dst7 = __msa_srari_h(hz_out5, 5);

        }

        SAT_SH4_SH(dst1, dst3, dst5, dst7, 7);

        dst0 = __msa_aver_s_h(dst0, dst1);

        dst1 = __msa_aver_s_h(dst2, dst3);

        dst2 = __msa_aver_s_h(dst4, dst5);

        dst3 = __msa_aver_s_h(dst6, dst7);

        out = PCKEV_XORI128_UB(dst0, dst0);

        ST8x1_UB(out, dst);

        dst += dst_stride;

        out = PCKEV_XORI128_UB(dst1, dst1);

        ST8x1_UB(out, dst);

        dst += dst_stride;

        out = PCKEV_XORI128_UB(dst2, dst2);

        ST8x1_UB(out, dst);

        dst += dst_stride;

        out = PCKEV_XORI128_UB(dst3, dst3);

        ST8x1_UB(out, dst);

        dst += dst_stride;

        hz_out0 = hz_out4;

        hz_out1 = hz_out5;

        hz_out2 = hz_out6;

        hz_out3 = hz_out7;

        hz_out4 = hz_out8;

    }

}


static int gif_parse_next_image(GifState *s)

{

    for (;;) {

        int code = bytestream_get_byte(&s->bytestream);

#ifdef DEBUG

        dprintf(s->avctx, "gif: code=%02x '%c'\n", code, code);

#endif

        switch (code) {

        case ',':

            if (gif_read_image(s) < 0)

                return -1;

            return 0;

        case ';':

            /* end of image */

            return -1;

        case '!':

            if (gif_read_extension(s) < 0)

                return -1;

            break;

        default:

            /* error or errneous EOF */

            return -1;

        }

    }

}


static int test_vector_fmul_reverse(AVFloatDSPContext *fdsp, AVFloatDSPContext *cdsp,

                                    const float *v1, const float *v2)

{

    LOCAL_ALIGNED(32, float, cdst, [LEN]);

    LOCAL_ALIGNED(32, float, odst, [LEN]);

    int ret;

    cdsp->vector_fmul_reverse(cdst, v1, v2, LEN);

    fdsp->vector_fmul_reverse(odst, v1, v2, LEN);

    if (ret = compare_floats(cdst, odst, LEN, FLT_EPSILON))

        av_log(NULL, AV_LOG_ERROR, "vector_fmul_reverse failed\n");

    return ret;

}


static int ipvideo_decode_block_opcode_0x3(IpvideoContext *s)

{

    unsigned char B;

    int x, y;

    /* copy 8x8 block from current frame from an up/left block */

    /* need 1 more byte for motion */

    CHECK_STREAM_PTR(1);

    B = *s->stream_ptr++;

    if (B < 56) {

        x = -(8 + (B % 7));

        y = -(B / 7);

    } else {

        x = -(-14 + ((B - 56) % 29));

        y = -(  8 + ((B - 56) / 29));

    }

    debug_interplay ("    motion byte = %d, (x, y) = (%d, %d)\n", B, x, y);

    return copy_from(s, &s->current_frame, x, y);

}