void HELPER(set_cp15)(CPUState *env, uint32_t insn, uint32_t val)

{

    int op1;

    int op2;

    int crm;

    op1 = (insn >> 21) & 7;

    op2 = (insn >> 5) & 7;

    crm = insn & 0xf;

    switch ((insn >> 16) & 0xf) {

    case 0:

        /* ID codes.  */

        if (arm_feature(env, ARM_FEATURE_XSCALE))

            break;

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        if (arm_feature(env, ARM_FEATURE_V7)

                && op1 == 2 && crm == 0 && op2 == 0) {

            env->cp15.c0_cssel = val & 0xf;

            break;

        }

        goto bad_reg;

    case 1: /* System configuration.  */

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            op2 = 0;

        switch (op2) {

        case 0:

            if (!arm_feature(env, ARM_FEATURE_XSCALE) || crm == 0)

                env->cp15.c1_sys = val;

            /* ??? Lots of these bits are not implemented.  */

            /* This may enable/disable the MMU, so do a TLB flush.  */

            tlb_flush(env, 1);

            break;

        case 1: /* Auxiliary cotrol register.  */

            if (arm_feature(env, ARM_FEATURE_XSCALE)) {

                env->cp15.c1_xscaleauxcr = val;

                break;

            }

            /* Not implemented.  */

            break;

        case 2:

            if (arm_feature(env, ARM_FEATURE_XSCALE))

                goto bad_reg;

            if (env->cp15.c1_coproc != val) {

                env->cp15.c1_coproc = val;

                /* ??? Is this safe when called from within a TB?  */

                tb_flush(env);

            }

            break;

        default:

            goto bad_reg;

        }

        break;

    case 2: /* MMU Page table control / MPU cache control.  */

        if (arm_feature(env, ARM_FEATURE_MPU)) {

            switch (op2) {

            case 0:

                env->cp15.c2_data = val;

                break;

            case 1:

                env->cp15.c2_insn = val;

                break;

            default:

                goto bad_reg;

            }

        } else {

	    switch (op2) {

	    case 0:

		env->cp15.c2_base0 = val;

		break;

	    case 1:

		env->cp15.c2_base1 = val;

		break;

	    case 2:

                val &= 7;

                env->cp15.c2_control = val;

		env->cp15.c2_mask = ~(((uint32_t)0xffffffffu) >> val);

                env->cp15.c2_base_mask = ~((uint32_t)0x3fffu >> val);

		break;

	    default:

		goto bad_reg;

	    }

        }

        break;

    case 3: /* MMU Domain access control / MPU write buffer control.  */

        env->cp15.c3 = val;

        tlb_flush(env, 1); /* Flush TLB as domain not tracked in TLB */

        break;

    case 4: /* Reserved.  */

        goto bad_reg;

    case 5: /* MMU Fault status / MPU access permission.  */

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            op2 = 0;

        switch (op2) {

        case 0:

            if (arm_feature(env, ARM_FEATURE_MPU))

                val = extended_mpu_ap_bits(val);

            env->cp15.c5_data = val;

            break;

        case 1:

            if (arm_feature(env, ARM_FEATURE_MPU))

                val = extended_mpu_ap_bits(val);

            env->cp15.c5_insn = val;

            break;

        case 2:

            if (!arm_feature(env, ARM_FEATURE_MPU))

                goto bad_reg;

            env->cp15.c5_data = val;

            break;

        case 3:

            if (!arm_feature(env, ARM_FEATURE_MPU))

                goto bad_reg;

            env->cp15.c5_insn = val;

            break;

        default:

            goto bad_reg;

        }

        break;

    case 6: /* MMU Fault address / MPU base/size.  */

        if (arm_feature(env, ARM_FEATURE_MPU)) {

            if (crm >= 8)

                goto bad_reg;

            env->cp15.c6_region[crm] = val;

        } else {

            if (arm_feature(env, ARM_FEATURE_OMAPCP))

                op2 = 0;

            switch (op2) {

            case 0:

                env->cp15.c6_data = val;

                break;

            case 1: /* ??? This is WFAR on armv6 */

            case 2:

                env->cp15.c6_insn = val;

                break;

            default:

                goto bad_reg;

            }

        }

        break;

    case 7: /* Cache control.  */

        env->cp15.c15_i_max = 0x000;

        env->cp15.c15_i_min = 0xff0;

        /* No cache, so nothing to do.  */

        /* ??? MPCore has VA to PA translation functions.  */

        break;

    case 8: /* MMU TLB control.  */

        switch (op2) {

        case 0: /* Invalidate all.  */

            tlb_flush(env, 0);

            break;

        case 1: /* Invalidate single TLB entry.  */

#if 0

            /* ??? This is wrong for large pages and sections.  */

            /* As an ugly hack to make linux work we always flush a 4K

               pages.  */

            val &= 0xfffff000;

            tlb_flush_page(env, val);

            tlb_flush_page(env, val + 0x400);

            tlb_flush_page(env, val + 0x800);

            tlb_flush_page(env, val + 0xc00);

#else

            tlb_flush(env, 1);

#endif

            break;

        case 2: /* Invalidate on ASID.  */

            tlb_flush(env, val == 0);

            break;

        case 3: /* Invalidate single entry on MVA.  */

            /* ??? This is like case 1, but ignores ASID.  */

            tlb_flush(env, 1);

            break;

        default:

            goto bad_reg;

        }

        break;

    case 9:

        if (arm_feature(env, ARM_FEATURE_OMAPCP))

            break;

        switch (crm) {

        case 0: /* Cache lockdown.  */

	    switch (op1) {

	    case 0: /* L1 cache.  */

		switch (op2) {

		case 0:

		    env->cp15.c9_data = val;

		    break;

		case 1:

		    env->cp15.c9_insn = val;

		    break;

		default:

		    goto bad_reg;

		}

		break;

	    case 1: /* L2 cache.  */

		/* Ignore writes to L2 lockdown/auxiliary registers.  */

		break;

	    default:

		goto bad_reg;

	    }

	    break;

        case 1: /* TCM memory region registers.  */

            /* Not implemented.  */

            goto bad_reg;

        default:

            goto bad_reg;

        }

        break;

    case 10: /* MMU TLB lockdown.  */

        /* ??? TLB lockdown not implemented.  */

        break;

    case 12: /* Reserved.  */

        goto bad_reg;

    case 13: /* Process ID.  */

        switch (op2) {

        case 0:

            /* Unlike real hardware the qemu TLB uses virtual addresses,

               not modified virtual addresses, so this causes a TLB flush.

             */

            if (env->cp15.c13_fcse != val)

              tlb_flush(env, 1);

            env->cp15.c13_fcse = val;

            break;

        case 1:

            /* This changes the ASID, so do a TLB flush.  */

            if (env->cp15.c13_context != val

                && !arm_feature(env, ARM_FEATURE_MPU))

              tlb_flush(env, 0);

            env->cp15.c13_context = val;

            break;

        case 2:

            env->cp15.c13_tls1 = val;

            break;

        case 3:

            env->cp15.c13_tls2 = val;

            break;

        case 4:

            env->cp15.c13_tls3 = val;

            break;

        default:

            goto bad_reg;

        }

        break;

    case 14: /* Reserved.  */

        goto bad_reg;

    case 15: /* Implementation specific.  */

        if (arm_feature(env, ARM_FEATURE_XSCALE)) {

            if (op2 == 0 && crm == 1) {

                if (env->cp15.c15_cpar != (val & 0x3fff)) {

                    /* Changes cp0 to cp13 behavior, so needs a TB flush.  */

                    tb_flush(env);

                    env->cp15.c15_cpar = val & 0x3fff;

                }

                break;

            }

            goto bad_reg;

        }

        if (arm_feature(env, ARM_FEATURE_OMAPCP)) {

            switch (crm) {

            case 0:

                break;

            case 1: /* Set TI925T configuration.  */

                env->cp15.c15_ticonfig = val & 0xe7;

                env->cp15.c0_cpuid = (val & (1 << 5)) ? /* OS_TYPE bit */

                        ARM_CPUID_TI915T : ARM_CPUID_TI925T;

                break;

            case 2: /* Set I_max.  */

                env->cp15.c15_i_max = val;

                break;

            case 3: /* Set I_min.  */

                env->cp15.c15_i_min = val;

                break;

            case 4: /* Set thread-ID.  */

                env->cp15.c15_threadid = val & 0xffff;

                break;

            case 8: /* Wait-for-interrupt (deprecated).  */

                cpu_interrupt(env, CPU_INTERRUPT_HALT);

                break;

            default:

                goto bad_reg;

            }

        }

        break;

    }

    return;

bad_reg:

    /* ??? For debugging only.  Should raise illegal instruction exception.  */

    cpu_abort(env, "Unimplemented cp15 register write (c%d, c%d, {%d, %d})\n",

              (insn >> 16) & 0xf, crm, op1, op2);

}


static void pci_pcnet_cleanup(NetClientState *nc)

{

    PCNetState *d = qemu_get_nic_opaque(nc);

    pcnet_common_cleanup(d);

}


static void gen_mulo(DisasContext *ctx)

{

    int l1 = gen_new_label();

    TCGv_i64 t0 = tcg_temp_new_i64();

    TCGv_i64 t1 = tcg_temp_new_i64();

    TCGv t2 = tcg_temp_new();

    /* Start with XER OV disabled, the most likely case */

    tcg_gen_movi_tl(cpu_ov, 0);

    tcg_gen_extu_tl_i64(t0, cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_extu_tl_i64(t1, cpu_gpr[rB(ctx->opcode)]);

    tcg_gen_mul_i64(t0, t0, t1);

    tcg_gen_trunc_i64_tl(t2, t0);

    gen_store_spr(SPR_MQ, t2);

    tcg_gen_shri_i64(t1, t0, 32);

    tcg_gen_trunc_i64_tl(cpu_gpr[rD(ctx->opcode)], t1);

    tcg_gen_ext32s_i64(t1, t0);

    tcg_gen_brcond_i64(TCG_COND_EQ, t0, t1, l1);

    tcg_gen_movi_tl(cpu_ov, 1);

    tcg_gen_movi_tl(cpu_so, 1);

    gen_set_label(l1);

    tcg_temp_free_i64(t0);

    tcg_temp_free_i64(t1);

    tcg_temp_free(t2);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);

}


static void test_source_flush_event_notifier(void)

{

    EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };

    event_notifier_init(&data.e, false);

    aio_set_event_notifier(ctx, &data.e, event_ready_cb);

    g_assert(g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 0);

    g_assert_cmpint(data.active, ==, 10);

    event_notifier_set(&data.e);

    g_assert(g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.active, ==, 9);

    g_assert(g_main_context_iteration(NULL, false));

    while (g_main_context_iteration(NULL, false));

    g_assert_cmpint(data.n, ==, 10);

    g_assert_cmpint(data.active, ==, 0);

    g_assert(!g_main_context_iteration(NULL, false));

    aio_set_event_notifier(ctx, &data.e, NULL);

    while (g_main_context_iteration(NULL, false));

    event_notifier_cleanup(&data.e);

}


uint32_t HELPER(v7m_mrs)(CPUARMState *env, uint32_t reg)

{

    uint32_t mask;

    unsigned el = arm_current_el(env);

    /* First handle registers which unprivileged can read */

    switch (reg) {

    case 0 ... 7: /* xPSR sub-fields */

        mask = 0;

        if ((reg & 1) && el) {

            mask |= XPSR_EXCP; /* IPSR (unpriv. reads as zero) */

        }

        if (!(reg & 4)) {

            mask |= XPSR_NZCV | XPSR_Q; /* APSR */

        }

        /* EPSR reads as zero */

        return xpsr_read(env) & mask;

        break;

    case 20: /* CONTROL */

        return env->v7m.control;

    }

    if (el == 0) {

        return 0; /* unprivileged reads others as zero */

    }

    switch (reg) {

    case 8: /* MSP */

        return (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) ?

            env->v7m.other_sp : env->regs[13];

    case 9: /* PSP */

        return (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) ?

            env->regs[13] : env->v7m.other_sp;

    case 16: /* PRIMASK */

        return env->v7m.primask[env->v7m.secure];

    case 17: /* BASEPRI */

    case 18: /* BASEPRI_MAX */

        return env->v7m.basepri[env->v7m.secure];

    case 19: /* FAULTMASK */

        return env->v7m.faultmask[env->v7m.secure];

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "Attempt to read unknown special"

                                       " register %d\n", reg);

        return 0;

    }

}


static void usbredir_control_packet(void *priv, uint32_t id,

    struct usb_redir_control_packet_header *control_packet,

    uint8_t *data, int data_len)

{

    USBRedirDevice *dev = priv;

    int len = control_packet->length;

    AsyncURB *aurb;

    DPRINTF("ctrl-in status %d len %d id %u\n", control_packet->status,

            len, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        free(data);

        return;

    }

    aurb->control_packet.status = control_packet->status;

    aurb->control_packet.length = control_packet->length;

    if (memcmp(&aurb->control_packet, control_packet,

               sizeof(*control_packet))) {

        ERROR("return control packet mismatch, please report this!\n");

        len = USB_RET_NAK;

    }

    if (aurb->packet) {

        len = usbredir_handle_status(dev, control_packet->status, len);

        if (len > 0) {

            usbredir_log_data(dev, "ctrl data in:", data, data_len);

            if (data_len <= sizeof(dev->dev.data_buf)) {

                memcpy(dev->dev.data_buf, data, data_len);

            } else {

                ERROR("ctrl buffer too small (%d > %zu)\n",

                      data_len, sizeof(dev->dev.data_buf));

                len = USB_RET_STALL;

            }

        }

        aurb->packet->result = len;

        usb_generic_async_ctrl_complete(&dev->dev, aurb->packet);

    }

    async_free(dev, aurb);

    free(data);

}


static int qemu_paio_submit(struct qemu_paiocb *aiocb, int is_write)

{

    aiocb->is_write = is_write;

    aiocb->ret = -EINPROGRESS;

    aiocb->active = 0;

    mutex_lock(&lock);

    if (idle_threads == 0 && cur_threads < max_threads)

        spawn_thread();

    TAILQ_INSERT_TAIL(&request_list, aiocb, node);

    mutex_unlock(&lock);

    cond_broadcast(&cond);

    return 0;

}


static void input_linux_event_keyboard(void *opaque)

{

    InputLinux *il = opaque;

    struct input_event event;

    int rc;

    for (;;) {

        rc = read(il->fd, &event, sizeof(event));

        if (rc != sizeof(event)) {

            if (rc < 0 && errno != EAGAIN) {

                fprintf(stderr, "%s: read: %s\n", __func__, strerror(errno));

                qemu_set_fd_handler(il->fd, NULL, NULL, NULL);

                close(il->fd);

            }

            break;

        }

        input_linux_handle_keyboard(il, &event);

    }

}


static void v9fs_create(void *opaque)

{

    int32_t fid;

    int err = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsQID qid;

    int32_t perm;

    int8_t mode;

    V9fsPath path;

    struct stat stbuf;

    V9fsString name;

    V9fsString extension;

    int iounit;

    V9fsPDU *pdu = opaque;

    v9fs_path_init(&path);

    pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name,

                  &perm, &mode, &extension);

    trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (perm & P9_STAT_MODE_DIR) {

        err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777,

                            fidp->uid, -1, &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

        err = v9fs_co_opendir(pdu, fidp);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_DIR;

    } else if (perm & P9_STAT_MODE_SYMLINK) {

        err = v9fs_co_symlink(pdu, fidp, &name,

                              extension.data, -1 , &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_LINK) {

        int32_t ofid = atoi(extension.data);

        V9fsFidState *ofidp = get_fid(pdu, ofid);

        if (ofidp == NULL) {

            err = -EINVAL;

            goto out;

        }

        err = v9fs_co_link(pdu, ofidp, fidp, &name);

        put_fid(pdu, ofidp);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            fidp->fid_type = P9_FID_NONE;

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

        err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

        if (err < 0) {

            fidp->fid_type = P9_FID_NONE;

            goto out;

        }

    } else if (perm & P9_STAT_MODE_DEVICE) {

        char ctype;

        uint32_t major, minor;

        mode_t nmode = 0;

        if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) {

            err = -errno;

            goto out;

        }

        switch (ctype) {

        case 'c':

            nmode = S_IFCHR;

            break;

        case 'b':

            nmode = S_IFBLK;

            break;

        default:

            err = -EIO;

            goto out;

        }

        nmode |= perm & 0777;

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            makedev(major, minor), nmode, &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_NAMED_PIPE) {

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            0, S_IFIFO | (perm & 0777), &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_SOCKET) {

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            0, S_IFSOCK | (perm & 0777), &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else {

        err = v9fs_co_open2(pdu, fidp, &name, -1,

                            omode_to_uflags(mode)|O_CREAT, perm, &stbuf);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_FILE;

        fidp->open_flags = omode_to_uflags(mode);

        if (fidp->open_flags & O_EXCL) {

            /*

             * We let the host file system do O_EXCL check

             * We should not reclaim such fd

             */

            fidp->flags |= FID_NON_RECLAIMABLE;

        }

    }

    iounit = get_iounit(pdu, &fidp->path);

    stat_to_qid(&stbuf, &qid);

    offset += pdu_marshal(pdu, offset, "Qd", &qid, iounit);

    err = offset;

out:

    put_fid(pdu, fidp);

out_nofid:

   complete_pdu(pdu->s, pdu, err);

   v9fs_string_free(&name);

   v9fs_string_free(&extension);

   v9fs_path_free(&path);

}


static int gen_neon_unzip(int rd, int rm, int size, int q)

{

    TCGv tmp, tmp2;

    if (size == 3 || (!q && size == 2)) {

        return 1;

    }

    tmp = tcg_const_i32(rd);

    tmp2 = tcg_const_i32(rm);

    if (q) {

        switch (size) {

        case 0:

            gen_helper_neon_qunzip8(tmp, tmp2);

            break;

        case 1:

            gen_helper_neon_qunzip16(tmp, tmp2);

            break;

        case 2:

            gen_helper_neon_qunzip32(tmp, tmp2);

            break;

        default:

            abort();

        }

    } else {

        switch (size) {

        case 0:

            gen_helper_neon_unzip8(tmp, tmp2);

            break;

        case 1:

            gen_helper_neon_unzip16(tmp, tmp2);

            break;

        default:

            abort();

        }

    }

    tcg_temp_free_i32(tmp);

    tcg_temp_free_i32(tmp2);

    return 0;

}


static void gen_wait(DisasContext *ctx)

{

    TCGv_i32 t0 = tcg_temp_new_i32();

    tcg_gen_st_i32(t0, cpu_env,

                   -offsetof(PowerPCCPU, env) + offsetof(CPUState, halted));

    tcg_temp_free_i32(t0);

    /* Stop translation, as the CPU is supposed to sleep from now */

    gen_exception_err(ctx, EXCP_HLT, 1);

}


GuestExec *qmp_guest_exec(const char *path,

                       bool has_arg, strList *arg,

                       bool has_env, strList *env,

                       bool has_input_data, const char *input_data,

                       bool has_capture_output, bool capture_output,

                       Error **err)

{

    GPid pid;

    GuestExec *ge = NULL;

    GuestExecInfo *gei;

    char **argv, **envp;

    strList arglist;

    gboolean ret;

    GError *gerr = NULL;

    gint in_fd, out_fd, err_fd;

    GIOChannel *in_ch, *out_ch, *err_ch;

    GSpawnFlags flags;

    bool has_output = (has_capture_output && capture_output);

    uint8_t *input = NULL;

    size_t ninput = 0;

    arglist.value = (char *)path;

    arglist.next = has_arg ? arg : NULL;

    if (has_input_data) {

        input = qbase64_decode(input_data, -1, &ninput, err);

        if (!input) {

            return NULL;

        }

    }

    argv = guest_exec_get_args(&arglist, true);

    envp = has_env ? guest_exec_get_args(env, false) : NULL;

    flags = G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD;

#if GLIB_CHECK_VERSION(2, 33, 2)

    flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;

#endif

    if (!has_output) {

        flags |= G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL;

    }

    ret = g_spawn_async_with_pipes(NULL, argv, envp, flags,

            guest_exec_task_setup, NULL, &pid, has_input_data ? &in_fd : NULL,

            has_output ? &out_fd : NULL, has_output ? &err_fd : NULL, &gerr);

    if (!ret) {

        error_setg(err, QERR_QGA_COMMAND_FAILED, gerr->message);

        g_error_free(gerr);

        goto done;

    }

    ge = g_new0(GuestExec, 1);

    ge->pid = gpid_to_int64(pid);

    gei = guest_exec_info_add(pid);

    gei->has_output = has_output;

    g_child_watch_add(pid, guest_exec_child_watch, gei);

    if (has_input_data) {

        gei->in.data = input;

        gei->in.size = ninput;

#ifdef G_OS_WIN32

        in_ch = g_io_channel_win32_new_fd(in_fd);

#else

        in_ch = g_io_channel_unix_new(in_fd);

#endif

        g_io_channel_set_encoding(in_ch, NULL, NULL);

        g_io_channel_set_buffered(in_ch, false);

        g_io_channel_set_flags(in_ch, G_IO_FLAG_NONBLOCK, NULL);

        g_io_add_watch(in_ch, G_IO_OUT, guest_exec_input_watch, &gei->in);

    }

    if (has_output) {

#ifdef G_OS_WIN32

        out_ch = g_io_channel_win32_new_fd(out_fd);

        err_ch = g_io_channel_win32_new_fd(err_fd);

#else

        out_ch = g_io_channel_unix_new(out_fd);

        err_ch = g_io_channel_unix_new(err_fd);

#endif

        g_io_channel_set_encoding(out_ch, NULL, NULL);

        g_io_channel_set_encoding(err_ch, NULL, NULL);

        g_io_channel_set_buffered(out_ch, false);

        g_io_channel_set_buffered(err_ch, false);

        g_io_channel_set_close_on_unref(out_ch, true);

        g_io_channel_set_close_on_unref(err_ch, true);

        g_io_add_watch(out_ch, G_IO_IN | G_IO_HUP,

                guest_exec_output_watch, &gei->out);

        g_io_add_watch(err_ch, G_IO_IN | G_IO_HUP,

                guest_exec_output_watch, &gei->err);

    }

done:

    g_free(argv);

    g_free(envp);

    return ge;

}


static inline void RENAME(bgr24ToUV_mmx)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src, long width, enum PixelFormat srcFormat)

{

    __asm__ volatile(

        "movq                   24(%4), %%mm6       \n\t"

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

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

        "1:                                         \n\t"

        PREFETCH"               64(%0)              \n\t"

        "movd                     (%0), %%mm0       \n\t"

        "movd                    2(%0), %%mm1       \n\t"

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

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

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

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

        "pmaddwd                  (%4), %%mm0       \n\t"

        "pmaddwd                 8(%4), %%mm1       \n\t"

        "pmaddwd                16(%4), %%mm2       \n\t"

        "pmaddwd                 %%mm6, %%mm3       \n\t"

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

        "paddd                   %%mm3, %%mm2       \n\t"

        "movd                    6(%0), %%mm1       \n\t"

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

        "add                       $12, %0          \n\t"

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

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

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

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

        "pmaddwd                  (%4), %%mm1       \n\t"

        "pmaddwd                 8(%4), %%mm3       \n\t"

        "pmaddwd                16(%4), %%mm4       \n\t"

        "pmaddwd                 %%mm6, %%mm5       \n\t"

        "paddd                   %%mm3, %%mm1       \n\t"

        "paddd                   %%mm5, %%mm4       \n\t"

        "movq "MANGLE(ff_bgr24toUVOffset)", %%mm3       \n\t"

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

        "paddd                   %%mm3, %%mm2       \n\t"

        "paddd                   %%mm3, %%mm1       \n\t"

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

        "psrad                     $15, %%mm0       \n\t"

        "psrad                     $15, %%mm2       \n\t"

        "psrad                     $15, %%mm1       \n\t"

        "psrad                     $15, %%mm4       \n\t"

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

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

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

        "packuswb                %%mm2, %%mm2       \n\t"

        "movd                %%mm0, (%1, %%"REG_a") \n\t"

        "movd                %%mm2, (%2, %%"REG_a") \n\t"

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

        " js                        1b              \n\t"

    : "+r" (src)

    : "r" (dstU+width), "r" (dstV+width), "g" ((x86_reg)-width), "r"(ff_bgr24toUV[srcFormat == PIX_FMT_RGB24])

    : "%"REG_a

    );

}


void intra_predict(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3],

                   VP8Macroblock *mb, int mb_x, int mb_y)

{

    int x, y, mode, nnz;

    uint32_t tr;

    /* for the first row, we need to run xchg_mb_border to init the top edge

     * to 127 otherwise, skip it if we aren't going to deblock */

    if (mb_y && (s->deblock_filter || !mb_y) && td->thread_nr == 0)

        xchg_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2],

                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,

                       s->filter.simple, 1);

    if (mb->mode < MODE_I4x4) {

        mode = check_intra_pred8x8_mode_emuedge(mb->mode, mb_x, mb_y);

        s->hpc.pred16x16[mode](dst[0], s->linesize);

    } else {

        uint8_t *ptr = dst[0];

        uint8_t *intra4x4 = mb->intra4x4_pred_mode_mb;

        uint8_t tr_top[4] = { 127, 127, 127, 127 };

        // all blocks on the right edge of the macroblock use bottom edge

        // the top macroblock for their topright edge

        uint8_t *tr_right = ptr - s->linesize + 16;

        // if we're on the right edge of the frame, said edge is extended

        // from the top macroblock

        if (mb_y && mb_x == s->mb_width - 1) {

            tr       = tr_right[-1] * 0x01010101u;

            tr_right = (uint8_t *) &tr;

        }

        if (mb->skip)

            AV_ZERO128(td->non_zero_count_cache);

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

            uint8_t *topright = ptr + 4 - s->linesize;

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

                int copy = 0, linesize = s->linesize;

                uint8_t *dst = ptr + 4 * x;

                DECLARE_ALIGNED(4, uint8_t, copy_dst)[5 * 8];

                if ((y == 0 || x == 3) && mb_y == 0) {

                    topright = tr_top;

                } else if (x == 3)

                    topright = tr_right;

                mode = check_intra_pred4x4_mode_emuedge(intra4x4[x],

                                                        mb_x + x, mb_y + y,

                                                        &copy);

                if (copy) {

                    dst      = copy_dst + 12;

                    linesize = 8;

                    if (!(mb_y + y)) {

                        copy_dst[3] = 127U;

                        AV_WN32A(copy_dst + 4, 127U * 0x01010101U);

                    } else {

                        AV_COPY32(copy_dst + 4, ptr + 4 * x - s->linesize);

                        if (!(mb_x + x)) {

                            copy_dst[3] = 129U;

                        } else {

                            copy_dst[3] = ptr[4 * x - s->linesize - 1];

                        }

                    }

                    if (!(mb_x + x)) {

                        copy_dst[11] =

                        copy_dst[19] =

                        copy_dst[27] =

                        copy_dst[35] = 129U;

                    } else {

                        copy_dst[11] = ptr[4 * x                   - 1];

                        copy_dst[19] = ptr[4 * x + s->linesize     - 1];

                        copy_dst[27] = ptr[4 * x + s->linesize * 2 - 1];

                        copy_dst[35] = ptr[4 * x + s->linesize * 3 - 1];

                    }

                }

                s->hpc.pred4x4[mode](dst, topright, linesize);

                if (copy) {

                    AV_COPY32(ptr + 4 * x,                   copy_dst + 12);

                    AV_COPY32(ptr + 4 * x + s->linesize,     copy_dst + 20);

                    AV_COPY32(ptr + 4 * x + s->linesize * 2, copy_dst + 28);

                    AV_COPY32(ptr + 4 * x + s->linesize * 3, copy_dst + 36);

                }

                nnz = td->non_zero_count_cache[y][x];

                if (nnz) {

                    if (nnz == 1)

                        s->vp8dsp.vp8_idct_dc_add(ptr + 4 * x,

                                                  td->block[y][x], s->linesize);

                    else

                        s->vp8dsp.vp8_idct_add(ptr + 4 * x,

                                               td->block[y][x], s->linesize);

                }

                topright += 4;

            }

            ptr      += 4 * s->linesize;

            intra4x4 += 4;

        }

    }

    mode = check_intra_pred8x8_mode_emuedge(mb->chroma_pred_mode, mb_x, mb_y);

    s->hpc.pred8x8[mode](dst[1], s->uvlinesize);

    s->hpc.pred8x8[mode](dst[2], s->uvlinesize);

    if (mb_y && (s->deblock_filter || !mb_y) && td->thread_nr == 0)

        xchg_mb_border(s->top_border[mb_x + 1], dst[0], dst[1], dst[2],

                       s->linesize, s->uvlinesize, mb_x, mb_y, s->mb_width,

                       s->filter.simple, 0);

}


static av_always_inline void decode_subband_internal(DiracContext *s, SubBand *b, int is_arith)

{

    int cb_x, cb_y, left, right, top, bottom;

    DiracArith c;

    GetBitContext gb;

    int cb_width  = s->codeblock[b->level + (b->orientation != subband_ll)].width;

    int cb_height = s->codeblock[b->level + (b->orientation != subband_ll)].height;

    int blockcnt_one = (cb_width + cb_height) == 2;

    if (!b->length)

        return;

    init_get_bits8(&gb, b->coeff_data, b->length);

    if (is_arith)

        ff_dirac_init_arith_decoder(&c, &gb, b->length);

    top = 0;

    for (cb_y = 0; cb_y < cb_height; cb_y++) {

        bottom = (b->height * (cb_y+1)) / cb_height;

        left = 0;

        for (cb_x = 0; cb_x < cb_width; cb_x++) {

            right = (b->width * (cb_x+1)) / cb_width;

            codeblock(s, b, &gb, &c, left, right, top, bottom, blockcnt_one, is_arith);

            left = right;

        }

        top = bottom;

    }

    if (b->orientation == subband_ll && s->num_refs == 0)

        intra_dc_prediction(b);

}


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

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

{

	int yalpha1=yalpha^4095;

	int uvalpha1=uvalpha^4095;

	if(fullUVIpol)

	{

#ifdef HAVE_MMX

		if(dstbpp == 32)

		{

			asm volatile(

FULL_YSCALEYUV2RGB

			"punpcklbw %%mm1, %%mm3		\n\t" // BGBGBGBG

			"punpcklbw %%mm7, %%mm0		\n\t" // R0R0R0R0

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

			"punpcklwd %%mm0, %%mm3		\n\t" // BGR0BGR0

			"punpckhwd %%mm0, %%mm1		\n\t" // BGR0BGR0

			MOVNTQ(%%mm3, (%4, %%eax, 4))

			MOVNTQ(%%mm1, 8(%4, %%eax, 4))

			"addl $4, %%eax			\n\t"

			"cmpl %5, %%eax			\n\t"

			" jb 1b				\n\t"

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

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

			: "%eax"

			);

		}

		else if(dstbpp==24)

		{

			asm volatile(

FULL_YSCALEYUV2RGB

								// lsb ... msb

			"punpcklbw %%mm1, %%mm3		\n\t" // BGBGBGBG

			"punpcklbw %%mm7, %%mm0		\n\t" // R0R0R0R0

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

			"punpcklwd %%mm0, %%mm3		\n\t" // BGR0BGR0

			"punpckhwd %%mm0, %%mm1		\n\t" // BGR0BGR0

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

			"psrlq $8, %%mm3		\n\t" // GR0BGR00

			"pand "MANGLE(bm00000111)", %%mm2\n\t" // BGR00000

			"pand "MANGLE(bm11111000)", %%mm3\n\t" // 000BGR00

			"por %%mm2, %%mm3		\n\t" // BGRBGR00

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

			"psllq $48, %%mm1		\n\t" // 000000BG

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

			"movq %%mm2, %%mm1		\n\t" // BGR0BGR0

			"psrld $16, %%mm2		\n\t" // R000R000

			"psrlq $24, %%mm1		\n\t" // 0BGR0000

			"por %%mm2, %%mm1		\n\t" // RBGRR000

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

			"addl %%eax, %%ebx		\n\t"

#ifdef HAVE_MMX2

			//FIXME Alignment

			"movntq %%mm3, (%%ebx, %%eax, 2)\n\t"

			"movntq %%mm1, 8(%%ebx, %%eax, 2)\n\t"

#else

			"movd %%mm3, (%%ebx, %%eax, 2)	\n\t"

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

			"movd %%mm3, 4(%%ebx, %%eax, 2)	\n\t"

			"movd %%mm1, 8(%%ebx, %%eax, 2)	\n\t"

#endif

			"addl $4, %%eax			\n\t"

			"cmpl %5, %%eax			\n\t"

			" jb 1b				\n\t"

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

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

			: "%eax", "%ebx"

			);

		}

		else if(dstbpp==15)

		{

			asm volatile(

FULL_YSCALEYUV2RGB

#ifdef DITHER1XBPP

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

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

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

#endif

			"punpcklbw %%mm7, %%mm1		\n\t" // 0G0G0G0G

			"punpcklbw %%mm7, %%mm3		\n\t" // 0B0B0B0B

			"punpcklbw %%mm7, %%mm0		\n\t" // 0R0R0R0R

			"psrlw $3, %%mm3		\n\t"

			"psllw $2, %%mm1		\n\t"

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

			"pand "MANGLE(g15Mask)", %%mm1	\n\t"

			"pand "MANGLE(r15Mask)", %%mm0	\n\t"

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

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

			MOVNTQ(%%mm0, (%4, %%eax, 2))

			"addl $4, %%eax			\n\t"

			"cmpl %5, %%eax			\n\t"

			" jb 1b				\n\t"

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

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

			: "%eax"

			);

		}

		else if(dstbpp==16)

		{

			asm volatile(

FULL_YSCALEYUV2RGB

#ifdef DITHER1XBPP

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

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

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

#endif

			"punpcklbw %%mm7, %%mm1		\n\t" // 0G0G0G0G

			"punpcklbw %%mm7, %%mm3		\n\t" // 0B0B0B0B

			"punpcklbw %%mm7, %%mm0		\n\t" // 0R0R0R0R

			"psrlw $3, %%mm3		\n\t"

			"psllw $3, %%mm1		\n\t"

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

			"pand "MANGLE(g16Mask)", %%mm1	\n\t"

			"pand "MANGLE(r16Mask)", %%mm0	\n\t"

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

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

			MOVNTQ(%%mm0, (%4, %%eax, 2))

			"addl $4, %%eax			\n\t"

			"cmpl %5, %%eax			\n\t"

			" jb 1b				\n\t"

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

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

			: "%eax"

			);

		}

#else

		if(dstbpp==32 || dstbpp==24)

		{

			int i;

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

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

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

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

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

				dest[0]=clip_table[((Y + yuvtab_40cf[U]) >>13)];

				dest[1]=clip_table[((Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13)];

				dest[2]=clip_table[((Y + yuvtab_3343[V]) >>13)];

				dest+=dstbpp>>3;

			}

		}

		else if(dstbpp==16)

		{

			int i;

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

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

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

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

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

				((uint16_t*)dest)[i] =

					clip_table16b[(Y + yuvtab_40cf[U]) >>13] |

					clip_table16g[(Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13] |

					clip_table16r[(Y + yuvtab_3343[V]) >>13];

			}

		}

		else if(dstbpp==15)

		{

			int i;

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

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

				int Y=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

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

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

				((uint16_t*)dest)[i] =

					clip_table15b[(Y + yuvtab_40cf[U]) >>13] |

					clip_table15g[(Y + yuvtab_1a1e[V] + yuvtab_0c92[U]) >>13] |

					clip_table15r[(Y + yuvtab_3343[V]) >>13];

			}

		}

#endif

	}//FULL_UV_IPOL

	else

	{

#ifdef HAVE_MMX

		if(dstbpp == 32)

		{

			asm volatile(

				YSCALEYUV2RGB

				WRITEBGR32

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

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

			: "%eax"

			);

		}

		else if(dstbpp==24)

		{

			asm volatile(

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

				YSCALEYUV2RGB

				WRITEBGR24

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

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

			: "%eax", "%ebx"

			);

		}

		else if(dstbpp==15)

		{

			asm volatile(

				YSCALEYUV2RGB

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

#ifdef DITHER1XBPP

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

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

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

#endif

				WRITEBGR15

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

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

			: "%eax"

			);

		}

		else if(dstbpp==16)

		{

			asm volatile(

				YSCALEYUV2RGB

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

#ifdef DITHER1XBPP

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

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

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

#endif

				WRITEBGR16

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

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

			: "%eax"

			);

		}

#else

		if(dstbpp==32)

		{

			int i;

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

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

				int Y1=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int Y2=yuvtab_2568[((buf0[i+1]*yalpha1+buf1[i+1]*yalpha)>>19)];

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

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

				int Cb= yuvtab_40cf[U];

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

				int Cr= yuvtab_3343[V];

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

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

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

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

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

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

			}

		}

		else if(dstbpp==24)

		{

			int i;

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

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

				int Y1=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int Y2=yuvtab_2568[((buf0[i+1]*yalpha1+buf1[i+1]*yalpha)>>19)];

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

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

				int Cb= yuvtab_40cf[U];

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

				int Cr= yuvtab_3343[V];

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

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

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

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

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

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

				dest+=6;

			}

		}

		else if(dstbpp==16)

		{

			int i;

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

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

				int Y1=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int Y2=yuvtab_2568[((buf0[i+1]*yalpha1+buf1[i+1]*yalpha)>>19)];

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

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

				int Cb= yuvtab_40cf[U];

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

				int Cr= yuvtab_3343[V];

				((uint16_t*)dest)[i] =

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

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

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

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

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

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

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

			}

		}

		else if(dstbpp==15)

		{

			int i;

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

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

				int Y1=yuvtab_2568[((buf0[i]*yalpha1+buf1[i]*yalpha)>>19)];

				int Y2=yuvtab_2568[((buf0[i+1]*yalpha1+buf1[i+1]*yalpha)>>19)];

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

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

				int Cb= yuvtab_40cf[U];

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

				int Cr= yuvtab_3343[V];

				((uint16_t*)dest)[i] =

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

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

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

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

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

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

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

			}

		}

#endif

	} //!FULL_UV_IPOL

}


static int wavpack_encode_block(WavPackEncodeContext *s,

                                int32_t *samples_l, int32_t *samples_r,

                                uint8_t *out, int out_size)

{

    int block_size, start, end, data_size, tcount, temp, m = 0;

    int i, j, ret, got_extra = 0, nb_samples = s->block_samples;

    uint32_t crc = 0xffffffffu;

    struct Decorr *dpp;

    PutByteContext pb;

    if (!(s->flags & WV_MONO) && s->optimize_mono) {

        int32_t lor = 0, diff = 0;

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

            lor  |= samples_l[i] | samples_r[i];

            diff |= samples_l[i] - samples_r[i];

            if (lor && diff)

                break;

        }

        if (i == nb_samples && lor && !diff) {

            s->flags &= ~(WV_JOINT_STEREO | WV_CROSS_DECORR);

            s->flags |= WV_FALSE_STEREO;

            if (!s->false_stereo) {

                s->false_stereo = 1;

                s->num_terms = 0;

                CLEAR(s->w);

            }

        } else if (s->false_stereo) {

            s->false_stereo = 0;

            s->num_terms = 0;

            CLEAR(s->w);

        }

    }

    if (s->flags & SHIFT_MASK) {

        int shift = (s->flags & SHIFT_MASK) >> SHIFT_LSB;

        int mag = (s->flags & MAG_MASK) >> MAG_LSB;

        if (s->flags & WV_MONO_DATA)

            shift_mono(samples_l, nb_samples, shift);

        else

            shift_stereo(samples_l, samples_r, nb_samples, shift);

        if ((mag -= shift) < 0)

            s->flags &= ~MAG_MASK;

        else

            s->flags -= (1 << MAG_LSB) * shift;

    }

    if ((s->flags & WV_FLOAT_DATA) || (s->flags & MAG_MASK) >> MAG_LSB >= 24) {

        av_fast_padded_malloc(&s->orig_l, &s->orig_l_size, sizeof(int32_t) * nb_samples);

        memcpy(s->orig_l, samples_l, sizeof(int32_t) * nb_samples);

        if (!(s->flags & WV_MONO_DATA)) {

            av_fast_padded_malloc(&s->orig_r, &s->orig_r_size, sizeof(int32_t) * nb_samples);

            memcpy(s->orig_r, samples_r, sizeof(int32_t) * nb_samples);

        }

        if (s->flags & WV_FLOAT_DATA)

            got_extra = scan_float(s, samples_l, samples_r, nb_samples);

        else

            got_extra = scan_int32(s, samples_l, samples_r, nb_samples);

        s->num_terms = 0;

    } else {

        scan_int23(s, samples_l, samples_r, nb_samples);

        if (s->shift != s->int32_zeros + s->int32_ones + s->int32_dups) {

            s->shift = s->int32_zeros + s->int32_ones + s->int32_dups;

            s->num_terms = 0;

        }

    }

    if (!s->num_passes && !s->num_terms) {

        s->num_passes = 1;

        if (s->flags & WV_MONO_DATA)

            ret = wv_mono(s, samples_l, 1, 0);

        else

            ret = wv_stereo(s, samples_l, samples_r, 1, 0);

        s->num_passes = 0;

    }

    if (s->flags & WV_MONO_DATA) {

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

            crc += (crc << 1) + samples_l[i];

        if (s->num_passes)

            ret = wv_mono(s, samples_l, !s->num_terms, 1);

    } else {

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

            crc += (crc << 3) + (samples_l[i] << 1) + samples_l[i] + samples_r[i];

        if (s->num_passes)

            ret = wv_stereo(s, samples_l, samples_r, !s->num_terms, 1);

    }

    if (ret < 0)

        return ret;

    if (!s->ch_offset)

        s->flags |= WV_INITIAL_BLOCK;

    s->ch_offset += 1 + !(s->flags & WV_MONO);

    if (s->ch_offset == s->avctx->channels)

        s->flags |= WV_FINAL_BLOCK;

    bytestream2_init_writer(&pb, out, out_size);

    bytestream2_put_le32(&pb, MKTAG('w', 'v', 'p', 'k'));

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le16(&pb, 0x410);

    bytestream2_put_le16(&pb, 0);

    bytestream2_put_le32(&pb, 0);

    bytestream2_put_le32(&pb, s->sample_index);

    bytestream2_put_le32(&pb, nb_samples);

    bytestream2_put_le32(&pb, s->flags);

    bytestream2_put_le32(&pb, crc);

    if (s->flags & WV_INITIAL_BLOCK &&

        s->avctx->channel_layout != AV_CH_LAYOUT_MONO &&

        s->avctx->channel_layout != AV_CH_LAYOUT_STEREO) {

        put_metadata_block(&pb, WP_ID_CHANINFO, 5);

        bytestream2_put_byte(&pb, s->avctx->channels);

        bytestream2_put_le32(&pb, s->avctx->channel_layout);

        bytestream2_put_byte(&pb, 0);

    }

    if ((s->flags & SRATE_MASK) == SRATE_MASK) {

        put_metadata_block(&pb, WP_ID_SAMPLE_RATE, 3);

        bytestream2_put_le24(&pb, s->avctx->sample_rate);

        bytestream2_put_byte(&pb, 0);

    }

    put_metadata_block(&pb, WP_ID_DECTERMS, s->num_terms);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        bytestream2_put_byte(&pb, ((dpp->value + 5) & 0x1f) | ((dpp->delta << 5) & 0xe0));

    }

    if (s->num_terms & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECWEIGHT(type) do {            \

        temp = store_weight(type);    \

        bytestream2_put_byte(&pb, temp);      \

        type = restore_weight(temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECWEIGHTS);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

    for (i = s->num_terms - 1; i >= 0; --i) {

        struct Decorr *dpp = &s->decorr_passes[i];

        if (store_weight(dpp->weightA) ||

            (!(s->flags & WV_MONO_DATA) && store_weight(dpp->weightB)))

                break;

    }

    tcount = i + 1;

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i < tcount) {

            WRITE_DECWEIGHT(dpp->weightA);

            if (!(s->flags & WV_MONO_DATA))

                WRITE_DECWEIGHT(dpp->weightB);

        } else {

            dpp->weightA = dpp->weightB = 0;

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 2] = WP_ID_DECWEIGHTS | (((end - start) & 1) ? WP_IDF_ODD: 0);

    out[start - 1] = (end - start + 1) >> 1;

    if ((end - start) & 1)

        bytestream2_put_byte(&pb, 0);

#define WRITE_DECSAMPLE(type) do {        \

        temp = log2s(type);               \

        type = wp_exp2(temp);             \

        bytestream2_put_le16(&pb, temp);  \

    } while (0)

    bytestream2_put_byte(&pb, WP_ID_DECSAMPLES);

    bytestream2_put_byte(&pb, 0);

    start = bytestream2_tell_p(&pb);

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

        struct Decorr *dpp = &s->decorr_passes[i];

        if (i == 0) {

            if (dpp->value > MAX_TERM) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesA[1]);

                if (!(s->flags & WV_MONO_DATA)) {

                    WRITE_DECSAMPLE(dpp->samplesB[0]);

                    WRITE_DECSAMPLE(dpp->samplesB[1]);

                }

            } else if (dpp->value < 0) {

                WRITE_DECSAMPLE(dpp->samplesA[0]);

                WRITE_DECSAMPLE(dpp->samplesB[0]);

            } else {

                for (j = 0; j < dpp->value; j++) {

                    WRITE_DECSAMPLE(dpp->samplesA[j]);

                    if (!(s->flags & WV_MONO_DATA))

                        WRITE_DECSAMPLE(dpp->samplesB[j]);

                }

            }

        } else {

            CLEAR(dpp->samplesA);

            CLEAR(dpp->samplesB);

        }

    }

    end = bytestream2_tell_p(&pb);

    out[start - 1] = (end - start) >> 1;

#define WRITE_CHAN_ENTROPY(chan) do {               \

        for (i = 0; i < 3; i++) {                   \

            temp = wp_log2(s->w.c[chan].median[i]); \

            bytestream2_put_le16(&pb, temp);        \

            s->w.c[chan].median[i] = wp_exp2(temp); \

        }                                           \

    } while (0)

    put_metadata_block(&pb, WP_ID_ENTROPY, 6 * (1 + (!(s->flags & WV_MONO_DATA))));

    WRITE_CHAN_ENTROPY(0);

    if (!(s->flags & WV_MONO_DATA))

        WRITE_CHAN_ENTROPY(1);

    if (s->flags & WV_FLOAT_DATA) {

        put_metadata_block(&pb, WP_ID_FLOATINFO, 4);

        bytestream2_put_byte(&pb, s->float_flags);

        bytestream2_put_byte(&pb, s->float_shift);

        bytestream2_put_byte(&pb, s->float_max_exp);

        bytestream2_put_byte(&pb, 127);

    }

    if (s->flags & WV_INT32_DATA) {

        put_metadata_block(&pb, WP_ID_INT32INFO, 4);

        bytestream2_put_byte(&pb, s->int32_sent_bits);

        bytestream2_put_byte(&pb, s->int32_zeros);

        bytestream2_put_byte(&pb, s->int32_ones);

        bytestream2_put_byte(&pb, s->int32_dups);

    }

    if (s->flags & WV_MONO_DATA && !s->num_passes) {

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

            int32_t code = samples_l[i];

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++) {

                int32_t sam;

                if (dpp->value > MAX_TERM) {

                    if (dpp->value & 1)

                        sam = 2 * dpp->samplesA[0] - dpp->samplesA[1];

                    else

                        sam = (3 * dpp->samplesA[0] - dpp->samplesA[1]) >> 1;

                    dpp->samplesA[1] = dpp->samplesA[0];

                    dpp->samplesA[0] = code;

                } else {

                    sam = dpp->samplesA[m];

                    dpp->samplesA[(m + dpp->value) & (MAX_TERM - 1)] = code;

                }

                code -= APPLY_WEIGHT(dpp->weightA, sam);

                UPDATE_WEIGHT(dpp->weightA, dpp->delta, sam, code);

            }

            m = (m + 1) & (MAX_TERM - 1);

            samples_l[i] = code;

        }

        if (m) {

            for (tcount = s->num_terms, dpp = s->decorr_passes; tcount--; dpp++)

                if (dpp->value > 0 && dpp->value <= MAX_TERM) {

                int32_t temp_A[MAX_TERM], temp_B[MAX_TERM];

                int k;

                memcpy(temp_A, dpp->samplesA, sizeof(dpp->samplesA));

                memcpy(temp_B, dpp->samplesB, sizeof(dpp->samplesB));

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

                    dpp->samplesA[k] = temp_A[m];

                    dpp->samplesB[k] = temp_B[m];

                    m = (m + 1) & (MAX_TERM - 1);

                }

            }

        }

    } else if (!s->num_passes) {

        if (s->flags & WV_JOINT_STEREO) {

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

                samples_r[i] += ((samples_l[i] -= samples_r[i]) >> 1);

        }

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

            struct Decorr *dpp = &s->decorr_passes[i];

            if (((s->flags & MAG_MASK) >> MAG_LSB) >= 16 || dpp->delta != 2)

                decorr_stereo_pass2(dpp, samples_l, samples_r, nb_samples);

            else

                decorr_stereo_pass_id2(dpp, samples_l, samples_r, nb_samples);

        }

    }

    bytestream2_put_byte(&pb, WP_ID_DATA | WP_IDF_LONG);

    init_put_bits(&s->pb, pb.buffer + 3, bytestream2_get_bytes_left_p(&pb));

    if (s->flags & WV_MONO_DATA) {

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

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

    } else {

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

            wavpack_encode_sample(s, &s->w.c[0], s->samples[0][i]);

            wavpack_encode_sample(s, &s->w.c[1], s->samples[1][i]);

        }

    }

    encode_flush(s);

    flush_put_bits(&s->pb);

    data_size = put_bits_count(&s->pb) >> 3;

    bytestream2_put_le24(&pb, (data_size + 1) >> 1);

    bytestream2_skip_p(&pb, data_size);

    if (data_size & 1)

        bytestream2_put_byte(&pb, 0);

    if (got_extra) {

        bytestream2_put_byte(&pb, WP_ID_EXTRABITS | WP_IDF_LONG);

        init_put_bits(&s->pb, pb.buffer + 7, bytestream2_get_bytes_left_p(&pb));

        if (s->flags & WV_FLOAT_DATA)

            pack_float(s, s->orig_l, s->orig_r, nb_samples);

        else

            pack_int32(s, s->orig_l, s->orig_r, nb_samples);

        flush_put_bits(&s->pb);

        data_size = put_bits_count(&s->pb) >> 3;

        bytestream2_put_le24(&pb, (data_size + 5) >> 1);

        bytestream2_put_le32(&pb, s->crc_x);

        bytestream2_skip_p(&pb, data_size);

        if (data_size & 1)

            bytestream2_put_byte(&pb, 0);

    }

    block_size = bytestream2_tell_p(&pb);

    AV_WL32(out + 4, block_size - 8);

    return block_size;

}


static void qemu_laio_process_completion(struct qemu_laio_state *s,

    struct qemu_laiocb *laiocb)

{

    int ret;

    s->count--;

    ret = laiocb->ret;

    if (ret != -ECANCELED) {

        if (ret == laiocb->nbytes)

            ret = 0;

        else if (ret >= 0)

            ret = -EINVAL;

        laiocb->common.cb(laiocb->common.opaque, ret);

    }

    qemu_aio_release(laiocb);

}


void throttle_get_config(ThrottleState *ts, ThrottleConfig *cfg)
{
    *cfg = ts->cfg;


vreader_xfr_bytes(VReader *reader,

                  unsigned char *send_buf, int send_buf_len,

                  unsigned char *receive_buf, int *receive_buf_len)

{

    VCardAPDU *apdu;

    VCardResponse *response = NULL;

    VCardStatus card_status;

    unsigned short status;

    VCard *card = vreader_get_card(reader);

    if (card == NULL) {

        return VREADER_NO_CARD;

    }

    apdu = vcard_apdu_new(send_buf, send_buf_len, &status);

    if (apdu == NULL) {

        response = vcard_make_response(status);

        card_status = VCARD_DONE;

    } else {

        g_debug("%s: CLS=0x%x,INS=0x%x,P1=0x%x,P2=0x%x,Lc=%d,Le=%d %s",

              __func__, apdu->a_cla, apdu->a_ins, apdu->a_p1, apdu->a_p2,

              apdu->a_Lc, apdu->a_Le, apdu_ins_to_string(apdu->a_ins));

        card_status = vcard_process_apdu(card, apdu, &response);

        if (response) {

            g_debug("%s: status=%d sw1=0x%x sw2=0x%x len=%d (total=%d)",

                  __func__, response->b_status, response->b_sw1,

                  response->b_sw2, response->b_len, response->b_total_len);

        }

    }

    assert(card_status == VCARD_DONE);

    if (card_status == VCARD_DONE) {

        int size = MIN(*receive_buf_len, response->b_total_len);

        memcpy(receive_buf, response->b_data, size);

        *receive_buf_len = size;

    }

    vcard_response_delete(response);

    vcard_apdu_delete(apdu);

    vcard_free(card); /* free our reference */

    return VREADER_OK;

}


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

{

    TSC210xState *s = (TSC210xState *) opaque;

    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    int i;

    s->x = qemu_get_be16(f);

    s->y = qemu_get_be16(f);

    s->pressure = qemu_get_byte(f);

    s->state = qemu_get_byte(f);

    s->page = qemu_get_byte(f);

    s->offset = qemu_get_byte(f);

    s->command = qemu_get_byte(f);

    s->irq = qemu_get_byte(f);

    qemu_get_be16s(f, &s->dav);

    timer_get(f, s->timer);

    s->enabled = qemu_get_byte(f);

    s->host_mode = qemu_get_byte(f);

    s->function = qemu_get_byte(f);

    s->nextfunction = qemu_get_byte(f);

    s->precision = qemu_get_byte(f);

    s->nextprecision = qemu_get_byte(f);

    s->filter = qemu_get_byte(f);

    s->pin_func = qemu_get_byte(f);

    s->ref = qemu_get_byte(f);

    s->timing = qemu_get_byte(f);

    s->noise = qemu_get_be32(f);

    qemu_get_be16s(f, &s->audio_ctrl1);

    qemu_get_be16s(f, &s->audio_ctrl2);

    qemu_get_be16s(f, &s->audio_ctrl3);

    qemu_get_be16s(f, &s->pll[0]);

    qemu_get_be16s(f, &s->pll[1]);

    qemu_get_be16s(f, &s->volume);

    s->volume_change = qemu_get_sbe64(f) + now;

    s->powerdown = qemu_get_sbe64(f) + now;

    s->softstep = qemu_get_byte(f);

    qemu_get_be16s(f, &s->dac_power);

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

        qemu_get_be16s(f, &s->filter_data[i]);

    s->busy = timer_pending(s->timer);

    qemu_set_irq(s->pint, !s->irq);

    qemu_set_irq(s->davint, !s->dav);

    return 0;


static uint16_t eepro100_read2(EEPRO100State * s, uint32_t addr)

{

    uint16_t val;

    if (addr <= sizeof(s->mem) - sizeof(val)) {

        memcpy(&val, &s->mem[addr], sizeof(val));

    }

    switch (addr) {

    case SCBStatus:

    case SCBCmd:

        TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));

        break;

    case SCBeeprom:

        val = eepro100_read_eeprom(s);

        TRACE(OTHER, logout("addr=%s val=0x%04x\n", regname(addr), val));

        break;

    default:

        logout("addr=%s val=0x%04x\n", regname(addr), val);

        missing("unknown word read");

    }

    return val;

}


static int disas_cp15_insn(CPUState *env, DisasContext *s, uint32_t insn)

{

    uint32_t rd;

    TCGv tmp, tmp2;

    /* M profile cores use memory mapped registers instead of cp15.  */

    if (arm_feature(env, ARM_FEATURE_M))

	return 1;

    if ((insn & (1 << 25)) == 0) {

        if (insn & (1 << 20)) {

            /* mrrc */

            return 1;

        }

        /* mcrr.  Used for block cache operations, so implement as no-op.  */

        return 0;

    }

    if ((insn & (1 << 4)) == 0) {

        /* cdp */

        return 1;

    }

    if (IS_USER(s) && !cp15_user_ok(insn)) {

        return 1;

    }

    /* Pre-v7 versions of the architecture implemented WFI via coprocessor

     * instructions rather than a separate instruction.

     */

    if ((insn & 0x0fff0fff) == 0x0e070f90) {

        /* 0,c7,c0,4: Standard v6 WFI (also used in some pre-v6 cores).

         * In v7, this must NOP.

         */

        if (!arm_feature(env, ARM_FEATURE_V7)) {

            /* Wait for interrupt.  */

            gen_set_pc_im(s->pc);

            s->is_jmp = DISAS_WFI;

        }

        return 0;

    }

    if ((insn & 0x0fff0fff) == 0x0e070f58) {

        /* 0,c7,c8,2: Not all pre-v6 cores implemented this WFI,

         * so this is slightly over-broad.

         */

        if (!arm_feature(env, ARM_FEATURE_V6)) {

            /* Wait for interrupt.  */

            gen_set_pc_im(s->pc);

            s->is_jmp = DISAS_WFI;

            return 0;

        }

        /* Otherwise fall through to handle via helper function.

         * In particular, on v7 and some v6 cores this is one of

         * the VA-PA registers.

         */

    }

    rd = (insn >> 12) & 0xf;

    if (cp15_tls_load_store(env, s, insn, rd))

        return 0;

    tmp2 = tcg_const_i32(insn);

    if (insn & ARM_CP_RW_BIT) {

        tmp = new_tmp();

        gen_helper_get_cp15(tmp, cpu_env, tmp2);

        /* If the destination register is r15 then sets condition codes.  */

        if (rd != 15)

            store_reg(s, rd, tmp);

        else

            dead_tmp(tmp);

    } else {

        tmp = load_reg(s, rd);

        gen_helper_set_cp15(cpu_env, tmp2, tmp);

        dead_tmp(tmp);

        /* Normally we would always end the TB here, but Linux

         * arch/arm/mach-pxa/sleep.S expects two instructions following

         * an MMU enable to execute from cache.  Imitate this behaviour.  */

        if (!arm_feature(env, ARM_FEATURE_XSCALE) ||

                (insn & 0x0fff0fff) != 0x0e010f10)

            gen_lookup_tb(s);

    }

    tcg_temp_free_i32(tmp2);

    return 0;

}


static int asf_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    ASFStream *stream;

    AVCodecContext *codec;

    uint32_t packet_number;

    int64_t pts;

    int start_sec;

    int flags = pkt->flags;

    int ret;

    uint64_t offset = avio_tell(pb);

    codec  = s->streams[pkt->stream_index]->codec;

    stream = &asf->streams[pkt->stream_index];

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)

        flags &= ~AV_PKT_FLAG_KEY;

    pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts;

    av_assert0(pts != AV_NOPTS_VALUE);

    pts *= 10000;

    asf->duration = FFMAX(asf->duration, pts + pkt->duration * 10000);

    packet_number = asf->nb_packets;

    put_frame(s, stream, s->streams[pkt->stream_index],

              pkt->dts, pkt->data, pkt->size, flags);

    start_sec = (int)((PREROLL_TIME * 10000 + pts + ASF_INDEXED_INTERVAL - 1)

              / ASF_INDEXED_INTERVAL);

    /* check index */

    if ((!asf->is_streamed) && (flags & AV_PKT_FLAG_KEY)) {

        uint16_t packet_count = asf->nb_packets - packet_number;

        ret = update_index(s, start_sec, packet_number, packet_count, offset);

        if (ret < 0)

            return ret;

    asf->end_sec = start_sec;

    return 0;


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

{

    SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass);

    DeviceClass *k = DEVICE_CLASS(klass);

    sdc->init = pl181_init;

    k->vmsd = &vmstate_pl181;

    k->reset = pl181_reset;

    k->no_user = 1;

}


static void ahci_start_transfer(IDEDMA *dma)

{

    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

    IDEState *s = &ad->port.ifs[0];

    uint32_t size = (uint32_t)(s->data_end - s->data_ptr);

    /* write == ram -> device */

    uint16_t opts = le16_to_cpu(ad->cur_cmd->opts);

    int is_write = opts & AHCI_CMD_WRITE;

    int is_atapi = opts & AHCI_CMD_ATAPI;

    int has_sglist = 0;

    if (is_atapi && !ad->done_atapi_packet) {

        /* already prepopulated iobuffer */

        ad->done_atapi_packet = true;

        size = 0;

        goto out;

    }

    if (ahci_dma_prepare_buf(dma, is_write)) {

        has_sglist = 1;

    }

    DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",

            is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",

            has_sglist ? "" : "o");

    if (has_sglist && size) {

        if (is_write) {

            dma_buf_write(s->data_ptr, size, &s->sg);

        } else {

            dma_buf_read(s->data_ptr, size, &s->sg);

        }

    }

out:

    /* declare that we processed everything */

    s->data_ptr = s->data_end;

    /* Update number of transferred bytes, destroy sglist */

    ahci_commit_buf(dma, size);

    s->end_transfer_func(s);

    if (!(s->status & DRQ_STAT)) {

        /* done with PIO send/receive */

        ahci_write_fis_pio(ad, le32_to_cpu(ad->cur_cmd->status));

    }

}


void bmdma_init(IDEBus *bus, BMDMAState *bm, PCIIDEState *d)

{

    qemu_irq *irq;

    if (bus->dma == &bm->dma) {

        return;

    }

    bm->dma.ops = &bmdma_ops;

    bus->dma = &bm->dma;

    bm->irq = bus->irq;

    irq = qemu_allocate_irqs(bmdma_irq, bm, 1);

    bus->irq = *irq;

    bm->pci_dev = d;

}


static void qemu_tcg_wait_io_event(void)

{

    CPUState *env;

    while (all_cpu_threads_idle()) {

       /* Start accounting real time to the virtual clock if the CPUs

          are idle.  */

        qemu_clock_warp(vm_clock);

        qemu_cond_wait(tcg_halt_cond, &qemu_global_mutex);

    }

    qemu_mutex_unlock(&qemu_global_mutex);

    /*

     * Users of qemu_global_mutex can be starved, having no chance

     * to acquire it since this path will get to it first.

     * So use another lock to provide fairness.

     */

    qemu_mutex_lock(&qemu_fair_mutex);

    qemu_mutex_unlock(&qemu_fair_mutex);

    qemu_mutex_lock(&qemu_global_mutex);

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        qemu_wait_io_event_common(env);

    }

}


void ff_mdct_calc_c(FFTContext *s, FFTSample *out, const FFTSample *input)

{

    int i, j, n, n8, n4, n2, n3;

    FFTDouble re, im;

    const uint16_t *revtab = s->revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    FFTComplex *x = (FFTComplex *)out;

    n = 1 << s->mdct_bits;

    n2 = n >> 1;

    n4 = n >> 2;

    n8 = n >> 3;

    n3 = 3 * n4;

    /* pre rotation */

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

        re = RSCALE(-input[2*i+n3] - input[n3-1-2*i]);

        im = RSCALE(-input[n4+2*i] + input[n4-1-2*i]);

        j = revtab[i];

        CMUL(x[j].re, x[j].im, re, im, -tcos[i], tsin[i]);

        re = RSCALE( input[2*i]    - input[n2-1-2*i]);

        im = RSCALE(-input[n2+2*i] - input[ n-1-2*i]);

        j = revtab[n8 + i];

        CMUL(x[j].re, x[j].im, re, im, -tcos[n8 + i], tsin[n8 + i]);

    }

    s->fft_calc(s, x);

    /* post rotation */

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

        FFTSample r0, i0, r1, i1;

        CMUL(i1, r0, x[n8-i-1].re, x[n8-i-1].im, -tsin[n8-i-1], -tcos[n8-i-1]);

        CMUL(i0, r1, x[n8+i  ].re, x[n8+i  ].im, -tsin[n8+i  ], -tcos[n8+i  ]);

        x[n8-i-1].re = r0;

        x[n8-i-1].im = i0;

        x[n8+i  ].re = r1;

        x[n8+i  ].im = i1;

    }

}


int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)

{

    BlockDriverState *bs;

    int ret;

    bs = bdrv_new("");

    if (!bs)

        return -ENOMEM;

    ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);

    if (ret < 0) {

        bdrv_delete(bs);

        return ret;

    }

    *pbs = bs;

    return 0;

}


static int sdp_parse_fmtp_config_h264(AVStream * stream,

                                      PayloadContext * h264_data,

                                      char *attr, char *value)

{

    AVCodecContext *codec = stream->codec;

    assert(codec->codec_id == CODEC_ID_H264);

    assert(h264_data != NULL);

    if (!strcmp(attr, "packetization-mode")) {

        av_log(codec, AV_LOG_DEBUG, "RTP Packetization Mode: %d\n", atoi(value));

        h264_data->packetization_mode = atoi(value);

        /*

           Packetization Mode:

           0 or not present: Single NAL mode (Only nals from 1-23 are allowed)

           1: Non-interleaved Mode: 1-23, 24 (STAP-A), 28 (FU-A) are allowed.

           2: Interleaved Mode: 25 (STAP-B), 26 (MTAP16), 27 (MTAP24), 28 (FU-A), and 29 (FU-B) are allowed.

         */

        if (h264_data->packetization_mode > 1)

            av_log(codec, AV_LOG_ERROR,

                   "Interleaved RTP mode is not supported yet.");

    } else if (!strcmp(attr, "profile-level-id")) {

        if (strlen(value) == 6) {

            char buffer[3];

            // 6 characters=3 bytes, in hex.

            uint8_t profile_idc;

            uint8_t profile_iop;

            uint8_t level_idc;

            buffer[0] = value[0]; buffer[1] = value[1]; buffer[2] = '\0';

            profile_idc = strtol(buffer, NULL, 16);

            buffer[0] = value[2]; buffer[1] = value[3];

            profile_iop = strtol(buffer, NULL, 16);

            buffer[0] = value[4]; buffer[1] = value[5];

            level_idc = strtol(buffer, NULL, 16);

            // set the parameters...

            av_log(codec, AV_LOG_DEBUG,

                   "RTP Profile IDC: %x Profile IOP: %x Level: %x\n",

                   profile_idc, profile_iop, level_idc);

            h264_data->profile_idc = profile_idc;

            h264_data->profile_iop = profile_iop;

            h264_data->level_idc = level_idc;

        }

    } else  if (!strcmp(attr, "sprop-parameter-sets")) {

        uint8_t start_sequence[]= { 0, 0, 1 };

        codec->extradata_size= 0;

        codec->extradata= NULL;

        while (*value) {

            char base64packet[1024];

            uint8_t decoded_packet[1024];

            uint32_t packet_size;

            char *dst = base64packet;

            while (*value && *value != ','

                   && (dst - base64packet) < sizeof(base64packet) - 1) {

                *dst++ = *value++;

            }

            *dst++ = '\0';

            if (*value == ',')

                value++;

            packet_size= av_base64_decode(decoded_packet, base64packet, sizeof(decoded_packet));

            if (packet_size) {

                uint8_t *dest = av_malloc(packet_size + sizeof(start_sequence) +

                                         codec->extradata_size +

                                         FF_INPUT_BUFFER_PADDING_SIZE);

                if(dest)

                {

                    if(codec->extradata_size)

                    {

                        // av_realloc?

                        memcpy(dest, codec->extradata, codec->extradata_size);

                        av_free(codec->extradata);

                    }

                    memcpy(dest+codec->extradata_size, start_sequence, sizeof(start_sequence));

                    memcpy(dest+codec->extradata_size+sizeof(start_sequence), decoded_packet, packet_size);

                    memset(dest+codec->extradata_size+sizeof(start_sequence)+

                           packet_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

                    codec->extradata= dest;

                    codec->extradata_size+= sizeof(start_sequence)+packet_size;

                } else {

                    av_log(codec, AV_LOG_ERROR, "Unable to allocate memory for extradata!");

                    return AVERROR(ENOMEM);

                }

            }

        }

        av_log(codec, AV_LOG_DEBUG, "Extradata set to %p (size: %d)!", codec->extradata, codec->extradata_size);

    }

    return 0;

}


void qpci_io_writeq(QPCIDevice *dev, void *data, uint64_t value)

{

    uintptr_t addr = (uintptr_t)data;

    if (addr < QPCI_PIO_LIMIT) {

        dev->bus->pio_writeq(dev->bus, addr, value);

    } else {

        value = cpu_to_le64(value);

        dev->bus->memwrite(dev->bus, addr, &value, sizeof(value));

    }

}


static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,

                          abi_ulong target_addr, socklen_t addrlen)

{

    void *addr;

    void *host_msg;

    abi_long ret;

    if ((int)addrlen < 0) {

        return -TARGET_EINVAL;

    }

    host_msg = lock_user(VERIFY_READ, msg, len, 1);

    if (!host_msg)

        return -TARGET_EFAULT;

    if (fd_trans_target_to_host_data(fd)) {

        ret = fd_trans_target_to_host_data(fd)(host_msg, len);

        if (ret < 0) {

            unlock_user(host_msg, msg, 0);

            return ret;

        }

    }

    if (target_addr) {

        addr = alloca(addrlen+1);

        ret = target_to_host_sockaddr(fd, addr, target_addr, addrlen);

        if (ret) {

            unlock_user(host_msg, msg, 0);

            return ret;

        }

        ret = get_errno(safe_sendto(fd, host_msg, len, flags, addr, addrlen));

    } else {

        ret = get_errno(safe_sendto(fd, host_msg, len, flags, NULL, 0));

    }

    unlock_user(host_msg, msg, 0);

    return ret;

}


static int vscsi_srp_direct_data(VSCSIState *s, vscsi_req *req,

                                 uint8_t *buf, uint32_t len)

{

    struct srp_direct_buf *md = req->cur_desc;

    uint32_t llen;

    int rc;

    dprintf("VSCSI: direct segment 0x%x bytes, va=0x%llx desc len=0x%x\n",

            len, (unsigned long long)md->va, md->len);

    llen = MIN(len, md->len);

    if (llen) {

        if (req->writing) { /* writing = to device = reading from memory */

            rc = spapr_tce_dma_read(&s->vdev, md->va, buf, llen);

        } else {

            rc = spapr_tce_dma_write(&s->vdev, md->va, buf, llen);

        }

    }

    md->len -= llen;

    md->va += llen;

    if (rc) {

        return -1;

    }

    return llen;

}


static inline void flash_sync_area(Flash *s, int64_t off, int64_t len)

{

    QEMUIOVector *iov = g_new(QEMUIOVector, 1);

    if (!s->blk || blk_is_read_only(s->blk)) {

        return;

    }

    assert(!(len % BDRV_SECTOR_SIZE));

    qemu_iovec_init(iov, 1);

    qemu_iovec_add(iov, s->storage + off, len);

    blk_aio_pwritev(s->blk, off, iov, 0, blk_sync_complete, iov);

}


static void gdb_vm_stopped(void *opaque, int reason)

{

    GDBState *s = opaque;

    char buf[256];

    int ret;

    if (s->state == RS_SYSCALL)

    /* disable single step if it was enable */

    cpu_single_step(s->env, 0);

    if (reason == EXCP_DEBUG) {

	tb_flush(s->env);

        ret = SIGTRAP;

    } else if (reason == EXCP_INTERRUPT) {

        ret = SIGINT;

    } else {

        ret = 0;

    snprintf(buf, sizeof(buf), "S%02x", ret);


void main_loop_wait(int timeout)

{

    IOHandlerRecord *ioh;

    fd_set rfds, wfds, xfds;

    int ret, nfds;

#ifdef _WIN32

    int ret2, i;

#endif

    struct timeval tv;

    PollingEntry *pe;

    /* XXX: need to suppress polling by better using win32 events */

    ret = 0;

    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {

        ret |= pe->func(pe->opaque);

    }

#ifdef _WIN32

    if (ret == 0) {

        int err;

        WaitObjects *w = &wait_objects;

        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);

        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {

            if (w->func[ret - WAIT_OBJECT_0])

                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);

            /* Check for additional signaled events */

            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {

                /* Check if event is signaled */

                ret2 = WaitForSingleObject(w->events[i], 0);

                if(ret2 == WAIT_OBJECT_0) {

                    if (w->func[i])

                        w->func[i](w->opaque[i]);

                } else if (ret2 == WAIT_TIMEOUT) {

                } else {

                    err = GetLastError();

                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);

                }

            }

        } else if (ret == WAIT_TIMEOUT) {

        } else {

            err = GetLastError();

            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);

        }

    }

#endif

    /* poll any events */

    /* XXX: separate device handlers from system ones */

    nfds = -1;

    FD_ZERO(&rfds);

    FD_ZERO(&wfds);

    FD_ZERO(&xfds);

    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {

        if (ioh->deleted)

            continue;

        if (ioh->fd_read &&

            (!ioh->fd_read_poll ||

             ioh->fd_read_poll(ioh->opaque) != 0)) {

            FD_SET(ioh->fd, &rfds);

            if (ioh->fd > nfds)

                nfds = ioh->fd;

        }

        if (ioh->fd_write) {

            FD_SET(ioh->fd, &wfds);

            if (ioh->fd > nfds)

                nfds = ioh->fd;

        }

    }

    tv.tv_sec = 0;

#ifdef _WIN32

    tv.tv_usec = 0;

#else

    tv.tv_usec = timeout * 1000;

#endif

#if defined(CONFIG_SLIRP)

    if (slirp_inited) {

        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);

    }

#endif

    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);

    if (ret > 0) {

        IOHandlerRecord **pioh;

        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {

            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {

                ioh->fd_read(ioh->opaque);

            }

            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {

                ioh->fd_write(ioh->opaque);

            }

        }

	/* remove deleted IO handlers */

	pioh = &first_io_handler;

	while (*pioh) {

            ioh = *pioh;

            if (ioh->deleted) {

                *pioh = ioh->next;

                qemu_free(ioh);

            } else

                pioh = &ioh->next;

        }

    }

#if defined(CONFIG_SLIRP)

    if (slirp_inited) {

        if (ret < 0) {

            FD_ZERO(&rfds);

            FD_ZERO(&wfds);

            FD_ZERO(&xfds);

        }

        slirp_select_poll(&rfds, &wfds, &xfds);

    }

#endif

    qemu_aio_poll();

    if (vm_running) {

        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))

        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],

                        qemu_get_clock(vm_clock));

        /* run dma transfers, if any */

        DMA_run();

    }

    /* real time timers */

    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],

                    qemu_get_clock(rt_clock));

    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {

        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);

        qemu_rearm_alarm_timer(alarm_timer);

    }

    /* Check bottom-halves last in case any of the earlier events triggered

       them.  */

    qemu_bh_poll();

}


static int buf_put_buffer(void *opaque, const uint8_t *buf,

                          int64_t pos, int size)

{

    QEMUBuffer *s = opaque;

    return qsb_write_at(s->qsb, buf, pos, size);

}


static void mv88w8618_eth_write(void *opaque, hwaddr offset,

                                uint64_t value, unsigned size)

{

    mv88w8618_eth_state *s = opaque;

    switch (offset) {

    case MP_ETH_SMIR:

        s->smir = value;

        break;

    case MP_ETH_PCXR:

        s->vlan_header = ((value >> MP_ETH_PCXR_2BSM_BIT) & 1) * 2;

        break;

    case MP_ETH_SDCMR:

        if (value & MP_ETH_CMD_TXHI) {

            eth_send(s, 1);

        }

        if (value & MP_ETH_CMD_TXLO) {

            eth_send(s, 0);

        }

        if (value & (MP_ETH_CMD_TXHI | MP_ETH_CMD_TXLO) && s->icr & s->imr) {

            qemu_irq_raise(s->irq);

        }

        break;

    case MP_ETH_ICR:

        s->icr &= value;

        break;

    case MP_ETH_IMR:

        s->imr = value;

        if (s->icr & s->imr) {

            qemu_irq_raise(s->irq);

        }

        break;

    case MP_ETH_FRDP0 ... MP_ETH_FRDP3:

        s->frx_queue[(offset - MP_ETH_FRDP0)/4] = value;

        break;

    case MP_ETH_CRDP0 ... MP_ETH_CRDP3:

        s->rx_queue[(offset - MP_ETH_CRDP0)/4] =

            s->cur_rx[(offset - MP_ETH_CRDP0)/4] = value;

        break;

    case MP_ETH_CTDP0 ... MP_ETH_CTDP3:

        s->tx_queue[(offset - MP_ETH_CTDP0)/4] = value;

        break;

    }

}


static int config_props(AVFilterLink *inlink)

{

    FadeContext *s = inlink->dst->priv;

    const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(inlink->format);

    s->hsub = pixdesc->log2_chroma_w;

    s->vsub = pixdesc->log2_chroma_h;

    s->bpp = av_get_bits_per_pixel(pixdesc) >> 3;

    s->alpha &= !!(pixdesc->flags & AV_PIX_FMT_FLAG_ALPHA);

    s->is_packed_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;

    /* use CCIR601/709 black level for studio-level pixel non-alpha components */

    s->black_level =

            ff_fmt_is_in(inlink->format, studio_level_pix_fmts) && !s->alpha ? 16 : 0;

    /* 32768 = 1 << 15, it is an integer representation

     * of 0.5 and is for rounding. */

    s->black_level_scaled = (s->black_level << 16) + 32768;

    return 0;

}


static void gen_msa(CPUMIPSState *env, DisasContext *ctx)

{

    uint32_t opcode = ctx->opcode;

    check_insn(ctx, ASE_MSA);

    check_msa_access(ctx);

    switch (MASK_MSA_MINOR(opcode)) {

    case OPC_MSA_I8_00:

    case OPC_MSA_I8_01:

    case OPC_MSA_I8_02:

        gen_msa_i8(env, ctx);

        break;

    case OPC_MSA_I5_06:

    case OPC_MSA_I5_07:

        gen_msa_i5(env, ctx);

        break;

    case OPC_MSA_BIT_09:

    case OPC_MSA_BIT_0A:

        gen_msa_bit(env, ctx);

        break;

    case OPC_MSA_3R_0D:

    case OPC_MSA_3R_0E:

    case OPC_MSA_3R_0F:

    case OPC_MSA_3R_10:

    case OPC_MSA_3R_11:

    case OPC_MSA_3R_12:

    case OPC_MSA_3R_13:

    case OPC_MSA_3R_14:

    case OPC_MSA_3R_15:

        gen_msa_3r(env, ctx);

        break;

    case OPC_MSA_ELM:

        gen_msa_elm(env, ctx);

        break;

    case OPC_MSA_3RF_1A:

    case OPC_MSA_3RF_1B:

    case OPC_MSA_3RF_1C:

        gen_msa_3rf(env, ctx);

        break;

    case OPC_MSA_VEC:

        gen_msa_vec(env, ctx);

        break;

    case OPC_LD_B:

    case OPC_LD_H:

    case OPC_LD_W:

    case OPC_LD_D:

    case OPC_ST_B:

    case OPC_ST_H:

    case OPC_ST_W:

    case OPC_ST_D:

        {

            int32_t s10 = sextract32(ctx->opcode, 16, 10);

            uint8_t rs = (ctx->opcode >> 11) & 0x1f;

            uint8_t wd = (ctx->opcode >> 6) & 0x1f;

            uint8_t df = (ctx->opcode >> 0) & 0x3;

            TCGv_i32 tdf = tcg_const_i32(df);

            TCGv_i32 twd = tcg_const_i32(wd);

            TCGv_i32 trs = tcg_const_i32(rs);

            TCGv_i32 ts10 = tcg_const_i32(s10);

            switch (MASK_MSA_MINOR(opcode)) {

            case OPC_LD_B:

            case OPC_LD_H:

            case OPC_LD_W:

            case OPC_LD_D:

                gen_helper_msa_ld_df(cpu_env, tdf, twd, trs, ts10);

                break;

            case OPC_ST_B:

            case OPC_ST_H:

            case OPC_ST_W:

            case OPC_ST_D:

                gen_helper_msa_st_df(cpu_env, tdf, twd, trs, ts10);

                break;

            }

            tcg_temp_free_i32(twd);

            tcg_temp_free_i32(tdf);

            tcg_temp_free_i32(trs);

            tcg_temp_free_i32(ts10);

        }

        break;

    default:

        MIPS_INVAL("MSA instruction");

        generate_exception(ctx, EXCP_RI);

        break;

    }

}


static BlockAIOCB *read_fifo_child(QuorumAIOCB *acb)

{

    BDRVQuorumState *s = acb->common.bs->opaque;

    acb->qcrs[acb->child_iter].buf =

        qemu_blockalign(s->children[acb->child_iter]->bs, acb->qiov->size);

    qemu_iovec_init(&acb->qcrs[acb->child_iter].qiov, acb->qiov->niov);

    qemu_iovec_clone(&acb->qcrs[acb->child_iter].qiov, acb->qiov,

                     acb->qcrs[acb->child_iter].buf);

    bdrv_aio_readv(s->children[acb->child_iter]->bs, acb->sector_num,

                   &acb->qcrs[acb->child_iter].qiov, acb->nb_sectors,

                   quorum_aio_cb, &acb->qcrs[acb->child_iter]);

    return &acb->common;

}


static void qmp_monitor_complete(void *opaque, QObject *ret_data)

{

    monitor_protocol_emitter(opaque, ret_data);

}


static int old_codec37(SANMVideoContext *ctx, int top,

                       int left, int width, int height)

{

    int stride = ctx->pitch;

    int i, j, k, t;

    int skip_run = 0;

    int compr, mvoff, seq, flags;

    uint32_t decoded_size;

    uint8_t *dst, *prev;

    compr        = bytestream2_get_byte(&ctx->gb);

    mvoff        = bytestream2_get_byte(&ctx->gb);

    seq          = bytestream2_get_le16(&ctx->gb);

    decoded_size = bytestream2_get_le32(&ctx->gb);

    bytestream2_skip(&ctx->gb, 4);

    flags        = bytestream2_get_byte(&ctx->gb);

    bytestream2_skip(&ctx->gb, 3);

    if (decoded_size > height * stride - left - top * stride) {

        decoded_size = height * stride - left - top * stride;

        av_log(ctx->avctx, AV_LOG_WARNING, "decoded size is too large\n");

    }

    ctx->rotate_code = 0;

    if (((seq & 1) || !(flags & 1)) && (compr && compr != 2))

        rotate_bufs(ctx, 1);

    dst  = ((uint8_t*)ctx->frm0) + left + top * stride;

    prev = ((uint8_t*)ctx->frm2) + left + top * stride;

    if (mvoff > 2) {

        av_log(ctx->avctx, AV_LOG_ERROR, "invalid motion base value %d\n", mvoff);

        return AVERROR_INVALIDDATA;

    }

    av_dlog(ctx->avctx, "compression %d\n", compr);

    switch (compr) {

    case 0:

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

            bytestream2_get_buffer(&ctx->gb, dst, width);

            dst += stride;

        }

        memset(ctx->frm1, 0, ctx->height * stride);

        memset(ctx->frm2, 0, ctx->height * stride);

        break;

    case 2:

        if (rle_decode(ctx, dst, decoded_size))

            return AVERROR_INVALIDDATA;

        memset(ctx->frm1, 0, ctx->frm1_size);

        memset(ctx->frm2, 0, ctx->frm2_size);

        break;

    case 3:

    case 4:

        if (flags & 4) {

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

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

                    int code;

                    if (skip_run) {

                        skip_run--;

                        copy_block4(dst + i, prev + i, stride, stride, 4);

                        continue;

                    }

                    if (bytestream2_get_bytes_left(&ctx->gb) < 1)

                        return AVERROR_INVALIDDATA;

                    code = bytestream2_get_byteu(&ctx->gb);

                    switch (code) {

                    case 0xFF:

                        if (bytestream2_get_bytes_left(&ctx->gb) < 16)

                            return AVERROR_INVALIDDATA;

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

                            bytestream2_get_bufferu(&ctx->gb, dst + i + k * stride, 4);

                        break;

                    case 0xFE:

                        if (bytestream2_get_bytes_left(&ctx->gb) < 4)

                            return AVERROR_INVALIDDATA;

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

                            memset(dst + i + k * stride, bytestream2_get_byteu(&ctx->gb), 4);

                        break;

                    case 0xFD:

                        if (bytestream2_get_bytes_left(&ctx->gb) < 1)

                            return AVERROR_INVALIDDATA;

                        t = bytestream2_get_byteu(&ctx->gb);

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

                            memset(dst + i + k * stride, t, 4);

                        break;

                    default:

                        if (compr == 4 && !code) {

                            if (bytestream2_get_bytes_left(&ctx->gb) < 1)

                                return AVERROR_INVALIDDATA;

                            skip_run = bytestream2_get_byteu(&ctx->gb) + 1;

                            i -= 4;

                        } else {

                            int mx, my;

                            mx = c37_mv[(mvoff * 255 + code) * 2    ];

                            my = c37_mv[(mvoff * 255 + code) * 2 + 1];

                            codec37_mv(dst + i, prev + i + mx + my * stride,

                                       ctx->height, stride, i + mx, j + my);

                        }

                    }

                }

                dst  += stride * 4;

                prev += stride * 4;

            }

        } else {

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

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

                    int code;

                    if (skip_run) {

                        skip_run--;

                        copy_block4(dst + i, prev + i, stride, stride, 4);

                        continue;

                    }

                    code = bytestream2_get_byte(&ctx->gb);

                    if (code == 0xFF) {

                        if (bytestream2_get_bytes_left(&ctx->gb) < 16)

                            return AVERROR_INVALIDDATA;

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

                            bytestream2_get_bufferu(&ctx->gb, dst + i + k * stride, 4);

                    } else if (compr == 4 && !code) {

                        if (bytestream2_get_bytes_left(&ctx->gb) < 1)

                            return AVERROR_INVALIDDATA;

                        skip_run = bytestream2_get_byteu(&ctx->gb) + 1;

                        i -= 4;

                    } else {

                        int mx, my;

                        mx = c37_mv[(mvoff * 255 + code) * 2];

                        my = c37_mv[(mvoff * 255 + code) * 2 + 1];

                        codec37_mv(dst + i, prev + i + mx + my * stride,

                                   ctx->height, stride, i + mx, j + my);

                    }

                }

                dst  += stride * 4;

                prev += stride * 4;

            }

        }

        break;

    default:

        av_log(ctx->avctx, AV_LOG_ERROR,

               "subcodec 37 compression %d not implemented\n", compr);

        return AVERROR_PATCHWELCOME;

    }

    return 0;

}


static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
                               BdrvCheckMode fix, bool *rebuild,
                               void **refcount_table, int64_t *nb_clusters)
{
    BDRVQcow2State *s = bs->opaque;
    int64_t i;
    QCowSnapshot *sn;
    int ret;
    if (!*refcount_table) {
        int64_t old_size = 0;
        ret = realloc_refcount_array(s, refcount_table,
                                     &old_size, *nb_clusters);
            res->check_errors++;
    /* header */
                        0, s->cluster_size);
    /* current L1 table */
    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
                             s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);
    /* snapshots */
    for (i = 0; i < s->nb_snapshots; i++) {
        sn = s->snapshots + i;
        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
                                 sn->l1_table_offset, sn->l1_size, 0);
                        s->snapshots_offset, s->snapshots_size);
    /* refcount data */
                        s->refcount_table_offset,
                        s->refcount_table_size * sizeof(uint64_t));
    return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);


static uint64_t calc_rice_params(RiceContext *rc,

                                 uint32_t udata[FLAC_MAX_BLOCKSIZE],

                                 uint64_t sums[32][MAX_PARTITIONS],

                                 int pmin, int pmax,

                                 const int32_t *data, int n, int pred_order, int exact)

{

    int i;

    uint64_t bits[MAX_PARTITION_ORDER+1];

    int opt_porder;

    RiceContext tmp_rc;

    int kmax = (1 << rc->coding_mode) - 2;

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

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

    av_assert1(pmin <= pmax);

    tmp_rc.coding_mode = rc->coding_mode;

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

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

    calc_sum_top(pmax, exact ? kmax : 0, udata, n, pred_order, sums);

    opt_porder = pmin;

    bits[pmin] = UINT32_MAX;

    for (i = pmax; ; ) {

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

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

            opt_porder = i;

            *rc = tmp_rc;

        }

        if (i == pmin)

            break;

        calc_sum_next(--i, sums, exact ? kmax : 0);

    }

    return bits[opt_porder];

}


static void nvdimm_realize(PCDIMMDevice *dimm, Error **errp)

{

    MemoryRegion *mr = host_memory_backend_get_memory(dimm->hostmem, errp);

    NVDIMMDevice *nvdimm = NVDIMM(dimm);

    uint64_t align, pmem_size, size = memory_region_size(mr);

    align = memory_region_get_alignment(mr);

    pmem_size = size - nvdimm->label_size;

    nvdimm->label_data = memory_region_get_ram_ptr(mr) + pmem_size;

    pmem_size = QEMU_ALIGN_DOWN(pmem_size, align);

    if (size <= nvdimm->label_size || !pmem_size) {

        HostMemoryBackend *hostmem = dimm->hostmem;

        char *path = object_get_canonical_path_component(OBJECT(hostmem));

        error_setg(errp, "the size of memdev %s (0x%" PRIx64 ") is too "

                   "small to contain nvdimm label (0x%" PRIx64 ") and "

                   "aligned PMEM (0x%" PRIx64 ")",

                   path, memory_region_size(mr), nvdimm->label_size, align);

        return;

    }

    memory_region_init_alias(&nvdimm->nvdimm_mr, OBJECT(dimm),

                             "nvdimm-memory", mr, 0, pmem_size);

    nvdimm->nvdimm_mr.align = align;

}


ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,

                                        int output_rate, int input_rate,

                                        enum AVSampleFormat sample_fmt_out,

                                        enum AVSampleFormat sample_fmt_in,

                                        int filter_length, int log2_phase_count,

                                        int linear, double cutoff)

{

    ReSampleContext *s;

    if (input_channels > MAX_CHANNELS) {

        av_log(NULL, AV_LOG_ERROR,

               "Resampling with input channels greater than %d is unsupported.\n",

               MAX_CHANNELS);

        return NULL;

    }

    if (output_channels > 2 &&

        !(output_channels == 6 && input_channels == 2) &&

        output_channels != input_channels) {

        av_log(NULL, AV_LOG_ERROR,

               "Resampling output channel count must be 1 or 2 for mono input; 1, 2 or 6 for stereo input; or N for N channel input.\n");

        return NULL;

    }

    s = av_mallocz(sizeof(ReSampleContext));

    if (!s) {

        av_log(NULL, AV_LOG_ERROR, "Can't allocate memory for resample context.\n");

        return NULL;

    }

    s->ratio = (float)output_rate / (float)input_rate;

    s->input_channels = input_channels;

    s->output_channels = output_channels;

    s->filter_channels = s->input_channels;

    if (s->output_channels < s->filter_channels)

        s->filter_channels = s->output_channels;

    s->sample_fmt[0]  = sample_fmt_in;

    s->sample_fmt[1]  = sample_fmt_out;

    s->sample_size[0] = av_get_bits_per_sample_fmt(s->sample_fmt[0]) >> 3;

    s->sample_size[1] = av_get_bits_per_sample_fmt(s->sample_fmt[1]) >> 3;

    if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) {

        if (!(s->convert_ctx[0] = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1,

                                                         s->sample_fmt[0], 1, NULL, 0))) {

            av_log(s, AV_LOG_ERROR,

                   "Cannot convert %s sample format to s16 sample format\n",

                   av_get_sample_fmt_name(s->sample_fmt[0]));

            av_free(s);

            return NULL;

        }

    }

    if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {

        if (!(s->convert_ctx[1] = av_audio_convert_alloc(s->sample_fmt[1], 1,

                                                         AV_SAMPLE_FMT_S16, 1, NULL, 0))) {

            av_log(s, AV_LOG_ERROR,

                   "Cannot convert s16 sample format to %s sample format\n",

                   av_get_sample_fmt_name(s->sample_fmt[1]));

            av_audio_convert_free(s->convert_ctx[0]);

            av_free(s);

            return NULL;

        }

    }

#define TAPS 16

    s->resample_context = av_resample_init(output_rate, input_rate,

                                           filter_length, log2_phase_count,

                                           linear, cutoff);

    *(const AVClass**)s->resample_context = &audioresample_context_class;

    return s;

}


static void gen_sync(DisasContext *ctx)

{

    uint32_t l = (ctx->opcode >> 21) & 3;

    /*

     * We may need to check for a pending TLB flush.

     *

     * We do this on ptesync (l == 2) on ppc64 and any sync pn ppc32.

     *

     * Additionally, this can only happen in kernel mode however so

     * check MSR_PR as well.

     */

    if (((l == 2) || !(ctx->insns_flags & PPC_64B)) && !ctx->pr) {

        gen_check_tlb_flush(ctx);

    }

}


static int qcrypto_ivgen_essiv_calculate(QCryptoIVGen *ivgen,

                                         uint64_t sector,

                                         uint8_t *iv, size_t niv,

                                         Error **errp)

{

    QCryptoIVGenESSIV *essiv = ivgen->private;

    size_t ndata = qcrypto_cipher_get_block_len(ivgen->cipher);

    uint8_t *data = g_new(uint8_t, ndata);

    sector = cpu_to_le64(sector);

    memcpy(data, (uint8_t *)&sector, ndata);

    if (sizeof(sector) < ndata) {

        memset(data + sizeof(sector), 0, ndata - sizeof(sector));

    }

    if (qcrypto_cipher_encrypt(essiv->cipher,

                               data,

                               data,

                               ndata,

                               errp) < 0) {

        g_free(data);

        return -1;

    }

    if (ndata > niv) {

        ndata = niv;

    }

    memcpy(iv, data, ndata);

    if (ndata < niv) {

        memset(iv + ndata, 0, niv - ndata);

    }

    g_free(data);

    return 0;

}


void ff_nut_free_sp(NUTContext *nut)

{

    av_tree_enumerate(nut->syncpoints, NULL, NULL, enu_free);

    av_tree_destroy(nut->syncpoints);

}


static void memory_region_oldmmio_write_accessor(MemoryRegion *mr,

                                                 hwaddr addr,

                                                 uint64_t *value,

                                                 unsigned size,

                                                 unsigned shift,

                                                 uint64_t mask)

{

    uint64_t tmp;

    tmp = (*value >> shift) & mask;

    trace_memory_region_ops_write(mr, addr, tmp, size);

    mr->ops->old_mmio.write[ctz32(size)](mr->opaque, addr, tmp);

}