static bool get_phys_addr_lpae(CPUARMState *env, target_ulong address,

                               MMUAccessType access_type, ARMMMUIdx mmu_idx,

                               hwaddr *phys_ptr, MemTxAttrs *txattrs, int *prot,

                               target_ulong *page_size_ptr,

                               ARMMMUFaultInfo *fi, ARMCacheAttrs *cacheattrs)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    /* Read an LPAE long-descriptor translation table. */

    ARMFaultType fault_type = ARMFault_Translation;

    uint32_t level;

    uint32_t epd = 0;

    int32_t t0sz, t1sz;

    uint32_t tg;

    uint64_t ttbr;

    int ttbr_select;

    hwaddr descaddr, indexmask, indexmask_grainsize;

    uint32_t tableattrs;

    target_ulong page_size;

    uint32_t attrs;

    int32_t stride = 9;

    int32_t addrsize;

    int inputsize;

    int32_t tbi = 0;

    TCR *tcr = regime_tcr(env, mmu_idx);

    int ap, ns, xn, pxn;

    uint32_t el = regime_el(env, mmu_idx);

    bool ttbr1_valid = true;

    uint64_t descaddrmask;

    bool aarch64 = arm_el_is_aa64(env, el);

    /* TODO:

     * This code does not handle the different format TCR for VTCR_EL2.

     * This code also does not support shareability levels.

     * Attribute and permission bit handling should also be checked when adding

     * support for those page table walks.

     */

    if (aarch64) {

        level = 0;

        addrsize = 64;

        if (el > 1) {

            if (mmu_idx != ARMMMUIdx_S2NS) {

                tbi = extract64(tcr->raw_tcr, 20, 1);

            }

        } else {

            if (extract64(address, 55, 1)) {

                tbi = extract64(tcr->raw_tcr, 38, 1);

            } else {

                tbi = extract64(tcr->raw_tcr, 37, 1);

            }

        }

        tbi *= 8;

        /* If we are in 64-bit EL2 or EL3 then there is no TTBR1, so mark it

         * invalid.

         */

        if (el > 1) {

            ttbr1_valid = false;

        }

    } else {

        level = 1;

        addrsize = 32;

        /* There is no TTBR1 for EL2 */

        if (el == 2) {

            ttbr1_valid = false;

        }

    }

    /* Determine whether this address is in the region controlled by

     * TTBR0 or TTBR1 (or if it is in neither region and should fault).

     * This is a Non-secure PL0/1 stage 1 translation, so controlled by

     * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:

     */

    if (aarch64) {

        /* AArch64 translation.  */

        t0sz = extract32(tcr->raw_tcr, 0, 6);

        t0sz = MIN(t0sz, 39);

        t0sz = MAX(t0sz, 16);

    } else if (mmu_idx != ARMMMUIdx_S2NS) {

        /* AArch32 stage 1 translation.  */

        t0sz = extract32(tcr->raw_tcr, 0, 3);

    } else {

        /* AArch32 stage 2 translation.  */

        bool sext = extract32(tcr->raw_tcr, 4, 1);

        bool sign = extract32(tcr->raw_tcr, 3, 1);

        /* Address size is 40-bit for a stage 2 translation,

         * and t0sz can be negative (from -8 to 7),

         * so we need to adjust it to use the TTBR selecting logic below.

         */

        addrsize = 40;

        t0sz = sextract32(tcr->raw_tcr, 0, 4) + 8;

        /* If the sign-extend bit is not the same as t0sz[3], the result

         * is unpredictable. Flag this as a guest error.  */

        if (sign != sext) {

            qemu_log_mask(LOG_GUEST_ERROR,

                          "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");

        }

    }

    t1sz = extract32(tcr->raw_tcr, 16, 6);

    if (aarch64) {

        t1sz = MIN(t1sz, 39);

        t1sz = MAX(t1sz, 16);

    }

    if (t0sz && !extract64(address, addrsize - t0sz, t0sz - tbi)) {

        /* there is a ttbr0 region and we are in it (high bits all zero) */

        ttbr_select = 0;

    } else if (ttbr1_valid && t1sz &&

               !extract64(~address, addrsize - t1sz, t1sz - tbi)) {

        /* there is a ttbr1 region and we are in it (high bits all one) */

        ttbr_select = 1;

    } else if (!t0sz) {

        /* ttbr0 region is "everything not in the ttbr1 region" */

        ttbr_select = 0;

    } else if (!t1sz && ttbr1_valid) {

        /* ttbr1 region is "everything not in the ttbr0 region" */

        ttbr_select = 1;

    } else {

        /* in the gap between the two regions, this is a Translation fault */

        fault_type = ARMFault_Translation;

        goto do_fault;

    }

    /* Note that QEMU ignores shareability and cacheability attributes,

     * so we don't need to do anything with the SH, ORGN, IRGN fields

     * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the

     * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently

     * implement any ASID-like capability so we can ignore it (instead

     * we will always flush the TLB any time the ASID is changed).

     */

    if (ttbr_select == 0) {

        ttbr = regime_ttbr(env, mmu_idx, 0);

        if (el < 2) {

            epd = extract32(tcr->raw_tcr, 7, 1);

        }

        inputsize = addrsize - t0sz;

        tg = extract32(tcr->raw_tcr, 14, 2);

        if (tg == 1) { /* 64KB pages */

            stride = 13;

        }

        if (tg == 2) { /* 16KB pages */

            stride = 11;

        }

    } else {

        /* We should only be here if TTBR1 is valid */

        assert(ttbr1_valid);

        ttbr = regime_ttbr(env, mmu_idx, 1);

        epd = extract32(tcr->raw_tcr, 23, 1);

        inputsize = addrsize - t1sz;

        tg = extract32(tcr->raw_tcr, 30, 2);

        if (tg == 3)  { /* 64KB pages */

            stride = 13;

        }

        if (tg == 1) { /* 16KB pages */

            stride = 11;

        }

    }

    /* Here we should have set up all the parameters for the translation:

     * inputsize, ttbr, epd, stride, tbi

     */

    if (epd) {

        /* Translation table walk disabled => Translation fault on TLB miss

         * Note: This is always 0 on 64-bit EL2 and EL3.

         */

        goto do_fault;

    }

    if (mmu_idx != ARMMMUIdx_S2NS) {

        /* The starting level depends on the virtual address size (which can

         * be up to 48 bits) and the translation granule size. It indicates

         * the number of strides (stride bits at a time) needed to

         * consume the bits of the input address. In the pseudocode this is:

         *  level = 4 - RoundUp((inputsize - grainsize) / stride)

         * where their 'inputsize' is our 'inputsize', 'grainsize' is

         * our 'stride + 3' and 'stride' is our 'stride'.

         * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:

         * = 4 - (inputsize - stride - 3 + stride - 1) / stride

         * = 4 - (inputsize - 4) / stride;

         */

        level = 4 - (inputsize - 4) / stride;

    } else {

        /* For stage 2 translations the starting level is specified by the

         * VTCR_EL2.SL0 field (whose interpretation depends on the page size)

         */

        uint32_t sl0 = extract32(tcr->raw_tcr, 6, 2);

        uint32_t startlevel;

        bool ok;

        if (!aarch64 || stride == 9) {

            /* AArch32 or 4KB pages */

            startlevel = 2 - sl0;

        } else {

            /* 16KB or 64KB pages */

            startlevel = 3 - sl0;

        }

        /* Check that the starting level is valid. */

        ok = check_s2_mmu_setup(cpu, aarch64, startlevel,

                                inputsize, stride);

        if (!ok) {

            fault_type = ARMFault_Translation;

            goto do_fault;

        }

        level = startlevel;

    }

    indexmask_grainsize = (1ULL << (stride + 3)) - 1;

    indexmask = (1ULL << (inputsize - (stride * (4 - level)))) - 1;

    /* Now we can extract the actual base address from the TTBR */

    descaddr = extract64(ttbr, 0, 48);

    descaddr &= ~indexmask;

    /* The address field in the descriptor goes up to bit 39 for ARMv7

     * but up to bit 47 for ARMv8, but we use the descaddrmask

     * up to bit 39 for AArch32, because we don't need other bits in that case

     * to construct next descriptor address (anyway they should be all zeroes).

     */

    descaddrmask = ((1ull << (aarch64 ? 48 : 40)) - 1) &

                   ~indexmask_grainsize;

    /* Secure accesses start with the page table in secure memory and

     * can be downgraded to non-secure at any step. Non-secure accesses

     * remain non-secure. We implement this by just ORing in the NSTable/NS

     * bits at each step.

     */

    tableattrs = regime_is_secure(env, mmu_idx) ? 0 : (1 << 4);

    for (;;) {

        uint64_t descriptor;

        bool nstable;

        descaddr |= (address >> (stride * (4 - level))) & indexmask;

        descaddr &= ~7ULL;

        nstable = extract32(tableattrs, 4, 1);

        descriptor = arm_ldq_ptw(cs, descaddr, !nstable, mmu_idx, fi);

        if (fi->s1ptw) {

            goto do_fault;

        }

        if (!(descriptor & 1) ||

            (!(descriptor & 2) && (level == 3))) {

            /* Invalid, or the Reserved level 3 encoding */

            goto do_fault;

        }

        descaddr = descriptor & descaddrmask;

        if ((descriptor & 2) && (level < 3)) {

            /* Table entry. The top five bits are attributes which  may

             * propagate down through lower levels of the table (and

             * which are all arranged so that 0 means "no effect", so

             * we can gather them up by ORing in the bits at each level).

             */

            tableattrs |= extract64(descriptor, 59, 5);

            level++;

            indexmask = indexmask_grainsize;

            continue;

        }

        /* Block entry at level 1 or 2, or page entry at level 3.

         * These are basically the same thing, although the number

         * of bits we pull in from the vaddr varies.

         */

        page_size = (1ULL << ((stride * (4 - level)) + 3));

        descaddr |= (address & (page_size - 1));

        /* Extract attributes from the descriptor */

        attrs = extract64(descriptor, 2, 10)

            | (extract64(descriptor, 52, 12) << 10);

        if (mmu_idx == ARMMMUIdx_S2NS) {

            /* Stage 2 table descriptors do not include any attribute fields */

            break;

        }

        /* Merge in attributes from table descriptors */

        attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */

        attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */

        /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1

         * means "force PL1 access only", which means forcing AP[1] to 0.

         */

        if (extract32(tableattrs, 2, 1)) {

            attrs &= ~(1 << 4);

        }

        attrs |= nstable << 3; /* NS */

        break;

    }

    /* Here descaddr is the final physical address, and attributes

     * are all in attrs.

     */

    fault_type = ARMFault_AccessFlag;

    if ((attrs & (1 << 8)) == 0) {

        /* Access flag */

        goto do_fault;

    }

    ap = extract32(attrs, 4, 2);

    xn = extract32(attrs, 12, 1);

    if (mmu_idx == ARMMMUIdx_S2NS) {

        ns = true;

        *prot = get_S2prot(env, ap, xn);

    } else {

        ns = extract32(attrs, 3, 1);

        pxn = extract32(attrs, 11, 1);

        *prot = get_S1prot(env, mmu_idx, aarch64, ap, ns, xn, pxn);

    }

    fault_type = ARMFault_Permission;

    if (!(*prot & (1 << access_type))) {

        goto do_fault;

    }

    if (ns) {

        /* The NS bit will (as required by the architecture) have no effect if

         * the CPU doesn't support TZ or this is a non-secure translation

         * regime, because the attribute will already be non-secure.

         */

        txattrs->secure = false;

    }

    if (cacheattrs != NULL) {

        if (mmu_idx == ARMMMUIdx_S2NS) {

            cacheattrs->attrs = convert_stage2_attrs(env,

                                                     extract32(attrs, 0, 4));

        } else {

            /* Index into MAIR registers for cache attributes */

            uint8_t attrindx = extract32(attrs, 0, 3);

            uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];

            assert(attrindx <= 7);

            cacheattrs->attrs = extract64(mair, attrindx * 8, 8);

        }

        cacheattrs->shareability = extract32(attrs, 6, 2);

    }

    *phys_ptr = descaddr;

    *page_size_ptr = page_size;

    return false;

do_fault:

    fi->type = fault_type;

    fi->level = level;

    /* Tag the error as S2 for failed S1 PTW at S2 or ordinary S2.  */

    fi->stage2 = fi->s1ptw || (mmu_idx == ARMMMUIdx_S2NS);

    return true;

}


void cuda_init (int *cuda_mem_index, qemu_irq irq)

{

    struct tm tm;

    CUDAState *s = &cuda_state;

    s->irq = irq;

    s->timers[0].index = 0;

    s->timers[0].timer = qemu_new_timer(vm_clock, cuda_timer1, s);

    s->timers[1].index = 1;

    qemu_get_timedate(&tm, RTC_OFFSET);

    s->tick_offset = mktimegm(&tm);

    s->adb_poll_timer = qemu_new_timer(vm_clock, cuda_adb_poll, s);

    *cuda_mem_index = cpu_register_io_memory(0, cuda_read, cuda_write, s);

    register_savevm("cuda", -1, 1, cuda_save, cuda_load, s);

    qemu_register_reset(cuda_reset, s);

    cuda_reset(s);

}


static void qdict_crumple_test_recursive(void)

{

    QDict *src, *dst, *rule, *vnc, *acl, *listen;

    QObject *res;

    QList *rules;

    src = qdict_new();

    qdict_put(src, "vnc.listen.addr", qstring_from_str("127.0.0.1"));

    qdict_put(src, "vnc.listen.port", qstring_from_str("5901"));

    qdict_put(src, "vnc.acl.rules.0.match", qstring_from_str("fred"));

    qdict_put(src, "vnc.acl.rules.0.policy", qstring_from_str("allow"));

    qdict_put(src, "vnc.acl.rules.1.match", qstring_from_str("bob"));

    qdict_put(src, "vnc.acl.rules.1.policy", qstring_from_str("deny"));

    qdict_put(src, "vnc.acl.default", qstring_from_str("deny"));

    qdict_put(src, "vnc.acl..name", qstring_from_str("acl0"));

    qdict_put(src, "vnc.acl.rule..name", qstring_from_str("acl0"));

    res = qdict_crumple(src, &error_abort);

    g_assert_cmpint(qobject_type(res), ==, QTYPE_QDICT);

    dst = qobject_to_qdict(res);

    g_assert_cmpint(qdict_size(dst), ==, 1);

    vnc = qdict_get_qdict(dst, "vnc");

    g_assert(vnc);

    listen = qdict_get_qdict(vnc, "listen");

    g_assert(listen);

    g_assert_cmpstr("127.0.0.1", ==, qdict_get_str(listen, "addr"));

    g_assert_cmpstr("5901", ==, qdict_get_str(listen, "port"));

    acl = qdict_get_qdict(vnc, "acl");

    g_assert(acl);

    rules = qdict_get_qlist(acl, "rules");

    g_assert(rules);

    g_assert_cmpint(qlist_size(rules), ==, 2);

    rule = qobject_to_qdict(qlist_pop(rules));

    g_assert_cmpint(qdict_size(rule), ==, 2);

    g_assert_cmpstr("fred", ==, qdict_get_str(rule, "match"));

    g_assert_cmpstr("allow", ==, qdict_get_str(rule, "policy"));

    QDECREF(rule);

    rule = qobject_to_qdict(qlist_pop(rules));

    g_assert_cmpint(qdict_size(rule), ==, 2);

    g_assert_cmpstr("bob", ==, qdict_get_str(rule, "match"));

    g_assert_cmpstr("deny", ==, qdict_get_str(rule, "policy"));

    QDECREF(rule);

    /* With recursive crumpling, we should see all names unescaped */

    g_assert_cmpstr("acl0", ==, qdict_get_str(vnc, "acl.name"));

    g_assert_cmpstr("acl0", ==, qdict_get_str(acl, "rule.name"));

    QDECREF(src);

    QDECREF(dst);

}


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

{

    VGACommonState *s = opaque;

    int index;

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

    if (vga_ioport_invalid(s, addr)) {

        return;

    }

#ifdef DEBUG_VGA

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

#endif

    switch(addr) {

    case VGA_ATT_W:

        if (s->ar_flip_flop == 0) {

            val &= 0x3f;

            s->ar_index = val;

        } else {

            index = s->ar_index & 0x1f;

            switch(index) {

            case VGA_ATC_PALETTE0 ... VGA_ATC_PALETTEF:

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

                break;

            case VGA_ATC_MODE:

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

                break;

            case VGA_ATC_OVERSCAN:

                s->ar[index] = val;

                break;

            case VGA_ATC_PLANE_ENABLE:

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

                break;

            case VGA_ATC_PEL:

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

                break;

            case VGA_ATC_COLOR_PAGE:

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

                break;

            default:

                break;

            }

        }

        s->ar_flip_flop ^= 1;

        break;

    case VGA_MIS_W:

        s->msr = val & ~0x10;

        s->update_retrace_info(s);

        break;

    case VGA_SEQ_I:

        s->sr_index = val & 7;

        break;

    case VGA_SEQ_D:

#ifdef DEBUG_VGA_REG

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

#endif

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

        vbe_update_vgaregs(s);

        if (s->sr_index == VGA_SEQ_CLOCK_MODE) {

            s->update_retrace_info(s);

        }

        vga_update_memory_access(s);

        break;

    case VGA_PEL_IR:

        s->dac_read_index = val;

        s->dac_sub_index = 0;

        s->dac_state = 3;

        break;

    case VGA_PEL_IW:

        s->dac_write_index = val;

        s->dac_sub_index = 0;

        s->dac_state = 0;

        break;

    case VGA_PEL_D:

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

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

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

            s->dac_sub_index = 0;

            s->dac_write_index++;

        }

        break;

    case VGA_GFX_I:

        s->gr_index = val & 0x0f;

        break;

    case VGA_GFX_D:

#ifdef DEBUG_VGA_REG

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

#endif

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

        vbe_update_vgaregs(s);

        vga_update_memory_access(s);

        break;

    case VGA_CRT_IM:

    case VGA_CRT_IC:

        s->cr_index = val;

        break;

    case VGA_CRT_DM:

    case VGA_CRT_DC:

#ifdef DEBUG_VGA_REG

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

#endif

        /* handle CR0-7 protection */

        if ((s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) &&

            s->cr_index <= VGA_CRTC_OVERFLOW) {

            /* can always write bit 4 of CR7 */

            if (s->cr_index == VGA_CRTC_OVERFLOW) {

                s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) |

                    (val & 0x10);

                vbe_update_vgaregs(s);

            }

            return;

        }

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

        vbe_update_vgaregs(s);

        switch(s->cr_index) {

        case VGA_CRTC_H_TOTAL:

        case VGA_CRTC_H_SYNC_START:

        case VGA_CRTC_H_SYNC_END:

        case VGA_CRTC_V_TOTAL:

        case VGA_CRTC_OVERFLOW:

        case VGA_CRTC_V_SYNC_END:

        case VGA_CRTC_MODE:

            s->update_retrace_info(s);

            break;

        }

        break;

    case VGA_IS1_RM:

    case VGA_IS1_RC:

        s->fcr = val & 0x10;

        break;

    }

}


static unsigned int celt_decode_band(CeltContext *s, OpusRangeCoder *rc,

                                     const int band, float *X, float *Y,

                                     int N, int b, unsigned int blocks,

                                     float *lowband, int duration,

                                     float *lowband_out, int level,

                                     float gain, float *lowband_scratch,

                                     int fill)

{

    const uint8_t *cache;

    int dualstereo, split;

    int imid = 0, iside = 0;

    unsigned int N0 = N;

    int N_B;

    int N_B0;

    int B0 = blocks;

    int time_divide = 0;

    int recombine = 0;

    int inv = 0;

    float mid = 0, side = 0;

    int longblocks = (B0 == 1);

    unsigned int cm = 0;

    N_B0 = N_B = N / blocks;

    split = dualstereo = (Y != NULL);

    if (N == 1) {

        /* special case for one sample */

        int i;

        float *x = X;

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

            int sign = 0;

            if (s->remaining2 >= 1<<3) {

                sign           = opus_getrawbits(rc, 1);

                s->remaining2 -= 1 << 3;

                b             -= 1 << 3;

            }

            x[0] = sign ? -1.0f : 1.0f;

            x = Y;

        }

        if (lowband_out)

            lowband_out[0] = X[0];

        return 1;

    }

    if (!dualstereo && level == 0) {

        int tf_change = s->tf_change[band];

        int k;

        if (tf_change > 0)

            recombine = tf_change;

        /* Band recombining to increase frequency resolution */

        if (lowband &&

            (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {

            int j;

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

                lowband_scratch[j] = lowband[j];

            lowband = lowband_scratch;

        }

        for (k = 0; k < recombine; k++) {

            if (lowband)

                celt_haar1(lowband, N >> k, 1 << k);

            fill = celt_bit_interleave[fill & 0xF] | celt_bit_interleave[fill >> 4] << 2;

        }

        blocks >>= recombine;

        N_B <<= recombine;

        /* Increasing the time resolution */

        while ((N_B & 1) == 0 && tf_change < 0) {

            if (lowband)

                celt_haar1(lowband, N_B, blocks);

            fill |= fill << blocks;

            blocks <<= 1;

            N_B >>= 1;

            time_divide++;

            tf_change++;

        }

        B0 = blocks;

        N_B0 = N_B;

        /* Reorganize the samples in time order instead of frequency order */

        if (B0 > 1 && lowband)

            celt_deinterleave_hadamard(s->scratch, lowband, N_B >> recombine,

                                       B0 << recombine, longblocks);

    }

    /* If we need 1.5 more bit than we can produce, split the band in two. */

    cache = celt_cache_bits +

            celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];

    if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {

        N >>= 1;

        Y = X + N;

        split = 1;

        duration -= 1;

        if (blocks == 1)

            fill = (fill & 1) | (fill << 1);

        blocks = (blocks + 1) >> 1;

    }

    if (split) {

        int qn;

        int itheta = 0;

        int mbits, sbits, delta;

        int qalloc;

        int pulse_cap;

        int offset;

        int orig_fill;

        int tell;

        /* Decide on the resolution to give to the split parameter theta */

        pulse_cap = celt_log_freq_range[band] + duration * 8;

        offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :

                                                          CELT_QTHETA_OFFSET);

        qn = (dualstereo && band >= s->intensitystereo) ? 1 :

             celt_compute_qn(N, b, offset, pulse_cap, dualstereo);

        tell = opus_rc_tell_frac(rc);

        if (qn != 1) {

            /* Entropy coding of the angle. We use a uniform pdf for the

            time split, a step for stereo, and a triangular one for the rest. */

            if (dualstereo && N > 2)

                itheta = opus_rc_stepmodel(rc, qn/2);

            else if (dualstereo || B0 > 1)

                itheta = opus_rc_unimodel(rc, qn+1);

            else

                itheta = opus_rc_trimodel(rc, qn);

            itheta = itheta * 16384 / qn;

            /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.

            Let's do that at higher complexity */

        } else if (dualstereo) {

            inv = (b > 2 << 3 && s->remaining2 > 2 << 3) ? opus_rc_p2model(rc, 2) : 0;

            itheta = 0;

        }

        qalloc = opus_rc_tell_frac(rc) - tell;

        b -= qalloc;

        orig_fill = fill;

        if (itheta == 0) {

            imid = 32767;

            iside = 0;

            fill &= (1 << blocks) - 1;

            delta = -16384;

        } else if (itheta == 16384) {

            imid = 0;

            iside = 32767;

            fill &= ((1 << blocks) - 1) << blocks;

            delta = 16384;

        } else {

            imid = celt_cos(itheta);

            iside = celt_cos(16384-itheta);

            /* This is the mid vs side allocation that minimizes squared error

            in that band. */

            delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));

        }

        mid  = imid  / 32768.0f;

        side = iside / 32768.0f;

        /* This is a special case for N=2 that only works for stereo and takes

        advantage of the fact that mid and side are orthogonal to encode

        the side with just one bit. */

        if (N == 2 && dualstereo) {

            int c;

            int sign = 0;

            float tmp;

            float *x2, *y2;

            mbits = b;

            /* Only need one bit for the side */

            sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;

            mbits -= sbits;

            c = (itheta > 8192);

            s->remaining2 -= qalloc+sbits;

            x2 = c ? Y : X;

            y2 = c ? X : Y;

            if (sbits)

                sign = opus_getrawbits(rc, 1);

            sign = 1 - 2 * sign;

            /* We use orig_fill here because we want to fold the side, but if

            itheta==16384, we'll have cleared the low bits of fill. */

            cm = celt_decode_band(s, rc, band, x2, NULL, N, mbits, blocks,

                                  lowband, duration, lowband_out, level, gain,

                                  lowband_scratch, orig_fill);

            /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),

            and there's no need to worry about mixing with the other channel. */

            y2[0] = -sign * x2[1];

            y2[1] =  sign * x2[0];

            X[0] *= mid;

            X[1] *= mid;

            Y[0] *= side;

            Y[1] *= side;

            tmp = X[0];

            X[0] = tmp - Y[0];

            Y[0] = tmp + Y[0];

            tmp = X[1];

            X[1] = tmp - Y[1];

            Y[1] = tmp + Y[1];

        } else {

            /* "Normal" split code */

            float *next_lowband2     = NULL;

            float *next_lowband_out1 = NULL;

            int next_level = 0;

            int rebalance;

            /* Give more bits to low-energy MDCTs than they would

             * otherwise deserve */

            if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {

                if (itheta > 8192)

                    /* Rough approximation for pre-echo masking */

                    delta -= delta >> (4 - duration);

                else

                    /* Corresponds to a forward-masking slope of

                     * 1.5 dB per 10 ms */

                    delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));

            }

            mbits = av_clip((b - delta) / 2, 0, b);

            sbits = b - mbits;

            s->remaining2 -= qalloc;

            if (lowband && !dualstereo)

                next_lowband2 = lowband + N; /* >32-bit split case */

            /* Only stereo needs to pass on lowband_out.

             * Otherwise, it's handled at the end */

            if (dualstereo)

                next_lowband_out1 = lowband_out;

            else

                next_level = level + 1;

            rebalance = s->remaining2;

            if (mbits >= sbits) {

                /* In stereo mode, we do not apply a scaling to the mid

                 * because we need the normalized mid for folding later */

                cm = celt_decode_band(s, rc, band, X, NULL, N, mbits, blocks,

                                      lowband, duration, next_lowband_out1,

                                      next_level, dualstereo ? 1.0f : (gain * mid),

                                      lowband_scratch, fill);

                rebalance = mbits - (rebalance - s->remaining2);

                if (rebalance > 3 << 3 && itheta != 0)

                    sbits += rebalance - (3 << 3);

                /* For a stereo split, the high bits of fill are always zero,

                 * so no folding will be done to the side. */

                cm |= celt_decode_band(s, rc, band, Y, NULL, N, sbits, blocks,

                                       next_lowband2, duration, NULL,

                                       next_level, gain * side, NULL,

                                       fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));

            } else {

                /* For a stereo split, the high bits of fill are always zero,

                 * so no folding will be done to the side. */

                cm = celt_decode_band(s, rc, band, Y, NULL, N, sbits, blocks,

                                      next_lowband2, duration, NULL,

                                      next_level, gain * side, NULL,

                                      fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));

                rebalance = sbits - (rebalance - s->remaining2);

                if (rebalance > 3 << 3 && itheta != 16384)

                    mbits += rebalance - (3 << 3);

                /* In stereo mode, we do not apply a scaling to the mid because

                 * we need the normalized mid for folding later */

                cm |= celt_decode_band(s, rc, band, X, NULL, N, mbits, blocks,

                                       lowband, duration, next_lowband_out1,

                                       next_level, dualstereo ? 1.0f : (gain * mid),

                                       lowband_scratch, fill);

            }

        }

    } else {

        /* This is the basic no-split case */

        unsigned int q         = celt_bits2pulses(cache, b);

        unsigned int curr_bits = celt_pulses2bits(cache, q);

        s->remaining2 -= curr_bits;

        /* Ensures we can never bust the budget */

        while (s->remaining2 < 0 && q > 0) {

            s->remaining2 += curr_bits;

            curr_bits      = celt_pulses2bits(cache, --q);

            s->remaining2 -= curr_bits;

        }

        if (q != 0) {

            /* Finally do the actual quantization */

            cm = celt_alg_unquant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),

                                  s->spread, blocks, gain);

        } else {

            /* If there's no pulse, fill the band anyway */

            int j;

            unsigned int cm_mask = (1 << blocks) - 1;

            fill &= cm_mask;

            if (!fill) {

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

                    X[j] = 0.0f;

            } else {

                if (lowband == NULL) {

                    /* Noise */

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

                        X[j] = (((int32_t)celt_rng(s)) >> 20);

                    cm = cm_mask;

                } else {

                    /* Folded spectrum */

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

                        /* About 48 dB below the "normal" folding level */

                        X[j] = lowband[j] + (((celt_rng(s)) & 0x8000) ? 1.0f / 256 : -1.0f / 256);

                    }

                    cm = fill;

                }

                celt_renormalize_vector(X, N, gain);

            }

        }

    }

    /* This code is used by the decoder and by the resynthesis-enabled encoder */

    if (dualstereo) {

        int j;

        if (N != 2)

            celt_stereo_merge(X, Y, mid, N);

        if (inv) {

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

                Y[j] *= -1;

        }

    } else if (level == 0) {

        int k;

        /* Undo the sample reorganization going from time order to frequency order */

        if (B0 > 1)

            celt_interleave_hadamard(s->scratch, X, N_B>>recombine,

                                     B0<<recombine, longblocks);

        /* Undo time-freq changes that we did earlier */

        N_B = N_B0;

        blocks = B0;

        for (k = 0; k < time_divide; k++) {

            blocks >>= 1;

            N_B <<= 1;

            cm |= cm >> blocks;

            celt_haar1(X, N_B, blocks);

        }

        for (k = 0; k < recombine; k++) {

            cm = celt_bit_deinterleave[cm];

            celt_haar1(X, N0>>k, 1<<k);

        }

        blocks <<= recombine;

        /* Scale output for later folding */

        if (lowband_out) {

            int j;

            float n = sqrtf(N0);

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

                lowband_out[j] = n * X[j];

        }

        cm &= (1 << blocks) - 1;

    }

    return cm;

}


static int tiff_unpack_strip(TiffContext *s, AVFrame *p, uint8_t *dst, int stride,

                             const uint8_t *src, int size, int strip_start, int lines)

{

    PutByteContext pb;

    int c, line, pixels, code, ret;

    const uint8_t *ssrc = src;

    int width = ((s->width * s->bpp) + 7) >> 3;

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(p->format);

    int is_yuv = !(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components >= 2;

    if (s->planar)

        width /= s->bppcount;

    if (size <= 0)

        return AVERROR_INVALIDDATA;

    if (is_yuv) {

        int bytes_per_row = (((s->width - 1) / s->subsampling[0] + 1) * s->bpp *

                            s->subsampling[0] * s->subsampling[1] + 7) >> 3;

        av_fast_padded_malloc(&s->yuv_line, &s->yuv_line_size, bytes_per_row);

        if (s->yuv_line == NULL) {

            av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n");

            return AVERROR(ENOMEM);

        }

        dst = s->yuv_line;

        stride = 0;

        width = s->width * s->subsampling[1] + 2*(s->width / s->subsampling[0]);

        av_assert0(width <= bytes_per_row);

        av_assert0(s->bpp == 24);

    }

    if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) {

#if CONFIG_ZLIB

        return tiff_unpack_zlib(s, p, dst, stride, src, size, width, lines,

                                strip_start, is_yuv);

#else

        av_log(s->avctx, AV_LOG_ERROR,

               "zlib support not enabled, "

               "deflate compression not supported\n");

        return AVERROR(ENOSYS);

#endif

    }

    if (s->compr == TIFF_LZMA) {

#if CONFIG_LZMA

        return tiff_unpack_lzma(s, p, dst, stride, src, size, width, lines,

                                strip_start, is_yuv);

#else

        av_log(s->avctx, AV_LOG_ERROR,

               "LZMA support not enabled\n");

        return AVERROR(ENOSYS);

#endif

    }

    if (s->compr == TIFF_LZW) {

        if (s->fill_order) {

            if ((ret = deinvert_buffer(s, src, size)) < 0)

                return ret;

            ssrc = src = s->deinvert_buf;

        }

        if (size > 1 && !src[0] && (src[1]&1)) {

            av_log(s->avctx, AV_LOG_ERROR, "Old style LZW is unsupported\n");

        }

        if ((ret = ff_lzw_decode_init(s->lzw, 8, src, size, FF_LZW_TIFF)) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "Error initializing LZW decoder\n");

            return ret;

        }

        for (line = 0; line < lines; line++) {

            pixels = ff_lzw_decode(s->lzw, dst, width);

            if (pixels < width) {

                av_log(s->avctx, AV_LOG_ERROR, "Decoded only %i bytes of %i\n",

                       pixels, width);

                return AVERROR_INVALIDDATA;

            }

            if (s->bpp < 8 && s->avctx->pix_fmt == AV_PIX_FMT_PAL8)

                horizontal_fill(s->bpp, dst, 1, dst, 0, width, 0);

            if (is_yuv) {

                unpack_yuv(s, p, dst, strip_start + line);

                line += s->subsampling[1] - 1;

            }

            dst += stride;

        }

        return 0;

    }

    if (s->compr == TIFF_CCITT_RLE ||

        s->compr == TIFF_G3        ||

        s->compr == TIFF_G4) {

        if (is_yuv)

            return AVERROR_INVALIDDATA;

        return tiff_unpack_fax(s, dst, stride, src, size, width, lines);

    }

    bytestream2_init(&s->gb, src, size);

    bytestream2_init_writer(&pb, dst, is_yuv ? s->yuv_line_size : (stride * lines));

    for (line = 0; line < lines; line++) {

        if (src - ssrc > size) {

            av_log(s->avctx, AV_LOG_ERROR, "Source data overread\n");

            return AVERROR_INVALIDDATA;

        }

        if (bytestream2_get_bytes_left(&s->gb) == 0 || bytestream2_get_eof(&pb))

            break;

        bytestream2_seek_p(&pb, stride * line, SEEK_SET);

        switch (s->compr) {

        case TIFF_RAW:

            if (ssrc + size - src < width)

                return AVERROR_INVALIDDATA;

            if (!s->fill_order) {

                horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),

                                dst, 1, src, 0, width, 0);

            } else {

                int i;

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

                    dst[i] = ff_reverse[src[i]];

            }

            src += width;

            break;

        case TIFF_PACKBITS:

            for (pixels = 0; pixels < width;) {

                if (ssrc + size - src < 2) {

                    av_log(s->avctx, AV_LOG_ERROR, "Read went out of bounds\n");

                    return AVERROR_INVALIDDATA;

                }

                code = s->fill_order ? (int8_t) ff_reverse[*src++]: (int8_t) *src++;

                if (code >= 0) {

                    code++;

                    if (pixels + code > width ||

                        ssrc + size - src < code) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Copy went out of bounds\n");

                        return AVERROR_INVALIDDATA;

                    }

                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),

                                    dst, 1, src, 0, code, pixels);

                    src    += code;

                    pixels += code;

                } else if (code != -128) { // -127..-1

                    code = (-code) + 1;

                    if (pixels + code > width) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Run went out of bounds\n");

                        return AVERROR_INVALIDDATA;

                    }

                    c = *src++;

                    horizontal_fill(s->bpp * (s->avctx->pix_fmt == AV_PIX_FMT_PAL8),

                                    dst, 0, NULL, c, code, pixels);

                    pixels += code;

                }

            }

            if (s->fill_order) {

                int i;

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

                    dst[i] = ff_reverse[dst[i]];

            }

            break;

        }

        if (is_yuv) {

            unpack_yuv(s, p, dst, strip_start + line);

            line += s->subsampling[1] - 1;

        }

        dst += stride;

    }

    return 0;

}


static void mkv_free(MatroskaMuxContext *mkv) {

    if (mkv->main_seekhead) {

        av_freep(&mkv->main_seekhead->entries);

        av_freep(&mkv->main_seekhead);

    if (mkv->cues) {

        av_freep(&mkv->cues->entries);

        av_freep(&mkv->cues);

    if (mkv->attachments) {

        av_freep(&mkv->attachments->entries);

        av_freep(&mkv->attachments);

    av_freep(&mkv->tracks);

    av_freep(&mkv->stream_durations);

    av_freep(&mkv->stream_duration_offsets);


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);

    dc->realize = raven_pcihost_realizefn;

    dc->fw_name = "pci";

    dc->no_user = 1;

}


static int chr_can_read(void *opaque)

{

    int can_read;

    SCLPConsole *scon = opaque;

    can_read = SIZE_BUFFER_VT220 - scon->iov_data_len;

    return can_read;

}


int show_filters(void *optctx, const char *opt, const char *arg)

{

    AVFilter av_unused(**filter) = NULL;

    printf("Filters:\n");

#if CONFIG_AVFILTER

    while ((filter = av_filter_next(filter)) && *filter)

        printf("%-16s %s\n", (*filter)->name, (*filter)->description);

#endif

    return 0;

}


static int cavs_find_frame_end(ParseContext *pc, const uint8_t *buf,

                               int buf_size) {

    int pic_found, i;

    uint32_t state;

    pic_found= pc->frame_start_found;

    state= pc->state;

    i=0;

    if(!pic_found){

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

            state= (state<<8) | buf[i];

            if(state == PIC_I_START_CODE || state == PIC_PB_START_CODE){

                i++;

                pic_found=1;

                break;

            }

        }

    }

    if(pic_found){

        /* EOF considered as end of frame */

        if (buf_size == 0)

            return 0;

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

            state= (state<<8) | buf[i];

            if((state&0xFFFFFF00) == 0x100){

                if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){

                    pc->frame_start_found=0;

                    pc->state=-1;

                    return i-3;

                }

            }

        }

    }

    pc->frame_start_found= pic_found;

    pc->state= state;

    return END_NOT_FOUND;

}


int net_client_init(Monitor *mon, QemuOpts *opts, int is_netdev)

{

    const char *name;

    const char *type;

    int i;

    type = qemu_opt_get(opts, "type");

    if (!type) {

        qerror_report(QERR_MISSING_PARAMETER, "type");

        return -1;

    }

    if (is_netdev) {

        if (strcmp(type, "tap") != 0 &&

#ifdef CONFIG_SLIRP

            strcmp(type, "user") != 0 &&

#endif

#ifdef CONFIG_VDE

            strcmp(type, "vde") != 0 &&

#endif

            strcmp(type, "socket") != 0) {

            qerror_report(QERR_INVALID_PARAMETER_VALUE, "type",

                          "a netdev backend type");

            return -1;

        }

        if (qemu_opt_get(opts, "vlan")) {

            qerror_report(QERR_INVALID_PARAMETER, "vlan");

            return -1;

        }

        if (qemu_opt_get(opts, "name")) {

            qerror_report(QERR_INVALID_PARAMETER, "name");

            return -1;

        }

        if (!qemu_opts_id(opts)) {

            qerror_report(QERR_MISSING_PARAMETER, "id");

            return -1;

        }

    }

    name = qemu_opts_id(opts);

    if (!name) {

        name = qemu_opt_get(opts, "name");

    }

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

        if (net_client_types[i].type != NULL &&

            !strcmp(net_client_types[i].type, type)) {

            VLANState *vlan = NULL;

            int ret;

            if (qemu_opts_validate(opts, &net_client_types[i].desc[0]) == -1) {

                return -1;

            }

            /* Do not add to a vlan if it's a -netdev or a nic with a

             * netdev= parameter. */

            if (!(is_netdev ||

                  (strcmp(type, "nic") == 0 && qemu_opt_get(opts, "netdev")))) {

                vlan = qemu_find_vlan(qemu_opt_get_number(opts, "vlan", 0), 1);

            }

            ret = 0;

            if (net_client_types[i].init) {

                ret = net_client_types[i].init(opts, mon, name, vlan);

                if (ret < 0) {

                    /* TODO push error reporting into init() methods */

                    qerror_report(QERR_DEVICE_INIT_FAILED, type);

                    return -1;

                }

            }

            return ret;

        }

    }

    qerror_report(QERR_INVALID_PARAMETER_VALUE, "type",

                  "a network client type");

    return -1;

}


static void bwf_write_bext_chunk(AVFormatContext *s)

{

    AVDictionaryEntry *tmp_tag;

    uint64_t time_reference = 0;

    int64_t bext = ff_start_tag(s->pb, "bext");

    bwf_write_bext_string(s, "description", 256);

    bwf_write_bext_string(s, "originator", 32);

    bwf_write_bext_string(s, "originator_reference", 32);

    bwf_write_bext_string(s, "origination_date", 10);

    bwf_write_bext_string(s, "origination_time", 8);

    if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))

        time_reference = strtoll(tmp_tag->value, NULL, 10);

    avio_wl64(s->pb, time_reference);

    avio_wl16(s->pb, 1);  // set version to 1

    if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {

        unsigned char umidpart_str[17] = {0};

        int64_t i;

        uint64_t umidpart;

        size_t len = strlen(tmp_tag->value+2);

        for (i = 0; i < len/16; i++) {

            memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);

            umidpart = strtoll(umidpart_str, NULL, 16);

            avio_wb64(s->pb, umidpart);

        }

        ffio_fill(s->pb, 0, 64 - i*8);

    } else

        ffio_fill(s->pb, 0, 64); // zero UMID

    ffio_fill(s->pb, 0, 190); // Reserved

    if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))

        avio_put_str(s->pb, tmp_tag->value);

    ff_end_tag(s->pb, bext);

}


static void free_schro_frame(SchroFrame *frame, void *priv)

{

    AVFrame *p_pic = priv;

    av_frame_free(&p_pic);

}


static void qdict_do_flatten(QDict *qdict, QDict *target, const char *prefix)

{

    QObject *value;

    const QDictEntry *entry, *next;

    const char *new_key;

    bool delete;

    entry = qdict_first(qdict);

    while (entry != NULL) {

        next = qdict_next(qdict, entry);

        value = qdict_entry_value(entry);

        new_key = NULL;

        delete = false;

        if (prefix) {

            qobject_incref(value);

            new_key = g_strdup_printf("%s.%s", prefix, entry->key);

            qdict_put_obj(target, new_key, value);

            delete = true;

        }

        if (qobject_type(value) == QTYPE_QDICT) {

            qdict_do_flatten(qobject_to_qdict(value), target,

                             new_key ? new_key : entry->key);

            delete = true;

        }

        if (delete) {

            qdict_del(qdict, entry->key);

            /* Restart loop after modifying the iterated QDict */

            entry = qdict_first(qdict);

            continue;

        }

        entry = next;

    }

}


static av_cold int flashsv2_encode_init(AVCodecContext * avctx)

{

    FlashSV2Context *s = avctx->priv_data;

    s->avctx = avctx;

    s->comp = avctx->compression_level;

    if (s->comp == -1)

        s->comp = 9;

    if (s->comp < 0 || s->comp > 9) {

               "Compression level should be 0-9, not %d\n", s->comp);

    if ((avctx->width > 4095) || (avctx->height > 4095)) {

               "Input dimensions too large, input must be max 4096x4096 !\n");

    if (av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0)

    s->last_key_frame = 0;

    s->image_width  = avctx->width;

    s->image_height = avctx->height;

    s->block_width  = (s->image_width /  12) & ~15;

    s->block_height = (s->image_height / 12) & ~15;

    if(!s->block_width)

        s->block_width = 1;

    if(!s->block_height)

        s->block_height = 1;

    s->rows = (s->image_height + s->block_height - 1) / s->block_height;

    s->cols = (s->image_width +  s->block_width -  1) / s->block_width;

    s->frame_size  = s->image_width * s->image_height * 3;

    s->blocks_size = s->rows * s->cols * sizeof(Block);

    s->encbuffer     = av_mallocz(s->frame_size);

    s->keybuffer     = av_mallocz(s->frame_size);

    s->databuffer    = av_mallocz(s->frame_size * 6);

    s->current_frame = av_mallocz(s->frame_size);

    s->key_frame     = av_mallocz(s->frame_size);

    s->frame_blocks  = av_mallocz(s->blocks_size);

    s->key_blocks    = av_mallocz(s->blocks_size);

    init_blocks(s, s->frame_blocks, s->encbuffer, s->databuffer);

    init_blocks(s, s->key_blocks,   s->keybuffer, 0);

    reset_stats(s);

#ifndef FLASHSV2_DUMB

    s->total_bits = 1;

#endif

    s->use_custom_palette =  0;

    s->palette_type       = -1;        // so that the palette will be generated in reconfigure_at_keyframe

    if (!s->encbuffer || !s->keybuffer || !s->databuffer

        || !s->current_frame || !s->key_frame || !s->key_blocks

        || !s->frame_blocks) {

        av_log(avctx, AV_LOG_ERROR, "Memory allocation failed.\n");

        cleanup(s);

    return 0;


float64 HELPER(ucf64_divd)(float64 a, float64 b, CPUUniCore32State *env)

{

    return float64_div(a, b, &env->ucf64.fp_status);

}


static void decode_pulses(Pulse * pulse, GetBitContext * gb, const uint16_t * swb_offset) {

    int i;

    pulse->num_pulse = get_bits(gb, 2) + 1;

    pulse->pos[0]    = swb_offset[get_bits(gb, 6)];

    pulse->pos[0]   += get_bits(gb, 5);

    pulse->amp[0]    = get_bits(gb, 4);

    for (i = 1; i < pulse->num_pulse; i++) {

        pulse->pos[i] = get_bits(gb, 5) + pulse->pos[i-1];

        pulse->amp[i] = get_bits(gb, 4);

    }

}


static inline void gen_op_eval_fbuge(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_xori_tl(cpu_tmp0, cpu_tmp0, 0x1);

    tcg_gen_and_tl(dst, dst, cpu_tmp0);

    tcg_gen_xori_tl(dst, dst, 0x1);

}


int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)

{

    char backing_filename[PATH_MAX];

    int back_flags, ret;

    BlockDriver *back_drv = NULL;

    Error *local_err = NULL;

    if (bs->backing_hd != NULL) {

        QDECREF(options);

        return 0;

    }

    /* NULL means an empty set of options */

    if (options == NULL) {

        options = qdict_new();

    }

    bs->open_flags &= ~BDRV_O_NO_BACKING;

    if (qdict_haskey(options, "file.filename")) {

        backing_filename[0] = '\0';

    } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {

        QDECREF(options);

        return 0;

    }

    bs->backing_hd = bdrv_new("");

    bdrv_get_full_backing_filename(bs, backing_filename,

                                   sizeof(backing_filename));

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

        back_drv = bdrv_find_format(bs->backing_format);

    }

    /* backing files always opened read-only */

    back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);

    ret = bdrv_open(bs->backing_hd,

                    *backing_filename ? backing_filename : NULL, options,

                    back_flags, back_drv, &local_err);

    if (ret < 0) {

        bdrv_unref(bs->backing_hd);

        bs->backing_hd = NULL;

        bs->open_flags |= BDRV_O_NO_BACKING;

        error_propagate(errp, local_err);

        return ret;

    }

    return 0;

}


static OSStatus audioDeviceIOProc(

    AudioDeviceID inDevice,

    const AudioTimeStamp* inNow,

    const AudioBufferList* inInputData,

    const AudioTimeStamp* inInputTime,

    AudioBufferList* outOutputData,

    const AudioTimeStamp* inOutputTime,

    void* hwptr)

{

    UInt32 frame, frameCount;

    float *out = outOutputData->mBuffers[0].mData;

    HWVoiceOut *hw = hwptr;

    coreaudioVoiceOut *core = (coreaudioVoiceOut *) hwptr;

    int rpos, live;

    st_sample_t *src;

#ifndef FLOAT_MIXENG

#ifdef RECIPROCAL

    const float scale = 1.f / UINT_MAX;

#else

    const float scale = UINT_MAX;

#endif

#endif

    if (coreaudio_lock (core, "audioDeviceIOProc")) {

        inInputTime = 0;

        return 0;

    }

    frameCount = core->audioDevicePropertyBufferFrameSize;

    live = core->live;

    /* if there are not enough samples, set signal and return */

    if (live < frameCount) {

        inInputTime = 0;

        coreaudio_unlock (core, "audioDeviceIOProc(empty)");

        return 0;

    }

    rpos = core->rpos;

    src = hw->mix_buf + rpos;

    /* fill buffer */

    for (frame = 0; frame < frameCount; frame++) {

#ifdef FLOAT_MIXENG

        *out++ = src[frame].l; /* left channel */

        *out++ = src[frame].r; /* right channel */

#else

#ifdef RECIPROCAL

        *out++ = src[frame].l * scale; /* left channel */

        *out++ = src[frame].r * scale; /* right channel */

#else

        *out++ = src[frame].l / scale; /* left channel */

        *out++ = src[frame].r / scale; /* right channel */

#endif

#endif

    }

    rpos = (rpos + frameCount) % hw->samples;

    core->decr += frameCount;

    core->rpos = rpos;

    coreaudio_unlock (core, "audioDeviceIOProc");

    return 0;

}


static void m68k_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    M68kCPU *cpu = M68K_CPU(obj);

    CPUM68KState *env = &cpu->env;

    static bool inited;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    if (tcg_enabled() && !inited) {

        inited = true;

        m68k_tcg_init();

    }

}


int ff_start_frame(AVFilterLink *link, AVFilterBufferRef *picref)

{

    int (*start_frame)(AVFilterLink *, AVFilterBufferRef *);

    AVFilterPad *src = link->srcpad;

    AVFilterPad *dst = link->dstpad;

    int ret, perms;

    AVFilterCommand *cmd= link->dst->command_queue;

    int64_t pts;

    FF_TPRINTF_START(NULL, start_frame); ff_tlog_link(NULL, link, 0); ff_tlog(NULL, " "); ff_tlog_ref(NULL, picref, 1);

    av_assert1(picref->format                     == link->format);

    av_assert1(picref->video->w                   == link->w);

    av_assert1(picref->video->h                   == link->h);

    if (link->closed) {

        avfilter_unref_buffer(picref);

        return AVERROR_EOF;

    }

    if (!(start_frame = dst->start_frame))

        start_frame = default_start_frame;

    av_assert1((picref->perms & src->min_perms) == src->min_perms);

    picref->perms &= ~ src->rej_perms;

    perms = picref->perms;

    if (picref->linesize[0] < 0)

        perms |= AV_PERM_NEG_LINESIZES;

    /* prepare to copy the picture if it has insufficient permissions */

    if ((dst->min_perms & perms) != dst->min_perms || dst->rej_perms & perms) {

        av_log(link->dst, AV_LOG_DEBUG,

                "frame copy needed (have perms %x, need %x, reject %x)\n",

                picref->perms,

                link->dstpad->min_perms, link->dstpad->rej_perms);

        link->cur_buf = ff_get_video_buffer(link, dst->min_perms, link->w, link->h);

        if (!link->cur_buf) {

            avfilter_unref_bufferp(&picref);

            return AVERROR(ENOMEM);

        }

        link->src_buf = picref;

        avfilter_copy_buffer_ref_props(link->cur_buf, link->src_buf);

        /* copy palette if required */

        if (av_pix_fmt_descriptors[link->format].flags & PIX_FMT_PAL)

            memcpy(link->cur_buf->data[1], link->src_buf-> data[1], AVPALETTE_SIZE);

    }

    else

        link->cur_buf = picref;

    link->cur_buf_copy = link->cur_buf;

    while(cmd && cmd->time <= picref->pts * av_q2d(link->time_base)){

        av_log(link->dst, AV_LOG_DEBUG,

               "Processing command time:%f command:%s arg:%s\n",

               cmd->time, cmd->command, cmd->arg);

        avfilter_process_command(link->dst, cmd->command, cmd->arg, 0, 0, cmd->flags);

        ff_command_queue_pop(link->dst);

        cmd= link->dst->command_queue;

    }

    pts = link->cur_buf->pts;

    ret = start_frame(link, link->cur_buf);

    ff_update_link_current_pts(link, pts);

    if (ret < 0)

        clear_link(link);

    else

        /* incoming buffers must not be freed in start frame,

           because they can still be in use by the automatic copy mechanism */

        av_assert1(link->cur_buf_copy->buf->refcount > 0);

    return ret;

}


static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,

                              int header_size)

{

    int len;

    short wave_format;

    if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {

        av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");

        return -1;

    }

    header += 4; /* chunk size */;

    if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {

        av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");

        return -1;

    }

    while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {

        len = bytestream_get_le32(&header);

        header += len;

    }

    len = bytestream_get_le32(&header);

    if (len < 16) {

        av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");

        return -1;

    }

    wave_format = bytestream_get_le16(&header);

    switch (wave_format) {

        case WAVE_FORMAT_PCM:

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");

            return -1;

    }

    header += 2;        // skip channels    (already got from shorten header)

    avctx->sample_rate = bytestream_get_le32(&header);

    header += 4;        // skip bit rate    (represents original uncompressed bit rate)

    header += 2;        // skip block align (not needed)

    avctx->bits_per_coded_sample = bytestream_get_le16(&header);

    if (avctx->bits_per_coded_sample != 16) {

        av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");

        return -1;

    }

    len -= 16;

    if (len > 0)

        av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);

    return 0;

}


static bool bdrv_drain_one(BlockDriverState *bs)

{

    bool bs_busy;

    bdrv_flush_io_queue(bs);

    bdrv_start_throttled_reqs(bs);

    bs_busy = bdrv_requests_pending(bs);

    bs_busy |= aio_poll(bdrv_get_aio_context(bs), bs_busy);

    return bs_busy;

}


static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque)

{

    return raw_aio_submit(bs, sector_num, qiov, nb_sectors,

                          cb, opaque, QEMU_AIO_READ);

}


static int authenticate(BDRVSSHState *s, const char *user)

{

    int r, ret;

    const char *userauthlist;

    LIBSSH2_AGENT *agent = NULL;

    struct libssh2_agent_publickey *identity;

    struct libssh2_agent_publickey *prev_identity = NULL;

    userauthlist = libssh2_userauth_list(s->session, user, strlen(user));

    if (strstr(userauthlist, "publickey") == NULL) {

        ret = -EPERM;

        error_report("remote server does not support \"publickey\" authentication");

        goto out;

    }

    /* Connect to ssh-agent and try each identity in turn. */

    agent = libssh2_agent_init(s->session);

    if (!agent) {

        ret = -EINVAL;

        session_error_report(s, "failed to initialize ssh-agent support");

        goto out;

    }

    if (libssh2_agent_connect(agent)) {

        ret = -ECONNREFUSED;

        session_error_report(s, "failed to connect to ssh-agent");

        goto out;

    }

    if (libssh2_agent_list_identities(agent)) {

        ret = -EINVAL;

        session_error_report(s, "failed requesting identities from ssh-agent");

        goto out;

    }

    for(;;) {

        r = libssh2_agent_get_identity(agent, &identity, prev_identity);

        if (r == 1) {           /* end of list */

            break;

        }

        if (r < 0) {

            ret = -EINVAL;

            session_error_report(s, "failed to obtain identity from ssh-agent");

            goto out;

        }

        r = libssh2_agent_userauth(agent, user, identity);

        if (r == 0) {

            /* Authenticated! */

            ret = 0;

            goto out;

        }

        /* Failed to authenticate with this identity, try the next one. */

        prev_identity = identity;

    }

    ret = -EPERM;

    error_report("failed to authenticate using publickey authentication "

                 "and the identities held by your ssh-agent");

 out:

    if (agent != NULL) {

        /* Note: libssh2 implementation implicitly calls

         * libssh2_agent_disconnect if necessary.

         */

        libssh2_agent_free(agent);

    }

    return ret;

}


static bool bdrv_is_valid_name(const char *name)

{

    return qemu_opts_id_wellformed(name);

}


static void cirrus_vga_mem_write(void *opaque,

                                 target_phys_addr_t addr,

                                 uint64_t mem_value,

                                 uint32_t size)

{

    CirrusVGAState *s = opaque;

    unsigned bank_index;

    unsigned bank_offset;

    unsigned mode;

    if ((s->vga.sr[0x07] & 0x01) == 0) {

        vga_mem_writeb(&s->vga, addr, mem_value);

        return;

    }

    if (addr < 0x10000) {

	if (s->cirrus_srcptr != s->cirrus_srcptr_end) {

	    /* bitblt */

	    *s->cirrus_srcptr++ = (uint8_t) mem_value;

	    if (s->cirrus_srcptr >= s->cirrus_srcptr_end) {

		cirrus_bitblt_cputovideo_next(s);

	    }

	} else {

	    /* video memory */

	    bank_index = addr >> 15;

	    bank_offset = addr & 0x7fff;

	    if (bank_offset < s->cirrus_bank_limit[bank_index]) {

		bank_offset += s->cirrus_bank_base[bank_index];

		if ((s->vga.gr[0x0B] & 0x14) == 0x14) {

		    bank_offset <<= 4;

		} else if (s->vga.gr[0x0B] & 0x02) {

		    bank_offset <<= 3;

		}

		bank_offset &= s->cirrus_addr_mask;

		mode = s->vga.gr[0x05] & 0x7;

		if (mode < 4 || mode > 5 || ((s->vga.gr[0x0B] & 0x4) == 0)) {

		    *(s->vga.vram_ptr + bank_offset) = mem_value;

                    memory_region_set_dirty(&s->vga.vram, bank_offset,

                                            sizeof(mem_value));

		} else {

		    if ((s->vga.gr[0x0B] & 0x14) != 0x14) {

			cirrus_mem_writeb_mode4and5_8bpp(s, mode,

							 bank_offset,

							 mem_value);

		    } else {

			cirrus_mem_writeb_mode4and5_16bpp(s, mode,

							  bank_offset,

							  mem_value);

		    }

		}

	    }

	}

    } else if (addr >= 0x18000 && addr < 0x18100) {

	/* memory-mapped I/O */

	if ((s->vga.sr[0x17] & 0x44) == 0x04) {

	    cirrus_mmio_blt_write(s, addr & 0xff, mem_value);

	}

    } else {

#ifdef DEBUG_CIRRUS

        printf("cirrus: mem_writeb " TARGET_FMT_plx " value %02x\n", addr,

               mem_value);

#endif

    }

}


static void vnc_tls_handshake_io(void *opaque) {

    struct VncState *vs = (struct VncState *)opaque;

    VNC_DEBUG("Handshake IO continue\n");

    vnc_start_vencrypt_handshake(vs);

}


int sclp_service_call(uint32_t sccb, uint64_t code)

{

    int r = 0;

    SCCB work_sccb;

    hwaddr sccb_len = sizeof(SCCB);

    /* first some basic checks on program checks */

    if (cpu_physical_memory_is_io(sccb)) {

        r = -PGM_ADDRESSING;

        goto out;

    }

    if (sccb & ~0x7ffffff8ul) {

        r = -PGM_SPECIFICATION;

        goto out;

    }

    /*

     * we want to work on a private copy of the sccb, to prevent guests

     * from playing dirty tricks by modifying the memory content after

     * the host has checked the values

     */

    cpu_physical_memory_read(sccb, &work_sccb, sccb_len);

    /* Valid sccb sizes */

    if (be16_to_cpu(work_sccb.h.length) < sizeof(SCCBHeader) ||

        be16_to_cpu(work_sccb.h.length) > SCCB_SIZE) {

        r = -PGM_SPECIFICATION;

        goto out;

    }

    sclp_execute((SCCB *)&work_sccb, code);

    cpu_physical_memory_write(sccb, &work_sccb,

                              be16_to_cpu(work_sccb.h.length));

    sclp_service_interrupt(sccb);

out:

    return r;

}


static void taihu_cpld_writeb (void *opaque,

                               hwaddr addr, uint32_t value)

{

    taihu_cpld_t *cpld;

    cpld = opaque;

    switch (addr) {

    case 0x0:

        /* Read only */

        break;

    case 0x1:

        cpld->reg1 = value;

        break;

    default:

        break;

    }

}


static int usb_bt_handle_control(USBDevice *dev, int request, int value,

                int index, int length, uint8_t *data)

{

    struct USBBtState *s = (struct USBBtState *) dev->opaque;

    int ret;

    ret = usb_desc_handle_control(dev, request, value, index, length, data);

    if (ret >= 0) {

        return ret;

    }

    ret = 0;

    switch (request) {

    case DeviceRequest | USB_REQ_GET_STATUS:

    case InterfaceRequest | USB_REQ_GET_STATUS:

    case EndpointRequest | USB_REQ_GET_STATUS:

        data[0] = (1 << USB_DEVICE_SELF_POWERED) |

            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);

        data[1] = 0x00;

        ret = 2;

        break;

    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:

    case InterfaceOutRequest | USB_REQ_CLEAR_FEATURE:

    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 0;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceOutRequest | USB_REQ_SET_FEATURE:

    case InterfaceOutRequest | USB_REQ_SET_FEATURE:

    case EndpointOutRequest | USB_REQ_SET_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 1;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_CONFIGURATION:

        data[0] = 1;

        ret = 1;

        s->config = 0;

        break;

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

        ret = 0;

        if (value != 1 && value != 0) {

            printf("%s: Wrong SET_CONFIGURATION request (%i)\n",

                            __FUNCTION__, value);

            goto fail;

        }

        s->config = 1;

        usb_bt_fifo_reset(&s->evt);

        usb_bt_fifo_reset(&s->acl);

        usb_bt_fifo_reset(&s->sco);

        break;

    case InterfaceRequest | USB_REQ_GET_INTERFACE:

        if (value != 0 || (index & ~1) || length != 1)

            goto fail;

        if (index == 1)

            data[0] = s->altsetting;

        else

            data[0] = 0;

        ret = 1;

        break;

    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:

        if ((index & ~1) || length != 0 ||

                        (index == 1 && (value < 0 || value > 4)) ||

                        (index == 0 && value != 0)) {

            printf("%s: Wrong SET_INTERFACE request (%i, %i)\n",

                            __FUNCTION__, index, value);

            goto fail;

        }

        s->altsetting = value;

        ret = 0;

        break;

    case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE) << 8):

        if (s->config)

            usb_bt_fifo_out_enqueue(s, &s->outcmd, s->hci->cmd_send,

                            usb_bt_hci_cmd_complete, data, length);

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static av_cold int svq1_encode_init(AVCodecContext *avctx)

{

    SVQ1EncContext *const s = avctx->priv_data;

    int ret;

    ff_hpeldsp_init(&s->hdsp, avctx->flags);

    ff_me_cmp_init(&s->mecc, avctx);

    ff_mpegvideoencdsp_init(&s->m.mpvencdsp, avctx);

    avctx->coded_frame = av_frame_alloc();

    s->current_picture = av_frame_alloc();

    s->last_picture    = av_frame_alloc();

    if (!avctx->coded_frame || !s->current_picture || !s->last_picture) {

        svq1_encode_end(avctx);

        return AVERROR(ENOMEM);

    }

    s->frame_width  = avctx->width;

    s->frame_height = avctx->height;

    s->y_block_width  = (s->frame_width  + 15) / 16;

    s->y_block_height = (s->frame_height + 15) / 16;

    s->c_block_width  = (s->frame_width  / 4 + 15) / 16;

    s->c_block_height = (s->frame_height / 4 + 15) / 16;

    s->avctx               = avctx;

    s->m.avctx             = avctx;

    if ((ret = ff_mpv_common_init(&s->m)) < 0) {

        svq1_encode_end(avctx);

        return ret;

    }

    s->m.picture_structure = PICT_FRAME;

    s->m.me.temp           =

    s->m.me.scratchpad     = av_mallocz((avctx->width + 64) *

                                        2 * 16 * 2 * sizeof(uint8_t));

    s->m.me.map            = av_mallocz(ME_MAP_SIZE * sizeof(uint32_t));

    s->m.me.score_map      = av_mallocz(ME_MAP_SIZE * sizeof(uint32_t));

    s->mb_type             = av_mallocz((s->y_block_width + 1) *

                                        s->y_block_height * sizeof(int16_t));

    s->dummy               = av_mallocz((s->y_block_width + 1) *

                                        s->y_block_height * sizeof(int32_t));

    s->ssd_int8_vs_int16   = ssd_int8_vs_int16_c;

    if (!s->m.me.temp || !s->m.me.scratchpad || !s->m.me.map ||

        !s->m.me.score_map || !s->mb_type || !s->dummy) {

        svq1_encode_end(avctx);

        return AVERROR(ENOMEM);

    }

    if (ARCH_PPC)

        ff_svq1enc_init_ppc(s);

    if (ARCH_X86)

        ff_svq1enc_init_x86(s);

    ff_h263_encode_init(&s->m); // mv_penalty

    return 0;

}


static void dp8393x_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    uint16_t old_val = dp8393x_readw(opaque, addr & ~0x1);

    switch (addr & 3) {

    case 0:

        val = val | (old_val & 0xff00);

        break;

    case 1:

        val = (val << 8) | (old_val & 0x00ff);

        break;

    }

    dp8393x_writew(opaque, addr & ~0x1, val);

}


static ssize_t nbd_co_receive_request(NBDRequestData *req,

                                      NBDRequest *request)

{

    NBDClient *client = req->client;

    ssize_t rc;

    g_assert(qemu_in_coroutine());

    assert(client->recv_coroutine == qemu_coroutine_self());

    rc = nbd_receive_request(client->ioc, request);

    if (rc < 0) {

        if (rc != -EAGAIN) {

            rc = -EIO;

        }

        goto out;

    }

    TRACE("Decoding type");

    if (request->type != NBD_CMD_WRITE) {

        /* No payload, we are ready to read the next request.  */

        req->complete = true;

    }

    if (request->type == NBD_CMD_DISC) {

        /* Special case: we're going to disconnect without a reply,

         * whether or not flags, from, or len are bogus */

        TRACE("Request type is DISCONNECT");

        rc = -EIO;

        goto out;

    }

    /* Check for sanity in the parameters, part 1.  Defer as many

     * checks as possible until after reading any NBD_CMD_WRITE

     * payload, so we can try and keep the connection alive.  */

    if ((request->from + request->len) < request->from) {

        LOG("integer overflow detected, you're probably being attacked");

        rc = -EINVAL;

        goto out;

    }

    if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {

        if (request->len > NBD_MAX_BUFFER_SIZE) {

            LOG("len (%" PRIu32" ) is larger than max len (%u)",

                request->len, NBD_MAX_BUFFER_SIZE);

            rc = -EINVAL;

            goto out;

        }

        req->data = blk_try_blockalign(client->exp->blk, request->len);

        if (req->data == NULL) {

            rc = -ENOMEM;

            goto out;

        }

    }

    if (request->type == NBD_CMD_WRITE) {

        TRACE("Reading %" PRIu32 " byte(s)", request->len);

        if (read_sync(client->ioc, req->data, request->len, NULL) < 0) {

            LOG("reading from socket failed");

            rc = -EIO;

            goto out;

        }

        req->complete = true;

    }

    /* Sanity checks, part 2. */

    if (request->from + request->len > client->exp->size) {

        LOG("operation past EOF; From: %" PRIu64 ", Len: %" PRIu32

            ", Size: %" PRIu64, request->from, request->len,

            (uint64_t)client->exp->size);

        rc = request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;

        goto out;

    }

    if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {

        LOG("unsupported flags (got 0x%x)", request->flags);

        rc = -EINVAL;

        goto out;

    }

    if (request->type != NBD_CMD_WRITE_ZEROES &&

        (request->flags & NBD_CMD_FLAG_NO_HOLE)) {

        LOG("unexpected flags (got 0x%x)", request->flags);

        rc = -EINVAL;

        goto out;

    }

    rc = 0;

out:

    client->recv_coroutine = NULL;

    nbd_client_receive_next_request(client);

    return rc;

}


static int pfpu_decode_insn(MilkymistPFPUState *s)

{

    uint32_t pc = s->regs[R_PC];

    uint32_t insn = s->microcode[pc];

    uint32_t reg_a = (insn >> 18) & 0x7f;

    uint32_t reg_b = (insn >> 11) & 0x7f;

    uint32_t op = (insn >> 7) & 0xf;

    uint32_t reg_d = insn & 0x7f;

    uint32_t r = 0;

    int latency = 0;

    switch (op) {

    case OP_NOP:

        break;

    case OP_FADD:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a + b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FADD;

        D_EXEC(qemu_log("ADD a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FSUB:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a - b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FSUB;

        D_EXEC(qemu_log("SUB a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FMUL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = a * b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FMUL;

        D_EXEC(qemu_log("MUL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_FABS:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float t = fabsf(a);

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_FABS;

        D_EXEC(qemu_log("ABS a=%f t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_F2I:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        int32_t t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_F2I;

        D_EXEC(qemu_log("F2I a=%f t=%d, r=%08x\n", a, t, r));

    } break;

    case OP_I2F:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_I2F;

        D_EXEC(qemu_log("I2F a=%08x t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_VECTOUT:

    {

        uint32_t a = cpu_to_be32(s->gp_regs[reg_a]);

        uint32_t b = cpu_to_be32(s->gp_regs[reg_b]);

        target_phys_addr_t dma_ptr =

            get_dma_address(s->regs[R_MESHBASE],

                    s->gp_regs[GPR_X], s->gp_regs[GPR_Y]);

        cpu_physical_memory_write(dma_ptr, (uint8_t *)&a, 4);

        cpu_physical_memory_write(dma_ptr + 4, (uint8_t *)&b, 4);

        s->regs[R_LASTDMA] = dma_ptr + 4;

        D_EXEC(qemu_log("VECTOUT a=%08x b=%08x dma=%08x\n", a, b, dma_ptr));

        trace_milkymist_pfpu_vectout(a, b, dma_ptr);

    } break;

    case OP_SIN:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = sinf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_SIN;

        D_EXEC(qemu_log("SIN a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_COS:

    {

        int32_t a = REINTERPRET_CAST(int32_t, s->gp_regs[reg_a]);

        float t = cosf(a * (1.0f / (M_PI * 4096.0f)));

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_COS;

        D_EXEC(qemu_log("COS a=%d t=%f, r=%08x\n", a, t, r));

    } break;

    case OP_ABOVE:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a > b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_ABOVE;

        D_EXEC(qemu_log("ABOVE a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_EQUAL:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (a == b) ? 1.0f : 0.0f;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_EQUAL;

        D_EXEC(qemu_log("EQUAL a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_COPY:

    {

        r = s->gp_regs[reg_a];

        latency = LATENCY_COPY;

        D_EXEC(qemu_log("COPY"));

    } break;

    case OP_IF:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        uint32_t f = s->gp_regs[GPR_FLAGS];

        float t = (f != 0) ? a : b;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_IF;

        D_EXEC(qemu_log("IF f=%u a=%f b=%f t=%f, r=%08x\n", f, a, b, t, r));

    } break;

    case OP_TSIGN:

    {

        float a = REINTERPRET_CAST(float, s->gp_regs[reg_a]);

        float b = REINTERPRET_CAST(float, s->gp_regs[reg_b]);

        float t = (b < 0) ? -a : a;

        r = REINTERPRET_CAST(uint32_t, t);

        latency = LATENCY_TSIGN;

        D_EXEC(qemu_log("TSIGN a=%f b=%f t=%f, r=%08x\n", a, b, t, r));

    } break;

    case OP_QUAKE:

    {

        uint32_t a = s->gp_regs[reg_a];

        r = 0x5f3759df - (a >> 1);

        latency = LATENCY_QUAKE;

        D_EXEC(qemu_log("QUAKE a=%d r=%08x\n", a, r));

    } break;

    default:

        error_report("milkymist_pfpu: unknown opcode %d", op);

        break;

    }

    if (!reg_d) {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d>\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency));

    } else {

        D_EXEC(qemu_log("%04d %8s R%03d, R%03d <L=%d, E=%04d> -> R%03d\n",

                    s->regs[R_PC], opcode_to_str[op], reg_a, reg_b, latency,

                    s->regs[R_PC] + latency, reg_d));

    }

    if (op == OP_VECTOUT) {

        return 0;

    }

    /* store output for this cycle */

    if (reg_d) {

        uint32_t val = output_queue_remove(s);

        D_EXEC(qemu_log("R%03d <- 0x%08x\n", reg_d, val));

        s->gp_regs[reg_d] = val;

    }

    output_queue_advance(s);

    /* store op output */

    if (op != OP_NOP) {

        output_queue_insert(s, r, latency-1);

    }

    /* advance PC */

    s->regs[R_PC]++;

    return 1;

};


static void eepro100_write(void *opaque, target_phys_addr_t addr,

                           uint64_t data, unsigned size)

{

    EEPRO100State *s = opaque;

    switch (size) {

    case 1:

        eepro100_write1(s, addr, data);

        break;

    case 2:

        eepro100_write2(s, addr, data);

        break;

    case 4:

        eepro100_write4(s, addr, data);

        break;

    default:

        abort();

    }

}


static uint8_t lsi_reg_readb(LSIState *s, int offset)

{

    uint8_t tmp;

#define CASE_GET_REG32(name, addr) \

    case addr: return s->name & 0xff; \

    case addr + 1: return (s->name >> 8) & 0xff; \

    case addr + 2: return (s->name >> 16) & 0xff; \

    case addr + 3: return (s->name >> 24) & 0xff;

#ifdef DEBUG_LSI_REG

    DPRINTF("Read reg %x\n", offset);

#endif

    switch (offset) {

    case 0x00: /* SCNTL0 */

        return s->scntl0;

    case 0x01: /* SCNTL1 */

        return s->scntl1;

    case 0x02: /* SCNTL2 */

        return s->scntl2;

    case 0x03: /* SCNTL3 */

        return s->scntl3;

    case 0x04: /* SCID */

        return s->scid;

    case 0x05: /* SXFER */

        return s->sxfer;

    case 0x06: /* SDID */

        return s->sdid;

    case 0x07: /* GPREG0 */

        return 0x7f;

    case 0x08: /* Revision ID */

        return 0x00;

    case 0xa: /* SSID */

        return s->ssid;

    case 0xb: /* SBCL */

        /* ??? This is not correct. However it's (hopefully) only

           used for diagnostics, so should be ok.  */

        return 0;

    case 0xc: /* DSTAT */

        tmp = s->dstat | 0x80;

        if ((s->istat0 & LSI_ISTAT0_INTF) == 0)

            s->dstat = 0;

        lsi_update_irq(s);

        return tmp;

    case 0x0d: /* SSTAT0 */

        return s->sstat0;

    case 0x0e: /* SSTAT1 */

        return s->sstat1;

    case 0x0f: /* SSTAT2 */

        return s->scntl1 & LSI_SCNTL1_CON ? 0 : 2;

    CASE_GET_REG32(dsa, 0x10)

    case 0x14: /* ISTAT0 */

        return s->istat0;

    case 0x16: /* MBOX0 */

        return s->mbox0;

    case 0x17: /* MBOX1 */

        return s->mbox1;

    case 0x18: /* CTEST0 */

        return 0xff;

    case 0x19: /* CTEST1 */

        return 0;

    case 0x1a: /* CTEST2 */

        tmp = LSI_CTEST2_DACK | LSI_CTEST2_CM;

        if (s->istat0 & LSI_ISTAT0_SIGP) {

            s->istat0 &= ~LSI_ISTAT0_SIGP;

            tmp |= LSI_CTEST2_SIGP;

        }

        return tmp;

    case 0x1b: /* CTEST3 */

        return s->ctest3;

    CASE_GET_REG32(temp, 0x1c)

    case 0x20: /* DFIFO */

        return 0;

    case 0x21: /* CTEST4 */

        return s->ctest4;

    case 0x22: /* CTEST5 */

        return s->ctest5;

    case 0x23: /* CTEST6 */

         return 0;

    case 0x24: /* DBC[0:7] */

        return s->dbc & 0xff;

    case 0x25: /* DBC[8:15] */

        return (s->dbc >> 8) & 0xff;

    case 0x26: /* DBC[16->23] */

        return (s->dbc >> 16) & 0xff;

    case 0x27: /* DCMD */

        return s->dcmd;

    CASE_GET_REG32(dsp, 0x2c)

    CASE_GET_REG32(dsps, 0x30)

    CASE_GET_REG32(scratch[0], 0x34)

    case 0x38: /* DMODE */

        return s->dmode;

    case 0x39: /* DIEN */

        return s->dien;

    case 0x3b: /* DCNTL */

        return s->dcntl;

    case 0x40: /* SIEN0 */

        return s->sien0;

    case 0x41: /* SIEN1 */

        return s->sien1;

    case 0x42: /* SIST0 */

        tmp = s->sist0;

        s->sist0 = 0;

        lsi_update_irq(s);

        return tmp;

    case 0x43: /* SIST1 */

        tmp = s->sist1;

        s->sist1 = 0;

        lsi_update_irq(s);

        return tmp;

    case 0x47: /* GPCNTL0 */

        return 0x0f;

    case 0x48: /* STIME0 */

        return s->stime0;

    case 0x4a: /* RESPID0 */

        return s->respid0;

    case 0x4b: /* RESPID1 */

        return s->respid1;

    case 0x4d: /* STEST1 */

        return s->stest1;

    case 0x4e: /* STEST2 */

        return s->stest2;

    case 0x4f: /* STEST3 */

        return s->stest3;

    case 0x50: /* SIDL */

        /* This is needed by the linux drivers.  We currently only update it

           during the MSG IN phase.  */

        return s->sidl;

    case 0x52: /* STEST4 */

        return 0xe0;

    case 0x56: /* CCNTL0 */

        return s->ccntl0;

    case 0x57: /* CCNTL1 */

        return s->ccntl1;

    case 0x58: /* SBDL */

        /* Some drivers peek at the data bus during the MSG IN phase.  */

        if ((s->sstat1 & PHASE_MASK) == PHASE_MI)

            return s->msg[0];

        return 0;

    case 0x59: /* SBDL high */

        return 0;

    CASE_GET_REG32(mmrs, 0xa0)

    CASE_GET_REG32(mmws, 0xa4)

    CASE_GET_REG32(sfs, 0xa8)

    CASE_GET_REG32(drs, 0xac)

    CASE_GET_REG32(sbms, 0xb0)

    CASE_GET_REG32(dmbs, 0xb4)

    CASE_GET_REG32(dnad64, 0xb8)

    CASE_GET_REG32(pmjad1, 0xc0)

    CASE_GET_REG32(pmjad2, 0xc4)

    CASE_GET_REG32(rbc, 0xc8)

    CASE_GET_REG32(ua, 0xcc)

    CASE_GET_REG32(ia, 0xd4)

    CASE_GET_REG32(sbc, 0xd8)

    CASE_GET_REG32(csbc, 0xdc)

    }

    if (offset >= 0x5c && offset < 0xa0) {

        int n;

        int shift;

        n = (offset - 0x58) >> 2;

        shift = (offset & 3) * 8;

        return (s->scratch[n] >> shift) & 0xff;

    }

    BADF("readb 0x%x\n", offset);

    exit(1);

#undef CASE_GET_REG32

}


void HELPER(mtspr)(CPUOpenRISCState *env,

                   target_ulong ra, target_ulong rb, target_ulong offset)

{

#ifndef CONFIG_USER_ONLY

    int spr = (ra | offset);

    int idx;

    OpenRISCCPU *cpu = openrisc_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    switch (spr) {

    case TO_SPR(0, 0): /* VR */

        env->vr = rb;

        break;

    case TO_SPR(0, 16): /* NPC */

        env->npc = rb;

        break;

    case TO_SPR(0, 17): /* SR */

        if ((env->sr & (SR_IME | SR_DME | SR_SM)) ^

            (rb & (SR_IME | SR_DME | SR_SM))) {

            tlb_flush(env, 1);

        }

        env->sr = rb;

        env->sr |= SR_FO;      /* FO is const equal to 1 */

        if (env->sr & SR_DME) {

            env->tlb->cpu_openrisc_map_address_data =

                &cpu_openrisc_get_phys_data;

        } else {

            env->tlb->cpu_openrisc_map_address_data =

                &cpu_openrisc_get_phys_nommu;

        }

        if (env->sr & SR_IME) {

            env->tlb->cpu_openrisc_map_address_code =

                &cpu_openrisc_get_phys_code;

        } else {

            env->tlb->cpu_openrisc_map_address_code =

                &cpu_openrisc_get_phys_nommu;

        }

        break;

    case TO_SPR(0, 18): /* PPC */

        env->ppc = rb;

        break;

    case TO_SPR(0, 32): /* EPCR */

        env->epcr = rb;

        break;

    case TO_SPR(0, 48): /* EEAR */

        env->eear = rb;

        break;

    case TO_SPR(0, 64): /* ESR */

        env->esr = rb;

        break;

    case TO_SPR(1, 512) ... TO_SPR(1, 639): /* DTLBW0MR 0-127 */

        idx = spr - TO_SPR(1, 512);

        if (!(rb & 1)) {

            tlb_flush_page(env, env->tlb->dtlb[0][idx].mr & TARGET_PAGE_MASK);

        }

        env->tlb->dtlb[0][idx].mr = rb;

        break;

    case TO_SPR(1, 640) ... TO_SPR(1, 767): /* DTLBW0TR 0-127 */

        idx = spr - TO_SPR(1, 640);

        env->tlb->dtlb[0][idx].tr = rb;

        break;

    case TO_SPR(1, 768) ... TO_SPR(1, 895):   /* DTLBW1MR 0-127 */

    case TO_SPR(1, 896) ... TO_SPR(1, 1023):  /* DTLBW1TR 0-127 */

    case TO_SPR(1, 1024) ... TO_SPR(1, 1151): /* DTLBW2MR 0-127 */

    case TO_SPR(1, 1152) ... TO_SPR(1, 1279): /* DTLBW2TR 0-127 */

    case TO_SPR(1, 1280) ... TO_SPR(1, 1407): /* DTLBW3MR 0-127 */

    case TO_SPR(1, 1408) ... TO_SPR(1, 1535): /* DTLBW3TR 0-127 */

        break;

    case TO_SPR(2, 512) ... TO_SPR(2, 639):   /* ITLBW0MR 0-127 */

        idx = spr - TO_SPR(2, 512);

        if (!(rb & 1)) {

            tlb_flush_page(env, env->tlb->itlb[0][idx].mr & TARGET_PAGE_MASK);

        }

        env->tlb->itlb[0][idx].mr = rb;

        break;

    case TO_SPR(2, 640) ... TO_SPR(2, 767): /* ITLBW0TR 0-127 */

        idx = spr - TO_SPR(2, 640);

        env->tlb->itlb[0][idx].tr = rb;

        break;

    case TO_SPR(2, 768) ... TO_SPR(2, 895):   /* ITLBW1MR 0-127 */

    case TO_SPR(2, 896) ... TO_SPR(2, 1023):  /* ITLBW1TR 0-127 */

    case TO_SPR(2, 1024) ... TO_SPR(2, 1151): /* ITLBW2MR 0-127 */

    case TO_SPR(2, 1152) ... TO_SPR(2, 1279): /* ITLBW2TR 0-127 */

    case TO_SPR(2, 1280) ... TO_SPR(2, 1407): /* ITLBW3MR 0-127 */

    case TO_SPR(2, 1408) ... TO_SPR(2, 1535): /* ITLBW3TR 0-127 */

        break;

    case TO_SPR(9, 0):  /* PICMR */

        env->picmr |= rb;

        break;

    case TO_SPR(9, 2):  /* PICSR */

        env->picsr &= ~rb;

        break;

    case TO_SPR(10, 0): /* TTMR */

        {

            if ((env->ttmr & TTMR_M) ^ (rb & TTMR_M)) {

                switch (rb & TTMR_M) {

                case TIMER_NONE:

                    cpu_openrisc_count_stop(cpu);

                    break;

                case TIMER_INTR:

                case TIMER_SHOT:

                case TIMER_CONT:

                    cpu_openrisc_count_start(cpu);

                    break;

                default:

                    break;

                }

            }

            int ip = env->ttmr & TTMR_IP;

            if (rb & TTMR_IP) {    /* Keep IP bit.  */

                env->ttmr = (rb & ~TTMR_IP) | ip;

            } else {    /* Clear IP bit.  */

                env->ttmr = rb & ~TTMR_IP;

                cs->interrupt_request &= ~CPU_INTERRUPT_TIMER;

            }

            cpu_openrisc_timer_update(cpu);

        }

        break;

    case TO_SPR(10, 1): /* TTCR */

        env->ttcr = rb;

        if (env->ttmr & TIMER_NONE) {

            return;

        }

        cpu_openrisc_timer_update(cpu);

        break;

    default:

        break;

    }

#endif

}


static int asf_probe(AVProbeData *pd)

{

    /* check file header */

    if (pd->buf_size <= 32)

        return 0;

    if (!memcmp(pd->buf, &asf_header, sizeof(GUID)))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static inline TCGv gen_ld8s(TCGv addr, int index)

{

    TCGv tmp = new_tmp();

    tcg_gen_qemu_ld8s(tmp, addr, index);

    return tmp;

}


static int write_adaptation_set(AVFormatContext *s, int as_index)

{

    WebMDashMuxContext *w = s->priv_data;

    AdaptationSet *as = &w->as[as_index];

    AVCodecContext *codec = s->streams[as->streams[0]]->codec;

    AVDictionaryEntry *lang;

    int i;

    static const char boolean[2][6] = { "false", "true" };

    int subsegmentStartsWithSAP = 1;

    // Width, Height and Sample Rate will go in the AdaptationSet tag if they

    // are the same for all contained Representations. otherwise, they will go

    // on their respective Representation tag. For live streams, they always go

    // in the Representation tag.

    int width_in_as = 1, height_in_as = 1, sample_rate_in_as = 1;

    if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {

      width_in_as = !w->is_live && check_matching_width(s, as);

      height_in_as = !w->is_live && check_matching_height(s, as);

    } else {

      sample_rate_in_as = !w->is_live && check_matching_sample_rate(s, as);

    }

    avio_printf(s->pb, "<AdaptationSet id=\"%s\"", as->id);

    avio_printf(s->pb, " mimeType=\"%s/webm\"",

                codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");

    avio_printf(s->pb, " codecs=\"%s\"", get_codec_name(codec->codec_id));

    lang = av_dict_get(s->streams[as->streams[0]]->metadata, "language", NULL, 0);

    if (lang) avio_printf(s->pb, " lang=\"%s\"", lang->value);

    if (codec->codec_type == AVMEDIA_TYPE_VIDEO && width_in_as)

        avio_printf(s->pb, " width=\"%d\"", codec->width);

    if (codec->codec_type == AVMEDIA_TYPE_VIDEO && height_in_as)

        avio_printf(s->pb, " height=\"%d\"", codec->height);

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO && sample_rate_in_as)

        avio_printf(s->pb, " audioSamplingRate=\"%d\"", codec->sample_rate);

    avio_printf(s->pb, " bitstreamSwitching=\"%s\"",

                boolean[bitstream_switching(s, as)]);

    avio_printf(s->pb, " subsegmentAlignment=\"%s\"",

                boolean[w->is_live || subsegment_alignment(s, as)]);

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

        AVDictionaryEntry *kf = av_dict_get(s->streams[as->streams[i]]->metadata,

                                            CLUSTER_KEYFRAME, NULL, 0);

        if (!w->is_live && (!kf || !strncmp(kf->value, "0", 1))) subsegmentStartsWithSAP = 0;

    }

    avio_printf(s->pb, " subsegmentStartsWithSAP=\"%d\"", subsegmentStartsWithSAP);

    avio_printf(s->pb, ">\n");

    if (w->is_live) {

        AVDictionaryEntry *filename =

            av_dict_get(s->streams[as->streams[0]]->metadata, FILENAME, NULL, 0);

        char *initialization_pattern = NULL;

        char *media_pattern = NULL;

        int ret = parse_filename(filename->value, NULL, &initialization_pattern,

                                 &media_pattern);

        if (ret) return ret;

        avio_printf(s->pb, "<ContentComponent id=\"1\" type=\"%s\"/>\n",

                    codec->codec_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");

        avio_printf(s->pb, "<SegmentTemplate");

        avio_printf(s->pb, " timescale=\"1000\"");

        avio_printf(s->pb, " duration=\"%d\"", w->chunk_duration);

        avio_printf(s->pb, " media=\"%s\"", media_pattern);

        avio_printf(s->pb, " startNumber=\"%d\"", w->chunk_start_index);

        avio_printf(s->pb, " initialization=\"%s\"", initialization_pattern);

        avio_printf(s->pb, "/>\n");

        av_free(initialization_pattern);

        av_free(media_pattern);

    }

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

        char *representation_id = NULL;

        int ret;

        if (w->is_live) {

            AVDictionaryEntry *filename =

                av_dict_get(s->streams[as->streams[i]]->metadata, FILENAME, NULL, 0);

            if (!filename ||

                (ret = parse_filename(filename->value, &representation_id, NULL, NULL))) {

                return ret;

            }

        } else {

            representation_id = av_asprintf("%d", w->representation_id++);

            if (!representation_id) return AVERROR(ENOMEM);

        }

        ret = write_representation(s, s->streams[as->streams[i]],

                                   representation_id, !width_in_as,

                                   !height_in_as, !sample_rate_in_as);

        if (ret) return ret;

        av_free(representation_id);

    }

    avio_printf(s->pb, "</AdaptationSet>\n");

    return 0;

}


static void usbredir_handle_bulk_data(USBRedirDevice *dev, USBPacket *p,

                                      uint8_t ep)

{

    struct usb_redir_bulk_packet_header bulk_packet;

    size_t size = (p->combined) ? p->combined->iov.size : p->iov.size;

    DPRINTF("bulk-out ep %02X len %zd id %"PRIu64"\n", ep, size, p->id);

    if (usbredir_already_in_flight(dev, p->id)) {

        p->status = USB_RET_ASYNC;

        return;

    }

    bulk_packet.endpoint  = ep;

    bulk_packet.length    = size;

    bulk_packet.stream_id = 0;

    bulk_packet.length_high = size >> 16;

    assert(bulk_packet.length_high == 0 ||

           usbredirparser_peer_has_cap(dev->parser,

                                       usb_redir_cap_32bits_bulk_length));

    if (ep & USB_DIR_IN) {

        usbredirparser_send_bulk_packet(dev->parser, p->id,

                                        &bulk_packet, NULL, 0);

    } else {

        uint8_t buf[size];

        if (p->combined) {

            iov_to_buf(p->combined->iov.iov, p->combined->iov.niov,

                       0, buf, size);

        } else {

            usb_packet_copy(p, buf, size);

        }

        usbredir_log_data(dev, "bulk data out:", buf, size);

        usbredirparser_send_bulk_packet(dev->parser, p->id,

                                        &bulk_packet, buf, size);

    }

    usbredirparser_do_write(dev->parser);

    p->status = USB_RET_ASYNC;

}


static ExitStatus trans_fop_dedd(DisasContext *ctx, uint32_t insn,

                                 const DisasInsn *di)

{

    unsigned rt = extract32(insn, 0, 5);

    unsigned rb = extract32(insn, 16, 5);

    unsigned ra = extract32(insn, 21, 5);

    return do_fop_dedd(ctx, rt, ra, rb, di->f_dedd);

}


static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,

                            enum AVCodecID codec_id)

{

    AVCodecContext *c;

    AVStream *st;

    /* find the encoder */

    *codec = avcodec_find_encoder(codec_id);

    if (!(*codec)) {

        fprintf(stderr, "Could not find encoder for '%s'\n",

                avcodec_get_name(codec_id));

        exit(1);

    }

    st = avformat_new_stream(oc, *codec);

    if (!st) {

        fprintf(stderr, "Could not allocate stream\n");

        exit(1);

    }

    st->id = oc->nb_streams-1;

    c = st->codec;

    switch ((*codec)->type) {

    case AVMEDIA_TYPE_AUDIO:

        st->id = 1;

        c->sample_fmt  = AV_SAMPLE_FMT_S16;

        c->bit_rate    = 64000;

        c->sample_rate = 44100;

        c->channels    = 2;

        break;

    case AVMEDIA_TYPE_VIDEO:

        avcodec_get_context_defaults3(c, *codec);

        c->codec_id = codec_id;

        c->bit_rate = 400000;

        /* Resolution must be a multiple of two. */

        c->width    = 352;

        c->height   = 288;

        /* timebase: This is the fundamental unit of time (in seconds) in terms

         * of which frame timestamps are represented. For fixed-fps content,

         * timebase should be 1/framerate and timestamp increments should be

         * identical to 1. */

        c->time_base.den = STREAM_FRAME_RATE;

        c->time_base.num = 1;

        c->gop_size      = 12; /* emit one intra frame every twelve frames at most */

        c->pix_fmt       = STREAM_PIX_FMT;

        if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

            /* just for testing, we also add B frames */

            c->max_b_frames = 2;

        }

        if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {

            /* Needed to avoid using macroblocks in which some coeffs overflow.

             * This does not happen with normal video, it just happens here as

             * the motion of the chroma plane does not match the luma plane. */

            c->mb_decision = 2;

        }

    break;

    default:

        break;

    }

    /* Some formats want stream headers to be separate. */

    if (oc->oformat->flags & AVFMT_GLOBALHEADER)

        c->flags |= CODEC_FLAG_GLOBAL_HEADER;

    return st;

}