static void phys_map_node_reserve(unsigned nodes)

{

    if (next_map.nodes_nb + nodes > next_map.nodes_nb_alloc) {

        next_map.nodes_nb_alloc = MAX(next_map.nodes_nb_alloc * 2,

                                            16);

        next_map.nodes_nb_alloc = MAX(next_map.nodes_nb_alloc,

                                      next_map.nodes_nb + nodes);

        next_map.nodes = g_renew(Node, next_map.nodes,

                                 next_map.nodes_nb_alloc);

    }

}


static int omap_dma_ch_reg_write(struct omap_dma_s *s,

                int ch, int reg, uint16_t value) {

    switch (reg) {

    case 0x00:	/* SYS_DMA_CSDP_CH0 */

        s->ch[ch].burst[1] = (value & 0xc000) >> 14;

        s->ch[ch].pack[1] = (value & 0x2000) >> 13;

        s->ch[ch].port[1] = (enum omap_dma_port) ((value & 0x1e00) >> 9);

        s->ch[ch].burst[0] = (value & 0x0180) >> 7;

        s->ch[ch].pack[0] = (value & 0x0040) >> 6;

        s->ch[ch].port[0] = (enum omap_dma_port) ((value & 0x003c) >> 2);

        s->ch[ch].data_type = (1 << (value & 3));

        if (s->ch[ch].port[0] >= omap_dma_port_last)

            printf("%s: invalid DMA port %i\n", __FUNCTION__,

                            s->ch[ch].port[0]);

        if (s->ch[ch].port[1] >= omap_dma_port_last)

            printf("%s: invalid DMA port %i\n", __FUNCTION__,

                            s->ch[ch].port[1]);

        if ((value & 3) == 3)

            printf("%s: bad data_type for DMA channel %i\n", __FUNCTION__, ch);

        break;

    case 0x02:	/* SYS_DMA_CCR_CH0 */

        s->ch[ch].mode[1] = (omap_dma_addressing_t) ((value & 0xc000) >> 14);

        s->ch[ch].mode[0] = (omap_dma_addressing_t) ((value & 0x3000) >> 12);

        s->ch[ch].end_prog = (value & 0x0800) >> 11;

        s->ch[ch].repeat = (value & 0x0200) >> 9;

        s->ch[ch].auto_init = (value & 0x0100) >> 8;

        s->ch[ch].priority = (value & 0x0040) >> 6;

        s->ch[ch].fs = (value & 0x0020) >> 5;

        s->ch[ch].sync = value & 0x001f;

        if (value & 0x0080) {

            if (s->ch[ch].running) {

                if (!s->ch[ch].signalled &&

                                s->ch[ch].auto_init && s->ch[ch].end_prog)

                    omap_dma_channel_load(s, ch);

            } else {

                s->ch[ch].running = 1;

                omap_dma_channel_load(s, ch);

            }

            if (!s->ch[ch].sync || (s->drq & (1 << s->ch[ch].sync)))

                omap_dma_request_run(s, ch, 0);

        } else {

            s->ch[ch].running = 0;

            omap_dma_request_stop(s, ch);

        }

        break;

    case 0x04:	/* SYS_DMA_CICR_CH0 */

        s->ch[ch].interrupts = value & 0x003f;

        break;

    case 0x06:	/* SYS_DMA_CSR_CH0 */

        return 1;

    case 0x08:	/* SYS_DMA_CSSA_L_CH0 */

        s->ch[ch].addr[0] &= 0xffff0000;

        s->ch[ch].addr[0] |= value;

        break;

    case 0x0a:	/* SYS_DMA_CSSA_U_CH0 */

        s->ch[ch].addr[0] &= 0x0000ffff;

        s->ch[ch].addr[0] |= value << 16;

        break;

    case 0x0c:	/* SYS_DMA_CDSA_L_CH0 */

        s->ch[ch].addr[1] &= 0xffff0000;

        s->ch[ch].addr[1] |= value;

        break;

    case 0x0e:	/* SYS_DMA_CDSA_U_CH0 */

        s->ch[ch].addr[1] &= 0x0000ffff;

        s->ch[ch].addr[1] |= value << 16;

        break;

    case 0x10:	/* SYS_DMA_CEN_CH0 */

        s->ch[ch].elements = value & 0xffff;

        break;

    case 0x12:	/* SYS_DMA_CFN_CH0 */

        s->ch[ch].frames = value & 0xffff;

        break;

    case 0x14:	/* SYS_DMA_CFI_CH0 */

        s->ch[ch].frame_index = value & 0xffff;

        break;

    case 0x16:	/* SYS_DMA_CEI_CH0 */

        s->ch[ch].element_index = value & 0xffff;

        break;

    case 0x18:	/* SYS_DMA_CPC_CH0 */

        return 1;

    default:

        OMAP_BAD_REG((unsigned long) reg);

    }

    return 0;

}


static void add_cpreg_to_hashtable(ARMCPU *cpu, const ARMCPRegInfo *r,

                                   void *opaque, int state, int secstate,

                                   int crm, int opc1, int opc2)

{

    /* Private utility function for define_one_arm_cp_reg_with_opaque():

     * add a single reginfo struct to the hash table.

     */

    uint32_t *key = g_new(uint32_t, 1);

    ARMCPRegInfo *r2 = g_memdup(r, sizeof(ARMCPRegInfo));

    int is64 = (r->type & ARM_CP_64BIT) ? 1 : 0;

    int ns = (secstate & ARM_CP_SECSTATE_NS) ? 1 : 0;

    /* Reset the secure state to the specific incoming state.  This is

     * necessary as the register may have been defined with both states.

     */

    r2->secure = secstate;

    if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {

        /* Register is banked (using both entries in array).

         * Overwriting fieldoffset as the array is only used to define

         * banked registers but later only fieldoffset is used.

         */

        r2->fieldoffset = r->bank_fieldoffsets[ns];

    }

    if (state == ARM_CP_STATE_AA32) {

        if (r->bank_fieldoffsets[0] && r->bank_fieldoffsets[1]) {

            /* If the register is banked then we don't need to migrate or

             * reset the 32-bit instance in certain cases:

             *

             * 1) If the register has both 32-bit and 64-bit instances then we

             *    can count on the 64-bit instance taking care of the

             *    non-secure bank.

             * 2) If ARMv8 is enabled then we can count on a 64-bit version

             *    taking care of the secure bank.  This requires that separate

             *    32 and 64-bit definitions are provided.

             */

            if ((r->state == ARM_CP_STATE_BOTH && ns) ||

                (arm_feature(&cpu->env, ARM_FEATURE_V8) && !ns)) {

                r2->type |= ARM_CP_NO_MIGRATE;

                r2->resetfn = arm_cp_reset_ignore;

            }

        } else if ((secstate != r->secure) && !ns) {

            /* The register is not banked so we only want to allow migration of

             * the non-secure instance.

             */

            r2->type |= ARM_CP_NO_MIGRATE;

            r2->resetfn = arm_cp_reset_ignore;

        }

        if (r->state == ARM_CP_STATE_BOTH) {

            /* We assume it is a cp15 register if the .cp field is left unset.

             */

            if (r2->cp == 0) {

                r2->cp = 15;

            }

#ifdef HOST_WORDS_BIGENDIAN

            if (r2->fieldoffset) {

                r2->fieldoffset += sizeof(uint32_t);

            }

#endif

        }

    }

    if (state == ARM_CP_STATE_AA64) {

        /* To allow abbreviation of ARMCPRegInfo

         * definitions, we treat cp == 0 as equivalent to

         * the value for "standard guest-visible sysreg".

         * STATE_BOTH definitions are also always "standard

         * sysreg" in their AArch64 view (the .cp value may

         * be non-zero for the benefit of the AArch32 view).

         */

        if (r->cp == 0 || r->state == ARM_CP_STATE_BOTH) {

            r2->cp = CP_REG_ARM64_SYSREG_CP;

        }

        *key = ENCODE_AA64_CP_REG(r2->cp, r2->crn, crm,

                                  r2->opc0, opc1, opc2);

    } else {

        *key = ENCODE_CP_REG(r2->cp, is64, ns, r2->crn, crm, opc1, opc2);

    }

    if (opaque) {

        r2->opaque = opaque;

    }

    /* reginfo passed to helpers is correct for the actual access,

     * and is never ARM_CP_STATE_BOTH:

     */

    r2->state = state;

    /* Make sure reginfo passed to helpers for wildcarded regs

     * has the correct crm/opc1/opc2 for this reg, not CP_ANY:

     */

    r2->crm = crm;

    r2->opc1 = opc1;

    r2->opc2 = opc2;

    /* By convention, for wildcarded registers only the first

     * entry is used for migration; the others are marked as

     * NO_MIGRATE so we don't try to transfer the register

     * multiple times. Special registers (ie NOP/WFI) are

     * never migratable.

     */

    if ((r->type & ARM_CP_SPECIAL) ||

        ((r->crm == CP_ANY) && crm != 0) ||

        ((r->opc1 == CP_ANY) && opc1 != 0) ||

        ((r->opc2 == CP_ANY) && opc2 != 0)) {

        r2->type |= ARM_CP_NO_MIGRATE;

    }

    /* Overriding of an existing definition must be explicitly

     * requested.

     */

    if (!(r->type & ARM_CP_OVERRIDE)) {

        ARMCPRegInfo *oldreg;

        oldreg = g_hash_table_lookup(cpu->cp_regs, key);

        if (oldreg && !(oldreg->type & ARM_CP_OVERRIDE)) {

            fprintf(stderr, "Register redefined: cp=%d %d bit "

                    "crn=%d crm=%d opc1=%d opc2=%d, "

                    "was %s, now %s\n", r2->cp, 32 + 32 * is64,

                    r2->crn, r2->crm, r2->opc1, r2->opc2,

                    oldreg->name, r2->name);

            g_assert_not_reached();

        }

    }

    g_hash_table_insert(cpu->cp_regs, key, r2);

}


static inline void RENAME(rgb24to16)(const uint8_t *src, uint8_t *dst, long src_size)

{

    const uint8_t *s = src;

    const uint8_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint8_t *mm_end;

#endif

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");

    __asm__ volatile(

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

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

        ::"m"(red_16mask),"m"(green_16mask));

    mm_end = end - 15;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

            "movd          %1, %%mm0    \n\t"

            "movd         3%1, %%mm3    \n\t"

            "punpckldq    6%1, %%mm0    \n\t"

            "punpckldq    9%1, %%mm3    \n\t"

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

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

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

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

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

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

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

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

            "psrlq         $5, %%mm1    \n\t"

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

            "pand       %%mm6, %%mm1    \n\t"

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

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

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

            "pand          %2, %%mm2    \n\t"

            "pand          %2, %%mm5    \n\t"

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

            "por        %%mm4, %%mm3    \n\t"

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

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

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

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

            MOVNTQ"     %%mm0, %0       \n\t"

            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

        d += 4;

        s += 12;

    }

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

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

#endif

    while (s < end) {

        const int r = *s++;

        const int g = *s++;

        const int b = *s++;

        *d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);

    }

}


static void read_event_data(SCLPEventFacility *ef, SCCB *sccb)

{

    unsigned int sclp_active_selection_mask;

    unsigned int sclp_cp_receive_mask;

    ReadEventData *red = (ReadEventData *) sccb;

    if (be16_to_cpu(sccb->h.length) != SCCB_SIZE) {

        sccb->h.response_code = cpu_to_be16(SCLP_RC_INSUFFICIENT_SCCB_LENGTH);

        goto out;

    }

    sclp_cp_receive_mask = ef->receive_mask;

    /* get active selection mask */

    switch (sccb->h.function_code) {

    case SCLP_UNCONDITIONAL_READ:

        sclp_active_selection_mask = sclp_cp_receive_mask;

        break;

    case SCLP_SELECTIVE_READ:

        if (!(sclp_cp_receive_mask & be32_to_cpu(red->mask))) {

            sccb->h.response_code =

                    cpu_to_be16(SCLP_RC_INVALID_SELECTION_MASK);

            goto out;

        }

        sclp_active_selection_mask = be32_to_cpu(red->mask);

        break;

    default:

        sccb->h.response_code = cpu_to_be16(SCLP_RC_INVALID_FUNCTION);

        goto out;

    }

    sccb->h.response_code = cpu_to_be16(

            handle_sccb_read_events(ef, sccb, sclp_active_selection_mask));

out:

    return;

}


static QObject *parse_keyword(JSONParserContext *ctxt)

{

    QObject *token;

    const char *val;

    token = parser_context_pop_token(ctxt);

    assert(token && token_get_type(token) == JSON_KEYWORD);

    val = token_get_value(token);

    if (!strcmp(val, "true")) {

        return QOBJECT(qbool_from_bool(true));

    } else if (!strcmp(val, "false")) {

        return QOBJECT(qbool_from_bool(false));

    } else if (!strcmp(val, "null")) {

        return qnull();

    }

    parse_error(ctxt, token, "invalid keyword '%s'", val);

    return NULL;

}


static void virtqueue_map_iovec(VirtIODevice *vdev, struct iovec *sg,

                                hwaddr *addr, unsigned int *num_sg,

                                unsigned int max_size, int is_write)

{

    unsigned int i;

    hwaddr len;

    /* Note: this function MUST validate input, some callers

     * are passing in num_sg values received over the network.

     */

    /* TODO: teach all callers that this can fail, and return failure instead

     * of asserting here.

     * When we do, we might be able to re-enable NDEBUG below.

     */

#ifdef NDEBUG

#error building with NDEBUG is not supported

#endif

    assert(*num_sg <= max_size);

    for (i = 0; i < *num_sg; i++) {

        len = sg[i].iov_len;

        sg[i].iov_base = dma_memory_map(vdev->dma_as,

                                        addr[i], &len, is_write ?

                                        DMA_DIRECTION_FROM_DEVICE :

                                        DMA_DIRECTION_TO_DEVICE);

        if (!sg[i].iov_base) {

            error_report("virtio: error trying to map MMIO memory");

            exit(1);

        }

        if (len != sg[i].iov_len) {

            error_report("virtio: unexpected memory split");

            exit(1);

        }

    }

}


void qmp_block_job_complete(const char *device, Error **errp)

{

    BlockJob *job = find_block_job(device);

    if (!job) {

        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);

        return;

    }

    trace_qmp_block_job_complete(job);

    block_job_complete(job, errp);

}


static uint32_t omap_l4_io_readb(void *opaque, target_phys_addr_t addr)

{

    unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;

    return omap_l4_io_readb_fn[i](omap_l4_io_opaque[i], addr);

}


void qemu_chr_initial_reset(void)

{

    CharDriverState *chr;

    initial_reset_issued = 1;

    TAILQ_FOREACH(chr, &chardevs, next) {

        qemu_chr_reset(chr);

    }

}


static void par_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)

{

    if (arm_feature(env, ARM_FEATURE_LPAE)) {

        env->cp15.par_el1 = value;

    } else if (arm_feature(env, ARM_FEATURE_V7)) {

        env->cp15.par_el1 = value & 0xfffff6ff;

    } else {

        env->cp15.par_el1 = value & 0xfffff1ff;

    }

}


void vnc_client_write(void *opaque)

{

    VncState *vs = opaque;

    vnc_lock_output(vs);

    if (vs->output.offset

#ifdef CONFIG_VNC_WS

            || vs->ws_output.offset

#endif

            ) {

        vnc_client_write_locked(opaque);

    } else if (vs->csock != -1) {

        qemu_set_fd_handler(vs->csock, vnc_client_read, NULL, vs);

    }

    vnc_unlock_output(vs);

}


static inline void RENAME(yuv2packed2)(SwsContext *c, const uint16_t *buf0, const uint16_t *buf1, const uint16_t *uvbuf0, const uint16_t *uvbuf1,

                          const uint16_t *abuf0, const uint16_t *abuf1, uint8_t *dest, int dstW, int yalpha, int uvalpha, int y)

{

    int  yalpha1=4095- yalpha;

    int uvalpha1=4095-uvalpha;

    int i;

#if COMPILE_TEMPLATE_MMX

    if(!(c->flags & SWS_BITEXACT)) {

        switch(c->dstFormat) {

        //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(

        case PIX_FMT_RGB32:

            if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

#if ARCH_X86_64

                __asm__ volatile(

                    YSCALEYUV2RGB(%%r8, %5)

                    YSCALEYUV2RGB_YA(%%r8, %5, %6, %7)

                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/

                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/

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

                    WRITEBGR32(%4, 8280(%5), %%r8, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "r" (dest),

                    "a" (&c->redDither)

                    ,"r" (abuf0), "r" (abuf1)

                    : "%r8"

                );

#else

                c->u_temp=(intptr_t)abuf0;

                c->v_temp=(intptr_t)abuf1;

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB(%%REGBP, %5)

                    "push                   %0              \n\t"

                    "push                   %1              \n\t"

                    "mov          "U_TEMP"(%5), %0          \n\t"

                    "mov          "V_TEMP"(%5), %1          \n\t"

                    YSCALEYUV2RGB_YA(%%REGBP, %5, %0, %1)

                    "psraw                  $3, %%mm1       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/

                    "psraw                  $3, %%mm7       \n\t" /* abuf0[eax] - abuf1[eax] >>7*/

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

                    "pop                    %1              \n\t"

                    "pop                    %0              \n\t"

                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

#endif

            } else {

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB(%%REGBP, %5)

                    "pcmpeqd %%mm7, %%mm7                   \n\t"

                    WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

            }

            return;

        case PIX_FMT_BGR24:

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB(%%REGBP, %5)

                "pxor    %%mm7, %%mm7                   \n\t"

                WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                "a" (&c->redDither)

            );

            return;

        case PIX_FMT_RGB555:

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB(%%REGBP, %5)

                "pxor    %%mm7, %%mm7                   \n\t"

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

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                WRITERGB15(%%REGb, 8280(%5), %%REGBP)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                "a" (&c->redDither)

            );

            return;

        case PIX_FMT_RGB565:

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2RGB(%%REGBP, %5)

                "pxor    %%mm7, %%mm7                   \n\t"

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

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                WRITERGB16(%%REGb, 8280(%5), %%REGBP)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                "a" (&c->redDither)

            );

            return;

        case PIX_FMT_YUYV422:

            __asm__ volatile(

                "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                "push %%"REG_BP"                        \n\t"

                YSCALEYUV2PACKED(%%REGBP, %5)

                WRITEYUY2(%%REGb, 8280(%5), %%REGBP)

                "pop %%"REG_BP"                         \n\t"

                "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                "a" (&c->redDither)

            );

            return;

        default: break;

        }

    }

#endif //COMPILE_TEMPLATE_MMX

    YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB2_C, YSCALE_YUV_2_PACKED2_C(void,0), YSCALE_YUV_2_GRAY16_2_C, YSCALE_YUV_2_MONO2_C)

}


static void default_qemu_fd_register(int fd)

{

}


int bdrv_is_sg(BlockDriverState *bs)

{

    return bs->sg;

}


void cpu_dump_state (CPUState *env, FILE *f, fprintf_function cpu_fprintf,

                     int flags)

{

#define RGPL  4

#define RFPL  4

    int i;

    cpu_fprintf(f, "NIP " TARGET_FMT_lx "   LR " TARGET_FMT_lx " CTR "

                TARGET_FMT_lx " XER " TARGET_FMT_lx "\n",

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

    cpu_fprintf(f, "MSR " TARGET_FMT_lx " HID0 " TARGET_FMT_lx "  HF "

                TARGET_FMT_lx " idx %d\n", env->msr, env->spr[SPR_HID0],

                env->hflags, env->mmu_idx);

#if !defined(NO_TIMER_DUMP)

    cpu_fprintf(f, "TB %08" PRIu32 " %08" PRIu64

#if !defined(CONFIG_USER_ONLY)

                " DECR %08" PRIu32

#endif

                "\n",

                cpu_ppc_load_tbu(env), cpu_ppc_load_tbl(env)

#if !defined(CONFIG_USER_ONLY)

                , cpu_ppc_load_decr(env)

#endif

                );

#endif

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

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

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

        cpu_fprintf(f, " %016" PRIx64, ppc_dump_gpr(env, i));

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

            cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "CR ");

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

        cpu_fprintf(f, "%01x", env->crf[i]);

    cpu_fprintf(f, "  [");

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

        char a = '-';

        if (env->crf[i] & 0x08)

            a = 'L';

        else if (env->crf[i] & 0x04)

            a = 'G';

        else if (env->crf[i] & 0x02)

            a = 'E';

        cpu_fprintf(f, " %c%c", a, env->crf[i] & 0x01 ? 'O' : ' ');

    }

    cpu_fprintf(f, " ]             RES " TARGET_FMT_lx "\n",

                env->reserve_addr);

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

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

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

        cpu_fprintf(f, " %016" PRIx64, *((uint64_t *)&env->fpr[i]));

        if ((i & (RFPL - 1)) == (RFPL - 1))

            cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "FPSCR %08x\n", env->fpscr);

#if !defined(CONFIG_USER_ONLY)

    cpu_fprintf(f, "SRR0 " TARGET_FMT_lx " SRR1 " TARGET_FMT_lx " SDR1 "

                TARGET_FMT_lx "\n", env->spr[SPR_SRR0], env->spr[SPR_SRR1],

                env->sdr1);

#endif

#undef RGPL

#undef RFPL

}


static int sockaddr_to_str(char *dest, int max_len,

                           struct sockaddr_storage *ss, socklen_t ss_len,

                           struct sockaddr_storage *ps, socklen_t ps_len,

                           bool is_listen, bool is_telnet)

{

    char shost[NI_MAXHOST], sserv[NI_MAXSERV];

    char phost[NI_MAXHOST], pserv[NI_MAXSERV];

    const char *left = "", *right = "";

    switch (ss->ss_family) {

#ifndef _WIN32

    case AF_UNIX:

        return snprintf(dest, max_len, "unix:%s%s",

                        ((struct sockaddr_un *)(ss))->sun_path,

                        is_listen ? ",server" : "");

#endif

    case AF_INET6:

        left  = "[";

        right = "]";

        /* fall through */

    case AF_INET:

        getnameinfo((struct sockaddr *) ss, ss_len, shost, sizeof(shost),

                    sserv, sizeof(sserv), NI_NUMERICHOST | NI_NUMERICSERV);

        getnameinfo((struct sockaddr *) ps, ps_len, phost, sizeof(phost),

                    pserv, sizeof(pserv), NI_NUMERICHOST | NI_NUMERICSERV);

        return snprintf(dest, max_len, "%s:%s%s%s:%s%s <-> %s%s%s:%s",

                        is_telnet ? "telnet" : "tcp",

                        left, shost, right, sserv,

                        is_listen ? ",server" : "",

                        left, phost, right, pserv);

    default:

        return snprintf(dest, max_len, "unknown");

    }

}


static inline unsigned int get_seg_limit(uint32_t e1, uint32_t e2)

{

    unsigned int limit;

    limit = (e1 & 0xffff) | (e2 & 0x000f0000);

    if (e2 & DESC_G_MASK)

        limit = (limit << 12) | 0xfff;

    return limit;

}


void hmp_info_block(Monitor *mon, const QDict *qdict)

{

    BlockInfoList *block_list, *info;

    ImageInfo *image_info;

    const char *device = qdict_get_try_str(qdict, "device");

    bool verbose = qdict_get_try_bool(qdict, "verbose", 0);

    block_list = qmp_query_block(NULL);

    for (info = block_list; info; info = info->next) {

        if (device && strcmp(device, info->value->device)) {

            continue;

        }

        monitor_printf(mon, "%s: removable=%d",

                       info->value->device, info->value->removable);

        if (info->value->removable) {

            monitor_printf(mon, " locked=%d", info->value->locked);

            monitor_printf(mon, " tray-open=%d", info->value->tray_open);

        }

        if (info->value->has_io_status) {

            monitor_printf(mon, " io-status=%s",

                           BlockDeviceIoStatus_lookup[info->value->io_status]);

        }

        if (info->value->has_inserted) {

            monitor_printf(mon, " file=");

            monitor_print_filename(mon, info->value->inserted->file);

            if (info->value->inserted->has_backing_file) {

                monitor_printf(mon, " backing_file=");

                monitor_print_filename(mon, info->value->inserted->backing_file);

                monitor_printf(mon, " backing_file_depth=%" PRId64,

                    info->value->inserted->backing_file_depth);

            }

            monitor_printf(mon, " ro=%d drv=%s encrypted=%d",

                           info->value->inserted->ro,

                           info->value->inserted->drv,

                           info->value->inserted->encrypted);

            monitor_printf(mon, " bps=%" PRId64 " bps_rd=%" PRId64

                            " bps_wr=%" PRId64 " iops=%" PRId64

                            " iops_rd=%" PRId64 " iops_wr=%" PRId64,

                            info->value->inserted->bps,

                            info->value->inserted->bps_rd,

                            info->value->inserted->bps_wr,

                            info->value->inserted->iops,

                            info->value->inserted->iops_rd,

                            info->value->inserted->iops_wr);

            if (verbose) {

                monitor_printf(mon, " images:\n");

                image_info = info->value->inserted->image;

                while (1) {

                        bdrv_image_info_dump((fprintf_function)monitor_printf,

                                             mon, image_info);

                    if (image_info->has_backing_image) {

                        image_info = image_info->backing_image;

                    } else {

                        break;

                    }

                }

            }

        } else {

            monitor_printf(mon, " [not inserted]");

        }

        monitor_printf(mon, "\n");

    }

    qapi_free_BlockInfoList(block_list);

}


void put_no_rnd_pixels16_xy2_altivec(uint8_t * block, const uint8_t * pixels, int line_size, int h)

{

POWERPC_TBL_DECLARE(altivec_put_no_rnd_pixels16_xy2_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    int j;

POWERPC_TBL_START_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);

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

      int i;

      const uint32_t a = (((const struct unaligned_32 *) (pixels))->l);

      const uint32_t b =

        (((const struct unaligned_32 *) (pixels + 1))->l);

      uint32_t l0 =

        (a & 0x03030303UL) + (b & 0x03030303UL) + 0x01010101UL;

      uint32_t h0 =

        ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

      uint32_t l1, h1;

      pixels += line_size;

      for (i = 0; i < h; i += 2) {

        uint32_t a = (((const struct unaligned_32 *) (pixels))->l);

        uint32_t b = (((const struct unaligned_32 *) (pixels + 1))->l);

        l1 = (a & 0x03030303UL) + (b & 0x03030303UL);

        h1 = ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

        *((uint32_t *) block) =

          h0 + h1 + (((l0 + l1) >> 2) & 0x0F0F0F0FUL);

        pixels += line_size;

        block += line_size;

        a = (((const struct unaligned_32 *) (pixels))->l);

        b = (((const struct unaligned_32 *) (pixels + 1))->l);

        l0 = (a & 0x03030303UL) + (b & 0x03030303UL) + 0x01010101UL;

        h0 = ((a & 0xFCFCFCFCUL) >> 2) + ((b & 0xFCFCFCFCUL) >> 2);

        *((uint32_t *) block) =

          h0 + h1 + (((l0 + l1) >> 2) & 0x0F0F0F0FUL);

        pixels += line_size;

        block += line_size;

      } pixels += 4 - line_size * (h + 1);

      block += 4 - line_size * h;

    }

POWERPC_TBL_STOP_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

   register int i;

   register vector unsigned char

     pixelsv1, pixelsv2, pixelsv3, pixelsv4;

   register vector unsigned char

     blockv, temp1, temp2;

   register vector unsigned short

     pixelssum1, pixelssum2, temp3,

     pixelssum3, pixelssum4, temp4;

   register const vector unsigned char vczero = (const vector unsigned char)vec_splat_u8(0);

   register const vector unsigned short vcone = (const vector unsigned short)vec_splat_u16(1);

   register const vector unsigned short vctwo = (const vector unsigned short)vec_splat_u16(2);

POWERPC_TBL_START_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);

   temp1 = vec_ld(0, pixels);

   temp2 = vec_ld(16, pixels);

   pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(0, pixels));

   if ((((unsigned long)pixels) & 0x0000000F) ==  0x0000000F)

   {

     pixelsv2 = temp2;

   }

   else

   {

     pixelsv2 = vec_perm(temp1, temp2, vec_lvsl(1, pixels));

   }

   pixelsv3 = vec_mergel(vczero, pixelsv1);

   pixelsv4 = vec_mergel(vczero, pixelsv2);

   pixelsv1 = vec_mergeh(vczero, pixelsv1);

   pixelsv2 = vec_mergeh(vczero, pixelsv2);

   pixelssum3 = vec_add((vector unsigned short)pixelsv3,

                        (vector unsigned short)pixelsv4);

   pixelssum3 = vec_add(pixelssum3, vcone);

   pixelssum1 = vec_add((vector unsigned short)pixelsv1,

                        (vector unsigned short)pixelsv2);

   pixelssum1 = vec_add(pixelssum1, vcone);

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

     blockv = vec_ld(0, block);

     temp1 = vec_ld(line_size, pixels);

     temp2 = vec_ld(line_size + 16, pixels);

     pixelsv1 = vec_perm(temp1, temp2, vec_lvsl(line_size, pixels));

     if (((((unsigned long)pixels) + line_size) & 0x0000000F) ==  0x0000000F)

     {

       pixelsv2 = temp2;

     }

     else

     {

       pixelsv2 = vec_perm(temp1, temp2, vec_lvsl(line_size + 1, pixels));

     }

     pixelsv3 = vec_mergel(vczero, pixelsv1);

     pixelsv4 = vec_mergel(vczero, pixelsv2);

     pixelsv1 = vec_mergeh(vczero, pixelsv1);

     pixelsv2 = vec_mergeh(vczero, pixelsv2);

     pixelssum4 = vec_add((vector unsigned short)pixelsv3,

                          (vector unsigned short)pixelsv4);

     pixelssum2 = vec_add((vector unsigned short)pixelsv1,

                          (vector unsigned short)pixelsv2);

     temp4 = vec_add(pixelssum3, pixelssum4);

     temp4 = vec_sra(temp4, vctwo);

     temp3 = vec_add(pixelssum1, pixelssum2);

     temp3 = vec_sra(temp3, vctwo);

     pixelssum3 = vec_add(pixelssum4, vcone);

     pixelssum1 = vec_add(pixelssum2, vcone);

     blockv = vec_packsu(temp3, temp4);

     vec_st(blockv, 0, block);

     block += line_size;

     pixels += line_size;

   }

POWERPC_TBL_STOP_COUNT(altivec_put_no_rnd_pixels16_xy2_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


static inline void rv34_mc(RV34DecContext *r, const int block_type,

                          const int xoff, const int yoff, int mv_off,

                          const int width, const int height, int dir,

                          const int thirdpel, int weighted,

                          qpel_mc_func (*qpel_mc)[16],

                          h264_chroma_mc_func (*chroma_mc))

{

    MpegEncContext *s = &r->s;

    uint8_t *Y, *U, *V, *srcY, *srcU, *srcV;

    int dxy, mx, my, umx, umy, lx, ly, uvmx, uvmy, src_x, src_y, uvsrc_x, uvsrc_y;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride + mv_off;

    int is16x16 = 1;

    if(thirdpel){

        int chroma_mx, chroma_my;

        mx = (s->current_picture_ptr->f.motion_val[dir][mv_pos][0] + (3 << 24)) / 3 - (1 << 24);

        my = (s->current_picture_ptr->f.motion_val[dir][mv_pos][1] + (3 << 24)) / 3 - (1 << 24);

        lx = (s->current_picture_ptr->f.motion_val[dir][mv_pos][0] + (3 << 24)) % 3;

        ly = (s->current_picture_ptr->f.motion_val[dir][mv_pos][1] + (3 << 24)) % 3;

        chroma_mx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] / 2;

        chroma_my = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] / 2;

        umx = (chroma_mx + (3 << 24)) / 3 - (1 << 24);

        umy = (chroma_my + (3 << 24)) / 3 - (1 << 24);

        uvmx = chroma_coeffs[(chroma_mx + (3 << 24)) % 3];

        uvmy = chroma_coeffs[(chroma_my + (3 << 24)) % 3];

    }else{

        int cx, cy;

        mx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] >> 2;

        my = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] >> 2;

        lx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] & 3;

        ly = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] & 3;

        cx = s->current_picture_ptr->f.motion_val[dir][mv_pos][0] / 2;

        cy = s->current_picture_ptr->f.motion_val[dir][mv_pos][1] / 2;

        umx = cx >> 2;

        umy = cy >> 2;

        uvmx = (cx & 3) << 1;

        uvmy = (cy & 3) << 1;

        //due to some flaw RV40 uses the same MC compensation routine for H2V2 and H3V3

        if(uvmx == 6 && uvmy == 6)

            uvmx = uvmy = 4;

    }

    if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME)) {

        /* wait for the referenced mb row to be finished */

        int mb_row = FFMIN(s->mb_height - 1, s->mb_y + ((yoff + my + 21) >> 4));

        AVFrame *f = dir ? &s->next_picture_ptr->f : &s->last_picture_ptr->f;

        ff_thread_await_progress(f, mb_row, 0);

    }

    dxy = ly*4 + lx;

    srcY = dir ? s->next_picture_ptr->f.data[0] : s->last_picture_ptr->f.data[0];

    srcU = dir ? s->next_picture_ptr->f.data[1] : s->last_picture_ptr->f.data[1];

    srcV = dir ? s->next_picture_ptr->f.data[2] : s->last_picture_ptr->f.data[2];

    src_x = s->mb_x * 16 + xoff + mx;

    src_y = s->mb_y * 16 + yoff + my;

    uvsrc_x = s->mb_x * 8 + (xoff >> 1) + umx;

    uvsrc_y = s->mb_y * 8 + (yoff >> 1) + umy;

    srcY += src_y * s->linesize + src_x;

    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;

    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

    if(s->h_edge_pos - (width << 3) < 6 || s->v_edge_pos - (height << 3) < 6 ||

       (unsigned)(src_x - !!lx*2) > s->h_edge_pos - !!lx*2 - (width <<3) - 4 ||

       (unsigned)(src_y - !!ly*2) > s->v_edge_pos - !!ly*2 - (height<<3) - 4) {

        uint8_t *uvbuf = s->edge_emu_buffer + 22 * s->linesize;

        srcY -= 2 + 2*s->linesize;

        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize, (width<<3)+6, (height<<3)+6,

                            src_x - 2, src_y - 2, s->h_edge_pos, s->v_edge_pos);

        srcY = s->edge_emu_buffer + 2 + 2*s->linesize;

        s->dsp.emulated_edge_mc(uvbuf     , srcU, s->uvlinesize, (width<<2)+1, (height<<2)+1,

                            uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);

        s->dsp.emulated_edge_mc(uvbuf + 16, srcV, s->uvlinesize, (width<<2)+1, (height<<2)+1,

                            uvsrc_x, uvsrc_y, s->h_edge_pos >> 1, s->v_edge_pos >> 1);

        srcU = uvbuf;

        srcV = uvbuf + 16;

    }

    if(!weighted){

        Y = s->dest[0] + xoff      + yoff     *s->linesize;

        U = s->dest[1] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

        V = s->dest[2] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

    }else{

        Y = r->tmp_b_block_y [dir]     +  xoff     +  yoff    *s->linesize;

        U = r->tmp_b_block_uv[dir*2]   + (xoff>>1) + (yoff>>1)*s->uvlinesize;

        V = r->tmp_b_block_uv[dir*2+1] + (xoff>>1) + (yoff>>1)*s->uvlinesize;

    }

    if(block_type == RV34_MB_P_16x8){

        qpel_mc[1][dxy](Y, srcY, s->linesize);

        Y    += 8;

        srcY += 8;

    }else if(block_type == RV34_MB_P_8x16){

        qpel_mc[1][dxy](Y, srcY, s->linesize);

        Y    += 8 * s->linesize;

        srcY += 8 * s->linesize;

    }

    is16x16 = (block_type != RV34_MB_P_8x8) && (block_type != RV34_MB_P_16x8) && (block_type != RV34_MB_P_8x16);

    qpel_mc[!is16x16][dxy](Y, srcY, s->linesize);

    chroma_mc[2-width]   (U, srcU, s->uvlinesize, height*4, uvmx, uvmy);

    chroma_mc[2-width]   (V, srcV, s->uvlinesize, height*4, uvmx, uvmy);

}


static int ftp_retrieve(FTPContext *s)

{

    char command[CONTROL_BUFFER_SIZE];

    const int retr_codes[] = {150, 550, 0}; /* 550 is incorrect code */

    snprintf(command, sizeof(command), "RETR %s\r\n", s->path);

    if (ftp_send_command(s, command, retr_codes, NULL) != 150)

        return AVERROR(EIO);

    s->state = DOWNLOADING;

    return 0;

}


void dct_unquantize_h263_altivec(MpegEncContext *s,

                                 DCTELEM *block, int n, int qscale)

{

POWERPC_TBL_DECLARE(altivec_dct_unquantize_h263_num, 1);

    int i, level, qmul, qadd;

    int nCoeffs;

    assert(s->block_last_index[n]>=0);

POWERPC_TBL_START_COUNT(altivec_dct_unquantize_h263_num, 1);

    qadd = (qscale - 1) | 1;

    qmul = qscale << 1;

    if (s->mb_intra) {

        if (!s->h263_aic) {

            if (n < 4)

                block[0] = block[0] * s->y_dc_scale;

            else

                block[0] = block[0] * s->c_dc_scale;

        }else

            qadd = 0;

        i = 1;

        nCoeffs= 63; //does not allways use zigzag table

    } else {

        i = 0;

        nCoeffs= s->intra_scantable.raster_end[ s->block_last_index[n] ];

    }

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    for(;i<=nCoeffs;i++) {

        level = block[i];

        if (level) {

            if (level < 0) {

                level = level * qmul - qadd;

            } else {

                level = level * qmul + qadd;

            }

            block[i] = level;

        }

    }

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    {

      register const vector short vczero = (const vector short)vec_splat_s16(0);

      short __attribute__ ((aligned(16))) qmul8[] =

          {

            qmul, qmul, qmul, qmul,

            qmul, qmul, qmul, qmul

          };

      short __attribute__ ((aligned(16))) qadd8[] =

          {

            qadd, qadd, qadd, qadd,

            qadd, qadd, qadd, qadd

          };

      short __attribute__ ((aligned(16))) nqadd8[] =

          {

            -qadd, -qadd, -qadd, -qadd,

            -qadd, -qadd, -qadd, -qadd

          };

      register vector short blockv, qmulv, qaddv, nqaddv, temp1;

      register vector bool short blockv_null, blockv_neg;

      register short backup_0 = block[0];

      register int j = 0;

      qmulv = vec_ld(0, qmul8);

      qaddv = vec_ld(0, qadd8);

      nqaddv = vec_ld(0, nqadd8);

#if 0 // block *is* 16 bytes-aligned, it seems.

      // first make sure block[j] is 16 bytes-aligned

      for(j = 0; (j <= nCoeffs) && ((((unsigned long)block) + (j << 1)) & 0x0000000F) ; j++) {

        level = block[j];

        if (level) {

          if (level < 0) {

                level = level * qmul - qadd;

            } else {

                level = level * qmul + qadd;

            }

            block[j] = level;

        }

      }

#endif

      // vectorize all the 16 bytes-aligned blocks

      // of 8 elements

      for(; (j + 7) <= nCoeffs ; j+=8)

      {

        blockv = vec_ld(j << 1, block);

        blockv_neg = vec_cmplt(blockv, vczero);

        blockv_null = vec_cmpeq(blockv, vczero);

        // choose between +qadd or -qadd as the third operand

        temp1 = vec_sel(qaddv, nqaddv, blockv_neg);

        // multiply & add (block{i,i+7} * qmul [+-] qadd)

        temp1 = vec_mladd(blockv, qmulv, temp1);

        // put 0 where block[{i,i+7} used to have 0

        blockv = vec_sel(temp1, blockv, blockv_null);

        vec_st(blockv, j << 1, block);

      }

      // if nCoeffs isn't a multiple of 8, finish the job

      // using good old scalar units.

      // (we could do it using a truncated vector,

      // but I'm not sure it's worth the hassle)

      for(; j <= nCoeffs ; j++) {

        level = block[j];

        if (level) {

          if (level < 0) {

                level = level * qmul - qadd;

            } else {

                level = level * qmul + qadd;

            }

            block[j] = level;

        }

      }

      if (i == 1)

      { // cheat. this avoid special-casing the first iteration

        block[0] = backup_0;

      }

    }

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

POWERPC_TBL_STOP_COUNT(altivec_dct_unquantize_h263_num, nCoeffs == 63);

}


DECL_IMDCT_BLOCKS(sse,sse)

DECL_IMDCT_BLOCKS(sse2,sse)

DECL_IMDCT_BLOCKS(sse3,sse)

DECL_IMDCT_BLOCKS(ssse3,sse)

DECL_IMDCT_BLOCKS(avx,avx)

#endif /* HAVE_YASM */

void ff_mpadsp_init_mmx(MPADSPContext *s)

{

    int mm_flags = av_get_cpu_flags();

    int i, j;

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

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

            mdct_win_sse[0][j][4*i    ] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[0][j][4*i + 1] = ff_mdct_win_float[j + 4][i];

            mdct_win_sse[0][j][4*i + 2] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[0][j][4*i + 3] = ff_mdct_win_float[j + 4][i];

            mdct_win_sse[1][j][4*i    ] = ff_mdct_win_float[0    ][i];

            mdct_win_sse[1][j][4*i + 1] = ff_mdct_win_float[4    ][i];

            mdct_win_sse[1][j][4*i + 2] = ff_mdct_win_float[j    ][i];

            mdct_win_sse[1][j][4*i + 3] = ff_mdct_win_float[j + 4][i];

        }

    }

#if HAVE_SSE2_INLINE

    if (mm_flags & AV_CPU_FLAG_SSE2) {

        s->apply_window_float = apply_window_mp3;

    }

#endif /* HAVE_SSE2_INLINE */

#if HAVE_YASM

    if (mm_flags & AV_CPU_FLAG_AVX && HAVE_AVX) {

        s->imdct36_blocks_float = imdct36_blocks_avx;

#if HAVE_SSE

    } else if (mm_flags & AV_CPU_FLAG_SSSE3) {

        s->imdct36_blocks_float = imdct36_blocks_ssse3;

    } else if (mm_flags & AV_CPU_FLAG_SSE3) {

        s->imdct36_blocks_float = imdct36_blocks_sse3;

    } else if (mm_flags & AV_CPU_FLAG_SSE2) {

        s->imdct36_blocks_float = imdct36_blocks_sse2;

    } else if (mm_flags & AV_CPU_FLAG_SSE) {

        s->imdct36_blocks_float = imdct36_blocks_sse;

#endif /* HAVE_SSE */

    }

#endif /* HAVE_YASM */

}


static inline int sub_left_prediction(HYuvContext *s, uint8_t *dst,

                                      const uint8_t *src, int w, int left)

{

    int i;

    if (s->bps <= 8) {

        if (w < 32) {

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

                const int temp = src[i];

                dst[i] = temp - left;

                left   = temp;

            }

            return left;

        } else {

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

                const int temp = src[i];

                dst[i] = temp - left;

                left   = temp;

            }

            s->llvidencdsp.diff_bytes(dst + 32, src + 32, src + 31, w - 32);

            return src[w-1];

        }

    } else {

        const uint16_t *src16 = (const uint16_t *)src;

        uint16_t       *dst16 = (      uint16_t *)dst;

        if (w < 32) {

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

                const int temp = src16[i];

                dst16[i] = temp - left;

                left   = temp;

            }

            return left;

        } else {

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

                const int temp = src16[i];

                dst16[i] = temp - left;

                left   = temp;

            }

            s->hencdsp.diff_int16(dst16 + 16, src16 + 16, src16 + 15, s->n - 1, w - 16);

            return src16[w-1];

        }

    }

}


void kvm_arm_reset_vcpu(ARMCPU *cpu)

{

    /* Re-init VCPU so that all registers are set to

     * their respective reset values.

     */

    kvm_arm_vcpu_init(CPU(cpu));

    write_kvmstate_to_list(cpu);

}


static uint32_t icp_accept(struct icp_server_state *ss)

{

    uint32_t xirr = ss->xirr;

    qemu_irq_lower(ss->output);

    ss->xirr = ss->pending_priority << 24;

    trace_xics_icp_accept(xirr, ss->xirr);

    return xirr;

}


VIOsPAPRBus *spapr_vio_bus_init(void)

{

    VIOsPAPRBus *bus;

    BusState *qbus;

    DeviceState *dev;

    /* Create bridge device */

    dev = qdev_create(NULL, "spapr-vio-bridge");

    qdev_init_nofail(dev);

    /* Create bus on bridge device */

    qbus = qbus_create(TYPE_SPAPR_VIO_BUS, dev, "spapr-vio");

    bus = DO_UPCAST(VIOsPAPRBus, bus, qbus);

    bus->next_reg = 0x1000;

    /* hcall-vio */

    spapr_register_hypercall(H_VIO_SIGNAL, h_vio_signal);

    /* hcall-tce */

    spapr_register_hypercall(H_PUT_TCE, h_put_tce);

    /* hcall-crq */

    spapr_register_hypercall(H_REG_CRQ, h_reg_crq);

    spapr_register_hypercall(H_FREE_CRQ, h_free_crq);

    spapr_register_hypercall(H_SEND_CRQ, h_send_crq);

    spapr_register_hypercall(H_ENABLE_CRQ, h_enable_crq);

    /* RTAS calls */

    spapr_rtas_register("ibm,set-tce-bypass", rtas_set_tce_bypass);

    spapr_rtas_register("quiesce", rtas_quiesce);

    return bus;

}


int ffurl_register_protocol(URLProtocol *protocol, int size)

{

    URLProtocol **p;

    if (size < sizeof(URLProtocol)) {

        URLProtocol *temp = av_mallocz(sizeof(URLProtocol));

        memcpy(temp, protocol, size);

        protocol = temp;

    }

    p = &first_protocol;

    while (*p != NULL)

        p = &(*p)->next;

    *p             = protocol;

    protocol->next = NULL;

    return 0;

}


static void vmsvga_update_display(void *opaque)

{

    struct vmsvga_state_s *s = opaque;

    DisplaySurface *surface;

    bool dirty = false;

    if (!s->enable) {

        s->vga.update(&s->vga);

        return;

    }

    vmsvga_check_size(s);

    surface = qemu_console_surface(s->vga.con);

    vmsvga_fifo_run(s);

    vmsvga_update_rect_flush(s);

    /*

     * Is it more efficient to look at vram VGA-dirty bits or wait

     * for the driver to issue SVGA_CMD_UPDATE?

     */

    if (memory_region_is_logging(&s->vga.vram)) {

        vga_sync_dirty_bitmap(&s->vga);

        dirty = memory_region_get_dirty(&s->vga.vram, 0,

            surface_stride(surface) * surface_height(surface),

            DIRTY_MEMORY_VGA);

    }

    if (s->invalidated || dirty) {

        s->invalidated = 0;

        memcpy(surface_data(surface), s->vga.vram_ptr,

               surface_stride(surface) * surface_height(surface));

        dpy_gfx_update(s->vga.con, 0, 0,

                   surface_width(surface), surface_height(surface));

    }

    if (dirty) {

        memory_region_reset_dirty(&s->vga.vram, 0,

            surface_stride(surface) * surface_height(surface),

            DIRTY_MEMORY_VGA);

    }

}


static void rv34_idct_add_c(uint8_t *dst, int stride, DCTELEM *block){

    int      temp[16];

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int      i;

    rv34_row_transform(temp, block);

    memset(block, 0, 16*sizeof(DCTELEM));

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

        const int z0 = 13*(temp[4*0+i] +    temp[4*2+i]) + 0x200;

        const int z1 = 13*(temp[4*0+i] -    temp[4*2+i]) + 0x200;

        const int z2 =  7* temp[4*1+i] - 17*temp[4*3+i];

        const int z3 = 17* temp[4*1+i] +  7*temp[4*3+i];

        dst[0] = cm[ dst[0] + ( (z0 + z3) >> 10 ) ];

        dst[1] = cm[ dst[1] + ( (z1 + z2) >> 10 ) ];

        dst[2] = cm[ dst[2] + ( (z1 - z2) >> 10 ) ];

        dst[3] = cm[ dst[3] + ( (z0 - z3) >> 10 ) ];

        dst  += stride;

    }

}


static void vfio_msi_interrupt(void *opaque)

{

    VFIOMSIVector *vector = opaque;

    VFIODevice *vdev = vector->vdev;

    int nr = vector - vdev->msi_vectors;

    if (!event_notifier_test_and_clear(&vector->interrupt)) {

        return;

    }

    DPRINTF("%s(%04x:%02x:%02x.%x) vector %d\n", __func__,

            vdev->host.domain, vdev->host.bus, vdev->host.slot,

            vdev->host.function, nr);

    if (vdev->interrupt == VFIO_INT_MSIX) {

        msix_notify(&vdev->pdev, nr);

    } else if (vdev->interrupt == VFIO_INT_MSI) {

        msi_notify(&vdev->pdev, nr);

    } else {

        error_report("vfio: MSI interrupt receieved, but not enabled?");

    }

}


int av_reallocp(void *ptr, size_t size)

{

    void **ptrptr = ptr;

    void *ret;

    ret = av_realloc(*ptrptr, size);

    if (!ret) {

        return AVERROR(ENOMEM);

    *ptrptr = ret;


static int alac_decode_frame(AVCodecContext *avctx, void *data,

                             int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *inbuffer = avpkt->data;

    int input_buffer_size = avpkt->size;

    ALACContext *alac = avctx->priv_data;

    int channels;

    unsigned int outputsamples;

    int hassize;

    unsigned int readsamplesize;

    int isnotcompressed;

    uint8_t interlacing_shift;

    uint8_t interlacing_leftweight;

    int i, ch, ret;

    init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);

    channels = get_bits(&alac->gb, 3) + 1;

    if (channels != avctx->channels) {

        av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");

        return AVERROR_INVALIDDATA;

    }

    /* 2^result = something to do with output waiting.

     * perhaps matters if we read > 1 frame in a pass?

     */

    skip_bits(&alac->gb, 4);

    skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */

    /* the output sample size is stored soon */

    hassize = get_bits1(&alac->gb);

    alac->extra_bits = get_bits(&alac->gb, 2) << 3;

    /* whether the frame is compressed */

    isnotcompressed = get_bits1(&alac->gb);

    if (hassize) {

        /* now read the number of samples as a 32bit integer */

        outputsamples = get_bits_long(&alac->gb, 32);

        if(outputsamples > alac->setinfo_max_samples_per_frame){

            av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);

            return -1;

        }

    } else

        outputsamples = alac->setinfo_max_samples_per_frame;

    /* get output buffer */

    if (outputsamples > INT32_MAX) {

        av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);

        return AVERROR_INVALIDDATA;

    }

    alac->frame.nb_samples = outputsamples;

    if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {

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

        return ret;

    }

    readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;

    if (readsamplesize > MIN_CACHE_BITS) {

        av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);

        return -1;

    }

    if (!isnotcompressed) {

        /* so it is compressed */

        int16_t predictor_coef_table[MAX_CHANNELS][32];

        int predictor_coef_num[MAX_CHANNELS];

        int prediction_type[MAX_CHANNELS];

        int prediction_quantitization[MAX_CHANNELS];

        int ricemodifier[MAX_CHANNELS];

        interlacing_shift = get_bits(&alac->gb, 8);

        interlacing_leftweight = get_bits(&alac->gb, 8);

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

            prediction_type[ch] = get_bits(&alac->gb, 4);

            prediction_quantitization[ch] = get_bits(&alac->gb, 4);

            ricemodifier[ch] = get_bits(&alac->gb, 3);

            predictor_coef_num[ch] = get_bits(&alac->gb, 5);

            /* read the predictor table */

            for (i = 0; i < predictor_coef_num[ch]; i++)

                predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);

        }

        if (alac->extra_bits) {

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

                for (ch = 0; ch < channels; ch++)

                    alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);

            }

        }

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

            bastardized_rice_decompress(alac,

                                        alac->predicterror_buffer[ch],

                                        outputsamples,

                                        readsamplesize,

                                        alac->setinfo_rice_initialhistory,

                                        alac->setinfo_rice_kmodifier,

                                        ricemodifier[ch] * alac->setinfo_rice_historymult / 4,

                                        (1 << alac->setinfo_rice_kmodifier) - 1);

            if (prediction_type[ch] == 0) {

                /* adaptive fir */

                predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],

                                               alac->outputsamples_buffer[ch],

                                               outputsamples,

                                               readsamplesize,

                                               predictor_coef_table[ch],

                                               predictor_coef_num[ch],

                                               prediction_quantitization[ch]);

            } else {

                av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[ch]);

                /* I think the only other prediction type (or perhaps this is

                 * just a boolean?) runs adaptive fir twice.. like:

                 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)

                 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)

                 * little strange..

                 */

            }

        }

    } else {

        /* not compressed, easy case */

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

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

                alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,

                                                                   alac->setinfo_sample_size);

            }

        }

        alac->extra_bits = 0;

        interlacing_shift = 0;

        interlacing_leftweight = 0;

    }

    if (get_bits(&alac->gb, 3) != 7)

        av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");

    if (channels == 2 && interlacing_leftweight) {

        decorrelate_stereo(alac->outputsamples_buffer, outputsamples,

                           interlacing_shift, interlacing_leftweight);

    }

    if (alac->extra_bits) {

        append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,

                          alac->extra_bits, alac->numchannels, outputsamples);

    }

    switch(alac->setinfo_sample_size) {

    case 16:

        if (channels == 2) {

            interleave_stereo_16(alac->outputsamples_buffer,

                                 (int16_t *)alac->frame.data[0], outputsamples);

        } else {

            int16_t *outbuffer = (int16_t *)alac->frame.data[0];

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

                outbuffer[i] = alac->outputsamples_buffer[0][i];

            }

        }

        break;

    case 24:

        if (channels == 2) {

            interleave_stereo_24(alac->outputsamples_buffer,

                                 (int32_t *)alac->frame.data[0], outputsamples);

        } else {

            int32_t *outbuffer = (int32_t *)alac->frame.data[0];

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

                outbuffer[i] = alac->outputsamples_buffer[0][i] << 8;

        }

        break;

    }

    if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)

        av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));

    *got_frame_ptr   = 1;

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

    return input_buffer_size;

}


static int avi_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf_size <= 32)

        return 0;

    if (p->buf[0] == 'R' && p->buf[1] == 'I' &&

        p->buf[2] == 'F' && p->buf[3] == 'F' &&

        p->buf[8] == 'A' && p->buf[9] == 'V' &&

        p->buf[10] == 'I' && (p->buf[11] == ' ' || p->buf[11] == 0x19))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static int decode_user_data(MpegEncContext *s, GetBitContext *gb){

    char buf[256];

    int i;

    int e;

    int ver = 0, build = 0, ver2 = 0, ver3 = 0;

    char last;

    for(i=0; i<255 && get_bits_count(gb) < gb->size_in_bits; i++){

        if(show_bits(gb, 23) == 0) break;

        buf[i]= get_bits(gb, 8);

    }

    buf[i]=0;

    /* divx detection */

    e=sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);

    if(e<2)

        e=sscanf(buf, "DivX%db%d%c", &ver, &build, &last);

    if(e>=2){

        s->divx_version= ver;

        s->divx_build= build;

        s->divx_packed= e==3 && last=='p';

        if(s->divx_packed)

            av_log(s->avctx, AV_LOG_WARNING, "Invalid and inefficient vfw-avi packed B frames detected\n");

    }

    /* ffmpeg detection */

    e=sscanf(buf, "FFmpe%*[^b]b%d", &build)+3;

    if(e!=4)

        e=sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);

    if(e!=4){

        e=sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3)+1;

        if (e>1)

            build= (ver<<16) + (ver2<<8) + ver3;

    }

    if(e!=4){

        if(strcmp(buf, "ffmpeg")==0){

            s->lavc_build= 4600;

        }

    }

    if(e==4){

        s->lavc_build= build;

    }

    /* Xvid detection */

    e=sscanf(buf, "XviD%d", &build);

    if(e==1){

        s->xvid_build= build;

    }

//printf("User Data: %s\n", buf);

    return 0;

}


static void RENAME(yuv2yuv1_ar)(SwsContext *c, const int16_t *lumSrc,

                                const int16_t *chrUSrc, const int16_t *chrVSrc,

                                const int16_t *alpSrc,

                                uint8_t *dest, uint8_t *uDest, uint8_t *vDest,

                                uint8_t *aDest, int dstW, int chrDstW)

{

    int p= 4;

    const int16_t *src[4]= { alpSrc + dstW, lumSrc + dstW, chrUSrc + chrDstW, chrVSrc + chrDstW };

    uint8_t *dst[4]= { aDest, dest, uDest, vDest };

    x86_reg counter[4]= { dstW, dstW, chrDstW, chrDstW };

    while (p--) {

        if (dst[p]) {

            __asm__ volatile(

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

                "pcmpeqw %%mm7, %%mm7                 \n\t"

                "psrlw                 $15, %%mm7     \n\t"

                "psllw                  $6, %%mm7     \n\t"

                ".p2align                4            \n\t" /* FIXME Unroll? */

                "1:                                   \n\t"

                "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"

                "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"

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

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

                "psraw                 $7, %%mm0      \n\t"

                "psraw                 $7, %%mm1      \n\t"

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

                MOVNTQ(%%mm0, (%1, %%REGa))

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

                "jnc                   1b             \n\t"

                :: "r" (src[p]), "r" (dst[p] + counter[p]),

                   "g" (-counter[p])

                : "%"REG_a

            );

        }

    }

}


void ff_put_h264_qpel8_mc02_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_vt_8w_msa(src - (stride * 2), stride, dst, stride, 8);

}


static int read_pakt_chunk(AVFormatContext *s, int64_t size)

{

    AVIOContext *pb = s->pb;

    AVStream *st      = s->streams[0];

    CaffContext *caf  = s->priv_data;

    int64_t pos = 0, ccount;

    int num_packets, i;

    ccount = avio_tell(pb);

    num_packets = avio_rb64(pb);

    if (num_packets < 0 || INT32_MAX / sizeof(AVIndexEntry) < num_packets)

        return AVERROR_INVALIDDATA;

    st->nb_frames  = avio_rb64(pb); /* valid frames */

    st->nb_frames += avio_rb32(pb); /* priming frames */

    st->nb_frames += avio_rb32(pb); /* remainder frames */

    st->duration = 0;

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

        av_add_index_entry(s->streams[0], pos, st->duration, 0, 0, AVINDEX_KEYFRAME);

        pos += caf->bytes_per_packet ? caf->bytes_per_packet : ff_mp4_read_descr_len(pb);

        st->duration += caf->frames_per_packet ? caf->frames_per_packet : ff_mp4_read_descr_len(pb);

    }

    if (avio_tell(pb) - ccount != size) {

        av_log(s, AV_LOG_ERROR, "error reading packet table\n");

        return -1;

    }

    caf->num_bytes = pos;

    return 0;

}


static void vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,

                                        int jobnr, int threadnr)

{

    decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0);

}


static av_cold int qdm2_decode_init(AVCodecContext *avctx)

{

    QDM2Context *s = avctx->priv_data;

    uint8_t *extradata;

    int extradata_size;

    int tmp_val, tmp, size;

    /* extradata parsing

    Structure:

    wave {

        frma (QDM2)

        QDCA

        QDCP

    }

    32  size (including this field)

    32  tag (=frma)

    32  type (=QDM2 or QDMC)

    32  size (including this field, in bytes)

    32  tag (=QDCA) // maybe mandatory parameters

    32  unknown (=1)

    32  channels (=2)

    32  samplerate (=44100)

    32  bitrate (=96000)

    32  block size (=4096)

    32  frame size (=256) (for one channel)

    32  packet size (=1300)

    32  size (including this field, in bytes)

    32  tag (=QDCP) // maybe some tuneable parameters

    32  float1 (=1.0)

    32  zero ?

    32  float2 (=1.0)

    32  float3 (=1.0)

    32  unknown (27)

    32  unknown (8)

    32  zero ?

    */

    if (!avctx->extradata || (avctx->extradata_size < 48)) {

        av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");

        return -1;

    }

    extradata = avctx->extradata;

    extradata_size = avctx->extradata_size;

    while (extradata_size > 7) {

        if (!memcmp(extradata, "frmaQDM", 7))

            break;

        extradata++;

        extradata_size--;

    }

    if (extradata_size < 12) {

        av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",

               extradata_size);

        return -1;

    }

    if (memcmp(extradata, "frmaQDM", 7)) {

        av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");

        return -1;

    }

    if (extradata[7] == 'C') {

//        s->is_qdmc = 1;

        av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");

        return -1;

    }

    extradata += 8;

    extradata_size -= 8;

    size = AV_RB32(extradata);

    if(size > extradata_size){

        av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",

               extradata_size, size);

        return -1;

    }

    extradata += 4;

    av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);

    if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {

        av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");

        return -1;

    }

    extradata += 8;

    avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);

    extradata += 4;

    if (s->channels > MPA_MAX_CHANNELS)

    avctx->sample_rate = AV_RB32(extradata);

    extradata += 4;

    avctx->bit_rate = AV_RB32(extradata);

    extradata += 4;

    s->group_size = AV_RB32(extradata);

    extradata += 4;

    s->fft_size = AV_RB32(extradata);

    extradata += 4;

    s->checksum_size = AV_RB32(extradata);

    s->fft_order = av_log2(s->fft_size) + 1;

    s->fft_frame_size = 2 * s->fft_size; // complex has two floats

    // something like max decodable tones

    s->group_order = av_log2(s->group_size) + 1;

    s->frame_size = s->group_size / 16; // 16 iterations per super block

    s->sub_sampling = s->fft_order - 7;

    s->frequency_range = 255 / (1 << (2 - s->sub_sampling));

    switch ((s->sub_sampling * 2 + s->channels - 1)) {

        case 0: tmp = 40; break;

        case 1: tmp = 48; break;

        case 2: tmp = 56; break;

        case 3: tmp = 72; break;

        case 4: tmp = 80; break;

        case 5: tmp = 100;break;

        default: tmp=s->sub_sampling; break;

    }

    tmp_val = 0;

    if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;

    if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;

    if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;

    if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;

    s->cm_table_select = tmp_val;

    if (s->sub_sampling == 0)

        tmp = 7999;

    else

        tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;

    /*

    0: 7999 -> 0

    1: 20000 -> 2

    2: 28000 -> 2

    */

    if (tmp < 8000)

        s->coeff_per_sb_select = 0;

    else if (tmp <= 16000)

        s->coeff_per_sb_select = 1;

    else

        s->coeff_per_sb_select = 2;

    // Fail on unknown fft order

    if ((s->fft_order < 7) || (s->fft_order > 9)) {

        av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);

        return -1;

    }

    ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);

    ff_mpadsp_init(&s->mpadsp);

    qdm2_init(s);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

//    dump_context(s);

    return 0;

}


void usb_packet_unmap(USBPacket *p)

{

    int is_write = (p->pid == USB_TOKEN_IN);

    int i;

    for (i = 0; i < p->iov.niov; i++) {

        cpu_physical_memory_unmap(p->iov.iov[i].iov_base,

                                  p->iov.iov[i].iov_len, is_write,

                                  p->iov.iov[i].iov_len);

    }

}


static void gen_mfc0 (DisasContext *ctx, int reg, int sel)

{

    const char *rn = "invalid";

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_op_mfc0_index();

            rn = "Index";

            break;

        case 1:

//            gen_op_mfc0_mvpcontrol(); /* MT ASE */

            rn = "MVPControl";

//            break;

        case 2:

//            gen_op_mfc0_mvpconf0(); /* MT ASE */

            rn = "MVPConf0";

//            break;

        case 3:

//            gen_op_mfc0_mvpconf1(); /* MT ASE */

            rn = "MVPConf1";

//            break;

        default:

            goto die;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

            gen_op_mfc0_random();

            rn = "Random";

            break;

        case 1:

//            gen_op_mfc0_vpecontrol(); /* MT ASE */

            rn = "VPEControl";

//            break;

        case 2:

//            gen_op_mfc0_vpeconf0(); /* MT ASE */

            rn = "VPEConf0";

//            break;

        case 3:

//            gen_op_mfc0_vpeconf1(); /* MT ASE */

            rn = "VPEConf1";

//            break;

        case 4:

//            gen_op_mfc0_YQMask(); /* MT ASE */

            rn = "YQMask";

//            break;

        case 5:

//            gen_op_mfc0_vpeschedule(); /* MT ASE */

            rn = "VPESchedule";

//            break;

        case 6:

//            gen_op_mfc0_vpeschefback(); /* MT ASE */

            rn = "VPEScheFBack";

//            break;

        case 7:

//            gen_op_mfc0_vpeopt(); /* MT ASE */

            rn = "VPEOpt";

//            break;

        default:

            goto die;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

            gen_op_mfc0_entrylo0();

            rn = "EntryLo0";

            break;

        case 1:

//            gen_op_mfc0_tcstatus(); /* MT ASE */

            rn = "TCStatus";

//            break;

        case 2:

//            gen_op_mfc0_tcbind(); /* MT ASE */

            rn = "TCBind";

//            break;

        case 3:

//            gen_op_mfc0_tcrestart(); /* MT ASE */

            rn = "TCRestart";

//            break;

        case 4:

//            gen_op_mfc0_tchalt(); /* MT ASE */

            rn = "TCHalt";

//            break;

        case 5:

//            gen_op_mfc0_tccontext(); /* MT ASE */

            rn = "TCContext";

//            break;

        case 6:

//            gen_op_mfc0_tcschedule(); /* MT ASE */

            rn = "TCSchedule";

//            break;

        case 7:

//            gen_op_mfc0_tcschefback(); /* MT ASE */

            rn = "TCScheFBack";

//            break;

        default:

            goto die;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

            gen_op_mfc0_entrylo1();

            rn = "EntryLo1";

            break;

        default:

            goto die;

        }

        break;

    case 4:

        switch (sel) {

        case 0:

            gen_op_mfc0_context();

            rn = "Context";

            break;

        case 1:

//            gen_op_mfc0_contextconfig(); /* SmartMIPS ASE */

            rn = "ContextConfig";

//            break;

        default:

            goto die;

        }

        break;

    case 5:

        switch (sel) {

        case 0:

            gen_op_mfc0_pagemask();

            rn = "PageMask";

            break;

        case 1:

            gen_op_mfc0_pagegrain();

            rn = "PageGrain";

            break;

        default:

            goto die;

        }

        break;

    case 6:

        switch (sel) {

        case 0:

            gen_op_mfc0_wired();

            rn = "Wired";

            break;

        case 1:

//            gen_op_mfc0_srsconf0(); /* shadow registers */

            rn = "SRSConf0";

//            break;

        case 2:

//            gen_op_mfc0_srsconf1(); /* shadow registers */

            rn = "SRSConf1";

//            break;

        case 3:

//            gen_op_mfc0_srsconf2(); /* shadow registers */

            rn = "SRSConf2";

//            break;

        case 4:

//            gen_op_mfc0_srsconf3(); /* shadow registers */

            rn = "SRSConf3";

//            break;

        case 5:

//            gen_op_mfc0_srsconf4(); /* shadow registers */

            rn = "SRSConf4";

//            break;

        default:

            goto die;

        }

        break;

    case 7:

        switch (sel) {

        case 0:

            gen_op_mfc0_hwrena();

            rn = "HWREna";

            break;

        default:

            goto die;

        }

        break;

    case 8:

        switch (sel) {

        case 0:

            gen_op_mfc0_badvaddr();

            rn = "BadVaddr";

            break;

        default:

            goto die;

       }

        break;

    case 9:

        switch (sel) {

        case 0:

            gen_op_mfc0_count();

            rn = "Count";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 10:

        switch (sel) {

        case 0:

            gen_op_mfc0_entryhi();

            rn = "EntryHi";

            break;

        default:

            goto die;

        }

        break;

    case 11:

        switch (sel) {

        case 0:

            gen_op_mfc0_compare();

            rn = "Compare";

            break;

        /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 12:

        switch (sel) {

        case 0:

            gen_op_mfc0_status();

            rn = "Status";

            break;

        case 1:

            gen_op_mfc0_intctl();

            rn = "IntCtl";

            break;

        case 2:

            gen_op_mfc0_srsctl();

            rn = "SRSCtl";

            break;

        case 3:

            gen_op_mfc0_srsmap();

            rn = "SRSMap";

            break;

        default:

            goto die;

       }

        break;

    case 13:

        switch (sel) {

        case 0:

            gen_op_mfc0_cause();

            rn = "Cause";

            break;

        default:

            goto die;

       }

        break;

    case 14:

        switch (sel) {

        case 0:

            gen_op_mfc0_epc();

            rn = "EPC";

            break;

        default:

            goto die;

        }

        break;

    case 15:

        switch (sel) {

        case 0:

            gen_op_mfc0_prid();

            rn = "PRid";

            break;

        case 1:

            gen_op_mfc0_ebase();

            rn = "EBase";

            break;

        default:

            goto die;

       }

        break;

    case 16:

        switch (sel) {

        case 0:

            gen_op_mfc0_config0();

            rn = "Config";

            break;

        case 1:

            gen_op_mfc0_config1();

            rn = "Config1";

            break;

        case 2:

            gen_op_mfc0_config2();

            rn = "Config2";

            break;

        case 3:

            gen_op_mfc0_config3();

            rn = "Config3";

            break;

        /* 4,5 are reserved */

        /* 6,7 are implementation dependent */

        case 6:

            gen_op_mfc0_config6();

            rn = "Config6";

            break;

        case 7:

            gen_op_mfc0_config7();

            rn = "Config7";

            break;

        default:

            goto die;

        }

        break;

    case 17:

        switch (sel) {

        case 0:

            gen_op_mfc0_lladdr();

            rn = "LLAddr";

            break;

        default:

            goto die;

        }

        break;

    case 18:

        switch (sel) {

        case 0 ... 7:

            gen_op_mfc0_watchlo(sel);

            rn = "WatchLo";

            break;

        default:

            goto die;

        }

        break;

    case 19:

        switch (sel) {

        case 0 ...7:

            gen_op_mfc0_watchhi(sel);

            rn = "WatchHi";

            break;

        default:

            goto die;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

#ifdef TARGET_MIPS64

            gen_op_mfc0_xcontext();

            rn = "XContext";

            break;

#endif

        default:

            goto die;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        switch (sel) {

        case 0:

            gen_op_mfc0_framemask();

            rn = "Framemask";

            break;

        default:

            goto die;

        }

        break;

    case 22:

        /* ignored */

        rn = "'Diagnostic"; /* implementation dependent */

        break;

    case 23:

        switch (sel) {

        case 0:

            gen_op_mfc0_debug(); /* EJTAG support */

            rn = "Debug";

            break;

        case 1:

//            gen_op_mfc0_tracecontrol(); /* PDtrace support */

            rn = "TraceControl";

//            break;

        case 2:

//            gen_op_mfc0_tracecontrol2(); /* PDtrace support */

            rn = "TraceControl2";

//            break;

        case 3:

//            gen_op_mfc0_usertracedata(); /* PDtrace support */

            rn = "UserTraceData";

//            break;

        case 4:

//            gen_op_mfc0_debug(); /* PDtrace support */

            rn = "TraceBPC";

//            break;

        default:

            goto die;

        }

        break;

    case 24:

        switch (sel) {

        case 0:

            gen_op_mfc0_depc(); /* EJTAG support */

            rn = "DEPC";

            break;

        default:

            goto die;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

            gen_op_mfc0_performance0();

            rn = "Performance0";

            break;

        case 1:

//            gen_op_mfc0_performance1();

            rn = "Performance1";

//            break;

        case 2:

//            gen_op_mfc0_performance2();

            rn = "Performance2";

//            break;

        case 3:

//            gen_op_mfc0_performance3();

            rn = "Performance3";

//            break;

        case 4:

//            gen_op_mfc0_performance4();

            rn = "Performance4";

//            break;

        case 5:

//            gen_op_mfc0_performance5();

            rn = "Performance5";

//            break;

        case 6:

//            gen_op_mfc0_performance6();

            rn = "Performance6";

//            break;

        case 7:

//            gen_op_mfc0_performance7();

            rn = "Performance7";

//            break;

        default:

            goto die;

        }

        break;

    case 26:

       rn = "ECC";

       break;

    case 27:

        switch (sel) {

        /* ignored */

        case 0 ... 3:

            rn = "CacheErr";

            break;

        default:

            goto die;

        }

        break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taglo();

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datalo();

            rn = "DataLo";

            break;

        default:

            goto die;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taghi();

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datahi();

            rn = "DataHi";

            break;

        default:

            goto die;

        }

        break;

    case 30:

        switch (sel) {

        case 0:

            gen_op_mfc0_errorepc();

            rn = "ErrorEPC";

            break;

        default:

            goto die;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

            gen_op_mfc0_desave(); /* EJTAG support */

            rn = "DESAVE";

            break;

        default:

            goto die;

        }

        break;

    default:

       goto die;

    }

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "mfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    return;

die:

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "mfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    generate_exception(ctx, EXCP_RI);

}


static int roq_decode_end(AVCodecContext *avctx)

{

    RoqContext *s = avctx->priv_data;

    /* release the last frame */

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

    return 0;

}


static void tgen_branch(TCGContext *s, int cc, int labelno)

{

    TCGLabel* l = &s->labels[labelno];

    if (l->has_value) {

        tgen_gotoi(s, cc, l->u.value_ptr);

    } else if (USE_LONG_BRANCHES) {

        tcg_out16(s, RIL_BRCL | (cc << 4));

        tcg_out_reloc(s, s->code_ptr, R_390_PC32DBL, labelno, -2);

        s->code_ptr += 2;

    } else {

        tcg_out16(s, RI_BRC | (cc << 4));

        tcg_out_reloc(s, s->code_ptr, R_390_PC16DBL, labelno, -2);

        s->code_ptr += 1;

    }

}


static void s390_pci_generate_event(uint8_t cc, uint16_t pec, uint32_t fh,

                                    uint32_t fid, uint64_t faddr, uint32_t e)

{

    SeiContainer *sei_cont;

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s) {

        return;

    }

    sei_cont = g_malloc0(sizeof(SeiContainer));

    sei_cont->fh = fh;

    sei_cont->fid = fid;

    sei_cont->cc = cc;

    sei_cont->pec = pec;

    sei_cont->faddr = faddr;

    sei_cont->e = e;

    QTAILQ_INSERT_TAIL(&s->pending_sei, sei_cont, link);

    css_generate_css_crws(0);

}


static void pci_spapr_set_irq(void *opaque, int irq_num, int level)

{

    /*

     * Here we use the number returned by pci_spapr_map_irq to find a

     * corresponding qemu_irq.

     */

    sPAPRPHBState *phb = opaque;

    qemu_set_irq(phb->lsi_table[irq_num].qirq, level);

}


static void test_io_channel(bool async,

                            SocketAddress *listen_addr,

                            SocketAddress *connect_addr,

                            bool passFD)

{

    QIOChannel *src, *dst;

    QIOChannelTest *test;

    if (async) {

        test_io_channel_setup_async(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, true, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

        test_io_channel_setup_async(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, false, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

    } else {

        test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, true, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

        test_io_channel_setup_sync(listen_addr, connect_addr, &src, &dst);

        g_assert(!passFD ||

                 qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(!passFD ||

                 qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_FD_PASS));

        g_assert(qio_channel_has_feature(src, QIO_CHANNEL_FEATURE_SHUTDOWN));

        g_assert(qio_channel_has_feature(dst, QIO_CHANNEL_FEATURE_SHUTDOWN));

        test = qio_channel_test_new();

        qio_channel_test_run_threads(test, false, src, dst);

        qio_channel_test_validate(test);

        object_unref(OBJECT(src));

        object_unref(OBJECT(dst));

    }

}


int floatx80_le(floatx80 a, floatx80 b, float_status *status)

{

    flag aSign, bSign;

    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( a )<<1 ) )

         || (    ( extractFloatx80Exp( b ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( b )<<1 ) )

       ) {

        float_raise(float_flag_invalid, status);

        return 0;

    }

    aSign = extractFloatx80Sign( a );

    bSign = extractFloatx80Sign( b );

    if ( aSign != bSign ) {

        return

               aSign

            || (    ( ( (uint16_t) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )

                 == 0 );

    }

    return

          aSign ? le128( b.high, b.low, a.high, a.low )

        : le128( a.high, a.low, b.high, b.low );

}


int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,

    int nb_sectors, QEMUIOVector *qiov)

{

    trace_bdrv_co_writev(bs, sector_num, nb_sectors);

    return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);

}


static int vfw_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    struct vfw_ctx *ctx = s->priv_data;

    AVCodecContext *codec;

    AVStream *st;

    int devnum;

    int bisize;

    BITMAPINFO *bi;

    CAPTUREPARMS cparms;

    DWORD biCompression;

    WORD biBitCount;

    int width;

    int height;

    int ret;

    if(!ap->time_base.den) {

        av_log(s, AV_LOG_ERROR, "A time base must be specified.\n");

        return AVERROR_IO;

    }

    ctx->s = s;

    ctx->hwnd = capCreateCaptureWindow(NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0);

    if(!ctx->hwnd) {

        av_log(s, AV_LOG_ERROR, "Could not create capture window.\n");

        return AVERROR_IO;

    }

    /* If atoi fails, devnum==0 and the default device is used */

    devnum = atoi(s->filename);

    ret = SendMessage(ctx->hwnd, WM_CAP_DRIVER_CONNECT, devnum, 0);

    if(!ret) {

        av_log(s, AV_LOG_ERROR, "Could not connect to device.\n");

        DestroyWindow(ctx->hwnd);

        return AVERROR(ENODEV);

    }

    SendMessage(ctx->hwnd, WM_CAP_SET_OVERLAY, 0, 0);

    SendMessage(ctx->hwnd, WM_CAP_SET_PREVIEW, 0, 0);

    ret = SendMessage(ctx->hwnd, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0,

                      (LPARAM) videostream_cb);

    if(!ret) {

        av_log(s, AV_LOG_ERROR, "Could not set video stream callback.\n");

        goto fail_io;

    }

    SetWindowLongPtr(ctx->hwnd, GWLP_USERDATA, (LONG_PTR) ctx);

    st = av_new_stream(s, 0);

    if(!st) {

        vfw_read_close(s);

        return AVERROR_NOMEM;

    }

    /* Set video format */

    bisize = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, 0, 0);

    if(!bisize)

        goto fail_io;

    bi = av_malloc(bisize);

    if(!bi) {

        vfw_read_close(s);

        return AVERROR_NOMEM;

    }

    ret = SendMessage(ctx->hwnd, WM_CAP_GET_VIDEOFORMAT, bisize, (LPARAM) bi);

    if(!ret)

        goto fail_bi;

    dump_bih(s, &bi->bmiHeader);

    width  = ap->width  ? ap->width  : bi->bmiHeader.biWidth ;

    height = ap->height ? ap->height : bi->bmiHeader.biHeight;

    bi->bmiHeader.biWidth  = width ;

    bi->bmiHeader.biHeight = height;

#if 0

    /* For testing yet unsupported compressions

     * Copy these values from user-supplied verbose information */

    bi->bmiHeader.biWidth       = 320;

    bi->bmiHeader.biHeight      = 240;

    bi->bmiHeader.biPlanes      = 1;

    bi->bmiHeader.biBitCount    = 12;

    bi->bmiHeader.biCompression = MKTAG('I','4','2','0');

    bi->bmiHeader.biSizeImage   = 115200;

    dump_bih(s, &bi->bmiHeader);

#endif

    ret = SendMessage(ctx->hwnd, WM_CAP_SET_VIDEOFORMAT, bisize, (LPARAM) bi);

    if(!ret) {

        av_log(s, AV_LOG_ERROR, "Could not set Video Format.\n");

        goto fail_bi;

    }

    biCompression = bi->bmiHeader.biCompression;

    biBitCount = bi->bmiHeader.biBitCount;

    av_free(bi);

    /* Set sequence setup */

    ret = SendMessage(ctx->hwnd, WM_CAP_GET_SEQUENCE_SETUP, sizeof(cparms),

                      (LPARAM) &cparms);

    if(!ret)

        goto fail_io;

    dump_captureparms(s, &cparms);

    cparms.fYield = 1; // Spawn a background thread

    cparms.dwRequestMicroSecPerFrame =

                               (ap->time_base.num*1000000) / ap->time_base.den;

    cparms.fAbortLeftMouse = 0;

    cparms.fAbortRightMouse = 0;

    cparms.fCaptureAudio = 0;

    cparms.vKeyAbort = 0;

    ret = SendMessage(ctx->hwnd, WM_CAP_SET_SEQUENCE_SETUP, sizeof(cparms),

                      (LPARAM) &cparms);

    if(!ret)

        goto fail_io;

    codec = st->codec;

    codec->time_base = ap->time_base;

    codec->codec_type = CODEC_TYPE_VIDEO;

    codec->width = width;

    codec->height = height;

    codec->pix_fmt = vfw_pixfmt(biCompression, biBitCount);

    if(codec->pix_fmt == PIX_FMT_NONE) {

        codec->codec_id = vfw_codecid(biCompression);

        if(codec->codec_id == CODEC_ID_NONE) {

            av_log(s, AV_LOG_ERROR, "Unknown compression type. "

                             "Please report verbose (-v 9) debug information.\n");

            vfw_read_close(s);

            return AVERROR_PATCHWELCOME;

        }

        codec->bits_per_coded_sample = biBitCount;

    } else {

        codec->codec_id = CODEC_ID_RAWVIDEO;

        if(biCompression == BI_RGB)

            codec->bits_per_coded_sample = biBitCount;

    }

    av_set_pts_info(st, 32, 1, 1000);

    ctx->mutex = CreateMutex(NULL, 0, NULL);

    if(!ctx->mutex) {

        av_log(s, AV_LOG_ERROR, "Could not create Mutex.\n" );

        goto fail_io;

    }

    ctx->event = CreateEvent(NULL, 1, 0, NULL);

    if(!ctx->event) {

        av_log(s, AV_LOG_ERROR, "Could not create Event.\n" );

        goto fail_io;

    }

    ret = SendMessage(ctx->hwnd, WM_CAP_SEQUENCE_NOFILE, 0, 0);

    if(!ret) {

        av_log(s, AV_LOG_ERROR, "Could not start capture sequence.\n" );

        goto fail_io;

    }

    return 0;

fail_bi:

    av_free(bi);

fail_io:

    vfw_read_close(s);

    return AVERROR_IO;

}


size_t v9fs_pack(struct iovec *in_sg, int in_num, size_t offset,

                const void *src, size_t size)

{

    return v9fs_packunpack((void *)src, in_sg, in_num, offset, size, 1);

}


void usb_packet_setup(USBPacket *p, int pid, uint8_t addr, uint8_t ep)

{

    assert(!usb_packet_is_inflight(p));

    p->state = USB_PACKET_SETUP;

    p->pid = pid;

    p->devaddr = addr;

    p->devep = ep;

    p->result = 0;

    qemu_iovec_reset(&p->iov);

}


int nbd_client_init(BlockDriverState *bs, QIOChannelSocket *sioc,

                    const char *export, Error **errp)

{

    NbdClientSession *client = nbd_get_client_session(bs);

    int ret;

    /* NBD handshake */

    logout("session init %s\n", export);

    qio_channel_set_blocking(QIO_CHANNEL(sioc), true, NULL);

    ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), export,

                                &client->nbdflags,

                                NULL, NULL,

                                &client->ioc,

                                &client->size, errp);

    if (ret < 0) {

        logout("Failed to negotiate with the NBD server\n");

        return ret;

    }

    qemu_co_mutex_init(&client->send_mutex);

    qemu_co_mutex_init(&client->free_sema);

    client->sioc = sioc;

    object_ref(OBJECT(client->sioc));

    if (!client->ioc) {

        client->ioc = QIO_CHANNEL(sioc);

        object_ref(OBJECT(client->ioc));

    }

    /* Now that we're connected, set the socket to be non-blocking and

     * kick the reply mechanism.  */

    qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);

    nbd_client_attach_aio_context(bs, bdrv_get_aio_context(bs));

    logout("Established connection with NBD server\n");

    return 0;

}


static void cuda_writel (void *opaque, target_phys_addr_t addr, uint32_t value)

{

}


static void tcg_out_brcond64(TCGContext *s, TCGCond cond,

                             TCGArg arg1, TCGArg arg2, int const_arg2,

                             int label_index, int small)

{

    tcg_out_cmp(s, arg1, arg2, const_arg2, P_REXW);

    tcg_out_jxx(s, tcg_cond_to_jcc[cond], label_index, small);

}


static void pci_init_wmask(PCIDevice *dev)

{

    int i;

    int config_size = pci_config_size(dev);

    dev->wmask[PCI_CACHE_LINE_SIZE] = 0xff;

    dev->wmask[PCI_INTERRUPT_LINE] = 0xff;

    pci_set_word(dev->wmask + PCI_COMMAND,

                 PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);

    for (i = PCI_CONFIG_HEADER_SIZE; i < config_size; ++i)

        dev->wmask[i] = 0xff;

}


static void *vnc_worker_thread(void *arg)

{

    VncJobQueue *queue = arg;

    qemu_thread_self(&queue->thread);

    while (!vnc_worker_thread_loop(queue)) ;

    vnc_queue_clear(queue);

    return NULL;

}


int qemu_savevm_state(QEMUFile *f)

{

    int saved_vm_running;

    int ret;

    saved_vm_running = vm_running;

    vm_stop(0);

    ret = qemu_savevm_state_begin(f);

    if (ret < 0)

        goto out;

    do {

        ret = qemu_savevm_state_iterate(f);

        if (ret < 0)

            goto out;

    } while (ret == 0);

    ret = qemu_savevm_state_complete(f);

out:

    if (saved_vm_running)

        vm_start();

    return ret;

}