static void vfio_map_bar(VFIOPCIDevice *vdev, int nr)

{

    VFIOBAR *bar = &vdev->bars[nr];

    uint64_t size = bar->region.size;

    char name[64];

    uint32_t pci_bar;

    uint8_t type;

    int ret;

    /* Skip both unimplemented BARs and the upper half of 64bit BARS. */

    if (!size) {

        return;

    }

    snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",

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

             vdev->host.function, nr);

    /* Determine what type of BAR this is for registration */

    ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),

                vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));

    if (ret != sizeof(pci_bar)) {

        error_report("vfio: Failed to read BAR %d (%m)", nr);

        return;

    }

    pci_bar = le32_to_cpu(pci_bar);

    bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);

    bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);

    type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :

                                    ~PCI_BASE_ADDRESS_MEM_MASK);

    /* A "slow" read/write mapping underlies all BARs */

    memory_region_init_io(&bar->region.mem, OBJECT(vdev), &vfio_region_ops,

                          bar, name, size);

    pci_register_bar(&vdev->pdev, nr, type, &bar->region.mem);

    /*

     * We can't mmap areas overlapping the MSIX vector table, so we

     * potentially insert a direct-mapped subregion before and after it.

     */

    if (vdev->msix && vdev->msix->table_bar == nr) {

        size = vdev->msix->table_offset & qemu_real_host_page_mask;

    }

    strncat(name, " mmap", sizeof(name) - strlen(name) - 1);

    if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,

                      &bar->region.mmap_mem, &bar->region.mmap,

                      size, 0, name)) {

        error_report("%s unsupported. Performance may be slow", name);

    }

    if (vdev->msix && vdev->msix->table_bar == nr) {

        uint64_t start;

        start = REAL_HOST_PAGE_ALIGN((uint64_t)vdev->msix->table_offset +

                                     (vdev->msix->entries *

                                      PCI_MSIX_ENTRY_SIZE));

        size = start < bar->region.size ? bar->region.size - start : 0;

        strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);

        /* VFIOMSIXInfo contains another MemoryRegion for this mapping */

        if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,

                          &vdev->msix->mmap_mem,

                          &vdev->msix->mmap, size, start, name)) {

            error_report("%s unsupported. Performance may be slow", name);

        }

    }

    vfio_bar_quirk_setup(vdev, nr);

}


static void ich9_cc_write(void *opaque, hwaddr addr,

                          uint64_t val, unsigned len)

{

    ICH9LPCState *lpc = (ICH9LPCState *)opaque;

    ich9_cc_addr_len(&addr, &len);

    memcpy(lpc->chip_config + addr, &val, len);

    pci_bus_fire_intx_routing_notifier(lpc->d.bus);

    ich9_cc_update(lpc);

}


opts_type_int(Visitor *v, int64_t *obj, const char *name, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    const QemuOpt *opt;

    const char *str;

    long long val;

    char *endptr;

    if (ov->list_mode == LM_SIGNED_INTERVAL) {

        *obj = ov->range_next.s;

        return;

    }

    opt = lookup_scalar(ov, name, errp);

    if (!opt) {

        return;

    }

    str = opt->str ? opt->str : "";

    /* we've gotten past lookup_scalar() */

    assert(ov->list_mode == LM_NONE || ov->list_mode == LM_IN_PROGRESS);

    errno = 0;

    val = strtoll(str, &endptr, 0);

    if (errno == 0 && endptr > str && INT64_MIN <= val && val <= INT64_MAX) {

        if (*endptr == '\0') {

            *obj = val;

            processed(ov, name);

            return;

        }

        if (*endptr == '-' && ov->list_mode == LM_IN_PROGRESS) {

            long long val2;

            str = endptr + 1;

            val2 = strtoll(str, &endptr, 0);

            if (errno == 0 && endptr > str && *endptr == '\0' &&

                INT64_MIN <= val2 && val2 <= INT64_MAX && val <= val2) {

                ov->range_next.s = val;

                ov->range_limit.s = val2;

                ov->list_mode = LM_SIGNED_INTERVAL;

                /* as if entering on the top */

                *obj = ov->range_next.s;

                return;

            }

        }

    }

    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,

              (ov->list_mode == LM_NONE) ? "an int64 value" :

                                           "an int64 value or range");

}


float32 HELPER(ucf64_df2sf)(float64 x, CPUUniCore32State *env)

{

    return float64_to_float32(x, &env->ucf64.fp_status);

}


static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,

                                     AVStream *st, int read_all)

{

    RMDemuxContext *rm = s->priv_data;

    char buf[256];

    uint32_t version;

    int i;

    /* ra type header */

    version = get_be32(pb); /* version */

    if (((version >> 16) & 0xff) == 3) {

        int64_t startpos = url_ftell(pb);

        /* very old version */

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

            get_byte(pb);

        get_str8(pb, s->title, sizeof(s->title));

        get_str8(pb, s->author, sizeof(s->author));

        get_str8(pb, s->copyright, sizeof(s->copyright));

        get_str8(pb, s->comment, sizeof(s->comment));

        if ((startpos + (version & 0xffff)) >= url_ftell(pb) + 2) {

            // fourcc (should always be "lpcJ")

            get_byte(pb);

            get_str8(pb, buf, sizeof(buf));

        }

        // Skip extra header crap (this should never happen)

        if ((startpos + (version & 0xffff)) > url_ftell(pb))

            url_fskip(pb, (version & 0xffff) + startpos - url_ftell(pb));

        st->codec->sample_rate = 8000;

        st->codec->channels = 1;

        st->codec->codec_type = CODEC_TYPE_AUDIO;

        st->codec->codec_id = CODEC_ID_RA_144;

    } else {

        int flavor, sub_packet_h, coded_framesize, sub_packet_size;

        /* old version (4) */

        get_be32(pb); /* .ra4 */

        get_be32(pb); /* data size */

        get_be16(pb); /* version2 */

        get_be32(pb); /* header size */

        flavor= get_be16(pb); /* add codec info / flavor */

        rm->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */

        get_be32(pb); /* ??? */

        get_be32(pb); /* ??? */

        get_be32(pb); /* ??? */

        rm->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */

        st->codec->block_align= get_be16(pb); /* frame size */

        rm->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */

        get_be16(pb); /* ??? */

        if (((version >> 16) & 0xff) == 5) {

            get_be16(pb); get_be16(pb); get_be16(pb);

        }

        st->codec->sample_rate = get_be16(pb);

        get_be32(pb);

        st->codec->channels = get_be16(pb);

        if (((version >> 16) & 0xff) == 5) {

            get_be32(pb);

            buf[0] = get_byte(pb);

            buf[1] = get_byte(pb);

            buf[2] = get_byte(pb);

            buf[3] = get_byte(pb);

            buf[4] = 0;

        } else {

            get_str8(pb, buf, sizeof(buf)); /* desc */

            get_str8(pb, buf, sizeof(buf)); /* desc */

        }

        st->codec->codec_type = CODEC_TYPE_AUDIO;

        if (!strcmp(buf, "dnet")) {

            st->codec->codec_id = CODEC_ID_AC3;

            st->need_parsing = AVSTREAM_PARSE_FULL;

        } else if (!strcmp(buf, "28_8")) {

            st->codec->codec_id = CODEC_ID_RA_288;

            st->codec->extradata_size= 0;

            rm->audio_framesize = st->codec->block_align;

            st->codec->block_align = coded_framesize;

            if(rm->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);

        } else if ((!strcmp(buf, "cook")) || (!strcmp(buf, "atrc")) || (!strcmp(buf, "sipr"))) {

            int codecdata_length, i;

            get_be16(pb); get_byte(pb);

            if (((version >> 16) & 0xff) == 5)

                get_byte(pb);

            codecdata_length = get_be32(pb);

            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                return -1;

            }

            if(sub_packet_size <= 0){

                av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");

                return -1;

            }

            if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;

            else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;

            else st->codec->codec_id = CODEC_ID_ATRAC3;

            st->codec->extradata_size= codecdata_length;

            st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

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

                ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);

            rm->audio_framesize = st->codec->block_align;

            st->codec->block_align = rm->sub_packet_size;

            if(rm->audio_framesize >= UINT_MAX / sub_packet_h){

                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");

                return -1;

            }

            rm->audiobuf = av_malloc(rm->audio_framesize * sub_packet_h);

        } else if (!strcmp(buf, "raac") || !strcmp(buf, "racp")) {

            int codecdata_length, i;

            get_be16(pb); get_byte(pb);

            if (((version >> 16) & 0xff) == 5)

                get_byte(pb);

            st->codec->codec_id = CODEC_ID_AAC;

            codecdata_length = get_be32(pb);

            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){

                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");

                return -1;

            }

            if (codecdata_length >= 1) {

                st->codec->extradata_size = codecdata_length - 1;

                st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                get_byte(pb);

                for(i = 0; i < st->codec->extradata_size; i++)

                    ((uint8_t*)st->codec->extradata)[i] = get_byte(pb);

            }

        } else {

            st->codec->codec_id = CODEC_ID_NONE;

            av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));

        }

        if (read_all) {

            get_byte(pb);

            get_byte(pb);

            get_byte(pb);

            get_str8(pb, s->title, sizeof(s->title));

            get_str8(pb, s->author, sizeof(s->author));

            get_str8(pb, s->copyright, sizeof(s->copyright));

            get_str8(pb, s->comment, sizeof(s->comment));

        }

    }

    return 0;

}


void ff_rv10_encode_picture_header(MpegEncContext *s, int picture_number)

{

    int full_frame= 0;

    avpriv_align_put_bits(&s->pb);

    put_bits(&s->pb, 1, 1);     /* marker */

    put_bits(&s->pb, 1, (s->pict_type == AV_PICTURE_TYPE_P));

    put_bits(&s->pb, 1, 0);     /* not PB frame */

    put_bits(&s->pb, 5, s->qscale);

    if (s->pict_type == AV_PICTURE_TYPE_I) {

        /* specific MPEG like DC coding not used */

    }

    /* if multiple packets per frame are sent, the position at which

       to display the macroblocks is coded here */

    if(!full_frame){

        put_bits(&s->pb, 6, 0); /* mb_x */

        put_bits(&s->pb, 6, 0); /* mb_y */

        put_bits(&s->pb, 12, s->mb_width * s->mb_height);

    }

    put_bits(&s->pb, 3, 0);     /* ignored */

}


int ff_cmap_read_palette(AVCodecContext *avctx, uint32_t *pal)

{

    int count, i;

    if (avctx->bits_per_coded_sample > 8) {

        av_log(avctx, AV_LOG_ERROR, "bit_per_coded_sample > 8 not supported\n");

        return AVERROR_INVALIDDATA;

    }

    count = 1 << avctx->bits_per_coded_sample;

    if (avctx->extradata_size < count * 3) {

        av_log(avctx, AV_LOG_ERROR, "palette data underflow\n");

        return AVERROR_INVALIDDATA;

    }

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

        pal[i] = 0xFF000000 | AV_RB24( avctx->extradata + i*3 );

    }

    return 0;

}


static CharDriverState* create_eventfd_chr_device(IVShmemState *s,

                                                  EventNotifier *n,

                                                  int vector)

{

    /* create a event character device based on the passed eventfd */

    PCIDevice *pdev = PCI_DEVICE(s);

    int eventfd = event_notifier_get_fd(n);

    CharDriverState *chr;

    s->msi_vectors[vector].pdev = pdev;

    chr = qemu_chr_open_eventfd(eventfd);

    if (chr == NULL) {

        error_report("creating chardriver for eventfd %d failed", eventfd);

        return NULL;

    }

    qemu_chr_fe_claim_no_fail(chr);

    /* if MSI is supported we need multiple interrupts */

    if (ivshmem_has_feature(s, IVSHMEM_MSI)) {

        s->msi_vectors[vector].pdev = PCI_DEVICE(s);

        qemu_chr_add_handlers(chr, ivshmem_can_receive, fake_irqfd,

                      ivshmem_event, &s->msi_vectors[vector]);

    } else {

        qemu_chr_add_handlers(chr, ivshmem_can_receive, ivshmem_receive,

                      ivshmem_event, s);

    }

    return chr;

}


void ff_hcscale_fast_mmxext(SwsContext *c, int16_t *dst1, int16_t *dst2,

                                 int dstWidth, const uint8_t *src1,

                                 const uint8_t *src2, int srcW, int xInc)

{

    int32_t *filterPos = c->hChrFilterPos;

    int16_t *filter    = c->hChrFilter;

    void    *mmxextFilterCode = c->chrMmxextFilterCode;

    int i;

#if ARCH_X86_64

    DECLARE_ALIGNED(8, uint64_t, retsave);

#else

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

#endif

    __asm__ volatile(

#if ARCH_X86_64

        "mov          -8(%%rsp), %%"FF_REG_a"    \n\t"

        "mov       %%"FF_REG_a", %7              \n\t"  // retsave

#else

#if defined(PIC)

        "mov       %%"FF_REG_b", %7              \n\t"  // ebxsave

#endif

#endif

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

        "mov                 %0, %%"FF_REG_c"    \n\t"

        "mov                 %1, %%"FF_REG_D"    \n\t"

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

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

        "xor          %%"FF_REG_a", %%"FF_REG_a" \n\t" // i

        PREFETCH"   (%%"FF_REG_c")               \n\t"

        PREFETCH" 32(%%"FF_REG_c")               \n\t"

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

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

        "xor          %%"FF_REG_a", %%"FF_REG_a" \n\t" // i

        "mov                    %5, %%"FF_REG_c" \n\t" // src2

        "mov                    %6, %%"FF_REG_D" \n\t" // dst2

        PREFETCH"   (%%"FF_REG_c")               \n\t"

        PREFETCH" 32(%%"FF_REG_c")               \n\t"

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

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

        CALL_MMXEXT_FILTER_CODE

#if ARCH_X86_64

        "mov                    %7, %%"FF_REG_a" \n\t"

        "mov          %%"FF_REG_a", -8(%%rsp)    \n\t"

#else

#if defined(PIC)

        "mov %7, %%"FF_REG_b"    \n\t"

#endif

#endif

        :: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),

           "m" (mmxextFilterCode), "m" (src2), "m"(dst2)

#if ARCH_X86_64

          ,"m"(retsave)

#else

#if defined(PIC)

          ,"m" (ebxsave)

#endif

#endif

        : "%"FF_REG_a, "%"FF_REG_c, "%"FF_REG_d, "%"FF_REG_S, "%"FF_REG_D

#if ARCH_X86_64 || !defined(PIC)

         ,"%"FF_REG_b

#endif

    );

    for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {

        dst1[i] = src1[srcW-1]*128;

        dst2[i] = src2[srcW-1]*128;

    }

}


static always_inline void gen_sradi (DisasContext *ctx, int n)

{

    int sh = SH(ctx->opcode) + (n << 5);

    if (sh != 0) {

        int l1, l2;

        TCGv t0;

        l1 = gen_new_label();

        l2 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_GE, cpu_gpr[rS(ctx->opcode)], 0, l1);

        t0 = tcg_temp_new(TCG_TYPE_TL);

        tcg_gen_andi_tl(t0, cpu_gpr[rS(ctx->opcode)], (1ULL << sh) - 1);

        tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);

        tcg_gen_ori_tl(cpu_xer, cpu_xer, 1 << XER_CA);

        tcg_gen_br(l2);

        gen_set_label(l1);

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_CA));

        gen_set_label(l2);

        tcg_gen_sari_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)], sh);

    } else {

        tcg_gen_mov_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);

        tcg_gen_andi_tl(cpu_xer, cpu_xer, ~(1 << XER_CA));

    }

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

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

}


static inline int wnv1_get_code(WNV1Context *w, int base_value)

{

    int v = get_vlc2(&w->gb, code_vlc.table, CODE_VLC_BITS, 1);

    if (v == 15)

        return ff_reverse[get_bits(&w->gb, 8 - w->shift)];

    else

        return base_value + ((v - 7) << w->shift);

}


static void cirrus_mem_writeb_mode4and5_16bpp(CirrusVGAState * s,

					      unsigned mode,

					      unsigned offset,

					      uint32_t mem_value)

{

    int x;

    unsigned val = mem_value;

    uint8_t *dst;

    dst = s->vram_ptr + offset;

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

	if (val & 0x80) {

	    *dst = s->cirrus_shadow_gr1;

	    *(dst + 1) = s->gr[0x11];

	} else if (mode == 5) {

	    *dst = s->cirrus_shadow_gr0;

	    *(dst + 1) = s->gr[0x10];

	}

	val <<= 1;

	dst += 2;

    }

    cpu_physical_memory_set_dirty(s->vram_offset + offset);

    cpu_physical_memory_set_dirty(s->vram_offset + offset + 15);

}


static void raw_refresh_limits(BlockDriverState *bs, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    struct stat st;

    if (!fstat(s->fd, &st)) {

        if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {

            int ret = hdev_get_max_transfer_length(bs, s->fd);

            if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {

                bs->bl.max_transfer = pow2floor(ret);

    raw_probe_alignment(bs, s->fd, errp);

    bs->bl.min_mem_alignment = s->buf_align;

    bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());


int av_image_get_linesize(enum PixelFormat pix_fmt, int width, int plane)

{

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];

    int max_step     [4];       /* max pixel step for each plane */

    int max_step_comp[4];       /* the component for each plane which has the max pixel step */

    int s;

    if (desc->flags & PIX_FMT_BITSTREAM)

        return (width * (desc->comp[0].step_minus1+1) + 7) >> 3;

    av_image_fill_max_pixsteps(max_step, max_step_comp, desc);

    s = (max_step_comp[plane] == 1 || max_step_comp[plane] == 2) ? desc->log2_chroma_w : 0;

    return max_step[plane] * (((width + (1 << s) - 1)) >> s);

}


rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,

                  AVPacket *pkt, uint32_t *timestamp,

                  const uint8_t *buf, int len, uint16_t rtp_seq, int flags)

{

    int seq = 1, res;

    AVIOContext pb;

    if (!rdt->rmctx)

        return AVERROR(EINVAL);

    if (rdt->audio_pkt_cnt == 0) {

        int pos;

        ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);

        flags = (flags & RTP_FLAG_KEY) ? 2 : 0;

        res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,

                                  &seq, flags, *timestamp);

        pos = avio_tell(&pb);

        if (res < 0)

            return res;

        if (res > 0) {

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

                memcpy (rdt->buffer, buf + pos, len - pos);

                rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,

                                                    NULL, NULL, NULL, NULL);

            }

            goto get_cache;

        }

    } else {

get_cache:

        rdt->audio_pkt_cnt =

            ff_rm_retrieve_cache (rdt->rmctx, rdt->rmctx->pb,

                                  st, rdt->rmst[st->index], pkt);

        if (rdt->audio_pkt_cnt == 0 &&

            st->codec->codec_id == AV_CODEC_ID_AAC)

            av_freep(&rdt->rmctx->pb);

    }

    pkt->stream_index = st->index;

    pkt->pts = *timestamp;

    return rdt->audio_pkt_cnt > 0;

}


static BlockBackend *img_open_file(const char *filename,

                                   QDict *options,

                                   const char *fmt, int flags,

                                   bool writethrough, bool quiet,

                                   bool force_share)

{

    BlockBackend *blk;

    Error *local_err = NULL;

    if (!options) {

        options = qdict_new();

    }

    if (fmt) {

        qdict_put_str(options, "driver", fmt);

    }

    if (force_share) {

        qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);

    }

    blk = blk_new_open(filename, NULL, options, flags, &local_err);

    if (!blk) {

        error_reportf_err(local_err, "Could not open '%s': ", filename);

        return NULL;

    }

    blk_set_enable_write_cache(blk, !writethrough);

    if (img_open_password(blk, filename, flags, quiet) < 0) {

        blk_unref(blk);

        return NULL;

    }

    return blk;

}


ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,

                      AVStream *st, RMStream *ast, AVPacket *pkt)

{

    RMDemuxContext *rm = s->priv_data;

    assert (rm->audio_pkt_cnt > 0);

    if (ast->deint_id == DEINT_ID_VBRF ||

        ast->deint_id == DEINT_ID_VBRS)

        av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);

    else {

        av_new_packet(pkt, st->codec->block_align);

        memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this

               (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),

               st->codec->block_align);

    }

    rm->audio_pkt_cnt--;

    if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {

        ast->audiotimestamp = AV_NOPTS_VALUE;

        pkt->flags = AV_PKT_FLAG_KEY;

    } else

        pkt->flags = 0;

    pkt->stream_index = st->index;

    return rm->audio_pkt_cnt;

}


int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)

{

    if (!pkt) {

        ctx->internal->eof = 1;

        return 0;

    }

    if (ctx->internal->eof) {

        av_log(ctx, AV_LOG_ERROR, "A non-NULL packet sent after an EOF.\n");

        return AVERROR(EINVAL);

    }

    if (ctx->internal->buffer_pkt->data ||

        ctx->internal->buffer_pkt->side_data_elems)

        return AVERROR(EAGAIN);

    av_packet_move_ref(ctx->internal->buffer_pkt, pkt);

    return 0;

}


static int refresh_thread(void *opaque)

{

    VideoState *is= opaque;

    while (!is->abort_request) {

        SDL_Event event;

        event.type = FF_REFRESH_EVENT;

        event.user.data1 = opaque;

        if (!is->refresh && (!is->paused || is->force_refresh)) {

            is->refresh = 1;

            SDL_PushEvent(&event);

        }

        //FIXME ideally we should wait the correct time but SDLs event passing is so slow it would be silly

        av_usleep(is->audio_st && is->show_mode != SHOW_MODE_VIDEO ? rdftspeed*1000 : 5000);

    }

    return 0;

}


void ff_hpeldsp_init_x86(HpelDSPContext *c, int flags)

{

    int cpu_flags = av_get_cpu_flags();

    if (INLINE_MMX(cpu_flags))

        hpeldsp_init_mmx(c, flags, cpu_flags);

    if (EXTERNAL_MMXEXT(cpu_flags))

        hpeldsp_init_mmxext(c, flags, cpu_flags);

    if (EXTERNAL_AMD3DNOW(cpu_flags))

        hpeldsp_init_3dnow(c, flags, cpu_flags);

    if (EXTERNAL_SSE2(cpu_flags))

        hpeldsp_init_sse2(c, flags, cpu_flags);

}


int av_opt_get(void *obj, const char *name, int search_flags, uint8_t **out_val)

{

    void *dst, *target_obj;

    const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);

    uint8_t *bin, buf[128];

    int len, i, ret;

    if (!o || !target_obj)

        return AVERROR_OPTION_NOT_FOUND;

    dst = (uint8_t*)target_obj + o->offset;

    buf[0] = 0;

    switch (o->type) {

    case AV_OPT_TYPE_FLAGS:     ret = snprintf(buf, sizeof(buf), "0x%08X",  *(int    *)dst);break;

    case AV_OPT_TYPE_INT:       ret = snprintf(buf, sizeof(buf), "%d" ,     *(int    *)dst);break;

    case AV_OPT_TYPE_INT64:     ret = snprintf(buf, sizeof(buf), "%"PRId64, *(int64_t*)dst);break;

    case AV_OPT_TYPE_FLOAT:     ret = snprintf(buf, sizeof(buf), "%f" ,     *(float  *)dst);break;

    case AV_OPT_TYPE_DOUBLE:    ret = snprintf(buf, sizeof(buf), "%f" ,     *(double *)dst);break;

    case AV_OPT_TYPE_RATIONAL:  ret = snprintf(buf, sizeof(buf), "%d/%d",   ((AVRational*)dst)->num, ((AVRational*)dst)->den);break;

    case AV_OPT_TYPE_STRING:

        if (*(uint8_t**)dst)

            *out_val = av_strdup(*(uint8_t**)dst);

        else

            *out_val = av_strdup("");

        return 0;

    case AV_OPT_TYPE_BINARY:

        len = *(int*)(((uint8_t *)dst) + sizeof(uint8_t *));

        if ((uint64_t)len*2 + 1 > INT_MAX)

            return AVERROR(EINVAL);

        if (!(*out_val = av_malloc(len*2 + 1)))

            return AVERROR(ENOMEM);

        bin = *(uint8_t**)dst;

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

            snprintf(*out_val + i*2, 3, "%02X", bin[i]);

        return 0;

    default:

        return AVERROR(EINVAL);

    }

    if (ret >= sizeof(buf))

        return AVERROR(EINVAL);

    *out_val = av_strdup(buf);

    return 0;

}


static int alac_set_info(ALACContext *alac)

{

    const unsigned char *ptr = alac->avctx->extradata;

    ptr += 4; /* size */

    ptr += 4; /* alac */

    ptr += 4; /* 0 ? */

    if(AV_RB32(ptr) >= UINT_MAX/4){

        av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");

        return -1;

    }

    /* buffer size / 2 ? */

    alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);

    ptr++;                          /* ??? */

    alac->setinfo_sample_size           = *ptr++;

    alac->setinfo_rice_historymult      = *ptr++;

    alac->setinfo_rice_initialhistory   = *ptr++;

    alac->setinfo_rice_kmodifier        = *ptr++;

    alac->numchannels                   = *ptr++;

    bytestream_get_be16(&ptr);      /* ??? */

    bytestream_get_be32(&ptr);      /* max coded frame size */

    bytestream_get_be32(&ptr);      /* bitrate ? */

    bytestream_get_be32(&ptr);      /* samplerate */

    return 0;

}


int ff_ivi_decode_blocks(GetBitContext *gb, IVIBandDesc *band, IVITile *tile)

{

    int         mbn, blk, num_blocks, num_coeffs, blk_size, scan_pos, run, val,

                pos, is_intra, mc_type, mv_x, mv_y, col_mask;

    uint8_t     col_flags[8];

    int32_t     prev_dc, trvec[64];

    uint32_t    cbp, sym, lo, hi, quant, buf_offs, q;

    IVIMbInfo   *mb;

    RVMapDesc   *rvmap = band->rv_map;

    void (*mc_with_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);

    void (*mc_no_delta_func)  (int16_t *buf, const int16_t *ref_buf, uint32_t pitch, int mc_type);

    const uint16_t  *base_tab;

    const uint8_t   *scale_tab;

    prev_dc = 0; /* init intra prediction for the DC coefficient */

    blk_size   = band->blk_size;

    col_mask   = blk_size - 1; /* column mask for tracking non-zero coeffs */

    num_blocks = (band->mb_size != blk_size) ? 4 : 1; /* number of blocks per mb */

    num_coeffs = blk_size * blk_size;

    if (blk_size == 8) {

        mc_with_delta_func = ff_ivi_mc_8x8_delta;

        mc_no_delta_func   = ff_ivi_mc_8x8_no_delta;

    } else {

        mc_with_delta_func = ff_ivi_mc_4x4_delta;

        mc_no_delta_func   = ff_ivi_mc_4x4_no_delta;

    }

    for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) {

        is_intra = !mb->type;

        cbp      = mb->cbp;

        buf_offs = mb->buf_offs;

        quant = av_clip(band->glob_quant + mb->q_delta, 0, 23);

        base_tab  = is_intra ? band->intra_base  : band->inter_base;

        scale_tab = is_intra ? band->intra_scale : band->inter_scale;

        if (scale_tab)

            quant = scale_tab[quant];

        if (!is_intra) {

            mv_x = mb->mv_x;

            mv_y = mb->mv_y;

            if (!band->is_halfpel) {

                mc_type = 0; /* we have only fullpel vectors */

            } else {

                mc_type = ((mv_y & 1) << 1) | (mv_x & 1);

                mv_x >>= 1;

                mv_y >>= 1; /* convert halfpel vectors into fullpel ones */

            }

        }

        for (blk = 0; blk < num_blocks; blk++) {

            /* adjust block position in the buffer according to its number */

            if (blk & 1) {

                buf_offs += blk_size;

            } else if (blk == 2) {

                buf_offs -= blk_size;

                buf_offs += blk_size * band->pitch;

            }

            if (cbp & 1) { /* block coded ? */

                scan_pos = -1;

                memset(trvec, 0, num_coeffs*sizeof(trvec[0])); /* zero transform vector */

                memset(col_flags, 0, sizeof(col_flags));      /* zero column flags */

                while (scan_pos <= num_coeffs) {

                    sym = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);

                    if (sym == rvmap->eob_sym)

                        break; /* End of block */

                    if (sym == rvmap->esc_sym) { /* Escape - run/val explicitly coded using 3 vlc codes */

                        run = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1) + 1;

                        lo  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);

                        hi  = get_vlc2(gb, band->blk_vlc.tab->table, IVI_VLC_BITS, 1);

                        val = IVI_TOSIGNED((hi << 6) | lo); /* merge them and convert into signed val */

                    } else {

                        if (sym >= 256U) {

                            av_log(NULL, AV_LOG_ERROR, "Invalid sym encountered: %d.\n", sym);

                            return -1;

                        }

                        run = rvmap->runtab[sym];

                        val = rvmap->valtab[sym];

                    }

                    /* de-zigzag and dequantize */

                    scan_pos += run;

                    if (scan_pos >= num_coeffs)

                        break;

                    pos = band->scan[scan_pos];

                    if (!val)

                        av_dlog(NULL, "Val = 0 encountered!\n");

                    q = (base_tab[pos] * quant) >> 9;

                    if (q > 1)

                        val = val * q + FFSIGN(val) * (((q ^ 1) - 1) >> 1);

                    trvec[pos] = val;

                    col_flags[pos & col_mask] |= !!val; /* track columns containing non-zero coeffs */

                }// while

                if (scan_pos >= num_coeffs && sym != rvmap->eob_sym)

                    return -1; /* corrupt block data */

                /* undoing DC coeff prediction for intra-blocks */

                if (is_intra && band->is_2d_trans) {

                    prev_dc      += trvec[0];

                    trvec[0]      = prev_dc;

                    col_flags[0] |= !!prev_dc;

                }

                /* apply inverse transform */

                band->inv_transform(trvec, band->buf + buf_offs,

                                    band->pitch, col_flags);

                /* apply motion compensation */

                if (!is_intra)

                    mc_with_delta_func(band->buf + buf_offs,

                                       band->ref_buf + buf_offs + mv_y * band->pitch + mv_x,

                                       band->pitch, mc_type);

            } else {

                /* block not coded */

                /* for intra blocks apply the dc slant transform */

                /* for inter - perform the motion compensation without delta */

                if (is_intra && band->dc_transform) {

                    band->dc_transform(&prev_dc, band->buf + buf_offs,

                                       band->pitch, blk_size);

                } else

                    mc_no_delta_func(band->buf + buf_offs,

                                     band->ref_buf + buf_offs + mv_y * band->pitch + mv_x,

                                     band->pitch, mc_type);

            }

            cbp >>= 1;

        }// for blk

    }// for mbn

    align_get_bits(gb);

    return 0;

}


void test_clone(void)

{

    uint8_t *stack1, *stack2;

    int pid1, pid2, status1, status2;

    stack1 = malloc(STACK_SIZE);

    pid1 = chk_error(clone(thread1_func, stack1 + STACK_SIZE,

                           CLONE_VM | CLONE_FS | CLONE_FILES | SIGCHLD, "hello1"));

    stack2 = malloc(STACK_SIZE);

    pid2 = chk_error(clone(thread2_func, stack2 + STACK_SIZE,

                           CLONE_VM | CLONE_FS | CLONE_FILES | SIGCHLD, "hello2"));

    while (waitpid(pid1, &status1, 0) != pid1);

    while (waitpid(pid2, &status2, 0) != pid2);

    if (thread1_res != 5 ||

        thread2_res != 6)

        error("clone");

}


static int h264_handle_packet(AVFormatContext *ctx,

                              PayloadContext *data,

                              AVStream *st,

                              AVPacket * pkt,

                              uint32_t * timestamp,

                              const uint8_t * buf,

                              int len, int flags)

{

    uint8_t nal = buf[0];

    uint8_t type = (nal & 0x1f);

    int result= 0;

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

#ifdef DEBUG

    assert(data);

    assert(data->cookie == MAGIC_COOKIE);

#endif

    assert(buf);

    if (type >= 1 && type <= 23)

        type = 1;              // simplify the case. (these are all the nal types used internally by the h264 codec)

    switch (type) {

    case 0:                    // undefined, but pass them through

    case 1:

        av_new_packet(pkt, len+sizeof(start_sequence));

        memcpy(pkt->data, start_sequence, sizeof(start_sequence));

        memcpy(pkt->data+sizeof(start_sequence), buf, len);

#ifdef DEBUG

        data->packet_types_received[nal & 0x1f]++;

#endif

        break;

    case 24:                   // STAP-A (one packet, multiple nals)

        // consume the STAP-A NAL

        buf++;

        len--;

        // first we are going to figure out the total size....

        {

            int pass= 0;

            int total_length= 0;

            uint8_t *dst= NULL;

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

                const uint8_t *src= buf;

                int src_len= len;

                do {

                    uint16_t nal_size = AV_RB16(src); // this going to be a problem if unaligned (can it be?)

                    // consume the length of the aggregate...

                    src += 2;

                    src_len -= 2;

                    if (nal_size <= src_len) {

                        if(pass==0) {

                            // counting...

                            total_length+= sizeof(start_sequence)+nal_size;

                        } else {

                            // copying

                            assert(dst);

                            memcpy(dst, start_sequence, sizeof(start_sequence));

                            dst+= sizeof(start_sequence);

                            memcpy(dst, src, nal_size);

#ifdef DEBUG

                            data->packet_types_received[*src & 0x1f]++;

#endif

                            dst+= nal_size;

                        }

                    } else {

                        av_log(ctx, AV_LOG_ERROR,

                               "nal size exceeds length: %d %d\n", nal_size, src_len);

                    }

                    // eat what we handled...

                    src += nal_size;

                    src_len -= nal_size;

                    if (src_len < 0)

                        av_log(ctx, AV_LOG_ERROR,

                               "Consumed more bytes than we got! (%d)\n", src_len);

                } while (src_len > 2);      // because there could be rtp padding..

                if(pass==0) {

                    // now we know the total size of the packet (with the start sequences added)

                    av_new_packet(pkt, total_length);

                    dst= pkt->data;

                } else {

                    assert(dst-pkt->data==total_length);

                }

            }

        }

        break;

    case 25:                   // STAP-B

    case 26:                   // MTAP-16

    case 27:                   // MTAP-24

    case 29:                   // FU-B

        av_log(ctx, AV_LOG_ERROR,

               "Unhandled type (%d) (See RFC for implementation details\n",

               type);

        result= -1;

        break;

    case 28:                   // FU-A (fragmented nal)

        buf++;

        len--;                  // skip the fu_indicator

        {

            // these are the same as above, we just redo them here for clarity...

            uint8_t fu_indicator = nal;

            uint8_t fu_header = *buf;   // read the fu_header.

            uint8_t start_bit = fu_header >> 7;

//            uint8_t end_bit = (fu_header & 0x40) >> 6;

            uint8_t nal_type = (fu_header & 0x1f);

            uint8_t reconstructed_nal;

            // reconstruct this packet's true nal; only the data follows..

            reconstructed_nal = fu_indicator & (0xe0);  // the original nal forbidden bit and NRI are stored in this packet's nal;

            reconstructed_nal |= nal_type;

            // skip the fu_header...

            buf++;

            len--;

#ifdef DEBUG

            if (start_bit)

                data->packet_types_received[nal_type]++;

#endif

            if(start_bit) {

                // copy in the start sequence, and the reconstructed nal....

                av_new_packet(pkt, sizeof(start_sequence)+sizeof(nal)+len);

                memcpy(pkt->data, start_sequence, sizeof(start_sequence));

                pkt->data[sizeof(start_sequence)]= reconstructed_nal;

                memcpy(pkt->data+sizeof(start_sequence)+sizeof(nal), buf, len);

            } else {

                av_new_packet(pkt, len);

                memcpy(pkt->data, buf, len);

            }

        }

        break;

    case 30:                   // undefined

    case 31:                   // undefined

    default:

        av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)", type);

        result= -1;

        break;

    }

    pkt->stream_index = st->index;

    return result;

}


static void wiener_denoise(WMAVoiceContext *s, int fcb_type,

                           float *synth_pf, int size,

                           const float *lpcs)

{

    int remainder, lim, n;

    if (fcb_type != FCB_TYPE_SILENCE) {

        float *tilted_lpcs = s->tilted_lpcs_pf,

              *coeffs = s->denoise_coeffs_pf, tilt_mem = 0;

        tilted_lpcs[0]           = 1.0;

        memcpy(&tilted_lpcs[1], lpcs, sizeof(lpcs[0]) * s->lsps);

        memset(&tilted_lpcs[s->lsps + 1], 0,

               sizeof(tilted_lpcs[0]) * (128 - s->lsps - 1));

        ff_tilt_compensation(&tilt_mem, 0.7 * tilt_factor(lpcs, s->lsps),

                             tilted_lpcs, s->lsps + 2);

        /* The IRDFT output (127 samples for 7-bit filter) beyond the frame

         * size is applied to the next frame. All input beyond this is zero,

         * and thus all output beyond this will go towards zero, hence we can

         * limit to min(size-1, 127-size) as a performance consideration. */

        remainder = FFMIN(127 - size, size - 1);

        calc_input_response(s, tilted_lpcs, fcb_type, coeffs, remainder);

        /* apply coefficients (in frequency spectrum domain), i.e. complex

         * number multiplication */

        memset(&synth_pf[size], 0, sizeof(synth_pf[0]) * (128 - size));

        ff_rdft_calc(&s->rdft, synth_pf);

        ff_rdft_calc(&s->rdft, coeffs);

        synth_pf[0] *= coeffs[0];

        synth_pf[1] *= coeffs[1];

        for (n = 1; n < 128; n++) {

            float v1 = synth_pf[n * 2], v2 = synth_pf[n * 2 + 1];

            synth_pf[n * 2]     = v1 * coeffs[n * 2] - v2 * coeffs[n * 2 + 1];

            synth_pf[n * 2 + 1] = v2 * coeffs[n * 2] + v1 * coeffs[n * 2 + 1];

        }

        ff_rdft_calc(&s->irdft, synth_pf);

    }

    /* merge filter output with the history of previous runs */

    if (s->denoise_filter_cache_size) {

        lim = FFMIN(s->denoise_filter_cache_size, size);

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

            synth_pf[n] += s->denoise_filter_cache[n];

        s->denoise_filter_cache_size -= lim;

        memmove(s->denoise_filter_cache, &s->denoise_filter_cache[size],

                sizeof(s->denoise_filter_cache[0]) * s->denoise_filter_cache_size);

    }

    /* move remainder of filter output into a cache for future runs */

    if (fcb_type != FCB_TYPE_SILENCE) {

        lim = FFMIN(remainder, s->denoise_filter_cache_size);

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

            s->denoise_filter_cache[n] += synth_pf[size + n];

        if (lim < remainder) {

            memcpy(&s->denoise_filter_cache[lim], &synth_pf[size + lim],

                   sizeof(s->denoise_filter_cache[0]) * (remainder - lim));

            s->denoise_filter_cache_size = remainder;

        }

    }

}


static av_always_inline int check_4block_inter(SnowContext *s, int mb_x, int mb_y, int p0, int p1, int ref, int *best_rd){

    const int b_stride= s->b_width << s->block_max_depth;

    BlockNode *block= &s->block[mb_x + mb_y * b_stride];

    BlockNode backup[4]= {block[0], block[1], block[b_stride], block[b_stride+1]};

    int rd, index, value;

    assert(mb_x>=0 && mb_y>=0);

    assert(mb_x<b_stride);

    assert(((mb_x|mb_y)&1) == 0);

    index= (p0 + 31*p1) & (ME_CACHE_SIZE-1);

    value= s->me_cache_generation + (p0>>10) + (p1<<6) + (block->ref<<12);

    if(s->me_cache[index] == value)

        return 0;

    s->me_cache[index]= value;

    block->mx= p0;

    block->my= p1;

    block->ref= ref;

    block->type &= ~BLOCK_INTRA;

    block[1]= block[b_stride]= block[b_stride+1]= *block;

    rd= get_4block_rd(s, mb_x, mb_y, 0);

//FIXME chroma

    if(rd < *best_rd){

        *best_rd= rd;

        return 1;

    }else{

        block[0]= backup[0];

        block[1]= backup[1];

        block[b_stride]= backup[2];

        block[b_stride+1]= backup[3];

        return 0;

    }

}


int qemu_signalfd(const sigset_t *mask)

{

#if defined(CONFIG_signalfd)

    int ret;

    ret = syscall(SYS_signalfd, -1, mask, _NSIG / 8);

    if (ret != -1)

        return ret;

#endif

    return qemu_signalfd_compat(mask);

}


static int vtd_dev_to_context_entry(IntelIOMMUState *s, uint8_t bus_num,

                                    uint8_t devfn, VTDContextEntry *ce)

{

    VTDRootEntry re;

    int ret_fr;

    ret_fr = vtd_get_root_entry(s, bus_num, &re);

    if (ret_fr) {

        return ret_fr;

    }

    if (!vtd_root_entry_present(&re)) {

        /* Not error - it's okay we don't have root entry. */

        trace_vtd_re_not_present(bus_num);

        return -VTD_FR_ROOT_ENTRY_P;

    } else if (re.rsvd || (re.val & VTD_ROOT_ENTRY_RSVD)) {

        trace_vtd_re_invalid(re.rsvd, re.val);

        return -VTD_FR_ROOT_ENTRY_RSVD;

    }

    ret_fr = vtd_get_context_entry_from_root(&re, devfn, ce);

    if (ret_fr) {

        return ret_fr;

    }

    if (!vtd_ce_present(ce)) {

        /* Not error - it's okay we don't have context entry. */

        trace_vtd_ce_not_present(bus_num, devfn);

        return -VTD_FR_CONTEXT_ENTRY_P;

    } else if ((ce->hi & VTD_CONTEXT_ENTRY_RSVD_HI) ||

               (ce->lo & VTD_CONTEXT_ENTRY_RSVD_LO)) {

        trace_vtd_ce_invalid(ce->hi, ce->lo);

        return -VTD_FR_CONTEXT_ENTRY_RSVD;

    }

    /* Check if the programming of context-entry is valid */

    if (!vtd_is_level_supported(s, vtd_ce_get_level(ce))) {

        trace_vtd_ce_invalid(ce->hi, ce->lo);

        return -VTD_FR_CONTEXT_ENTRY_INV;

    } else {

        switch (vtd_ce_get_type(ce)) {

        case VTD_CONTEXT_TT_MULTI_LEVEL:

            /* fall through */

        case VTD_CONTEXT_TT_DEV_IOTLB:

            break;

        default:

            trace_vtd_ce_invalid(ce->hi, ce->lo);

            return -VTD_FR_CONTEXT_ENTRY_INV;

        }

    }

    return 0;

}


static int get_buffer(AVCodecContext *avctx, AVFrame *pic)

{

    pic->type = FF_BUFFER_TYPE_USER;

    pic->data[0] = (void *)1;

    return 0;

}


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

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    switch (reg) {

    case 0: /* APSR */

        return xpsr_read(env) & 0xf8000000;

    case 1: /* IAPSR */

        return xpsr_read(env) & 0xf80001ff;

    case 2: /* EAPSR */

        return xpsr_read(env) & 0xff00fc00;

    case 3: /* xPSR */

        return xpsr_read(env) & 0xff00fdff;

    case 5: /* IPSR */

        return xpsr_read(env) & 0x000001ff;

    case 6: /* EPSR */

        return xpsr_read(env) & 0x0700fc00;

    case 7: /* IEPSR */

        return xpsr_read(env) & 0x0700edff;

    case 8: /* MSP */

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

    case 9: /* PSP */

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

    case 16: /* PRIMASK */

        return (env->daif & PSTATE_I) != 0;

    case 17: /* BASEPRI */

    case 18: /* BASEPRI_MAX */

        return env->v7m.basepri;

    case 19: /* FAULTMASK */

        return (env->daif & PSTATE_F) != 0;

    case 20: /* CONTROL */

        return env->v7m.control;

    default:

        /* ??? For debugging only.  */

        cpu_abort(CPU(cpu), "Unimplemented system register read (%d)\n", reg);

        return 0;

    }

}


static inline int RENAME(yuv420_rgb32)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

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

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*4 > dstStride[0]) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

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

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

YUV2RGB

		     /* convert RGB plane to RGB packed format,

			mm0 -> B, mm1 -> R, mm2 -> G, mm3 -> 0,

			mm4 -> GB, mm5 -> AR pixel 4-7,

			mm6 -> GB, mm7 -> AR pixel 0-3 */

		     "pxor %%mm3, %%mm3;" /* zero mm3 */

		     "movq %%mm0, %%mm6;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "movq %%mm1, %%mm7;" /* R7 R6 R5 R4 R3 R2 R1 R0 */

		     "movq %%mm0, %%mm4;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "movq %%mm1, %%mm5;" /* R7 R6 R5 R4 R3 R2 R1 R0 */

		     "punpcklbw %%mm2, %%mm6;" /* G3 B3 G2 B2 G1 B1 G0 B0 */

		     "punpcklbw %%mm3, %%mm7;" /* 00 R3 00 R2 00 R1 00 R0 */

		     "punpcklwd %%mm7, %%mm6;" /* 00 R1 B1 G1 00 R0 B0 G0 */

		     MOVNTQ " %%mm6, (%1);" /* Store ARGB1 ARGB0 */

		     "movq %%mm0, %%mm6;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "punpcklbw %%mm2, %%mm6;" /* G3 B3 G2 B2 G1 B1 G0 B0 */

		     "punpckhwd %%mm7, %%mm6;" /* 00 R3 G3 B3 00 R2 B3 G2 */

		     MOVNTQ " %%mm6, 8 (%1);" /* Store ARGB3 ARGB2 */

		     "punpckhbw %%mm2, %%mm4;" /* G7 B7 G6 B6 G5 B5 G4 B4 */

		     "punpckhbw %%mm3, %%mm5;" /* 00 R7 00 R6 00 R5 00 R4 */

		     "punpcklwd %%mm5, %%mm4;" /* 00 R5 B5 G5 00 R4 B4 G4 */

		     MOVNTQ " %%mm4, 16 (%1);" /* Store ARGB5 ARGB4 */

		     "movq %%mm0, %%mm4;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "punpckhbw %%mm2, %%mm4;" /* G7 B7 G6 B6 G5 B5 G4 B4 */

		     "punpckhwd %%mm5, %%mm4;" /* 00 R7 G7 B7 00 R6 B6 G6 */

		     MOVNTQ " %%mm4, 24 (%1);" /* Store ARGB7 ARGB6 */

		     "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "pxor %%mm4, %%mm4;" /* zero mm4 */

		     "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

		     "add $32, %1			\n\t"

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

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


static void qmp_tmp105_set_temperature(const char *id, int value)

{

    QDict *response;

    response = qmp("{ 'execute': 'qom-set', 'arguments': { 'path': '%s', "

                   "'property': 'temperature', 'value': %d } }", id, value);

    g_assert(qdict_haskey(response, "return"));

    QDECREF(response);

}


void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)

{

    struct capture_callback *cb;

    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {

        if (cb->opaque == cb_opaque) {

            cb->ops.destroy (cb_opaque);

            QLIST_REMOVE (cb, entries);

            g_free (cb);

            if (!cap->cb_head.lh_first) {

                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;

                while (sw) {

                    SWVoiceCap *sc = (SWVoiceCap *) sw;

#ifdef DEBUG_CAPTURE

                    dolog ("freeing %s\n", sw->name);

#endif

                    sw1 = sw->entries.le_next;

                    if (sw->rate) {

                        st_rate_stop (sw->rate);

                        sw->rate = NULL;

                    }

                    QLIST_REMOVE (sw, entries);

                    QLIST_REMOVE (sc, entries);

                    g_free (sc);

                    sw = sw1;

                }

                QLIST_REMOVE (cap, entries);

                g_free (cap);

            }

            return;

        }

    }

}


struct omap_sdrc_s *omap_sdrc_init(MemoryRegion *sysmem,

                                   hwaddr base)

{

    struct omap_sdrc_s *s = (struct omap_sdrc_s *)

            g_malloc0(sizeof(struct omap_sdrc_s));

    omap_sdrc_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_sdrc_ops, s, "omap.sdrc", 0x1000);

    memory_region_add_subregion(sysmem, base, &s->iomem);

    return s;

}


static int oggvorbis_decode_init(AVCodecContext *avccontext) {

    OggVorbisDecContext *context = avccontext->priv_data ;

    uint8_t *p= avccontext->extradata;

    int i, hsizes[3];

    unsigned char *headers[3], *extradata = avccontext->extradata;

    vorbis_info_init(&context->vi) ;

    vorbis_comment_init(&context->vc) ;

    if(! avccontext->extradata_size || ! p) {

        av_log(avccontext, AV_LOG_ERROR, "vorbis extradata absent\n");

        return -1;

    }

    if(p[0] == 0 && p[1] == 30) {

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

            hsizes[i] = bytestream_get_be16((const uint8_t **)&p);

            headers[i] = p;

            p += hsizes[i];

        }

    } else if(*p == 2) {

        unsigned int offset = 1;

        p++;

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

            hsizes[i] = 0;

            while((*p == 0xFF) && (offset < avccontext->extradata_size)) {

                hsizes[i] += 0xFF;

                offset++;

                p++;

            }

            if(offset >= avccontext->extradata_size - 1) {

                av_log(avccontext, AV_LOG_ERROR,

                       "vorbis header sizes damaged\n");

                return -1;

            }

            hsizes[i] += *p;

            offset++;

            p++;

        }

        hsizes[2] = avccontext->extradata_size - hsizes[0]-hsizes[1]-offset;

#if 0

        av_log(avccontext, AV_LOG_DEBUG,

               "vorbis header sizes: %d, %d, %d, / extradata_len is %d \n",

               hsizes[0], hsizes[1], hsizes[2], avccontext->extradata_size);

#endif

        headers[0] = extradata + offset;

        headers[1] = extradata + offset + hsizes[0];

        headers[2] = extradata + offset + hsizes[0] + hsizes[1];

    } else {

        av_log(avccontext, AV_LOG_ERROR,

               "vorbis initial header len is wrong: %d\n", *p);

        return -1;

    }

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

        context->op.b_o_s= i==0;

        context->op.bytes = hsizes[i];

        context->op.packet = headers[i];

        if(vorbis_synthesis_headerin(&context->vi, &context->vc, &context->op)<0){

            av_log(avccontext, AV_LOG_ERROR, "%d. vorbis header damaged\n", i+1);

            return -1;

        }

    }

    avccontext->channels = context->vi.channels;

    avccontext->sample_rate = context->vi.rate;

    avccontext->sample_fmt = AV_SAMPLE_FMT_S16;

    avccontext->time_base= (AVRational){1, avccontext->sample_rate};

    vorbis_synthesis_init(&context->vd, &context->vi);

    vorbis_block_init(&context->vd, &context->vb);

    return 0 ;

}


static CharDriverState *qemu_chr_open_pipe(QemuOpts *opts)

{

    int fd_in, fd_out;

    char filename_in[256], filename_out[256];

    const char *filename = qemu_opt_get(opts, "path");

    if (filename == NULL) {

        fprintf(stderr, "chardev: pipe: no filename given\n");

        return NULL;

    }

    snprintf(filename_in, 256, "%s.in", filename);

    snprintf(filename_out, 256, "%s.out", filename);

    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));

    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));

    if (fd_in < 0 || fd_out < 0) {

	if (fd_in >= 0)

	    close(fd_in);

	if (fd_out >= 0)

	    close(fd_out);

        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));

        if (fd_in < 0)

            return NULL;

    }

    return qemu_chr_open_fd(fd_in, fd_out);

}


yuv2rgb48_2_c_template(SwsContext *c, const int32_t *buf[2],

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf[2], uint16_t *dest, int dstW,

                       int yalpha, int uvalpha, int y,

                       enum AVPixelFormat target)

{

    const int32_t *buf0  = buf[0],  *buf1  = buf[1],

                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1];

    int  yalpha1 = 4096 - yalpha;

    int uvalpha1 = 4096 - uvalpha;

    int i;

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

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

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

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int R, G, B;

        Y1 -= c->yuv2rgb_y_offset;

        Y2 -= c->yuv2rgb_y_offset;

        Y1 *= c->yuv2rgb_y_coeff;

        Y2 *= c->yuv2rgb_y_coeff;

        Y1 += 1 << 13;

        Y2 += 1 << 13;

        R = V * c->yuv2rgb_v2r_coeff;

        G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

        B =                            U * c->yuv2rgb_u2b_coeff;

        output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

        output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

        output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

        output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

        output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

        output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

        dest += 6;

    }

}


static void filter_mb( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {

    MpegEncContext * const s = &h->s;

    const int mb_xy= mb_x + mb_y*s->mb_stride;

    const int mb_type = s->current_picture.mb_type[mb_xy];

    const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;

    int first_vertical_edge_done = 0;

    int dir;

    //for sufficiently low qp, filtering wouldn't do anything

    //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp

    if(!FRAME_MBAFF){

        int qp_thresh = 15 - h->slice_alpha_c0_offset - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]);

        int qp = s->current_picture.qscale_table[mb_xy];

        if(qp <= qp_thresh

           && (mb_x == 0 || ((qp + s->current_picture.qscale_table[mb_xy-1] + 1)>>1) <= qp_thresh)

           && (mb_y == 0 || ((qp + s->current_picture.qscale_table[h->top_mb_xy] + 1)>>1) <= qp_thresh)){

            return;

        }

    }

    if (FRAME_MBAFF

            // left mb is in picture

            && h->slice_table[mb_xy-1] != 255

            // and current and left pair do not have the same interlaced type

            && (IS_INTERLACED(mb_type) != IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]))

            // and left mb is in the same slice if deblocking_filter == 2

            && (h->deblocking_filter!=2 || h->slice_table[mb_xy-1] == h->slice_table[mb_xy])) {

        /* First vertical edge is different in MBAFF frames

         * There are 8 different bS to compute and 2 different Qp

         */

        const int pair_xy = mb_x + (mb_y&~1)*s->mb_stride;

        const int left_mb_xy[2] = { pair_xy-1, pair_xy-1+s->mb_stride };

        int16_t bS[8];

        int qp[2];

        int bqp[2];

        int rqp[2];

        int mb_qp, mbn0_qp, mbn1_qp;

        int i;

        first_vertical_edge_done = 1;

        if( IS_INTRA(mb_type) )

            bS[0] = bS[1] = bS[2] = bS[3] = bS[4] = bS[5] = bS[6] = bS[7] = 4;

        else {

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

                int mbn_xy = MB_FIELD ? left_mb_xy[i>>2] : left_mb_xy[i&1];

                if( IS_INTRA( s->current_picture.mb_type[mbn_xy] ) )

                    bS[i] = 4;

                else if( h->non_zero_count_cache[12+8*(i>>1)] != 0 ||

                         /* FIXME: with 8x8dct + cavlc, should check cbp instead of nnz */

                         h->non_zero_count[mbn_xy][MB_FIELD ? i&3 : (i>>2)+(mb_y&1)*2] )

                    bS[i] = 2;

                else

                    bS[i] = 1;

            }

        }

        mb_qp = s->current_picture.qscale_table[mb_xy];

        mbn0_qp = s->current_picture.qscale_table[left_mb_xy[0]];

        mbn1_qp = s->current_picture.qscale_table[left_mb_xy[1]];

        qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;

        bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;

        rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;

        qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;

        bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;

        rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;

        /* Filter edge */

        tprintf(s->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);

        { int i; for (i = 0; i < 8; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }

        filter_mb_mbaff_edgev ( h, &img_y [0], linesize,   bS, qp );

        filter_mb_mbaff_edgecv( h, &img_cb[0], uvlinesize, bS, bqp );

        filter_mb_mbaff_edgecv( h, &img_cr[0], uvlinesize, bS, rqp );

    }

    /* dir : 0 -> vertical edge, 1 -> horizontal edge */

    for( dir = 0; dir < 2; dir++ )

    {

        int edge;

        const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;

        const int mbm_type = s->current_picture.mb_type[mbm_xy];

        int start = h->slice_table[mbm_xy] == 255 ? 1 : 0;

        const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))

                                  == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;

        // how often to recheck mv-based bS when iterating between edges

        const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :

                              (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;

        // how often to recheck mv-based bS when iterating along each edge

        const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));

        if (first_vertical_edge_done) {

            start = 1;

            first_vertical_edge_done = 0;

        }

        if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])

            start = 1;

        if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0

            && !IS_INTERLACED(mb_type)

            && IS_INTERLACED(mbm_type)

            ) {

            // This is a special case in the norm where the filtering must

            // be done twice (one each of the field) even if we are in a

            // frame macroblock.

            //

            static const int nnz_idx[4] = {4,5,6,3};

            unsigned int tmp_linesize   = 2 *   linesize;

            unsigned int tmp_uvlinesize = 2 * uvlinesize;

            int mbn_xy = mb_xy - 2 * s->mb_stride;

            int qp;

            int i, j;

            int16_t bS[4];

            for(j=0; j<2; j++, mbn_xy += s->mb_stride){

                if( IS_INTRA(mb_type) ||

                    IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {

                    bS[0] = bS[1] = bS[2] = bS[3] = 3;

                } else {

                    const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];

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

                        if( h->non_zero_count_cache[scan8[0]+i] != 0 ||

                            mbn_nnz[nnz_idx[i]] != 0 )

                            bS[i] = 2;

                        else

                            bS[i] = 1;

                    }

                }

                // Do not use s->qscale as luma quantizer because it has not the same

                // value in IPCM macroblocks.

                qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;

                tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);

                { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }

                filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );

                filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,

                                  ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,

                                  ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

            }

            start = 1;

        }

        /* Calculate bS */

        for( edge = start; edge < edges; edge++ ) {

            /* mbn_xy: neighbor macroblock */

            const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;

            const int mbn_type = s->current_picture.mb_type[mbn_xy];

            int16_t bS[4];

            int qp;

            if( (edge&1) && IS_8x8DCT(mb_type) )

                continue;

            if( IS_INTRA(mb_type) ||

                IS_INTRA(mbn_type) ) {

                int value;

                if (edge == 0) {

                    if (   (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))

                        || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))

                    ) {

                        value = 4;

                    } else {

                        value = 3;

                    }

                } else {

                    value = 3;

                }

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

            } else {

                int i, l;

                int mv_done;

                if( edge & mask_edge ) {

                    bS[0] = bS[1] = bS[2] = bS[3] = 0;

                    mv_done = 1;

                }

                else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {

                    bS[0] = bS[1] = bS[2] = bS[3] = 1;

                    mv_done = 1;

                }

                else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {

                    int b_idx= 8 + 4 + edge * (dir ? 8:1);

                    int bn_idx= b_idx - (dir ? 8:1);

                    int v = 0;

                    int xn= h->slice_type_nos == FF_B_TYPE && h->ref2frm[0][h->ref_cache[0][b_idx]+2] != h->ref2frm[0][h->ref_cache[0][bn_idx]+2];

                    for( l = 0; !v && l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {

                        int ln= l^xn;

                        v |= h->ref2frm[l][h->ref_cache[l][b_idx]+2] != h->ref2frm[ln][h->ref_cache[ln][bn_idx]+2] ||

                             FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||

                             FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit;

                    }

                    bS[0] = bS[1] = bS[2] = bS[3] = v;

                    mv_done = 1;

                }

                else

                    mv_done = 0;

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

                    int x = dir == 0 ? edge : i;

                    int y = dir == 0 ? i    : edge;

                    int b_idx= 8 + 4 + x + 8*y;

                    int bn_idx= b_idx - (dir ? 8:1);

                    if( h->non_zero_count_cache[b_idx] != 0 ||

                        h->non_zero_count_cache[bn_idx] != 0 ) {

                        bS[i] = 2;

                    }

                    else if(!mv_done)

                    {

                        int xn= h->slice_type_nos == FF_B_TYPE && h->ref2frm[0][h->ref_cache[0][b_idx]+2] != h->ref2frm[0][h->ref_cache[0][bn_idx]+2];

                        bS[i] = 0;

                        for( l = 0; l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {

                            int ln= l^xn;

                            if( h->ref2frm[l][h->ref_cache[l][b_idx]+2] != h->ref2frm[ln][h->ref_cache[ln][bn_idx]+2] ||

                                FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||

                                FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit ) {

                                bS[i] = 1;

                                break;

                            }

                        }

                    }

                }

                if(bS[0]+bS[1]+bS[2]+bS[3] == 0)

                    continue;

            }

            /* Filter edge */

            // Do not use s->qscale as luma quantizer because it has not the same

            // value in IPCM macroblocks.

            qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;

            //tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp, s->current_picture.qscale_table[mbn_xy]);

            tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);

            { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }

            if( dir == 0 ) {

                filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );

                if( (edge&1) == 0 ) {

                    filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,

                                      ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                    filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,

                                      ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                }

            } else {

                filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );

                if( (edge&1) == 0 ) {

                    filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,

                                      ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                    filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,

                                      ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                }

            }

        }

    }

}


static int twolame_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                                const AVFrame *frame, int *got_packet_ptr)

{

    TWOLAMEContext *s = avctx->priv_data;

    int ret;

    if ((ret = ff_alloc_packet(avpkt, MPA_MAX_CODED_FRAME_SIZE)) < 0)

        return ret;

    if (frame) {

        switch (avctx->sample_fmt) {

        case AV_SAMPLE_FMT_FLT:

            ret = twolame_encode_buffer_float32_interleaved(s->glopts,

                                                            (const float *)frame->data[0],

                                                            frame->nb_samples,

                                                            avpkt->data,

                                                            avpkt->size);

            break;

        case AV_SAMPLE_FMT_FLTP:

            ret = twolame_encode_buffer_float32(s->glopts,

                                                (const float *)frame->data[0],

                                                (const float *)frame->data[1],

                                                frame->nb_samples,

                                                avpkt->data, avpkt->size);

            break;

        case AV_SAMPLE_FMT_S16:

            ret = twolame_encode_buffer_interleaved(s->glopts,

                                                    (const short int *)frame->data[0],

                                                    frame->nb_samples,

                                                    avpkt->data, avpkt->size);

            break;

        case AV_SAMPLE_FMT_S16P:

            ret = twolame_encode_buffer(s->glopts,

                                        (const short int *)frame->data[0],

                                        (const short int *)frame->data[1],

                                        frame->nb_samples,

                                        avpkt->data, avpkt->size);

            break;

        default:

            av_log(avctx, AV_LOG_ERROR,

                   "Unsupported sample format %d.\n", avctx->sample_fmt);

            return AVERROR_BUG;

        }

    } else {

        ret = twolame_encode_flush(s->glopts, avpkt->data, avpkt->size);

    }

    if (!ret)     // no bytes written

        return 0;

    if (ret < 0)  // twolame error

        return AVERROR_UNKNOWN;

    avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);

    if (frame) {

        if (frame->pts != AV_NOPTS_VALUE)

            avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->delay);

    } else {

        avpkt->pts = s->next_pts;

    }

    // this is for setting pts for flushed packet(s).

    if (avpkt->pts != AV_NOPTS_VALUE)

        s->next_pts = avpkt->pts + avpkt->duration;

    av_shrink_packet(avpkt, ret);

    *got_packet_ptr = 1;

    return 0;

}


av_cold void ff_vc1dsp_init_x86(VC1DSPContext *dsp)

{

    int cpu_flags = av_get_cpu_flags();

    if (INLINE_MMX(cpu_flags))

        ff_vc1dsp_init_mmx(dsp);

    if (INLINE_MMXEXT(cpu_flags))

        ff_vc1dsp_init_mmxext(dsp);

#define ASSIGN_LF(EXT) \

        dsp->vc1_v_loop_filter4  = ff_vc1_v_loop_filter4_ ## EXT; \

        dsp->vc1_h_loop_filter4  = ff_vc1_h_loop_filter4_ ## EXT; \

        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_ ## EXT; \

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_ ## EXT; \

        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_ ## EXT; \

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_ ## EXT

#if HAVE_YASM

    if (cpu_flags & AV_CPU_FLAG_MMX) {

        dsp->put_no_rnd_vc1_chroma_pixels_tab[0] = ff_put_vc1_chroma_mc8_nornd_mmx;

    }

    if (cpu_flags & AV_CPU_FLAG_MMXEXT) {

        ASSIGN_LF(mmxext);

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_mmxext;

        dsp->avg_vc1_mspel_pixels_tab[0]         = avg_vc1_mspel_mc00_mmxext;

    } else if (cpu_flags & AV_CPU_FLAG_3DNOW) {

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_3dnow;

    }

    if (cpu_flags & AV_CPU_FLAG_SSE2) {

        dsp->vc1_v_loop_filter8  = ff_vc1_v_loop_filter8_sse2;

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse2;

        dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_sse2;

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse2;

    }

    if (cpu_flags & AV_CPU_FLAG_SSSE3) {

        ASSIGN_LF(ssse3);

        dsp->put_no_rnd_vc1_chroma_pixels_tab[0] = ff_put_vc1_chroma_mc8_nornd_ssse3;

        dsp->avg_no_rnd_vc1_chroma_pixels_tab[0] = ff_avg_vc1_chroma_mc8_nornd_ssse3;

    }

    if (cpu_flags & AV_CPU_FLAG_SSE4) {

        dsp->vc1_h_loop_filter8  = ff_vc1_h_loop_filter8_sse4;

        dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_sse4;

    }

#endif /* HAVE_YASM */

}


static inline void neon_store_reg64(TCGv var, int reg)

{

    tcg_gen_st_i64(var, cpu_env, vfp_reg_offset(1, reg));

}


static DisplaySurface *qemu_create_message_surface(int w, int h,

                                                   const char *msg)

{

    DisplaySurface *surface = qemu_create_displaysurface(w, h);

    pixman_color_t bg = color_table_rgb[0][COLOR_BLACK];

    pixman_color_t fg = color_table_rgb[0][COLOR_WHITE];

    pixman_image_t *glyph;

    int len, x, y, i;

    len = strlen(msg);

    x = (w / FONT_WIDTH  - len) / 2;

    y = (h / FONT_HEIGHT - 1)   / 2;

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

        glyph = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, msg[i]);

        qemu_pixman_glyph_render(glyph, surface->image, &fg, &bg,

                                 x+i, y, FONT_WIDTH, FONT_HEIGHT);

        qemu_pixman_image_unref(glyph);

    }

    return surface;

}


static bool vregs_needed(void *opaque)

{

#ifdef CONFIG_KVM

    if (kvm_enabled()) {

        return kvm_check_extension(kvm_state, KVM_CAP_S390_VECTOR_REGISTERS);

    }

#endif

    return 0;

}


static unsigned int dec_abs_r(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "abs $r%u, $r%u\n",

		    dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZ);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	tcg_gen_sari_tl(t0, cpu_R[dc->op1], 31);

	tcg_gen_xor_tl(cpu_R[dc->op2], cpu_R[dc->op1], t0);

	tcg_gen_sub_tl(cpu_R[dc->op2], cpu_R[dc->op2], t0);

	tcg_temp_free(t0);

	cris_alu(dc, CC_OP_MOVE,

		    cpu_R[dc->op2], cpu_R[dc->op2], cpu_R[dc->op2], 4);

	return 2;

}


static int calculate_new_instance_id(const char *idstr)

{

    SaveStateEntry *se;

    int instance_id = 0;

    TAILQ_FOREACH(se, &savevm_handlers, entry) {

        if (strcmp(idstr, se->idstr) == 0

            && instance_id <= se->instance_id) {

            instance_id = se->instance_id + 1;

        }

    }

    return instance_id;

}


static int resample(ResampleContext *c, void *dst, const void *src,

                    int *consumed, int src_size, int dst_size, int update_ctx,

                    int nearest_neighbour)

{

    int dst_index;

    int index         = c->index;

    int frac          = c->frac;

    int dst_incr_frac = c->dst_incr % c->src_incr;

    int dst_incr      = c->dst_incr / c->src_incr;

    int compensation_distance = c->compensation_distance;

    if (!dst != !src)

        return AVERROR(EINVAL);

    if (nearest_neighbour) {

        int64_t index2 = ((int64_t)index) << 32;

        int64_t incr   = (1LL << 32) * c->dst_incr / c->src_incr;

        dst_size       = FFMIN(dst_size,

                               (src_size-1-index) * (int64_t)c->src_incr /

                               c->dst_incr);

        if (dst) {

            for(dst_index = 0; dst_index < dst_size; dst_index++) {

                c->resample_nearest(dst, dst_index, src, index2 >> 32);

                index2 += incr;

            }

        } else {

            dst_index = dst_size;

        }

        index += dst_index * dst_incr;

        index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;

        frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;

    } else {

        for (dst_index = 0; dst_index < dst_size; dst_index++) {

            int sample_index = index >> c->phase_shift;

            if (sample_index + c->filter_length > src_size ||

                -sample_index >= src_size)

                break;

            if (dst)

                c->resample_one(c, dst, dst_index, src, src_size, index, frac);

            frac  += dst_incr_frac;

            index += dst_incr;

            if (frac >= c->src_incr) {

                frac -= c->src_incr;

                index++;

            }

            if (dst_index + 1 == compensation_distance) {

                compensation_distance = 0;

                dst_incr_frac = c->ideal_dst_incr % c->src_incr;

                dst_incr      = c->ideal_dst_incr / c->src_incr;

            }

        }

    }

    if (consumed)

        *consumed = FFMAX(index, 0) >> c->phase_shift;

    if (update_ctx) {

        if (index >= 0)

            index &= c->phase_mask;

        if (compensation_distance) {

            compensation_distance -= dst_index;

            if (compensation_distance <= 0)

                return AVERROR_BUG;

        }

        c->frac     = frac;

        c->index    = index;

        c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;

        c->compensation_distance = compensation_distance;

    }

    return dst_index;

}


static void l2cap_frame_in(struct l2cap_instance_s *l2cap,

                const l2cap_hdr *frame)

{

    uint16_t cid = le16_to_cpu(frame->cid);

    uint16_t len = le16_to_cpu(frame->len);

    if (unlikely(cid >= L2CAP_CID_MAX || !l2cap->cid[cid])) {

        fprintf(stderr, "%s: frame addressed to a non-existent L2CAP "

                        "channel %04x received.\n", __FUNCTION__, cid);

        return;

    }

    l2cap->cid[cid]->frame_in(l2cap->cid[cid], cid, frame, len);

}


static uint32_t superio_ioport_readb(void *opaque, uint32_t addr)

{

    SuperIOConfig *superio_conf = opaque;

    DPRINTF("superio_ioport_readb  address 0x%x   \n", addr);

    return (superio_conf->config[superio_conf->index]);

}


void aio_notify_accept(AioContext *ctx)

{

    if (atomic_xchg(&ctx->notified, false)) {

        event_notifier_test_and_clear(&ctx->notifier);

    }

}


static inline void code_gen_alloc(size_t tb_size)

{

    code_gen_buffer_size = size_code_gen_buffer(tb_size);

    code_gen_buffer = alloc_code_gen_buffer();

    if (code_gen_buffer == NULL) {

        fprintf(stderr, "Could not allocate dynamic translator buffer\n");

        exit(1);

    }

    map_exec(code_gen_prologue, sizeof(code_gen_prologue));

    code_gen_buffer_max_size = code_gen_buffer_size -

        (TCG_MAX_OP_SIZE * OPC_BUF_SIZE);

    code_gen_max_blocks = code_gen_buffer_size / CODE_GEN_AVG_BLOCK_SIZE;

    tbs = g_malloc(code_gen_max_blocks * sizeof(TranslationBlock));

}


static void qemu_chr_parse_parallel(QemuOpts *opts, ChardevBackend *backend,

                                    Error **errp)

{

    const char *device = qemu_opt_get(opts, "path");

    if (device == NULL) {

        error_setg(errp, "chardev: parallel: no device path given");

        return;

    }

    backend->parallel = g_new0(ChardevHostdev, 1);

    backend->parallel->device = g_strdup(device);

}


static void guess_chs_for_size(BlockDriverState *bs,

                uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs)

{

    uint64_t nb_sectors;

    int cylinders;

    bdrv_get_geometry(bs, &nb_sectors);

    cylinders = nb_sectors / (16 * 63);

    if (cylinders > 16383) {

        cylinders = 16383;

    } else if (cylinders < 2) {

        cylinders = 2;

    }

    *pcyls = cylinders;

    *pheads = 16;

    *psecs = 63;

}