static int vmdk_open_vmdk4(BlockDriverState *bs,

                           BlockDriverState *file,

                           int flags)

{

    int ret;

    uint32_t magic;

    uint32_t l1_size, l1_entry_sectors;

    VMDK4Header header;

    VmdkExtent *extent;

    int64_t l1_backup_offset = 0;

    ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));

    if (ret < 0) {

        return ret;

    }

    if (header.capacity == 0) {

        int64_t desc_offset = le64_to_cpu(header.desc_offset);

        if (desc_offset) {

            return vmdk_open_desc_file(bs, flags, desc_offset << 9);

        }

    }

    if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {

        /*

         * The footer takes precedence over the header, so read it in. The

         * footer starts at offset -1024 from the end: One sector for the

         * footer, and another one for the end-of-stream marker.

         */

        struct {

            struct {

                uint64_t val;

                uint32_t size;

                uint32_t type;

                uint8_t pad[512 - 16];

            } QEMU_PACKED footer_marker;

            uint32_t magic;

            VMDK4Header header;

            uint8_t pad[512 - 4 - sizeof(VMDK4Header)];

            struct {

                uint64_t val;

                uint32_t size;

                uint32_t type;

                uint8_t pad[512 - 16];

            } QEMU_PACKED eos_marker;

        } QEMU_PACKED footer;

        ret = bdrv_pread(file,

            bs->file->total_sectors * 512 - 1536,

            &footer, sizeof(footer));

        if (ret < 0) {

            return ret;

        }

        /* Some sanity checks for the footer */

        if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||

            le32_to_cpu(footer.footer_marker.size) != 0  ||

            le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||

            le64_to_cpu(footer.eos_marker.val) != 0  ||

            le32_to_cpu(footer.eos_marker.size) != 0  ||

            le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)

        {

            return -EINVAL;

        }

        header = footer.header;

    }

    if (le32_to_cpu(header.version) >= 3) {

        char buf[64];

        snprintf(buf, sizeof(buf), "VMDK version %d",

                 le32_to_cpu(header.version));

        qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,

                bs->device_name, "vmdk", buf);

        return -ENOTSUP;

    }

    l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)

                        * le64_to_cpu(header.granularity);

    if (l1_entry_sectors == 0) {

        return -EINVAL;

    }

    l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)

                / l1_entry_sectors;

    if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {

        l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;

    }

    extent = vmdk_add_extent(bs, file, false,

                          le64_to_cpu(header.capacity),

                          le64_to_cpu(header.gd_offset) << 9,

                          l1_backup_offset,

                          l1_size,

                          le32_to_cpu(header.num_gtes_per_gte),

                          le64_to_cpu(header.granularity));

    extent->compressed =

        le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;

    extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;

    extent->version = le32_to_cpu(header.version);

    extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;

    ret = vmdk_init_tables(bs, extent);

    if (ret) {

        /* free extent allocated by vmdk_add_extent */

        vmdk_free_last_extent(bs);

    }

    return ret;

}


static void control_to_network(RDMAControlHeader *control)

{

    control->type = htonl(control->type);

    control->len = htonl(control->len);

    control->repeat = htonl(control->repeat);

}


static bool use_multiport(VirtIOSerial *vser)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(vser);

    return virtio_has_feature(vdev, VIRTIO_CONSOLE_F_MULTIPORT);

}


static int poll_filter(OutputStream *ost)

{

    OutputFile    *of = output_files[ost->file_index];

    AVFrame *filtered_frame = NULL;

    int frame_size, ret;

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

        return AVERROR(ENOMEM);

    } else

        avcodec_get_frame_defaults(ost->filtered_frame);

    filtered_frame = ost->filtered_frame;

    if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&

        !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))

        ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,

                                         ost->st->codec->frame_size);

    else

        ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);

    if (ret < 0)

        return ret;

    if (filtered_frame->pts != AV_NOPTS_VALUE) {

        filtered_frame->pts = av_rescale_q(filtered_frame->pts,

                                           ost->filter->filter->inputs[0]->time_base,

                                           ost->st->codec->time_base) -

                              av_rescale_q(of->start_time,

                                           AV_TIME_BASE_Q,

                                           ost->st->codec->time_base);

    }

    switch (ost->filter->filter->inputs[0]->type) {

    case AVMEDIA_TYPE_VIDEO:

        if (!ost->frame_aspect_ratio)

            ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;

        do_video_out(of->ctx, ost, filtered_frame, &frame_size);

        if (vstats_filename && frame_size)

            do_video_stats(ost, frame_size);

        break;

    case AVMEDIA_TYPE_AUDIO:

        do_audio_out(of->ctx, ost, filtered_frame);

        break;

    default:

        // TODO support subtitle filters

        av_assert0(0);

    }

    av_frame_unref(filtered_frame);

    return 0;

}


void *memory_region_get_ram_ptr(MemoryRegion *mr)

{

    if (mr->alias) {

        return memory_region_get_ram_ptr(mr->alias) + mr->alias_offset;

    }

    assert(mr->terminates);

    return qemu_get_ram_ptr(mr->ram_addr & TARGET_PAGE_MASK);

}


void ff_af_queue_init(AVCodecContext *avctx, AudioFrameQueue *afq)

{

    afq->avctx             = avctx;

    afq->next_pts          = AV_NOPTS_VALUE;

    afq->remaining_delay   = avctx->delay;

    afq->remaining_samples = avctx->delay;

    afq->frame_queue       = NULL;

}


void kvm_s390_service_interrupt(S390CPU *cpu, uint32_t parm)

{

    kvm_s390_interrupt_internal(cpu, KVM_S390_INT_SERVICE, parm, 0 , 1);

}


static inline void RENAME(rgb24tobgr15)(const uint8_t *src, uint8_t *dst, int src_size)

{

    const uint8_t *s = src;

    const uint8_t *end;

    const uint8_t *mm_end;

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

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

    __asm__ volatile(

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

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

        ::"m"(red_15mask),"m"(green_15mask));

    mm_end = end - 11;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

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

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

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

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

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

            "psrlq         $3, %%mm0    \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        d += 4;

        s += 12;

    }

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

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

    while (s < end) {

        const int b = *s++;

        const int g = *s++;

        const int r = *s++;

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

    }

}


static gboolean gd_motion_event(GtkWidget *widget, GdkEventMotion *motion,

                                void *opaque)

{

    GtkDisplayState *s = opaque;

    int x, y;

    int mx, my;

    int fbh, fbw;

    int ww, wh;

    fbw = surface_width(s->ds) * s->scale_x;

    fbh = surface_height(s->ds) * s->scale_y;

    gdk_drawable_get_size(gtk_widget_get_window(s->drawing_area), &ww, &wh);

    mx = my = 0;

    if (ww > fbw) {

        mx = (ww - fbw) / 2;

    }

    if (wh > fbh) {

        my = (wh - fbh) / 2;

    }

    x = (motion->x - mx) / s->scale_x;

    y = (motion->y - my) / s->scale_y;

    if (x < 0 || y < 0 ||

        x >= surface_width(s->ds) ||

        y >= surface_height(s->ds)) {

        return TRUE;

    }

    if (qemu_input_is_absolute()) {

        qemu_input_queue_abs(s->dcl.con, INPUT_AXIS_X, x,

                             surface_width(s->ds));

        qemu_input_queue_abs(s->dcl.con, INPUT_AXIS_Y, y,

                             surface_height(s->ds));

        qemu_input_event_sync();

    } else if (s->last_x != -1 && s->last_y != -1 && gd_is_grab_active(s)) {

        qemu_input_queue_rel(s->dcl.con, INPUT_AXIS_X, x - s->last_x);

        qemu_input_queue_rel(s->dcl.con, INPUT_AXIS_Y, y - s->last_y);

        qemu_input_event_sync();

    }

    s->last_x = x;

    s->last_y = y;

    if (!qemu_input_is_absolute() && gd_is_grab_active(s)) {

        GdkScreen *screen = gtk_widget_get_screen(s->drawing_area);

        int x = (int)motion->x_root;

        int y = (int)motion->y_root;

        /* In relative mode check to see if client pointer hit

         * one of the screen edges, and if so move it back by

         * 200 pixels. This is important because the pointer

         * in the server doesn't correspond 1-for-1, and so

         * may still be only half way across the screen. Without

         * this warp, the server pointer would thus appear to hit

         * an invisible wall */

        if (x == 0) {

            x += 200;

        }

        if (y == 0) {

            y += 200;

        }

        if (x == (gdk_screen_get_width(screen) - 1)) {

            x -= 200;

        }

        if (y == (gdk_screen_get_height(screen) - 1)) {

            y -= 200;

        }

        if (x != (int)motion->x_root || y != (int)motion->y_root) {

#if GTK_CHECK_VERSION(3, 0, 0)

            GdkDevice *dev = gdk_event_get_device((GdkEvent *)motion);

            gdk_device_warp(dev, screen, x, y);

#else

            GdkDisplay *display = gtk_widget_get_display(widget);

            gdk_display_warp_pointer(display, screen, x, y);

#endif

            s->last_x = -1;

            s->last_y = -1;

            return FALSE;

        }

    }

    return TRUE;

}


int ff_vdpau_common_init(AVCodecContext *avctx, VdpDecoderProfile profile,

                         int level)

{

    VDPAUHWContext *hwctx = avctx->hwaccel_context;

    VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;

    VdpVideoSurfaceQueryCapabilities *surface_query_caps;

    VdpDecoderQueryCapabilities *decoder_query_caps;

    VdpDecoderCreate *create;

    void *func;

    VdpStatus status;

    VdpBool supported;

    uint32_t max_level, max_mb, max_width, max_height;

    VdpChromaType type;

    uint32_t width;

    uint32_t height;

    vdctx->width            = UINT32_MAX;

    vdctx->height           = UINT32_MAX;

    if (av_vdpau_get_surface_parameters(avctx, &type, &width, &height))

        return AVERROR(ENOSYS);

    if (hwctx) {

        hwctx->reset            = 0;

        if (hwctx->context.decoder != VDP_INVALID_HANDLE) {

            vdctx->decoder = hwctx->context.decoder;

            vdctx->render  = hwctx->context.render;

            vdctx->device  = VDP_INVALID_HANDLE;

            return 0; /* Decoder created by user */

        }

        vdctx->device           = hwctx->device;

        vdctx->get_proc_address = hwctx->get_proc_address;

        if (hwctx->flags & AV_HWACCEL_FLAG_IGNORE_LEVEL)

            level = 0;

        if (!(hwctx->flags & AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH) &&

            type != VDP_CHROMA_TYPE_420)

            return AVERROR(ENOSYS);

    } else {

        AVHWFramesContext *frames_ctx = NULL;

        AVVDPAUDeviceContext *dev_ctx;

        // We assume the hw_frames_ctx always survives until ff_vdpau_common_uninit

        // is called. This holds true as the user is not allowed to touch

        // hw_device_ctx, or hw_frames_ctx after get_format (and ff_get_format

        // itself also uninits before unreffing hw_frames_ctx).

        if (avctx->hw_frames_ctx) {

            frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

        } else if (avctx->hw_device_ctx) {

            int ret;

            avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);

            if (!avctx->hw_frames_ctx)

                return AVERROR(ENOMEM);

            frames_ctx            = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

            frames_ctx->format    = AV_PIX_FMT_VDPAU;

            frames_ctx->sw_format = avctx->sw_pix_fmt;

            frames_ctx->width     = avctx->coded_width;

            frames_ctx->height    = avctx->coded_height;

            ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);

            if (ret < 0) {

                av_buffer_unref(&avctx->hw_frames_ctx);

                return ret;

            }

        }

        if (!frames_ctx) {

            av_log(avctx, AV_LOG_ERROR, "A hardware frames context is "

                   "required for VDPAU decoding.\n");

            return AVERROR(EINVAL);

        }

        dev_ctx = frames_ctx->device_ctx->hwctx;

        vdctx->device           = dev_ctx->device;

        vdctx->get_proc_address = dev_ctx->get_proc_address;

        if (avctx->hwaccel_flags & AV_HWACCEL_FLAG_IGNORE_LEVEL)

            level = 0;

    }

    if (level < 0)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device,

                                     VDP_FUNC_ID_VIDEO_SURFACE_QUERY_CAPABILITIES,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        surface_query_caps = func;

    status = surface_query_caps(vdctx->device, type, &supported,

                                &max_width, &max_height);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    if (supported != VDP_TRUE ||

        max_width < width || max_height < height)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device,

                                     VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        decoder_query_caps = func;

    status = decoder_query_caps(vdctx->device, profile, &supported, &max_level,

                                &max_mb, &max_width, &max_height);

#ifdef VDP_DECODER_PROFILE_H264_CONSTRAINED_BASELINE

    if ((status != VDP_STATUS_OK || supported != VDP_TRUE) && profile == VDP_DECODER_PROFILE_H264_CONSTRAINED_BASELINE) {

        profile = VDP_DECODER_PROFILE_H264_MAIN;

        status = decoder_query_caps(vdctx->device, profile, &supported,

                                    &max_level, &max_mb,

                                    &max_width, &max_height);

    }

#endif

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    if (supported != VDP_TRUE || max_level < level ||

        max_width < width || max_height < height)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_CREATE,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        create = func;

    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_RENDER,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        vdctx->render = func;

    status = create(vdctx->device, profile, width, height, avctx->refs,

                    &vdctx->decoder);

    if (status == VDP_STATUS_OK) {

        vdctx->width  = avctx->coded_width;

        vdctx->height = avctx->coded_height;

    }

    return vdpau_error(status);

}


static int estimate_qp(MpegEncContext *s, int dry_run){

    if (s->next_lambda){

        s->current_picture_ptr->f.quality =

        s->current_picture.f.quality = s->next_lambda;

        if(!dry_run) s->next_lambda= 0;

    } else if (!s->fixed_qscale) {

        s->current_picture_ptr->f.quality =

        s->current_picture.f.quality = ff_rate_estimate_qscale(s, dry_run);

        if (s->current_picture.f.quality < 0)

            return -1;

    }

    if(s->adaptive_quant){

        switch(s->codec_id){

        case AV_CODEC_ID_MPEG4:

            if (CONFIG_MPEG4_ENCODER)

                ff_clean_mpeg4_qscales(s);

            break;

        case AV_CODEC_ID_H263:

        case AV_CODEC_ID_H263P:

        case AV_CODEC_ID_FLV1:

            if (CONFIG_H263_ENCODER)

                ff_clean_h263_qscales(s);

            break;

        default:

            ff_init_qscale_tab(s);

        }

        s->lambda= s->lambda_table[0];

        //FIXME broken

    }else

        s->lambda = s->current_picture.f.quality;

    update_qscale(s);

    return 0;

}


static void spr_write_tbu (DisasContext *ctx, int sprn, int gprn)

{

    if (use_icount) {

        gen_io_start();

    }

    gen_helper_store_tbu(cpu_env, cpu_gpr[gprn]);

    if (use_icount) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static void vfio_intx_enable_kvm(VFIOPCIDevice *vdev)

{

#ifdef CONFIG_KVM

    struct kvm_irqfd irqfd = {

        .fd = event_notifier_get_fd(&vdev->intx.interrupt),

        .gsi = vdev->intx.route.irq,

        .flags = KVM_IRQFD_FLAG_RESAMPLE,

    };

    struct vfio_irq_set *irq_set;

    int ret, argsz;

    int32_t *pfd;

    if (!VFIO_ALLOW_KVM_INTX || !kvm_irqfds_enabled() ||

        vdev->intx.route.mode != PCI_INTX_ENABLED ||

        !kvm_resamplefds_enabled()) {

        return;

    }

    /* Get to a known interrupt state */

    qemu_set_fd_handler(irqfd.fd, NULL, NULL, vdev);

    vfio_mask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);

    vdev->intx.pending = false;

    pci_irq_deassert(&vdev->pdev);

    /* Get an eventfd for resample/unmask */

    if (event_notifier_init(&vdev->intx.unmask, 0)) {

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

        goto fail;

    }

    /* KVM triggers it, VFIO listens for it */

    irqfd.resamplefd = event_notifier_get_fd(&vdev->intx.unmask);

    if (kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd)) {

        error_report("vfio: Error: Failed to setup resample irqfd: %m");

        goto fail_irqfd;

    }

    argsz = sizeof(*irq_set) + sizeof(*pfd);

    irq_set = g_malloc0(argsz);

    irq_set->argsz = argsz;

    irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_UNMASK;

    irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;

    irq_set->start = 0;

    irq_set->count = 1;

    pfd = (int32_t *)&irq_set->data;

    *pfd = irqfd.resamplefd;

    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);

    g_free(irq_set);

    if (ret) {

        error_report("vfio: Error: Failed to setup INTx unmask fd: %m");

        goto fail_vfio;

    }

    /* Let'em rip */

    vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);

    vdev->intx.kvm_accel = true;

    trace_vfio_intx_enable_kvm(vdev->vbasedev.name);

    return;

fail_vfio:

    irqfd.flags = KVM_IRQFD_FLAG_DEASSIGN;

    kvm_vm_ioctl(kvm_state, KVM_IRQFD, &irqfd);

fail_irqfd:

    event_notifier_cleanup(&vdev->intx.unmask);

fail:

    qemu_set_fd_handler(irqfd.fd, vfio_intx_interrupt, NULL, vdev);

    vfio_unmask_single_irqindex(&vdev->vbasedev, VFIO_PCI_INTX_IRQ_INDEX);

#endif

}


static inline void gen_evfsnabs(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    tcg_gen_ori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x8000000080000000LL);

#else

    tcg_gen_ori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x80000000);

    tcg_gen_ori_tl(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)], 0x80000000);

#endif

}


static uint64_t imx_timerg_read(void *opaque, target_phys_addr_t offset,

                                unsigned size)

{

    IMXTimerGState *s = (IMXTimerGState *)opaque;

    DPRINTF("g-read(offset=%x)", offset >> 2);

    switch (offset >> 2) {

    case 0: /* Control Register */

        DPRINTF(" cr = %x\n", s->cr);

        return s->cr;

    case 1: /* prescaler */

        DPRINTF(" pr = %x\n", s->pr);

        return s->pr;

    case 2: /* Status Register */

        DPRINTF(" sr = %x\n", s->sr);

        return s->sr;

    case 3: /* Interrupt Register */

        DPRINTF(" ir = %x\n", s->ir);

        return s->ir;

    case 4: /* Output Compare Register 1 */

        DPRINTF(" ocr1 = %x\n", s->ocr1);

        return s->ocr1;

    case 9: /* cnt */

        imx_timerg_update_counts(s);

        DPRINTF(" cnt = %x\n", s->cnt);

        return s->cnt;

    }

    IPRINTF("imx_timerg_read: Bad offset %x\n",

            (int)offset >> 2);

    return 0;

}


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

                         Error **errp)

{

    BDRVBlkdebugState *s = bs->opaque;

    QemuOpts *opts;

    Error *local_err = NULL;

    int ret;

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto out;

    }

    /* Read rules from config file or command line options */

    s->config_file = g_strdup(qemu_opt_get(opts, "config"));

    ret = read_config(s, s->config_file, options, errp);

    if (ret) {

        goto out;

    }

    /* Set initial state */

    s->state = 1;

    /* Open the image file */

    bs->file = bdrv_open_child(qemu_opt_get(opts, "x-image"), options, "image",

                               bs, &child_file, false, &local_err);

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

        goto out;

    }

    bs->supported_write_flags = BDRV_REQ_FUA &

        bs->file->bs->supported_write_flags;

    bs->supported_zero_flags = (BDRV_REQ_FUA | BDRV_REQ_MAY_UNMAP) &

        bs->file->bs->supported_zero_flags;

    ret = -EINVAL;

    /* Set request alignment */

    s->align = qemu_opt_get_size(opts, "align", 0);

    if (s->align && (s->align >= INT_MAX || !is_power_of_2(s->align))) {

        error_setg(errp, "Cannot meet constraints with align %" PRIu64,

                   s->align);

        goto out;

    }

    ret = 0;

out:

    if (ret < 0) {

        g_free(s->config_file);

    }

    qemu_opts_del(opts);

    return ret;

}


static void test_qemu_strtoull_full_negative(void)

{

    const char *str = " \t -321";

    uint64_t res = 999;

    int err;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 18446744073709551295LLU);

}


static uint64_t exynos4210_fimd_read(void *opaque, target_phys_addr_t offset,

                                  unsigned size)

{

    Exynos4210fimdState *s = (Exynos4210fimdState *)opaque;

    int w, i;

    uint32_t ret = 0;

    DPRINT_L2("read offset 0x%08x\n", offset);

    switch (offset) {

    case FIMD_VIDCON0 ... FIMD_VIDCON3:

        return s->vidcon[(offset - FIMD_VIDCON0) >> 2];

    case FIMD_VIDTCON_START ... FIMD_VIDTCON_END:

        return s->vidtcon[(offset - FIMD_VIDTCON_START) >> 2];

    case FIMD_WINCON_START ... FIMD_WINCON_END:

        return s->window[(offset - FIMD_WINCON_START) >> 2].wincon;

    case FIMD_SHADOWCON:

        return s->shadowcon;

    case FIMD_WINCHMAP:

        return s->winchmap;

    case FIMD_VIDOSD_START ... FIMD_VIDOSD_END:

        w = (offset - FIMD_VIDOSD_START) >> 4;

        i = ((offset - FIMD_VIDOSD_START) & 0xF) >> 2;

        switch (i) {

        case 0:

            ret = ((s->window[w].lefttop_x & FIMD_VIDOSD_COORD_MASK) <<

            FIMD_VIDOSD_HOR_SHIFT) |

            (s->window[w].lefttop_y & FIMD_VIDOSD_COORD_MASK);

            break;

        case 1:

            ret = ((s->window[w].rightbot_x & FIMD_VIDOSD_COORD_MASK) <<

                FIMD_VIDOSD_HOR_SHIFT) |

                (s->window[w].rightbot_y & FIMD_VIDOSD_COORD_MASK);

            break;

        case 2:

            if (w == 0) {

                ret = s->window[w].osdsize;

            } else {

                ret = (pack_upper_4(s->window[w].alpha_val[0]) <<

                    FIMD_VIDOSD_AEN0_SHIFT) |

                    pack_upper_4(s->window[w].alpha_val[1]);

            }

            break;

        case 3:

            if (w != 1 && w != 2) {

                DPRINT_ERROR("bad read offset 0x%08x\n", offset);

                return 0xBAADBAAD;

            }

            ret = s->window[w].osdsize;

            break;

        }

        return ret;

    case FIMD_VIDWADD0_START ... FIMD_VIDWADD0_END:

        w = (offset - FIMD_VIDWADD0_START) >> 3;

        i = ((offset - FIMD_VIDWADD0_START) >> 2) & 1;

        return s->window[w].buf_start[i];

    case FIMD_VIDWADD1_START ... FIMD_VIDWADD1_END:

        w = (offset - FIMD_VIDWADD1_START) >> 3;

        i = ((offset - FIMD_VIDWADD1_START) >> 2) & 1;

        return s->window[w].buf_end[i];

    case FIMD_VIDWADD2_START ... FIMD_VIDWADD2_END:

        w = (offset - FIMD_VIDWADD2_START) >> 2;

        return s->window[w].virtpage_width | (s->window[w].virtpage_offsize <<

            FIMD_VIDWADD2_OFFSIZE_SHIFT);

    case FIMD_VIDINTCON0 ... FIMD_VIDINTCON1:

        return s->vidintcon[(offset - FIMD_VIDINTCON0) >> 2];

    case FIMD_WKEYCON_START ... FIMD_WKEYCON_END:

        w = ((offset - FIMD_WKEYCON_START) >> 3) + 1;

        i = ((offset - FIMD_WKEYCON_START) >> 2) & 1;

        return s->window[w].keycon[i];

    case FIMD_WKEYALPHA_START ... FIMD_WKEYALPHA_END:

        w = ((offset - FIMD_WKEYALPHA_START) >> 2) + 1;

        return s->window[w].keyalpha;

    case FIMD_DITHMODE:

        return s->dithmode;

    case FIMD_WINMAP_START ... FIMD_WINMAP_END:

        return s->window[(offset - FIMD_WINMAP_START) >> 2].winmap;

    case FIMD_WPALCON_HIGH ... FIMD_WPALCON_LOW:

        return s->wpalcon[(offset - FIMD_WPALCON_HIGH) >> 2];

    case FIMD_TRIGCON:

        return s->trigcon;

    case FIMD_I80IFCON_START ... FIMD_I80IFCON_END:

        return s->i80ifcon[(offset - FIMD_I80IFCON_START) >> 2];

    case FIMD_COLORGAINCON:

        return s->colorgaincon;

    case FIMD_LDI_CMDCON0 ... FIMD_LDI_CMDCON1:

        return s->ldi_cmdcon[(offset - FIMD_LDI_CMDCON0) >> 2];

    case FIMD_SIFCCON0 ... FIMD_SIFCCON2:

        i = (offset - FIMD_SIFCCON0) >> 2;

        return s->sifccon[i];

    case FIMD_HUECOEFCR_START ... FIMD_HUECOEFCR_END:

        i = (offset - FIMD_HUECOEFCR_START) >> 2;

        return s->huecoef_cr[i];

    case FIMD_HUECOEFCB_START ... FIMD_HUECOEFCB_END:

        i = (offset - FIMD_HUECOEFCB_START) >> 2;

        return s->huecoef_cb[i];

    case FIMD_HUEOFFSET:

        return s->hueoffset;

    case FIMD_VIDWALPHA_START ... FIMD_VIDWALPHA_END:

        w = ((offset - FIMD_VIDWALPHA_START) >> 3);

        i = ((offset - FIMD_VIDWALPHA_START) >> 2) & 1;

        return s->window[w].alpha_val[i] &

                (w == 0 ? 0xFFFFFF : FIMD_VIDALPHA_ALPHA_LOWER);

    case FIMD_BLENDEQ_START ... FIMD_BLENDEQ_END:

        return s->window[(offset - FIMD_BLENDEQ_START) >> 2].blendeq;

    case FIMD_BLENDCON:

        return s->blendcon;

    case FIMD_WRTQOSCON_START ... FIMD_WRTQOSCON_END:

        return s->window[(offset - FIMD_WRTQOSCON_START) >> 2].rtqoscon;

    case FIMD_I80IFCMD_START ... FIMD_I80IFCMD_END:

        return s->i80ifcmd[(offset - FIMD_I80IFCMD_START) >> 2];

    case FIMD_VIDW0ADD0_B2 ... FIMD_VIDW4ADD0_B2:

        if (offset & 0x0004) {

            break;

        }

        return s->window[(offset - FIMD_VIDW0ADD0_B2) >> 3].buf_start[2];

    case FIMD_SHD_ADD0_START ... FIMD_SHD_ADD0_END:

        if (offset & 0x0004) {

            break;

        }

        return s->window[(offset - FIMD_SHD_ADD0_START) >> 3].shadow_buf_start;

    case FIMD_SHD_ADD1_START ... FIMD_SHD_ADD1_END:

        if (offset & 0x0004) {

            break;

        }

        return s->window[(offset - FIMD_SHD_ADD1_START) >> 3].shadow_buf_end;

    case FIMD_SHD_ADD2_START ... FIMD_SHD_ADD2_END:

        return s->window[(offset - FIMD_SHD_ADD2_START) >> 2].shadow_buf_size;

    case FIMD_PAL_MEM_START ... FIMD_PAL_MEM_END:

        w = (offset - FIMD_PAL_MEM_START) >> 10;

        i = ((offset - FIMD_PAL_MEM_START) >> 2) & 0xFF;

        return s->window[w].palette[i];

    case FIMD_PALMEM_AL_START ... FIMD_PALMEM_AL_END:

        /* Palette aliases for win 0,1 */

        w = (offset - FIMD_PALMEM_AL_START) >> 10;

        i = ((offset - FIMD_PALMEM_AL_START) >> 2) & 0xFF;

        return s->window[w].palette[i];

    }

    DPRINT_ERROR("bad read offset 0x%08x\n", offset);

    return 0xBAADBAAD;

}


float64 HELPER(ucf64_absd)(float64 a)

{

    return float64_abs(a);

}


static CharDriverState *qemu_chr_open_null(const char *id,

                                           ChardevBackend *backend,

                                           ChardevReturn *ret,

                                           Error **errp)

{

    CharDriverState *chr;

    ChardevCommon *common = backend->u.null;

    chr = qemu_chr_alloc(common, errp);

    if (!chr) {

        return NULL;

    }

    chr->chr_write = null_chr_write;

    chr->explicit_be_open = true;

    return chr;

}


static int packet_enqueue(CompareState *s, int mode)

{

    ConnectionKey key;

    Packet *pkt = NULL;

    Connection *conn;

    if (mode == PRIMARY_IN) {

        pkt = packet_new(s->pri_rs.buf,

                         s->pri_rs.packet_len,

                         s->pri_rs.vnet_hdr_len);

    } else {

        pkt = packet_new(s->sec_rs.buf,

                         s->sec_rs.packet_len,

                         s->sec_rs.vnet_hdr_len);

    }

    if (parse_packet_early(pkt)) {

        packet_destroy(pkt, NULL);

        pkt = NULL;

        return -1;

    }

    fill_connection_key(pkt, &key);

    conn = connection_get(s->connection_track_table,

                          &key,

                          &s->conn_list);

    if (!conn->processing) {

        g_queue_push_tail(&s->conn_list, conn);

        conn->processing = true;

    }

    if (mode == PRIMARY_IN) {

        if (!colo_insert_packet(&conn->primary_list, pkt)) {

            error_report("colo compare primary queue size too big,"

                         "drop packet");

        }

    } else {

        if (!colo_insert_packet(&conn->secondary_list, pkt)) {

            error_report("colo compare secondary queue size too big,"

                         "drop packet");

        }

    }

    return 0;

}


enum CodecID av_codec_get_id(const AVCodecTag *tags[4], unsigned int tag)

{

    int i;

    for(i=0; i<4 && tags[i]; i++){

        enum CodecID id= codec_get_id(tags[i], tag);

        if(id!=CODEC_ID_NONE) return id;

    }

    return CODEC_ID_NONE;

}


static void ide_atapi_identify(IDEState *s)

{

    uint16_t *p;

    if (s->identify_set) {

	memcpy(s->io_buffer, s->identify_data, sizeof(s->identify_data));

	return;

    }

    memset(s->io_buffer, 0, 512);

    p = (uint16_t *)s->io_buffer;

    /* Removable CDROM, 50us response, 12 byte packets */

    put_le16(p + 0, (2 << 14) | (5 << 8) | (1 << 7) | (2 << 5) | (0 << 0));

    padstr((char *)(p + 10), s->drive_serial_str, 20); /* serial number */

    put_le16(p + 20, 3); /* buffer type */

    put_le16(p + 21, 512); /* cache size in sectors */

    put_le16(p + 22, 4); /* ecc bytes */

    padstr((char *)(p + 23), s->version, 8); /* firmware version */

    padstr((char *)(p + 27), "QEMU DVD-ROM", 40); /* model */

    put_le16(p + 48, 1); /* dword I/O (XXX: should not be set on CDROM) */

#ifdef USE_DMA_CDROM

    put_le16(p + 49, 1 << 9 | 1 << 8); /* DMA and LBA supported */

    put_le16(p + 53, 7); /* words 64-70, 54-58, 88 valid */

    put_le16(p + 62, 7);  /* single word dma0-2 supported */

    put_le16(p + 63, 7);  /* mdma0-2 supported */

#else

    put_le16(p + 49, 1 << 9); /* LBA supported, no DMA */

    put_le16(p + 53, 3); /* words 64-70, 54-58 valid */

    put_le16(p + 63, 0x103); /* DMA modes XXX: may be incorrect */

#endif

    put_le16(p + 64, 3); /* pio3-4 supported */

    put_le16(p + 65, 0xb4); /* minimum DMA multiword tx cycle time */

    put_le16(p + 66, 0xb4); /* recommended DMA multiword tx cycle time */

    put_le16(p + 67, 0x12c); /* minimum PIO cycle time without flow control */

    put_le16(p + 68, 0xb4); /* minimum PIO cycle time with IORDY flow control */

    put_le16(p + 71, 30); /* in ns */

    put_le16(p + 72, 30); /* in ns */

    if (s->ncq_queues) {

        put_le16(p + 75, s->ncq_queues - 1);

        /* NCQ supported */

        put_le16(p + 76, (1 << 8));

    }

    put_le16(p + 80, 0x1e); /* support up to ATA/ATAPI-4 */

#ifdef USE_DMA_CDROM

    put_le16(p + 88, 0x3f | (1 << 13)); /* udma5 set and supported */

#endif

    memcpy(s->identify_data, p, sizeof(s->identify_data));

    s->identify_set = 1;

}


static int kvm_put_xsave(CPUState *env)

{

#ifdef KVM_CAP_XSAVE

    int i, r;

    struct kvm_xsave* xsave;

    uint16_t cwd, swd, twd, fop;

    if (!kvm_has_xsave())

        return kvm_put_fpu(env);

    xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));

    memset(xsave, 0, sizeof(struct kvm_xsave));

    cwd = swd = twd = fop = 0;

    swd = env->fpus & ~(7 << 11);

    swd |= (env->fpstt & 7) << 11;

    cwd = env->fpuc;

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

        twd |= (!env->fptags[i]) << i;

    xsave->region[0] = (uint32_t)(swd << 16) + cwd;

    xsave->region[1] = (uint32_t)(fop << 16) + twd;

    memcpy(&xsave->region[XSAVE_ST_SPACE], env->fpregs,

            sizeof env->fpregs);

    memcpy(&xsave->region[XSAVE_XMM_SPACE], env->xmm_regs,

            sizeof env->xmm_regs);

    xsave->region[XSAVE_MXCSR] = env->mxcsr;

    *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV] = env->xstate_bv;

    memcpy(&xsave->region[XSAVE_YMMH_SPACE], env->ymmh_regs,

            sizeof env->ymmh_regs);

    r = kvm_vcpu_ioctl(env, KVM_SET_XSAVE, xsave);

    qemu_free(xsave);

    return r;

#else

    return kvm_put_fpu(env);

#endif

}


static inline void blockCopy(uint8_t dst[], int dstStride, uint8_t src[], int srcStride,

	int numLines, int levelFix)

{

	int i;

	if(levelFix)

	{

#ifdef HAVE_MMX

					asm volatile(

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

						"movl %%eax, temp0\n\t"

						"pushl %0 \n\t"

						"pushl %1 \n\t"

						"leal (%2,%2), %%eax	\n\t"

						"leal (%3,%3), %%ebx	\n\t"

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

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

						"pxor %%mm4, %%mm4	\n\t"

#define SCALED_CPY					\

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

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

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

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

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

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

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

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

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

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

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

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

						"movq %%mm0, (%1)	\n\t"\

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

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

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

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

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

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

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

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

						"movq %%mm1, (%1, %3)	\n\t"\

						"1:			\n\t"

SCALED_CPY

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

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

SCALED_CPY

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

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

						"decl temp0		\n\t"

						"jnz 1b			\n\t"

						"popl %1 \n\t"

						"popl %0 \n\t"

						: : "r" (src),

						"r" (dst),

						"r" (srcStride),

						"r" (dstStride),

						"m" (numLines>>2)

						: "%eax", "%ebx"

					);

#else

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

					memcpy(	&(dst[dstStride*i]),

						&(src[srcStride*i]), BLOCK_SIZE);

#endif

	}

	else

	{

#ifdef HAVE_MMX

					asm volatile(

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

						"movl %%eax, temp0\n\t"

						"pushl %0 \n\t"

						"pushl %1 \n\t"

						"leal (%2,%2), %%eax	\n\t"

						"leal (%3,%3), %%ebx	\n\t"

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

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

#define SIMPLE_CPY					\

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

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

						"movq %%mm0, (%1)	\n\t"\

						"movq %%mm1, (%1, %3)	\n\t"\

						"1:			\n\t"

SIMPLE_CPY

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

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

SIMPLE_CPY

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

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

						"decl temp0		\n\t"

						"jnz 1b			\n\t"

						"popl %1 \n\t"

						"popl %0 \n\t"

						: : "r" (src),

						"r" (dst),

						"r" (srcStride),

						"r" (dstStride),

						"m" (numLines>>2)

						: "%eax", "%ebx"

					);

#else

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

					memcpy(	&(dst[dstStride*i]),

						&(src[srcStride*i]), BLOCK_SIZE);

#endif

	}

}


build_tpm2(GArray *table_data, BIOSLinker *linker)

{

    Acpi20TPM2 *tpm2_ptr;

    tpm2_ptr = acpi_data_push(table_data, sizeof *tpm2_ptr);

    tpm2_ptr->platform_class = cpu_to_le16(TPM2_ACPI_CLASS_CLIENT);

    tpm2_ptr->control_area_address = cpu_to_le64(0);

    tpm2_ptr->start_method = cpu_to_le32(TPM2_START_METHOD_MMIO);

    build_header(linker, table_data,

                 (void *)tpm2_ptr, "TPM2", sizeof(*tpm2_ptr), 4, NULL, NULL);

}


int ff_hevc_output_frame(HEVCContext *s, AVFrame *out, int flush)

{

    do {

        int nb_output = 0;

        int min_poc   = INT_MAX;

        int i, min_idx, ret;

        if (s->sh.no_output_of_prior_pics_flag == 1) {

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

                HEVCFrame *frame = &s->DPB[i];

                if (!(frame->flags & HEVC_FRAME_FLAG_BUMPING) && frame->poc != s->poc &&

                        frame->sequence == s->seq_output) {

                    ff_hevc_unref_frame(s, frame, HEVC_FRAME_FLAG_OUTPUT);

                }

            }

        }

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

            HEVCFrame *frame = &s->DPB[i];

            if ((frame->flags & HEVC_FRAME_FLAG_OUTPUT) &&

                frame->sequence == s->seq_output) {

                nb_output++;

                if (frame->poc < min_poc) {

                    min_poc = frame->poc;

                    min_idx = i;

                }

            }

        }

        /* wait for more frames before output */

        if (!flush && s->seq_output == s->seq_decode && s->sps &&

            nb_output <= s->sps->temporal_layer[s->sps->max_sub_layers - 1].num_reorder_pics)

            return 0;

        if (nb_output) {

            HEVCFrame *frame = &s->DPB[min_idx];

            AVFrame *dst = out;

            AVFrame *src = frame->frame;

            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(src->format);

            int pixel_shift = !!(desc->comp[0].depth_minus1 > 7);

            ret = av_frame_ref(out, src);

            if (frame->flags & HEVC_FRAME_FLAG_BUMPING)

                ff_hevc_unref_frame(s, frame, HEVC_FRAME_FLAG_OUTPUT | HEVC_FRAME_FLAG_BUMPING);

            else

                ff_hevc_unref_frame(s, frame, HEVC_FRAME_FLAG_OUTPUT);

            if (ret < 0)

                return ret;

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

                int hshift = (i > 0) ? desc->log2_chroma_w : 0;

                int vshift = (i > 0) ? desc->log2_chroma_h : 0;

                int off = ((frame->window.left_offset >> hshift) << pixel_shift) +

                          (frame->window.top_offset   >> vshift) * dst->linesize[i];

                dst->data[i] += off;

            }

            av_log(s->avctx, AV_LOG_DEBUG,

                   "Output frame with POC %d.\n", frame->poc);

            return 1;

        }

        if (s->seq_output != s->seq_decode)

            s->seq_output = (s->seq_output + 1) & 0xff;

        else

            break;

    } while (1);

    return 0;

}


static int mpegaudio_parse(AVCodecParserContext *s1,

                           AVCodecContext *avctx,

                           uint8_t **poutbuf, int *poutbuf_size,

                           const uint8_t *buf, int buf_size)

{

    MpegAudioParseContext *s = s1->priv_data;

    int len, ret;

    uint32_t header;

    const uint8_t *buf_ptr;

    *poutbuf = NULL;

    *poutbuf_size = 0;

    buf_ptr = buf;

    while (buf_size > 0) {

	len = s->inbuf_ptr - s->inbuf;

	if (s->frame_size == 0) {

            /* special case for next header for first frame in free

               format case (XXX: find a simpler method) */

            if (s->free_format_next_header != 0) {

                s->inbuf[0] = s->free_format_next_header >> 24;

                s->inbuf[1] = s->free_format_next_header >> 16;

                s->inbuf[2] = s->free_format_next_header >> 8;

                s->inbuf[3] = s->free_format_next_header;

                s->inbuf_ptr = s->inbuf + 4;

                s->free_format_next_header = 0;

                goto got_header;

            }

	    /* no header seen : find one. We need at least MPA_HEADER_SIZE

               bytes to parse it */

	    len = MPA_HEADER_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

	    if (len > 0) {

		memcpy(s->inbuf_ptr, buf_ptr, len);

		buf_ptr += len;

		buf_size -= len;

		s->inbuf_ptr += len;

	    }

	    if ((s->inbuf_ptr - s->inbuf) >= MPA_HEADER_SIZE) {

            got_header:

		header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

		    (s->inbuf[2] << 8) | s->inbuf[3];

                ret = mpa_decode_header(avctx, header);

                if (ret < 0) {

		    /* no sync found : move by one byte (inefficient, but simple!) */

		    memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);

		    s->inbuf_ptr--;

                    dprintf("skip %x\n", header);

                    /* reset free format frame size to give a chance

                       to get a new bitrate */

                    s->free_format_frame_size = 0;

		} else {

                    s->frame_size = ret;

#if 0

                    /* free format: prepare to compute frame size */

		    if (decode_header(s, header) == 1) {

			s->frame_size = -1;

                    }

#endif

		}

	    }

        } else

#if 0

        if (s->frame_size == -1) {

            /* free format : find next sync to compute frame size */

	    len = MPA_MAX_CODED_FRAME_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

            if (len == 0) {

		/* frame too long: resync */

                s->frame_size = 0;

		memmove(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf - 1);

		s->inbuf_ptr--;

            } else {

                uint8_t *p, *pend;

                uint32_t header1;

                int padding;

                memcpy(s->inbuf_ptr, buf_ptr, len);

                /* check for header */

                p = s->inbuf_ptr - 3;

                pend = s->inbuf_ptr + len - 4;

                while (p <= pend) {

                    header = (p[0] << 24) | (p[1] << 16) |

                        (p[2] << 8) | p[3];

                    header1 = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

                        (s->inbuf[2] << 8) | s->inbuf[3];

                    /* check with high probability that we have a

                       valid header */

                    if ((header & SAME_HEADER_MASK) ==

                        (header1 & SAME_HEADER_MASK)) {

                        /* header found: update pointers */

                        len = (p + 4) - s->inbuf_ptr;

                        buf_ptr += len;

                        buf_size -= len;

                        s->inbuf_ptr = p;

                        /* compute frame size */

                        s->free_format_next_header = header;

                        s->free_format_frame_size = s->inbuf_ptr - s->inbuf;

                        padding = (header1 >> 9) & 1;

                        if (s->layer == 1)

                            s->free_format_frame_size -= padding * 4;

                        else

                            s->free_format_frame_size -= padding;

                        dprintf("free frame size=%d padding=%d\n",

                                s->free_format_frame_size, padding);

                        decode_header(s, header1);

                        goto next_data;

                    }

                    p++;

                }

                /* not found: simply increase pointers */

                buf_ptr += len;

                s->inbuf_ptr += len;

                buf_size -= len;

            }

	} else

#endif

        if (len < s->frame_size) {

            if (s->frame_size > MPA_MAX_CODED_FRAME_SIZE)

                s->frame_size = MPA_MAX_CODED_FRAME_SIZE;

	    len = s->frame_size - len;

	    if (len > buf_size)

		len = buf_size;

	    memcpy(s->inbuf_ptr, buf_ptr, len);

	    buf_ptr += len;

	    s->inbuf_ptr += len;

	    buf_size -= len;

	}

        //    next_data:

        if (s->frame_size > 0 &&

            (s->inbuf_ptr - s->inbuf) >= s->frame_size) {

            *poutbuf = s->inbuf;

            *poutbuf_size = s->inbuf_ptr - s->inbuf;

	    s->inbuf_ptr = s->inbuf;

	    s->frame_size = 0;

	    break;

	}

    }

    return buf_ptr - buf;

}


JNIEnv *ff_jni_attach_env(int *attached, void *log_ctx)

{

    int ret = 0;

    JNIEnv *env = NULL;

    *attached = 0;

    pthread_mutex_lock(&lock);

    if (java_vm == NULL && (java_vm = av_jni_get_java_vm(log_ctx)) == NULL) {

        av_log(log_ctx, AV_LOG_INFO, "Retrieving current Java virtual machine using Android JniInvocation wrapper\n");

        if (check_jni_invocation(log_ctx) == 0) {

            if ((java_vm = get_java_vm(NULL, log_ctx)) != NULL ||

                (java_vm = get_java_vm("libdvm.so", log_ctx)) != NULL ||

                (java_vm = get_java_vm("libart.so", log_ctx)) != NULL) {

                av_log(log_ctx, AV_LOG_INFO, "Found Java virtual machine using Android JniInvocation wrapper\n");

            }

        }

    }

    pthread_mutex_unlock(&lock);

    if (!java_vm) {

        av_log(log_ctx, AV_LOG_ERROR, "Could not retrieve a Java virtual machine\n");

        return NULL;

    }

    ret = (*java_vm)->GetEnv(java_vm, (void **)&env, JNI_VERSION_1_6);

    switch(ret) {

    case JNI_EDETACHED:

        if ((*java_vm)->AttachCurrentThread(java_vm, &env, NULL) != 0) {

            av_log(log_ctx, AV_LOG_ERROR, "Failed to attach the JNI environment to the current thread\n");

            env = NULL;

        } else {

            *attached = 1;

        }

        break;

    case JNI_OK:

        break;

    case JNI_EVERSION:

        av_log(log_ctx, AV_LOG_ERROR, "The specified JNI version is not supported\n");

        break;

    default:

        av_log(log_ctx, AV_LOG_ERROR, "Failed to get the JNI environment attached to this thread");

        break;

    }

    return env;

}


static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)

{

    BDRVQcow2State *s = bs->opaque;

    Qcow2COWRegion *start = &m->cow_start;

    Qcow2COWRegion *end = &m->cow_end;

    unsigned buffer_size;

    unsigned data_bytes = end->offset - (start->offset + start->nb_bytes);

    bool merge_reads;

    uint8_t *start_buffer, *end_buffer;

    QEMUIOVector qiov;

    int ret;

    assert(start->nb_bytes <= UINT_MAX - end->nb_bytes);

    assert(start->nb_bytes + end->nb_bytes <= UINT_MAX - data_bytes);

    assert(start->offset + start->nb_bytes <= end->offset);

    assert(!m->data_qiov || m->data_qiov->size == data_bytes);

    if (start->nb_bytes == 0 && end->nb_bytes == 0) {

        return 0;

    }

    /* If we have to read both the start and end COW regions and the

     * middle region is not too large then perform just one read

     * operation */

    merge_reads = start->nb_bytes && end->nb_bytes && data_bytes <= 16384;

    if (merge_reads) {

        buffer_size = start->nb_bytes + data_bytes + end->nb_bytes;

    } else {

        /* If we have to do two reads, add some padding in the middle

         * if necessary to make sure that the end region is optimally

         * aligned. */

        size_t align = bdrv_opt_mem_align(bs);

        assert(align > 0 && align <= UINT_MAX);

        assert(QEMU_ALIGN_UP(start->nb_bytes, align) <=

               UINT_MAX - end->nb_bytes);

        buffer_size = QEMU_ALIGN_UP(start->nb_bytes, align) + end->nb_bytes;

    }

    /* Reserve a buffer large enough to store all the data that we're

     * going to read */

    start_buffer = qemu_try_blockalign(bs, buffer_size);

    if (start_buffer == NULL) {

        return -ENOMEM;

    }

    /* The part of the buffer where the end region is located */

    end_buffer = start_buffer + buffer_size - end->nb_bytes;

    qemu_iovec_init(&qiov, 2 + (m->data_qiov ? m->data_qiov->niov : 0));

    qemu_co_mutex_unlock(&s->lock);

    /* First we read the existing data from both COW regions. We

     * either read the whole region in one go, or the start and end

     * regions separately. */

    if (merge_reads) {

        qemu_iovec_add(&qiov, start_buffer, buffer_size);

        ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);

    } else {

        qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);

        ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);

        if (ret < 0) {

            goto fail;

        }

        qemu_iovec_reset(&qiov);

        qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);

        ret = do_perform_cow_read(bs, m->offset, end->offset, &qiov);

    }

    if (ret < 0) {

        goto fail;

    }

    /* Encrypt the data if necessary before writing it */

    if (bs->encrypted) {

        if (!do_perform_cow_encrypt(bs, m->offset, start->offset,

                                    start_buffer, start->nb_bytes) ||

            !do_perform_cow_encrypt(bs, m->offset, end->offset,

                                    end_buffer, end->nb_bytes)) {

            ret = -EIO;

            goto fail;

        }

    }

    /* And now we can write everything. If we have the guest data we

     * can write everything in one single operation */

    if (m->data_qiov) {

        qemu_iovec_reset(&qiov);

        if (start->nb_bytes) {

            qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);

        }

        qemu_iovec_concat(&qiov, m->data_qiov, 0, data_bytes);

        if (end->nb_bytes) {

            qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);

        }

        /* NOTE: we have a write_aio blkdebug event here followed by

         * a cow_write one in do_perform_cow_write(), but there's only

         * one single I/O operation */

        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);

        ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);

    } else {

        /* If there's no guest data then write both COW regions separately */

        qemu_iovec_reset(&qiov);

        qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);

        ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);

        if (ret < 0) {

            goto fail;

        }

        qemu_iovec_reset(&qiov);

        qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);

        ret = do_perform_cow_write(bs, m->alloc_offset, end->offset, &qiov);

    }

fail:

    qemu_co_mutex_lock(&s->lock);

    /*

     * Before we update the L2 table to actually point to the new cluster, we

     * need to be sure that the refcounts have been increased and COW was

     * handled.

     */

    if (ret == 0) {

        qcow2_cache_depends_on_flush(s->l2_table_cache);

    }

    qemu_vfree(start_buffer);

    qemu_iovec_destroy(&qiov);

    return ret;

}


void sws_rgb2rgb_init(int flags)

{

#if HAVE_SSE2 || HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX

    if (flags & SWS_CPU_CAPS_SSE2)

        rgb2rgb_init_SSE2();

    else if (flags & SWS_CPU_CAPS_MMX2)

        rgb2rgb_init_MMX2();

    else if (flags & SWS_CPU_CAPS_3DNOW)

        rgb2rgb_init_3DNOW();

    else if (flags & SWS_CPU_CAPS_MMX)

        rgb2rgb_init_MMX();

    else

#endif /* HAVE_MMX2 || HAVE_AMD3DNOW || HAVE_MMX */

        rgb2rgb_init_C();

}


static double tget_double(GetByteContext *gb, int le)

{

    av_alias64 i = { .u64 = le ? bytestream2_get_le64(gb) : bytestream2_get_be64(gb)};

    return i.f64;

}


static void init_proc_power5plus(CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* Time base */

    gen_tbl(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_clear,

                 0x60000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_750FX_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_970_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 POWERPC970_HID5_INIT);

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* Memory management */

    /* XXX: not correct */

    gen_low_BATs(env);

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCFG, "MMUCFG",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, SPR_NOACCESS,

                 0x00000000); /* TOFIX */

    /* XXX : not implemented */

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000); /* TOFIX */

    spr_register(env, SPR_HIOR, "SPR_HIOR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_hior, &spr_write_hior,

                 0x00000000);

    spr_register(env, SPR_CTRL, "SPR_CTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_UCTRL, "SPR_UCTRL",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_VRSAVE, "SPR_VRSAVE",

                 &spr_read_generic, &spr_write_generic,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

#if !defined(CONFIG_USER_ONLY)

    env->slb_nr = 64;

#endif

    init_excp_970(env);

    env->dcache_line_size = 128;

    env->icache_line_size = 128;

    /* Allocate hardware IRQ controller */

    ppc970_irq_init(env);

    /* Can't find information on what this should be on reset.  This

     * value is the one used by 74xx processors. */

    vscr_init(env, 0x00010000);

}


static int64_t get_bit_rate(AVCodecContext *ctx)

{

    int64_t bit_rate;

    int bits_per_sample;

    switch (ctx->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

    case AVMEDIA_TYPE_DATA:

    case AVMEDIA_TYPE_SUBTITLE:

    case AVMEDIA_TYPE_ATTACHMENT:

        bit_rate = ctx->bit_rate;

        break;

    case AVMEDIA_TYPE_AUDIO:

        bits_per_sample = av_get_bits_per_sample(ctx->codec_id);

        bit_rate = bits_per_sample ? ctx->sample_rate * ctx->channels * bits_per_sample : ctx->bit_rate;

        break;

    default:

        bit_rate = 0;

        break;

    }

    return bit_rate;

}


static int mkv_write_codecprivate(AVFormatContext *s, AVIOContext *pb,

                                  AVCodecParameters *par,

                                  int native_id, int qt_id)

{

    AVIOContext *dyn_cp;

    uint8_t *codecpriv;

    int ret, codecpriv_size;

    ret = avio_open_dyn_buf(&dyn_cp);

    if (ret < 0)

        return ret;

    if (native_id) {

        ret = mkv_write_native_codecprivate(s, par, dyn_cp);

    } else if (par->codec_type == AVMEDIA_TYPE_VIDEO) {

        if (qt_id) {

            if (!par->codec_tag)

                par->codec_tag = ff_codec_get_tag(ff_codec_movvideo_tags,

                                                    par->codec_id);

            if (   ff_codec_get_id(ff_codec_movvideo_tags, par->codec_tag) == par->codec_id

                && (!par->extradata_size || ff_codec_get_id(ff_codec_movvideo_tags, AV_RL32(par->extradata + 4)) != par->codec_id)

            ) {

                int i;

                avio_wb32(dyn_cp, 0x5a + par->extradata_size);

                avio_wl32(dyn_cp, par->codec_tag);

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

                    avio_w8(dyn_cp, 0);

            }

            avio_write(dyn_cp, par->extradata, par->extradata_size);

        } else {

            if (!ff_codec_get_tag(ff_codec_bmp_tags, par->codec_id))

                av_log(s, AV_LOG_WARNING, "codec %s is not supported by this format\n",

                       avcodec_get_name(par->codec_id));

            if (!par->codec_tag)

                par->codec_tag = ff_codec_get_tag(ff_codec_bmp_tags,

                                                  par->codec_id);

            if (!par->codec_tag && par->codec_id != AV_CODEC_ID_RAWVIDEO) {

                av_log(s, AV_LOG_ERROR, "No bmp codec tag found for codec %s\n",

                       avcodec_get_name(par->codec_id));

                ret = AVERROR(EINVAL);

            }

            ff_put_bmp_header(dyn_cp, par, ff_codec_bmp_tags, 0, 0);

        }

    } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) {

        unsigned int tag;

        tag = ff_codec_get_tag(ff_codec_wav_tags, par->codec_id);

        if (!tag) {

            av_log(s, AV_LOG_ERROR, "No wav codec tag found for codec %s\n",

                   avcodec_get_name(par->codec_id));

            ret = AVERROR(EINVAL);

        }

        if (!par->codec_tag)

            par->codec_tag = tag;

        ff_put_wav_header(s, dyn_cp, par, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);

    }

    codecpriv_size = avio_close_dyn_buf(dyn_cp, &codecpriv);

    if (codecpriv_size)

        put_ebml_binary(pb, MATROSKA_ID_CODECPRIVATE, codecpriv,

                        codecpriv_size);

    av_free(codecpriv);

    return ret;

}


void ff_vp3_idct_dc_add_c(uint8_t *dest/*align 8*/, int line_size, const DCTELEM *block/*align 16*/){

    int i, dc = (block[0] + 15) >> 5;

    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP + dc;

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

        dest[0] = cm[dest[0]];

        dest[1] = cm[dest[1]];

        dest[2] = cm[dest[2]];

        dest[3] = cm[dest[3]];

        dest[4] = cm[dest[4]];

        dest[5] = cm[dest[5]];

        dest[6] = cm[dest[6]];

        dest[7] = cm[dest[7]];

        dest += line_size;

    }

}


void object_property_add_bool(Object *obj, const char *name,

                              bool (*get)(Object *, Error **),

                              void (*set)(Object *, bool, Error **),

                              Error **errp)

{

    BoolProperty *prop = g_malloc0(sizeof(*prop));

    prop->get = get;

    prop->set = set;

    object_property_add(obj, name, "bool",

                        get ? property_get_bool : NULL,

                        set ? property_set_bool : NULL,

                        property_release_bool,

                        prop, errp);

}


static inline int mirror(int v, int m){

    if     (v<0) return -v;

    else if(v>m) return 2*m-v;

    else         return v;

}


void virtio_blk_data_plane_stop(VirtIOBlockDataPlane *s)

{

    if (!s->started) {

        return;

    }

    s->started = false;

    trace_virtio_blk_data_plane_stop(s);

    /* Stop thread or cancel pending thread creation BH */

    if (s->start_bh) {

        qemu_bh_delete(s->start_bh);

        s->start_bh = NULL;

    } else {

        event_poll_notify(&s->event_poll);

        qemu_thread_join(&s->thread);

    }

    ioq_cleanup(&s->ioqueue);

    s->vdev->binding->set_host_notifier(s->vdev->binding_opaque, 0, false);

    event_poll_cleanup(&s->event_poll);

    /* Clean up guest notifier (irq) */

    s->vdev->binding->set_guest_notifiers(s->vdev->binding_opaque, 1, false);

    vring_teardown(&s->vring);

}


static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,

                              MOVTrack *track, AVStream *st)

{

    int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,

                                      track->timescale, AV_ROUND_UP);

    int version = duration < INT32_MAX ? 0 : 1;

    int flags   = MOV_TKHD_FLAG_IN_MOVIE;

    int rotation = 0;

    int group   = 0;

    uint32_t *display_matrix = NULL;

    int      display_matrix_size, i;

    if (st) {

        if (mov->per_stream_grouping)

            group = st->index;

        else

            group = st->codecpar->codec_type;

        display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,

                                                            &display_matrix_size);

        if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))

            display_matrix = NULL;

    }

    if (track->flags & MOV_TRACK_ENABLED)

        flags |= MOV_TKHD_FLAG_ENABLED;

    if (track->mode == MODE_ISM)

        version = 1;

    (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */

    ffio_wfourcc(pb, "tkhd");

    avio_w8(pb, version);

    avio_wb24(pb, flags);

    if (version == 1) {

        avio_wb64(pb, track->time);

        avio_wb64(pb, track->time);

    } else {

        avio_wb32(pb, track->time); /* creation time */

        avio_wb32(pb, track->time); /* modification time */

    }

    avio_wb32(pb, track->track_id); /* track-id */

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

    if (!track->entry && mov->mode == MODE_ISM)

        (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);

    else if (!track->entry)

        (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);

    else

        (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);

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

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

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

    avio_wb16(pb, group); /* alternate group) */

    /* Volume, only for audio */

    if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)

        avio_wb16(pb, 0x0100);

    else

        avio_wb16(pb, 0);

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

    /* Matrix structure */

    if (st && st->metadata) {

        AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);

        rotation = (rot && rot->value) ? atoi(rot->value) : 0;

    }

    if (display_matrix) {

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

            avio_wb32(pb, display_matrix[i]);

    } else if (rotation == 90) {

        write_matrix(pb,  0,  1, -1,  0, track->par->height, 0);

    } else if (rotation == 180) {

        write_matrix(pb, -1,  0,  0, -1, track->par->width, track->par->height);

    } else if (rotation == 270) {

        write_matrix(pb,  0, -1,  1,  0, 0, track->par->width);

    } else {

        write_matrix(pb,  1,  0,  0,  1, 0, 0);

    }

    /* Track width and height, for visual only */

    if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||

               track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {

        int64_t track_width_1616;

        if (track->mode == MODE_MOV) {

            track_width_1616 = track->par->width * 0x10000ULL;

        } else {

            track_width_1616 = av_rescale(st->sample_aspect_ratio.num,

                                                  track->par->width * 0x10000LL,

                                                  st->sample_aspect_ratio.den);

            if (!track_width_1616 ||

                track->height != track->par->height ||

                track_width_1616 > UINT32_MAX)

                track_width_1616 = track->par->width * 0x10000ULL;

        }

        if (track_width_1616 > UINT32_MAX) {

            av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");

            track_width_1616 = 0;

        }

        avio_wb32(pb, track_width_1616);

        if (track->height > 0xFFFF) {

            av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");

            avio_wb32(pb, 0);

        } else

            avio_wb32(pb, track->height * 0x10000U);

    } else {

        avio_wb32(pb, 0);

        avio_wb32(pb, 0);

    }

    return 0x5c;

}


static int vobsub_read_seek(AVFormatContext *s, int stream_index,

                            int64_t min_ts, int64_t ts, int64_t max_ts, int flags)

{

    MpegDemuxContext *vobsub = s->priv_data;

    /* Rescale requested timestamps based on the first stream (timebase is the

     * same for all subtitles stream within a .idx/.sub). Rescaling is done just

     * like in avformat_seek_file(). */

    if (stream_index == -1 && s->nb_streams != 1) {

        int i, ret = 0;

        AVRational time_base = s->streams[0]->time_base;

        ts = av_rescale_q(ts, AV_TIME_BASE_Q, time_base);

        min_ts = av_rescale_rnd(min_ts, time_base.den,

                                time_base.num * (int64_t)AV_TIME_BASE,

                                AV_ROUND_UP   | AV_ROUND_PASS_MINMAX);

        max_ts = av_rescale_rnd(max_ts, time_base.den,

                                time_base.num * (int64_t)AV_TIME_BASE,

                                AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);

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

            int r = ff_subtitles_queue_seek(&vobsub->q[i], s, stream_index,

                                            min_ts, ts, max_ts, flags);

            if (r < 0)

                ret = r;

        }

        return ret;

    }

    return ff_subtitles_queue_seek(&vobsub->q[stream_index], s, stream_index,

                                   min_ts, ts, max_ts, flags);

}


static av_cold int aac_encode_init(AVCodecContext *avctx)

{

    AACContext *s = avctx->priv_data;

    int ret = AVERROR(EINVAL);

    AACENC_InfoStruct info = { 0 };

    CHANNEL_MODE mode;

    AACENC_ERROR err;

    int aot = FF_PROFILE_AAC_LOW + 1;

    int sce = 0, cpe = 0;

    if ((err = aacEncOpen(&s->handle, 0, avctx->channels)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to open the encoder: %s\n",

               aac_get_error(err));

        goto error;

    }

    if (avctx->profile != FF_PROFILE_UNKNOWN)

        aot = avctx->profile + 1;

    if ((err = aacEncoder_SetParam(s->handle, AACENC_AOT, aot)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set the AOT %d: %s\n",

               aot, aac_get_error(err));

        goto error;

    }

    if (aot == FF_PROFILE_AAC_ELD + 1 && s->eld_sbr) {

        if ((err = aacEncoder_SetParam(s->handle, AACENC_SBR_MODE,

                                       1)) != AACENC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to enable SBR for ELD: %s\n",

                   aac_get_error(err));

            goto error;

        }

    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_SAMPLERATE,

                                   avctx->sample_rate)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set the sample rate %d: %s\n",

               avctx->sample_rate, aac_get_error(err));

        goto error;

    }

    switch (avctx->channels) {

    case 1: mode = MODE_1;       sce = 1; cpe = 0; break;

    case 2: mode = MODE_2;       sce = 0; cpe = 1; break;

    case 3: mode = MODE_1_2;     sce = 1; cpe = 1; break;

    case 4: mode = MODE_1_2_1;   sce = 2; cpe = 1; break;

    case 5: mode = MODE_1_2_2;   sce = 1; cpe = 2; break;

    case 6: mode = MODE_1_2_2_1; sce = 2; cpe = 2; break;

    default:

        av_log(avctx, AV_LOG_ERROR,

               "Unsupported number of channels %d\n", avctx->channels);

        goto error;

    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELMODE,

                                   mode)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR,

               "Unable to set channel mode %d: %s\n", mode, aac_get_error(err));

        goto error;

    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELORDER,

                                   1)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR,

               "Unable to set wav channel order %d: %s\n",

               mode, aac_get_error(err));

        goto error;

    }

    if (avctx->flags & CODEC_FLAG_QSCALE || s->vbr) {

        int mode = s->vbr ? s->vbr : avctx->global_quality;

        if (mode <  1 || mode > 5) {

            av_log(avctx, AV_LOG_WARNING,

                   "VBR quality %d out of range, should be 1-5\n", mode);

            mode = av_clip(mode, 1, 5);

        }

        av_log(avctx, AV_LOG_WARNING,

               "Note, the VBR setting is unsupported and only works with "

               "some parameter combinations\n");

        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATEMODE,

                                       mode)) != AACENC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set the VBR bitrate mode %d: %s\n",

                   mode, aac_get_error(err));

            goto error;

        }

    } else {

        if (avctx->bit_rate <= 0) {

            if (avctx->profile == FF_PROFILE_AAC_HE_V2) {

                sce = 1;

                cpe = 0;

            }

            avctx->bit_rate = (96*sce + 128*cpe) * avctx->sample_rate / 44;

            if (avctx->profile == FF_PROFILE_AAC_HE ||

                avctx->profile == FF_PROFILE_AAC_HE_V2 ||

                s->eld_sbr)

                avctx->bit_rate /= 2;

        }

        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATE,

                                       avctx->bit_rate)) != AACENC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set the bitrate %d: %s\n",

                   avctx->bit_rate, aac_get_error(err));

            goto error;

        }

    }

    /* Choose bitstream format - if global header is requested, use

     * raw access units, otherwise use ADTS. */

    if ((err = aacEncoder_SetParam(s->handle, AACENC_TRANSMUX,

                                   avctx->flags & CODEC_FLAG_GLOBAL_HEADER ? 0 : s->latm ? 10 : 2)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set the transmux format: %s\n",

               aac_get_error(err));

        goto error;

    }

    if (s->latm && s->header_period) {

        if ((err = aacEncoder_SetParam(s->handle, AACENC_HEADER_PERIOD,

                                       s->header_period)) != AACENC_OK) {

             av_log(avctx, AV_LOG_ERROR, "Unable to set header period: %s\n",

                    aac_get_error(err));

             goto error;

        }

    }

    /* If no signaling mode is chosen, use explicit hierarchical signaling

     * if using mp4 mode (raw access units, with global header) and

     * implicit signaling if using ADTS. */

    if (s->signaling < 0)

        s->signaling = avctx->flags & CODEC_FLAG_GLOBAL_HEADER ? 2 : 0;

    if ((err = aacEncoder_SetParam(s->handle, AACENC_SIGNALING_MODE,

                                   s->signaling)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set signaling mode %d: %s\n",

               s->signaling, aac_get_error(err));

        goto error;

    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_AFTERBURNER,

                                   s->afterburner)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set afterburner to %d: %s\n",

               s->afterburner, aac_get_error(err));

        goto error;

    }

    if (avctx->cutoff > 0) {

        if (avctx->cutoff < (avctx->sample_rate + 255) >> 8) {

            av_log(avctx, AV_LOG_ERROR, "cutoff valid range is %d-20000\n",

                   (avctx->sample_rate + 255) >> 8);

            goto error;

        }

        if ((err = aacEncoder_SetParam(s->handle, AACENC_BANDWIDTH,

                                       avctx->cutoff)) != AACENC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set the encoder bandwidth to %d: %s\n",

                   avctx->cutoff, aac_get_error(err));

            goto error;

        }

    }

    if ((err = aacEncEncode(s->handle, NULL, NULL, NULL, NULL)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to initialize the encoder: %s\n",

               aac_get_error(err));

        return AVERROR(EINVAL);

    }

    if ((err = aacEncInfo(s->handle, &info)) != AACENC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to get encoder info: %s\n",

               aac_get_error(err));

        goto error;

    }

#if FF_API_OLD_ENCODE_AUDIO

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

#endif

    avctx->frame_size = info.frameLength;

    avctx->delay      = info.encoderDelay;

    ff_af_queue_init(avctx, &s->afq);

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {

        avctx->extradata_size = info.confSize;

        avctx->extradata      = av_mallocz(avctx->extradata_size +

                                           FF_INPUT_BUFFER_PADDING_SIZE);

        if (!avctx->extradata) {

            ret = AVERROR(ENOMEM);

            goto error;

        }

        memcpy(avctx->extradata, info.confBuf, info.confSize);

    }

    return 0;

error:

    aac_encode_close(avctx);

    return ret;

}


static int vorbis_floor1_decode(vorbis_context *vc,

                                vorbis_floor_data *vfu, float *vec)

{

    vorbis_floor1 *vf = &vfu->t1;

    GetBitContext *gb = &vc->gb;

    uint16_t range_v[4] = { 256, 128, 86, 64 };

    unsigned range = range_v[vf->multiplier - 1];

    uint16_t floor1_Y[258];

    uint16_t floor1_Y_final[258];

    int floor1_flag[258];

    unsigned class, cdim, cbits, csub, cval, offset, i, j;

    int book, adx, ady, dy, off, predicted, err;

    if (!get_bits1(gb)) // silence

        return 1;

// Read values (or differences) for the floor's points

    floor1_Y[0] = get_bits(gb, ilog(range - 1));

    floor1_Y[1] = get_bits(gb, ilog(range - 1));

    av_dlog(NULL, "floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);

    offset = 2;

    for (i = 0; i < vf->partitions; ++i) {

        class = vf->partition_class[i];

        cdim   = vf->class_dimensions[class];

        cbits  = vf->class_subclasses[class];

        csub = (1 << cbits) - 1;

        cval = 0;

        av_dlog(NULL, "Cbits %u\n", cbits);

        if (cbits) // this reads all subclasses for this partition's class

            cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[class]].vlc.table,

                            vc->codebooks[vf->class_masterbook[class]].nb_bits, 3);

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

            book = vf->subclass_books[class][cval & csub];

            av_dlog(NULL, "book %d Cbits %u cval %u  bits:%d\n",

                    book, cbits, cval, get_bits_count(gb));

            cval = cval >> cbits;

            if (book > -1) {

                floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,

                vc->codebooks[book].nb_bits, 3);

            } else {

                floor1_Y[offset+j] = 0;

            }

            av_dlog(NULL, " floor(%d) = %d \n",

                    vf->list[offset+j].x, floor1_Y[offset+j]);

        }

        offset+=cdim;

    }

// Amplitude calculation from the differences

    floor1_flag[0] = 1;

    floor1_flag[1] = 1;

    floor1_Y_final[0] = floor1_Y[0];

    floor1_Y_final[1] = floor1_Y[1];

    for (i = 2; i < vf->x_list_dim; ++i) {

        unsigned val, highroom, lowroom, room, high_neigh_offs, low_neigh_offs;

        low_neigh_offs  = vf->list[i].low;

        high_neigh_offs = vf->list[i].high;

        dy  = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs];  // render_point begin

        adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;

        ady = FFABS(dy);

        err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);

        off = err / adx;

        if (dy < 0) {

            predicted = floor1_Y_final[low_neigh_offs] - off;

        } else {

            predicted = floor1_Y_final[low_neigh_offs] + off;

        } // render_point end

        val = floor1_Y[i];

        highroom = range-predicted;

        lowroom  = predicted;

        if (highroom < lowroom) {

            room = highroom * 2;

        } else {

            room = lowroom * 2;   // SPEC mispelling

        }

        if (val) {

            floor1_flag[low_neigh_offs]  = 1;

            floor1_flag[high_neigh_offs] = 1;

            floor1_flag[i]               = 1;

            if (val >= room) {

                if (highroom > lowroom) {

                    floor1_Y_final[i] = val - lowroom + predicted;

                } else {

                    floor1_Y_final[i] = predicted - val + highroom - 1;

                }

            } else {

                if (val & 1) {

                    floor1_Y_final[i] = predicted - (val + 1) / 2;

                } else {

                    floor1_Y_final[i] = predicted + val / 2;

                }

            }

        } else {

            floor1_flag[i]    = 0;

            floor1_Y_final[i] = predicted;

        }

        av_dlog(NULL, " Decoded floor(%d) = %u / val %u\n",

                vf->list[i].x, floor1_Y_final[i], val);

    }

// Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?

    ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);

    av_dlog(NULL, " Floor decoded\n");

    return 0;

}


static void colo_process_checkpoint(MigrationState *s)
{
    QIOChannelBuffer *bioc;
    QEMUFile *fb = NULL;
    int64_t current_time, checkpoint_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);
    Error *local_err = NULL;
    int ret;
    failover_init_state();
    s->rp_state.from_dst_file = qemu_file_get_return_path(s->to_dst_file);
    if (!s->rp_state.from_dst_file) {
        error_report("Open QEMUFile from_dst_file failed");
    /*
     * Wait for Secondary finish loading VM states and enter COLO
     * restore.
     */
    colo_receive_check_message(s->rp_state.from_dst_file,
                       COLO_MESSAGE_CHECKPOINT_READY, &local_err);
    if (local_err) {
    bioc = qio_channel_buffer_new(COLO_BUFFER_BASE_SIZE);
    fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
    object_unref(OBJECT(bioc));
    qemu_mutex_lock_iothread();
    vm_start();
    qemu_mutex_unlock_iothread();
    trace_colo_vm_state_change("stop", "run");
    while (s->state == MIGRATION_STATUS_COLO) {
        current_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);
        if (current_time - checkpoint_time <
            s->parameters.x_checkpoint_delay) {
            int64_t delay_ms;
            delay_ms = s->parameters.x_checkpoint_delay -
                       (current_time - checkpoint_time);
            g_usleep(delay_ms * 1000);
        ret = colo_do_checkpoint_transaction(s, bioc, fb);
        if (ret < 0) {
        checkpoint_time = qemu_clock_get_ms(QEMU_CLOCK_HOST);
out:
    /* Throw the unreported error message after exited from loop */
    if (local_err) {
        error_report_err(local_err);
    if (fb) {
        qemu_fclose(fb);
    if (s->rp_state.from_dst_file) {
        qemu_fclose(s->rp_state.from_dst_file);


static void pc_init1(QEMUMachineInitArgs *args,

                     int pci_enabled,

                     int kvmclock_enabled)

{

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq *smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    ISADevice *floppy;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    DeviceState *icc_bridge;

    FWCfgState *fw_cfg = NULL;

    PcGuestInfo *guest_info;

    if (xen_enabled() && xen_hvm_init(&ram_memory) != 0) {

        fprintf(stderr, "xen hardware virtual machine initialisation failed\n");

        exit(1);

    }

    icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE);

    object_property_add_child(qdev_get_machine(), "icc-bridge",

                              OBJECT(icc_bridge), NULL);

    pc_cpus_init(args->cpu_model, icc_bridge);

    if (kvm_enabled() && kvmclock_enabled) {

        kvmclock_create();

    }

    /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory).

     * If it doesn't, we need to split it in chunks below and above 4G.

     * In any case, try to make sure that guest addresses aligned at

     * 1G boundaries get mapped to host addresses aligned at 1G boundaries.

     * For old machine types, use whatever split we used historically to avoid

     * breaking migration.

     */

    if (args->ram_size >= 0xe0000000) {

        ram_addr_t lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000;

        above_4g_mem_size = args->ram_size - lowmem;

        below_4g_mem_size = lowmem;

    } else {

        above_4g_mem_size = 0;

        below_4g_mem_size = args->ram_size;

    }

    if (pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size);

    guest_info->has_acpi_build = has_acpi_build;

    guest_info->has_pci_info = has_pci_info;

    guest_info->isapc_ram_fw = !pci_enabled;

    if (smbios_defaults) {

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            args->machine->name);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        fw_cfg = pc_memory_init(system_memory,

                       args->kernel_filename, args->kernel_cmdline,

                       args->initrd_filename,

                       below_4g_mem_size, above_4g_mem_size,

                       rom_memory, &ram_memory, guest_info);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_irqchip_in_kernel()) {

        kvm_pc_setup_irq_routing(pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, args->ram_size,

                              below_4g_mem_size,

                              above_4g_mem_size,

                              pci_memory, ram_memory);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, system_io);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_irqchip_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        cpu_irq = pc_allocate_cpu_irq();

        i8259 = i8259_init(isa_bus, cpu_irq[0]);

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    if (pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    qdev_init_nofail(icc_bridge);

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL);

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, &floppy, xen_enabled(),

        0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, MAX_IDE_BUS);

    if (pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, args->boot_order,

                 floppy, idebus[0], idebus[1], rtc_state);

    if (pci_enabled && usb_enabled(false)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pci_enabled && acpi_enabled) {

        I2CBus *smbus;

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], *smi_irq,

                              kvm_enabled(), fw_cfg);

        smbus_eeprom_init(smbus, 8, NULL, 0);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

}


uint32_t wm8750_adc_dat(void *opaque)

{

    WM8750State *s = (WM8750State *) opaque;

    uint32_t *data;

    if (s->idx_in >= sizeof(s->data_in))

        wm8750_in_load(s);

    data = (uint32_t *) &s->data_in[s->idx_in];

    s->req_in -= 4;

    s->idx_in += 4;

    return *data;

}


static QmpInputVisitor *to_qiv(Visitor *v)

{

    return container_of(v, QmpInputVisitor, visitor);

}


static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    struct video_data *s = s1->priv_data;

    AVFrame *frame = s1->streams[0]->codec->coded_frame;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    int res;

    av_init_packet(pkt);

    if ((res = mmap_read_frame(s1, pkt)) < 0) {

        return res;

    }

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    if (frame && s->interlaced) {

        frame->interlaced_frame = 1;

        frame->top_field_first = s->top_field_first;

    }

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    return pkt->size;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = bonito_pcihost_initfn;

    dc->no_user = 1;

}


static int mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)

{

    uint32_t v, spf;

    MPADecodeHeader c;

    int vbrtag_size = 0;

    MP3DecContext *mp3 = s->priv_data;

    ffio_init_checksum(s->pb, ff_crcA001_update, 0);

    v = avio_rb32(s->pb);

    if(ff_mpa_check_header(v) < 0)

      return -1;

    if (avpriv_mpegaudio_decode_header(&c, v) == 0)

        vbrtag_size = c.frame_size;

    if(c.layer != 3)

        return -1;

    spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */

    mp3->frames = 0;

    mp3->size   = 0;

    mp3_parse_info_tag(s, st, &c, spf);

    mp3_parse_vbri_tag(s, st, base);

    if (!mp3->frames && !mp3->size)

        return -1;

    /* Skip the vbr tag frame */

    avio_seek(s->pb, base + vbrtag_size, SEEK_SET);

    if (mp3->frames)

        st->duration = av_rescale_q(mp3->frames, (AVRational){spf, c.sample_rate},

                                    st->time_base);

    if (mp3->size && mp3->frames && !mp3->is_cbr)

        st->codec->bit_rate = av_rescale(mp3->size, 8 * c.sample_rate, mp3->frames * (int64_t)spf);

    return 0;

}


void memory_region_iommu_replay_all(MemoryRegion *mr)

{

    IOMMUNotifier *notifier;

    IOMMU_NOTIFIER_FOREACH(notifier, mr) {

        memory_region_iommu_replay(mr, notifier, false);

    }

}


static int usb_uhci_piix3_initfn(PCIDevice *dev)

{

    UHCIState *s = DO_UPCAST(UHCIState, dev, dev);

    uint8_t *pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_82371SB_2);

    return usb_uhci_common_initfn(s);

}


static void mpegts_write_pmt(AVFormatContext *s, MpegTSService *service)

{

    MpegTSWrite *ts = s->priv_data;

    uint8_t data[1012], *q, *desc_length_ptr, *program_info_length_ptr;

    int val, stream_type, i;

    q = data;

    put16(&q, 0xe000 | service->pcr_pid);

    program_info_length_ptr = q;

    q += 2; /* patched after */

    /* put program info here */

    val = 0xf000 | (q - program_info_length_ptr - 2);

    program_info_length_ptr[0] = val >> 8;

    program_info_length_ptr[1] = val;

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

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

        MpegTSWriteStream *ts_st = st->priv_data;

        AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);

        switch(st->codec->codec_id) {

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            stream_type = STREAM_TYPE_VIDEO_MPEG2;

            break;

        case AV_CODEC_ID_MPEG4:

            stream_type = STREAM_TYPE_VIDEO_MPEG4;

            break;

        case AV_CODEC_ID_H264:

            stream_type = STREAM_TYPE_VIDEO_H264;

            break;

        case AV_CODEC_ID_CAVS:

            stream_type = STREAM_TYPE_VIDEO_CAVS;

            break;

        case AV_CODEC_ID_DIRAC:

            stream_type = STREAM_TYPE_VIDEO_DIRAC;

            break;

        case AV_CODEC_ID_MP2:

        case AV_CODEC_ID_MP3:

            stream_type = STREAM_TYPE_AUDIO_MPEG1;

            break;

        case AV_CODEC_ID_AAC:

            stream_type = (ts->flags & MPEGTS_FLAG_AAC_LATM) ? STREAM_TYPE_AUDIO_AAC_LATM : STREAM_TYPE_AUDIO_AAC;

            break;

        case AV_CODEC_ID_AAC_LATM:

            stream_type = STREAM_TYPE_AUDIO_AAC_LATM;

            break;

        case AV_CODEC_ID_AC3:

            stream_type = STREAM_TYPE_AUDIO_AC3;

            break;

        default:

            stream_type = STREAM_TYPE_PRIVATE_DATA;

            break;

        }

        *q++ = stream_type;

        put16(&q, 0xe000 | ts_st->pid);

        desc_length_ptr = q;

        q += 2; /* patched after */

        /* write optional descriptors here */

        switch(st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if(st->codec->codec_id==AV_CODEC_ID_EAC3){

                *q++=0x7a; // EAC3 descriptor see A038 DVB SI

                *q++=1; // 1 byte, all flags sets to 0

                *q++=0; // omit all fields...

            }

            if(st->codec->codec_id==AV_CODEC_ID_S302M){

                *q++ = 0x05; /* MPEG-2 registration descriptor*/

                *q++ = 4;

                *q++ = 'B';

                *q++ = 'S';

                *q++ = 'S';

                *q++ = 'D';

            }

            if (lang) {

                char *p;

                char *next = lang->value;

                uint8_t *len_ptr;

                *q++ = 0x0a; /* ISO 639 language descriptor */

                len_ptr = q++;

                *len_ptr = 0;

                for (p = lang->value; next && *len_ptr < 255 / 4 * 4; p = next + 1) {

                    next = strchr(p, ',');

                    if (strlen(p) != 3 && (!next || next != p + 3))

                        continue; /* not a 3-letter code */

                    *q++ = *p++;

                    *q++ = *p++;

                    *q++ = *p++;

                if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)

                    *q++ = 0x01;

                else if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)

                    *q++ = 0x02;

                else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)

                    *q++ = 0x03;

                else

                    *q++ = 0; /* undefined type */

                    *len_ptr += 4;

                }

                if (*len_ptr == 0)

                    q -= 2; /* no language codes were written */

            }

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            {

                const char default_language[] = "und";

                const char *language = lang && strlen(lang->value) >= 3 ? lang->value : default_language;

                if (st->codec->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {

                    uint8_t *len_ptr;

                    int extradata_copied = 0;

                    *q++ = 0x59; /* subtitling_descriptor */

                    len_ptr = q++;

                    while (strlen(language) >= 3 && (sizeof(data) - (q - data)) >= 8) { /* 8 bytes per DVB subtitle substream data */

                        *q++ = *language++;

                        *q++ = *language++;

                        *q++ = *language++;

                        /* Skip comma */

                        if (*language != '\0')

                            language++;

                        if (st->codec->extradata_size - extradata_copied >= 5) {

                            *q++ = st->codec->extradata[extradata_copied + 4]; /* subtitling_type */

                            memcpy(q, st->codec->extradata + extradata_copied, 4); /* composition_page_id and ancillary_page_id */

                            extradata_copied += 5;

                            q += 4;

                        } else {

                            /* subtitling_type:

                             * 0x10 - normal with no monitor aspect ratio criticality

                             * 0x20 - for the hard of hearing with no monitor aspect ratio criticality */

                            *q++ = (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) ? 0x20 : 0x10;

                            if ((st->codec->extradata_size == 4) && (extradata_copied == 0)) {

                                /* support of old 4-byte extradata format */

                                memcpy(q, st->codec->extradata, 4); /* composition_page_id and ancillary_page_id */

                                extradata_copied += 4;

                                q += 4;

                            } else {

                                put16(&q, 1); /* composition_page_id */

                                put16(&q, 1); /* ancillary_page_id */

                            }

                        }

                    }

                    *len_ptr = q - len_ptr - 1;

                } else if (st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) {

                    uint8_t *len_ptr = NULL;

                    int extradata_copied = 0;

                    /* The descriptor tag. teletext_descriptor */

                    *q++ = 0x56;

                    len_ptr = q++;

                    while (strlen(language) >= 3) {

                        *q++ = *language++;

                        *q++ = *language++;

                        *q++ = *language++;

                        /* Skip comma */

                        if (*language != '\0')

                            language++;

                        if (st->codec->extradata_size - 1 > extradata_copied) {

                            memcpy(q, st->codec->extradata + extradata_copied, 2);

                            extradata_copied += 2;

                            q += 2;

                        } else {

                            /* The Teletext descriptor:

                             * teletext_type: This 5-bit field indicates the type of Teletext page indicated. (0x01 Initial Teletext page)

                             * teletext_magazine_number: This is a 3-bit field which identifies the magazine number.

                             * teletext_page_number: This is an 8-bit field giving two 4-bit hex digits identifying the page number. */

                            *q++ = 0x08;

                            *q++ = 0x00;

                        }

                    }

                    *len_ptr = q - len_ptr - 1;

                 }

            }

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (stream_type == STREAM_TYPE_VIDEO_DIRAC) {

                *q++ = 0x05; /*MPEG-2 registration descriptor*/

                *q++ = 4;

                *q++ = 'd';

                *q++ = 'r';

                *q++ = 'a';

                *q++ = 'c';

            }

            break;

        case AVMEDIA_TYPE_DATA:

            if (st->codec->codec_id == AV_CODEC_ID_SMPTE_KLV) {

                *q++ = 0x05; /* MPEG-2 registration descriptor */

                *q++ = 4;

                *q++ = 'K';

                *q++ = 'L';

                *q++ = 'V';

                *q++ = 'A';

            }

            break;

        }

        val = 0xf000 | (q - desc_length_ptr - 2);

        desc_length_ptr[0] = val >> 8;

        desc_length_ptr[1] = val;

    }

    mpegts_write_section1(&service->pmt, PMT_TID, service->sid, ts->tables_version, 0, 0,

                          data, q - data);

}