static void numa_add(const char *optarg)

{

    char option[128];

    char *endptr;

    unsigned long long value, endvalue;

    int nodenr;

    optarg = get_opt_name(option, 128, optarg, ',') + 1;

    if (!strcmp(option, "node")) {

        if (get_param_value(option, 128, "nodeid", optarg) == 0) {

            nodenr = nb_numa_nodes;

        } else {

            nodenr = strtoull(option, NULL, 10);

        }

        if (get_param_value(option, 128, "mem", optarg) == 0) {

            node_mem[nodenr] = 0;

        } else {

            int64_t sval;

            sval = strtosz(option, &endptr);

            if (sval < 0 || *endptr) {

                fprintf(stderr, "qemu: invalid numa mem size: %s\n", optarg);

                exit(1);

            }

            node_mem[nodenr] = sval;

        }

        if (get_param_value(option, 128, "cpus", optarg) == 0) {

            node_cpumask[nodenr] = 0;

        } else {

            value = strtoull(option, &endptr, 10);

            if (value >= 64) {

                value = 63;

                fprintf(stderr, "only 64 CPUs in NUMA mode supported.\n");

            } else {

                if (*endptr == '-') {

                    endvalue = strtoull(endptr+1, &endptr, 10);

                    if (endvalue >= 63) {

                        endvalue = 62;

                        fprintf(stderr,

                            "only 63 CPUs in NUMA mode supported.\n");

                    }

                    value = (2ULL << endvalue) - (1ULL << value);

                } else {

                    value = 1ULL << value;

                }

            }

            node_cpumask[nodenr] = value;

        }

        nb_numa_nodes++;

    }

    return;

}


static uint32_t rtas_set_dr_indicator(uint32_t idx, uint32_t state)

{

    sPAPRDRConnector *drc = spapr_drc_by_index(idx);

    if (!drc) {

        return RTAS_OUT_PARAM_ERROR;

    }

    trace_spapr_drc_set_dr_indicator(idx, state);

    drc->dr_indicator = state;

    return RTAS_OUT_SUCCESS;

}


static void unplug_disks(PCIBus *b, PCIDevice *d, void *o)

{

    /* We have to ignore passthrough devices */

    if (!strcmp(d->name, "xen-pci-passthrough")) {

        return;

    }

    switch (pci_get_word(d->config + PCI_CLASS_DEVICE)) {

    case PCI_CLASS_STORAGE_IDE:

        pci_piix3_xen_ide_unplug(DEVICE(d));

        break;

    case PCI_CLASS_STORAGE_SCSI:

    case PCI_CLASS_STORAGE_EXPRESS:

        object_unparent(OBJECT(d));

        break;

    default:

        break;

    }

}


static void monitor_start_input(void)

{

    readline_start("(qemu) ", 0, monitor_handle_command1, NULL);

}


MKSCALE16(scale16be, AV_RB16, AV_WB16)

MKSCALE16(scale16le, AV_RL16, AV_WL16)

static int raw_decode(AVCodecContext *avctx, void *data, int *got_frame,

                      AVPacket *avpkt)

{

    const AVPixFmtDescriptor *desc;

    RawVideoContext *context       = avctx->priv_data;

    const uint8_t *buf             = avpkt->data;

    int buf_size                   = avpkt->size;

    int linesize_align             = 4;

    int stride;

    int res, len;

    int need_copy;

    AVFrame   *frame   = data;

    if (avctx->width <= 0) {

        av_log(avctx, AV_LOG_ERROR, "width is not set\n");

        return AVERROR_INVALIDDATA;

    }

    if (avctx->height <= 0) {

        av_log(avctx, AV_LOG_ERROR, "height is not set\n");

        return AVERROR_INVALIDDATA;

    }

    if (context->is_nut_mono)

        stride = avctx->width / 8 + (avctx->width & 7 ? 1 : 0);

    else if (context->is_nut_pal8)

        stride = avctx->width;

    else

        stride = avpkt->size / avctx->height;

    av_log(avctx, AV_LOG_DEBUG, "PACKET SIZE: %d, STRIDE: %d\n", avpkt->size, stride);

    if (stride == 0 || avpkt->size < stride * avctx->height) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small (%d)\n", avpkt->size);

        return AVERROR_INVALIDDATA;

    }

    desc = av_pix_fmt_desc_get(avctx->pix_fmt);

    if ((avctx->bits_per_coded_sample == 8 || avctx->bits_per_coded_sample == 4 ||

         avctx->bits_per_coded_sample == 2 || avctx->bits_per_coded_sample == 1 ||

         (avctx->bits_per_coded_sample == 0 && (context->is_nut_pal8 || context->is_mono)) ) &&

        (context->is_mono || context->is_pal8) &&

        (!avctx->codec_tag || avctx->codec_tag == MKTAG('r','a','w',' ') ||

                context->is_nut_mono || context->is_nut_pal8)) {

        context->is_1_2_4_8_bpp = 1;

        if (context->is_mono) {

            int row_bytes = avctx->width / 8 + (avctx->width & 7 ? 1 : 0);

            context->frame_size = av_image_get_buffer_size(avctx->pix_fmt,

                                                           FFALIGN(row_bytes, 16) * 8,

                                                           avctx->height, 1);

        } else

            context->frame_size = av_image_get_buffer_size(avctx->pix_fmt,

                                                           FFALIGN(avctx->width, 16),

                                                           avctx->height, 1);

    } else {

        context->is_lt_16bpp = av_get_bits_per_pixel(desc) == 16 && avctx->bits_per_coded_sample && avctx->bits_per_coded_sample < 16;

        context->frame_size = av_image_get_buffer_size(avctx->pix_fmt, avctx->width,

                                                       avctx->height, 1);

    }

    if (context->frame_size < 0)

        return context->frame_size;

    need_copy = !avpkt->buf || context->is_1_2_4_8_bpp || context->is_yuv2 || context->is_lt_16bpp;

    frame->pict_type        = AV_PICTURE_TYPE_I;

    frame->key_frame        = 1;

    res = ff_decode_frame_props(avctx, frame);

    if (res < 0)

        return res;

    av_frame_set_pkt_pos     (frame, avctx->internal->pkt->pos);

    av_frame_set_pkt_duration(frame, avctx->internal->pkt->duration);

    if (context->tff >= 0) {

        frame->interlaced_frame = 1;

        frame->top_field_first  = context->tff;

    }

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

        return res;

    if (need_copy)

        frame->buf[0] = av_buffer_alloc(FFMAX(context->frame_size, buf_size));

    else

        frame->buf[0] = av_buffer_ref(avpkt->buf);

    if (!frame->buf[0])

        return AVERROR(ENOMEM);

    // 1, 2, 4 and 8 bpp in avi/mov, 1 and 8 bpp in nut

    if (context->is_1_2_4_8_bpp) {

        int i, j, row_pix = 0;

        uint8_t *dst = frame->buf[0]->data;

        buf_size = context->frame_size - (context->is_pal8 ? AVPALETTE_SIZE : 0);

        if (avctx->bits_per_coded_sample == 8 || context->is_nut_pal8 || context->is_mono) {

            int pix_per_byte = context->is_mono ? 8 : 1;

            for (i = 0, j = 0; j < buf_size && i<avpkt->size; i++, j++) {

                dst[j] = buf[i];

                row_pix += pix_per_byte;

                if (row_pix >= avctx->width) {

                    i += stride - (i % stride) - 1;

                    j += 16 - (j % 16) - 1;

                    row_pix = 0;

                }

            }

        } else if (avctx->bits_per_coded_sample == 4) {

            for (i = 0, j = 0; 2 * j + 1 < buf_size && i<avpkt->size; i++, j++) {

                dst[2 * j + 0] = buf[i] >> 4;

                dst[2 * j + 1] = buf[i] & 15;

                row_pix += 2;

                if (row_pix >= avctx->width) {

                    i += stride - (i % stride) - 1;

                    j += 8 - (j % 8) - 1;

                    row_pix = 0;

                }

            }

        } else if (avctx->bits_per_coded_sample == 2) {

            for (i = 0, j = 0; 4 * j + 3 < buf_size && i<avpkt->size; i++, j++) {

                dst[4 * j + 0] = buf[i] >> 6;

                dst[4 * j + 1] = buf[i] >> 4 & 3;

                dst[4 * j + 2] = buf[i] >> 2 & 3;

                dst[4 * j + 3] = buf[i]      & 3;

                row_pix += 4;

                if (row_pix >= avctx->width) {

                    i += stride - (i % stride) - 1;

                    j += 4 - (j % 4) - 1;

                    row_pix = 0;

                }

            }

        } else {

            av_assert0(avctx->bits_per_coded_sample == 1);

            for (i = 0, j = 0; 8 * j + 7 < buf_size && i<avpkt->size; i++, j++) {

                dst[8 * j + 0] = buf[i] >> 7;

                dst[8 * j + 1] = buf[i] >> 6 & 1;

                dst[8 * j + 2] = buf[i] >> 5 & 1;

                dst[8 * j + 3] = buf[i] >> 4 & 1;

                dst[8 * j + 4] = buf[i] >> 3 & 1;

                dst[8 * j + 5] = buf[i] >> 2 & 1;

                dst[8 * j + 6] = buf[i] >> 1 & 1;

                dst[8 * j + 7] = buf[i]      & 1;

                row_pix += 8;

                if (row_pix >= avctx->width) {

                    i += stride - (i % stride) - 1;

                    j += 2 - (j % 2) - 1;

                    row_pix = 0;

                }

            }

        }

        linesize_align = 16;

        buf = dst;

    } else if (context->is_lt_16bpp) {

        uint8_t *dst = frame->buf[0]->data;

        int packed = (avctx->codec_tag & 0xFFFFFF) == MKTAG('B','I','T', 0);

        int swap   =  avctx->codec_tag >> 24;

        if (packed && swap) {

            av_fast_padded_malloc(&context->bitstream_buf, &context->bitstream_buf_size, buf_size);

            if (!context->bitstream_buf)

                return AVERROR(ENOMEM);

            if (swap == 16)

                context->bbdsp.bswap16_buf(context->bitstream_buf, (const uint16_t*)buf, buf_size / 2);

            else if (swap == 32)

                context->bbdsp.bswap_buf(context->bitstream_buf, (const uint32_t*)buf, buf_size / 4);

            else

                return AVERROR_INVALIDDATA;

            buf = context->bitstream_buf;

        }

        if (desc->flags & AV_PIX_FMT_FLAG_BE)

            scale16be(avctx, dst, buf, buf_size, packed);

        else

            scale16le(avctx, dst, buf, buf_size, packed);

        buf = dst;

    } else if (need_copy) {

        memcpy(frame->buf[0]->data, buf, buf_size);

        buf = frame->buf[0]->data;

    }

    if (avctx->codec_tag == MKTAG('A', 'V', '1', 'x') ||

        avctx->codec_tag == MKTAG('A', 'V', 'u', 'p'))

        buf += buf_size - context->frame_size;

    len = context->frame_size - (avctx->pix_fmt==AV_PIX_FMT_PAL8 ? AVPALETTE_SIZE : 0);

    if (buf_size < len && ((avctx->codec_tag & 0xFFFFFF) != MKTAG('B','I','T', 0) || !need_copy)) {

        av_log(avctx, AV_LOG_ERROR, "Invalid buffer size, packet size %d < expected frame_size %d\n", buf_size, len);

        av_buffer_unref(&frame->buf[0]);

        return AVERROR(EINVAL);

    }

    if ((res = av_image_fill_arrays(frame->data, frame->linesize,

                                    buf, avctx->pix_fmt,

                                    avctx->width, avctx->height, 1)) < 0) {

        av_buffer_unref(&frame->buf[0]);

        return res;

    }

    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {

        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE,

                                                     NULL);

        int ret;

        if (!context->palette)

            context->palette = av_buffer_alloc(AVPALETTE_SIZE);

        if (!context->palette) {

            av_buffer_unref(&frame->buf[0]);

            return AVERROR(ENOMEM);

        }

        ret = av_buffer_make_writable(&context->palette);

        if (ret < 0) {

            av_buffer_unref(&frame->buf[0]);

            return ret;

        }

        if (pal) {

            memcpy(context->palette->data, pal, AVPALETTE_SIZE);

            frame->palette_has_changed = 1;

        } else if (context->is_nut_pal8) {

            int vid_size = avctx->width * avctx->height;

            int pal_size = avpkt->size - vid_size;

            if (avpkt->size > vid_size && pal_size <= AVPALETTE_SIZE) {

                pal = avpkt->data + vid_size;

                memcpy(context->palette->data, pal, pal_size);

                frame->palette_has_changed = 1;

            }

        }

    }

    if ((avctx->pix_fmt==AV_PIX_FMT_RGB24    ||

        avctx->pix_fmt==AV_PIX_FMT_BGR24     ||

        avctx->pix_fmt==AV_PIX_FMT_GRAY8     ||

        avctx->pix_fmt==AV_PIX_FMT_RGB555LE  ||

        avctx->pix_fmt==AV_PIX_FMT_RGB555BE  ||

        avctx->pix_fmt==AV_PIX_FMT_RGB565LE  ||

        avctx->pix_fmt==AV_PIX_FMT_MONOWHITE ||

        avctx->pix_fmt==AV_PIX_FMT_MONOBLACK ||

        avctx->pix_fmt==AV_PIX_FMT_PAL8) &&

        FFALIGN(frame->linesize[0], linesize_align) * avctx->height <= buf_size)

        frame->linesize[0] = FFALIGN(frame->linesize[0], linesize_align);

    if (avctx->pix_fmt == AV_PIX_FMT_NV12 && avctx->codec_tag == MKTAG('N', 'V', '1', '2') &&

        FFALIGN(frame->linesize[0], linesize_align) * avctx->height +

        FFALIGN(frame->linesize[1], linesize_align) * ((avctx->height + 1) / 2) <= buf_size) {

        int la0 = FFALIGN(frame->linesize[0], linesize_align);

        frame->data[1] += (la0 - frame->linesize[0]) * avctx->height;

        frame->linesize[0] = la0;

        frame->linesize[1] = FFALIGN(frame->linesize[1], linesize_align);

    }

    if ((avctx->pix_fmt == AV_PIX_FMT_PAL8 && buf_size < context->frame_size) ||

        (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)) {

        frame->buf[1]  = av_buffer_ref(context->palette);

        if (!frame->buf[1]) {

            av_buffer_unref(&frame->buf[0]);

            return AVERROR(ENOMEM);

        }

        frame->data[1] = frame->buf[1]->data;

    }

    if (avctx->pix_fmt == AV_PIX_FMT_BGR24 &&

        ((frame->linesize[0] + 3) & ~3) * avctx->height <= buf_size)

        frame->linesize[0] = (frame->linesize[0] + 3) & ~3;

    if (context->flip)

        flip(avctx, frame);

    if (avctx->codec_tag == MKTAG('Y', 'V', '1', '2') ||

        avctx->codec_tag == MKTAG('Y', 'V', '1', '6') ||

        avctx->codec_tag == MKTAG('Y', 'V', '2', '4') ||

        avctx->codec_tag == MKTAG('Y', 'V', 'U', '9'))

        FFSWAP(uint8_t *, frame->data[1], frame->data[2]);

    if (avctx->codec_tag == AV_RL32("I420") && (avctx->width+1)*(avctx->height+1) * 3/2 == buf_size) {

        frame->data[1] = frame->data[1] +  (avctx->width+1)*(avctx->height+1) -avctx->width*avctx->height;

        frame->data[2] = frame->data[2] + ((avctx->width+1)*(avctx->height+1) -avctx->width*avctx->height)*5/4;

    }

    if (avctx->codec_tag == AV_RL32("yuv2") &&

        avctx->pix_fmt   == AV_PIX_FMT_YUYV422) {

        int x, y;

        uint8_t *line = frame->data[0];

        for (y = 0; y < avctx->height; y++) {

            for (x = 0; x < avctx->width; x++)

                line[2 * x + 1] ^= 0x80;

            line += frame->linesize[0];

        }

    }

    if (avctx->codec_tag == AV_RL32("b64a") &&

        avctx->pix_fmt   == AV_PIX_FMT_RGBA64BE) {

        uint8_t *dst = frame->data[0];

        uint64_t v;

        int x;

        for (x = 0; x >> 3 < avctx->width * avctx->height; x += 8) {

            v = AV_RB64(&dst[x]);

            AV_WB64(&dst[x], v << 16 | v >> 48);

        }

    }

    if (avctx->field_order > AV_FIELD_PROGRESSIVE) { /* we have interlaced material flagged in container */

        frame->interlaced_frame = 1;

        if (avctx->field_order == AV_FIELD_TT || avctx->field_order == AV_FIELD_TB)

            frame->top_field_first = 1;

    }

    *got_frame = 1;

    return buf_size;

}


static void opt_qmin(const char *arg)

{

    video_qmin = atoi(arg);

    if (video_qmin < 0 ||

        video_qmin > 31) {

        fprintf(stderr, "qmin must be >= 1 and <= 31\n");

        exit(1);

    }

}


void migrate_decompress_threads_join(void)

{

    int i, thread_count;

    quit_decomp_thread = true;

    thread_count = migrate_decompress_threads();

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

        qemu_mutex_lock(&decomp_param[i].mutex);

        qemu_cond_signal(&decomp_param[i].cond);

        qemu_mutex_unlock(&decomp_param[i].mutex);

    }

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

        qemu_thread_join(decompress_threads + i);

        qemu_mutex_destroy(&decomp_param[i].mutex);

        qemu_cond_destroy(&decomp_param[i].cond);

        g_free(decomp_param[i].compbuf);

    }

    g_free(decompress_threads);

    g_free(decomp_param);

    decompress_threads = NULL;

    decomp_param = NULL;

}


ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    if (drv && drv->bdrv_get_specific_info) {

        return drv->bdrv_get_specific_info(bs);

    }

    return NULL;

}


do_gen_eob_worker(DisasContext *s, bool inhibit, bool recheck_tf, TCGv jr)

{

    gen_update_cc_op(s);

    /* If several instructions disable interrupts, only the first does it.  */

    if (inhibit && !(s->flags & HF_INHIBIT_IRQ_MASK)) {

        gen_set_hflag(s, HF_INHIBIT_IRQ_MASK);

    } else {

        gen_reset_hflag(s, HF_INHIBIT_IRQ_MASK);

    }

    if (s->tb->flags & HF_RF_MASK) {

        gen_helper_reset_rf(cpu_env);

    }

    if (s->singlestep_enabled) {

        gen_helper_debug(cpu_env);

    } else if (recheck_tf) {

        gen_helper_rechecking_single_step(cpu_env);

        tcg_gen_exit_tb(0);

    } else if (s->tf) {

        gen_helper_single_step(cpu_env);

    } else if (!TCGV_IS_UNUSED(jr)) {

        TCGv vaddr = tcg_temp_new();

        tcg_gen_add_tl(vaddr, jr, cpu_seg_base[R_CS]);

        tcg_gen_lookup_and_goto_ptr(vaddr);

        tcg_temp_free(vaddr);

    } else {

        tcg_gen_exit_tb(0);

    }

    s->is_jmp = DISAS_TB_JUMP;

}


SocketAddressLegacy *socket_local_address(int fd, Error **errp)

{

    struct sockaddr_storage ss;

    socklen_t sslen = sizeof(ss);

    if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {

        error_setg_errno(errp, errno, "%s",

                         "Unable to query local socket address");

        return NULL;

    }

    return socket_sockaddr_to_address(&ss, sslen, errp);

}


static void machine_numa_finish_init(MachineState *machine)

{

    int i;

    bool default_mapping;

    GString *s = g_string_new(NULL);

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    const CPUArchIdList *possible_cpus = mc->possible_cpu_arch_ids(machine);

    assert(nb_numa_nodes);

    for (i = 0; i < possible_cpus->len; i++) {

        if (possible_cpus->cpus[i].props.has_node_id) {

            break;

        }

    }

    default_mapping = (i == possible_cpus->len);

    for (i = 0; i < possible_cpus->len; i++) {

        const CPUArchId *cpu_slot = &possible_cpus->cpus[i];

        if (!cpu_slot->props.has_node_id) {

            if (default_mapping) {

                /* fetch default mapping from board and enable it */

                CpuInstanceProperties props = cpu_slot->props;

                props.has_node_id = true;

                machine_set_cpu_numa_node(machine, &props, &error_fatal);

            } else {

                /* record slots with not set mapping,

                 * TODO: make it hard error in future */

                char *cpu_str = cpu_slot_to_string(cpu_slot);

                g_string_append_printf(s, "%sCPU %d [%s]",

                                       s->len ? ", " : "", i, cpu_str);

                g_free(cpu_str);

            }

        }

    }

    if (s->len && !qtest_enabled()) {

        error_report("warning: CPU(s) not present in any NUMA nodes: %s",

                     s->str);

        error_report("warning: All CPU(s) up to maxcpus should be described "

                     "in NUMA config, ability to start up with partial NUMA "

                     "mappings is obsoleted and will be removed in future");

    }

    g_string_free(s, true);

}


void qmp_block_dirty_bitmap_clear(const char *node, const char *name,

                                  Error **errp)

{

    AioContext *aio_context;

    BdrvDirtyBitmap *bitmap;

    BlockDriverState *bs;

    bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);

    if (!bitmap || !bs) {

        return;

    }

    if (bdrv_dirty_bitmap_frozen(bitmap)) {

        error_setg(errp,

                   "Bitmap '%s' is currently frozen and cannot be modified",

                   name);

        goto out;

    } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {

        error_setg(errp,

                   "Bitmap '%s' is currently disabled and cannot be cleared",

                   name);

        goto out;

    }

    bdrv_clear_dirty_bitmap(bitmap, NULL);

 out:

    aio_context_release(aio_context);

}


FWCfgState *fw_cfg_init(uint32_t ctl_port, uint32_t data_port,

                        target_phys_addr_t ctl_addr, target_phys_addr_t data_addr)

{

    DeviceState *dev;

    SysBusDevice *d;

    FWCfgState *s;

    dev = qdev_create(NULL, "fw_cfg");

    qdev_prop_set_uint32(dev, "ctl_iobase", ctl_port);

    qdev_prop_set_uint32(dev, "data_iobase", data_port);

    qdev_init_nofail(dev);

    d = sysbus_from_qdev(dev);

    s = DO_UPCAST(FWCfgState, busdev.qdev, dev);

    if (ctl_addr) {

        sysbus_mmio_map(d, 0, ctl_addr);

    }

    if (data_addr) {

        sysbus_mmio_map(d, 1, data_addr);

    }

    fw_cfg_add_bytes(s, FW_CFG_SIGNATURE, (uint8_t *)"QEMU", 4);

    fw_cfg_add_bytes(s, FW_CFG_UUID, qemu_uuid, 16);

    fw_cfg_add_i16(s, FW_CFG_NOGRAPHIC, (uint16_t)(display_type == DT_NOGRAPHIC));

    fw_cfg_add_i16(s, FW_CFG_NB_CPUS, (uint16_t)smp_cpus);

    fw_cfg_add_i16(s, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i16(s, FW_CFG_BOOT_MENU, (uint16_t)boot_menu);

    fw_cfg_bootsplash(s);

    fw_cfg_reboot(s);

    s->machine_ready.notify = fw_cfg_machine_ready;

    qemu_add_machine_init_done_notifier(&s->machine_ready);

    return s;

}


static void boston_flash_write(void *opaque, hwaddr addr,

                               uint64_t val, unsigned size)

{

}


static void revert_cdlms(WmallDecodeCtx *s, int ch,

                         int coef_begin, int coef_end)

{

    int icoef, pred, ilms, num_lms, residue, input;

    num_lms = s->cdlms_ttl[ch];

    for (ilms = num_lms - 1; ilms >= 0; ilms--) {

        for (icoef = coef_begin; icoef < coef_end; icoef++) {

            pred = 1 << (s->cdlms[ch][ilms].scaling - 1);

            residue = s->channel_residues[ch][icoef];

            pred += s->dsp.scalarproduct_and_madd_int16(s->cdlms[ch][ilms].coefs,

                                                        s->cdlms[ch][ilms].lms_prevvalues

                                                            + s->cdlms[ch][ilms].recent,

                                                        s->cdlms[ch][ilms].lms_updates

                                                            + s->cdlms[ch][ilms].recent,

                                                        s->cdlms[ch][ilms].order,

                                                        WMASIGN(residue));

            input = residue + (pred >> s->cdlms[ch][ilms].scaling);

            lms_update(s, ch, ilms, input);

            s->channel_residues[ch][icoef] = input;

        }

    }

}


static void utf8_string(void)

{

    /*

     * FIXME Current behavior for invalid UTF-8 sequences is

     * incorrect.  This test expects current, incorrect results.

     * They're all marked "bug:" below, and are to be replaced by

     * correct ones as the bugs get fixed.

     *

     * The JSON parser rejects some invalid sequences, but accepts

     * others without correcting the problem.

     *

     * We should either reject all invalid sequences, or minimize

     * overlong sequences and replace all other invalid sequences by a

     * suitable replacement character.  A common choice for

     * replacement is U+FFFD.

     *

     * Problem: we can't easily deal with embedded U+0000.  Parsing

     * the JSON string "this \\u0000" is fun" yields "this \0 is fun",

     * which gets misinterpreted as NUL-terminated "this ".  We should

     * consider using overlong encoding \xC0\x80 for U+0000 ("modified

     * UTF-8").

     *

     * Most test cases are scraped from Markus Kuhn's UTF-8 decoder

     * capability and stress test at

     * http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt

     */

    static const struct {

        const char *json_in;

        const char *utf8_out;

        const char *json_out;   /* defaults to @json_in */

        const char *utf8_in;    /* defaults to @utf8_out */

    } test_cases[] = {

        /*

         * Bug markers used here:

         * - bug: not corrected

         *   JSON parser fails to correct invalid sequence(s)

         * - bug: rejected

         *   JSON parser rejects invalid sequence(s)

         *   We may choose to define this as feature

         * - bug: want "..."

         *   JSON parser produces incorrect result, this is the

         *   correct one, assuming replacement character U+FFFF

         *   We may choose to reject instead of replace

         */

        /* 1  Some correct UTF-8 text */

        {

            /* a bit of German */

            "\"Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt"

            " jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg.\"",

            "Falsches \xC3\x9C" "ben von Xylophonmusik qu\xC3\xA4lt"

            " jeden gr\xC3\xB6\xC3\x9F" "eren Zwerg.",

            "\"Falsches \\u00DCben von Xylophonmusik qu\\u00E4lt"

            " jeden gr\\u00F6\\u00DFeren Zwerg.\"",

        },

        {

            /* a bit of Greek */

            "\"\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5\"",

            "\xCE\xBA\xE1\xBD\xB9\xCF\x83\xCE\xBC\xCE\xB5",

            "\"\\u03BA\\u1F79\\u03C3\\u03BC\\u03B5\"",

        },

        /* 2  Boundary condition test cases */

        /* 2.1  First possible sequence of a certain length */

        /* 2.1.1  1 byte U+0000 */

        {

            "\"\\u0000\"",

            "",                 /* bug: want overlong "\xC0\x80" */

            "\"\\u0000\"",

            "\xC0\x80",

        },

        /* 2.1.2  2 bytes U+0080 */

        {

            "\"\xC2\x80\"",

            "\xC2\x80",

            "\"\\u0080\"",

        },

        /* 2.1.3  3 bytes U+0800 */

        {

            "\"\xE0\xA0\x80\"",

            "\xE0\xA0\x80",

            "\"\\u0800\"",

        },

        /* 2.1.4  4 bytes U+10000 */

        {

            "\"\xF0\x90\x80\x80\"",

            "\xF0\x90\x80\x80",

            "\"\\uD800\\uDC00\"",

        },

        /* 2.1.5  5 bytes U+200000 */

        {

            "\"\xF8\x88\x80\x80\x80\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF8\x88\x80\x80\x80",

        },

        /* 2.1.6  6 bytes U+4000000 */

        {

            "\"\xFC\x84\x80\x80\x80\x80\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFC\x84\x80\x80\x80\x80",

        },

        /* 2.2  Last possible sequence of a certain length */

        /* 2.2.1  1 byte U+007F */

        {

            "\"\x7F\"",

            "\x7F",

            "\"\\u007F\"",

        },

        /* 2.2.2  2 bytes U+07FF */

        {

            "\"\xDF\xBF\"",

            "\xDF\xBF",

            "\"\\u07FF\"",

        },

        /*

         * 2.2.3  3 bytes U+FFFC

         * The last possible sequence is actually U+FFFF.  But that's

         * a noncharacter, and already covered by its own test case

         * under 5.3.  Same for U+FFFE.  U+FFFD is the last character

         * in the BMP, and covered under 2.3.  Because of U+FFFD's

         * special role as replacement character, it's worth testing

         * U+FFFC here.

         */

        {

            "\"\xEF\xBF\xBC\"",

            "\xEF\xBF\xBC",

            "\"\\uFFFC\"",

        },

        /* 2.2.4  4 bytes U+1FFFFF */

        {

            "\"\xF7\xBF\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF7\xBF\xBF\xBF",

        },

        /* 2.2.5  5 bytes U+3FFFFFF */

        {

            "\"\xFB\xBF\xBF\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFB\xBF\xBF\xBF\xBF",

        },

        /* 2.2.6  6 bytes U+7FFFFFFF */

        {

            "\"\xFD\xBF\xBF\xBF\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFD\xBF\xBF\xBF\xBF\xBF",

        },

        /* 2.3  Other boundary conditions */

        {

            /* last one before surrogate range: U+D7FF */

            "\"\xED\x9F\xBF\"",

            "\xED\x9F\xBF",

            "\"\\uD7FF\"",

        },

        {

            /* first one after surrogate range: U+E000 */

            "\"\xEE\x80\x80\"",

            "\xEE\x80\x80",

            "\"\\uE000\"",

        },

        {

            /* last one in BMP: U+FFFD */

            "\"\xEF\xBF\xBD\"",

            "\xEF\xBF\xBD",

            "\"\\uFFFD\"",

        },

        {

            /* last one in last plane: U+10FFFD */

            "\"\xF4\x8F\xBF\xBD\"",

            "\xF4\x8F\xBF\xBD",

            "\"\\uDBFF\\uDFFD\""

        },

        {

            /* first one beyond Unicode range: U+110000 */

            "\"\xF4\x90\x80\x80\"",

            "\xF4\x90\x80\x80",

            "\"\\uFFFD\"",

        },

        /* 3  Malformed sequences */

        /* 3.1  Unexpected continuation bytes */

        /* 3.1.1  First continuation byte */

        {

            "\"\x80\"",

            "\x80",             /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.1.2  Last continuation byte */

        {

            "\"\xBF\"",

            "\xBF",             /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.1.3  2 continuation bytes */

        {

            "\"\x80\xBF\"",

            "\x80\xBF",         /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        /* 3.1.4  3 continuation bytes */

        {

            "\"\x80\xBF\x80\"",

            "\x80\xBF\x80",     /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\\uFFFD\"",

        },

        /* 3.1.5  4 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\"",

            "\x80\xBF\x80\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

        },

        /* 3.1.6  5 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\"",

            "\x80\xBF\x80\xBF\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

        },

        /* 3.1.7  6 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\xBF\"",

            "\x80\xBF\x80\xBF\x80\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

        },

        /* 3.1.8  7 continuation bytes */

        {

            "\"\x80\xBF\x80\xBF\x80\xBF\x80\"",

            "\x80\xBF\x80\xBF\x80\xBF\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

        },

        /* 3.1.9  Sequence of all 64 possible continuation bytes */

        {

            "\"\x80\x81\x82\x83\x84\x85\x86\x87"

            "\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"

            "\x90\x91\x92\x93\x94\x95\x96\x97"

            "\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"

            "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7"

            "\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"

            "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7"

            "\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\"",

             /* bug: not corrected */

            "\x80\x81\x82\x83\x84\x85\x86\x87"

            "\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F"

            "\x90\x91\x92\x93\x94\x95\x96\x97"

            "\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F"

            "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7"

            "\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF"

            "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7"

            "\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF",

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\""

        },

        /* 3.2  Lonely start characters */

        /* 3.2.1  All 32 first bytes of 2-byte sequences, followed by space */

        {

            "\"\xC0 \xC1 \xC2 \xC3 \xC4 \xC5 \xC6 \xC7 "

            "\xC8 \xC9 \xCA \xCB \xCC \xCD \xCE \xCF "

            "\xD0 \xD1 \xD2 \xD3 \xD4 \xD5 \xD6 \xD7 "

            "\xD8 \xD9 \xDA \xDB \xDC \xDD \xDE \xDF \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD "

            "\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD "

            "\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD "

            "\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \"",

            "\xC0 \xC1 \xC2 \xC3 \xC4 \xC5 \xC6 \xC7 "

            "\xC8 \xC9 \xCA \xCB \xCC \xCD \xCE \xCF "

            "\xD0 \xD1 \xD2 \xD3 \xD4 \xD5 \xD6 \xD7 "

            "\xD8 \xD9 \xDA \xDB \xDC \xDD \xDE \xDF ",

        },

        /* 3.2.2  All 16 first bytes of 3-byte sequences, followed by space */

        {

            "\"\xE0 \xE1 \xE2 \xE3 \xE4 \xE5 \xE6 \xE7 "

            "\xE8 \xE9 \xEA \xEB \xEC \xED \xEE \xEF \"",

            /* bug: not corrected */

            "\xE0 \xE1 \xE2 \xE3 \xE4 \xE5 \xE6 \xE7 "

            "\xE8 \xE9 \xEA \xEB \xEC \xED \xEE \xEF ",

            "\"\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD "

            "\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \"",

        },

        /* 3.2.3  All 8 first bytes of 4-byte sequences, followed by space */

        {

            "\"\xF0 \xF1 \xF2 \xF3 \xF4 \xF5 \xF6 \xF7 \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \\uFFFD \"",

            "\xF0 \xF1 \xF2 \xF3 \xF4 \xF5 \xF6 \xF7 ",

        },

        /* 3.2.4  All 4 first bytes of 5-byte sequences, followed by space */

        {

            "\"\xF8 \xF9 \xFA \xFB \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD \\uFFFD \\uFFFD \\uFFFD \"",

            "\xF8 \xF9 \xFA \xFB ",

        },

        /* 3.2.5  All 2 first bytes of 6-byte sequences, followed by space */

        {

            "\"\xFC \xFD \"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD \\uFFFD \"",

            "\xFC \xFD ",

        },

        /* 3.3  Sequences with last continuation byte missing */

        /* 3.3.1  2-byte sequence with last byte missing (U+0000) */

        {

            "\"\xC0\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xC0",

        },

        /* 3.3.2  3-byte sequence with last byte missing (U+0000) */

        {

            "\"\xE0\x80\"",

            "\xE0\x80",           /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.3.3  4-byte sequence with last byte missing (U+0000) */

        {

            "\"\xF0\x80\x80\"",

            "\xF0\x80\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.3.4  5-byte sequence with last byte missing (U+0000) */

        {

            "\"\xF8\x80\x80\x80\"",

            NULL,                   /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF8\x80\x80\x80",

        },

        /* 3.3.5  6-byte sequence with last byte missing (U+0000) */

        {

            "\"\xFC\x80\x80\x80\x80\"",

            NULL,                        /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFC\x80\x80\x80\x80",

        },

        /* 3.3.6  2-byte sequence with last byte missing (U+07FF) */

        {

            "\"\xDF\"",

            "\xDF",             /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.3.7  3-byte sequence with last byte missing (U+FFFF) */

        {

            "\"\xEF\xBF\"",

            "\xEF\xBF",           /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 3.3.8  4-byte sequence with last byte missing (U+1FFFFF) */

        {

            "\"\xF7\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF7\xBF\xBF",

        },

        /* 3.3.9  5-byte sequence with last byte missing (U+3FFFFFF) */

        {

            "\"\xFB\xBF\xBF\xBF\"",

            NULL,                 /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFB\xBF\xBF\xBF",

        },

        /* 3.3.10  6-byte sequence with last byte missing (U+7FFFFFFF) */

        {

            "\"\xFD\xBF\xBF\xBF\xBF\"",

            NULL,                        /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFD\xBF\xBF\xBF\xBF",

        },

        /* 3.4  Concatenation of incomplete sequences */

        {

            "\"\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80"

            "\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

            "\xC0\xE0\x80\xF0\x80\x80\xF8\x80\x80\x80\xFC\x80\x80\x80\x80"

            "\xDF\xEF\xBF\xF7\xBF\xBF\xFB\xBF\xBF\xBF\xFD\xBF\xBF\xBF\xBF",

        },

        /* 3.5  Impossible bytes */

        {

            "\"\xFE\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFE",

        },

        {

            "\"\xFF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFF",

        },

        {

            "\"\xFE\xFE\xFF\xFF\"",

            NULL,                 /* bug: rejected */

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

            "\xFE\xFE\xFF\xFF",

        },

        /* 4  Overlong sequences */

        /* 4.1  Overlong '/' */

        {

            "\"\xC0\xAF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xC0\xAF",

        },

        {

            "\"\xE0\x80\xAF\"",

            "\xE0\x80\xAF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            "\"\xF0\x80\x80\xAF\"",

            "\xF0\x80\x80\xAF",  /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            "\"\xF8\x80\x80\x80\xAF\"",

            NULL,                        /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF8\x80\x80\x80\xAF",

        },

        {

            "\"\xFC\x80\x80\x80\x80\xAF\"",

            NULL,                               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFC\x80\x80\x80\x80\xAF",

        },

        /*

         * 4.2  Maximum overlong sequences

         * Highest Unicode value that is still resulting in an

         * overlong sequence if represented with the given number of

         * bytes.  This is a boundary test for safe UTF-8 decoders.

         */

        {

            /* \U+007F */

            "\"\xC1\xBF\"",

            NULL,               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xC1\xBF",

        },

        {

            /* \U+07FF */

            "\"\xE0\x9F\xBF\"",

            "\xE0\x9F\xBF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /*

             * \U+FFFC

             * The actual maximum would be U+FFFF, but that's a

             * noncharacter.  Testing U+FFFC seems more useful.  See

             * also 2.2.3

             */

            "\"\xF0\x8F\xBF\xBC\"",

            "\xF0\x8F\xBF\xBC",   /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+1FFFFF */

            "\"\xF8\x87\xBF\xBF\xBF\"",

            NULL,                        /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF8\x87\xBF\xBF\xBF",

        },

        {

            /* \U+3FFFFFF */

            "\"\xFC\x83\xBF\xBF\xBF\xBF\"",

            NULL,                               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFC\x83\xBF\xBF\xBF\xBF",

        },

        /* 4.3  Overlong representation of the NUL character */

        {

            /* \U+0000 */

            "\"\xC0\x80\"",

            NULL,               /* bug: rejected */

            "\"\\u0000\"",

            "\xC0\x80",

        },

        {

            /* \U+0000 */

            "\"\xE0\x80\x80\"",

            "\xE0\x80\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+0000 */

            "\"\xF0\x80\x80\x80\"",

            "\xF0\x80\x80\x80",   /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+0000 */

            "\"\xF8\x80\x80\x80\x80\"",

            NULL,                        /* bug: rejected */

            "\"\\uFFFD\"",

            "\xF8\x80\x80\x80\x80",

        },

        {

            /* \U+0000 */

            "\"\xFC\x80\x80\x80\x80\x80\"",

            NULL,                               /* bug: rejected */

            "\"\\uFFFD\"",

            "\xFC\x80\x80\x80\x80\x80",

        },

        /* 5  Illegal code positions */

        /* 5.1  Single UTF-16 surrogates */

        {

            /* \U+D800 */

            "\"\xED\xA0\x80\"",

            "\xED\xA0\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DB7F */

            "\"\xED\xAD\xBF\"",

            "\xED\xAD\xBF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DB80 */

            "\"\xED\xAE\x80\"",

            "\xED\xAE\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DBFF */

            "\"\xED\xAF\xBF\"",

            "\xED\xAF\xBF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DC00 */

            "\"\xED\xB0\x80\"",

            "\xED\xB0\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DF80 */

            "\"\xED\xBE\x80\"",

            "\xED\xBE\x80",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+DFFF */

            "\"\xED\xBF\xBF\"",

            "\xED\xBF\xBF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* 5.2  Paired UTF-16 surrogates */

        {

            /* \U+D800\U+DC00 */

            "\"\xED\xA0\x80\xED\xB0\x80\"",

            "\xED\xA0\x80\xED\xB0\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+D800\U+DFFF */

            "\"\xED\xA0\x80\xED\xBF\xBF\"",

            "\xED\xA0\x80\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DB7F\U+DC00 */

            "\"\xED\xAD\xBF\xED\xB0\x80\"",

            "\xED\xAD\xBF\xED\xB0\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DB7F\U+DFFF */

            "\"\xED\xAD\xBF\xED\xBF\xBF\"",

            "\xED\xAD\xBF\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DB80\U+DC00 */

            "\"\xED\xAE\x80\xED\xB0\x80\"",

            "\xED\xAE\x80\xED\xB0\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DB80\U+DFFF */

            "\"\xED\xAE\x80\xED\xBF\xBF\"",

            "\xED\xAE\x80\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DBFF\U+DC00 */

            "\"\xED\xAF\xBF\xED\xB0\x80\"",

            "\xED\xAF\xBF\xED\xB0\x80", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        {

            /* \U+DBFF\U+DFFF */

            "\"\xED\xAF\xBF\xED\xBF\xBF\"",

            "\xED\xAF\xBF\xED\xBF\xBF", /* bug: not corrected */

            "\"\\uFFFD\\uFFFD\"",

        },

        /* 5.3  Other illegal code positions */

        /* BMP noncharacters */

        {

            /* \U+FFFE */

            "\"\xEF\xBF\xBE\"",

            "\xEF\xBF\xBE",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* \U+FFFF */

            "\"\xEF\xBF\xBF\"",

            "\xEF\xBF\xBF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* U+FDD0 */

            "\"\xEF\xB7\x90\"",

            "\xEF\xB7\x90",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        {

            /* U+FDEF */

            "\"\xEF\xB7\xAF\"",

            "\xEF\xB7\xAF",     /* bug: not corrected */

            "\"\\uFFFD\"",

        },

        /* Plane 1 .. 16 noncharacters */

        {

            /* U+1FFFE U+1FFFF U+2FFFE U+2FFFF ... U+10FFFE U+10FFFF */

            "\"\xF0\x9F\xBF\xBE\xF0\x9F\xBF\xBF"

            "\xF0\xAF\xBF\xBE\xF0\xAF\xBF\xBF"

            "\xF0\xBF\xBF\xBE\xF0\xBF\xBF\xBF"

            "\xF1\x8F\xBF\xBE\xF1\x8F\xBF\xBF"

            "\xF1\x9F\xBF\xBE\xF1\x9F\xBF\xBF"

            "\xF1\xAF\xBF\xBE\xF1\xAF\xBF\xBF"

            "\xF1\xBF\xBF\xBE\xF1\xBF\xBF\xBF"

            "\xF2\x8F\xBF\xBE\xF2\x8F\xBF\xBF"

            "\xF2\x9F\xBF\xBE\xF2\x9F\xBF\xBF"

            "\xF2\xAF\xBF\xBE\xF2\xAF\xBF\xBF"

            "\xF2\xBF\xBF\xBE\xF2\xBF\xBF\xBF"

            "\xF3\x8F\xBF\xBE\xF3\x8F\xBF\xBF"

            "\xF3\x9F\xBF\xBE\xF3\x9F\xBF\xBF"

            "\xF3\xAF\xBF\xBE\xF3\xAF\xBF\xBF"

            "\xF3\xBF\xBF\xBE\xF3\xBF\xBF\xBF"

            "\xF4\x8F\xBF\xBE\xF4\x8F\xBF\xBF\"",

            /* bug: not corrected */

            "\xF0\x9F\xBF\xBE\xF0\x9F\xBF\xBF"

            "\xF0\xAF\xBF\xBE\xF0\xAF\xBF\xBF"

            "\xF0\xBF\xBF\xBE\xF0\xBF\xBF\xBF"

            "\xF1\x8F\xBF\xBE\xF1\x8F\xBF\xBF"

            "\xF1\x9F\xBF\xBE\xF1\x9F\xBF\xBF"

            "\xF1\xAF\xBF\xBE\xF1\xAF\xBF\xBF"

            "\xF1\xBF\xBF\xBE\xF1\xBF\xBF\xBF"

            "\xF2\x8F\xBF\xBE\xF2\x8F\xBF\xBF"

            "\xF2\x9F\xBF\xBE\xF2\x9F\xBF\xBF"

            "\xF2\xAF\xBF\xBE\xF2\xAF\xBF\xBF"

            "\xF2\xBF\xBF\xBE\xF2\xBF\xBF\xBF"

            "\xF3\x8F\xBF\xBE\xF3\x8F\xBF\xBF"

            "\xF3\x9F\xBF\xBE\xF3\x9F\xBF\xBF"

            "\xF3\xAF\xBF\xBE\xF3\xAF\xBF\xBF"

            "\xF3\xBF\xBF\xBE\xF3\xBF\xBF\xBF"

            "\xF4\x8F\xBF\xBE\xF4\x8F\xBF\xBF",

            "\"\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD"

            "\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\\uFFFD\"",

        },

        {}

    };

    int i;

    QObject *obj;

    QString *str;

    const char *json_in, *utf8_out, *utf8_in, *json_out;

    for (i = 0; test_cases[i].json_in; i++) {

        json_in = test_cases[i].json_in;

        utf8_out = test_cases[i].utf8_out;

        utf8_in = test_cases[i].utf8_in ?: test_cases[i].utf8_out;

        json_out = test_cases[i].json_out ?: test_cases[i].json_in;

        obj = qobject_from_json(json_in, NULL);

        if (utf8_out) {

            str = qobject_to_qstring(obj);

            g_assert(str);

            g_assert_cmpstr(qstring_get_str(str), ==, utf8_out);

        } else {

            g_assert(!obj);

        }

        qobject_decref(obj);

        obj = QOBJECT(qstring_from_str(utf8_in));

        str = qobject_to_json(obj);

        if (json_out) {

            g_assert(str);

            g_assert_cmpstr(qstring_get_str(str), ==, json_out);

        } else {

            g_assert(!str);

        }

        QDECREF(str);

        qobject_decref(obj);

        /*

         * Disabled, because qobject_from_json() is buggy, and I can't

         * be bothered to add the expected incorrect results.

         * FIXME Enable once these bugs have been fixed.

         */

        if (0 && json_out != json_in) {

            obj = qobject_from_json(json_out, NULL);

            str = qobject_to_qstring(obj);

            g_assert(str);

            g_assert_cmpstr(qstring_get_str(str), ==, utf8_out);

        }

    }

}


static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts, int64_t *pkt_dts)

{

    AVFrame *decoded_frame, *filtered_frame = NULL;

    void *buffer_to_free = NULL;

    int i, ret = 0;

    float quality = 0;

#if CONFIG_AVFILTER

    int frame_available = 1;

#endif

    int duration=0;

    int64_t *best_effort_timestamp;

    AVRational *frame_sample_aspect;

    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))

        return AVERROR(ENOMEM);

    else

        avcodec_get_frame_defaults(ist->decoded_frame);

    decoded_frame = ist->decoded_frame;

    pkt->pts  = *pkt_pts;

    pkt->dts  = *pkt_dts;

    *pkt_pts  = AV_NOPTS_VALUE;

    if (pkt->duration) {

        duration = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);

    } else if(ist->st->codec->time_base.num != 0) {

        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

        duration = ((int64_t)AV_TIME_BASE *

                          ist->st->codec->time_base.num * ticks) /

                          ist->st->codec->time_base.den;

    }

    if(*pkt_dts != AV_NOPTS_VALUE && duration) {

        *pkt_dts += duration;

    }else

        *pkt_dts = AV_NOPTS_VALUE;

    ret = avcodec_decode_video2(ist->st->codec,

                                decoded_frame, got_output, pkt);

    if (ret < 0)

        return ret;

    quality = same_quant ? decoded_frame->quality : 0;

    if (!*got_output) {

        /* no picture yet */

        return ret;

    }

    best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");

    if(*best_effort_timestamp != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = *best_effort_timestamp;

    ist->next_pts += duration;

    pkt->size = 0;

    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

#if CONFIG_AVFILTER

    frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");

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

        OutputStream *ost = ost = &output_streams[i];

        if(check_output_constraints(ist, ost)){

            if (!frame_sample_aspect->num)

                *frame_sample_aspect = ist->st->sample_aspect_ratio;

            decoded_frame->pts = ist->pts;

            av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);

        }

    }

#endif

    rate_emu_sleep(ist);

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

        OutputStream *ost = &output_streams[i];

        int frame_size;

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

#if CONFIG_AVFILTER

        if (ost->input_video_filter) {

            frame_available = av_buffersink_poll_frame(ost->output_video_filter);

        }

        while (frame_available) {

            if (ost->output_video_filter) {

                AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;

                if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0){

                    av_log(0, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");

                    goto cont;

                }

                if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {

                    av_free(buffer_to_free);

                    return AVERROR(ENOMEM);

                } else

                    avcodec_get_frame_defaults(ist->filtered_frame);

                filtered_frame = ist->filtered_frame;

                *filtered_frame= *decoded_frame; //for me_threshold

                if (ost->picref) {

                    avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);

                    ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

                }

            }

            if (ost->picref->video && !ost->frame_aspect_ratio)

                ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;

#else

            filtered_frame = decoded_frame;

#endif

            do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,

                         same_quant ? quality : ost->st->codec->global_quality);

            if (vstats_filename && frame_size)

                do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);

#if CONFIG_AVFILTER

            cont:

            frame_available = ost->output_video_filter && av_buffersink_poll_frame(ost->output_video_filter);

            avfilter_unref_buffer(ost->picref);

        }

#endif

    }

    av_free(buffer_to_free);

    return ret;

}


SubchDev *css_create_sch(CssDevId bus_id, bool is_virtual, bool squash_mcss,

                         Error **errp)

{

    uint16_t schid = 0;

    SubchDev *sch;

    if (bus_id.valid) {

        if (is_virtual != (bus_id.cssid == VIRTUAL_CSSID)) {

            error_setg(errp, "cssid %hhx not valid for %s devices",

                       bus_id.cssid,

                       (is_virtual ? "virtual" : "non-virtual"));

            return NULL;

        }

    }

    if (bus_id.valid) {

        if (squash_mcss) {

            bus_id.cssid = channel_subsys.default_cssid;

        } else if (!channel_subsys.css[bus_id.cssid]) {

            css_create_css_image(bus_id.cssid, false);

        }

        if (!css_find_free_subch_for_devno(bus_id.cssid, bus_id.ssid,

                                           bus_id.devid, &schid, errp)) {

            return NULL;

        }

    } else if (squash_mcss || is_virtual) {

        bus_id.cssid = channel_subsys.default_cssid;

        if (!css_find_free_subch_and_devno(bus_id.cssid, &bus_id.ssid,

                                           &bus_id.devid, &schid, errp)) {

            return NULL;

        }

    } else {

        for (bus_id.cssid = 0; bus_id.cssid < MAX_CSSID; ++bus_id.cssid) {

            if (bus_id.cssid == VIRTUAL_CSSID) {

                continue;

            }

            if (!channel_subsys.css[bus_id.cssid]) {

                css_create_css_image(bus_id.cssid, false);

            }

            if   (css_find_free_subch_and_devno(bus_id.cssid, &bus_id.ssid,

                                                &bus_id.devid, &schid,

                                                NULL)) {

                break;

            }

            if (bus_id.cssid == MAX_CSSID) {

                error_setg(errp, "Virtual channel subsystem is full!");

                return NULL;

            }

        }

    }

    sch = g_new0(SubchDev, 1);

    sch->cssid = bus_id.cssid;

    sch->ssid = bus_id.ssid;

    sch->devno = bus_id.devid;

    sch->schid = schid;

    css_subch_assign(sch->cssid, sch->ssid, schid, sch->devno, sch);

    return sch;

}


static int vdi_create(const char *filename, QemuOpts *opts, Error **errp)

{

    int ret = 0;

    uint64_t bytes = 0;

    uint32_t blocks;

    size_t block_size = DEFAULT_CLUSTER_SIZE;

    uint32_t image_type = VDI_TYPE_DYNAMIC;

    VdiHeader header;

    size_t i;

    size_t bmap_size;

    int64_t offset = 0;

    Error *local_err = NULL;

    BlockDriverState *bs = NULL;

    uint32_t *bmap = NULL;

    logout("\n");

    /* Read out options. */

    bytes = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);

#if defined(CONFIG_VDI_BLOCK_SIZE)

    /* TODO: Additional checks (SECTOR_SIZE * 2^n, ...). */

    block_size = qemu_opt_get_size_del(opts,

                                       BLOCK_OPT_CLUSTER_SIZE,

                                       DEFAULT_CLUSTER_SIZE);

#endif

#if defined(CONFIG_VDI_STATIC_IMAGE)

    if (qemu_opt_get_bool_del(opts, BLOCK_OPT_STATIC, false)) {

        image_type = VDI_TYPE_STATIC;

    }

#endif

    if (bytes > VDI_DISK_SIZE_MAX) {

        ret = -ENOTSUP;

        error_setg(errp, "Unsupported VDI image size (size is 0x%" PRIx64

                          ", max supported is 0x%" PRIx64 ")",

                          bytes, VDI_DISK_SIZE_MAX);

        goto exit;

    }

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

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,

                    NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    /* We need enough blocks to store the given disk size,

       so always round up. */

    blocks = (bytes + block_size - 1) / block_size;

    bmap_size = blocks * sizeof(uint32_t);

    bmap_size = ((bmap_size + SECTOR_SIZE - 1) & ~(SECTOR_SIZE -1));

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

    pstrcpy(header.text, sizeof(header.text), VDI_TEXT);

    header.signature = VDI_SIGNATURE;

    header.version = VDI_VERSION_1_1;

    header.header_size = 0x180;

    header.image_type = image_type;

    header.offset_bmap = 0x200;

    header.offset_data = 0x200 + bmap_size;

    header.sector_size = SECTOR_SIZE;

    header.disk_size = bytes;

    header.block_size = block_size;

    header.blocks_in_image = blocks;

    if (image_type == VDI_TYPE_STATIC) {

        header.blocks_allocated = blocks;

    }

    uuid_generate(header.uuid_image);

    uuid_generate(header.uuid_last_snap);

    /* There is no need to set header.uuid_link or header.uuid_parent here. */

#if defined(CONFIG_VDI_DEBUG)

    vdi_header_print(&header);

#endif

    vdi_header_to_le(&header);

    ret = bdrv_pwrite_sync(bs, offset, &header, sizeof(header));

    if (ret < 0) {

        error_setg(errp, "Error writing header to %s", filename);

        goto exit;

    }

    offset += sizeof(header);

    if (bmap_size > 0) {

        bmap = g_malloc0(bmap_size);

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

            if (image_type == VDI_TYPE_STATIC) {

                bmap[i] = i;

            } else {

                bmap[i] = VDI_UNALLOCATED;

            }

        }

        ret = bdrv_pwrite_sync(bs, offset, bmap, bmap_size);

        if (ret < 0) {

            error_setg(errp, "Error writing bmap to %s", filename);

            goto exit;

        }

        offset += bmap_size;

    }

    if (image_type == VDI_TYPE_STATIC) {

        ret = bdrv_truncate(bs, offset + blocks * block_size);

        if (ret < 0) {

            error_setg(errp, "Failed to statically allocate %s", filename);

            goto exit;

        }

    }

exit:

    bdrv_unref(bs);

    g_free(bmap);

    return ret;

}


static int brpix_decode_frame(AVCodecContext *avctx,
                              void *data, int *got_frame,
                              AVPacket *avpkt)
{
    BRPixContext *s = avctx->priv_data;
    AVFrame *frame_out = data;
    int ret;
    GetByteContext gb;
    unsigned int bytes_pp;
    unsigned int magic[4];
    unsigned int chunk_type;
    unsigned int data_len;
    BRPixHeader hdr;
    bytestream2_init(&gb, avpkt->data, avpkt->size);
    magic[0] = bytestream2_get_be32(&gb);
    magic[1] = bytestream2_get_be32(&gb);
    magic[2] = bytestream2_get_be32(&gb);
    magic[3] = bytestream2_get_be32(&gb);
    if (magic[0] != 0x12 ||
        magic[1] != 0x8 ||
        magic[2] != 0x2 ||
        magic[3] != 0x2) {
        av_log(avctx, AV_LOG_ERROR, "Not a BRender PIX file\n");
        return AVERROR_INVALIDDATA;
    chunk_type = bytestream2_get_be32(&gb);
    if (chunk_type != 0x3 && chunk_type != 0x3d) {
        av_log(avctx, AV_LOG_ERROR, "Invalid chunk type %d\n", chunk_type);
        return AVERROR_INVALIDDATA;
    ret = brpix_decode_header(&hdr, &gb);
    if (!ret) {
        av_log(avctx, AV_LOG_ERROR, "Invalid header length\n");
        return AVERROR_INVALIDDATA;
    switch (hdr.format) {
    case 3:
        avctx->pix_fmt = AV_PIX_FMT_PAL8;
        bytes_pp = 1;
        break;
    case 4:
        avctx->pix_fmt = AV_PIX_FMT_RGB555BE;
        bytes_pp = 2;
        break;
    case 5:
        avctx->pix_fmt = AV_PIX_FMT_RGB565BE;
        bytes_pp = 2;
        break;
    case 6:
        avctx->pix_fmt = AV_PIX_FMT_RGB24;
        bytes_pp = 3;
        break;
    case 7:
        avctx->pix_fmt = AV_PIX_FMT_0RGB;
        bytes_pp = 4;
        break;
    case 18:
        avctx->pix_fmt = AV_PIX_FMT_GRAY8A;
        bytes_pp = 2;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "Format %d is not supported\n",
                                    hdr.format);
        return AVERROR_PATCHWELCOME;
    if (s->frame.data[0])
        avctx->release_buffer(avctx, &s->frame);
    if (av_image_check_size(hdr.width, hdr.height, 0, avctx) < 0)
        return AVERROR_INVALIDDATA;
    if (hdr.width != avctx->width || hdr.height != avctx->height)
        avcodec_set_dimensions(avctx, hdr.width, hdr.height);
    if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    chunk_type = bytestream2_get_be32(&gb);
    if (avctx->pix_fmt == AV_PIX_FMT_PAL8 &&
        (chunk_type == 0x3 || chunk_type == 0x3d)) {
        BRPixHeader palhdr;
        ret = brpix_decode_header(&palhdr, &gb);
        if (!ret) {
            av_log(avctx, AV_LOG_ERROR, "Invalid palette header length\n");
            return AVERROR_INVALIDDATA;
        if (palhdr.format != 7) {
            av_log(avctx, AV_LOG_ERROR, "Palette is not in 0RGB format\n");
            return AVERROR_INVALIDDATA;
        chunk_type = bytestream2_get_be32(&gb);
        data_len = bytestream2_get_be32(&gb);
        bytestream2_skip(&gb, 8);
        if (chunk_type != 0x21 || data_len != 1032 ||
            bytestream2_get_bytes_left(&gb) < 1032) {
            av_log(avctx, AV_LOG_ERROR, "Invalid palette data\n");
            return AVERROR_INVALIDDATA;
        // convert 0RGB to machine endian format (ARGB32)
            bytestream2_skipu(&gb, 1);
            *pal_out++ = (0xFFU << 24) | bytestream2_get_be24u(&gb);
        bytestream2_skip(&gb, 8);
        chunk_type = bytestream2_get_be32(&gb);
    data_len = bytestream2_get_be32(&gb);
    bytestream2_skip(&gb, 8);
    // read the image data to the buffer
    {
        unsigned int bytes_per_scanline = bytes_pp * hdr.width;
        unsigned int bytes_left = bytestream2_get_bytes_left(&gb);
        if (chunk_type != 0x21 || data_len != bytes_left ||
            bytes_left / bytes_per_scanline < hdr.height)
        {
            av_log(avctx, AV_LOG_ERROR, "Invalid image data\n");
            return AVERROR_INVALIDDATA;
        av_image_copy_plane(s->frame.data[0], s->frame.linesize[0],
                            avpkt->data + bytestream2_tell(&gb),
                            bytes_per_scanline,
                            bytes_per_scanline, hdr.height);
    *frame_out = s->frame;
    *got_frame = 1;
    return avpkt->size;


static int mov_read_dref(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = st->priv_data;

    int entries, i, j;

    get_be32(pb); // version + flags

    entries = get_be32(pb);

    if (entries >= UINT_MAX / sizeof(*sc->drefs))

        return -1;

    sc->drefs_count = entries;

    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));

    for (i = 0; i < sc->drefs_count; i++) {

        MOV_dref_t *dref = &sc->drefs[i];

        uint32_t size = get_be32(pb);

        offset_t next = url_ftell(pb) + size - 4;

        dref->type = get_le32(pb);

        get_be32(pb); // version + flags

        dprintf(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);

        if (dref->type == MKTAG('a','l','i','s') && size > 150) {

            /* macintosh alias record */

            uint16_t volume_len, len;

            char volume[28];

            int16_t type;

            url_fskip(pb, 10);

            volume_len = get_byte(pb);

            volume_len = FFMIN(volume_len, 27);

            get_buffer(pb, volume, 27);

            volume[volume_len] = 0;

            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", volume, volume_len);

            url_fskip(pb, 112);

            for (type = 0; type != -1 && url_ftell(pb) < next; ) {

                type = get_be16(pb);

                len = get_be16(pb);

                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);

                if (len&1)

                    len += 1;

                if (type == 2) { // absolute path

                    dref->path = av_mallocz(len+1);

                    get_buffer(pb, dref->path, len);

                    if (!strncmp(dref->path, volume, volume_len)) {

                        len -= volume_len;

                        memmove(dref->path, dref->path+volume_len, len);

                        dref->path[len] = 0;

                    }

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

                        if (dref->path[j] == ':')

                            dref->path[j] = '/';

                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);

                } else

                    url_fskip(pb, len);

            }

        }

        url_fseek(pb, next, SEEK_SET);

    }

    return 0;

}


int usb_handle_packet(USBDevice *dev, USBPacket *p)

{

    int ret;

    if (dev == NULL) {

        return USB_RET_NODEV;

    }

    assert(dev->addr == p->devaddr);

    assert(dev->state == USB_STATE_DEFAULT);

    assert(p->owner == NULL);

    if (p->devep == 0) {

        /* control pipe */

        switch (p->pid) {

        case USB_TOKEN_SETUP:

            ret = do_token_setup(dev, p);

            break;

        case USB_TOKEN_IN:

            ret = do_token_in(dev, p);

            break;

        case USB_TOKEN_OUT:

            ret = do_token_out(dev, p);

            break;

        default:

            ret = USB_RET_STALL;

            break;

        }

    } else {

        /* data pipe */

        ret = usb_device_handle_data(dev, p);

    }

    if (ret == USB_RET_ASYNC) {

        p->owner = usb_ep_get(dev, p->pid, p->devep);

    }

    return ret;

}


static void old_pc_system_rom_init(MemoryRegion *rom_memory, bool isapc_ram_fw)

{

    char *filename;

    MemoryRegion *bios, *isa_bios;

    int bios_size, isa_bios_size;

    int ret;

    /* BIOS load */

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = get_image_size(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size <= 0 ||

        (bios_size % 65536) != 0) {

        goto bios_error;

    }

    bios = g_malloc(sizeof(*bios));

    memory_region_init_ram(bios, NULL, "pc.bios", bios_size, &error_abort);

    vmstate_register_ram_global(bios);

    if (!isapc_ram_fw) {

        memory_region_set_readonly(bios, true);

    }

    ret = rom_add_file_fixed(bios_name, (uint32_t)(-bios_size), -1);

    if (ret != 0) {

    bios_error:

        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);

        exit(1);

    }

    g_free(filename);

    /* map the last 128KB of the BIOS in ISA space */

    isa_bios_size = bios_size;

    if (isa_bios_size > (128 * 1024)) {

        isa_bios_size = 128 * 1024;

    }

    isa_bios = g_malloc(sizeof(*isa_bios));

    memory_region_init_alias(isa_bios, NULL, "isa-bios", bios,

                             bios_size - isa_bios_size, isa_bios_size);

    memory_region_add_subregion_overlap(rom_memory,

                                        0x100000 - isa_bios_size,

                                        isa_bios,

                                        1);

    if (!isapc_ram_fw) {

        memory_region_set_readonly(isa_bios, true);

    }

    /* map all the bios at the top of memory */

    memory_region_add_subregion(rom_memory,

                                (uint32_t)(-bios_size),

                                bios);

}


static int kvm_handle_debug(PowerPCCPU *cpu, struct kvm_run *run)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    struct kvm_debug_exit_arch *arch_info = &run->debug.arch;

    int handle = 0;

    if (kvm_find_sw_breakpoint(cs, arch_info->address)) {

        handle = 1;

    } else {

        /* QEMU is not able to handle debug exception, so inject

         * program exception to guest;

         * Yes program exception NOT debug exception !!

         * For software breakpoint QEMU uses a privileged instruction;

         * So there cannot be any reason that we are here for guest

         * set debug exception, only possibility is guest executed a

         * privileged / illegal instruction and that's why we are

         * injecting a program interrupt.

         */

        cpu_synchronize_state(cs);

        /* env->nip is PC, so increment this by 4 to use

         * ppc_cpu_do_interrupt(), which set srr0 = env->nip - 4.

         */

        env->nip += 4;

        cs->exception_index = POWERPC_EXCP_PROGRAM;

        env->error_code = POWERPC_EXCP_INVAL;

        ppc_cpu_do_interrupt(cs);

    }

    return handle;

}


void helper_ldda_asi(target_ulong addr, int asi, int rd)

{

    if ((asi < 0x80 && (env->pstate & PS_PRIV) == 0)

        || ((env->def->features & CPU_FEATURE_HYPV)

            && asi >= 0x30 && asi < 0x80

            && !(env->hpstate & HS_PRIV)))

        raise_exception(TT_PRIV_ACT);

    switch (asi) {

    case 0x24: // Nucleus quad LDD 128 bit atomic

    case 0x2c: // Nucleus quad LDD 128 bit atomic LE

        helper_check_align(addr, 0xf);

        if (rd == 0) {

            env->gregs[1] = ldq_kernel(addr + 8);

            if (asi == 0x2c)

                bswap64s(&env->gregs[1]);

        } else if (rd < 8) {

            env->gregs[rd] = ldq_kernel(addr);

            env->gregs[rd + 1] = ldq_kernel(addr + 8);

            if (asi == 0x2c) {

                bswap64s(&env->gregs[rd]);

                bswap64s(&env->gregs[rd + 1]);

            }

        } else {

            env->regwptr[rd] = ldq_kernel(addr);

            env->regwptr[rd + 1] = ldq_kernel(addr + 8);

            if (asi == 0x2c) {

                bswap64s(&env->regwptr[rd]);

                bswap64s(&env->regwptr[rd + 1]);

            }

        }

        break;

    default:

        helper_check_align(addr, 0x3);

        if (rd == 0)

            env->gregs[1] = helper_ld_asi(addr + 4, asi, 4, 0);

        else if (rd < 8) {

            env->gregs[rd] = helper_ld_asi(addr, asi, 4, 0);

            env->gregs[rd + 1] = helper_ld_asi(addr + 4, asi, 4, 0);

        } else {

            env->regwptr[rd] = helper_ld_asi(addr, asi, 4, 0);

            env->regwptr[rd + 1] = helper_ld_asi(addr + 4, asi, 4, 0);

        }

        break;

    }

}


static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    VBDecContext * const c = avctx->priv_data;

    uint8_t *outptr, *srcptr;

    int i, j;

    int flags;

    uint32_t size;

    int rest = buf_size;

    int offset = 0;

    if(c->pic.data[0])

        avctx->release_buffer(avctx, &c->pic);

    c->pic.reference = 3;

    if(avctx->get_buffer(avctx, &c->pic) < 0){

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

        return -1;

    }

    c->stream = buf;

    flags = bytestream_get_le16(&c->stream);

    rest -= 2;

    if(flags & VB_HAS_GMC){

        i = (int16_t)bytestream_get_le16(&c->stream);

        j = (int16_t)bytestream_get_le16(&c->stream);

        offset = i + j * avctx->width;

        rest -= 4;

    }

    if(flags & VB_HAS_VIDEO){

        size = bytestream_get_le32(&c->stream);

        if(size > rest){

            av_log(avctx, AV_LOG_ERROR, "Frame size is too big\n");

            return -1;

        }

        vb_decode_framedata(c, c->stream, size, offset);

        c->stream += size - 4;

        rest -= size;

    }

    if(flags & VB_HAS_PALETTE){

        size = bytestream_get_le32(&c->stream);

        if(size > rest){

            av_log(avctx, AV_LOG_ERROR, "Palette size is too big\n");

            return -1;

        }

        vb_decode_palette(c, size);

        rest -= size;

    }

    memcpy(c->pic.data[1], c->pal, AVPALETTE_SIZE);

    c->pic.palette_has_changed = flags & VB_HAS_PALETTE;

    outptr = c->pic.data[0];

    srcptr = c->frame;

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

        memcpy(outptr, srcptr, avctx->width);

        srcptr += avctx->width;

        outptr += c->pic.linesize[0];

    }

    FFSWAP(uint8_t*, c->frame, c->prev_frame);

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = c->pic;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


static inline void RENAME(bgr32ToY)(uint8_t *dst, uint8_t *src, int width)

{

	int i;

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

	{

		int b=  ((uint32_t*)src)[i]&0xFF;

		int g= (((uint32_t*)src)[i]>>8)&0xFF;

		int r= (((uint32_t*)src)[i]>>16)&0xFF;

		dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)) )>>RGB2YUV_SHIFT);

	}

}


static void gen_read_xer(TCGv dst)

{

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    TCGv t2 = tcg_temp_new();

    tcg_gen_mov_tl(dst, cpu_xer);

    tcg_gen_shli_tl(t0, cpu_so, XER_SO);

    tcg_gen_shli_tl(t1, cpu_ov, XER_OV);

    tcg_gen_shli_tl(t2, cpu_ca, XER_CA);

    tcg_gen_or_tl(t0, t0, t1);

    tcg_gen_or_tl(dst, dst, t2);

    tcg_gen_or_tl(dst, dst, t0);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

    tcg_temp_free(t2);

}


Object *object_dynamic_cast(Object *obj, const char *typename)

{

    if (object_class_dynamic_cast(object_get_class(obj), typename)) {

        return obj;

    }

    return NULL;

}


static void h264_h_loop_filter_chroma_intra_c(uint8_t *pix, int stride, int alpha, int beta)

{

    h264_loop_filter_chroma_intra_c(pix, 1, stride, alpha, beta);

}


static int svq1_encode_frame(AVCodecContext *avctx, unsigned char *buf,

    int buf_size, void *data)

{

    SVQ1Context * const s = avctx->priv_data;

    AVFrame *pict = data;

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

    AVFrame temp;

    int i;

    if(avctx->pix_fmt != PIX_FMT_YUV410P){

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

        return -1;

    }

    if(!s->current_picture.data[0]){

        avctx->get_buffer(avctx, &s->current_picture);

        avctx->get_buffer(avctx, &s->last_picture);

        s->scratchbuf = av_malloc(s->current_picture.linesize[0] * 16);

    }

    temp= s->current_picture;

    s->current_picture= s->last_picture;

    s->last_picture= temp;

    init_put_bits(&s->pb, buf, buf_size);

    *p = *pict;

    p->pict_type = avctx->gop_size && avctx->frame_number % avctx->gop_size ? FF_P_TYPE : FF_I_TYPE;

    p->key_frame = p->pict_type == FF_I_TYPE;

    svq1_write_header(s, p->pict_type);

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

        if(svq1_encode_plane(s, i,

            s->picture.data[i], s->last_picture.data[i], s->current_picture.data[i],

            s->frame_width / (i?4:1), s->frame_height / (i?4:1),

            s->picture.linesize[i], s->current_picture.linesize[i]) < 0)

                return -1;

    }

//    align_put_bits(&s->pb);

    while(put_bits_count(&s->pb) & 31)

        put_bits(&s->pb, 1, 0);

    flush_put_bits(&s->pb);

    return put_bits_count(&s->pb) / 8;

}


static void xics_common_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->reset = xics_common_reset;

}


static BlockJob *test_block_job_start(unsigned int iterations,

                                      bool use_timer,

                                      int rc, int *result)

{

    BlockDriverState *bs;

    TestBlockJob *s;

    TestBlockJobCBData *data;

    data = g_new0(TestBlockJobCBData, 1);

    bs = bdrv_new();

    s = block_job_create(&test_block_job_driver, bs, 0, test_block_job_cb,

                         data, &error_abort);

    s->iterations = iterations;

    s->use_timer = use_timer;

    s->rc = rc;

    s->result = result;

    s->common.co = qemu_coroutine_create(test_block_job_run);

    data->job = s;

    data->result = result;

    qemu_coroutine_enter(s->common.co, s);

    return &s->common;

}


static int cook_decode_init(AVCodecContext *avctx)
{
    COOKextradata *e = avctx->extradata;
    COOKContext *q = avctx->priv_data;
    /* Take care of the codec specific extradata. */
    if (avctx->extradata_size <= 0) {
        av_log(NULL,AV_LOG_ERROR,"Necessary extradata missing!\n");
    } else {
        /* 8 for mono, 16 for stereo, ? for multichannel
           Swap to right endianness so we don't need to care later on. */
        av_log(NULL,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);
        if (avctx->extradata_size >= 8){
            e->cookversion = be2me_32(e->cookversion);
            e->samples_per_frame = be2me_16(e->samples_per_frame);
            e->subbands = be2me_16(e->subbands);
        }
        if (avctx->extradata_size >= 16){
            e->js_subband_start = be2me_16(e->js_subband_start);
            e->js_vlc_bits = be2me_16(e->js_vlc_bits);
        }
    }
    /* Take data from the AVCodecContext (RM container). */
    q->sample_rate = avctx->sample_rate;
    q->nb_channels = avctx->channels;
    q->bit_rate = avctx->bit_rate;
    /* Initialize state. */
    q->random_state = 1;
    /* Initialize extradata related variables. */
    q->samples_per_channel = e->samples_per_frame / q->nb_channels;
    q->samples_per_frame = e->samples_per_frame;
    q->subbands = e->subbands;
    q->bits_per_subpacket = avctx->block_align * 8;
    /* Initialize default data states. */
    q->js_subband_start = 0;
    q->log2_numvector_size = 5;
    q->total_subbands = q->subbands;
    /* Initialize version-dependent variables */
    av_log(NULL,AV_LOG_DEBUG,"e->cookversion=%x\n",e->cookversion);
    switch (e->cookversion) {
        case MONO_COOK1:
            if (q->nb_channels != 1) {
                av_log(NULL,AV_LOG_ERROR,"Container channels != 1, report sample!\n");
            }
            av_log(NULL,AV_LOG_DEBUG,"MONO_COOK1\n");
            break;
        case MONO_COOK2:
            if (q->nb_channels != 1) {
                q->joint_stereo = 0;
                q->bits_per_subpacket = q->bits_per_subpacket/2;
            }
            av_log(NULL,AV_LOG_DEBUG,"MONO_COOK2\n");
            break;
        case JOINT_STEREO:
            if (q->nb_channels != 2) {
                av_log(NULL,AV_LOG_ERROR,"Container channels != 2, report sample!\n");
            }
            av_log(NULL,AV_LOG_DEBUG,"JOINT_STEREO\n");
            if (avctx->extradata_size >= 16){
                q->total_subbands = q->subbands + e->js_subband_start;
                q->js_subband_start = e->js_subband_start;
                q->joint_stereo = 1;
                q->js_vlc_bits = e->js_vlc_bits;
            }
            if (q->samples_per_channel > 256) {
                q->log2_numvector_size  = 6;
            }
            if (q->samples_per_channel > 512) {
                q->log2_numvector_size  = 7;
            }
            break;
        case MC_COOK:
            av_log(NULL,AV_LOG_ERROR,"MC_COOK not supported!\n");
            break;
        default:
            av_log(NULL,AV_LOG_ERROR,"Unknown Cook version, report sample!\n");
            break;
    }
    /* Initialize variable relations */
    q->mlt_size = q->samples_per_channel;
    q->numvector_size = (1 << q->log2_numvector_size);
    /* Generate tables */
    init_rootpow2table(q);
    init_pow2table(q);
    init_gain_table(q);
    if (init_cook_vlc_tables(q) != 0)
    /* Pad the databuffer with FF_INPUT_BUFFER_PADDING_SIZE,
       this is for the bitstreamreader. */
    if ((q->decoded_bytes_buffer = av_mallocz((avctx->block_align+(4-avctx->block_align%4) + FF_INPUT_BUFFER_PADDING_SIZE)*sizeof(uint8_t)))  == NULL)
    q->decode_buf_ptr[0] = q->decode_buffer_1;
    q->decode_buf_ptr[1] = q->decode_buffer_2;
    q->decode_buf_ptr[2] = q->decode_buffer_3;
    q->decode_buf_ptr[3] = q->decode_buffer_4;
    q->decode_buf_ptr2[0] = q->decode_buffer_3;
    q->decode_buf_ptr2[1] = q->decode_buffer_4;
    q->previous_buffer_ptr[0] = q->mono_previous_buffer1;
    q->previous_buffer_ptr[1] = q->mono_previous_buffer2;
    /* Initialize transform. */
    if ( init_cook_mlt(q) == 0 )
    /* Try to catch some obviously faulty streams, othervise it might be exploitable */
    if (q->total_subbands > 53) {
        av_log(NULL,AV_LOG_ERROR,"total_subbands > 53, report sample!\n");
    }
    if (q->subbands > 50) {
        av_log(NULL,AV_LOG_ERROR,"subbands > 50, report sample!\n");
    }
    if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512) || (q->samples_per_channel == 1024)) {
    } else {
        av_log(NULL,AV_LOG_ERROR,"unknown amount of samples_per_channel = %d, report sample!\n",q->samples_per_channel);
    }
#ifdef COOKDEBUG
    dump_cook_context(q,e);
#endif
    return 0;
}


static int check_for_block_signature(BlockDriverState *bs, const uint8_t *buf)

{

    static const uint8_t signatures[][4] = {

        { 'Q', 'F', 'I', 0xfb }, /* qcow/qcow2 */

        { 'C', 'O', 'W', 'D' }, /* VMDK3 */

        { 'V', 'M', 'D', 'K' }, /* VMDK4 */

        { 'O', 'O', 'O', 'M' }, /* UML COW */

        {}

    };

    int i;

    for (i = 0; signatures[i][0] != 0; i++) {

        if (memcmp(buf, signatures[i], 4) == 0) {

            return 1;

        }

    }

    return 0;

}


static int parallels_open(BlockDriverState *bs, QDict *options, int flags,

                          Error **errp)

{

    BDRVParallelsState *s = bs->opaque;

    ParallelsHeader ph;

    int ret, size, i;

    QemuOpts *opts = NULL;

    Error *local_err = NULL;

    char *buf;

    bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,

                               false, errp);

    if (!bs->file) {

        return -EINVAL;

    }

    ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));

    if (ret < 0) {

        goto fail;

    }

    bs->total_sectors = le64_to_cpu(ph.nb_sectors);

    if (le32_to_cpu(ph.version) != HEADER_VERSION) {

        goto fail_format;

    }

    if (!memcmp(ph.magic, HEADER_MAGIC, 16)) {

        s->off_multiplier = 1;

        bs->total_sectors = 0xffffffff & bs->total_sectors;

    } else if (!memcmp(ph.magic, HEADER_MAGIC2, 16)) {

        s->off_multiplier = le32_to_cpu(ph.tracks);

    } else {

        goto fail_format;

    }

    s->tracks = le32_to_cpu(ph.tracks);

    if (s->tracks == 0) {

        error_setg(errp, "Invalid image: Zero sectors per track");

        ret = -EINVAL;

        goto fail;

    }

    if (s->tracks > INT32_MAX/513) {

        error_setg(errp, "Invalid image: Too big cluster");

        ret = -EFBIG;

        goto fail;

    }

    s->bat_size = le32_to_cpu(ph.bat_entries);

    if (s->bat_size > INT_MAX / sizeof(uint32_t)) {

        error_setg(errp, "Catalog too large");

        ret = -EFBIG;

        goto fail;

    }

    size = bat_entry_off(s->bat_size);

    s->header_size = ROUND_UP(size, bdrv_opt_mem_align(bs->file->bs));

    s->header = qemu_try_blockalign(bs->file->bs, s->header_size);

    if (s->header == NULL) {

        ret = -ENOMEM;

        goto fail;

    }

    s->data_end = le32_to_cpu(ph.data_off);

    if (s->data_end == 0) {

        s->data_end = ROUND_UP(bat_entry_off(s->bat_size), BDRV_SECTOR_SIZE);

    }

    if (s->data_end < s->header_size) {

        /* there is not enough unused space to fit to block align between BAT

           and actual data. We can't avoid read-modify-write... */

        s->header_size = size;

    }

    ret = bdrv_pread(bs->file, 0, s->header, s->header_size);

    if (ret < 0) {

        goto fail;

    }

    s->bat_bitmap = (uint32_t *)(s->header + 1);

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

        int64_t off = bat2sect(s, i);

        if (off >= s->data_end) {

            s->data_end = off + s->tracks;

        }

    }

    if (le32_to_cpu(ph.inuse) == HEADER_INUSE_MAGIC) {

        /* Image was not closed correctly. The check is mandatory */

        s->header_unclean = true;

        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {

            error_setg(errp, "parallels: Image was not closed correctly; "

                       "cannot be opened read/write");

            ret = -EACCES;

            goto fail;

        }

    }

    opts = qemu_opts_create(&parallels_runtime_opts, NULL, 0, &local_err);

    if (local_err != NULL) {

        goto fail_options;

    }

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err != NULL) {

        goto fail_options;

    }

    s->prealloc_size =

        qemu_opt_get_size_del(opts, PARALLELS_OPT_PREALLOC_SIZE, 0);

    s->prealloc_size = MAX(s->tracks, s->prealloc_size >> BDRV_SECTOR_BITS);

    buf = qemu_opt_get_del(opts, PARALLELS_OPT_PREALLOC_MODE);

    s->prealloc_mode = qapi_enum_parse(prealloc_mode_lookup, buf,

            PRL_PREALLOC_MODE__MAX, PRL_PREALLOC_MODE_FALLOCATE, &local_err);

    g_free(buf);

    if (local_err != NULL) {

        goto fail_options;

    }

    if (!(flags & BDRV_O_RESIZE) || !bdrv_has_zero_init(bs->file->bs) ||

            bdrv_truncate(bs->file, bdrv_getlength(bs->file->bs),

                          PREALLOC_MODE_OFF, NULL) != 0) {

        s->prealloc_mode = PRL_PREALLOC_MODE_FALLOCATE;

    }

    if (flags & BDRV_O_RDWR) {

        s->header->inuse = cpu_to_le32(HEADER_INUSE_MAGIC);

        ret = parallels_update_header(bs);

        if (ret < 0) {

            goto fail;

        }

    }

    s->bat_dirty_block = 4 * getpagesize();

    s->bat_dirty_bmap =

        bitmap_new(DIV_ROUND_UP(s->header_size, s->bat_dirty_block));

    qemu_co_mutex_init(&s->lock);

    return 0;

fail_format:

    error_setg(errp, "Image not in Parallels format");

    ret = -EINVAL;

fail:

    qemu_vfree(s->header);

    return ret;

fail_options:

    error_propagate(errp, local_err);

    ret = -EINVAL;

    goto fail;

}


static void __attribute__((constructor)) st_init(void)

{

    atexit(st_flush_trace_buffer);

}


static void test_qemu_strtoull_full_max(void)

{

    const char *str = g_strdup_printf("%lld", ULLONG_MAX);

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, ULLONG_MAX);

}


static av_cold int mss1_decode_init(AVCodecContext *avctx)

{

    MSS1Context * const c = avctx->priv_data;

    int ret;

    c->ctx.avctx       = avctx;

    c->pic = av_frame_alloc();

    if (!c->pic)

        return AVERROR(ENOMEM);

    ret = ff_mss12_decode_init(&c->ctx, 0, &c->sc, NULL);

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    return ret;

}


static int ioreq_map(struct ioreq *ioreq)

{

    XenGnttab gnt = ioreq->blkdev->xendev.gnttabdev;

    uint32_t domids[BLKIF_MAX_SEGMENTS_PER_REQUEST];

    uint32_t refs[BLKIF_MAX_SEGMENTS_PER_REQUEST];

    void *page[BLKIF_MAX_SEGMENTS_PER_REQUEST];

    int i, j, new_maps = 0;

    PersistentGrant *grant;

    /* domids and refs variables will contain the information necessary

     * to map the grants that are needed to fulfill this request.

     *

     * After mapping the needed grants, the page array will contain the

     * memory address of each granted page in the order specified in ioreq

     * (disregarding if it's a persistent grant or not).

     */

    if (ioreq->v.niov == 0 || ioreq->mapped == 1) {

        return 0;

    }

    if (ioreq->blkdev->feature_persistent) {

        for (i = 0; i < ioreq->v.niov; i++) {

            grant = g_tree_lookup(ioreq->blkdev->persistent_gnts,

                                    GUINT_TO_POINTER(ioreq->refs[i]));

            if (grant != NULL) {

                page[i] = grant->page;

                xen_be_printf(&ioreq->blkdev->xendev, 3,

                              "using persistent-grant %" PRIu32 "\n",

                              ioreq->refs[i]);

            } else {

                    /* Add the grant to the list of grants that

                     * should be mapped

                     */

                    domids[new_maps] = ioreq->domids[i];

                    refs[new_maps] = ioreq->refs[i];

                    page[i] = NULL;

                    new_maps++;

            }

        }

        /* Set the protection to RW, since grants may be reused later

         * with a different protection than the one needed for this request

         */

        ioreq->prot = PROT_WRITE | PROT_READ;

    } else {

        /* All grants in the request should be mapped */

        memcpy(refs, ioreq->refs, sizeof(refs));

        memcpy(domids, ioreq->domids, sizeof(domids));

        memset(page, 0, sizeof(page));

        new_maps = ioreq->v.niov;

    }

    if (batch_maps && new_maps) {

        ioreq->pages = xc_gnttab_map_grant_refs

            (gnt, new_maps, domids, refs, ioreq->prot);

        if (ioreq->pages == NULL) {

            xen_be_printf(&ioreq->blkdev->xendev, 0,

                          "can't map %d grant refs (%s, %d maps)\n",

                          new_maps, strerror(errno), ioreq->blkdev->cnt_map);

            return -1;

        }

        for (i = 0, j = 0; i < ioreq->v.niov; i++) {

            if (page[i] == NULL) {

                page[i] = ioreq->pages + (j++) * XC_PAGE_SIZE;

            }

        }

        ioreq->blkdev->cnt_map += new_maps;

    } else if (new_maps)  {

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

            ioreq->page[i] = xc_gnttab_map_grant_ref

                (gnt, domids[i], refs[i], ioreq->prot);

            if (ioreq->page[i] == NULL) {

                xen_be_printf(&ioreq->blkdev->xendev, 0,

                              "can't map grant ref %d (%s, %d maps)\n",

                              refs[i], strerror(errno), ioreq->blkdev->cnt_map);

                ioreq->mapped = 1;

                ioreq_unmap(ioreq);

                return -1;

            }

            ioreq->blkdev->cnt_map++;

        }

        for (i = 0, j = 0; i < ioreq->v.niov; i++) {

            if (page[i] == NULL) {

                page[i] = ioreq->page[j++];

            }

        }

    }

    if (ioreq->blkdev->feature_persistent) {

        while ((ioreq->blkdev->persistent_gnt_count < ioreq->blkdev->max_grants)

              && new_maps) {

            /* Go through the list of newly mapped grants and add as many

             * as possible to the list of persistently mapped grants.

             *

             * Since we start at the end of ioreq->page(s), we only need

             * to decrease new_maps to prevent this granted pages from

             * being unmapped in ioreq_unmap.

             */

            grant = g_malloc0(sizeof(*grant));

            new_maps--;

            if (batch_maps) {

                grant->page = ioreq->pages + (new_maps) * XC_PAGE_SIZE;

            } else {

                grant->page = ioreq->page[new_maps];

            }

            grant->blkdev = ioreq->blkdev;

            xen_be_printf(&ioreq->blkdev->xendev, 3,

                          "adding grant %" PRIu32 " page: %p\n",

                          refs[new_maps], grant->page);

            g_tree_insert(ioreq->blkdev->persistent_gnts,

                          GUINT_TO_POINTER(refs[new_maps]),

                          grant);

            ioreq->blkdev->persistent_gnt_count++;

        }

    }

    for (i = 0; i < ioreq->v.niov; i++) {

        ioreq->v.iov[i].iov_base += (uintptr_t)page[i];

    }

    ioreq->mapped = 1;

    ioreq->num_unmap = new_maps;

    return 0;

}


static void *aio_thread(void *unused)

{

    sigset_t set;

    /* block all signals */

    sigfillset(&set);

    sigprocmask(SIG_BLOCK, &set, NULL);

    while (1) {

        struct qemu_paiocb *aiocb;

        size_t offset;

        int ret = 0;

        pthread_mutex_lock(&lock);

        while (TAILQ_EMPTY(&request_list) &&

               !(ret == ETIMEDOUT)) {

            struct timespec ts = { 0 };

            qemu_timeval tv;

            qemu_gettimeofday(&tv);

            ts.tv_sec = tv.tv_sec + 10;

            ret = pthread_cond_timedwait(&cond, &lock, &ts);

        }

        if (ret == ETIMEDOUT)

            break;

        aiocb = TAILQ_FIRST(&request_list);

        TAILQ_REMOVE(&request_list, aiocb, node);

        offset = 0;

        aiocb->active = 1;

        idle_threads--;

        pthread_mutex_unlock(&lock);

        while (offset < aiocb->aio_nbytes) {

            ssize_t len;

            if (aiocb->is_write)

                len = pwrite(aiocb->aio_fildes,

                             (const char *)aiocb->aio_buf + offset,

                             aiocb->aio_nbytes - offset,

                             aiocb->aio_offset + offset);

            else

                len = pread(aiocb->aio_fildes,

                            (char *)aiocb->aio_buf + offset,

                            aiocb->aio_nbytes - offset,

                            aiocb->aio_offset + offset);

            if (len == -1 && errno == EINTR)

                continue;

            else if (len == -1) {

                pthread_mutex_lock(&lock);

                aiocb->ret = -errno;

                pthread_mutex_unlock(&lock);

                break;

            } else if (len == 0)

                break;

            offset += len;

            pthread_mutex_lock(&lock);

            aiocb->ret = offset;

            pthread_mutex_unlock(&lock);

        }

        pthread_mutex_lock(&lock);

        idle_threads++;

        pthread_mutex_unlock(&lock);

        sigqueue(getpid(),

                 aiocb->aio_sigevent.sigev_signo,

                 aiocb->aio_sigevent.sigev_value);

    }

    idle_threads--;

    cur_threads--;

    pthread_mutex_unlock(&lock);

    return NULL;

}


int ff_dca_convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst,

                             int max_size)

{

    uint32_t mrk;

    int i, tmp;

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

    uint16_t *sdst = (uint16_t *) dst;

    PutBitContext pb;

    if ((unsigned) src_size > (unsigned) max_size)

        src_size = max_size;

    mrk = AV_RB32(src);

    switch (mrk) {

    case DCA_SYNCWORD_CORE_BE:

        memcpy(dst, src, src_size);

        return src_size;

    case DCA_SYNCWORD_CORE_LE:

        for (i = 0; i < (src_size + 1) >> 1; i++)

            *sdst++ = av_bswap16(*ssrc++);

        return src_size;

    case DCA_SYNCWORD_CORE_14B_BE:

    case DCA_SYNCWORD_CORE_14B_LE:

        init_put_bits(&pb, dst, max_size);

        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {

            tmp = ((mrk == DCA_SYNCWORD_CORE_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;

            put_bits(&pb, 14, tmp);

        }

        flush_put_bits(&pb);

        return (put_bits_count(&pb) + 7) >> 3;

    default:

        return AVERROR_INVALIDDATA;

    }

}


av_cold void ff_vp8dsp_init_arm(VP8DSPContext *dsp)

{

    int cpu_flags = av_get_cpu_flags();

    if (have_armv6(cpu_flags))

        ff_vp8dsp_init_armv6(dsp);

    if (have_neon(cpu_flags))

        ff_vp8dsp_init_neon(dsp);

}