CPUState *cpu_mb_init (const char *cpu_model)

{

    CPUState *env;

    static int tcg_initialized = 0;

    int i;

    env = qemu_mallocz(sizeof(CPUState));

    cpu_exec_init(env);

    cpu_reset(env);

    env->pvr.regs[0] = PVR0_PVR_FULL_MASK \

                       | PVR0_USE_BARREL_MASK \

                       | PVR0_USE_DIV_MASK \

                       | PVR0_USE_HW_MUL_MASK \

                       | PVR0_USE_EXC_MASK \

                       | PVR0_USE_ICACHE_MASK \

                       | PVR0_USE_DCACHE_MASK \

                       | PVR0_USE_MMU \

                       | (0xb << 8);

    env->pvr.regs[2] = PVR2_D_OPB_MASK \

                        | PVR2_D_LMB_MASK \

                        | PVR2_I_OPB_MASK \

                        | PVR2_I_LMB_MASK \

                        | PVR2_USE_MSR_INSTR \

                        | PVR2_USE_PCMP_INSTR \

                        | PVR2_USE_BARREL_MASK \

                        | PVR2_USE_DIV_MASK \

                        | PVR2_USE_HW_MUL_MASK \

                        | PVR2_USE_MUL64_MASK \

                        | 0;

    env->pvr.regs[10] = 0x0c000000; /* Default to spartan 3a dsp family.  */

    env->pvr.regs[11] = PVR11_USE_MMU | (16 << 17);

#if !defined(CONFIG_USER_ONLY)

    env->mmu.c_mmu = 3;

    env->mmu.c_mmu_tlb_access = 3;

    env->mmu.c_mmu_zones = 16;

#endif

    if (tcg_initialized)

        return env;

    tcg_initialized = 1;

    cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");

    env_debug = tcg_global_mem_new(TCG_AREG0,

                    offsetof(CPUState, debug),

                    "debug0");

    env_iflags = tcg_global_mem_new(TCG_AREG0,

                    offsetof(CPUState, iflags),

                    "iflags");

    env_imm = tcg_global_mem_new(TCG_AREG0,

                    offsetof(CPUState, imm),

                    "imm");

    env_btarget = tcg_global_mem_new(TCG_AREG0,

                     offsetof(CPUState, btarget),

                     "btarget");

    env_btaken = tcg_global_mem_new(TCG_AREG0,

                     offsetof(CPUState, btaken),

                     "btaken");

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

        cpu_R[i] = tcg_global_mem_new(TCG_AREG0,

                          offsetof(CPUState, regs[i]),

                          regnames[i]);

    }

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

        cpu_SR[i] = tcg_global_mem_new(TCG_AREG0,

                          offsetof(CPUState, sregs[i]),

                          special_regnames[i]);

    }

#define GEN_HELPER 2

#include "helper.h"

    return env;

}


int cpu_x86_exec(CPUX86State *env1)

{

    int saved_T0, saved_T1, saved_A0;

    CPUX86State *saved_env;

#ifdef reg_EAX

    int saved_EAX;

#endif

#ifdef reg_ECX

    int saved_ECX;

#endif

#ifdef reg_EDX

    int saved_EDX;

#endif

#ifdef reg_EBX

    int saved_EBX;

#endif

#ifdef reg_ESP

    int saved_ESP;

#endif

#ifdef reg_EBP

    int saved_EBP;

#endif

#ifdef reg_ESI

    int saved_ESI;

#endif

#ifdef reg_EDI

    int saved_EDI;

#endif

#ifdef __sparc__

    int saved_i7, tmp_T0;

#endif

    int code_gen_size, ret;

    void (*gen_func)(void);

    TranslationBlock *tb, **ptb;

    uint8_t *tc_ptr, *cs_base, *pc;

    unsigned int flags;

    /* first we save global registers */

    saved_T0 = T0;

    saved_T1 = T1;

    saved_A0 = A0;

    saved_env = env;

    env = env1;

#ifdef reg_EAX

    saved_EAX = EAX;

    EAX = env->regs[R_EAX];

#endif

#ifdef reg_ECX

    saved_ECX = ECX;

    ECX = env->regs[R_ECX];

#endif

#ifdef reg_EDX

    saved_EDX = EDX;

    EDX = env->regs[R_EDX];

#endif

#ifdef reg_EBX

    saved_EBX = EBX;

    EBX = env->regs[R_EBX];

#endif

#ifdef reg_ESP

    saved_ESP = ESP;

    ESP = env->regs[R_ESP];

#endif

#ifdef reg_EBP

    saved_EBP = EBP;

    EBP = env->regs[R_EBP];

#endif

#ifdef reg_ESI

    saved_ESI = ESI;

    ESI = env->regs[R_ESI];

#endif

#ifdef reg_EDI

    saved_EDI = EDI;

    EDI = env->regs[R_EDI];

#endif

#ifdef __sparc__

    /* we also save i7 because longjmp may not restore it */

    asm volatile ("mov %%i7, %0" : "=r" (saved_i7));

#endif

    /* put eflags in CPU temporary format */

    CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    DF = 1 - (2 * ((env->eflags >> 10) & 1));

    CC_OP = CC_OP_EFLAGS;

    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    env->interrupt_request = 0;

    /* prepare setjmp context for exception handling */

    if (setjmp(env->jmp_env) == 0) {

        T0 = 0; /* force lookup of first TB */

        for(;;) {

#ifdef __sparc__

	  /* g1 can be modified by some libc? functions */

	    tmp_T0 = T0;

#endif

            if (env->interrupt_request) {

                env->exception_index = EXCP_INTERRUPT;

                cpu_loop_exit();

            }

#ifdef DEBUG_EXEC

            if (loglevel) {

                /* XXX: save all volatile state in cpu state */

                /* restore flags in standard format */

                env->regs[R_EAX] = EAX;

                env->regs[R_EBX] = EBX;

                env->regs[R_ECX] = ECX;

                env->regs[R_EDX] = EDX;

                env->regs[R_ESI] = ESI;

                env->regs[R_EDI] = EDI;

                env->regs[R_EBP] = EBP;

                env->regs[R_ESP] = ESP;

                env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);

                cpu_x86_dump_state(env, logfile, 0);

                env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

            }

#endif

            /* we compute the CPU state. We assume it will not

               change during the whole generated block. */

            flags = env->seg_cache[R_CS].seg_32bit << GEN_FLAG_CODE32_SHIFT;

            flags |= env->seg_cache[R_SS].seg_32bit << GEN_FLAG_SS32_SHIFT;

            flags |= (((unsigned long)env->seg_cache[R_DS].base |

                       (unsigned long)env->seg_cache[R_ES].base |

                       (unsigned long)env->seg_cache[R_SS].base) != 0) <<

                GEN_FLAG_ADDSEG_SHIFT;

            if (!(env->eflags & VM_MASK)) {

                flags |= (env->segs[R_CS] & 3) << GEN_FLAG_CPL_SHIFT;

            } else {

                /* NOTE: a dummy CPL is kept */

                flags |= (1 << GEN_FLAG_VM_SHIFT);

                flags |= (3 << GEN_FLAG_CPL_SHIFT);

            }

            flags |= (env->eflags & (IOPL_MASK | TF_MASK));

            cs_base = env->seg_cache[R_CS].base;

            pc = cs_base + env->eip;

            tb = tb_find(&ptb, (unsigned long)pc, (unsigned long)cs_base,

                         flags);

            if (!tb) {

                spin_lock(&tb_lock);

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

                tb = tb_alloc((unsigned long)pc);

                if (!tb) {

                    /* flush must be done */

                    tb_flush();

                    /* cannot fail at this point */

                    tb = tb_alloc((unsigned long)pc);

                    /* don't forget to invalidate previous TB info */

                    ptb = &tb_hash[tb_hash_func((unsigned long)pc)];

                    T0 = 0;

                }

                tc_ptr = code_gen_ptr;

                tb->tc_ptr = tc_ptr;

                tb->cs_base = (unsigned long)cs_base;

                tb->flags = flags;

                ret = cpu_x86_gen_code(tb, CODE_GEN_MAX_SIZE, &code_gen_size);

                /* if invalid instruction, signal it */

                if (ret != 0) {

                    /* NOTE: the tb is allocated but not linked, so we

                       can leave it */

                    spin_unlock(&tb_lock);

                    raise_exception(EXCP06_ILLOP);

                }

                *ptb = tb;

                tb->hash_next = NULL;

                tb_link(tb);

                code_gen_ptr = (void *)(((unsigned long)code_gen_ptr + code_gen_size + CODE_GEN_ALIGN - 1) & ~(CODE_GEN_ALIGN - 1));

                spin_unlock(&tb_lock);

            }

#ifdef DEBUG_EXEC

	    if (loglevel) {

		fprintf(logfile, "Trace 0x%08lx [0x%08lx] %s\n",

			(long)tb->tc_ptr, (long)tb->pc,

			lookup_symbol((void *)tb->pc));

	    }

#endif

#ifdef __sparc__

	    T0 = tmp_T0;

#endif

            /* see if we can patch the calling TB */

            if (T0 != 0 && !(env->eflags & TF_MASK)) {

                spin_lock(&tb_lock);

                tb_add_jump((TranslationBlock *)(T0 & ~3), T0 & 3, tb);

                spin_unlock(&tb_lock);

            }

            tc_ptr = tb->tc_ptr;

            /* execute the generated code */

            gen_func = (void *)tc_ptr;

#if defined(__sparc__)

	    __asm__ __volatile__("call	%0\n\t"

				 "mov	%%o7,%%i0"

				 : /* no outputs */

				 : "r" (gen_func)

				 : "i0", "i1", "i2", "i3", "i4", "i5");

#elif defined(__arm__)

            asm volatile ("mov pc, %0\n\t"

                          ".global exec_loop\n\t"

                          "exec_loop:\n\t"

                          : /* no outputs */

                          : "r" (gen_func)

                          : "r1", "r2", "r3", "r8", "r9", "r10", "r12", "r14");

#else

            gen_func();

#endif

        }

    }

    ret = env->exception_index;

    /* restore flags in standard format */

    env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);

    /* restore global registers */

#ifdef reg_EAX

    EAX = saved_EAX;

#endif

#ifdef reg_ECX

    ECX = saved_ECX;

#endif

#ifdef reg_EDX

    EDX = saved_EDX;

#endif

#ifdef reg_EBX

    EBX = saved_EBX;

#endif

#ifdef reg_ESP

    ESP = saved_ESP;

#endif

#ifdef reg_EBP

    EBP = saved_EBP;

#endif

#ifdef reg_ESI

    ESI = saved_ESI;

#endif

#ifdef reg_EDI

    EDI = saved_EDI;

#endif

#ifdef __sparc__

    asm volatile ("mov %0, %%i7" : : "r" (saved_i7));

#endif

    T0 = saved_T0;

    T1 = saved_T1;

    A0 = saved_A0;

    env = saved_env;

    return ret;

}


void s390_pci_sclp_configure(SCCB *sccb)

{

    PciCfgSccb *psccb = (PciCfgSccb *)sccb;

    S390PCIBusDevice *pbdev = s390_pci_find_dev_by_fid(be32_to_cpu(psccb->aid));

    uint16_t rc;

    if (be16_to_cpu(sccb->h.length) < 16) {

        rc = SCLP_RC_INSUFFICIENT_SCCB_LENGTH;

        goto out;

    }

    if (pbdev) {

        if (pbdev->configured) {

            rc = SCLP_RC_NO_ACTION_REQUIRED;

        } else {

            pbdev->configured = true;

            rc = SCLP_RC_NORMAL_COMPLETION;

        }

    } else {

        DPRINTF("sclp config no dev found\n");

        rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;

    }

out:

    psccb->header.response_code = cpu_to_be16(rc);

}


static BlockJob *find_block_job(const char *device)

{

    BlockDriverState *bs;

    bs = bdrv_find(device);

    if (!bs || !bs->job) {

        return NULL;

    }

    return bs->job;

}


static void usb_host_realize(USBDevice *udev, Error **errp)

{

    USBHostDevice *s = USB_HOST_DEVICE(udev);

    if (s->match.vendor_id > 0xffff) {

        error_setg(errp, "vendorid out of range");

        return;

    }

    if (s->match.product_id > 0xffff) {

        error_setg(errp, "productid out of range");

        return;

    }

    if (s->match.addr > 127) {

        error_setg(errp, "hostaddr out of range");

        return;

    }

    loglevel = s->loglevel;

    udev->flags |= (1 << USB_DEV_FLAG_IS_HOST);

    udev->auto_attach = 0;

    QTAILQ_INIT(&s->requests);

    QTAILQ_INIT(&s->isorings);

    s->exit.notify = usb_host_exit_notifier;

    qemu_add_exit_notifier(&s->exit);

    QTAILQ_INSERT_TAIL(&hostdevs, s, next);

    usb_host_auto_check(NULL);

}


static void rtas_int_off(sPAPREnvironment *spapr, uint32_t token,

                         uint32_t nargs, target_ulong args,

                         uint32_t nret, target_ulong rets)

{

    struct ics_state *ics = spapr->icp->ics;

    uint32_t nr;

    if ((nargs != 1) || (nret != 1)) {

        rtas_st(rets, 0, -3);

        return;

    }

    nr = rtas_ld(args, 0);

    if (!ics_valid_irq(ics, nr)) {

        rtas_st(rets, 0, -3);

        return;

    }

    ics_write_xive(ics, nr, ics->irqs[nr - ics->offset].server, 0xff,

                   ics->irqs[nr - ics->offset].priority);

    rtas_st(rets, 0, 0); /* Success */

}


static void filter_mb_mbaff_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[7], int bsi, int qp ) {

    int index_a = qp + h->slice_alpha_c0_offset;

    int alpha = alpha_table[index_a];

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

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

    if( bS[0] < 4 ) {

        int8_t tc[4];

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

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

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

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

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

    } else {

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

    }

}


static uint32_t gic_dist_readb(void *opaque, target_phys_addr_t offset)

{

    GICState *s = (GICState *)opaque;

    uint32_t res;

    int irq;

    int i;

    int cpu;

    int cm;

    int mask;

    cpu = gic_get_current_cpu(s);

    cm = 1 << cpu;

    if (offset < 0x100) {

        if (offset == 0)

            return s->enabled;

        if (offset == 4)

            return ((s->num_irq / 32) - 1) | ((NUM_CPU(s) - 1) << 5);

        if (offset < 0x08)

            return 0;

        if (offset >= 0x80) {

            /* Interrupt Security , RAZ/WI */

            return 0;

        }

        goto bad_reg;

    } else if (offset < 0x200) {

        /* Interrupt Set/Clear Enable.  */

        if (offset < 0x180)

            irq = (offset - 0x100) * 8;

        else

            irq = (offset - 0x180) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_ENABLED(irq + i, cm)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Set/Clear Pending.  */

        if (offset < 0x280)

            irq = (offset - 0x200) * 8;

        else

            irq = (offset - 0x280) * 8;

        irq += GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (GIC_TEST_PENDING(irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        irq = (offset - 0x300) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

        mask = (irq < GIC_INTERNAL) ?  cm : ALL_CPU_MASK;

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

            if (GIC_TEST_ACTIVE(irq + i, mask)) {

                res |= (1 << i);

            }

        }

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = GIC_GET_PRIORITY(irq, cpu);

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target.  */

        if (s->num_cpu == 1 && s->revision != REV_11MPCORE) {

            /* For uniprocessor GICs these RAZ/WI */

            res = 0;

        } else {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq >= 29 && irq <= 31) {

                res = cm;

            } else {

                res = GIC_TARGET(irq);

            }

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 2 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        res = 0;

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

            if (GIC_TEST_MODEL(irq + i))

                res |= (1 << (i * 2));

            if (GIC_TEST_TRIGGER(irq + i))

                res |= (2 << (i * 2));

        }

    } else if (offset < 0xfe0) {

        goto bad_reg;

    } else /* offset >= 0xfe0 */ {

        if (offset & 3) {

            res = 0;

        } else {

            res = gic_id[(offset - 0xfe0) >> 2];

        }

    }

    return res;

bad_reg:

    hw_error("gic_dist_readb: Bad offset %x\n", (int)offset);

    return 0;

}


static void qmp_serialize(void *native_in, void **datap,

                          VisitorFunc visit, Error **errp)

{

    QmpSerializeData *d = g_malloc0(sizeof(*d));

    d->qov = qmp_output_visitor_new(&d->obj);

    visit(d->qov, &native_in, errp);

    *datap = d;

}


static void tcg_target_init(TCGContext *s)

{

    tcg_regset_set32(tcg_target_available_regs[TCG_TYPE_I32], 0, 0xffffffff);

    tcg_regset_set32(tcg_target_call_clobber_regs, 0,

                     (1 << TCG_REG_R0) |

#ifdef _CALL_DARWIN

                     (1 << TCG_REG_R2) |

#endif

                     (1 << TCG_REG_R3) |

                     (1 << TCG_REG_R4) |

                     (1 << TCG_REG_R5) |

                     (1 << TCG_REG_R6) |

                     (1 << TCG_REG_R7) |

                     (1 << TCG_REG_R8) |

                     (1 << TCG_REG_R9) |

                     (1 << TCG_REG_R10) |

                     (1 << TCG_REG_R11) |

                     (1 << TCG_REG_R12)

        );

    tcg_regset_clear(s->reserved_regs);

    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R0);

    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R1);

#ifndef _CALL_DARWIN

    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R2);

#endif

#ifdef _CALL_SYSV

    tcg_regset_set_reg(s->reserved_regs, TCG_REG_R13);

#endif

    tcg_add_target_add_op_defs(ppc_op_defs);

}


static void emulate_spapr_hypercall(PPCVirtualHypervisor *vhyp,
                                    PowerPCCPU *cpu)
{
    CPUPPCState *env = &cpu->env;
    if (msr_pr) {
        hcall_dprintf("Hypercall made with MSR[PR]=1\n");
        env->gpr[3] = H_PRIVILEGE;
    } else {
        env->gpr[3] = spapr_hypercall(cpu, env->gpr[3], &env->gpr[4]);
    }
}


test_opts_range_unvisited(void)

{

    intList *list = NULL;

    intList *tail;

    QemuOpts *opts;

    Visitor *v;

    opts = qemu_opts_parse(qemu_find_opts("userdef"), "ilist=0-2", false,

                           &error_abort);

    v = opts_visitor_new(opts);

    visit_start_struct(v, NULL, NULL, 0, &error_abort);

    /* Would be simpler if the visitor genuinely supported virtual walks */

    visit_start_list(v, "ilist", (GenericList **)&list, sizeof(*list),

                     &error_abort);

    tail = list;

    visit_type_int(v, NULL, &tail->value, &error_abort);

    g_assert_cmpint(tail->value, ==, 0);

    tail = (intList *)visit_next_list(v, (GenericList *)tail, sizeof(*list));

    g_assert(tail);

    visit_type_int(v, NULL, &tail->value, &error_abort);

    g_assert_cmpint(tail->value, ==, 1);

    tail = (intList *)visit_next_list(v, (GenericList *)tail, sizeof(*list));

    g_assert(tail);

    visit_check_list(v, &error_abort); /* BUG: unvisited tail not reported */

    visit_end_list(v, (void **)&list);

    visit_check_struct(v, &error_abort);

    visit_end_struct(v, NULL);

    qapi_free_intList(list);

    visit_free(v);

    qemu_opts_del(opts);

}


static int decode_subframe(WMAProDecodeCtx *s)

{

    int offset = s->samples_per_frame;

    int subframe_len = s->samples_per_frame;

    int i;

    int total_samples   = s->samples_per_frame * s->avctx->channels;

    int transmit_coeffs = 0;

    int cur_subwoofer_cutoff;

    s->subframe_offset = get_bits_count(&s->gb);

    /** reset channel context and find the next block offset and size

        == the next block of the channel with the smallest number of

        decoded samples

    */

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

        s->channel[i].grouped = 0;

        if (offset > s->channel[i].decoded_samples) {

            offset = s->channel[i].decoded_samples;

            subframe_len =

                s->channel[i].subframe_len[s->channel[i].cur_subframe];

        }

    }

    av_dlog(s->avctx,

            "processing subframe with offset %i len %i\n", offset, subframe_len);

    /** get a list of all channels that contain the estimated block */

    s->channels_for_cur_subframe = 0;

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

        const int cur_subframe = s->channel[i].cur_subframe;

        /** subtract already processed samples */

        total_samples -= s->channel[i].decoded_samples;

        /** and count if there are multiple subframes that match our profile */

        if (offset == s->channel[i].decoded_samples &&

            subframe_len == s->channel[i].subframe_len[cur_subframe]) {

            total_samples -= s->channel[i].subframe_len[cur_subframe];

            s->channel[i].decoded_samples +=

                s->channel[i].subframe_len[cur_subframe];

            s->channel_indexes_for_cur_subframe[s->channels_for_cur_subframe] = i;

            ++s->channels_for_cur_subframe;

        }

    }

    /** check if the frame will be complete after processing the

        estimated block */

    if (!total_samples)

        s->parsed_all_subframes = 1;

    av_dlog(s->avctx, "subframe is part of %i channels\n",

            s->channels_for_cur_subframe);

    /** calculate number of scale factor bands and their offsets */

    s->table_idx         = av_log2(s->samples_per_frame/subframe_len);

    s->num_bands         = s->num_sfb[s->table_idx];

    s->cur_sfb_offsets   = s->sfb_offsets[s->table_idx];

    cur_subwoofer_cutoff = s->subwoofer_cutoffs[s->table_idx];

    /** configure the decoder for the current subframe */

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

        int c = s->channel_indexes_for_cur_subframe[i];

        s->channel[c].coeffs = &s->channel[c].out[(s->samples_per_frame >> 1)

                                                  + offset];

    }

    s->subframe_len = subframe_len;

    s->esc_len = av_log2(s->subframe_len - 1) + 1;

    /** skip extended header if any */

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

        int num_fill_bits;

        if (!(num_fill_bits = get_bits(&s->gb, 2))) {

            int len = get_bits(&s->gb, 4);

            num_fill_bits = get_bits(&s->gb, len) + 1;

        }

        if (num_fill_bits >= 0) {

            if (get_bits_count(&s->gb) + num_fill_bits > s->num_saved_bits) {

                av_log(s->avctx, AV_LOG_ERROR, "invalid number of fill bits\n");

                return AVERROR_INVALIDDATA;

            }

            skip_bits_long(&s->gb, num_fill_bits);

        }

    }

    /** no idea for what the following bit is used */

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

        avpriv_request_sample(s->avctx, "Reserved bit");

        return AVERROR_PATCHWELCOME;

    }

    if (decode_channel_transform(s) < 0)

        return AVERROR_INVALIDDATA;

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

        int c = s->channel_indexes_for_cur_subframe[i];

        if ((s->channel[c].transmit_coefs = get_bits1(&s->gb)))

            transmit_coeffs = 1;

    }

    if (transmit_coeffs) {

        int step;

        int quant_step = 90 * s->bits_per_sample >> 4;

        /** decode number of vector coded coefficients */

        if ((s->transmit_num_vec_coeffs = get_bits1(&s->gb))) {

            int num_bits = av_log2((s->subframe_len + 3)/4) + 1;

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

                int c = s->channel_indexes_for_cur_subframe[i];

                int num_vec_coeffs = get_bits(&s->gb, num_bits) << 2;

                if (num_vec_coeffs > WMAPRO_BLOCK_MAX_SIZE) {

                    av_log(s->avctx, AV_LOG_ERROR, "num_vec_coeffs %d is too large\n", num_vec_coeffs);

                    return AVERROR_INVALIDDATA;

                }

                s->channel[c].num_vec_coeffs = num_vec_coeffs;

            }

        } else {

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

                int c = s->channel_indexes_for_cur_subframe[i];

                s->channel[c].num_vec_coeffs = s->subframe_len;

            }

        }

        /** decode quantization step */

        step = get_sbits(&s->gb, 6);

        quant_step += step;

        if (step == -32 || step == 31) {

            const int sign = (step == 31) - 1;

            int quant = 0;

            while (get_bits_count(&s->gb) + 5 < s->num_saved_bits &&

                   (step = get_bits(&s->gb, 5)) == 31) {

                quant += 31;

            }

            quant_step += ((quant + step) ^ sign) - sign;

        }

        if (quant_step < 0) {

            av_log(s->avctx, AV_LOG_DEBUG, "negative quant step\n");

        }

        /** decode quantization step modifiers for every channel */

        if (s->channels_for_cur_subframe == 1) {

            s->channel[s->channel_indexes_for_cur_subframe[0]].quant_step = quant_step;

        } else {

            int modifier_len = get_bits(&s->gb, 3);

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

                int c = s->channel_indexes_for_cur_subframe[i];

                s->channel[c].quant_step = quant_step;

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

                    if (modifier_len) {

                        s->channel[c].quant_step += get_bits(&s->gb, modifier_len) + 1;

                    } else

                        ++s->channel[c].quant_step;

                }

            }

        }

        /** decode scale factors */

        if (decode_scale_factors(s) < 0)

            return AVERROR_INVALIDDATA;

    }

    av_dlog(s->avctx, "BITSTREAM: subframe header length was %i\n",

            get_bits_count(&s->gb) - s->subframe_offset);

    /** parse coefficients */

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

        int c = s->channel_indexes_for_cur_subframe[i];

        if (s->channel[c].transmit_coefs &&

            get_bits_count(&s->gb) < s->num_saved_bits) {

            decode_coeffs(s, c);

        } else

            memset(s->channel[c].coeffs, 0,

                   sizeof(*s->channel[c].coeffs) * subframe_len);

    }

    av_dlog(s->avctx, "BITSTREAM: subframe length was %i\n",

            get_bits_count(&s->gb) - s->subframe_offset);

    if (transmit_coeffs) {

        FFTContext *mdct = &s->mdct_ctx[av_log2(subframe_len) - WMAPRO_BLOCK_MIN_BITS];

        /** reconstruct the per channel data */

        inverse_channel_transform(s);

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

            int c = s->channel_indexes_for_cur_subframe[i];

            const int* sf = s->channel[c].scale_factors;

            int b;

            if (c == s->lfe_channel)

                memset(&s->tmp[cur_subwoofer_cutoff], 0, sizeof(*s->tmp) *

                       (subframe_len - cur_subwoofer_cutoff));

            /** inverse quantization and rescaling */

            for (b = 0; b < s->num_bands; b++) {

                const int end = FFMIN(s->cur_sfb_offsets[b+1], s->subframe_len);

                const int exp = s->channel[c].quant_step -

                            (s->channel[c].max_scale_factor - *sf++) *

                            s->channel[c].scale_factor_step;

                const float quant = pow(10.0, exp / 20.0);

                int start = s->cur_sfb_offsets[b];

                s->fdsp.vector_fmul_scalar(s->tmp + start,

                                           s->channel[c].coeffs + start,

                                           quant, end - start);

            }

            /** apply imdct (imdct_half == DCTIV with reverse) */

            mdct->imdct_half(mdct, s->channel[c].coeffs, s->tmp);

        }

    }

    /** window and overlapp-add */

    wmapro_window(s);

    /** handled one subframe */

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

        int c = s->channel_indexes_for_cur_subframe[i];

        if (s->channel[c].cur_subframe >= s->channel[c].num_subframes) {

            av_log(s->avctx, AV_LOG_ERROR, "broken subframe\n");

            return AVERROR_INVALIDDATA;

        }

        ++s->channel[c].cur_subframe;

    }

    return 0;

}


static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,

                         char *tag, uint32_t *vid, int for_snapshot)

{

    int ret, fd;

    SheepdogVdiReq hdr;

    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;

    unsigned int wlen, rlen = 0;

    char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];

    fd = connect_to_sdog(s->addr, s->port);

    if (fd < 0) {

        return fd;

    }

    memset(buf, 0, sizeof(buf));

    strncpy(buf, filename, SD_MAX_VDI_LEN);

    strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);

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

    if (for_snapshot) {

        hdr.opcode = SD_OP_GET_VDI_INFO;

    } else {

        hdr.opcode = SD_OP_LOCK_VDI;

    }

    wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;

    hdr.proto_ver = SD_PROTO_VER;

    hdr.data_length = wlen;

    hdr.snapid = snapid;

    hdr.flags = SD_FLAG_CMD_WRITE;

    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);

    if (ret) {

        goto out;

    }

    if (rsp->result != SD_RES_SUCCESS) {

        error_report("cannot get vdi info, %s, %s %d %s",

                     sd_strerror(rsp->result), filename, snapid, tag);

        if (rsp->result == SD_RES_NO_VDI) {

            ret = -ENOENT;

        } else {

            ret = -EIO;

        }

        goto out;

    }

    *vid = rsp->vdi_id;

    ret = 0;

out:

    closesocket(fd);

    return ret;

}


static void setup_frame(int sig, struct target_sigaction *ka,

			target_sigset_t *set, CPUX86State *env)

{

	abi_ulong frame_addr;

	struct sigframe *frame;

	int i, err = 0;

	frame_addr = get_sigframe(ka, env, sizeof(*frame));

	if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

		goto give_sigsegv;

    __put_user(current_exec_domain_sig(sig),

               &frame->sig);

	if (err)

		goto give_sigsegv;

	setup_sigcontext(&frame->sc, &frame->fpstate, env, set->sig[0],

                         frame_addr + offsetof(struct sigframe, fpstate));

	if (err)

		goto give_sigsegv;

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

            if (__put_user(set->sig[i], &frame->extramask[i - 1]))

                goto give_sigsegv;

        }

	/* Set up to return from userspace.  If provided, use a stub

	   already in userspace.  */

	if (ka->sa_flags & TARGET_SA_RESTORER) {

        __put_user(ka->sa_restorer, &frame->pretcode);

	} else {

                uint16_t val16;

                abi_ulong retcode_addr;

                retcode_addr = frame_addr + offsetof(struct sigframe, retcode);

        __put_user(retcode_addr, &frame->pretcode);

		/* This is popl %eax ; movl $,%eax ; int $0x80 */

                val16 = 0xb858;

        __put_user(val16, (uint16_t *)(frame->retcode+0));

        __put_user(TARGET_NR_sigreturn, (int *)(frame->retcode+2));

                val16 = 0x80cd;

        __put_user(val16, (uint16_t *)(frame->retcode+6));

	}

	if (err)

		goto give_sigsegv;

	/* Set up registers for signal handler */

	env->regs[R_ESP] = frame_addr;

	env->eip = ka->_sa_handler;

        cpu_x86_load_seg(env, R_DS, __USER_DS);

        cpu_x86_load_seg(env, R_ES, __USER_DS);

        cpu_x86_load_seg(env, R_SS, __USER_DS);

        cpu_x86_load_seg(env, R_CS, __USER_CS);

	env->eflags &= ~TF_MASK;

	unlock_user_struct(frame, frame_addr, 1);

	return;

give_sigsegv:

	unlock_user_struct(frame, frame_addr, 1);

	if (sig == TARGET_SIGSEGV)

		ka->_sa_handler = TARGET_SIG_DFL;

	force_sig(TARGET_SIGSEGV /* , current */);

}


static void ahci_pci_enable(AHCIQState *ahci)

{

    uint8_t reg;

    start_ahci_device(ahci);

    switch (ahci->fingerprint) {

    case AHCI_INTEL_ICH9:

        /* ICH9 has a register at PCI 0x92 that

         * acts as a master port enabler mask. */

        reg = qpci_config_readb(ahci->dev, 0x92);

        reg |= 0x3F;

        qpci_config_writeb(ahci->dev, 0x92, reg);

        /* 0...0111111b -- bit significant, ports 0-5 enabled. */

        ASSERT_BIT_SET(qpci_config_readb(ahci->dev, 0x92), 0x3F);

        break;

    }

}


main(

    int argc,

    char *argv[]

) {

    GMainLoop *loop;

    GIOChannel *channel_stdin;

    char *qemu_host;

    char *qemu_port;

    VSCMsgHeader mhHeader;

    VCardEmulOptions *command_line_options = NULL;

    char *cert_names[MAX_CERTS];

    char *emul_args = NULL;

    int cert_count = 0;

    int c, sock;

    if (socket_init() != 0)

        return 1;

    while ((c = getopt(argc, argv, "c:e:pd:")) != -1) {

        switch (c) {

        case 'c':

            if (cert_count >= MAX_CERTS) {

                printf("too many certificates (max = %d)\n", MAX_CERTS);

                exit(5);

            }

            cert_names[cert_count++] = optarg;

            break;

        case 'e':

            emul_args = optarg;

            break;

        case 'p':

            print_usage();

            exit(4);

            break;

        case 'd':

            verbose = get_id_from_string(optarg, 1);

            break;

        }

    }

    if (argc - optind != 2) {

        print_usage();

        exit(4);

    }

    if (cert_count > 0) {

        char *new_args;

        int len, i;

        /* if we've given some -c options, we clearly we want do so some

         * software emulation.  add that emulation now. this is NSS Emulator

         * specific */

        if (emul_args == NULL) {

            emul_args = (char *)"db=\"/etc/pki/nssdb\"";

        }

#define SOFT_STRING ",soft=(,Virtual Reader,CAC,,"

             /* 2 == close paren & null */

        len = strlen(emul_args) + strlen(SOFT_STRING) + 2;

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

            len += strlen(cert_names[i])+1; /* 1 == comma */

        }

        new_args = g_malloc(len);

        strcpy(new_args, emul_args);

        strcat(new_args, SOFT_STRING);

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

            strcat(new_args, cert_names[i]);

            strcat(new_args, ",");

        }

        strcat(new_args, ")");

        emul_args = new_args;

    }

    if (emul_args) {

        command_line_options = vcard_emul_options(emul_args);

    }

    qemu_host = g_strdup(argv[argc - 2]);

    qemu_port = g_strdup(argv[argc - 1]);

    sock = connect_to_qemu(qemu_host, qemu_port);

    if (sock == -1) {

        fprintf(stderr, "error opening socket, exiting.\n");

        exit(5);

    }

    socket_to_send = g_byte_array_new();

    qemu_mutex_init(&socket_to_send_lock);

    qemu_mutex_init(&pending_reader_lock);

    qemu_cond_init(&pending_reader_condition);

    vcard_emul_init(command_line_options);

    loop = g_main_loop_new(NULL, true);

    printf("> ");

    fflush(stdout);

#ifdef _WIN32

    channel_stdin = g_io_channel_win32_new_fd(STDIN_FILENO);

#else

    channel_stdin = g_io_channel_unix_new(STDIN_FILENO);

#endif

    g_io_add_watch(channel_stdin, G_IO_IN, do_command, NULL);

#ifdef _WIN32

    channel_socket = g_io_channel_win32_new_socket(sock);

#else

    channel_socket = g_io_channel_unix_new(sock);

#endif

    g_io_channel_set_encoding(channel_socket, NULL, NULL);

    /* we buffer ourself for thread safety reasons */

    g_io_channel_set_buffered(channel_socket, FALSE);

    /* Send init message, Host responds (and then we send reader attachments) */

    VSCMsgInit init = {

        .version = htonl(VSCARD_VERSION),

        .magic = VSCARD_MAGIC,

        .capabilities = {0}

    };

    send_msg(VSC_Init, mhHeader.reader_id, &init, sizeof(init));

    g_main_loop_run(loop);

    g_main_loop_unref(loop);

    g_io_channel_unref(channel_stdin);

    g_io_channel_unref(channel_socket);

    g_byte_array_unref(socket_to_send);

    closesocket(sock);

    return 0;

}


static VFIOINTp *vfio_init_intp(VFIODevice *vbasedev,

                                struct vfio_irq_info info)

{

    int ret;

    VFIOPlatformDevice *vdev =

        container_of(vbasedev, VFIOPlatformDevice, vbasedev);

    SysBusDevice *sbdev = SYS_BUS_DEVICE(vdev);

    VFIOINTp *intp;

    intp = g_malloc0(sizeof(*intp));

    intp->vdev = vdev;

    intp->pin = info.index;

    intp->flags = info.flags;

    intp->state = VFIO_IRQ_INACTIVE;

    intp->kvm_accel = false;

    sysbus_init_irq(sbdev, &intp->qemuirq);

    /* Get an eventfd for trigger */

    intp->interrupt = g_malloc0(sizeof(EventNotifier));

    ret = event_notifier_init(intp->interrupt, 0);

    if (ret) {

        g_free(intp->interrupt);

        g_free(intp);

        error_report("vfio: Error: trigger event_notifier_init failed ");

        return NULL;

    }

    /* Get an eventfd for resample/unmask */

    intp->unmask = g_malloc0(sizeof(EventNotifier));

    ret = event_notifier_init(intp->unmask, 0);

    if (ret) {

        g_free(intp->interrupt);

        g_free(intp->unmask);

        g_free(intp);

        error_report("vfio: Error: resamplefd event_notifier_init failed");

        return NULL;

    }

    QLIST_INSERT_HEAD(&vdev->intp_list, intp, next);

    return intp;

}


void OPPROTO op_udivx_T1_T0(void)

{

    T0 /= T1;

    FORCE_RET();


void address_space_init(AddressSpace *as, MemoryRegion *root)

{

    memory_region_transaction_begin();

    as->root = root;

    as->current_map = g_new(FlatView, 1);

    flatview_init(as->current_map);

    QTAILQ_INSERT_TAIL(&address_spaces, as, address_spaces_link);

    as->name = NULL;

    memory_region_transaction_commit();

    address_space_init_dispatch(as);

}


ebml_read_ascii (MatroskaDemuxContext *matroska,

                 uint32_t             *id,

                 char                **str)

{

    ByteIOContext *pb = matroska->ctx->pb;

    int size, res;

    uint64_t rlength;

    if ((res = ebml_read_element_id(matroska, id, NULL)) < 0 ||

        (res = ebml_read_element_length(matroska, &rlength)) < 0)

        return res;

    size = rlength;

    /* ebml strings are usually not 0-terminated, so we allocate one

     * byte more, read the string and NULL-terminate it ourselves. */

    if (size < 0 || !(*str = av_malloc(size + 1))) {

        av_log(matroska->ctx, AV_LOG_ERROR, "Memory allocation failed\n");

        return AVERROR(ENOMEM);

    }

    if (get_buffer(pb, (uint8_t *) *str, size) != size) {

        offset_t pos = url_ftell(pb);

        av_log(matroska->ctx, AV_LOG_ERROR,

               "Read error at pos. %"PRIu64" (0x%"PRIx64")\n", pos, pos);

        return AVERROR(EIO);

    }

    (*str)[size] = '\0';

    return 0;

}


static void memory_dump(Monitor *mon, int count, int format, int wsize,

                        target_phys_addr_t addr, int is_physical)

{

    CPUState *env;

    int l, line_size, i, max_digits, len;

    uint8_t buf[16];

    uint64_t v;

    if (format == 'i') {

        int flags;

        flags = 0;

        env = mon_get_cpu();

        if (!env && !is_physical)

            return;

#ifdef TARGET_I386

        if (wsize == 2) {

            flags = 1;

        } else if (wsize == 4) {

            flags = 0;

        } else {

            /* as default we use the current CS size */

            flags = 0;

            if (env) {

#ifdef TARGET_X86_64

                if ((env->efer & MSR_EFER_LMA) &&

                    (env->segs[R_CS].flags & DESC_L_MASK))

                    flags = 2;

                else

#endif

                if (!(env->segs[R_CS].flags & DESC_B_MASK))

                    flags = 1;

            }

        }

#endif

        monitor_disas(mon, env, addr, count, is_physical, flags);

        return;

    }

    len = wsize * count;

    if (wsize == 1)

        line_size = 8;

    else

        line_size = 16;

    max_digits = 0;

    switch(format) {

    case 'o':

        max_digits = (wsize * 8 + 2) / 3;

        break;

    default:

    case 'x':

        max_digits = (wsize * 8) / 4;

        break;

    case 'u':

    case 'd':

        max_digits = (wsize * 8 * 10 + 32) / 33;

        break;

    case 'c':

        wsize = 1;

        break;

    }

    while (len > 0) {

        if (is_physical)

            monitor_printf(mon, TARGET_FMT_plx ":", addr);

        else

            monitor_printf(mon, TARGET_FMT_lx ":", (target_ulong)addr);

        l = len;

        if (l > line_size)

            l = line_size;

        if (is_physical) {

            cpu_physical_memory_rw(addr, buf, l, 0);

        } else {

            env = mon_get_cpu();

            if (!env)

                break;

            if (cpu_memory_rw_debug(env, addr, buf, l, 0) < 0) {

                monitor_printf(mon, " Cannot access memory\n");

                break;

            }

        }

        i = 0;

        while (i < l) {

            switch(wsize) {

            default:

            case 1:

                v = ldub_raw(buf + i);

                break;

            case 2:

                v = lduw_raw(buf + i);

                break;

            case 4:

                v = (uint32_t)ldl_raw(buf + i);

                break;

            case 8:

                v = ldq_raw(buf + i);

                break;

            }

            monitor_printf(mon, " ");

            switch(format) {

            case 'o':

                monitor_printf(mon, "%#*" PRIo64, max_digits, v);

                break;

            case 'x':

                monitor_printf(mon, "0x%0*" PRIx64, max_digits, v);

                break;

            case 'u':

                monitor_printf(mon, "%*" PRIu64, max_digits, v);

                break;

            case 'd':

                monitor_printf(mon, "%*" PRId64, max_digits, v);

                break;

            case 'c':

                monitor_printc(mon, v);

                break;

            }

            i += wsize;

        }

        monitor_printf(mon, "\n");

        addr += l;

        len -= l;

    }

}


RGB_FUNCTIONS(rgba32)

#undef RGB_IN

#undef RGB_OUT

#undef BPP

static void rgb24_to_rgb565(AVPicture *dst, AVPicture *src,

                            int width, int height)

{

    const unsigned char *p;

    unsigned char *q;

    int r, g, b, dst_wrap, src_wrap;

    int x, y;

    p = src->data[0];

    src_wrap = src->linesize[0] - 3 * width;

    q = dst->data[0];

    dst_wrap = dst->linesize[0] - 2 * width;

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

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

            r = p[0];

            g = p[1];

            b = p[2];

            ((unsigned short *)q)[0] =

                ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);

            q += 2;

            p += 3;

        }

        p += src_wrap;

        q += dst_wrap;

    }

}


static void avc_luma_mid_and_aver_dst_16x16_msa(const uint8_t *src,

                                                int32_t src_stride,

                                                uint8_t *dst,

                                                int32_t dst_stride)

{

    avc_luma_mid_and_aver_dst_8w_msa(src, src_stride, dst, dst_stride, 16);

    avc_luma_mid_and_aver_dst_8w_msa(src + 8, src_stride, dst + 8, dst_stride,

                                     16);

}


void MPV_common_init_armv4l(MpegEncContext *s)

{

    int i;

    const int idct_algo= s->avctx->idct_algo;

    ff_put_pixels_clamped = s->avctx->dsp.put_pixels_clamped;

    ff_add_pixels_clamped = s->avctx->dsp.put_pixels_clamped;

    if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_ARM){

        s->idct_put= arm_idct_put;

        s->idct_add= arm_idct_add;

        s->idct_permutation_type= FF_NO_IDCT_PERM;

    }

}


static int sbr_hf_calc_npatches(AACContext *ac, SpectralBandReplication *sbr)

{

    int i, k, sb = 0;

    int msb = sbr->k[0];

    int usb = sbr->kx[1];

    int goal_sb = ((1000 << 11) + (sbr->sample_rate >> 1)) / sbr->sample_rate;

    sbr->num_patches = 0;

    if (goal_sb < sbr->kx[1] + sbr->m[1]) {

        for (k = 0; sbr->f_master[k] < goal_sb; k++) ;

    } else

        k = sbr->n_master;

    do {

        int odd = 0;

        for (i = k; i == k || sb > (sbr->k[0] - 1 + msb - odd); i--) {

            sb = sbr->f_master[i];

            odd = (sb + sbr->k[0]) & 1;

        }

        // Requirements (14496-3 sp04 p205) sets the maximum number of patches to 5.

        // After this check the final number of patches can still be six which is

        // illegal however the Coding Technologies decoder check stream has a final

        // count of 6 patches

        if (sbr->num_patches > 5) {

            av_log(ac->avctx, AV_LOG_ERROR, "Too many patches: %d\n", sbr->num_patches);

            return -1;

        }

        sbr->patch_num_subbands[sbr->num_patches]  = FFMAX(sb - usb, 0);

        sbr->patch_start_subband[sbr->num_patches] = sbr->k[0] - odd - sbr->patch_num_subbands[sbr->num_patches];

        if (sbr->patch_num_subbands[sbr->num_patches] > 0) {

            usb = sb;

            msb = sb;

            sbr->num_patches++;

        } else

            msb = sbr->kx[1];

        if (sbr->f_master[k] - sb < 3)

            k = sbr->n_master;

    } while (sb != sbr->kx[1] + sbr->m[1]);

    if (sbr->patch_num_subbands[sbr->num_patches-1] < 3 && sbr->num_patches > 1)

        sbr->num_patches--;

    return 0;

}


static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)

{

    int channel, stereo, phase, exp;

    int local_int_4,  local_int_8,  stereo_phase,  local_int_10;

    int local_int_14, stereo_exp, local_int_20, local_int_28;

    int n, offset;

    local_int_4 = 0;

    local_int_28 = 0;

    local_int_20 = 2;

    local_int_8 = (4 - duration);

    local_int_10 = 1 << (q->group_order - duration - 1);

    offset = 1;

    while (1) {

        if (q->superblocktype_2_3) {

            while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {

                offset = 1;

                if (n == 0) {

                    local_int_4 += local_int_10;

                    local_int_28 += (1 << local_int_8);

                } else {

                    local_int_4 += 8*local_int_10;

                    local_int_28 += (8 << local_int_8);

                }

            }

            offset += (n - 2);

        } else {

            offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);

            while (offset >= (local_int_10 - 1)) {

                offset += (1 - (local_int_10 - 1));

                local_int_4  += local_int_10;

                local_int_28 += (1 << local_int_8);

            }

        }

        if (local_int_4 >= q->group_size)

            return;

        local_int_14 = (offset >> local_int_8);

        if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))

            return;

        if (q->nb_channels > 1) {

            channel = get_bits1(gb);

            stereo = get_bits1(gb);

        } else {

            channel = 0;

            stereo = 0;

        }

        exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);

        exp += q->fft_level_exp[fft_level_index_table[local_int_14]];

        exp = (exp < 0) ? 0 : exp;

        phase = get_bits(gb, 3);

        stereo_exp = 0;

        stereo_phase = 0;

        if (stereo) {

            stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));

            stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));

            if (stereo_phase < 0)

                stereo_phase += 8;

        }

        if (q->frequency_range > (local_int_14 + 1)) {

            int sub_packet = (local_int_20 + local_int_28);

            qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);

            if (stereo)

                qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);

        }

        offset++;

    }

}


void ff_rtp_send_h263(AVFormatContext *s1, const uint8_t *buf1, int size)

{

    RTPMuxContext *s = s1->priv_data;

    int len, max_packet_size;

    uint8_t *q;

    max_packet_size = s->max_payload_size;

    while (size > 0) {

        q = s->buf;

        if ((buf1[0] == 0) && (buf1[1] == 0)) {

            *q++ = 0x04;

            buf1 += 2;

            size -= 2;

        } else {

            *q++ = 0;

        }

        *q++ = 0;

        len = FFMIN(max_packet_size - 2, size);

        /* Look for a better place to split the frame into packets. */

        if (len < size) {

            const uint8_t *end = find_resync_marker_reverse(buf1, buf1 + len);

            len = end - buf1;

        }

        memcpy(q, buf1, len);

        q += len;

        /* 90 KHz time stamp */

        s->timestamp = s->cur_timestamp;

        ff_rtp_send_data(s1, s->buf, q - s->buf, (len == size));

        buf1 += len;

        size -= len;

    }

}


void tcg_gen_callN(void *func, TCGTemp *ret, int nargs, TCGTemp **args)

{

    TCGContext *s = tcg_ctx;

    int i, real_args, nb_rets, pi;

    unsigned sizemask, flags;

    TCGHelperInfo *info;

    TCGOp *op;

    info = g_hash_table_lookup(helper_table, (gpointer)func);

    flags = info->flags;

    sizemask = info->sizemask;

#if defined(__sparc__) && !defined(__arch64__) \

    && !defined(CONFIG_TCG_INTERPRETER)

    /* We have 64-bit values in one register, but need to pass as two

       separate parameters.  Split them.  */

    int orig_sizemask = sizemask;

    int orig_nargs = nargs;

    TCGv_i64 retl, reth;

    TCGTemp *split_args[MAX_OPC_PARAM];

    retl = NULL;

    reth = NULL;

    if (sizemask != 0) {

        for (i = real_args = 0; i < nargs; ++i) {

            int is_64bit = sizemask & (1 << (i+1)*2);

            if (is_64bit) {

                TCGv_i64 orig = temp_tcgv_i64(args[i]);

                TCGv_i32 h = tcg_temp_new_i32();

                TCGv_i32 l = tcg_temp_new_i32();

                tcg_gen_extr_i64_i32(l, h, orig);

                split_args[real_args++] = tcgv_i32_temp(h);

                split_args[real_args++] = tcgv_i32_temp(l);

            } else {

                split_args[real_args++] = args[i];

            }

        }

        nargs = real_args;

        args = split_args;

        sizemask = 0;

    }

#elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64

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

        int is_64bit = sizemask & (1 << (i+1)*2);

        int is_signed = sizemask & (2 << (i+1)*2);

        if (!is_64bit) {

            TCGv_i64 temp = tcg_temp_new_i64();

            TCGv_i64 orig = temp_tcgv_i64(args[i]);

            if (is_signed) {

                tcg_gen_ext32s_i64(temp, orig);

            } else {

                tcg_gen_ext32u_i64(temp, orig);

            }

            args[i] = tcgv_i64_temp(temp);

        }

    }

#endif /* TCG_TARGET_EXTEND_ARGS */

    i = s->gen_next_op_idx;

    tcg_debug_assert(i < OPC_BUF_SIZE);

    s->gen_op_buf[0].prev = i;

    s->gen_next_op_idx = i + 1;

    op = &s->gen_op_buf[i];

    /* Set links for sequential allocation during translation.  */

    memset(op, 0, offsetof(TCGOp, args));

    op->opc = INDEX_op_call;

    op->prev = i - 1;

    op->next = i + 1;

    pi = 0;

    if (ret != NULL) {

#if defined(__sparc__) && !defined(__arch64__) \

    && !defined(CONFIG_TCG_INTERPRETER)

        if (orig_sizemask & 1) {

            /* The 32-bit ABI is going to return the 64-bit value in

               the %o0/%o1 register pair.  Prepare for this by using

               two return temporaries, and reassemble below.  */

            retl = tcg_temp_new_i64();

            reth = tcg_temp_new_i64();

            op->args[pi++] = tcgv_i64_arg(reth);

            op->args[pi++] = tcgv_i64_arg(retl);

            nb_rets = 2;

        } else {

            op->args[pi++] = temp_arg(ret);

            nb_rets = 1;

        }

#else

        if (TCG_TARGET_REG_BITS < 64 && (sizemask & 1)) {

#ifdef HOST_WORDS_BIGENDIAN

            op->args[pi++] = temp_arg(ret + 1);

            op->args[pi++] = temp_arg(ret);

#else

            op->args[pi++] = temp_arg(ret);

            op->args[pi++] = temp_arg(ret + 1);

#endif

            nb_rets = 2;

        } else {

            op->args[pi++] = temp_arg(ret);

            nb_rets = 1;

        }

#endif

    } else {

        nb_rets = 0;

    }

    op->callo = nb_rets;

    real_args = 0;

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

        int is_64bit = sizemask & (1 << (i+1)*2);

        if (TCG_TARGET_REG_BITS < 64 && is_64bit) {

#ifdef TCG_TARGET_CALL_ALIGN_ARGS

            /* some targets want aligned 64 bit args */

            if (real_args & 1) {

                op->args[pi++] = TCG_CALL_DUMMY_ARG;

                real_args++;

            }

#endif

           /* If stack grows up, then we will be placing successive

              arguments at lower addresses, which means we need to

              reverse the order compared to how we would normally

              treat either big or little-endian.  For those arguments

              that will wind up in registers, this still works for

              HPPA (the only current STACK_GROWSUP target) since the

              argument registers are *also* allocated in decreasing

              order.  If another such target is added, this logic may

              have to get more complicated to differentiate between

              stack arguments and register arguments.  */

#if defined(HOST_WORDS_BIGENDIAN) != defined(TCG_TARGET_STACK_GROWSUP)

            op->args[pi++] = temp_arg(args[i] + 1);

            op->args[pi++] = temp_arg(args[i]);

#else

            op->args[pi++] = temp_arg(args[i]);

            op->args[pi++] = temp_arg(args[i] + 1);

#endif

            real_args += 2;

            continue;

        }

        op->args[pi++] = temp_arg(args[i]);

        real_args++;

    }

    op->args[pi++] = (uintptr_t)func;

    op->args[pi++] = flags;

    op->calli = real_args;

    /* Make sure the fields didn't overflow.  */

    tcg_debug_assert(op->calli == real_args);

    tcg_debug_assert(pi <= ARRAY_SIZE(op->args));

#if defined(__sparc__) && !defined(__arch64__) \

    && !defined(CONFIG_TCG_INTERPRETER)

    /* Free all of the parts we allocated above.  */

    for (i = real_args = 0; i < orig_nargs; ++i) {

        int is_64bit = orig_sizemask & (1 << (i+1)*2);

        if (is_64bit) {

            tcg_temp_free_internal(args[real_args++]);

            tcg_temp_free_internal(args[real_args++]);

        } else {

            real_args++;

        }

    }

    if (orig_sizemask & 1) {

        /* The 32-bit ABI returned two 32-bit pieces.  Re-assemble them.

           Note that describing these as TCGv_i64 eliminates an unnecessary

           zero-extension that tcg_gen_concat_i32_i64 would create.  */

        tcg_gen_concat32_i64(temp_tcgv_i64(ret), retl, reth);

        tcg_temp_free_i64(retl);

        tcg_temp_free_i64(reth);

    }

#elif defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64

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

        int is_64bit = sizemask & (1 << (i+1)*2);

        if (!is_64bit) {

            tcg_temp_free_internal(args[i]);

        }

    }

#endif /* TCG_TARGET_EXTEND_ARGS */

}


void block_job_enter(BlockJob *job)

{

    if (!block_job_started(job)) {

        return;

    }

    if (job->deferred_to_main_loop) {

        return;

    }

    if (!job->busy) {

        bdrv_coroutine_enter(blk_bs(job->blk), job->co);

    }

}


static int vorbis_decode_frame(AVCodecContext *avccontext,

                               void *data, int *data_size,

                               AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    vorbis_context *vc = avccontext->priv_data ;

    GetBitContext *gb = &(vc->gb);

    const float *channel_ptrs[255];

    int i, len;

    if (!buf_size)

        return 0;

    av_dlog(NULL, "packet length %d \n", buf_size);

    init_get_bits(gb, buf, buf_size*8);

    len = vorbis_parse_audio_packet(vc);

    if (len <= 0) {

        *data_size = 0;

        return buf_size;

    }

    if (!vc->first_frame) {

        vc->first_frame = 1;

        *data_size = 0;

        return buf_size ;

    }

    av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",

            get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);

    if (vc->audio_channels > 8) {

        for (i = 0; i < vc->audio_channels; i++)

            channel_ptrs[i] = vc->channel_floors + i * len;

    } else {

        for (i = 0; i < vc->audio_channels; i++)

            channel_ptrs[i] = vc->channel_floors +

                              len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];

    }

    if (avccontext->sample_fmt == AV_SAMPLE_FMT_FLT)

        vc->fmt_conv.float_interleave(data, channel_ptrs, len, vc->audio_channels);

    else

        vc->fmt_conv.float_to_int16_interleave(data, channel_ptrs, len,

                                               vc->audio_channels);

    *data_size = len * vc->audio_channels *

                 av_get_bytes_per_sample(avccontext->sample_fmt);

    return buf_size ;

}


void qmp_guest_shutdown(bool has_mode, const char *mode, Error **err)

{

    UINT shutdown_flag = EWX_FORCE;

    slog("guest-shutdown called, mode: %s", mode);

    if (!has_mode || strcmp(mode, "powerdown") == 0) {

        shutdown_flag |= EWX_POWEROFF;

    } else if (strcmp(mode, "halt") == 0) {

        shutdown_flag |= EWX_SHUTDOWN;

    } else if (strcmp(mode, "reboot") == 0) {

        shutdown_flag |= EWX_REBOOT;

    } else {

        error_set(err, QERR_INVALID_PARAMETER_VALUE, "mode",

                  "halt|powerdown|reboot");

        return;

    }

    /* Request a shutdown privilege, but try to shut down the system

       anyway. */

    acquire_privilege(SE_SHUTDOWN_NAME, err);

    if (error_is_set(err)) {

        return;

    }

    if (!ExitWindowsEx(shutdown_flag, SHTDN_REASON_FLAG_PLANNED)) {

        slog("guest-shutdown failed: %d", GetLastError());

        error_set(err, QERR_UNDEFINED_ERROR);

    }

}


void helper_rdmsr(void)

{

    uint64_t val;

    helper_svm_check_intercept_param(SVM_EXIT_MSR, 0);

    switch((uint32_t)ECX) {

    case MSR_IA32_SYSENTER_CS:

        val = env->sysenter_cs;

    case MSR_IA32_SYSENTER_ESP:

        val = env->sysenter_esp;

    case MSR_IA32_SYSENTER_EIP:

        val = env->sysenter_eip;

    case MSR_IA32_APICBASE:

        val = cpu_get_apic_base(env);

    case MSR_EFER:

        val = env->efer;

    case MSR_STAR:

        val = env->star;

    case MSR_PAT:

        val = env->pat;

    case MSR_VM_HSAVE_PA:

        val = env->vm_hsave;

    case MSR_IA32_PERF_STATUS:

        /* tsc_increment_by_tick */

        val = 1000ULL;

        /* CPU multiplier */

        val |= (((uint64_t)4ULL) << 40);

#ifdef TARGET_X86_64

    case MSR_LSTAR:

        val = env->lstar;

    case MSR_CSTAR:

        val = env->cstar;

    case MSR_FMASK:

        val = env->fmask;

    case MSR_FSBASE:

        val = env->segs[R_FS].base;

    case MSR_GSBASE:

        val = env->segs[R_GS].base;

    case MSR_KERNELGSBASE:

        val = env->kernelgsbase;

#endif

#ifdef USE_KQEMU

    case MSR_QPI_COMMBASE:

        if (env->kqemu_enabled) {

            val = kqemu_comm_base;

        } else {

            val = 0;

        }

#endif

    default:

        /* XXX: exception ? */

        val = 0;

    }

    EAX = (uint32_t)(val);

    EDX = (uint32_t)(val >> 32);

}


BlockJobInfoList *qmp_query_block_jobs(Error **errp)

{

    BlockJobInfoList *head = NULL, **p_next = &head;

    BlockDriverState *bs;

    BdrvNextIterator *it = NULL;

    while ((it = bdrv_next(it, &bs))) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        aio_context_acquire(aio_context);

        if (bs->job) {

            BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);

            elem->value = block_job_query(bs->job);

            *p_next = elem;

            p_next = &elem->next;

        }

        aio_context_release(aio_context);

    }

    return head;

}


DeviceState *ssi_create_slave(SSIBus *bus, const char *name)

{

    DeviceState *dev;

    dev = qdev_create(&bus->qbus, name);

    qdev_init(dev);

    return dev;

}


int ff_mjpeg_decode_sos(MJpegDecodeContext *s, const uint8_t *mb_bitmask,

                        const AVFrame *reference)

{

    int len, nb_components, i, h, v, predictor, point_transform;

    int index, id, ret;

    const int block_size = s->lossless ? 1 : 8;

    int ilv, prev_shift;

    if (!s->got_picture) {

        av_log(s->avctx, AV_LOG_WARNING,

                "Can not process SOS before SOF, skipping\n");

        return -1;

    }

    av_assert0(s->picture_ptr->data[0]);

    /* XXX: verify len field validity */

    len = get_bits(&s->gb, 16);

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

    if (nb_components == 0 || nb_components > MAX_COMPONENTS) {

        av_log(s->avctx, AV_LOG_ERROR,

               "decode_sos: nb_components (%d) unsupported\n", nb_components);

        return AVERROR_PATCHWELCOME;

    }

    if (len != 6 + 2 * nb_components) {

        av_log(s->avctx, AV_LOG_ERROR, "decode_sos: invalid len (%d)\n", len);

        return AVERROR_INVALIDDATA;

    }

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

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

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

        /* find component index */

        for (index = 0; index < s->nb_components; index++)

            if (id == s->component_id[index])

                break;

        if (index == s->nb_components) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "decode_sos: index(%d) out of components\n", index);

            return AVERROR_INVALIDDATA;

        }

        /* Metasoft MJPEG codec has Cb and Cr swapped */

        if (s->avctx->codec_tag == MKTAG('M', 'T', 'S', 'J')

            && nb_components == 3 && s->nb_components == 3 && i)

            index = 3 - i;

        s->quant_sindex[i] = s->quant_index[index];

        s->nb_blocks[i] = s->h_count[index] * s->v_count[index];

        s->h_scount[i]  = s->h_count[index];

        s->v_scount[i]  = s->v_count[index];

        if(nb_components == 3 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)

            index = (i+2)%3;

        if(nb_components == 1 && s->nb_components == 3 && s->avctx->pix_fmt == AV_PIX_FMT_GBR24P)

            index = (index+2)%3;

        s->comp_index[i] = index;

        s->dc_index[i] = get_bits(&s->gb, 4);

        s->ac_index[i] = get_bits(&s->gb, 4);

        if (s->dc_index[i] <  0 || s->ac_index[i] < 0 ||

            s->dc_index[i] >= 4 || s->ac_index[i] >= 4)

            goto out_of_range;

        if (!s->vlcs[0][s->dc_index[i]].table || !(s->progressive ? s->vlcs[2][s->ac_index[0]].table : s->vlcs[1][s->ac_index[i]].table))

            goto out_of_range;

    }

    predictor = get_bits(&s->gb, 8);       /* JPEG Ss / lossless JPEG predictor /JPEG-LS NEAR */

    ilv = get_bits(&s->gb, 8);             /* JPEG Se / JPEG-LS ILV */

    if(s->avctx->codec_tag != AV_RL32("CJPG")){

        prev_shift      = get_bits(&s->gb, 4); /* Ah */

        point_transform = get_bits(&s->gb, 4); /* Al */

    }else

        prev_shift = point_transform = 0;

    if (nb_components > 1) {

        /* interleaved stream */

        s->mb_width  = (s->width  + s->h_max * block_size - 1) / (s->h_max * block_size);

        s->mb_height = (s->height + s->v_max * block_size - 1) / (s->v_max * block_size);

    } else if (!s->ls) { /* skip this for JPEG-LS */

        h = s->h_max / s->h_scount[0];

        v = s->v_max / s->v_scount[0];

        s->mb_width     = (s->width  + h * block_size - 1) / (h * block_size);

        s->mb_height    = (s->height + v * block_size - 1) / (v * block_size);

        s->nb_blocks[0] = 1;

        s->h_scount[0]  = 1;

        s->v_scount[0]  = 1;

    }

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

        av_log(s->avctx, AV_LOG_DEBUG, "%s %s p:%d >>:%d ilv:%d bits:%d skip:%d %s comp:%d\n",

               s->lossless ? "lossless" : "sequential DCT", s->rgb ? "RGB" : "",

               predictor, point_transform, ilv, s->bits, s->mjpb_skiptosod,

               s->pegasus_rct ? "PRCT" : (s->rct ? "RCT" : ""), nb_components);

    /* mjpeg-b can have padding bytes between sos and image data, skip them */

    for (i = s->mjpb_skiptosod; i > 0; i--)

        skip_bits(&s->gb, 8);

next_field:

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

        s->last_dc[i] = (4 << s->bits);

    if (s->lossless) {

        av_assert0(s->picture_ptr == s->picture);

        if (CONFIG_JPEGLS_DECODER && s->ls) {

//            for () {

//            reset_ls_coding_parameters(s, 0);

            if ((ret = ff_jpegls_decode_picture(s, predictor,

                                                point_transform, ilv)) < 0)

                return ret;

        } else {

            if (s->rgb) {

                if ((ret = ljpeg_decode_rgb_scan(s, nb_components, predictor, point_transform)) < 0)

                    return ret;

            } else {

                if ((ret = ljpeg_decode_yuv_scan(s, predictor,

                                                 point_transform,

                                                 nb_components)) < 0)

                    return ret;

            }

        }

    } else {

        if (s->progressive && predictor) {

            av_assert0(s->picture_ptr == s->picture);

            if ((ret = mjpeg_decode_scan_progressive_ac(s, predictor,

                                                        ilv, prev_shift,

                                                        point_transform)) < 0)

                return ret;

        } else {

            if ((ret = mjpeg_decode_scan(s, nb_components,

                                         prev_shift, point_transform,

                                         mb_bitmask, reference)) < 0)

                return ret;

        }

    }

    if (s->interlaced &&

        get_bits_left(&s->gb) > 32 &&

        show_bits(&s->gb, 8) == 0xFF) {

        GetBitContext bak = s->gb;

        align_get_bits(&bak);

        if (show_bits(&bak, 16) == 0xFFD1) {

            av_log(s->avctx, AV_LOG_DEBUG, "AVRn interlaced picture marker found\n");

            s->gb = bak;

            skip_bits(&s->gb, 16);

            s->bottom_field ^= 1;

            goto next_field;

        }

    }

    emms_c();

    return 0;

 out_of_range:

    av_log(s->avctx, AV_LOG_ERROR, "decode_sos: ac/dc index out of range\n");

    return AVERROR_INVALIDDATA;

}


static void v9fs_renameat(void *opaque)
{
    ssize_t err = 0;
    size_t offset = 7;
    V9fsPDU *pdu = opaque;
    V9fsState *s = pdu->s;
    int32_t olddirfid, newdirfid;
    V9fsString old_name, new_name;
    v9fs_string_init(&old_name);
    v9fs_string_init(&new_name);
    err = pdu_unmarshal(pdu, offset, "dsds", &olddirfid,
                        &old_name, &newdirfid, &new_name);
    if (err < 0) {
    if (name_is_illegal(old_name.data) || name_is_illegal(new_name.data)) {
        err = -ENOENT;
    v9fs_path_write_lock(s);
    err = v9fs_complete_renameat(pdu, olddirfid,
                                 &old_name, newdirfid, &new_name);
    v9fs_path_unlock(s);
    if (!err) {
        err = offset;
out_err:
    pdu_complete(pdu, err);
    v9fs_string_free(&old_name);
    v9fs_string_free(&new_name);


if_start(void)
{
	struct mbuf *ifm, *ifqt;
	DEBUG_CALL("if_start");
	if (if_queued == 0)
	   return; /* Nothing to do */
 again:
        /* check if we can really output */
        if (!slirp_can_output())
            return;
	/*
	 * See which queue to get next packet from
	 * If there's something in the fastq, select it immediately
	 */
	if (if_fastq.ifq_next != &if_fastq) {
		ifm = if_fastq.ifq_next;
	} else {
		/* Nothing on fastq, see if next_m is valid */
		if (next_m != &if_batchq)
		   ifm = next_m;
		else
		   ifm = if_batchq.ifq_next;
		/* Set which packet to send on next iteration */
		next_m = ifm->ifq_next;
	}
	/* Remove it from the queue */
	ifqt = ifm->ifq_prev;
	remque(ifm);
	--if_queued;
	/* If there are more packets for this session, re-queue them */
	if (ifm->ifs_next != /* ifm->ifs_prev != */ ifm) {
		insque(ifm->ifs_next, ifqt);
		ifs_remque(ifm);
	}
	/* Update so_queued */
	if (ifm->ifq_so) {
		if (--ifm->ifq_so->so_queued == 0)
		   /* If there's no more queued, reset nqueued */
		   ifm->ifq_so->so_nqueued = 0;
	}
	/* Encapsulate the packet for sending */
        if_encap(ifm->m_data, ifm->m_len);
	if (if_queued)
	   goto again;
}


static void mips_cpu_realizefn(DeviceState *dev, Error **errp)

{

    MIPSCPU *cpu = MIPS_CPU(dev);

    MIPSCPUClass *mcc = MIPS_CPU_GET_CLASS(dev);

    cpu_reset(CPU(cpu));

    mcc->parent_realize(dev, errp);

}


int ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)

{

    int ret = 0;

    if (av_strstart(p, "pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,", &p)) {

        AVIOContext pb;

        RTSPState *rt = s->priv_data;

        AVDictionary *opts = NULL;

        int len = strlen(p) * 6 / 8;

        char *buf = av_mallocz(len);

        av_base64_decode(buf, p, len);

        if (rtp_asf_fix_header(buf, len) < 0)

            av_log(s, AV_LOG_ERROR,

                   "Failed to fix invalid RTSP-MS/ASF min_pktsize\n");

        init_packetizer(&pb, buf, len);

        if (rt->asf_ctx) {

            avformat_close_input(&rt->asf_ctx);

        }

        if (!(rt->asf_ctx = avformat_alloc_context()))

            return AVERROR(ENOMEM);

        rt->asf_ctx->pb      = &pb;

        av_dict_set(&opts, "no_resync_search", "1", 0);

        ret = avformat_open_input(&rt->asf_ctx, "", &ff_asf_demuxer, &opts);

        av_dict_free(&opts);

        if (ret < 0)

            return ret;

        av_dict_copy(&s->metadata, rt->asf_ctx->metadata, 0);

        rt->asf_pb_pos = avio_tell(&pb);

        av_free(buf);

        rt->asf_ctx->pb = NULL;

    }

    return ret;

}


static void alloc_picture(VideoState *is)

{

    VideoPicture *vp;

    int64_t bufferdiff;

    vp = &is->pictq[is->pictq_windex];

    if (vp->bmp)

        SDL_FreeYUVOverlay(vp->bmp);

    video_open(is, 0, vp);

    vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,

                                   SDL_YV12_OVERLAY,

                                   screen);

    bufferdiff = vp->bmp ? FFMAX(vp->bmp->pixels[0], vp->bmp->pixels[1]) - FFMIN(vp->bmp->pixels[0], vp->bmp->pixels[1]) : 0;

    if (!vp->bmp || vp->bmp->pitches[0] < vp->width || bufferdiff < vp->height * vp->bmp->pitches[0]) {

        /* SDL allocates a buffer smaller than requested if the video

         * overlay hardware is unable to support the requested size. */

        av_log(NULL, AV_LOG_FATAL,

               "Error: the video system does not support an image\n"

                        "size of %dx%d pixels. Try using -lowres or -vf \"scale=w:h\"\n"

                        "to reduce the image size.\n", vp->width, vp->height );

        do_exit(is);

    }

    SDL_LockMutex(is->pictq_mutex);

    vp->allocated = 1;

    SDL_CondSignal(is->pictq_cond);

    SDL_UnlockMutex(is->pictq_mutex);

}


void virtqueue_discard(VirtQueue *vq, const VirtQueueElement *elem,

                       unsigned int len)

{

    vq->last_avail_idx--;

    virtqueue_unmap_sg(vq, elem, len);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->reset = arm_gic_common_reset;

    dc->realize = arm_gic_common_realize;

    dc->props = arm_gic_common_properties;

    dc->vmsd = &vmstate_gic;

    dc->no_user = 1;

}


static CharDriverState *qemu_chr_open_tty(QemuOpts *opts)

{

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

    CharDriverState *chr;

    int fd;

    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));

    if (fd < 0) {

        return NULL;

    }

    tty_serial_init(fd, 115200, 'N', 8, 1);

    chr = qemu_chr_open_fd(fd, fd);

    if (!chr) {

        close(fd);

        return NULL;

    }

    chr->chr_ioctl = tty_serial_ioctl;

    chr->chr_close = qemu_chr_close_tty;

    return chr;

}


void object_property_set_qobject(Object *obj, QObject *value,

                                 const char *name, Error **errp)

{

    Visitor *v;

    /* TODO: Should we reject, rather than ignore, excess input? */

    v = qobject_input_visitor_new(value, false);

    object_property_set(obj, v, name, errp);

    visit_free(v);

}


static int http_receive_data(HTTPContext *c)

{

    int len;

    HTTPContext *c1;

    if (c->buffer_ptr >= c->buffer_end) {

        FFStream *feed = c->stream;

        /* a packet has been received : write it in the store, except

           if header */

        if (c->data_count > FFM_PACKET_SIZE) {

            //            printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size);

            /* XXX: use llseek or url_seek */

            lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);

            write(c->feed_fd, c->buffer, FFM_PACKET_SIZE);

            feed->feed_write_index += FFM_PACKET_SIZE;

            /* update file size */

            if (feed->feed_write_index > c->stream->feed_size)

                feed->feed_size = feed->feed_write_index;

            /* handle wrap around if max file size reached */

            if (feed->feed_write_index >= c->stream->feed_max_size)

                feed->feed_write_index = FFM_PACKET_SIZE;

            /* write index */

            ffm_write_write_index(c->feed_fd, feed->feed_write_index);

            /* wake up any waiting connections */

            for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {

                if (c1->state == HTTPSTATE_WAIT_FEED &&

                    c1->stream->feed == c->stream->feed) {

                    c1->state = HTTPSTATE_SEND_DATA;

                }

            }

        } else {

            /* We have a header in our hands that contains useful data */

            AVFormatContext s;

            ByteIOContext *pb = &s.pb;

            int i;

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

            url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);

            pb->buf_end = c->buffer_end;        /* ?? */

            pb->is_streamed = 1;

            if (feed->fmt->read_header(&s, 0) < 0) {

                goto fail;

            }

            /* Now we have the actual streams */

            if (s.nb_streams != feed->nb_streams) {

                goto fail;

            }

            for (i = 0; i < s.nb_streams; i++) {

                memcpy(&feed->streams[i]->codec, &s.streams[i]->codec, sizeof(AVCodecContext));

            }

        }

        c->buffer_ptr = c->buffer;

    }

    len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);

    if (len < 0) {

        if (errno != EAGAIN && errno != EINTR) {

            /* error : close connection */

            goto fail;

        }

    } else if (len == 0) {

        /* end of connection : close it */

        goto fail;

    } else {

        c->buffer_ptr += len;

        c->data_count += len;

    }

    return 0;

 fail:

    c->stream->feed_opened = 0;

    close(c->feed_fd);

    return -1;

}


static int stellaris_sys_init(uint32_t base, qemu_irq irq,

                              stellaris_board_info * board,

                              uint8_t *macaddr)

{

    ssys_state *s;

    s = (ssys_state *)g_malloc0(sizeof(ssys_state));

    s->irq = irq;

    s->board = board;

    /* Most devices come preprogrammed with a MAC address in the user data. */

    s->user0 = macaddr[0] | (macaddr[1] << 8) | (macaddr[2] << 16);

    s->user1 = macaddr[3] | (macaddr[4] << 8) | (macaddr[5] << 16);

    memory_region_init_io(&s->iomem, NULL, &ssys_ops, s, "ssys", 0x00001000);

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

    ssys_reset(s);

    vmstate_register(NULL, -1, &vmstate_stellaris_sys, s);

    return 0;

}


static int kvm_recommended_vcpus(KVMState *s)

{

    int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);

    return (ret) ? ret : 4;

}


static void reschedule_dma(void *opaque)

{

    DMAAIOCB *dbs = (DMAAIOCB *)opaque;

    qemu_bh_delete(dbs->bh);

    dbs->bh = NULL;

    dma_bdrv_cb(opaque, 0);

}


static int adpcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    ADPCMContext *c = avctx->priv_data;

    ADPCMChannelStatus *cs;

    int n, m, channel, i;

    int block_predictor[2];

    short *samples;

    short *samples_end;

    uint8_t *src;

    int st; /* stereo */

    /* DK3 ADPCM accounting variables */

    unsigned char last_byte = 0;

    unsigned char nibble;

    int decode_top_nibble_next = 0;

    int diff_channel;

    /* EA ADPCM state variables */

    uint32_t samples_in_chunk;

    int32_t previous_left_sample, previous_right_sample;

    int32_t current_left_sample, current_right_sample;

    int32_t next_left_sample, next_right_sample;

    int32_t coeff1l, coeff2l, coeff1r, coeff2r;

    uint8_t shift_left, shift_right;

    int count1, count2;

    if (!buf_size)

        return 0;

    //should protect all 4bit ADPCM variants

    //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels

    //

    if(*data_size/4 < buf_size + 8)

        return -1;

    samples = data;

    samples_end= samples + *data_size/2;

    *data_size= 0;

    src = buf;

    st = avctx->channels == 2 ? 1 : 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT:

        n = (buf_size - 2);/* >> 2*avctx->channels;*/

        channel = c->channel;

        cs = &(c->status[channel]);

        /* (pppppp) (piiiiiii) */

        /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */

        cs->predictor = (*src++) << 8;

        cs->predictor |= (*src & 0x80);

        cs->predictor &= 0xFF80;

        /* sign extension */

        if(cs->predictor & 0x8000)

            cs->predictor -= 0x10000;

        CLAMP_TO_SHORT(cs->predictor);

        cs->step_index = (*src++) & 0x7F;

        if (cs->step_index > 88){

            av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

            cs->step_index = 88;

        }

        cs->step = step_table[cs->step_index];

        if (st && channel)

            samples++;

        for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */

            *samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);

            samples += avctx->channels;

            *samples = adpcm_ima_expand_nibble(cs, (src[0] >> 4) & 0x0F, 3);

            samples += avctx->channels;

            src ++;

        }

        if(st) { /* handle stereo interlacing */

            c->channel = (channel + 1) % 2; /* we get one packet for left, then one for right data */

            if(channel == 1) { /* wait for the other packet before outputing anything */

                return src - buf;

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

//        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;

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

            cs = &(c->status[i]);

            cs->predictor = (int16_t)(src[0] + (src[1]<<8));

            src+=2;

        // XXX: is this correct ??: *samples++ = cs->predictor;

            cs->step_index = *src++;

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */

        }

        while(src < buf + buf_size){

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

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);

                src++;

            }

            src += 4*st;

        }

        break;

    case CODEC_ID_ADPCM_4XM:

        cs = &(c->status[0]);

        c->status[0].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        c->status[0].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        if (cs->step_index < 0) cs->step_index = 0;

        if (cs->step_index > 88) cs->step_index = 88;

        m= (buf_size - (src - buf))>>st;

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

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);

        }

        src += m<<st;

        break;

    case CODEC_ID_ADPCM_MS:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        n = buf_size - 7 * avctx->channels;

        if (n < 0)

            return -1;

        block_predictor[0] = av_clip(*src++, 0, 7);

        block_predictor[1] = 0;

        if (st)

            block_predictor[1] = av_clip(*src++, 0, 7);

        c->status[0].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st){

            c->status[1].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

            src+=2;

        }

        c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];

        c->status[0].coeff2 = AdaptCoeff2[block_predictor[0]];

        c->status[1].coeff1 = AdaptCoeff1[block_predictor[1]];

        c->status[1].coeff2 = AdaptCoeff2[block_predictor[1]];

        c->status[0].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        c->status[0].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        *samples++ = c->status[0].sample1;

        if (st) *samples++ = c->status[1].sample1;

        *samples++ = c->status[0].sample2;

        if (st) *samples++ = c->status[1].sample2;

        for(;n>0;n--) {

            *samples++ = adpcm_ms_expand_nibble(&c->status[0], (src[0] >> 4) & 0x0F);

            *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);

            src ++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        c->status[0].predictor = (int16_t)(src[0] | (src[1] << 8));

        c->status[0].step_index = src[2];

        src += 4;

        *samples++ = c->status[0].predictor;

        if (st) {

            c->status[1].predictor = (int16_t)(src[0] | (src[1] << 8));

            c->status[1].step_index = src[2];

            src += 4;

            *samples++ = c->status[1].predictor;

        }

        while (src < buf + buf_size) {

            /* take care of the top nibble (always left or mono channel) */

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                (src[0] >> 4) & 0x0F, 3);

            /* take care of the bottom nibble, which is right sample for

             * stereo, or another mono sample */

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            else

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK3:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        if(buf_size + 16 > (samples_end - samples)*3/8)

            return -1;

        c->status[0].predictor = (int16_t)(src[10] | (src[11] << 8));

        c->status[1].predictor = (int16_t)(src[12] | (src[13] << 8));

        c->status[0].step_index = src[14];

        c->status[1].step_index = src[15];

        /* sign extend the predictors */

        src += 16;

        diff_channel = c->status[1].predictor;

        /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when

         * the buffer is consumed */

        while (1) {

            /* for this algorithm, c->status[0] is the sum channel and

             * c->status[1] is the diff channel */

            /* process the first predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the diff channel predictor */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[1], nibble, 3);

            /* process the first pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

            /* process the second predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the second pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        /* no per-block initialization; just start decoding the data */

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            } else {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_XA:

        c->status[0].sample1 = c->status[0].sample2 =

        c->status[1].sample1 = c->status[1].sample2 = 0;

        while (buf_size >= 128) {

            xa_decode(samples, src, &c->status[0], &c->status[1],

                avctx->channels);

            src += 128;

            samples += 28 * 8;

            buf_size -= 128;

        }

        break;

    case CODEC_ID_ADPCM_EA:

        samples_in_chunk = AV_RL32(src);

        if (samples_in_chunk >= ((buf_size - 12) * 2)) {

            src += buf_size;

            break;

        }

        src += 4;

        current_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        current_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        for (count1 = 0; count1 < samples_in_chunk/28;count1++) {

            coeff1l = ea_adpcm_table[(*src >> 4) & 0x0F];

            coeff2l = ea_adpcm_table[((*src >> 4) & 0x0F) + 4];

            coeff1r = ea_adpcm_table[*src & 0x0F];

            coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];

            src++;

            shift_left = ((*src >> 4) & 0x0F) + 8;

            shift_right = (*src & 0x0F) + 8;

            src++;

            for (count2 = 0; count2 < 28; count2++) {

                next_left_sample = (((*src & 0xF0) << 24) >> shift_left);

                next_right_sample = (((*src & 0x0F) << 28) >> shift_right);

                src++;

                next_left_sample = (next_left_sample +

                    (current_left_sample * coeff1l) +

                    (previous_left_sample * coeff2l) + 0x80) >> 8;

                next_right_sample = (next_right_sample +

                    (current_right_sample * coeff1r) +

                    (previous_right_sample * coeff2r) + 0x80) >> 8;

                CLAMP_TO_SHORT(next_left_sample);

                CLAMP_TO_SHORT(next_right_sample);

                previous_left_sample = current_left_sample;

                current_left_sample = next_left_sample;

                previous_right_sample = current_right_sample;

                current_right_sample = next_right_sample;

                *samples++ = (unsigned short)current_left_sample;

                *samples++ = (unsigned short)current_right_sample;

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_SMJPEG:

        c->status[0].predictor = *src;

        src += 2;

        c->status[0].step_index = *src++;

        src++;  /* skip another byte before getting to the meat */

        while (src < buf + buf_size) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                *src & 0x0F, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                (*src >> 4) & 0x0F, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_CT:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F);

                *samples++ = adpcm_ct_expand_nibble(&c->status[1],

                    src[0] & 0x0F);

            } else {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F);

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    src[0] & 0x0F);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_SBPRO_4:

    case CODEC_ID_ADPCM_SBPRO_3:

    case CODEC_ID_ADPCM_SBPRO_2:

        if (!c->status[0].step_index) {

            /* the first byte is a raw sample */

            *samples++ = 128 * (*src++ - 0x80);

            if (st)

              *samples++ = 128 * (*src++ - 0x80);

            c->status[0].step_index = 1;

        }

        if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {

            while (src < buf + buf_size) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 4, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x0F, 4, 0);

                src++;

            }

        } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {

            while (src < buf + buf_size && samples + 2 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 5) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] & 0x03, 2, 0);

                src++;

            }

        } else {

            while (src < buf + buf_size && samples + 3 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 6) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    (src[0] >> 4) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x03, 2, 2);

                src++;

            }

        }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        GetBitContext gb;

        const int *table;

        int k0, signmask, nb_bits;

        int size = buf_size*8;

        init_get_bits(&gb, buf, size);

        //read bits & inital values

        nb_bits = get_bits(&gb, 2)+2;

        //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);

        table = swf_index_tables[nb_bits-2];

        k0 = 1 << (nb_bits-2);

        signmask = 1 << (nb_bits-1);

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

            *samples++ = c->status[i].predictor = get_sbits(&gb, 16);

            c->status[i].step_index = get_bits(&gb, 6);

        }

        while (get_bits_count(&gb) < size)

        {

            int i;

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

                // similar to IMA adpcm

                int delta = get_bits(&gb, nb_bits);

                int step = step_table[c->status[i].step_index];

                long vpdiff = 0; // vpdiff = (delta+0.5)*step/4

                int k = k0;

                do {

                    if (delta & k)

                        vpdiff += step;

                    step >>= 1;

                    k >>= 1;

                } while(k);

                vpdiff += step;

                if (delta & signmask)

                    c->status[i].predictor -= vpdiff;

                else

                    c->status[i].predictor += vpdiff;

                c->status[i].step_index += table[delta & (~signmask)];

                c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

                c->status[i].predictor = av_clip(c->status[i].predictor, -32768, 32767);

                *samples++ = c->status[i].predictor;

                if (samples >= samples_end) {

                    av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

                    return -1;

                }

            }

        }

        src += buf_size;

        break;

    }

    case CODEC_ID_ADPCM_YAMAHA:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[1],

                        (src[0] >> 4) & 0x0F);

            } else {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        (src[0] >> 4) & 0x0F);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_THP:

    {

        int table[2][16];

        unsigned int samplecnt;

        int prev[2][2];

        int ch;

        if (buf_size < 80) {

            av_log(avctx, AV_LOG_ERROR, "frame too small\n");

            return -1;

        }

        src+=4;

        samplecnt = bytestream_get_be32(&src);

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

            table[0][i] = (int16_t)bytestream_get_be16(&src);

        /* Initialize the previous sample.  */

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

            prev[0][i] = (int16_t)bytestream_get_be16(&src);

        if (samplecnt >= (samples_end - samples) /  (st + 1)) {

            av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

            return -1;

        }

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

            samples = (unsigned short *) data + ch;

            /* Read in every sample for this channel.  */

            for (i = 0; i < samplecnt / 14; i++) {

                int index = (*src >> 4) & 7;

                unsigned int exp = 28 - (*src++ & 15);

                int factor1 = table[ch][index * 2];

                int factor2 = table[ch][index * 2 + 1];

                /* Decode 14 samples.  */

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

                    int32_t sampledat;

                    if(n&1) sampledat=  *src++    <<28;

                    else    sampledat= (*src&0xF0)<<24;

                    *samples = ((prev[ch][0]*factor1

                                + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);

                    prev[ch][1] = prev[ch][0];

                    prev[ch][0] = *samples++;

                    /* In case of stereo, skip one sample, this sample

                       is for the other channel.  */

                    samples += st;

                }

            }

        }

        /* In the previous loop, in case stereo is used, samples is

           increased exactly one time too often.  */

        samples -= st;

        break;

    }

    default:

        return -1;

    }

    *data_size = (uint8_t *)samples - (uint8_t *)data;

    return src - buf;

}


static coroutine_fn void test_multi_co_schedule_entry(void *opaque)

{

    g_assert(to_schedule[id] == NULL);

    atomic_mb_set(&to_schedule[id], qemu_coroutine_self());

    while (!atomic_mb_read(&now_stopping)) {

        int n;

        n = g_test_rand_int_range(0, NUM_CONTEXTS);

        schedule_next(n);

        qemu_coroutine_yield();

        g_assert(to_schedule[id] == NULL);

        atomic_mb_set(&to_schedule[id], qemu_coroutine_self());

    }

}