static int ir2_decode_frame(AVCodecContext *avctx,

                        void *data, int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    Ir2Context * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p= (AVFrame*)&s->picture;

    int start;

    if(p->data[0])

        avctx->release_buffer(avctx, p);

    p->reference = 1;

    p->buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, p)) {

        av_log(s->avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return -1;

    }

    s->decode_delta = buf[18];

    /* decide whether frame uses deltas or not */

#ifndef ALT_BITSTREAM_READER_LE

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

        buf[i] = av_reverse[buf[i]];

#endif

    start = 48; /* hardcoded for now */

    init_get_bits(&s->gb, buf + start, buf_size - start);

    if (s->decode_delta) { /* intraframe */

        ir2_decode_plane(s, avctx->width, avctx->height,

                         s->picture.data[0], s->picture.linesize[0], ir2_luma_table);

        /* swapped U and V */

        ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[2], s->picture.linesize[2], ir2_luma_table);

        ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[1], s->picture.linesize[1], ir2_luma_table);

    } else { /* interframe */

        ir2_decode_plane_inter(s, avctx->width, avctx->height,

                         s->picture.data[0], s->picture.linesize[0], ir2_luma_table);

        /* swapped U and V */

        ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[2], s->picture.linesize[2], ir2_luma_table);

        ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[1], s->picture.linesize[1], ir2_luma_table);

    }

    *picture= *(AVFrame*)&s->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


void Process(void *ctx, AVPicture *picture, enum PixelFormat pix_fmt, int width, int height, INT64 pts)

{

    ContextInfo *ci = (ContextInfo *) ctx;

    AVPicture picture1;

    Imlib_Image image;

    DATA32 *data;

    image = get_cached_image(ci, width, height);

    if (!image) {

        image = imlib_create_image(width, height);

        put_cached_image(ci, image, width, height);

    }

    imlib_context_set_image(image);

    data = imlib_image_get_data();

    if (pix_fmt != PIX_FMT_RGBA32) {

        avpicture_fill(&picture1, (UINT8 *) data, PIX_FMT_RGBA32, width, height);

        if (img_convert(&picture1, PIX_FMT_RGBA32,

                        picture, pix_fmt, width, height) < 0) {

            goto done;

        }

    } else {

        av_abort();

    }

    imlib_image_set_has_alpha(0);

    {

        int wid, hig, h_a, v_a;

        char buff[1000];

        char tbuff[1000];

        char *tbp = ci->text;

        time_t now = time(0);

        char *p, *q;

        int x, y;

        if (ci->file) {

            int fd = open(ci->file, O_RDONLY);

            if (fd < 0) {

                tbp = "[File not found]";

            } else {

                int l = read(fd, tbuff, sizeof(tbuff) - 1);

                if (l >= 0) {

                    tbuff[l] = 0;

                    tbp = tbuff;

                } else {

                    tbp = "[I/O Error]";

                }

                close(fd);

            }

        }

        strftime(buff, sizeof(buff), tbp, localtime(&now));

        x = ci->x;

        y = ci->y;

        for (p = buff; p; p = q) {

            q = strchr(p, '\n');

            if (q)

                *q++ = 0;

            imlib_text_draw_with_return_metrics(x, y, p, &wid, &hig, &h_a, &v_a);

            y += v_a;

        }

    }

    if (pix_fmt != PIX_FMT_RGBA32) {

        if (img_convert(picture, pix_fmt,

                        &picture1, PIX_FMT_RGBA32, width, height) < 0) {

        }

    }

done:

    ;

}


static void host_signal_handler(int host_signum, siginfo_t *info,
                                void *puc)
{
    CPUArchState *env = thread_cpu->env_ptr;
    int sig;
    target_siginfo_t tinfo;
    /* the CPU emulator uses some host signals to detect exceptions,
       we forward to it some signals */
    if ((host_signum == SIGSEGV || host_signum == SIGBUS)
        && info->si_code > 0) {
        if (cpu_signal_handler(host_signum, info, puc))
            return;
    }
    /* get target signal number */
    sig = host_to_target_signal(host_signum);
    if (sig < 1 || sig > TARGET_NSIG)
        return;
    trace_user_host_signal(env, host_signum, sig);
    host_to_target_siginfo_noswap(&tinfo, info);
    if (queue_signal(env, sig, &tinfo) == 1) {
        /* interrupt the virtual CPU as soon as possible */
        cpu_exit(thread_cpu);
    }
}


void stellaris_gamepad_init(int n, qemu_irq *irq, const int *keycode)

{

    gamepad_state *s;

    int i;

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

    s->buttons = (gamepad_button *)g_malloc0(n * sizeof (gamepad_button));

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

        s->buttons[i].irq = irq[i];

        s->buttons[i].keycode = keycode[i];

    }

    s->num_buttons = n;

    qemu_add_kbd_event_handler(stellaris_gamepad_put_key, s);

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

}


static void arm_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    ARMCPU *cpu = ARM_CPU(obj);

    static bool inited;

    uint32_t Aff1, Aff0;

    cs->env_ptr = &cpu->env;

    cpu_exec_init(cs, &error_abort);

    cpu->cp_regs = g_hash_table_new_full(g_int_hash, g_int_equal,

                                         g_free, g_free);

    /* This cpu-id-to-MPIDR affinity is used only for TCG; KVM will override it.

     * We don't support setting cluster ID ([16..23]) (known as Aff2

     * in later ARM ARM versions), or any of the higher affinity level fields,

     * so these bits always RAZ.

     */

    Aff1 = cs->cpu_index / ARM_CPUS_PER_CLUSTER;

    Aff0 = cs->cpu_index % ARM_CPUS_PER_CLUSTER;

    cpu->mp_affinity = (Aff1 << ARM_AFF1_SHIFT) | Aff0;

#ifndef CONFIG_USER_ONLY

    /* Our inbound IRQ and FIQ lines */

    if (kvm_enabled()) {

        /* VIRQ and VFIQ are unused with KVM but we add them to maintain

         * the same interface as non-KVM CPUs.

         */

        qdev_init_gpio_in(DEVICE(cpu), arm_cpu_kvm_set_irq, 4);

    } else {

        qdev_init_gpio_in(DEVICE(cpu), arm_cpu_set_irq, 4);

    }

    cpu->gt_timer[GTIMER_PHYS] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_ptimer_cb, cpu);

    cpu->gt_timer[GTIMER_VIRT] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_vtimer_cb, cpu);

    cpu->gt_timer[GTIMER_HYP] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_htimer_cb, cpu);

    cpu->gt_timer[GTIMER_SEC] = timer_new(QEMU_CLOCK_VIRTUAL, GTIMER_SCALE,

                                                arm_gt_stimer_cb, cpu);

    qdev_init_gpio_out(DEVICE(cpu), cpu->gt_timer_outputs,

                       ARRAY_SIZE(cpu->gt_timer_outputs));

#endif

    /* DTB consumers generally don't in fact care what the 'compatible'

     * string is, so always provide some string and trust that a hypothetical

     * picky DTB consumer will also provide a helpful error message.

     */

    cpu->dtb_compatible = "qemu,unknown";

    cpu->psci_version = 1; /* By default assume PSCI v0.1 */

    cpu->kvm_target = QEMU_KVM_ARM_TARGET_NONE;

    if (tcg_enabled()) {

        cpu->psci_version = 2; /* TCG implements PSCI 0.2 */

        if (!inited) {

            inited = true;

            arm_translate_init();

        }

    }

}


static int vmdk_create(const char *filename, QEMUOptionParameter *options,

                       Error **errp)

{

    int idx = 0;

    BlockDriverState *new_bs = NULL;

    Error *local_err;

    char *desc = NULL;

    int64_t total_size = 0, filesize;

    const char *adapter_type = NULL;

    const char *backing_file = NULL;

    const char *fmt = NULL;

    int flags = 0;

    int ret = 0;

    bool flat, split, compress;

    GString *ext_desc_lines;

    char path[PATH_MAX], prefix[PATH_MAX], postfix[PATH_MAX];

    const int64_t split_size = 0x80000000;  /* VMDK has constant split size */

    const char *desc_extent_line;

    char parent_desc_line[BUF_SIZE] = "";

    uint32_t parent_cid = 0xffffffff;

    uint32_t number_heads = 16;

    bool zeroed_grain = false;

    uint32_t desc_offset = 0, desc_len;

    const char desc_template[] =

        "# Disk DescriptorFile\n"

        "version=1\n"

        "CID=%" PRIx32 "\n"

        "parentCID=%" PRIx32 "\n"

        "createType=\"%s\"\n"

        "%s"

        "\n"

        "# Extent description\n"

        "%s"

        "\n"

        "# The Disk Data Base\n"

        "#DDB\n"

        "\n"

        "ddb.virtualHWVersion = \"%d\"\n"

        "ddb.geometry.cylinders = \"%" PRId64 "\"\n"

        "ddb.geometry.heads = \"%" PRIu32 "\"\n"

        "ddb.geometry.sectors = \"63\"\n"

        "ddb.adapterType = \"%s\"\n";

    ext_desc_lines = g_string_new(NULL);

    if (filename_decompose(filename, path, prefix, postfix, PATH_MAX, errp)) {

        ret = -EINVAL;

        goto exit;

    }

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            total_size = options->value.n;

        } else if (!strcmp(options->name, BLOCK_OPT_ADAPTER_TYPE)) {

            adapter_type = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {

            backing_file = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_COMPAT6)) {

            flags |= options->value.n ? BLOCK_FLAG_COMPAT6 : 0;

        } else if (!strcmp(options->name, BLOCK_OPT_SUBFMT)) {

            fmt = options->value.s;

        } else if (!strcmp(options->name, BLOCK_OPT_ZEROED_GRAIN)) {

            zeroed_grain |= options->value.n;

        }

        options++;

    }

    if (!adapter_type) {

        adapter_type = "ide";

    } else if (strcmp(adapter_type, "ide") &&

               strcmp(adapter_type, "buslogic") &&

               strcmp(adapter_type, "lsilogic") &&

               strcmp(adapter_type, "legacyESX")) {

        error_setg(errp, "Unknown adapter type: '%s'", adapter_type);

        ret = -EINVAL;

        goto exit;

    }

    if (strcmp(adapter_type, "ide") != 0) {

        /* that's the number of heads with which vmware operates when

           creating, exporting, etc. vmdk files with a non-ide adapter type */

        number_heads = 255;

    }

    if (!fmt) {

        /* Default format to monolithicSparse */

        fmt = "monolithicSparse";

    } else if (strcmp(fmt, "monolithicFlat") &&

               strcmp(fmt, "monolithicSparse") &&

               strcmp(fmt, "twoGbMaxExtentSparse") &&

               strcmp(fmt, "twoGbMaxExtentFlat") &&

               strcmp(fmt, "streamOptimized")) {

        error_setg(errp, "Unknown subformat: '%s'", fmt);

        ret = -EINVAL;

        goto exit;

    }

    split = !(strcmp(fmt, "twoGbMaxExtentFlat") &&

              strcmp(fmt, "twoGbMaxExtentSparse"));

    flat = !(strcmp(fmt, "monolithicFlat") &&

             strcmp(fmt, "twoGbMaxExtentFlat"));

    compress = !strcmp(fmt, "streamOptimized");

    if (flat) {

        desc_extent_line = "RW %" PRId64 " FLAT \"%s\" 0\n";

    } else {

        desc_extent_line = "RW %" PRId64 " SPARSE \"%s\"\n";

    }

    if (flat && backing_file) {

        error_setg(errp, "Flat image can't have backing file");

        ret = -ENOTSUP;

        goto exit;

    }

    if (flat && zeroed_grain) {

        error_setg(errp, "Flat image can't enable zeroed grain");

        ret = -ENOTSUP;

        goto exit;

    }

    if (backing_file) {

        BlockDriverState *bs = NULL;

        ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_NO_BACKING, NULL,

                        errp);

        if (ret != 0) {

            goto exit;

        }

        if (strcmp(bs->drv->format_name, "vmdk")) {

            bdrv_unref(bs);

            ret = -EINVAL;

            goto exit;

        }

        parent_cid = vmdk_read_cid(bs, 0);

        bdrv_unref(bs);

        snprintf(parent_desc_line, sizeof(parent_desc_line),

                "parentFileNameHint=\"%s\"", backing_file);

    }

    /* Create extents */

    filesize = total_size;

    while (filesize > 0) {

        char desc_line[BUF_SIZE];

        char ext_filename[PATH_MAX];

        char desc_filename[PATH_MAX];

        int64_t size = filesize;

        if (split && size > split_size) {

            size = split_size;

        }

        if (split) {

            snprintf(desc_filename, sizeof(desc_filename), "%s-%c%03d%s",

                    prefix, flat ? 'f' : 's', ++idx, postfix);

        } else if (flat) {

            snprintf(desc_filename, sizeof(desc_filename), "%s-flat%s",

                    prefix, postfix);

        } else {

            snprintf(desc_filename, sizeof(desc_filename), "%s%s",

                    prefix, postfix);

        }

        snprintf(ext_filename, sizeof(ext_filename), "%s%s",

                path, desc_filename);

        if (vmdk_create_extent(ext_filename, size,

                               flat, compress, zeroed_grain, errp)) {

            ret = -EINVAL;

            goto exit;

        }

        filesize -= size;

        /* Format description line */

        snprintf(desc_line, sizeof(desc_line),

                    desc_extent_line, size / BDRV_SECTOR_SIZE, desc_filename);

        g_string_append(ext_desc_lines, desc_line);

    }

    /* generate descriptor file */

    desc = g_strdup_printf(desc_template,

                           (uint32_t)time(NULL),

                           parent_cid,

                           fmt,

                           parent_desc_line,

                           ext_desc_lines->str,

                           (flags & BLOCK_FLAG_COMPAT6 ? 6 : 4),

                           total_size /

                               (int64_t)(63 * number_heads * BDRV_SECTOR_SIZE),

                           number_heads,

                           adapter_type);

    desc_len = strlen(desc);

    /* the descriptor offset = 0x200 */

    if (!split && !flat) {

        desc_offset = 0x200;

    } else {

        ret = bdrv_create_file(filename, options, &local_err);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not create image file");

            goto exit;

        }

    }

    assert(new_bs == NULL);

    ret = bdrv_open(&new_bs, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write description");

        goto exit;

    }

    ret = bdrv_pwrite(new_bs, desc_offset, desc, desc_len);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write description");

        goto exit;

    }

    /* bdrv_pwrite write padding zeros to align to sector, we don't need that

     * for description file */

    if (desc_offset == 0) {

        ret = bdrv_truncate(new_bs, desc_len);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not truncate file");

        }

    }

exit:

    if (new_bs) {

        bdrv_unref(new_bs);

    }

    g_free(desc);

    g_string_free(ext_desc_lines, true);

    return ret;

}


int vmstate_register_with_alias_id(DeviceState *dev, int instance_id,

                                   const VMStateDescription *vmsd,

                                   void *opaque, int alias_id,

                                   int required_for_version)

{

    SaveStateEntry *se;

    /* If this triggers, alias support can be dropped for the vmsd. */

    assert(alias_id == -1 || required_for_version >= vmsd->minimum_version_id);

    se = g_malloc0(sizeof(SaveStateEntry));

    se->version_id = vmsd->version_id;

    se->section_id = savevm_state.global_section_id++;

    se->opaque = opaque;

    se->vmsd = vmsd;

    se->alias_id = alias_id;

    if (dev) {

        char *id = qdev_get_dev_path(dev);

        if (id) {

            pstrcpy(se->idstr, sizeof(se->idstr), id);

            pstrcat(se->idstr, sizeof(se->idstr), "/");

            g_free(id);

            se->compat = g_malloc0(sizeof(CompatEntry));

            pstrcpy(se->compat->idstr, sizeof(se->compat->idstr), vmsd->name);

            se->compat->instance_id = instance_id == -1 ?

                         calculate_compat_instance_id(vmsd->name) : instance_id;

            instance_id = -1;

        }

    }

    pstrcat(se->idstr, sizeof(se->idstr), vmsd->name);

    if (instance_id == -1) {

        se->instance_id = calculate_new_instance_id(se->idstr);

    } else {

        se->instance_id = instance_id;

    }

    assert(!se->compat || se->instance_id == 0);

    /* add at the end of list */

    QTAILQ_INSERT_TAIL(&savevm_state.handlers, se, entry);

    return 0;

}


void visit_start_alternate(Visitor *v, const char *name,

                           GenericAlternate **obj, size_t size,

                           bool promote_int, Error **errp)

{

    Error *err = NULL;

    assert(obj && size >= sizeof(GenericAlternate));

    assert(v->type != VISITOR_OUTPUT || *obj);

    if (v->start_alternate) {

        v->start_alternate(v, name, obj, size, promote_int, &err);

    }

    if (v->type == VISITOR_INPUT) {

        assert(v->start_alternate && !err != !*obj);

    }

    error_propagate(errp, err);

}


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

{

    IOAPICCommonState s;

    kvm_ioapic_get(&s);

    ioapic_print_redtbl(mon, &s);

}


milkymist_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    LM32CPU *cpu;

    CPULM32State *env;

    int kernel_size;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *phys_sdram = g_new(MemoryRegion, 1);

    qemu_irq irq[32];

    int i;

    char *bios_filename;

    ResetInfo *reset_info;

    /* memory map */

    hwaddr flash_base   = 0x00000000;

    size_t flash_sector_size        = 128 * 1024;

    size_t flash_size               = 32 * 1024 * 1024;

    hwaddr sdram_base   = 0x40000000;

    size_t sdram_size               = 128 * 1024 * 1024;

    hwaddr initrd_base  = sdram_base + 0x1002000;

    hwaddr cmdline_base = sdram_base + 0x1000000;

    size_t initrd_max = sdram_size - 0x1002000;

    reset_info = g_malloc0(sizeof(ResetInfo));

    if (cpu_model == NULL) {

        cpu_model = "lm32-full";

    }

    cpu = LM32_CPU(cpu_generic_init(TYPE_LM32_CPU, cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "qemu: unable to find CPU '%s'\n", cpu_model);

        exit(1);

    }

    env = &cpu->env;

    reset_info->cpu = cpu;

    cpu_lm32_set_phys_msb_ignore(env, 1);

    memory_region_allocate_system_memory(phys_sdram, NULL, "milkymist.sdram",

                                         sdram_size);

    memory_region_add_subregion(address_space_mem, sdram_base, phys_sdram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* Numonyx JS28F256J3F105 */

    pflash_cfi01_register(flash_base, NULL, "milkymist.flash", flash_size,

                          dinfo ? blk_by_legacy_dinfo(dinfo) : NULL,

                          flash_sector_size, flash_size / flash_sector_size,

                          2, 0x00, 0x89, 0x00, 0x1d, 1);

    /* create irq lines */

    env->pic_state = lm32_pic_init(qemu_allocate_irq(cpu_irq_handler, cpu, 0));

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

        irq[i] = qdev_get_gpio_in(env->pic_state, i);

    }

    /* load bios rom */

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (bios_filename) {

        load_image_targphys(bios_filename, BIOS_OFFSET, BIOS_SIZE);

    }

    reset_info->bootstrap_pc = BIOS_OFFSET;

    /* if no kernel is given no valid bios rom is a fatal error */

    if (!kernel_filename && !dinfo && !bios_filename && !qtest_enabled()) {

        fprintf(stderr, "qemu: could not load Milkymist One bios '%s'\n",

                bios_name);

        exit(1);

    }

    g_free(bios_filename);

    milkymist_uart_create(0x60000000, irq[0], serial_hds[0]);

    milkymist_sysctl_create(0x60001000, irq[1], irq[2], irq[3],

            80000000, 0x10014d31, 0x0000041f, 0x00000001);

    milkymist_hpdmc_create(0x60002000);

    milkymist_vgafb_create(0x60003000, 0x40000000, 0x0fffffff);

    milkymist_memcard_create(0x60004000);

    milkymist_ac97_create(0x60005000, irq[4], irq[5], irq[6], irq[7]);

    milkymist_pfpu_create(0x60006000, irq[8]);

    if (machine->enable_graphics) {

        milkymist_tmu2_create(0x60007000, irq[9]);

    }

    milkymist_minimac2_create(0x60008000, 0x30000000, irq[10], irq[11]);

    milkymist_softusb_create(0x6000f000, irq[15],

            0x20000000, 0x1000, 0x20020000, 0x2000);

    /* make sure juart isn't the first chardev */

    env->juart_state = lm32_juart_init(serial_hds[1]);

    if (kernel_filename) {

        uint64_t entry;

        /* Boots a kernel elf binary.  */

        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,

                               1, EM_LATTICEMICO32, 0, 0);

        reset_info->bootstrap_pc = entry;

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, sdram_base,

                                              sdram_size);

            reset_info->bootstrap_pc = sdram_base;

        }

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

    }

    if (kernel_cmdline && strlen(kernel_cmdline)) {

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE,

                kernel_cmdline);

        reset_info->cmdline_base = (uint32_t)cmdline_base;

    }

    if (initrd_filename) {

        size_t initrd_size;

        initrd_size = load_image_targphys(initrd_filename, initrd_base,

                initrd_max);

        reset_info->initrd_base = (uint32_t)initrd_base;

        reset_info->initrd_size = (uint32_t)initrd_size;

    }

    qemu_register_reset(main_cpu_reset, reset_info);

}


static int read_probe(AVProbeData *pd)

{

    if (pd->buf[0] == 'J' && pd->buf[1] == 'V' && strlen(MAGIC) <= pd->buf_size - 4 &&

        !memcmp(pd->buf + 4, MAGIC, strlen(MAGIC)))

        return AVPROBE_SCORE_MAX;

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);

    dc->reset = ich9_lpc_reset;

    k->init = ich9_lpc_initfn;

    dc->vmsd = &vmstate_ich9_lpc;

    dc->no_user = 1;

    k->config_write = ich9_lpc_config_write;

    dc->desc = "ICH9 LPC bridge";

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_ICH9_8;

    k->revision = ICH9_A2_LPC_REVISION;

    k->class_id = PCI_CLASS_BRIDGE_ISA;

}


hwaddr cpu_mips_translate_address(CPUMIPSState *env, target_ulong address, int rw)

{

    hwaddr physical;

    int prot;

    int access_type;

    int ret = 0;

    /* data access */

    access_type = ACCESS_INT;

    ret = get_physical_address(env, &physical, &prot,

                               address, rw, access_type);

    if (ret != TLBRET_MATCH) {

        raise_mmu_exception(env, address, rw, ret);

        return -1LL;

    } else {

        return physical;

    }

}


static int h263_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             UINT8 *buf, int buf_size)

{

    MpegEncContext *s = avctx->priv_data;

    int ret;

    AVPicture *pict = data;

#ifdef DEBUG

    printf("*****frame %d size=%d\n", avctx->frame_number, buf_size);

    printf("bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);

#endif

    /* no supplementary picture */

    if (buf_size == 0) {

        *data_size = 0;

        return 0;

    }

    if(s->bitstream_buffer_size) //divx 5.01+ frame reorder

        init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size);

    else

        init_get_bits(&s->gb, buf, buf_size);

    /* let's go :-) */

    if (s->h263_msmpeg4) {

        ret = msmpeg4_decode_picture_header(s);

    } else if (s->h263_pred) {

        ret = mpeg4_decode_picture_header(s);

        s->has_b_frames= !s->low_delay;

    } else if (s->h263_intel) {

        ret = intel_h263_decode_picture_header(s);

    } else {

        ret = h263_decode_picture_header(s);

    }

        /* After H263 & mpeg4 header decode we have the height, width,*/

        /* and other parameters. So then we could init the picture   */

        /* FIXME: By the way H263 decoder is evolving it should have */

        /* an H263EncContext                                         */

    if (!s->context_initialized) {

        avctx->width = s->width;

        avctx->height = s->height;

        avctx->aspect_ratio_info= s->aspect_ratio_info;

        if (MPV_common_init(s) < 0)

            return -1;

    } else if (s->width != avctx->width || s->height != avctx->height) {

        /* H.263 could change picture size any time */

        MPV_common_end(s);

        if (MPV_common_init(s) < 0)

            return -1;

    }

    if(ret==FRAME_SKIPED) return 0;

    if (ret < 0)

        return -1;

    /* skip b frames if we dont have reference frames */

    if(s->num_available_buffers<2 && s->pict_type==B_TYPE) return 0;

    MPV_frame_start(s);

#ifdef DEBUG

    printf("qscale=%d\n", s->qscale);

#endif

    /* decode each macroblock */

    s->block_wrap[0]=

    s->block_wrap[1]=

    s->block_wrap[2]=

    s->block_wrap[3]= s->mb_width*2 + 2;

    s->block_wrap[4]=

    s->block_wrap[5]= s->mb_width + 2;

    for(s->mb_y=0; s->mb_y < s->mb_height; s->mb_y++) {

        /* Check for GOB headers on H.263 */

        /* FIXME: In the future H.263+ will have intra prediction */

        /* and we are gonna need another way to detect MPEG4      */

        if (s->mb_y && !s->h263_pred) {

            s->first_gob_line = h263_decode_gob_header(s);

        }

        s->block_index[0]= s->block_wrap[0]*(s->mb_y*2 + 1) - 1;

        s->block_index[1]= s->block_wrap[0]*(s->mb_y*2 + 1);

        s->block_index[2]= s->block_wrap[0]*(s->mb_y*2 + 2) - 1;

        s->block_index[3]= s->block_wrap[0]*(s->mb_y*2 + 2);

        s->block_index[4]= s->block_wrap[4]*(s->mb_y + 1)                    + s->block_wrap[0]*(s->mb_height*2 + 2);

        s->block_index[5]= s->block_wrap[4]*(s->mb_y + 1 + s->mb_height + 2) + s->block_wrap[0]*(s->mb_height*2 + 2);

        for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {

            s->block_index[0]+=2;

            s->block_index[1]+=2;

            s->block_index[2]+=2;

            s->block_index[3]+=2;

            s->block_index[4]++;

            s->block_index[5]++;

#ifdef DEBUG

            printf("**mb x=%d y=%d\n", s->mb_x, s->mb_y);

#endif

            //fprintf(stderr,"\nFrame: %d\tMB: %d",avctx->frame_number, (s->mb_y * s->mb_width) + s->mb_x);

            /* DCT & quantize */

            if (s->h263_msmpeg4) {

                msmpeg4_dc_scale(s);

            } else if (s->h263_pred) {

                h263_dc_scale(s);

            } else {

                /* default quantization values */

                s->y_dc_scale = 8;

                s->c_dc_scale = 8;

            }

            clear_blocks(s->block[0]);

            s->mv_dir = MV_DIR_FORWARD;

            s->mv_type = MV_TYPE_16X16;

            if (s->h263_msmpeg4) {

		if (msmpeg4_decode_mb(s, s->block) < 0) {

		    fprintf(stderr,"\nError at MB: %d\n", (s->mb_y * s->mb_width) + s->mb_x);

                    return -1;

		}

            } else {

                if (h263_decode_mb(s, s->block) < 0) {

                    fprintf(stderr,"\nError at MB: %d\n", (s->mb_y * s->mb_width) + s->mb_x);

                    return -1;

                }

            }

            MPV_decode_mb(s, s->block);

        }

        if (    avctx->draw_horiz_band

            && (s->num_available_buffers>=1 || (!s->has_b_frames)) ) {

            UINT8 *src_ptr[3];

            int y, h, offset;

            y = s->mb_y * 16;

            h = s->height - y;

            if (h > 16)

                h = 16;

            offset = y * s->linesize;

            if(s->pict_type==B_TYPE || (!s->has_b_frames)){

                src_ptr[0] = s->current_picture[0] + offset;

                src_ptr[1] = s->current_picture[1] + (offset >> 2);

                src_ptr[2] = s->current_picture[2] + (offset >> 2);

            } else {

                src_ptr[0] = s->last_picture[0] + offset;

                src_ptr[1] = s->last_picture[1] + (offset >> 2);

                src_ptr[2] = s->last_picture[2] + (offset >> 2);

            }

            avctx->draw_horiz_band(avctx, src_ptr, s->linesize,

                                   y, s->width, h);

        }

    }

    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type==I_TYPE)

        if(msmpeg4_decode_ext_header(s, buf_size) < 0) return -1;

    /* divx 5.01+ bistream reorder stuff */

    if(s->h263_pred && s->bitstream_buffer_size==0){

        int current_pos= get_bits_count(&s->gb)/8;

        if(   buf_size - current_pos > 5

           && buf_size - current_pos < BITSTREAM_BUFFER_SIZE){

            memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos);

            s->bitstream_buffer_size= buf_size - current_pos;

        }

    }else

        s->bitstream_buffer_size=0;

    MPV_frame_end(s);

    if(s->pict_type==B_TYPE || (!s->has_b_frames)){

        pict->data[0] = s->current_picture[0];

        pict->data[1] = s->current_picture[1];

        pict->data[2] = s->current_picture[2];

    } else {

        pict->data[0] = s->last_picture[0];

        pict->data[1] = s->last_picture[1];

        pict->data[2] = s->last_picture[2];

    }

    pict->linesize[0] = s->linesize;

    pict->linesize[1] = s->linesize / 2;

    pict->linesize[2] = s->linesize / 2;

    avctx->quality = s->qscale;

    /* Return the Picture timestamp as the frame number */

    /* we substract 1 because it is added on utils.c    */

    avctx->frame_number = s->picture_number - 1;

    /* dont output the last pic after seeking

       note we allready added +1 for the current pix in MPV_frame_end(s) */

    if(s->num_available_buffers>=2 || (!s->has_b_frames))

        *data_size = sizeof(AVPicture);

    return buf_size;

}


PPC_OP(setlr)

{

    regs->lr = PARAM1;

    RETURN();

}


static int mlib_YUV2ABGR420_32(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

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

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    assert(srcStride[1] == srcStride[2]);

    mlib_VideoColorYUV2ABGR420(dst[0]+srcSliceY*dstStride[0], src[0], src[1], src[2], c->dstW,

			     srcSliceH, dstStride[0], srcStride[0], srcStride[1]);

    return srcSliceH;

}


BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
                                 QEMUIOVector *iov, int nb_sectors,
                                 BlockDriverCompletionFunc *cb, void *opaque)
{
    return bdrv_aio_rw_vector(bs, sector_num, iov, nb_sectors,
                              cb, opaque, 0);
}


static int init(AVFilterContext *ctx, const char *args)
{
    EvalContext *eval = ctx->priv;
    char *args1 = av_strdup(args);
    char *expr, *buf, *bufptr;
    int ret, i;
    eval->class = &aevalsrc_class;
    av_opt_set_defaults(eval);
    /* parse expressions */
    buf = args1;
    i = 0;
    while (expr = av_strtok(buf, ":", &bufptr)) {
        ret = av_expr_parse(&eval->expr[i], expr, var_names,
                            NULL, NULL, NULL, NULL, 0, ctx);
        if (ret < 0)
        i++;
        if (bufptr && *bufptr == ':') { /* found last expression */
            bufptr++;
            break;
        buf = NULL;
    eval->nb_channels = i;
    if (bufptr && (ret = av_set_options_string(eval, bufptr, "=", ":")) < 0)
    if (eval->chlayout_str) {
        int n;
        ret = ff_parse_channel_layout(&eval->chlayout, eval->chlayout_str, ctx);
        if (ret < 0)
        n = av_get_channel_layout_nb_channels(eval->chlayout);
        if (n != eval->nb_channels) {
            av_log(ctx, AV_LOG_ERROR,
                   "Mismatch between the specified number of channels '%d' "
                   "and the number of channels '%d' in the specified channel layout '%s'\n",
                   eval->nb_channels, n, eval->chlayout_str);
            ret = AVERROR(EINVAL);
    } else {
        /* guess channel layout from nb expressions/channels */
        eval->chlayout = av_get_default_channel_layout(eval->nb_channels);
        if (!eval->chlayout) {
            av_log(ctx, AV_LOG_ERROR, "Invalid number of channels '%d' provided\n",
                   eval->nb_channels);
            ret = AVERROR(EINVAL);
    if ((ret = ff_parse_sample_rate(&eval->sample_rate, eval->sample_rate_str, ctx)))
    eval->duration = -1;
    if (eval->duration_str) {
        int64_t us = -1;
        if ((ret = av_parse_time(&us, eval->duration_str, 1)) < 0) {
            av_log(ctx, AV_LOG_ERROR, "Invalid duration: '%s'\n", eval->duration_str);
        eval->duration = (double)us / 1000000;
    eval->n = 0;
end:
    av_free(args1);
    return ret;


BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque)

{

    Coroutine *co;

    BlockAIOCBCoroutine *acb;

    trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);

    acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);

    acb->need_bh = true;

    acb->req.error = -EINPROGRESS;

    acb->req.sector = sector_num;

    acb->req.nb_sectors = nb_sectors;

    co = qemu_coroutine_create(bdrv_aio_discard_co_entry);

    qemu_coroutine_enter(co, acb);

    bdrv_co_maybe_schedule_bh(acb);

    return &acb->common;

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *got_frame, AVPacket *avpkt)

{

    TiffContext *const s = avctx->priv_data;

    AVFrame *const p = data;

    ThreadFrame frame = { .f = data };

    unsigned off;

    int le, ret, plane, planes;

    int i, j, entries, stride;

    unsigned soff, ssize;

    uint8_t *dst;

    GetByteContext stripsizes;

    GetByteContext stripdata;

    bytestream2_init(&s->gb, avpkt->data, avpkt->size);

    // parse image header

    if ((ret = ff_tdecode_header(&s->gb, &le, &off))) {

        av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n");

        return ret;

    } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) {

        av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");

        return AVERROR_INVALIDDATA;

    }

    s->le          = le;

    // TIFF_BPP is not a required tag and defaults to 1

    s->bppcount    = s->bpp = 1;

    s->photometric = TIFF_PHOTOMETRIC_NONE;

    s->compr       = TIFF_RAW;

    s->fill_order  = 0;

    free_geotags(s);

    // Reset these offsets so we can tell if they were set this frame

    s->stripsizesoff = s->strippos = 0;

    /* parse image file directory */

    bytestream2_seek(&s->gb, off, SEEK_SET);

    entries = ff_tget_short(&s->gb, le);

    if (bytestream2_get_bytes_left(&s->gb) < entries * 12)

        return AVERROR_INVALIDDATA;

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

        if ((ret = tiff_decode_tag(s, p)) < 0)

            return ret;

    }

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

        const char *keyname = get_geokey_name(s->geotags[i].key);

        if (!keyname) {

            av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);

            continue;

        }

        if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {

            av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);

            continue;

        }

        ret = av_dict_set(&p->metadata, keyname, s->geotags[i].val, 0);

        if (ret<0) {

            av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);

            return ret;

        }

    }

    if (!s->strippos && !s->stripoff) {

        av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");

        return AVERROR_INVALIDDATA;

    }

    /* now we have the data and may start decoding */

    if ((ret = init_image(s, &frame)) < 0)

        return ret;

    if (s->strips == 1 && !s->stripsize) {

        av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");

        s->stripsize = avpkt->size - s->stripoff;

    }

    if (s->stripsizesoff) {

        if (s->stripsizesoff >= (unsigned)avpkt->size)

            return AVERROR_INVALIDDATA;

        bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff,

                         avpkt->size - s->stripsizesoff);

    }

    if (s->strippos) {

        if (s->strippos >= (unsigned)avpkt->size)

            return AVERROR_INVALIDDATA;

        bytestream2_init(&stripdata, avpkt->data + s->strippos,

                         avpkt->size - s->strippos);

    }

    if (s->rps <= 0 || s->rps % s->subsampling[1]) {

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

        return AVERROR_INVALIDDATA;

    }

    planes = s->planar ? s->bppcount : 1;

    for (plane = 0; plane < planes; plane++) {

        stride = p->linesize[plane];

        dst = p->data[plane];

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

            if (s->stripsizesoff)

                ssize = ff_tget(&stripsizes, s->sstype, le);

            else

                ssize = s->stripsize;

            if (s->strippos)

                soff = ff_tget(&stripdata, s->sot, le);

            else

                soff = s->stripoff;

            if (soff > avpkt->size || ssize > avpkt->size - soff) {

                av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");

                return AVERROR_INVALIDDATA;

            }

            if ((ret = tiff_unpack_strip(s, p, dst, stride, avpkt->data + soff, ssize, i,

                                         FFMIN(s->rps, s->height - i))) < 0) {

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return ret;

                break;

            }

            dst += s->rps * stride;

        }

        if (s->predictor == 2) {

            if (s->photometric == TIFF_PHOTOMETRIC_YCBCR) {

                av_log(s->avctx, AV_LOG_ERROR, "predictor == 2 with YUV is unsupported");

                return AVERROR_PATCHWELCOME;

            }

            dst   = p->data[plane];

            soff  = s->bpp >> 3;

            if (s->planar)

                soff  = FFMAX(soff / s->bppcount, 1);

            ssize = s->width * soff;

            if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_RGBA64LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GRAY16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_YA16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GBRP16LE ||

                s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16LE) {

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

                    for (j = soff; j < ssize; j += 2)

                        AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));

                    dst += stride;

                }

            } else if (s->avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_RGBA64BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_YA16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GBRP16BE ||

                       s->avctx->pix_fmt == AV_PIX_FMT_GBRAP16BE) {

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

                    for (j = soff; j < ssize; j += 2)

                        AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));

                    dst += stride;

                }

            } else {

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

                    for (j = soff; j < ssize; j++)

                        dst[j] += dst[j - soff];

                    dst += stride;

                }

            }

        }

        if (s->photometric == TIFF_PHOTOMETRIC_WHITE_IS_ZERO) {

            int c = (s->avctx->pix_fmt == AV_PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255);

            dst = p->data[plane];

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

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

                    dst[j] = c - dst[j];

                dst += stride;

            }

        }

    }

    if (s->planar && s->bppcount > 2) {

        FFSWAP(uint8_t*, p->data[0],     p->data[2]);

        FFSWAP(int,      p->linesize[0], p->linesize[2]);

        FFSWAP(uint8_t*, p->data[0],     p->data[1]);

        FFSWAP(int,      p->linesize[0], p->linesize[1]);

    }

    *got_frame = 1;

    return avpkt->size;

}


static int process_video_header_vp6(AVFormatContext *s)

{

    EaDemuxContext *ea = s->priv_data;

    AVIOContext *pb = s->pb;

    avio_skip(pb, 8);

    ea->nb_frames = avio_rl32(pb);

    avio_skip(pb, 4);

    ea->time_base.den = avio_rl32(pb);

    ea->time_base.num = avio_rl32(pb);

    ea->video_codec = AV_CODEC_ID_VP6;

    return 1;


void cpu_reset (CPUCRISState *env)
{
	memset(env, 0, offsetof(CPUCRISState, breakpoints));
	tlb_flush(env, 1);
	env->pregs[PR_VR] = 32;
#if defined(CONFIG_USER_ONLY)
	/* start in user mode with interrupts enabled.  */
	env->pregs[PR_CCS] |= U_FLAG | I_FLAG;
#else
	env->pregs[PR_CCS] = 0;
#endif


static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)

{

    BlockDriver *drv = bs->drv;

    if (!drv) {

        return -ENOMEDIUM;

    }

    if (bdrv_check_request(bs, sector_num, nb_sectors)) {

        return -EIO;

    }

    /* throttling disk read I/O */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_intercept(bs, false, nb_sectors);

    }

    return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);

}


av_cold static int auto_matrix(SwrContext *s)

{

    int i, j, out_i;

    double matrix[NUM_NAMED_CHANNELS][NUM_NAMED_CHANNELS]={{0}};

    int64_t unaccounted, in_ch_layout, out_ch_layout;

    double maxcoef=0;

    char buf[128];

    const int matrix_encoding = s->matrix_encoding;

    float maxval;

    in_ch_layout = clean_layout(s, s->in_ch_layout);

    out_ch_layout = clean_layout(s, s->out_ch_layout);

    if(   out_ch_layout == AV_CH_LAYOUT_STEREO_DOWNMIX

       && (in_ch_layout & AV_CH_LAYOUT_STEREO_DOWNMIX) == 0

    )

        out_ch_layout = AV_CH_LAYOUT_STEREO;

    if(    in_ch_layout == AV_CH_LAYOUT_STEREO_DOWNMIX

       && (out_ch_layout & AV_CH_LAYOUT_STEREO_DOWNMIX) == 0

    )

        in_ch_layout = AV_CH_LAYOUT_STEREO;

    if(!sane_layout(in_ch_layout)){

        av_get_channel_layout_string(buf, sizeof(buf), -1, s->in_ch_layout);

        av_log(s, AV_LOG_ERROR, "Input channel layout '%s' is not supported\n", buf);

        return AVERROR(EINVAL);

    }

    if(!sane_layout(out_ch_layout)){

        av_get_channel_layout_string(buf, sizeof(buf), -1, s->out_ch_layout);

        av_log(s, AV_LOG_ERROR, "Output channel layout '%s' is not supported\n", buf);

        return AVERROR(EINVAL);

    }

    memset(s->matrix, 0, sizeof(s->matrix));

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

        if(in_ch_layout & out_ch_layout & (1ULL<<i))

            matrix[i][i]= 1.0;

    }

    unaccounted= in_ch_layout & ~out_ch_layout;

//FIXME implement dolby surround

//FIXME implement full ac3

    if(unaccounted & AV_CH_FRONT_CENTER){

        if((out_ch_layout & AV_CH_LAYOUT_STEREO) == AV_CH_LAYOUT_STEREO){

            if(in_ch_layout & AV_CH_LAYOUT_STEREO) {

                matrix[ FRONT_LEFT][FRONT_CENTER]+= s->clev;

                matrix[FRONT_RIGHT][FRONT_CENTER]+= s->clev;

            } else {

                matrix[ FRONT_LEFT][FRONT_CENTER]+= M_SQRT1_2;

                matrix[FRONT_RIGHT][FRONT_CENTER]+= M_SQRT1_2;

            }

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_LAYOUT_STEREO){

        if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[FRONT_CENTER][ FRONT_LEFT]+= M_SQRT1_2;

            matrix[FRONT_CENTER][FRONT_RIGHT]+= M_SQRT1_2;

            if(in_ch_layout & AV_CH_FRONT_CENTER)

                matrix[FRONT_CENTER][ FRONT_CENTER] = s->clev*sqrt(2);

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_BACK_CENTER){

        if(out_ch_layout & AV_CH_BACK_LEFT){

            matrix[ BACK_LEFT][BACK_CENTER]+= M_SQRT1_2;

            matrix[BACK_RIGHT][BACK_CENTER]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_SIDE_LEFT){

            matrix[ SIDE_LEFT][BACK_CENTER]+= M_SQRT1_2;

            matrix[SIDE_RIGHT][BACK_CENTER]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY ||

                matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                if (unaccounted & (AV_CH_BACK_LEFT | AV_CH_SIDE_LEFT)) {

                    matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev * M_SQRT1_2;

                    matrix[FRONT_RIGHT][BACK_CENTER] += s->slev * M_SQRT1_2;

                } else {

                    matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev;

                    matrix[FRONT_RIGHT][BACK_CENTER] += s->slev;

                }

            } else {

                matrix[ FRONT_LEFT][BACK_CENTER]+= s->slev*M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_CENTER]+= s->slev*M_SQRT1_2;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][BACK_CENTER]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_BACK_LEFT){

        if(out_ch_layout & AV_CH_BACK_CENTER){

            matrix[BACK_CENTER][ BACK_LEFT]+= M_SQRT1_2;

            matrix[BACK_CENTER][BACK_RIGHT]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_SIDE_LEFT){

            if(in_ch_layout & AV_CH_SIDE_LEFT){

                matrix[ SIDE_LEFT][ BACK_LEFT]+= M_SQRT1_2;

                matrix[SIDE_RIGHT][BACK_RIGHT]+= M_SQRT1_2;

            }else{

            matrix[ SIDE_LEFT][ BACK_LEFT]+= 1.0;

            matrix[SIDE_RIGHT][BACK_RIGHT]+= 1.0;

            }

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) {

                matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * M_SQRT1_2;

                matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * M_SQRT1_2;

            } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * SQRT3_2;

                matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * SQRT3_2;

            } else {

                matrix[ FRONT_LEFT][ BACK_LEFT] += s->slev;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][BACK_LEFT ]+= s->slev*M_SQRT1_2;

            matrix[ FRONT_CENTER][BACK_RIGHT]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_SIDE_LEFT){

        if(out_ch_layout & AV_CH_BACK_LEFT){

            /* if back channels do not exist in the input, just copy side

               channels to back channels, otherwise mix side into back */

            if (in_ch_layout & AV_CH_BACK_LEFT) {

                matrix[BACK_LEFT ][SIDE_LEFT ] += M_SQRT1_2;

                matrix[BACK_RIGHT][SIDE_RIGHT] += M_SQRT1_2;

            } else {

                matrix[BACK_LEFT ][SIDE_LEFT ] += 1.0;

                matrix[BACK_RIGHT][SIDE_RIGHT] += 1.0;

            }

        }else if(out_ch_layout & AV_CH_BACK_CENTER){

            matrix[BACK_CENTER][ SIDE_LEFT]+= M_SQRT1_2;

            matrix[BACK_CENTER][SIDE_RIGHT]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) {

                matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * M_SQRT1_2;

                matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * M_SQRT1_2;

            } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * SQRT3_2;

                matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * SQRT3_2;

            } else {

                matrix[ FRONT_LEFT][ SIDE_LEFT] += s->slev;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][SIDE_LEFT ]+= s->slev*M_SQRT1_2;

            matrix[ FRONT_CENTER][SIDE_RIGHT]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_FRONT_LEFT_OF_CENTER){

        if(out_ch_layout & AV_CH_FRONT_LEFT){

            matrix[ FRONT_LEFT][ FRONT_LEFT_OF_CENTER]+= 1.0;

            matrix[FRONT_RIGHT][FRONT_RIGHT_OF_CENTER]+= 1.0;

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][ FRONT_LEFT_OF_CENTER]+= M_SQRT1_2;

            matrix[ FRONT_CENTER][FRONT_RIGHT_OF_CENTER]+= M_SQRT1_2;

        }else

            av_assert0(0);

    }

    /* mix LFE into front left/right or center */

    if (unaccounted & AV_CH_LOW_FREQUENCY) {

        if (out_ch_layout & AV_CH_FRONT_CENTER) {

            matrix[FRONT_CENTER][LOW_FREQUENCY] += s->lfe_mix_level;

        } else if (out_ch_layout & AV_CH_FRONT_LEFT) {

            matrix[FRONT_LEFT ][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2;

            matrix[FRONT_RIGHT][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2;

        } else

            av_assert0(0);

    }

    for(out_i=i=0; i<64; i++){

        double sum=0;

        int in_i=0;

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

            if (i < FF_ARRAY_ELEMS(matrix) && j < FF_ARRAY_ELEMS(matrix[0]))

                s->matrix[out_i][in_i]= matrix[i][j];

            else

                s->matrix[out_i][in_i]= i == j && (in_ch_layout & out_ch_layout & (1ULL<<i));

            sum += fabs(s->matrix[out_i][in_i]);

            if(in_ch_layout & (1ULL<<j))

                in_i++;

        }

        maxcoef= FFMAX(maxcoef, sum);

        if(out_ch_layout & (1ULL<<i))

            out_i++;

    }

    if(s->rematrix_volume  < 0)

        maxcoef = -s->rematrix_volume;

    if (s->rematrix_maxval > 0) {

        maxval = s->rematrix_maxval;

    } else if (   av_get_packed_sample_fmt(s->out_sample_fmt) < AV_SAMPLE_FMT_FLT

               || av_get_packed_sample_fmt(s->int_sample_fmt) < AV_SAMPLE_FMT_FLT) {

        maxval = 1.0;

    } else

        maxval = INT_MAX;

    if(maxcoef > maxval || s->rematrix_volume  < 0){

        maxcoef /= maxval;

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

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

                s->matrix[i][j] /= maxcoef;

            }

    }

    if(s->rematrix_volume > 0){

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

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

                s->matrix[i][j] *= s->rematrix_volume;

            }

    }

    for(i=0; i<av_get_channel_layout_nb_channels(out_ch_layout); i++){

        for(j=0; j<av_get_channel_layout_nb_channels(in_ch_layout); j++){

            av_log(NULL, AV_LOG_DEBUG, "%f ", s->matrix[i][j]);

        }

        av_log(NULL, AV_LOG_DEBUG, "\n");

    }

    return 0;

}


void av_thread_message_queue_set_err_recv(AVThreadMessageQueue *mq,

                                          int err)

{

#if HAVE_THREADS

    pthread_mutex_lock(&mq->lock);

    mq->err_recv = err;

    pthread_cond_broadcast(&mq->cond);

    pthread_mutex_unlock(&mq->lock);

#endif /* HAVE_THREADS */

}


static int local_renameat(FsContext *ctx, V9fsPath *olddir,

                          const char *old_name, V9fsPath *newdir,

                          const char *new_name)

{

    int ret;

    int odirfd, ndirfd;

    odirfd = local_opendir_nofollow(ctx, olddir->data);

    if (odirfd == -1) {

        return -1;

    }

    ndirfd = local_opendir_nofollow(ctx, newdir->data);

    if (ndirfd == -1) {

        close_preserve_errno(odirfd);

        return -1;

    }

    ret = renameat(odirfd, old_name, ndirfd, new_name);

    if (ret < 0) {

        goto out;

    }

    if (ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        int omap_dirfd, nmap_dirfd;

        ret = mkdirat(ndirfd, VIRTFS_META_DIR, 0700);

        if (ret < 0 && errno != EEXIST) {

            goto err_undo_rename;

        }

        omap_dirfd = openat(odirfd, VIRTFS_META_DIR,

                            O_RDONLY | O_DIRECTORY | O_NOFOLLOW);

        if (omap_dirfd == -1) {

            goto err;

        }

        nmap_dirfd = openat(ndirfd, VIRTFS_META_DIR,

                            O_RDONLY | O_DIRECTORY | O_NOFOLLOW);

        if (nmap_dirfd == -1) {

            close_preserve_errno(omap_dirfd);

            goto err;

        }

        /* rename the .virtfs_metadata files */

        ret = renameat(omap_dirfd, old_name, nmap_dirfd, new_name);

        close_preserve_errno(nmap_dirfd);

        close_preserve_errno(omap_dirfd);

        if (ret < 0 && errno != ENOENT) {

            goto err_undo_rename;

        }

        ret = 0;

    }

    goto out;

err:

    ret = -1;

err_undo_rename:

    renameat_preserve_errno(ndirfd, new_name, odirfd, old_name);

out:

    close_preserve_errno(ndirfd);

    close_preserve_errno(odirfd);

    return ret;

}


static bool blit_is_unsafe(struct CirrusVGAState *s)
{
    /* should be the case, see cirrus_bitblt_start */
    assert(s->cirrus_blt_width > 0);
    assert(s->cirrus_blt_height > 0);
    if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch,
                              s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) {
    if (blit_region_is_unsafe(s, s->cirrus_blt_srcpitch,
                              s->cirrus_blt_srcaddr & s->cirrus_addr_mask)) {
    return false;


static void update_error_limit(WavpackFrameContext *ctx)

{

    int i, br[2], sl[2];

    for (i = 0; i <= ctx->stereo_in; i++) {

        ctx->ch[i].bitrate_acc += ctx->ch[i].bitrate_delta;

        br[i]                   = ctx->ch[i].bitrate_acc >> 16;

        sl[i]                   = LEVEL_DECAY(ctx->ch[i].slow_level);

    }

    if (ctx->stereo_in && ctx->hybrid_bitrate) {

        int balance = (sl[1] - sl[0] + br[1] + 1) >> 1;

        if (balance > br[0]) {

            br[1] = br[0] << 1;

            br[0] = 0;

        } else if (-balance > br[0]) {

            br[0] <<= 1;

            br[1]   = 0;

        } else {

            br[1] = br[0] + balance;

            br[0] = br[0] - balance;

        }

    }

    for (i = 0; i <= ctx->stereo_in; i++) {

        if (ctx->hybrid_bitrate) {

            if (sl[i] - br[i] > -0x100)

                ctx->ch[i].error_limit = wp_exp2(sl[i] - br[i] + 0x100);

            else

                ctx->ch[i].error_limit = 0;

        } else {

            ctx->ch[i].error_limit = wp_exp2(br[i]);

        }

    }

}


static int do_token_setup(USBDevice *s, USBPacket *p)

{

    int request, value, index;

    int ret = 0;

    if (p->len != 8)

    memcpy(s->setup_buf, p->data, 8);

    s->setup_len   = (s->setup_buf[7] << 8) | s->setup_buf[6];

    s->setup_index = 0;

    request = (s->setup_buf[0] << 8) | s->setup_buf[1];

    value   = (s->setup_buf[3] << 8) | s->setup_buf[2];

    index   = (s->setup_buf[5] << 8) | s->setup_buf[4];

    if (s->setup_buf[0] & USB_DIR_IN) {

        ret = s->info->handle_control(s, request, value, index,

                                      s->setup_len, s->data_buf);

        if (ret < 0)

            return ret;

        if (ret < s->setup_len)

            s->setup_len = ret;

        s->setup_state = SETUP_STATE_DATA;

    } else {

        if (s->setup_len == 0)

            s->setup_state = SETUP_STATE_ACK;

        else

            s->setup_state = SETUP_STATE_DATA;

    return ret;


static int colo_packet_compare_common(Packet *ppkt, Packet *spkt, int offset)

{

    if (trace_event_get_state(TRACE_COLO_COMPARE_MISCOMPARE)) {

        char pri_ip_src[20], pri_ip_dst[20], sec_ip_src[20], sec_ip_dst[20];

        strcpy(pri_ip_src, inet_ntoa(ppkt->ip->ip_src));

        strcpy(pri_ip_dst, inet_ntoa(ppkt->ip->ip_dst));

        strcpy(sec_ip_src, inet_ntoa(spkt->ip->ip_src));

        strcpy(sec_ip_dst, inet_ntoa(spkt->ip->ip_dst));

        trace_colo_compare_ip_info(ppkt->size, pri_ip_src,

                                   pri_ip_dst, spkt->size,

                                   sec_ip_src, sec_ip_dst);

    }

    offset = ppkt->vnet_hdr_len + offset;

    if (ppkt->size == spkt->size) {

        return memcmp(ppkt->data + offset,

                      spkt->data + offset,

                      spkt->size - offset);

    } else {

        trace_colo_compare_main("Net packet size are not the same");

        return -1;

    }

}


static void nbd_coroutine_end(NbdClientSession *s,

    struct nbd_request *request)

{

    int i = HANDLE_TO_INDEX(s, request->handle);

    s->recv_coroutine[i] = NULL;

    if (s->in_flight-- == MAX_NBD_REQUESTS) {

        qemu_co_mutex_unlock(&s->free_sema);

    }

}


static char *read_splashfile(char *filename, int *file_sizep, int *file_typep)

{

    GError *err = NULL;

    gboolean res;

    gchar *content;

    int file_type = -1;

    unsigned int filehead = 0;

    int bmp_bpp;

    res = g_file_get_contents(filename, &content, (gsize *)file_sizep, &err);

    if (res == FALSE) {

        error_report("failed to read splash file '%s'", filename);

        g_error_free(err);

        return NULL;

    }

    /* check file size */

    if (*file_sizep < 30) {

        goto error;

    }

    /* check magic ID */

    filehead = ((content[0] & 0xff) + (content[1] << 8)) & 0xffff;

    if (filehead == 0xd8ff) {

        file_type = JPG_FILE;

    } else if (filehead == 0x4d42) {

        file_type = BMP_FILE;

    } else {

        goto error;

    }

    /* check BMP bpp */

    if (file_type == BMP_FILE) {

        bmp_bpp = (content[28] + (content[29] << 8)) & 0xffff;

        if (bmp_bpp != 24) {

            goto error;

        }

    }

    /* return values */

    *file_typep = file_type;

    return content;

error:

    error_report("splash file '%s' format not recognized; must be JPEG "

                 "or 24 bit BMP", filename);

    g_free(content);

    return NULL;

}


int av_bsf_list_parse_str(const char *str, AVBSFContext **bsf_lst)

{

    AVBSFList *lst;

    char *bsf_str, *buf, *dup, *saveptr;

    int ret;

    if (!str)

        return av_bsf_get_null_filter(bsf_lst);

    lst = av_bsf_list_alloc();

    if (!lst)

        return AVERROR(ENOMEM);

    if (!(dup = buf = av_strdup(str)))

        return AVERROR(ENOMEM);

    while (1) {

        bsf_str = av_strtok(buf, ",", &saveptr);

        if (!bsf_str)

            break;

        ret = bsf_parse_single(bsf_str, lst);

        if (ret < 0)

            goto end;

        buf = NULL;

    }

    ret = av_bsf_list_finalize(&lst, bsf_lst);

end:

    if (ret < 0)

        av_bsf_list_free(&lst);

    av_free(dup);

    return ret;

}


static int decode_spectrum_and_dequant(AACContext * ac, float coef[1024], GetBitContext * gb, float sf[120],

        int pulse_present, const Pulse * pulse, const IndividualChannelStream * ics, enum BandType band_type[120]) {

    int i, k, g, idx = 0;

    const int c = 1024/ics->num_windows;

    const uint16_t * offsets = ics->swb_offset;

    float *coef_base = coef;

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

        memset(coef + g * 128 + offsets[ics->max_sfb], 0, sizeof(float)*(c - offsets[ics->max_sfb]));

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

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

            const int cur_band_type = band_type[idx];

            const int dim = cur_band_type >= FIRST_PAIR_BT ? 2 : 4;

            const int is_cb_unsigned = IS_CODEBOOK_UNSIGNED(cur_band_type);

            int group;

            if (cur_band_type == ZERO_BT) {

                for (group = 0; group < ics->group_len[g]; group++) {

                    memset(coef + group * 128 + offsets[i], 0, (offsets[i+1] - offsets[i])*sizeof(float));

                }

            }else if (cur_band_type == NOISE_BT) {

                const float scale = sf[idx] / ((offsets[i+1] - offsets[i]) * PNS_MEAN_ENERGY);

                for (group = 0; group < ics->group_len[g]; group++) {

                    for (k = offsets[i]; k < offsets[i+1]; k++) {

                        ac->random_state  = lcg_random(ac->random_state);

                        coef[group*128+k] = ac->random_state * scale;

                    }

                }

            }else if (cur_band_type != INTENSITY_BT2 && cur_band_type != INTENSITY_BT) {

                for (group = 0; group < ics->group_len[g]; group++) {

                    for (k = offsets[i]; k < offsets[i+1]; k += dim) {

                        const int index = get_vlc2(gb, vlc_spectral[cur_band_type - 1].table, 6, 3);

                        const int coef_tmp_idx = (group << 7) + k;

                        const float *vq_ptr;

                        int j;

                        if(index >= ff_aac_spectral_sizes[cur_band_type - 1]) {

                            av_log(ac->avccontext, AV_LOG_ERROR,

                                "Read beyond end of ff_aac_codebook_vectors[%d][]. index %d >= %d\n",

                                cur_band_type - 1, index, ff_aac_spectral_sizes[cur_band_type - 1]);

                            return -1;

                        }

                        vq_ptr = &ff_aac_codebook_vectors[cur_band_type - 1][index * dim];

                        if (is_cb_unsigned) {

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

                                if (vq_ptr[j])

                                    coef[coef_tmp_idx + j] = 1 - 2*(int)get_bits1(gb);

                        }else {

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

                                coef[coef_tmp_idx + j] = 1.0f;

                        }

                        if (cur_band_type == ESC_BT) {

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

                                if (vq_ptr[j] == 64.0f) {

                                    int n = 4;

                                    /* The total length of escape_sequence must be < 22 bits according

                                       to the specification (i.e. max is 11111111110xxxxxxxxxx). */

                                    while (get_bits1(gb) && n < 15) n++;

                                    if(n == 15) {

                                        av_log(ac->avccontext, AV_LOG_ERROR, "error in spectral data, ESC overflow\n");

                                        return -1;

                                    }

                                    n = (1<<n) + get_bits(gb, n);

                                    coef[coef_tmp_idx + j] *= cbrtf(fabsf(n)) * n;

                                }else

                                    coef[coef_tmp_idx + j] *= vq_ptr[j];

                            }

                        }else

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

                                coef[coef_tmp_idx + j] *= vq_ptr[j];

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

                            coef[coef_tmp_idx + j] *= sf[idx];

                    }

                }

            }

        }

        coef += ics->group_len[g]<<7;

    }

    if (pulse_present) {

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

            float co  = coef_base[ pulse->pos[i] ];

            float ico = co / sqrtf(sqrtf(fabsf(co))) + pulse->amp[i];

            coef_base[ pulse->pos[i] ] = cbrtf(fabsf(ico)) * ico;

        }

    }

    return 0;

}


struct pxa2xx_lcdc_s *pxa2xx_lcdc_init(target_phys_addr_t base, qemu_irq irq,

                DisplayState *ds)

{

    int iomemtype;

    struct pxa2xx_lcdc_s *s;

    s = (struct pxa2xx_lcdc_s *) qemu_mallocz(sizeof(struct pxa2xx_lcdc_s));

    s->base = base;

    s->invalidated = 1;

    s->irq = irq;

    s->ds = ds;

    pxa2xx_lcdc_orientation(s, graphic_rotate);

    iomemtype = cpu_register_io_memory(0, pxa2xx_lcdc_readfn,

                    pxa2xx_lcdc_writefn, s);

    cpu_register_physical_memory(base, 0x000fffff, iomemtype);

    graphic_console_init(ds, pxa2xx_update_display,

                    pxa2xx_invalidate_display, pxa2xx_screen_dump, s);

    switch (s->ds->depth) {

    case 0:

        s->dest_width = 0;

        break;

    case 8:

        s->line_fn[0] = pxa2xx_draw_fn_8;

        s->line_fn[1] = pxa2xx_draw_fn_8t;

        s->dest_width = 1;

        break;

    case 15:

        s->line_fn[0] = pxa2xx_draw_fn_15;

        s->line_fn[1] = pxa2xx_draw_fn_15t;

        s->dest_width = 2;

        break;

    case 16:

        s->line_fn[0] = pxa2xx_draw_fn_16;

        s->line_fn[1] = pxa2xx_draw_fn_16t;

        s->dest_width = 2;

        break;

    case 24:

        s->line_fn[0] = pxa2xx_draw_fn_24;

        s->line_fn[1] = pxa2xx_draw_fn_24t;

        s->dest_width = 3;

        break;

    case 32:

        s->line_fn[0] = pxa2xx_draw_fn_32;

        s->line_fn[1] = pxa2xx_draw_fn_32t;

        s->dest_width = 4;

        break;

    default:

        fprintf(stderr, "%s: Bad color depth\n", __FUNCTION__);

        exit(1);

    }

    register_savevm("pxa2xx_lcdc", 0, 0,

                    pxa2xx_lcdc_save, pxa2xx_lcdc_load, s);

    return s;

}


static int stdio_get_fd(void *opaque)

{

    QEMUFileStdio *s = opaque;

    return fileno(s->stdio_file);

}


static inline void cris_fidx_d(unsigned int x)

{

	register unsigned int v asm("$r10") = x;

	asm ("fidxd\t[%0]\n" : : "r" (v) );

}


void *av_malloc(size_t size)

{

    void *ptr = NULL;

#if CONFIG_MEMALIGN_HACK

    long diff;

#endif

    /* let's disallow possible ambiguous cases */

    if (size > (max_alloc_size - 32))

        return NULL;

#if CONFIG_MEMALIGN_HACK

    ptr = malloc(size + ALIGN);

    if (!ptr)

        return ptr;

    diff              = ((~(long)ptr)&(ALIGN - 1)) + 1;

    ptr               = (char *)ptr + diff;

    ((char *)ptr)[-1] = diff;

#elif HAVE_POSIX_MEMALIGN

    if (size) //OS X on SDK 10.6 has a broken posix_memalign implementation

    if (posix_memalign(&ptr, ALIGN, size))

        ptr = NULL;

#elif HAVE_ALIGNED_MALLOC

    ptr = _aligned_malloc(size, ALIGN);

#elif HAVE_MEMALIGN

#ifndef __DJGPP__

    ptr = memalign(ALIGN, size);

#else

    ptr = memalign(size, ALIGN);

#endif

    /* Why 64?

     * Indeed, we should align it:

     *   on  4 for 386

     *   on 16 for 486

     *   on 32 for 586, PPro - K6-III

     *   on 64 for K7 (maybe for P3 too).

     * Because L1 and L2 caches are aligned on those values.

     * But I don't want to code such logic here!

     */

    /* Why 32?

     * For AVX ASM. SSE / NEON needs only 16.

     * Why not larger? Because I did not see a difference in benchmarks ...

     */

    /* benchmarks with P3

     * memalign(64) + 1          3071, 3051, 3032

     * memalign(64) + 2          3051, 3032, 3041

     * memalign(64) + 4          2911, 2896, 2915

     * memalign(64) + 8          2545, 2554, 2550

     * memalign(64) + 16         2543, 2572, 2563

     * memalign(64) + 32         2546, 2545, 2571

     * memalign(64) + 64         2570, 2533, 2558

     *

     * BTW, malloc seems to do 8-byte alignment by default here.

     */

#else

    ptr = malloc(size);

#endif

    if(!ptr && !size) {

        size = 1;

        ptr= av_malloc(1);

    }

#if CONFIG_MEMORY_POISONING

    if (ptr)

        memset(ptr, 0x2a, size);

#endif

    return ptr;

}


static int mov_write_audio_tag(AVIOContext *pb, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

    int version = 0;

    uint32_t tag = track->tag;

    if (track->mode == MODE_MOV) {

        if (track->timescale > UINT16_MAX) {

            if (mov_get_lpcm_flags(track->enc->codec_id))

                tag = AV_RL32("lpcm");

            version = 2;

        } else if (track->audio_vbr || mov_pcm_le_gt16(track->enc->codec_id) ||

                   track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||

                   track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||

                   track->enc->codec_id == AV_CODEC_ID_QDM2) {

            version = 1;

        }

    }

    avio_wb32(pb, 0); /* size */

    avio_wl32(pb, tag); // store it byteswapped

    avio_wb32(pb, 0); /* Reserved */

    avio_wb16(pb, 0); /* Reserved */

    avio_wb16(pb, 1); /* Data-reference index, XXX  == 1 */

    /* SoundDescription */

    avio_wb16(pb, version); /* Version */

    avio_wb16(pb, 0); /* Revision level */

    avio_wb32(pb, 0); /* Reserved */

    if (version == 2) {

        avio_wb16(pb, 3);

        avio_wb16(pb, 16);

        avio_wb16(pb, 0xfffe);

        avio_wb16(pb, 0);

        avio_wb32(pb, 0x00010000);

        avio_wb32(pb, 72);

        avio_wb64(pb, av_double2int(track->enc->sample_rate));

        avio_wb32(pb, track->enc->channels);

        avio_wb32(pb, 0x7F000000);

        avio_wb32(pb, av_get_bits_per_sample(track->enc->codec_id));

        avio_wb32(pb, mov_get_lpcm_flags(track->enc->codec_id));

        avio_wb32(pb, track->sample_size);

        avio_wb32(pb, get_samples_per_packet(track));

    } else {

        if (track->mode == MODE_MOV) {

            avio_wb16(pb, track->enc->channels);

            if (track->enc->codec_id == AV_CODEC_ID_PCM_U8 ||

                track->enc->codec_id == AV_CODEC_ID_PCM_S8)

                avio_wb16(pb, 8); /* bits per sample */

            else

                avio_wb16(pb, 16);

            avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */

        } else { /* reserved for mp4/3gp */

            avio_wb16(pb, 2);

            avio_wb16(pb, 16);

            avio_wb16(pb, 0);

        }

        avio_wb16(pb, 0); /* packet size (= 0) */

        avio_wb16(pb, track->enc->sample_rate <= UINT16_MAX ?

                      track->enc->sample_rate : 0);

        avio_wb16(pb, 0); /* Reserved */

    }

    if(version == 1) { /* SoundDescription V1 extended info */

        avio_wb32(pb, track->enc->frame_size); /* Samples per packet */

        avio_wb32(pb, track->sample_size / track->enc->channels); /* Bytes per packet */

        avio_wb32(pb, track->sample_size); /* Bytes per frame */

        avio_wb32(pb, 2); /* Bytes per sample */

    }

    if(track->mode == MODE_MOV &&

       (track->enc->codec_id == AV_CODEC_ID_AAC ||

        track->enc->codec_id == AV_CODEC_ID_AC3 ||

        track->enc->codec_id == AV_CODEC_ID_AMR_NB ||

        track->enc->codec_id == AV_CODEC_ID_ALAC ||

        track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||

        track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||

        track->enc->codec_id == AV_CODEC_ID_QDM2 ||

        (mov_pcm_le_gt16(track->enc->codec_id) && version==1)))

        mov_write_wave_tag(pb, track);

    else if(track->tag == MKTAG('m','p','4','a'))

        mov_write_esds_tag(pb, track);

    else if(track->enc->codec_id == AV_CODEC_ID_AMR_NB)

        mov_write_amr_tag(pb, track);

    else if(track->enc->codec_id == AV_CODEC_ID_AC3)

        mov_write_ac3_tag(pb, track);

    else if(track->enc->codec_id == AV_CODEC_ID_ALAC)

        mov_write_extradata_tag(pb, track);

    else if (track->enc->codec_id == AV_CODEC_ID_WMAPRO)

        mov_write_wfex_tag(pb, track);

    else if (track->vos_len > 0)

        mov_write_glbl_tag(pb, track);

    if (track->mode == MODE_MOV && track->enc->codec_type == AVMEDIA_TYPE_AUDIO)

        mov_write_chan_tag(pb, track);

    return update_size(pb, pos);

}


static int metadata_parse(FLACContext *s)

{

    int i, metadata_last, metadata_type, metadata_size;

    int initial_pos= get_bits_count(&s->gb);

    if (show_bits_long(&s->gb, 32) == MKBETAG('f','L','a','C')) {

        skip_bits_long(&s->gb, 32);

        do {

            metadata_last = get_bits1(&s->gb);

            metadata_type = get_bits(&s->gb, 7);

            metadata_size = get_bits_long(&s->gb, 24);

            if (get_bits_count(&s->gb) + 8*metadata_size > s->gb.size_in_bits) {

                skip_bits_long(&s->gb, initial_pos - get_bits_count(&s->gb));

                break;

            }

            if (metadata_size) {

                switch (metadata_type) {

                case FLAC_METADATA_TYPE_STREAMINFO:

                    if (!s->got_streaminfo) {

                        ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s,

                                                 s->gb.buffer+get_bits_count(&s->gb)/8);

                        allocate_buffers(s);

                        s->got_streaminfo = 1;

                    }

                default:

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

                        skip_bits(&s->gb, 8);

                }

            }

        } while (!metadata_last);

        return 1;

    }

    return 0;

}


static int coroutine_fn v9fs_complete_rename(V9fsPDU *pdu, V9fsFidState *fidp,

                                             int32_t newdirfid,

                                             V9fsString *name)

{

    char *end;

    int err = 0;

    V9fsPath new_path;

    V9fsFidState *tfidp;

    V9fsState *s = pdu->s;

    V9fsFidState *dirfidp = NULL;

    char *old_name, *new_name;

    v9fs_path_init(&new_path);

    if (newdirfid != -1) {

        dirfidp = get_fid(pdu, newdirfid);

        if (dirfidp == NULL) {

            err = -ENOENT;

            goto out_nofid;

        }

        BUG_ON(dirfidp->fid_type != P9_FID_NONE);

        v9fs_co_name_to_path(pdu, &dirfidp->path, name->data, &new_path);

    } else {

        old_name = fidp->path.data;

        end = strrchr(old_name, '/');

        if (end) {

            end++;

        } else {

            end = old_name;

        }

        new_name = g_malloc0(end - old_name + name->size + 1);

        strncat(new_name, old_name, end - old_name);

        strncat(new_name + (end - old_name), name->data, name->size);

        v9fs_co_name_to_path(pdu, NULL, new_name, &new_path);

        g_free(new_name);

    }

    err = v9fs_co_rename(pdu, &fidp->path, &new_path);

    if (err < 0) {

        goto out;

    }

    /*

     * Fixup fid's pointing to the old name to

     * start pointing to the new name

     */

    for (tfidp = s->fid_list; tfidp; tfidp = tfidp->next) {

        if (v9fs_path_is_ancestor(&fidp->path, &tfidp->path)) {

            /* replace the name */

            v9fs_fix_path(&tfidp->path, &new_path, strlen(fidp->path.data));

        }

    }

out:

    if (dirfidp) {

        put_fid(pdu, dirfidp);

    }

    v9fs_path_free(&new_path);

out_nofid:

    return err;

}


static av_cold int alac_decode_close(AVCodecContext *avctx)

{

    ALACContext *alac = avctx->priv_data;

    int chan;

    for (chan = 0; chan < alac->numchannels; chan++) {

        av_freep(&alac->predicterror_buffer[chan]);

        av_freep(&alac->outputsamples_buffer[chan]);

        av_freep(&alac->wasted_bits_buffer[chan]);

    }

    return 0;

}


void OPPROTO op_fdiv_ST0_FT0(void)

{

    ST0 /= FT0;

}


static void ipmi_sim_handle_command(IPMIBmc *b,

                                    uint8_t *cmd, unsigned int cmd_len,

                                    unsigned int max_cmd_len,

                                    uint8_t msg_id)

{

    IPMIBmcSim *ibs = IPMI_BMC_SIMULATOR(b);

    IPMIInterface *s = ibs->parent.intf;

    IPMIInterfaceClass *k = IPMI_INTERFACE_GET_CLASS(s);

    unsigned int netfn;

    uint8_t rsp[MAX_IPMI_MSG_SIZE];

    unsigned int rsp_len_holder = 0;

    unsigned int *rsp_len = &rsp_len_holder;

    unsigned int max_rsp_len = sizeof(rsp);

    /* Set up the response, set the low bit of NETFN. */

    /* Note that max_rsp_len must be at least 3 */

    if (max_rsp_len < 3) {

        rsp[2] = IPMI_CC_REQUEST_DATA_TRUNCATED;

        goto out;

    }

    IPMI_ADD_RSP_DATA(cmd[0] | 0x04);

    IPMI_ADD_RSP_DATA(cmd[1]);

    IPMI_ADD_RSP_DATA(0); /* Assume success */

    /* If it's too short or it was truncated, return an error. */

    if (cmd_len < 2) {

        rsp[2] = IPMI_CC_REQUEST_DATA_LENGTH_INVALID;

        goto out;

    }

    if (cmd_len > max_cmd_len) {

        rsp[2] = IPMI_CC_REQUEST_DATA_TRUNCATED;

        goto out;

    }

    if ((cmd[0] & 0x03) != 0) {

        /* Only have stuff on LUN 0 */

        rsp[2] = IPMI_CC_COMMAND_INVALID_FOR_LUN;

        goto out;

    }

    netfn = cmd[0] >> 2;

    /* Odd netfns are not valid, make sure the command is registered */

    if ((netfn & 1) || !ibs->netfns[netfn / 2] ||

                        (cmd[1] >= ibs->netfns[netfn / 2]->cmd_nums) ||

                        (!ibs->netfns[netfn / 2]->cmd_handlers[cmd[1]])) {

        rsp[2] = IPMI_CC_INVALID_CMD;

        goto out;

    }

    ibs->netfns[netfn / 2]->cmd_handlers[cmd[1]](ibs, cmd, cmd_len, rsp, rsp_len,

                                                max_rsp_len);

 out:

    k->handle_rsp(s, msg_id, rsp, *rsp_len);

    next_timeout(ibs);

}


static void qed_read_backing_file(BDRVQEDState *s, uint64_t pos,

                                  QEMUIOVector *qiov,

                                  BlockDriverCompletionFunc *cb, void *opaque)

{

    uint64_t backing_length = 0;

    size_t size;

    /* If there is a backing file, get its length.  Treat the absence of a

     * backing file like a zero length backing file.

     */

    if (s->bs->backing_hd) {

        int64_t l = bdrv_getlength(s->bs->backing_hd);

        if (l < 0) {

            cb(opaque, l);

            return;

        }

        backing_length = l;

    }

    /* Zero all sectors if reading beyond the end of the backing file */

    if (pos >= backing_length ||

        pos + qiov->size > backing_length) {

        qemu_iovec_memset(qiov, 0, 0, qiov->size);

    }

    /* Complete now if there are no backing file sectors to read */

    if (pos >= backing_length) {

        cb(opaque, 0);

        return;

    }

    /* If the read straddles the end of the backing file, shorten it */

    size = MIN((uint64_t)backing_length - pos, qiov->size);

    BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);

    bdrv_aio_readv(s->bs->backing_hd, pos / BDRV_SECTOR_SIZE,

                   qiov, size / BDRV_SECTOR_SIZE, cb, opaque);

}


int av_parse_cpu_caps(unsigned *flags, const char *s)

{

        static const AVOption cpuflags_opts[] = {

        { "flags"   , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },

#if   ARCH_PPC

        { "altivec" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ALTIVEC  },    .unit = "flags" },

#elif ARCH_X86

        { "mmx"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX      },    .unit = "flags" },

        { "mmx2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX2     },    .unit = "flags" },

        { "mmxext"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX2     },    .unit = "flags" },

        { "sse"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE      },    .unit = "flags" },

        { "sse2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE2     },    .unit = "flags" },

        { "sse2slow", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE2SLOW },    .unit = "flags" },

        { "sse3"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE3     },    .unit = "flags" },

        { "sse3slow", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE3SLOW },    .unit = "flags" },

        { "ssse3"   , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSSE3    },    .unit = "flags" },

        { "atom"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ATOM     },    .unit = "flags" },

        { "sse4.1"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE4     },    .unit = "flags" },

        { "sse4.2"  , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_SSE42    },    .unit = "flags" },

        { "avx"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_AVX      },    .unit = "flags" },

        { "xop"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_XOP      },    .unit = "flags" },

        { "fma3"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_FMA3     },    .unit = "flags" },

        { "fma4"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_FMA4     },    .unit = "flags" },

        { "avx2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_AVX2     },    .unit = "flags" },

        { "bmi1"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_BMI1     },    .unit = "flags" },

        { "bmi2"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_BMI2     },    .unit = "flags" },

        { "3dnow"   , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_3DNOW    },    .unit = "flags" },

        { "3dnowext", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_3DNOWEXT },    .unit = "flags" },

        { "cmov",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_CMOV     },    .unit = "flags" },

#define CPU_FLAG_P2 AV_CPU_FLAG_CMOV | AV_CPU_FLAG_MMX

#define CPU_FLAG_P3 CPU_FLAG_P2 | AV_CPU_FLAG_MMX2 | AV_CPU_FLAG_SSE

#define CPU_FLAG_P4 CPU_FLAG_P3| AV_CPU_FLAG_SSE2

        { "pentium2", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P2          },    .unit = "flags" },

        { "pentium3", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P3          },    .unit = "flags" },

        { "pentium4", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_P4          },    .unit = "flags" },

#define CPU_FLAG_K62 AV_CPU_FLAG_MMX | AV_CPU_FLAG_3DNOW

#define CPU_FLAG_ATHLON   CPU_FLAG_K62 | AV_CPU_FLAG_CMOV | AV_CPU_FLAG_3DNOWEXT | AV_CPU_FLAG_MMX2

#define CPU_FLAG_ATHLONXP CPU_FLAG_ATHLON | AV_CPU_FLAG_SSE

#define CPU_FLAG_K8  CPU_FLAG_ATHLONXP | AV_CPU_FLAG_SSE2

        { "k6",       NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_MMX      },    .unit = "flags" },

        { "k62",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_K62         },    .unit = "flags" },

        { "athlon",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_ATHLON      },    .unit = "flags" },

        { "athlonxp", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_ATHLONXP    },    .unit = "flags" },

        { "k8",       NULL, 0, AV_OPT_TYPE_CONST, { .i64 = CPU_FLAG_K8          },    .unit = "flags" },

#elif ARCH_ARM

        { "armv5te",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV5TE  },    .unit = "flags" },

        { "armv6",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV6    },    .unit = "flags" },

        { "armv6t2",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV6T2  },    .unit = "flags" },

        { "vfp",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFP      },    .unit = "flags" },

        { "vfpv3",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFPV3    },    .unit = "flags" },

        { "neon",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_NEON     },    .unit = "flags" },

#elif ARCH_AARCH64

        { "armv8",    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_ARMV8    },    .unit = "flags" },

        { "neon",     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_NEON     },    .unit = "flags" },

        { "vfp",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_CPU_FLAG_VFP      },    .unit = "flags" },

#endif

        { NULL },

    };

    static const AVClass class = {

        .class_name = "cpuflags",

        .item_name  = av_default_item_name,

        .option     = cpuflags_opts,

        .version    = LIBAVUTIL_VERSION_INT,

    };

    const AVClass *pclass = &class;

    return av_opt_eval_flags(&pclass, &cpuflags_opts[0], s, flags);

}


static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,

                                Error **errp)

{

    char *msg = NULL;

    int result = -1;

    if (!(reply->type & (1 << 31))) {

        return 1;

    }

    if (reply->length) {

        if (reply->length > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "server error 0x%" PRIx32

                       " (%s) message is too long",

                       reply->type, nbd_rep_lookup(reply->type));

            goto cleanup;

        }

        msg = g_malloc(reply->length + 1);

        if (nbd_read(ioc, msg, reply->length, errp) < 0) {

            error_prepend(errp, "failed to read option error 0x%" PRIx32

                          " (%s) message",

                          reply->type, nbd_rep_lookup(reply->type));

            goto cleanup;

        }

        msg[reply->length] = '\0';

    }

    switch (reply->type) {

    case NBD_REP_ERR_UNSUP:

        trace_nbd_reply_err_unsup(reply->option, nbd_opt_lookup(reply->option));

        result = 0;

        goto cleanup;

    case NBD_REP_ERR_POLICY:

        error_setg(errp, "Denied by server for option %" PRIx32 " (%s)",

                   reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_INVALID:

        error_setg(errp, "Invalid data length for option %" PRIx32 " (%s)",

                   reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_PLATFORM:

        error_setg(errp, "Server lacks support for option %" PRIx32 " (%s)",

                   reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_TLS_REQD:

        error_setg(errp, "TLS negotiation required before option %" PRIx32

                   " (%s)", reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_UNKNOWN:

        error_setg(errp, "Requested export not available for option %" PRIx32

                   " (%s)", reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_SHUTDOWN:

        error_setg(errp, "Server shutting down before option %" PRIx32 " (%s)",

                   reply->option, nbd_opt_lookup(reply->option));

        break;

    case NBD_REP_ERR_BLOCK_SIZE_REQD:

        error_setg(errp, "Server requires INFO_BLOCK_SIZE for option %" PRIx32

                   " (%s)", reply->option, nbd_opt_lookup(reply->option));

        break;

    default:

        error_setg(errp, "Unknown error code when asking for option %" PRIx32

                   " (%s)", reply->option, nbd_opt_lookup(reply->option));

        break;

    }

    if (msg) {

        error_append_hint(errp, "%s\n", msg);

    }

 cleanup:

    g_free(msg);

    if (result < 0) {

        nbd_send_opt_abort(ioc);

    }

    return result;

}


static int check_refcounts_l1(BlockDriverState *bs,

                              BdrvCheckResult *res,

                              uint16_t *refcount_table,

                              int refcount_table_size,

                              int64_t l1_table_offset, int l1_size,

                              int flags)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t *l1_table, l2_offset, l1_size2;

    int i, ret;

    l1_size2 = l1_size * sizeof(uint64_t);

    /* Mark L1 table as used */

    inc_refcounts(bs, res, refcount_table, refcount_table_size,

        l1_table_offset, l1_size2);

    /* Read L1 table entries from disk */

    if (l1_size2 == 0) {

        l1_table = NULL;

    } else {

        l1_table = g_malloc(l1_size2);

        if (bdrv_pread(bs->file, l1_table_offset,

                       l1_table, l1_size2) != l1_size2)

            goto fail;

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

            be64_to_cpus(&l1_table[i]);

    }

    /* Do the actual checks */

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

        l2_offset = l1_table[i];

        if (l2_offset) {

            /* Mark L2 table as used */

            l2_offset &= L1E_OFFSET_MASK;

            inc_refcounts(bs, res, refcount_table, refcount_table_size,

                l2_offset, s->cluster_size);

            /* L2 tables are cluster aligned */

            if (offset_into_cluster(s, l2_offset)) {

                fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "

                    "cluster aligned; L1 entry corrupted\n", l2_offset);

                res->corruptions++;

            }

            /* Process and check L2 entries */

            ret = check_refcounts_l2(bs, res, refcount_table,

                                     refcount_table_size, l2_offset, flags);

            if (ret < 0) {

                goto fail;

            }

        }

    }

    g_free(l1_table);

    return 0;

fail:

    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");

    res->check_errors++;

    g_free(l1_table);

    return -EIO;

}


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

{

    int level, i, j, run;

    RLTable *rl = &ff_rl_mpeg1;

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

    const uint16_t *quant_matrix;

    const int qscale = s->qscale;

    int mismatch;

    mismatch = 1;

    {

        OPEN_READER(re, &s->gb);

        i = -1;

        if (n < 4)

            quant_matrix = s->inter_matrix;

        else

            quant_matrix = s->chroma_inter_matrix;

        // special case for first coefficient, no need to add second VLC table

        UPDATE_CACHE(re, &s->gb);

        if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {

            level= (3 * qscale * quant_matrix[0]) >> 5;

            if (GET_CACHE(re, &s->gb) & 0x40000000)

                level = -level;

            block[0]  = level;

            mismatch ^= level;

            i++;

            SKIP_BITS(re, &s->gb, 2);

            if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

                goto end;

        }

        /* now quantify & encode AC coefficients */

        for (;;) {

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

            if (level != 0) {

                i += run;

                j = scantable[i];

                level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

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

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

            } else {

                /* escape */

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

                UPDATE_CACHE(re, &s->gb);

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

                i += run;

                j = scantable[i];

                if (level < 0) {

                    level = ((-level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

                    level = -level;

                } else {

                    level = ((level * 2 + 1) * qscale * quant_matrix[j]) >> 5;

                }

            }

            if (i > 63) {

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

                return -1;

            }

            mismatch ^= level;

            block[j]  = level;

            if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

                break;

            UPDATE_CACHE(re, &s->gb);

        }

end:

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

        CLOSE_READER(re, &s->gb);

    }

    block[63] ^= (mismatch & 1);

    s->block_last_index[n] = i;

    return 0;

}


static void channel_out_run(struct fs_dma_ctrl *ctrl, int c)

{

	uint32_t len;

	uint32_t saved_data_buf;

	unsigned char buf[2 * 1024];

	if (ctrl->channels[c].eol == 1)

		return;

	saved_data_buf = channel_reg(ctrl, c, RW_SAVED_DATA_BUF);

	D(fprintf(logfile, "ch=%d buf=%x after=%x saved_data_buf=%x\n",

		 c,

		 (uint32_t)ctrl->channels[c].current_d.buf,

		 (uint32_t)ctrl->channels[c].current_d.after,

		 saved_data_buf));

	len = (uint32_t)(unsigned long) ctrl->channels[c].current_d.after;

	len -= saved_data_buf;

	if (len > sizeof buf)

		len = sizeof buf;

	cpu_physical_memory_read (saved_data_buf, buf, len);

	D(printf("channel %d pushes %x %u bytes\n", c,

		 saved_data_buf, len));

	if (ctrl->channels[c].client->client.push)

		ctrl->channels[c].client->client.push(

			ctrl->channels[c].client->client.opaque, buf, len);

	else

		printf("WARNING: DMA ch%d dataloss, no attached client.\n", c);

	saved_data_buf += len;

	if (saved_data_buf ==

	    (uint32_t)(unsigned long)ctrl->channels[c].current_d.after) {

		/* Done. Step to next.  */

		if (ctrl->channels[c].current_d.out_eop) {

			/* TODO: signal eop to the client.  */

			D(printf("signal eop\n"));

		}

		if (ctrl->channels[c].current_d.intr) {

			/* TODO: signal eop to the client.  */

			/* data intr.  */

			D(printf("signal intr\n"));

			ctrl->channels[c].regs[R_INTR] |= (1 << 2);

			channel_update_irq(ctrl, c);

		}

		if (ctrl->channels[c].current_d.eol) {

			D(printf("channel %d EOL\n", c));

			ctrl->channels[c].eol = 1;

			/* Mark the context as disabled.  */

			ctrl->channels[c].current_c.dis = 1;

			channel_store_c(ctrl, c);

			channel_stop(ctrl, c);

		} else {

			ctrl->channels[c].regs[RW_SAVED_DATA] =

				(uint32_t)(unsigned long) ctrl->channels[c].current_d.next;

			/* Load new descriptor.  */

			channel_load_d(ctrl, c);

			saved_data_buf = (uint32_t)(unsigned long)

				ctrl->channels[c].current_d.buf;

		}

		channel_store_d(ctrl, c);

		ctrl->channels[c].regs[RW_SAVED_DATA_BUF] = saved_data_buf;

		D(dump_d(c, &ctrl->channels[c].current_d));

	}

	ctrl->channels[c].regs[RW_SAVED_DATA_BUF] = saved_data_buf;

}


static int dvbsub_parse_region_segment(AVCodecContext *avctx,
                                       const uint8_t *buf, int buf_size)
{
    DVBSubContext *ctx = avctx->priv_data;
    const uint8_t *buf_end = buf + buf_size;
    int region_id, object_id;
    int av_unused version;
    DVBSubRegion *region;
    DVBSubObject *object;
    DVBSubObjectDisplay *display;
    int fill;
    int ret;
    if (buf_size < 10)
        return AVERROR_INVALIDDATA;
    region_id = *buf++;
    region = get_region(ctx, region_id);
    if (!region) {
        region = av_mallocz(sizeof(DVBSubRegion));
        if (!region)
            return AVERROR(ENOMEM);
        region->id = region_id;
        region->version = -1;
        region->next = ctx->region_list;
        ctx->region_list = region;
    version = ((*buf)>>4) & 15;
    fill = ((*buf++) >> 3) & 1;
    region->width = AV_RB16(buf);
    buf += 2;
    region->height = AV_RB16(buf);
    buf += 2;
    if (region->width * region->height != region->buf_size) {
        av_free(region->pbuf);
        region->buf_size = region->width * region->height;
        region->pbuf = av_malloc(region->buf_size);
        if (!region->pbuf) {
            region->buf_size =
            region->width =
            region->height = 0;
            return AVERROR(ENOMEM);
        fill = 1;
        region->dirty = 0;
    region->depth = 1 << (((*buf++) >> 2) & 7);
    if(region->depth<2 || region->depth>8){
        av_log(avctx, AV_LOG_ERROR, "region depth %d is invalid\n", region->depth);
        region->depth= 4;
    region->clut = *buf++;
    if (region->depth == 8) {
        region->bgcolor = *buf++;
        buf += 1;
    } else {
        buf += 1;
        if (region->depth == 4)
            region->bgcolor = (((*buf++) >> 4) & 15);
        else
            region->bgcolor = (((*buf++) >> 2) & 3);
    ff_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height);
    if (fill) {
        memset(region->pbuf, region->bgcolor, region->buf_size);
        ff_dlog(avctx, "Fill region (%d)\n", region->bgcolor);
    delete_region_display_list(ctx, region);
    while (buf + 5 < buf_end) {
        object_id = AV_RB16(buf);
        buf += 2;
        object = get_object(ctx, object_id);
        if (!object) {
            object = av_mallocz(sizeof(DVBSubObject));
            if (!object)
                return AVERROR(ENOMEM);
            object->id = object_id;
            object->next = ctx->object_list;
            ctx->object_list = object;
        object->type = (*buf) >> 6;
        display = av_mallocz(sizeof(DVBSubObjectDisplay));
        if (!display)
            return AVERROR(ENOMEM);
        display->object_id = object_id;
        display->region_id = region_id;
        display->x_pos = AV_RB16(buf) & 0xfff;
        buf += 2;
        display->y_pos = AV_RB16(buf) & 0xfff;
        buf += 2;
        if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) {
            display->fgcolor = *buf++;
            display->bgcolor = *buf++;
        display->region_list_next = region->display_list;
        region->display_list = display;
        display->object_list_next = object->display_list;
        object->display_list = display;
    return 0;