av_cold void ff_sws_init_input_funcs(SwsContext *c)

{

    enum PixelFormat srcFormat = c->srcFormat;

    c->chrToYV12 = NULL;

    switch(srcFormat) {

        case PIX_FMT_YUYV422  : c->chrToYV12 = yuy2ToUV_c; break;

        case PIX_FMT_UYVY422  : c->chrToYV12 = uyvyToUV_c; break;

        case PIX_FMT_NV12     : c->chrToYV12 = nv12ToUV_c; break;

        case PIX_FMT_NV21     : c->chrToYV12 = nv21ToUV_c; break;

        case PIX_FMT_RGB8     :

        case PIX_FMT_BGR8     :

        case PIX_FMT_PAL8     :

        case PIX_FMT_BGR4_BYTE:

        case PIX_FMT_RGB4_BYTE: c->chrToYV12 = palToUV_c; break;

        case PIX_FMT_GBRP9LE:

        case PIX_FMT_GBRP10LE:

        case PIX_FMT_GBRP16LE:  c->readChrPlanar = planar_rgb16le_to_uv; break;

        case PIX_FMT_GBRP9BE:

        case PIX_FMT_GBRP10BE:

        case PIX_FMT_GBRP16BE:  c->readChrPlanar = planar_rgb16be_to_uv; break;

        case PIX_FMT_GBRP:      c->readChrPlanar = planar_rgb_to_uv; break;

#if HAVE_BIGENDIAN

        case PIX_FMT_YUV444P9LE:

        case PIX_FMT_YUV422P9LE:

        case PIX_FMT_YUV420P9LE:

        case PIX_FMT_YUV422P10LE:

        case PIX_FMT_YUV444P10LE:

        case PIX_FMT_YUV420P10LE:

        case PIX_FMT_YUV420P16LE:

        case PIX_FMT_YUV422P16LE:

        case PIX_FMT_YUV444P16LE: c->chrToYV12 = bswap16UV_c; break;

#else

        case PIX_FMT_YUV444P9BE:

        case PIX_FMT_YUV422P9BE:

        case PIX_FMT_YUV420P9BE:

        case PIX_FMT_YUV444P10BE:

        case PIX_FMT_YUV422P10BE:

        case PIX_FMT_YUV420P10BE:

        case PIX_FMT_YUV420P16BE:

        case PIX_FMT_YUV422P16BE:

        case PIX_FMT_YUV444P16BE: c->chrToYV12 = bswap16UV_c; break;

#endif

    }

    if (c->chrSrcHSubSample) {

        switch(srcFormat) {

        case PIX_FMT_RGBA64BE: c->chrToYV12 = rgb64BEToUV_half_c; break;

        case PIX_FMT_RGBA64LE: c->chrToYV12 = rgb64LEToUV_half_c; break;

        case PIX_FMT_RGB48BE : c->chrToYV12 = rgb48BEToUV_half_c; break;

        case PIX_FMT_RGB48LE : c->chrToYV12 = rgb48LEToUV_half_c; break;

        case PIX_FMT_BGR48BE : c->chrToYV12 = bgr48BEToUV_half_c; break;

        case PIX_FMT_BGR48LE : c->chrToYV12 = bgr48LEToUV_half_c; break;

        case PIX_FMT_RGB32   : c->chrToYV12 = bgr32ToUV_half_c;   break;

        case PIX_FMT_RGB32_1 : c->chrToYV12 = bgr321ToUV_half_c;  break;

        case PIX_FMT_BGR24   : c->chrToYV12 = bgr24ToUV_half_c;   break;

        case PIX_FMT_BGR565LE: c->chrToYV12 = bgr16leToUV_half_c; break;

        case PIX_FMT_BGR565BE: c->chrToYV12 = bgr16beToUV_half_c; break;

        case PIX_FMT_BGR555LE: c->chrToYV12 = bgr15leToUV_half_c; break;

        case PIX_FMT_BGR555BE: c->chrToYV12 = bgr15beToUV_half_c; break;

        case PIX_FMT_BGR444LE: c->chrToYV12 = bgr12leToUV_half_c; break;

        case PIX_FMT_BGR444BE: c->chrToYV12 = bgr12beToUV_half_c; break;

        case PIX_FMT_BGR32   : c->chrToYV12 = rgb32ToUV_half_c;   break;

        case PIX_FMT_BGR32_1 : c->chrToYV12 = rgb321ToUV_half_c;  break;

        case PIX_FMT_RGB24   : c->chrToYV12 = rgb24ToUV_half_c;   break;

        case PIX_FMT_RGB565LE: c->chrToYV12 = rgb16leToUV_half_c; break;

        case PIX_FMT_RGB565BE: c->chrToYV12 = rgb16beToUV_half_c; break;

        case PIX_FMT_RGB555LE: c->chrToYV12 = rgb15leToUV_half_c; break;

        case PIX_FMT_RGB555BE: c->chrToYV12 = rgb15beToUV_half_c; break;

        case PIX_FMT_GBR24P  : c->chrToYV12 = gbr24pToUV_half_c;  break;

        case PIX_FMT_RGB444LE: c->chrToYV12 = rgb12leToUV_half_c; break;

        case PIX_FMT_RGB444BE: c->chrToYV12 = rgb12beToUV_half_c; break;

        }

    } else {

        switch(srcFormat) {

        case PIX_FMT_RGB48BE : c->chrToYV12 = rgb48BEToUV_c; break;

        case PIX_FMT_RGB48LE : c->chrToYV12 = rgb48LEToUV_c; break;

        case PIX_FMT_BGR48BE : c->chrToYV12 = bgr48BEToUV_c; break;

        case PIX_FMT_BGR48LE : c->chrToYV12 = bgr48LEToUV_c; break;

        case PIX_FMT_RGB32   : c->chrToYV12 = bgr32ToUV_c;   break;

        case PIX_FMT_RGB32_1 : c->chrToYV12 = bgr321ToUV_c;  break;

        case PIX_FMT_BGR24   : c->chrToYV12 = bgr24ToUV_c;   break;

        case PIX_FMT_BGR565LE: c->chrToYV12 = bgr16leToUV_c; break;

        case PIX_FMT_BGR565BE: c->chrToYV12 = bgr16beToUV_c; break;

        case PIX_FMT_BGR555LE: c->chrToYV12 = bgr15leToUV_c; break;

        case PIX_FMT_BGR555BE: c->chrToYV12 = bgr15beToUV_c; break;

        case PIX_FMT_BGR444LE: c->chrToYV12 = bgr12leToUV_c; break;

        case PIX_FMT_BGR444BE: c->chrToYV12 = bgr12beToUV_c; break;

        case PIX_FMT_BGR32   : c->chrToYV12 = rgb32ToUV_c;   break;

        case PIX_FMT_BGR32_1 : c->chrToYV12 = rgb321ToUV_c;  break;

        case PIX_FMT_RGB24   : c->chrToYV12 = rgb24ToUV_c;   break;

        case PIX_FMT_RGB565LE: c->chrToYV12 = rgb16leToUV_c; break;

        case PIX_FMT_RGB565BE: c->chrToYV12 = rgb16beToUV_c; break;

        case PIX_FMT_RGB555LE: c->chrToYV12 = rgb15leToUV_c; break;

        case PIX_FMT_RGB555BE: c->chrToYV12 = rgb15beToUV_c; break;

        case PIX_FMT_RGB444LE: c->chrToYV12 = rgb12leToUV_c; break;

        case PIX_FMT_RGB444BE: c->chrToYV12 = rgb12beToUV_c; break;

        }

    }

    c->lumToYV12 = NULL;

    c->alpToYV12 = NULL;

    switch (srcFormat) {

    case PIX_FMT_GBRP9LE:

    case PIX_FMT_GBRP10LE:

    case PIX_FMT_GBRP16LE: c->readLumPlanar = planar_rgb16le_to_y; break;

    case PIX_FMT_GBRP9BE:

    case PIX_FMT_GBRP10BE:

    case PIX_FMT_GBRP16BE: c->readLumPlanar = planar_rgb16be_to_y; break;

    case PIX_FMT_GBRP:     c->readLumPlanar = planar_rgb_to_y; break;

#if HAVE_BIGENDIAN

    case PIX_FMT_YUV444P9LE:

    case PIX_FMT_YUV422P9LE:

    case PIX_FMT_YUV420P9LE:

    case PIX_FMT_YUV444P10LE:

    case PIX_FMT_YUV422P10LE:

    case PIX_FMT_YUV420P10LE:

    case PIX_FMT_YUV420P16LE:

    case PIX_FMT_YUV422P16LE:

    case PIX_FMT_YUV444P16LE:

    case PIX_FMT_GRAY16LE: c->lumToYV12 = bswap16Y_c; break;

#else

    case PIX_FMT_YUV444P9BE:

    case PIX_FMT_YUV422P9BE:

    case PIX_FMT_YUV420P9BE:

    case PIX_FMT_YUV444P10BE:

    case PIX_FMT_YUV422P10BE:

    case PIX_FMT_YUV420P10BE:

    case PIX_FMT_YUV420P16BE:

    case PIX_FMT_YUV422P16BE:

    case PIX_FMT_YUV444P16BE:

    case PIX_FMT_GRAY16BE: c->lumToYV12 = bswap16Y_c; break;

#endif

    case PIX_FMT_YUYV422  :

    case PIX_FMT_Y400A    : c->lumToYV12 = yuy2ToY_c; break;

    case PIX_FMT_UYVY422  : c->lumToYV12 = uyvyToY_c;    break;

    case PIX_FMT_BGR24    : c->lumToYV12 = bgr24ToY_c;   break;

    case PIX_FMT_BGR565LE : c->lumToYV12 = bgr16leToY_c; break;

    case PIX_FMT_BGR565BE : c->lumToYV12 = bgr16beToY_c; break;

    case PIX_FMT_BGR555LE : c->lumToYV12 = bgr15leToY_c; break;

    case PIX_FMT_BGR555BE : c->lumToYV12 = bgr15beToY_c; break;

    case PIX_FMT_BGR444LE : c->lumToYV12 = bgr12leToY_c; break;

    case PIX_FMT_BGR444BE : c->lumToYV12 = bgr12beToY_c; break;

    case PIX_FMT_RGB24    : c->lumToYV12 = rgb24ToY_c;   break;

    case PIX_FMT_RGB565LE : c->lumToYV12 = rgb16leToY_c; break;

    case PIX_FMT_RGB565BE : c->lumToYV12 = rgb16beToY_c; break;

    case PIX_FMT_RGB555LE : c->lumToYV12 = rgb15leToY_c; break;

    case PIX_FMT_RGB555BE : c->lumToYV12 = rgb15beToY_c; break;

    case PIX_FMT_RGB444LE : c->lumToYV12 = rgb12leToY_c; break;

    case PIX_FMT_RGB444BE : c->lumToYV12 = rgb12beToY_c; break;

    case PIX_FMT_RGB8     :

    case PIX_FMT_BGR8     :

    case PIX_FMT_PAL8     :

    case PIX_FMT_BGR4_BYTE:

    case PIX_FMT_RGB4_BYTE: c->lumToYV12 = palToY_c; break;

    case PIX_FMT_MONOBLACK: c->lumToYV12 = monoblack2Y_c; break;

    case PIX_FMT_MONOWHITE: c->lumToYV12 = monowhite2Y_c; break;

    case PIX_FMT_RGB32  : c->lumToYV12 = bgr32ToY_c;  break;

    case PIX_FMT_RGB32_1: c->lumToYV12 = bgr321ToY_c; break;

    case PIX_FMT_BGR32  : c->lumToYV12 = rgb32ToY_c;  break;

    case PIX_FMT_BGR32_1: c->lumToYV12 = rgb321ToY_c; break;

    case PIX_FMT_RGB48BE: c->lumToYV12 = rgb48BEToY_c; break;

    case PIX_FMT_RGB48LE: c->lumToYV12 = rgb48LEToY_c; break;

    case PIX_FMT_BGR48BE: c->lumToYV12 = bgr48BEToY_c; break;

    case PIX_FMT_BGR48LE: c->lumToYV12 = bgr48LEToY_c; break;

    case PIX_FMT_RGBA64BE:c->lumToYV12 = rgb64BEToY_c; break;

    case PIX_FMT_RGBA64LE:c->lumToYV12 = rgb64LEToY_c; break;

    }

    if (c->alpPixBuf) {

        switch (srcFormat) {

        case PIX_FMT_RGBA64LE:

        case PIX_FMT_RGBA64BE:  c->alpToYV12 = rgba64ToA_c; break;

        case PIX_FMT_BGRA:

        case PIX_FMT_RGBA:  c->alpToYV12 = rgbaToA_c; break;

        case PIX_FMT_ABGR:

        case PIX_FMT_ARGB:  c->alpToYV12 = abgrToA_c; break;

        case PIX_FMT_Y400A: c->alpToYV12 = uyvyToY_c; break;

        case PIX_FMT_PAL8 : c->alpToYV12 = palToA_c; break;

        }

    }

}


static uint32_t pcie_mmcfg_data_read(PCIBus *s, uint32_t addr, int len)

{

    PCIDevice *pci_dev = pcie_dev_find_by_mmcfg_addr(s, addr);

    if (!pci_dev) {

        return ~0x0;

    }

    return pci_host_config_read_common(pci_dev, PCIE_MMCFG_CONFOFFSET(addr),

                                       pci_config_size(pci_dev), len);

}


int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,

                            uint8_t *data, size_t size)

{

    AVPacketSideData *sd, *tmp;

    int i;

    for (i = 0; i < st->nb_side_data; i++) {

        sd = &st->side_data[i];

        if (sd->type == type) {

            av_freep(&sd->data);

            sd->data = data;

            sd->size = size;

            return 0;

        }

    }

    tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));

    if (!tmp) {

        return AVERROR(ENOMEM);

    }

    st->side_data = tmp;

    st->nb_side_data++;

    sd = &st->side_data[st->nb_side_data - 1];

    sd->type = type;

    sd->data = data;

    sd->size = size;

    return 0;

}


static void qemu_announce_self_once(void *opaque)

{

    int i, len;

    VLANState *vlan;

    VLANClientState *vc;

    uint8_t buf[256];

    static int count = SELF_ANNOUNCE_ROUNDS;

    QEMUTimer *timer = *(QEMUTimer **)opaque;

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

        if (!nd_table[i].used)

            continue;

        len = announce_self_create(buf, nd_table[i].macaddr);

        vlan = nd_table[i].vlan;

        QTAILQ_FOREACH(vc, &vlan->clients, next) {

            vc->receive(vc, buf, len);

        }

    }

    if (count--) {

	    qemu_mod_timer(timer, qemu_get_clock(rt_clock) + 100);

    } else {

	    qemu_del_timer(timer);

	    qemu_free_timer(timer);

    }

}


static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,

                                         const char *name, int devfn)

{

    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);

    PCIConfigReadFunc *config_read = pc->config_read;

    PCIConfigWriteFunc *config_write = pc->config_write;

    AddressSpace *dma_as;

    if (devfn < 0) {

        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);

            devfn += PCI_FUNC_MAX) {

            if (!bus->devices[devfn])

                goto found;

        }

        error_report("PCI: no slot/function available for %s, all in use", name);

        return NULL;

    found: ;

    } else if (bus->devices[devfn]) {

        error_report("PCI: slot %d function %d not available for %s, in use by %s",

                     PCI_SLOT(devfn), PCI_FUNC(devfn), name, bus->devices[devfn]->name);

        return NULL;

    }

    pci_dev->bus = bus;

    dma_as = pci_device_iommu_address_space(pci_dev);

    memory_region_init_alias(&pci_dev->bus_master_enable_region,

                             OBJECT(pci_dev), "bus master",

                             dma_as->root, 0, memory_region_size(dma_as->root));

    memory_region_set_enabled(&pci_dev->bus_master_enable_region, false);

    address_space_init(&pci_dev->bus_master_as, &pci_dev->bus_master_enable_region,

                       name);

    pci_dev->devfn = devfn;

    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);

    pci_dev->irq_state = 0;

    pci_config_alloc(pci_dev);

    pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);

    pci_config_set_device_id(pci_dev->config, pc->device_id);

    pci_config_set_revision(pci_dev->config, pc->revision);

    pci_config_set_class(pci_dev->config, pc->class_id);

    if (!pc->is_bridge) {

        if (pc->subsystem_vendor_id || pc->subsystem_id) {

            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,

                         pc->subsystem_vendor_id);

            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,

                         pc->subsystem_id);

        } else {

            pci_set_default_subsystem_id(pci_dev);

        }

    } else {

        /* subsystem_vendor_id/subsystem_id are only for header type 0 */

        assert(!pc->subsystem_vendor_id);

        assert(!pc->subsystem_id);

    }

    pci_init_cmask(pci_dev);

    pci_init_wmask(pci_dev);

    pci_init_w1cmask(pci_dev);

    if (pc->is_bridge) {

        pci_init_mask_bridge(pci_dev);

    }

    if (pci_init_multifunction(bus, pci_dev)) {

        pci_config_free(pci_dev);

        return NULL;

    }

    if (!config_read)

        config_read = pci_default_read_config;

    if (!config_write)

        config_write = pci_default_write_config;

    pci_dev->config_read = config_read;

    pci_dev->config_write = config_write;

    bus->devices[devfn] = pci_dev;

    pci_dev->version_id = 2; /* Current pci device vmstate version */

    return pci_dev;

}


static void avc_luma_vt_8w_msa(const uint8_t *src, int32_t src_stride,

                               uint8_t *dst, int32_t dst_stride,

                               int32_t height)

{

    int32_t loop_cnt;

    int16_t filt_const0 = 0xfb01;

    int16_t filt_const1 = 0x1414;

    int16_t filt_const2 = 0x1fb;

    v16i8 src0, src1, src2, src3, src4, src7, src8, src9, src10;

    v16i8 src10_r, src32_r, src76_r, src98_r;

    v16i8 src21_r, src43_r, src87_r, src109_r;

    v8i16 out0_r, out1_r, out2_r, out3_r;

    v16i8 filt0, filt1, filt2;

    v16u8 out0, out1;

    filt0 = (v16i8) __msa_fill_h(filt_const0);

    filt1 = (v16i8) __msa_fill_h(filt_const1);

    filt2 = (v16i8) __msa_fill_h(filt_const2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_r, src21_r, src32_r, src43_r);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src7, src8, src9, src10);

        src += (4 * src_stride);

        XORI_B4_128_SB(src7, src8, src9, src10);

        ILVR_B4_SB(src7, src4, src8, src7, src9, src8, src10, src9,

                   src76_r, src87_r, src98_r, src109_r);

        out0_r = DPADD_SH3_SH(src10_r, src32_r, src76_r, filt0, filt1, filt2);

        out1_r = DPADD_SH3_SH(src21_r, src43_r, src87_r, filt0, filt1, filt2);

        out2_r = DPADD_SH3_SH(src32_r, src76_r, src98_r, filt0, filt1, filt2);

        out3_r = DPADD_SH3_SH(src43_r, src87_r, src109_r, filt0, filt1, filt2);

        SRARI_H4_SH(out0_r, out1_r, out2_r, out3_r, 5);

        SAT_SH4_SH(out0_r, out1_r, out2_r, out3_r, 7);

        out0 = PCKEV_XORI128_UB(out0_r, out1_r);

        out1 = PCKEV_XORI128_UB(out2_r, out3_r);

        ST8x4_UB(out0, out1, dst, dst_stride);

        dst += (4 * dst_stride);

        src10_r = src76_r;

        src32_r = src98_r;

        src21_r = src87_r;

        src43_r = src109_r;

        src4 = src10;

    }

}


static bool xhci_er_full(void *opaque, int version_id)

{

    struct XHCIInterrupter *intr = opaque;

    return intr->er_full;

}


bool st_change_trace_event_state(const char *tname, bool tstate)

{

    TraceEvent *tp;

    tp = find_trace_event_by_name(tname);

    if (tp) {

        tp->state = tstate;

        return true;

    }

    return false;

}


aio_read_f(int argc, char **argv)

{

	int nr_iov, c;

	struct aio_ctx *ctx = calloc(1, sizeof(struct aio_ctx));

	BlockDriverAIOCB *acb;

	while ((c = getopt(argc, argv, "CP:qv")) != EOF) {

		switch (c) {

		case 'C':

			ctx->Cflag = 1;

			break;

		case 'P':

			ctx->Pflag = 1;

			ctx->pattern = parse_pattern(optarg);

			if (ctx->pattern < 0)

				return 0;

			break;

		case 'q':

			ctx->qflag = 1;

			break;

		case 'v':

			ctx->vflag = 1;

			break;

		default:

			free(ctx);

			return command_usage(&aio_read_cmd);

		}

	}

	if (optind > argc - 2) {

		free(ctx);

		return command_usage(&aio_read_cmd);

	}

	ctx->offset = cvtnum(argv[optind]);

	if (ctx->offset < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		free(ctx);

		return 0;

	}

	optind++;

	if (ctx->offset & 0x1ff) {

		printf("offset %" PRId64 " is not sector aligned\n",

                       ctx->offset);

		free(ctx);

		return 0;

	}

	nr_iov = argc - optind;

	ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, 0xab);

	gettimeofday(&ctx->t1, NULL);

	acb = bdrv_aio_readv(bs, ctx->offset >> 9, &ctx->qiov,

			      ctx->qiov.size >> 9, aio_read_done, ctx);

	if (!acb) {

		free(ctx->buf);

		free(ctx);

		return -EIO;

	}

	return 0;

}


int ff_eval_refl(int *refl, const int16_t *coefs, AVCodecContext *avctx)

{

    int b, i, j;

    int buffer1[LPC_ORDER];

    int buffer2[LPC_ORDER];

    int *bp1 = buffer1;

    int *bp2 = buffer2;

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

        buffer2[i] = coefs[i];

    refl[LPC_ORDER-1] = bp2[LPC_ORDER-1];

    if ((unsigned) bp2[LPC_ORDER-1] + 0x1000 > 0x1fff) {

        av_log(avctx, AV_LOG_ERROR, "Overflow. Broken sample?\n");

        return 1;

    }

    for (i = LPC_ORDER-2; i >= 0; i--) {

        b = 0x1000-((bp2[i+1] * bp2[i+1]) >> 12);

        if (!b)

            b = -2;

        b = 0x1000000 / b;

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

#if CONFIG_FTRAPV

            int a = bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12);

            if((int)(a*(unsigned)b) != a*(int64_t)b)

                return 1;

#endif

            bp1[j] = ((bp2[j] - ((refl[i+1] * bp2[i-j]) >> 12)) * b) >> 12;

        }

        if ((unsigned) bp1[i] + 0x1000 > 0x1fff)

            return 1;

        refl[i] = bp1[i];

        FFSWAP(int *, bp1, bp2);

    }

    return 0;

}


void cpu_loop(CPUAlphaState *env)

{

    int trapnr;

    target_siginfo_t info;

    abi_long sysret;

    while (1) {

        trapnr = cpu_alpha_exec (env);

        /* All of the traps imply a transition through PALcode, which

           implies an REI instruction has been executed.  Which means

           that the intr_flag should be cleared.  */

        env->intr_flag = 0;

        switch (trapnr) {

        case EXCP_RESET:

            fprintf(stderr, "Reset requested. Exit\n");

            exit(1);

            break;

        case EXCP_MCHK:

            fprintf(stderr, "Machine check exception. Exit\n");

            exit(1);

            break;

        case EXCP_SMP_INTERRUPT:

        case EXCP_CLK_INTERRUPT:

        case EXCP_DEV_INTERRUPT:

            fprintf(stderr, "External interrupt. Exit\n");

            exit(1);

            break;

        case EXCP_MMFAULT:

            env->lock_addr = -1;

            info.si_signo = TARGET_SIGSEGV;

            info.si_errno = 0;

            info.si_code = (page_get_flags(env->trap_arg0) & PAGE_VALID

                            ? TARGET_SEGV_ACCERR : TARGET_SEGV_MAPERR);

            info._sifields._sigfault._addr = env->trap_arg0;

            queue_signal(env, info.si_signo, &info);

            break;

        case EXCP_UNALIGN:

            env->lock_addr = -1;

            info.si_signo = TARGET_SIGBUS;

            info.si_errno = 0;

            info.si_code = TARGET_BUS_ADRALN;

            info._sifields._sigfault._addr = env->trap_arg0;

            queue_signal(env, info.si_signo, &info);

            break;

        case EXCP_OPCDEC:

        do_sigill:

            env->lock_addr = -1;

            info.si_signo = TARGET_SIGILL;

            info.si_errno = 0;

            info.si_code = TARGET_ILL_ILLOPC;

            info._sifields._sigfault._addr = env->pc;

            queue_signal(env, info.si_signo, &info);

            break;

        case EXCP_ARITH:

            env->lock_addr = -1;

            info.si_signo = TARGET_SIGFPE;

            info.si_errno = 0;

            info.si_code = TARGET_FPE_FLTINV;

            info._sifields._sigfault._addr = env->pc;

            queue_signal(env, info.si_signo, &info);

            break;

        case EXCP_FEN:

            /* No-op.  Linux simply re-enables the FPU.  */

            break;

        case EXCP_CALL_PAL:

            env->lock_addr = -1;

            switch (env->error_code) {

            case 0x80:

                /* BPT */

                info.si_signo = TARGET_SIGTRAP;

                info.si_errno = 0;

                info.si_code = TARGET_TRAP_BRKPT;

                info._sifields._sigfault._addr = env->pc;

                queue_signal(env, info.si_signo, &info);

                break;

            case 0x81:

                /* BUGCHK */

                info.si_signo = TARGET_SIGTRAP;

                info.si_errno = 0;

                info.si_code = 0;

                info._sifields._sigfault._addr = env->pc;

                queue_signal(env, info.si_signo, &info);

                break;

            case 0x83:

                /* CALLSYS */

                trapnr = env->ir[IR_V0];

                sysret = do_syscall(env, trapnr,

                                    env->ir[IR_A0], env->ir[IR_A1],

                                    env->ir[IR_A2], env->ir[IR_A3],

                                    env->ir[IR_A4], env->ir[IR_A5],

                                    0, 0);

                if (trapnr == TARGET_NR_sigreturn

                    || trapnr == TARGET_NR_rt_sigreturn) {

                    break;

                }

                /* Syscall writes 0 to V0 to bypass error check, similar

                   to how this is handled internal to Linux kernel.  */

                if (env->ir[IR_V0] == 0) {

                    env->ir[IR_V0] = sysret;

                } else {

                    env->ir[IR_V0] = (sysret < 0 ? -sysret : sysret);

                    env->ir[IR_A3] = (sysret < 0);

                }

                break;

            case 0x86:

                /* IMB */

                /* ??? We can probably elide the code using page_unprotect

                   that is checking for self-modifying code.  Instead we

                   could simply call tb_flush here.  Until we work out the

                   changes required to turn off the extra write protection,

                   this can be a no-op.  */

                break;

            case 0x9E:

                /* RDUNIQUE */

                /* Handled in the translator for usermode.  */

                abort();

            case 0x9F:

                /* WRUNIQUE */

                /* Handled in the translator for usermode.  */

                abort();

            case 0xAA:

                /* GENTRAP */

                info.si_signo = TARGET_SIGFPE;

                switch (env->ir[IR_A0]) {

                case TARGET_GEN_INTOVF:

                    info.si_code = TARGET_FPE_INTOVF;

                    break;

                case TARGET_GEN_INTDIV:

                    info.si_code = TARGET_FPE_INTDIV;

                    break;

                case TARGET_GEN_FLTOVF:

                    info.si_code = TARGET_FPE_FLTOVF;

                    break;

                case TARGET_GEN_FLTUND:

                    info.si_code = TARGET_FPE_FLTUND;

                    break;

                case TARGET_GEN_FLTINV:

                    info.si_code = TARGET_FPE_FLTINV;

                    break;

                case TARGET_GEN_FLTINE:

                    info.si_code = TARGET_FPE_FLTRES;

                    break;

                case TARGET_GEN_ROPRAND:

                    info.si_code = 0;

                    break;

                default:

                    info.si_signo = TARGET_SIGTRAP;

                    info.si_code = 0;

                    break;

                }

                info.si_errno = 0;

                info._sifields._sigfault._addr = env->pc;

                queue_signal(env, info.si_signo, &info);

                break;

            default:

                goto do_sigill;

            }

            break;

        case EXCP_DEBUG:

            info.si_signo = gdb_handlesig (env, TARGET_SIGTRAP);

            if (info.si_signo) {

                env->lock_addr = -1;

                info.si_errno = 0;

                info.si_code = TARGET_TRAP_BRKPT;

                queue_signal(env, info.si_signo, &info);

            }

            break;

        case EXCP_STL_C:

        case EXCP_STQ_C:

            do_store_exclusive(env, env->error_code, trapnr - EXCP_STL_C);

            break;

        case EXCP_INTERRUPT:

            /* Just indicate that signals should be handled asap.  */

            break;

        default:

            printf ("Unhandled trap: 0x%x\n", trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            exit (1);

        }

        process_pending_signals (env);

    }

}


static BlockDriverState *get_bs_snapshots(void)

{

    BlockDriverState *bs;

    DriveInfo *dinfo;

    if (bs_snapshots)

        return bs_snapshots;

    QTAILQ_FOREACH(dinfo, &drives, next) {

        bs = dinfo->bdrv;

        if (bdrv_can_snapshot(bs))

            goto ok;

    }

    return NULL;

 ok:

    bs_snapshots = bs;

    return bs;

}


opts_visitor_new(const QemuOpts *opts)

{

    OptsVisitor *ov;

    ov = g_malloc0(sizeof *ov);

    ov->visitor.type = VISITOR_INPUT;

    ov->visitor.start_struct = &opts_start_struct;

    ov->visitor.check_struct = &opts_check_struct;

    ov->visitor.end_struct   = &opts_end_struct;

    ov->visitor.start_list = &opts_start_list;

    ov->visitor.next_list  = &opts_next_list;

    ov->visitor.end_list   = &opts_end_list;

    ov->visitor.type_int64  = &opts_type_int64;

    ov->visitor.type_uint64 = &opts_type_uint64;

    ov->visitor.type_size   = &opts_type_size;

    ov->visitor.type_bool   = &opts_type_bool;

    ov->visitor.type_str    = &opts_type_str;

    /* type_number() is not filled in, but this is not the first visitor to

     * skip some mandatory methods... */

    ov->visitor.optional = &opts_optional;

    ov->visitor.free = opts_free;

    ov->opts_root = opts;

    return &ov->visitor;

}


size_t qcrypto_hash_digest_len(QCryptoHashAlgorithm alg)

{

    if (alg >= G_N_ELEMENTS(qcrypto_hash_alg_size)) {

        return 0;

    }

    return qcrypto_hash_alg_size[alg];

}


int read_targphys(const char *name,

                  int fd, target_phys_addr_t dst_addr, size_t nbytes)

{

    uint8_t *buf;

    size_t did;

    buf = g_malloc(nbytes);

    did = read(fd, buf, nbytes);

    if (did > 0)

        rom_add_blob_fixed("read", buf, did, dst_addr);

    g_free(buf);

    return did;

}


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

{

#ifdef HAVE_MMXFIXME

#else

	int i;

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

		dst[i]= src[2*i];

#endif

}


static av_cold int source_init(AVFilterContext *ctx, const char *args, void *opaque)

{

    Frei0rContext *frei0r = ctx->priv;

    char dl_name[1024], c;

    char frame_size[128] = "";

    char frame_rate[128] = "";

    AVRational frame_rate_q;

    memset(frei0r->params, 0, sizeof(frei0r->params));

    if (args)

        sscanf(args, "%127[^:]:%127[^:]:%1023[^:=]%c%255c",

               frame_size, frame_rate, dl_name, &c, frei0r->params);

    if (av_parse_video_size(&frei0r->w, &frei0r->h, frame_size) < 0) {

        av_log(ctx, AV_LOG_ERROR, "Invalid frame size: '%s'\n", frame_size);

        return AVERROR(EINVAL);

    }

    if (av_parse_video_rate(&frame_rate_q, frame_rate) < 0 ||

        frame_rate_q.den <= 0 || frame_rate_q.num <= 0) {

        av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: '%s'\n", frame_rate);

        return AVERROR(EINVAL);

    }

    frei0r->time_base.num = frame_rate_q.den;

    frei0r->time_base.den = frame_rate_q.num;

    return frei0r_init(ctx, dl_name, F0R_PLUGIN_TYPE_SOURCE);

}


static void dash_free(AVFormatContext *s)
{
    DASHContext *c = s->priv_data;
    int i, j;
    if (c->as) {
        for (i = 0; i < c->nb_as; i++)
            av_dict_free(&c->as[i].metadata);
        av_freep(&c->as);
        c->nb_as = 0;
    }
    if (!c->streams)
        return;
    for (i = 0; i < s->nb_streams; i++) {
        OutputStream *os = &c->streams[i];
        if (os->ctx && os->ctx_inited)
            av_write_trailer(os->ctx);
        if (os->ctx && os->ctx->pb)
            ffio_free_dyn_buf(&os->ctx->pb);
        ff_format_io_close(s, &os->out);
        if (os->ctx)
            avformat_free_context(os->ctx);
        for (j = 0; j < os->nb_segments; j++)
            av_free(os->segments[j]);
        av_free(os->segments);
    }
    av_freep(&c->streams);
}


static void decode_bo_addrmode_post_pre_base(CPUTriCoreState *env,

                                             DisasContext *ctx)

{

    uint32_t op2;

    uint32_t off10;

    int32_t r1, r2;

    TCGv temp;

    r1 = MASK_OP_BO_S1D(ctx->opcode);

    r2  = MASK_OP_BO_S2(ctx->opcode);

    off10 = MASK_OP_BO_OFF10_SEXT(ctx->opcode);

    op2 = MASK_OP_BO_OP2(ctx->opcode);

    switch (op2) {

    case OPC2_32_BO_CACHEA_WI_SHORTOFF:

    case OPC2_32_BO_CACHEA_W_SHORTOFF:

    case OPC2_32_BO_CACHEA_I_SHORTOFF:

        /* instruction to access the cache */

        break;

    case OPC2_32_BO_CACHEA_WI_POSTINC:

    case OPC2_32_BO_CACHEA_W_POSTINC:

    case OPC2_32_BO_CACHEA_I_POSTINC:

        /* instruction to access the cache, but we still need to handle

           the addressing mode */

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_CACHEA_WI_PREINC:

    case OPC2_32_BO_CACHEA_W_PREINC:

    case OPC2_32_BO_CACHEA_I_PREINC:

        /* instruction to access the cache, but we still need to handle

           the addressing mode */

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_CACHEI_WI_SHORTOFF:

    case OPC2_32_BO_CACHEI_W_SHORTOFF:

        /* TODO: Raise illegal opcode trap,

                 if !tricore_feature(TRICORE_FEATURE_131) */

        break;

    case OPC2_32_BO_CACHEI_W_POSTINC:

    case OPC2_32_BO_CACHEI_WI_POSTINC:

        if (tricore_feature(env, TRICORE_FEATURE_131)) {

            tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        } /* TODO: else raise illegal opcode trap */

        break;

    case OPC2_32_BO_CACHEI_W_PREINC:

    case OPC2_32_BO_CACHEI_WI_PREINC:

        if (tricore_feature(env, TRICORE_FEATURE_131)) {

            tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        } /* TODO: else raise illegal opcode trap */

        break;

    case OPC2_32_BO_ST_A_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_a[r1], cpu_gpr_a[r2], off10, MO_LESL);

        break;

    case OPC2_32_BO_ST_A_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_a[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LESL);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_A_PREINC:

        gen_st_preincr(ctx, cpu_gpr_a[r1], cpu_gpr_a[r2], off10, MO_LESL);

        break;

    case OPC2_32_BO_ST_B_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_UB);

        break;

    case OPC2_32_BO_ST_B_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_UB);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_B_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_UB);

        break;

    case OPC2_32_BO_ST_D_SHORTOFF:

        gen_offset_st_2regs(cpu_gpr_d[r1+1], cpu_gpr_d[r1], cpu_gpr_a[r2],

                            off10, ctx);

        break;

    case OPC2_32_BO_ST_D_POSTINC:

        gen_st_2regs_64(cpu_gpr_d[r1+1], cpu_gpr_d[r1], cpu_gpr_a[r2], ctx);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_D_PREINC:

        temp = tcg_temp_new();

        tcg_gen_addi_tl(temp, cpu_gpr_a[r2], off10);

        gen_st_2regs_64(cpu_gpr_d[r1+1], cpu_gpr_d[r1], temp, ctx);

        tcg_gen_mov_tl(cpu_gpr_a[r2], temp);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_DA_SHORTOFF:

        gen_offset_st_2regs(cpu_gpr_a[r1+1], cpu_gpr_a[r1], cpu_gpr_a[r2],

                            off10, ctx);

        break;

    case OPC2_32_BO_ST_DA_POSTINC:

        gen_st_2regs_64(cpu_gpr_a[r1+1], cpu_gpr_a[r1], cpu_gpr_a[r2], ctx);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_DA_PREINC:

        temp = tcg_temp_new();

        tcg_gen_addi_tl(temp, cpu_gpr_a[r2], off10);

        gen_st_2regs_64(cpu_gpr_a[r1+1], cpu_gpr_a[r1], temp, ctx);

        tcg_gen_mov_tl(cpu_gpr_a[r2], temp);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_H_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUW);

        break;

    case OPC2_32_BO_ST_H_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUW);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_H_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUW);

        break;

    case OPC2_32_BO_ST_Q_SHORTOFF:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        gen_offset_st(ctx, temp, cpu_gpr_a[r2], off10, MO_LEUW);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_Q_POSTINC:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        tcg_gen_qemu_st_tl(temp, cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUW);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_Q_PREINC:

        temp = tcg_temp_new();

        tcg_gen_shri_tl(temp, cpu_gpr_d[r1], 16);

        gen_st_preincr(ctx, temp, cpu_gpr_a[r2], off10, MO_LEUW);

        tcg_temp_free(temp);

        break;

    case OPC2_32_BO_ST_W_SHORTOFF:

        gen_offset_st(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUL);

        break;

    case OPC2_32_BO_ST_W_POSTINC:

        tcg_gen_qemu_st_tl(cpu_gpr_d[r1], cpu_gpr_a[r2], ctx->mem_idx,

                           MO_LEUL);

        tcg_gen_addi_tl(cpu_gpr_a[r2], cpu_gpr_a[r2], off10);

        break;

    case OPC2_32_BO_ST_W_PREINC:

        gen_st_preincr(ctx, cpu_gpr_d[r1], cpu_gpr_a[r2], off10, MO_LEUL);

        break;

    }

}


void ff_wms_parse_sdp_a_line(AVFormatContext *s, const char *p)

{

    if (av_strstart(p, "pgmpu:data:application/vnd.ms.wms-hdr.asfv1;base64,", &p)) {

        ByteIOContext pb;

        RTSPState *rt = s->priv_data;

        int len = strlen(p) * 6 / 8;

        char *buf = av_mallocz(len);

        av_base64_decode(buf, p, len);

        if (rtp_asf_fix_header(buf, len) < 0)

            av_log(s, AV_LOG_ERROR,

                   "Failed to fix invalid RTSP-MS/ASF min_pktsize\n");

        init_packetizer(&pb, buf, len);

        if (rt->asf_ctx) {

            av_close_input_stream(rt->asf_ctx);

            rt->asf_ctx = NULL;

        }

        av_open_input_stream(&rt->asf_ctx, &pb, "", &asf_demuxer, NULL);

        rt->asf_pb_pos = url_ftell(&pb);

        av_free(buf);

        rt->asf_ctx->pb = NULL;

    }

}


static int dtext_prepare_text(AVFilterContext *ctx)

{

    DrawTextContext *dtext = ctx->priv;

    uint32_t code = 0, prev_code = 0;

    int x = 0, y = 0, i = 0, ret;

    int text_height, baseline;

    char *text = dtext->text;

    uint8_t *p;

    int str_w = 0, len;

    int y_min = 32000, y_max = -32000;

    FT_Vector delta;

    Glyph *glyph = NULL, *prev_glyph = NULL;

    Glyph dummy = { 0 };

    int width  = ctx->inputs[0]->w;

    int height = ctx->inputs[0]->h;

#if HAVE_LOCALTIME_R

    time_t now = time(0);

    struct tm ltime;

    uint8_t *buf = dtext->expanded_text;

    int buf_size = dtext->expanded_text_size;

    if (!buf)

        buf_size = 2*strlen(dtext->text)+1;

    localtime_r(&now, &ltime);

    while ((buf = av_realloc(buf, buf_size))) {

        *buf = 1;

        if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)

            break;

        buf_size *= 2;

    }

    if (!buf)

        return AVERROR(ENOMEM);

    text = dtext->expanded_text = buf;

    dtext->expanded_text_size = buf_size;

#endif

    if ((len = strlen(text)) > dtext->nb_positions) {

        FT_Vector *p = av_realloc(dtext->positions,

                                  len * sizeof(*dtext->positions));

        if (!p) {

            av_freep(dtext->positions);

            dtext->nb_positions = 0;

            return AVERROR(ENOMEM);

        } else {

            dtext->positions = p;

            dtext->nb_positions = len;

        }

    }

    /* load and cache glyphs */

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* get glyph */

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        if (!glyph)

            ret = load_glyph(ctx, &glyph, code);

        if (ret) return ret;

        y_min = FFMIN(glyph->bbox.yMin, y_min);

        y_max = FFMAX(glyph->bbox.yMax, y_max);

    }

    text_height = y_max - y_min;

    baseline    = y_max;

    /* compute and save position for each glyph */

    glyph = NULL;

    for (i = 0, p = text; *p; i++) {

        GET_UTF8(code, *p++, continue;);

        /* skip the \n in the sequence \r\n */

        if (prev_code == '\r' && code == '\n')

            continue;

        prev_code = code;

        if (is_newline(code)) {

            str_w = FFMAX(str_w, x - dtext->x);

            y += text_height;

            x = 0;

            continue;

        }

        /* get glyph */

        prev_glyph = glyph;

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);

        /* kerning */

        if (dtext->use_kerning && prev_glyph && glyph->code) {

            FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,

                           ft_kerning_default, &delta);

            x += delta.x >> 6;

        }

        if (x + glyph->bbox.xMax >= width) {

            str_w = FFMAX(str_w, x);

            y += text_height;

            x = 0;

        }

        /* save position */

        dtext->positions[i].x = x + glyph->bitmap_left;

        dtext->positions[i].y = y - glyph->bitmap_top + baseline;

        if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;

        else              x += glyph->advance;

    }

    str_w = FFMIN(width - 1, FFMAX(str_w, x));

    y     = FFMIN(y + text_height, height - 1);

    dtext->w = str_w;

    dtext->h = y;

    return 0;

}


static int vsink_query_formats(AVFilterContext *ctx)

{

    BufferSinkContext *buf = ctx->priv;

    AVFilterFormats *formats = NULL;

    unsigned i;

    int ret;

    CHECK_LIST_SIZE(pixel_fmts)

    if (buf->pixel_fmts_size) {

        for (i = 0; i < NB_ITEMS(buf->pixel_fmts); i++)

            if ((ret = ff_add_format(&formats, buf->pixel_fmts[i])) < 0)

                return ret;

        ff_set_common_formats(ctx, formats);

    } else {

        ff_default_query_formats(ctx);

    }

    return 0;

}


static int poll_filters(void)

{

    AVFilterBufferRef *picref;

    AVFrame *filtered_frame = NULL;

    int i, frame_size;

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

        OutputStream *ost = output_streams[i];

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

        int ret = 0;

        if (!ost->filter)

            continue;

        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;

        while (ret >= 0 && !ost->is_past_recording_time) {

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

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

                ret = av_buffersink_read_samples(ost->filter->filter, &picref,

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

            else

                ret = av_buffersink_read(ost->filter->filter, &picref);

            if (ret < 0)

                break;

            avfilter_copy_buf_props(filtered_frame, picref);

            if (picref->pts != AV_NOPTS_VALUE)

                filtered_frame->pts = av_rescale_q(picref->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);

            if (of->start_time && filtered_frame->pts < of->start_time) {

                avfilter_unref_buffer(picref);

                continue;

            }

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

            case AVMEDIA_TYPE_VIDEO:

                if (!ost->frame_aspect_ratio)

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

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

                             same_quant ? ost->last_quality :

                                          ost->st->codec->global_quality);

                if (vstats_filename && frame_size)

                    do_video_stats(of->ctx, 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);

            }

            avfilter_unref_buffer(picref);

        }

    }

    return 0;

}


static int file_read_dir(URLContext *h, AVIODirEntry **next)

{

#if HAVE_DIRENT_H

    FileContext *c = h->priv_data;

    struct dirent *dir;

    char *fullpath = NULL;

    *next = ff_alloc_dir_entry();

    if (!*next)

        return AVERROR(ENOMEM);

    do {

        errno = 0;

        dir = readdir(c->dir);

        if (!dir) {

            av_freep(next);

            return AVERROR(errno);

        }

    } while (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."));

    fullpath = av_append_path_component(h->filename, dir->d_name);

    if (fullpath) {

        struct stat st;

        if (!lstat(fullpath, &st)) {

            if (S_ISDIR(st.st_mode))

                (*next)->type = AVIO_ENTRY_DIRECTORY;

            else if (S_ISFIFO(st.st_mode))

                (*next)->type = AVIO_ENTRY_NAMED_PIPE;

            else if (S_ISCHR(st.st_mode))

                (*next)->type = AVIO_ENTRY_CHARACTER_DEVICE;

            else if (S_ISBLK(st.st_mode))

                (*next)->type = AVIO_ENTRY_BLOCK_DEVICE;

            else if (S_ISLNK(st.st_mode))

                (*next)->type = AVIO_ENTRY_SYMBOLIC_LINK;

            else if (S_ISSOCK(st.st_mode))

                (*next)->type = AVIO_ENTRY_SOCKET;

            else if (S_ISREG(st.st_mode))

                (*next)->type = AVIO_ENTRY_FILE;

            else

                (*next)->type = AVIO_ENTRY_UNKNOWN;

            (*next)->group_id = st.st_gid;

            (*next)->user_id = st.st_uid;

            (*next)->size = st.st_size;

            (*next)->filemode = st.st_mode & 0777;

            (*next)->modification_timestamp = INT64_C(1000000) * st.st_mtime;

            (*next)->access_timestamp =  INT64_C(1000000) * st.st_atime;

            (*next)->status_change_timestamp = INT64_C(1000000) * st.st_ctime;

        }

        av_free(fullpath);

    }

    (*next)->name = av_strdup(dir->d_name);

    return 0;

#else

    return AVERROR(ENOSYS);

#endif /* HAVE_DIRENT_H */

}


static void monitor_qmp_event(void *opaque, int event)

{

    QObject *data;

    Monitor *mon = opaque;

    switch (event) {

    case CHR_EVENT_OPENED:

        mon->qmp.in_command_mode = false;

        data = get_qmp_greeting();

        monitor_json_emitter(mon, data);

        qobject_decref(data);

        mon_refcount++;

        break;

    case CHR_EVENT_CLOSED:

        json_message_parser_destroy(&mon->qmp.parser);

        json_message_parser_init(&mon->qmp.parser, handle_qmp_command);

        mon_refcount--;

        monitor_fdsets_cleanup();

        break;

    }

}


void add_user_command(char *optarg)

{

    ncmdline++;

    cmdline = realloc(cmdline, ncmdline * sizeof(char *));

    if (!cmdline) {

        perror("realloc");

        exit(1);

    }

    cmdline[ncmdline-1] = optarg;

}


static void check_update_timer(RTCState *s)

{

    uint64_t next_update_time;

    uint64_t guest_nsec;

    int next_alarm_sec;

    /* From the data sheet: "Holding the dividers in reset prevents

     * interrupts from operating, while setting the SET bit allows"

     * them to occur.  However, it will prevent an alarm interrupt

     * from occurring, because the time of day is not updated.

     */

    if ((s->cmos_data[RTC_REG_A] & 0x60) == 0x60) {

        timer_del(s->update_timer);

        return;

    }

    if ((s->cmos_data[RTC_REG_C] & REG_C_UF) &&

        (s->cmos_data[RTC_REG_B] & REG_B_SET)) {

        timer_del(s->update_timer);

        return;

    }

    if ((s->cmos_data[RTC_REG_C] & REG_C_UF) &&

        (s->cmos_data[RTC_REG_C] & REG_C_AF)) {

        timer_del(s->update_timer);

        return;

    }

    guest_nsec = get_guest_rtc_ns(s) % NANOSECONDS_PER_SECOND;

    /* if UF is clear, reprogram to next second */

    next_update_time = qemu_clock_get_ns(rtc_clock)

        + NANOSECONDS_PER_SECOND - guest_nsec;

    /* Compute time of next alarm.  One second is already accounted

     * for in next_update_time.

     */

    next_alarm_sec = get_next_alarm(s);

    s->next_alarm_time = next_update_time +

                         (next_alarm_sec - 1) * NANOSECONDS_PER_SECOND;

    if (s->cmos_data[RTC_REG_C] & REG_C_UF) {

        /* UF is set, but AF is clear.  Program the timer to target

         * the alarm time.  */

        next_update_time = s->next_alarm_time;

    }

    if (next_update_time != timer_expire_time_ns(s->update_timer)) {

        timer_mod(s->update_timer, next_update_time);

    }

}


int main(int argc, char **argv)

{

    TestInputVisitorData testdata;

    g_test_init(&argc, &argv, NULL);

    validate_test_add("/visitor/input-strict/pass/struct",

                       &testdata, test_validate_struct);

    validate_test_add("/visitor/input-strict/pass/struct-nested",

                       &testdata, test_validate_struct_nested);

    validate_test_add("/visitor/input-strict/pass/list",

                       &testdata, test_validate_list);

    validate_test_add("/visitor/input-strict/pass/union",

                       &testdata, test_validate_union);

    validate_test_add("/visitor/input-strict/pass/union-flat",

                       &testdata, test_validate_union_flat);

    validate_test_add("/visitor/input-strict/pass/union-anon",

                       &testdata, test_validate_union_anon);

    validate_test_add("/visitor/input-strict/fail/struct",

                       &testdata, test_validate_fail_struct);

    validate_test_add("/visitor/input-strict/fail/struct-nested",

                       &testdata, test_validate_fail_struct_nested);

    validate_test_add("/visitor/input-strict/fail/list",

                       &testdata, test_validate_fail_list);

    validate_test_add("/visitor/input-strict/fail/union",

                       &testdata, test_validate_fail_union);

    validate_test_add("/visitor/input-strict/fail/union-flat",

                       &testdata, test_validate_fail_union_flat);

    validate_test_add("/visitor/input-strict/fail/union-flat-no-discriminator",

                       &testdata, test_validate_fail_union_flat_no_discrim);

    validate_test_add("/visitor/input-strict/fail/union-anon",

                       &testdata, test_validate_fail_union_anon);

    g_test_run();

    return 0;

}


void slirp_select_fill(int *pnfds,

                       fd_set *readfds, fd_set *writefds, fd_set *xfds)

{

    Slirp *slirp;

    struct socket *so, *so_next;

    int nfds;

    if (QTAILQ_EMPTY(&slirp_instances)) {

        return;

    }

    /* fail safe */

    global_readfds = NULL;

    global_writefds = NULL;

    global_xfds = NULL;

    nfds = *pnfds;

    /*

     * First, TCP sockets

     */

    do_slowtimo = 0;

    QTAILQ_FOREACH(slirp, &slirp_instances, entry) {

        /*

         * *_slowtimo needs calling if there are IP fragments

         * in the fragment queue, or there are TCP connections active

         */

        do_slowtimo |= ((slirp->tcb.so_next != &slirp->tcb) ||

                (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));

        for (so = slirp->tcb.so_next; so != &slirp->tcb;

                so = so_next) {

            so_next = so->so_next;

            /*

             * See if we need a tcp_fasttimo

             */

            if (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK) {

                time_fasttimo = curtime; /* Flag when we want a fasttimo */

            }

            /*

             * NOFDREF can include still connecting to local-host,

             * newly socreated() sockets etc. Don't want to select these.

             */

            if (so->so_state & SS_NOFDREF || so->s == -1) {

                continue;

            }

            /*

             * Set for reading sockets which are accepting

             */

            if (so->so_state & SS_FACCEPTCONN) {

                FD_SET(so->s, readfds);

                UPD_NFDS(so->s);

                continue;

            }

            /*

             * Set for writing sockets which are connecting

             */

            if (so->so_state & SS_ISFCONNECTING) {

                FD_SET(so->s, writefds);

                UPD_NFDS(so->s);

                continue;

            }

            /*

             * Set for writing if we are connected, can send more, and

             * we have something to send

             */

            if (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {

                FD_SET(so->s, writefds);

                UPD_NFDS(so->s);

            }

            /*

             * Set for reading (and urgent data) if we are connected, can

             * receive more, and we have room for it XXX /2 ?

             */

            if (CONN_CANFRCV(so) &&

                (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {

                FD_SET(so->s, readfds);

                FD_SET(so->s, xfds);

                UPD_NFDS(so->s);

            }

        }

        /*

         * UDP sockets

         */

        for (so = slirp->udb.so_next; so != &slirp->udb;

                so = so_next) {

            so_next = so->so_next;

            /*

             * See if it's timed out

             */

            if (so->so_expire) {

                if (so->so_expire <= curtime) {

                    udp_detach(so);

                    continue;

                } else {

                    do_slowtimo = 1; /* Let socket expire */

                }

            }

            /*

             * When UDP packets are received from over the

             * link, they're sendto()'d straight away, so

             * no need for setting for writing

             * Limit the number of packets queued by this session

             * to 4.  Note that even though we try and limit this

             * to 4 packets, the session could have more queued

             * if the packets needed to be fragmented

             * (XXX <= 4 ?)

             */

            if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {

                FD_SET(so->s, readfds);

                UPD_NFDS(so->s);

            }

        }

        /*

         * ICMP sockets

         */

        for (so = slirp->icmp.so_next; so != &slirp->icmp;

                so = so_next) {

            so_next = so->so_next;

            /*

             * See if it's timed out

             */

            if (so->so_expire) {

                if (so->so_expire <= curtime) {

                    icmp_detach(so);

                    continue;

                } else {

                    do_slowtimo = 1; /* Let socket expire */

                }

            }

            if (so->so_state & SS_ISFCONNECTED) {

                FD_SET(so->s, readfds);

                UPD_NFDS(so->s);

            }

        }

    }

    *pnfds = nfds;

}


static void test_validate_qmp_introspect(TestInputVisitorData *data,

                                           const void *unused)

{

    do_test_validate_qmp_introspect(data, test_qmp_schema_json);

    do_test_validate_qmp_introspect(data, qmp_schema_json);

}


static void dump_receive(void *opaque, const uint8_t *buf, size_t size)

{

    DumpState *s = opaque;

    struct pcap_sf_pkthdr hdr;

    int64_t ts;

    int caplen;

    /* Early return in case of previous error. */

    if (s->fd < 0) {

        return;

    }

    ts = muldiv64(qemu_get_clock(vm_clock), 1000000, ticks_per_sec);

    caplen = size > s->pcap_caplen ? s->pcap_caplen : size;

    hdr.ts.tv_sec = ts / 1000000;

    hdr.ts.tv_usec = ts % 1000000;

    hdr.caplen = caplen;

    hdr.len = size;

    if (write(s->fd, &hdr, sizeof(hdr)) != sizeof(hdr) ||

        write(s->fd, buf, caplen) != caplen) {

        qemu_log("-net dump write error - stop dump\n");

        close(s->fd);

        s->fd = -1;

    }

}


void OPPROTO op_mov_T0_cc(void)

{

    T0 = cc_table[CC_OP].compute_all();

}


static int alsa_run_in (HWVoiceIn *hw)

{

    ALSAVoiceIn *alsa = (ALSAVoiceIn *) hw;

    int hwshift = hw->info.shift;

    int i;

    int live = audio_pcm_hw_get_live_in (hw);

    int dead = hw->samples - live;

    int decr;

    struct {

        int add;

        int len;

    } bufs[2] = {

        { hw->wpos, 0 },

        { 0, 0 }

    };

    snd_pcm_sframes_t avail;

    snd_pcm_uframes_t read_samples = 0;

    if (!dead) {

        return 0;

    }

    avail = alsa_get_avail (alsa->handle);

    if (avail < 0) {

        dolog ("Could not get number of captured frames\n");

        return 0;

    }

    if (!avail && (snd_pcm_state (alsa->handle) == SND_PCM_STATE_PREPARED)) {

        avail = hw->samples;

    }

    decr = audio_MIN (dead, avail);

    if (!decr) {

        return 0;

    }

    if (hw->wpos + decr > hw->samples) {

        bufs[0].len = (hw->samples - hw->wpos);

        bufs[1].len = (decr - (hw->samples - hw->wpos));

    }

    else {

        bufs[0].len = decr;

    }

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

        void *src;

        st_sample_t *dst;

        snd_pcm_sframes_t nread;

        snd_pcm_uframes_t len;

        len = bufs[i].len;

        src = advance (alsa->pcm_buf, bufs[i].add << hwshift);

        dst = hw->conv_buf + bufs[i].add;

        while (len) {

            nread = snd_pcm_readi (alsa->handle, src, len);

            if (nread <= 0) {

                switch (nread) {

                case 0:

                    if (conf.verbose) {

                        dolog ("Failed to read %ld frames (read zero)\n", len);

                    }

                    goto exit;

                case -EPIPE:

                    if (alsa_recover (alsa->handle)) {

                        alsa_logerr (nread, "Failed to read %ld frames\n", len);

                        goto exit;

                    }

                    if (conf.verbose) {

                        dolog ("Recovering from capture xrun\n");

                    }

                    continue;

                case -EAGAIN:

                    goto exit;

                default:

                    alsa_logerr (

                        nread,

                        "Failed to read %ld frames from %p\n",

                        len,

                        src

                        );

                    goto exit;

                }

            }

            hw->conv (dst, src, nread, &nominal_volume);

            src = advance (src, nread << hwshift);

            dst += nread;

            read_samples += nread;

            len -= nread;

        }

    }

 exit:

    hw->wpos = (hw->wpos + read_samples) % hw->samples;

    return read_samples;

}


static void do_change(int argc, const char **argv)

{

    BlockDriverState *bs;

    if (argc != 3) {

        help_cmd(argv[0]);

        return;

    }

    bs = bdrv_find(argv[1]);

    if (!bs) {

        term_printf("device not found\n");

        return;

    }

    if (eject_device(bs, 0) < 0)

        return;

    bdrv_open(bs, argv[2], 0);

}


static void opt_qscale(const char *arg)

{

    video_qscale = atof(arg);

    if (video_qscale <= 0 ||

        video_qscale > 255) {

        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");

        ffmpeg_exit(1);

    }

}


static int multiple_resample(ResampleContext *c, AudioData *dst, int dst_size, AudioData *src, int src_size, int *consumed){

    int i, ret= -1;

    int av_unused mm_flags = av_get_cpu_flags();

    int need_emms = c->format == AV_SAMPLE_FMT_S16P && ARCH_X86_32 &&

                    (mm_flags & (AV_CPU_FLAG_MMX2 | AV_CPU_FLAG_SSE2)) == AV_CPU_FLAG_MMX2;

    int64_t max_src_size = (INT64_MAX/2 / c->phase_count) / c->src_incr;

    if (c->compensation_distance)

        dst_size = FFMIN(dst_size, c->compensation_distance);

    src_size = FFMIN(src_size, max_src_size);

    for(i=0; i<dst->ch_count; i++){

        ret= swri_resample(c, dst->ch[i], src->ch[i],

                           consumed, src_size, dst_size, i+1==dst->ch_count);

    }

    if(need_emms)

        emms_c();

    if (c->compensation_distance) {

        c->compensation_distance -= ret;

        if (!c->compensation_distance) {

            c->dst_incr     = c->ideal_dst_incr;

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

            c->dst_incr_mod = c->dst_incr % c->src_incr;

        }

    }

    return ret;

}


static bool run_poll_handlers(AioContext *ctx, int64_t max_ns)

{

    bool progress;

    int64_t end_time;

    assert(ctx->notify_me);

    assert(qemu_lockcnt_count(&ctx->list_lock) > 0);

    assert(ctx->poll_disable_cnt == 0);

    trace_run_poll_handlers_begin(ctx, max_ns);

    end_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + max_ns;

    do {

        progress = run_poll_handlers_once(ctx);

    } while (!progress && qemu_clock_get_ns(QEMU_CLOCK_REALTIME) < end_time);

    trace_run_poll_handlers_end(ctx, progress);

    return progress;

}


static CharDriverState *qemu_chr_open_win_con(const char *id,

                                              ChardevBackend *backend,

                                              ChardevReturn *ret,

                                              Error **errp)

{

    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));

}


void qmp_nbd_server_start(SocketAddress *addr,

                          bool has_tls_creds, const char *tls_creds,

                          Error **errp)

{

    if (nbd_server) {

        error_setg(errp, "NBD server already running");

        return;

    }

    nbd_server = g_new0(NBDServerData, 1);

    nbd_server->watch = -1;

    nbd_server->listen_ioc = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL(nbd_server->listen_ioc),

                         "nbd-listener");

    if (qio_channel_socket_listen_sync(

            nbd_server->listen_ioc, addr, errp) < 0) {

        goto error;

    }

    if (has_tls_creds) {

        nbd_server->tlscreds = nbd_get_tls_creds(tls_creds, errp);

        if (!nbd_server->tlscreds) {

            goto error;

        }

        /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */

        if (addr->type != SOCKET_ADDRESS_KIND_INET) {

            error_setg(errp, "TLS is only supported with IPv4/IPv6");

            goto error;

        }

    }

    nbd_server->watch = qio_channel_add_watch(

        QIO_CHANNEL(nbd_server->listen_ioc),

        G_IO_IN,

        nbd_accept,

        NULL,

        NULL);

    return;

 error:

    nbd_server_free(nbd_server);

    nbd_server = NULL;

}


int v9fs_co_mkdir(V9fsState *s, char *name, mode_t mode, uid_t uid, gid_t gid)

{

    int err;

    FsCred cred;

    cred_init(&cred);

    cred.fc_mode = mode;

    cred.fc_uid = uid;

    cred.fc_gid = gid;

    v9fs_co_run_in_worker(

        {

            err = s->ops->mkdir(&s->ctx, name, &cred);

            if (err < 0) {

                err = -errno;

            }

        });

    return err;

}


static uint32_t nam_readw (void *opaque, uint32_t addr)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    uint32_t val = ~0U;

    uint32_t index = addr - s->base[0];

    s->cas = 0;

    val = mixer_load (s, index);

    return val;

}


static uint32_t virtio_net_bad_features(VirtIODevice *vdev)

{

    uint32_t features = 0;

    /* Linux kernel 2.6.25.  It understood MAC (as everyone must),

     * but also these: */

    features |= (1 << VIRTIO_NET_F_MAC);

    features |= (1 << VIRTIO_NET_F_CSUM);

    features |= (1 << VIRTIO_NET_F_HOST_TSO4);

    features |= (1 << VIRTIO_NET_F_HOST_TSO6);

    features |= (1 << VIRTIO_NET_F_HOST_ECN);

    return features;

}


void visit_type_uint16(Visitor *v, uint16_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (v->type_uint16) {

        v->type_uint16(v, obj, name, errp);

    } else {

        value = *obj;

        v->type_int64(v, &value, name, errp);

        if (value < 0 || value > UINT16_MAX) {

            /* FIXME questionable reuse of errp if callback changed

               value on error */

            error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                       name ? name : "null", "uint16_t");

            return;

        }

        *obj = value;

    }

}


static int try_decode_frame(AVStream *st, AVPacket *avpkt)

{

    int16_t *samples;

    AVCodec *codec;

    int got_picture, data_size, ret=0;

    AVFrame picture;

    if(!st->codec->codec){

        codec = avcodec_find_decoder(st->codec->codec_id);

        if (!codec)

            return -1;

        ret = avcodec_open(st->codec, codec);

        if (ret < 0)

            return ret;

    }

    if(!has_codec_parameters(st->codec)){

        switch(st->codec->codec_type) {

        case CODEC_TYPE_VIDEO:

            ret = avcodec_decode_video2(st->codec, &picture,

                                        &got_picture, avpkt);

            break;

        case CODEC_TYPE_AUDIO:

            data_size = FFMAX(avpkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE);

            samples = av_malloc(data_size);

            if (!samples)

                goto fail;

            ret = avcodec_decode_audio3(st->codec, samples,

                                        &data_size, avpkt);

            av_free(samples);

            break;

        default:

            break;

        }

    }

 fail:

    return ret;

}


int s390_virtio_hypercall(CPUS390XState *env)

{

    s390_virtio_fn fn = s390_diag500_table[env->regs[1]];

    if (!fn) {

        return -EINVAL;

    }

    return fn(&env->regs[2]);

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                         int *got_picture_ptr,

                         AVPacket *avpkt)

{

    int ret;

    *got_picture_ptr= 0;

    if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

        return -1;

    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){

        av_packet_split_side_data(avpkt);

        apply_param_change(avctx, avpkt);

        avctx->pkt = avpkt;

        if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)

             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                          avpkt);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                              avpkt);

            picture->pkt_dts= avpkt->dts;

            if(!avctx->has_b_frames){

            picture->pkt_pos= avpkt->pos;

            }

            //FIXME these should be under if(!avctx->has_b_frames)

            if (!picture->sample_aspect_ratio.num)

                picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

            if (!picture->width)

                picture->width = avctx->width;

            if (!picture->height)

                picture->height = avctx->height;

            if (picture->format == PIX_FMT_NONE)

                picture->format = avctx->pix_fmt;

        }

        emms_c(); //needed to avoid an emms_c() call before every return;

        if (*got_picture_ptr){

            avctx->frame_number++;

            picture->best_effort_timestamp = guess_correct_pts(avctx,

                                                            picture->pkt_pts,

                                                            picture->pkt_dts);

        }

    }else

        ret= 0;

    return ret;

}


void qemu_thread_create(QemuThread *thread, const char *name,

                       void *(*start_routine)(void*),

                       void *arg, int mode)

{

    sigset_t set, oldset;

    int err;

    pthread_attr_t attr;

    err = pthread_attr_init(&attr);

    if (err) {

        error_exit(err, __func__);

    }

    if (mode == QEMU_THREAD_DETACHED) {

        err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        if (err) {

            error_exit(err, __func__);

        }

    }

    /* Leave signal handling to the iothread.  */

    sigfillset(&set);

    pthread_sigmask(SIG_SETMASK, &set, &oldset);

    err = pthread_create(&thread->thread, &attr, start_routine, arg);

    if (err)

        error_exit(err, __func__);

    if (name_threads) {

        qemu_thread_set_name(thread, name);

    }

    pthread_sigmask(SIG_SETMASK, &oldset, NULL);

    pthread_attr_destroy(&attr);

}


static inline void vmsvga_fill_rect(struct vmsvga_state_s *s,

                uint32_t c, int x, int y, int w, int h)

{

    DisplaySurface *surface = qemu_console_surface(s->vga.con);

    int bypl = surface_stride(surface);

    int width = surface_bytes_per_pixel(surface) * w;

    int line = h;

    int column;

    uint8_t *fst;

    uint8_t *dst;

    uint8_t *src;

    uint8_t col[4];

    col[0] = c;

    col[1] = c >> 8;

    col[2] = c >> 16;

    col[3] = c >> 24;

    fst = s->vga.vram_ptr + surface_bytes_per_pixel(surface) * x + bypl * y;

    if (line--) {

        dst = fst;

        src = col;

        for (column = width; column > 0; column--) {

            *(dst++) = *(src++);

            if (src - col == surface_bytes_per_pixel(surface)) {

                src = col;

            }

        }

        dst = fst;

        for (; line > 0; line--) {

            dst += bypl;

            memcpy(dst, fst, width);

        }

    }

    vmsvga_update_rect_delayed(s, x, y, w, h);

}


static void IMLT(float *pInput, float *pOutput, int odd_band)

{

    int     i;

    if (odd_band) {

        /**

        * Reverse the odd bands before IMDCT, this is an effect of the QMF transform

        * or it gives better compression to do it this way.

        * FIXME: It should be possible to handle this in ff_imdct_calc

        * for that to happen a modification of the prerotation step of

        * all SIMD code and C code is needed.

        * Or fix the functions before so they generate a pre reversed spectrum.

        */

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

            FFSWAP(float, pInput[i], pInput[255-i]);

    }

    ff_imdct_calc(&mdct_ctx,pOutput,pInput);

    /* Perform windowing on the output. */

    dsp.vector_fmul(pOutput,mdct_window,512);

}


static void mxf_write_generic_sound_common(AVFormatContext *s, AVStream *st, const UID key, unsigned size)

{

    AVIOContext *pb = s->pb;

    mxf_write_generic_desc(s, st, key, size+5+12+8+8);

    // audio locked

    mxf_write_local_tag(pb, 1, 0x3D02);

    avio_w8(pb, 1);

    // write audio sampling rate

    mxf_write_local_tag(pb, 8, 0x3D03);

    avio_wb32(pb, st->codec->sample_rate);

    avio_wb32(pb, 1);

    mxf_write_local_tag(pb, 4, 0x3D07);

    avio_wb32(pb, st->codec->channels);

    mxf_write_local_tag(pb, 4, 0x3D01);

    avio_wb32(pb, av_get_bits_per_sample(st->codec->codec_id));

}


static void mpeg_decode_quant_matrix_extension(MpegEncContext *s)

{

    int i, v, j;

    dprintf("matrix extension\n");

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->intra_matrix[j] = v;

            s->chroma_intra_matrix[j] = v;

        }

    }

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->non_intra_matrix[j] = v;

            s->chroma_non_intra_matrix[j] = v;

        }

    }

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->chroma_intra_matrix[j] = v;

        }

    }

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->chroma_non_intra_matrix[j] = v;

        }

    }

}


uint64_t HELPER(neon_abdl_s16)(uint32_t a, uint32_t b)

{

    uint64_t tmp;

    uint64_t result;

    DO_ABD(result, a, b, int8_t);

    DO_ABD(tmp, a >> 8, b >> 8, int8_t);

    result |= tmp << 16;

    DO_ABD(tmp, a >> 16, b >> 16, int8_t);

    result |= tmp << 32;

    DO_ABD(tmp, a >> 24, b >> 24, int8_t);

    result |= tmp << 48;

    return result;

}


int pcie_cap_v1_init(PCIDevice *dev, uint8_t offset, uint8_t type,

                     uint8_t port)

{

    /* PCIe cap v1 init */

    int pos;

    uint8_t *exp_cap;

    assert(pci_is_express(dev));

    pos = pci_add_capability(dev, PCI_CAP_ID_EXP, offset, PCI_EXP_VER1_SIZEOF);

    if (pos < 0) {

        return pos;

    }

    dev->exp.exp_cap = pos;

    exp_cap = dev->config + pos;

    pcie_cap_v1_fill(exp_cap, port, type, PCI_EXP_FLAGS_VER1);

    return pos;

}


static int oggvorbis_encode_frame(AVCodecContext *avctx, unsigned char *packets,

                                  int buf_size, void *data)

{

    OggVorbisContext *s = avctx->priv_data;

    ogg_packet op;

    float *audio = data;

    int pkt_size;

    /* send samples to libvorbis */

    if (data) {

        const int samples = avctx->frame_size;

        float **buffer;

        int c, channels = s->vi.channels;

        buffer = vorbis_analysis_buffer(&s->vd, samples);

        for (c = 0; c < channels; c++) {

            int i;

            int co = (channels > 8) ? c :

                     ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];

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

                buffer[c][i] = audio[i * channels + co];

        }

        vorbis_analysis_wrote(&s->vd, samples);

    } else {

        if (!s->eof)

            vorbis_analysis_wrote(&s->vd, 0);

        s->eof = 1;

    }

    /* retrieve available packets from libvorbis */

    while (vorbis_analysis_blockout(&s->vd, &s->vb) == 1) {

        vorbis_analysis(&s->vb, NULL);

        vorbis_bitrate_addblock(&s->vb);

        /* add any available packets to the output packet buffer */

        while (vorbis_bitrate_flushpacket(&s->vd, &op)) {

            /* i'd love to say the following line is a hack, but sadly it's

             * not, apparently the end of stream decision is in libogg. */

            if (op.bytes == 1 && op.e_o_s)

                continue;

            if (s->buffer_index + sizeof(ogg_packet) + op.bytes > BUFFER_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "libvorbis: buffer overflow.");

                return -1;

            }

            memcpy(s->buffer + s->buffer_index, &op, sizeof(ogg_packet));

            s->buffer_index += sizeof(ogg_packet);

            memcpy(s->buffer + s->buffer_index, op.packet, op.bytes);

            s->buffer_index += op.bytes;

        }

    }

    /* output then next packet from the output buffer, if available */

    pkt_size = 0;

    if (s->buffer_index) {

        ogg_packet *op2 = (ogg_packet *)s->buffer;

        op2->packet     = s->buffer + sizeof(ogg_packet);

        pkt_size = op2->bytes;

        // FIXME: we should use the user-supplied pts and duration

        avctx->coded_frame->pts = ff_samples_to_time_base(avctx,

                                                          op2->granulepos);

        if (pkt_size > buf_size) {

            av_log(avctx, AV_LOG_ERROR, "libvorbis: buffer overflow.");

            return -1;

        }

        memcpy(packets, op2->packet, pkt_size);

        s->buffer_index -= pkt_size + sizeof(ogg_packet);

        memmove(s->buffer, s->buffer + pkt_size + sizeof(ogg_packet),

                s->buffer_index);

    }

    return pkt_size;

}


static void av_always_inline filter_mb_edgev( uint8_t *pix, int stride, const int16_t bS[4], unsigned int qp, H264Context *h, int intra ) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 || !intra ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]];

        tc[1] = tc0_table[index_a][bS[1]];

        tc[2] = tc0_table[index_a][bS[2]];

        tc[3] = tc0_table[index_a][bS[3]];

        h->h264dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_luma_intra(pix, stride, alpha, beta);

    }

}


static void v9fs_getlock(void *opaque)
{
    size_t offset = 7;
    struct stat stbuf;
    V9fsFidState *fidp;
    V9fsGetlock *glock;
    int32_t fid, err = 0;
    V9fsPDU *pdu = opaque;
    V9fsState *s = pdu->s;
    glock = g_malloc(sizeof(*glock));
    pdu_unmarshal(pdu, offset, "dbqqds", &fid, &glock->type,
                  &glock->start, &glock->length, &glock->proc_id,
                  &glock->client_id);
    trace_v9fs_getlock(pdu->tag, pdu->id, fid,
                       glock->type, glock->start, glock->length);
    fidp = get_fid(pdu, fid);
    if (fidp == NULL) {
        err = -ENOENT;
        goto out_nofid;
    }
    err = v9fs_co_fstat(pdu, fidp->fs.fd, &stbuf);
    if (err < 0) {
        goto out;
    }
    glock->type = P9_LOCK_TYPE_UNLCK;
    offset += pdu_marshal(pdu, offset, "bqqds", glock->type,
                          glock->start, glock->length, glock->proc_id,
                          &glock->client_id);
    err = offset;
out:
    put_fid(pdu, fidp);
out_nofid:
    complete_pdu(s, pdu, err);
    v9fs_string_free(&glock->client_id);
    g_free(glock);
}


static int vp9_superframe_filter(AVBSFContext *ctx, AVPacket *out)

{

    BitstreamContext bc;

    VP9BSFContext *s = ctx->priv_data;

    AVPacket *in;

    int res, invisible, profile, marker, uses_superframe_syntax = 0, n;

    res = ff_bsf_get_packet(ctx, &in);

    if (res < 0)

        return res;

    marker = in->data[in->size - 1];

    if ((marker & 0xe0) == 0xc0) {

        int nbytes = 1 + ((marker >> 3) & 0x3);

        int n_frames = 1 + (marker & 0x7), idx_sz = 2 + n_frames * nbytes;

        uses_superframe_syntax = in->size >= idx_sz && in->data[in->size - idx_sz] == marker;

    }

    res = bitstream_init8(&bc, in->data, in->size);

    if (res < 0)

        goto done;

    bitstream_read(&bc, 2); // frame marker

    profile  = bitstream_read(&bc, 1);

    profile |= bitstream_read(&bc, 1) << 1;

    if (profile == 3)

        profile += bitstream_read(&bc, 1);

    if (bitstream_read(&bc, 1)) {

        invisible = 0;

    } else {

        bitstream_read(&bc, 1); // keyframe

        invisible = !bitstream_read(&bc, 1);

    }

    if (uses_superframe_syntax && s->n_cache > 0) {

        av_log(ctx, AV_LOG_ERROR,

               "Mixing of superframe syntax and naked VP9 frames not supported");

        res = AVERROR(ENOSYS);

        goto done;

    } else if ((!invisible || uses_superframe_syntax) && !s->n_cache) {

        // passthrough

        av_packet_move_ref(out, in);

        goto done;

    } else if (s->n_cache + 1 >= MAX_CACHE) {

        av_log(ctx, AV_LOG_ERROR,

               "Too many invisible frames");

        res = AVERROR_INVALIDDATA;

        goto done;

    }

    s->cache[s->n_cache++] = in;

    in                     = NULL;

    if (invisible) {

        res = AVERROR(EAGAIN);

        goto done;

    }

    av_assert0(s->n_cache > 0);

    // build superframe

    if ((res = merge_superframe(s->cache, s->n_cache, out)) < 0)

        goto done;

    res = av_packet_copy_props(out, s->cache[s->n_cache - 1]);

    if (res < 0)

        goto done;

    for (n = 0; n < s->n_cache; n++)

        av_packet_free(&s->cache[n]);

    s->n_cache = 0;

done:

    if (res < 0)

        av_packet_unref(out);

    av_packet_free(&in);

    return res;

}


static int virtio_pci_set_host_notifier_internal(VirtIOPCIProxy *proxy,

                                                 int n, bool assign, bool set_handler)

{

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    VirtQueue *vq = virtio_get_queue(vdev, n);

    EventNotifier *notifier = virtio_queue_get_host_notifier(vq);

    int r = 0;

    if (assign) {

        r = event_notifier_init(notifier, 1);

        if (r < 0) {

            error_report("%s: unable to init event notifier: %d",

                         __func__, r);

            return r;

        }

        virtio_queue_set_host_notifier_fd_handler(vq, true, set_handler);

        memory_region_add_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,

                                  true, n, notifier);

    } else {

        memory_region_del_eventfd(&proxy->bar, VIRTIO_PCI_QUEUE_NOTIFY, 2,

                                  true, n, notifier);

        virtio_queue_set_host_notifier_fd_handler(vq, false, false);

        event_notifier_cleanup(notifier);

    }

    return r;

}


static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, int srcWidth, int srcHeight, int srcStride, int dstStride)

{

    int x,y;

    dst[0]= src[0];

    // first line

    for (x=0; x<srcWidth-1; x++) {

        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

    }

    dst[2*srcWidth-1]= src[srcWidth-1];

    dst+= dstStride;

    for (y=1; y<srcHeight; y++) {

        const x86_reg mmxSize= srcWidth&~15;

        __asm__ volatile(

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

            "movq        "MANGLE(mmx_ff)", %%mm0    \n\t"

            "movq         (%0, %%"REG_a"), %%mm4    \n\t"

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

            "psllq                     $8, %%mm4    \n\t"

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

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

            "movq         (%1, %%"REG_a"), %%mm5    \n\t"

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

            "psllq                     $8, %%mm5    \n\t"

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

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

            "1:                                     \n\t"

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

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

            "movq        1(%0, %%"REG_a"), %%mm2    \n\t"

            "movq        1(%1, %%"REG_a"), %%mm3    \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

            "punpckhbw              %%mm2, %%mm6    \n\t"

            MOVNTQ"                 %%mm5,  (%2, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm7, 8(%2, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm4,  (%3, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm6, 8(%3, %%"REG_a", 2)  \n\t"

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

            "movq       -1(%0, %%"REG_a"), %%mm4    \n\t"

            "movq       -1(%1, %%"REG_a"), %%mm5    \n\t"

            " js                       1b                       \n\t"

            :: "r" (src + mmxSize  ), "r" (src + srcStride + mmxSize  ),

               "r" (dst + mmxSize*2), "r" (dst + dstStride + mmxSize*2),

               "g" (-mmxSize)

               NAMED_CONSTRAINTS_ADD(mmx_ff)

            : "%"REG_a

        );

        for (x=mmxSize-1; x<srcWidth-1; x++) {

            dst[2*x          +1]= (3*src[x+0] +   src[x+srcStride+1])>>2;

            dst[2*x+dstStride+2]= (  src[x+0] + 3*src[x+srcStride+1])>>2;

            dst[2*x+dstStride+1]= (  src[x+1] + 3*src[x+srcStride  ])>>2;

            dst[2*x          +2]= (3*src[x+1] +   src[x+srcStride  ])>>2;

        }

        dst[srcWidth*2 -1            ]= (3*src[srcWidth-1] +   src[srcWidth-1 + srcStride])>>2;

        dst[srcWidth*2 -1 + dstStride]= (  src[srcWidth-1] + 3*src[srcWidth-1 + srcStride])>>2;

        dst+=dstStride*2;

        src+=srcStride;

    }

    // last line

    dst[0]= src[0];

    for (x=0; x<srcWidth-1; x++) {

        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

    }

    dst[2*srcWidth-1]= src[srcWidth-1];

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

}


int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)

{

    int64_t offset1;

    int64_t pos;

    int force = whence & AVSEEK_FORCE;

    whence &= ~AVSEEK_FORCE;

    if(!s)

        return AVERROR(EINVAL);

    pos = s->pos - (s->write_flag ? 0 : (s->buf_end - s->buffer));

    if (whence != SEEK_CUR && whence != SEEK_SET)

        return AVERROR(EINVAL);

    if (whence == SEEK_CUR) {

        offset1 = pos + (s->buf_ptr - s->buffer);

        if (offset == 0)

            return offset1;

        offset += offset1;

    }

    offset1 = offset - pos;

    if (!s->must_flush &&

        offset1 >= 0 && offset1 < (s->buf_end - s->buffer)) {

        /* can do the seek inside the buffer */

        s->buf_ptr = s->buffer + offset1;

    } else if ((!s->seekable ||

               offset1 <= s->buf_end + SHORT_SEEK_THRESHOLD - s->buffer) &&

               !s->write_flag && offset1 >= 0 &&

              (whence != SEEK_END || force)) {

        while(s->pos < offset && !s->eof_reached)

            fill_buffer(s);

        if (s->eof_reached)

            return AVERROR_EOF;

        s->buf_ptr = s->buf_end + offset - s->pos;

    } else {

        int64_t res;

        if (s->write_flag) {

            flush_buffer(s);

            s->must_flush = 1;

        }

        if (!s->seek)

            return AVERROR(EPIPE);

        if ((res = s->seek(s->opaque, offset, SEEK_SET)) < 0)

            return res;

        if (!s->write_flag)

            s->buf_end = s->buffer;

        s->buf_ptr = s->buffer;

        s->pos = offset;

    }

    s->eof_reached = 0;

    return offset;

}


static int net_vhost_check_net(void *opaque, QemuOpts *opts, Error **errp)

{

    const char *name = opaque;

    const char *driver, *netdev;

    const char virtio_name[] = "virtio-net-";

    driver = qemu_opt_get(opts, "driver");

    netdev = qemu_opt_get(opts, "netdev");

    if (!driver || !netdev) {

        return 0;

    }

    if (strcmp(netdev, name) == 0 &&

        strncmp(driver, virtio_name, strlen(virtio_name)) != 0) {

        error_report("vhost-user requires frontend driver virtio-net-*");

        return -1;

    }

    return 0;

}


static bool tlb_is_dirty_ram(CPUTLBEntry *tlbe)

{

    return (tlbe->addr_write & (TLB_INVALID_MASK|TLB_MMIO|TLB_NOTDIRTY)) == 0;

}


static int mxf_read_generic_descriptor(MXFDescriptor *descriptor, ByteIOContext *pb, int tag, int size, UID uid)

{

    switch(tag) {

    case 0x3F01:

        descriptor->sub_descriptors_count = get_be32(pb);

        if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))

            return -1;

        descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));

        if (!descriptor->sub_descriptors_refs)

            return -1;

        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */

        get_buffer(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));

        break;

    case 0x3004:

        get_buffer(pb, descriptor->essence_container_ul, 16);

        break;

    case 0x3006:

        descriptor->linked_track_id = get_be32(pb);

        break;

    case 0x3201: /* PictureEssenceCoding */

        get_buffer(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3203:

        descriptor->width = get_be32(pb);

        break;

    case 0x3202:

        descriptor->height = get_be32(pb);

        break;

    case 0x320E:

        descriptor->aspect_ratio.num = get_be32(pb);

        descriptor->aspect_ratio.den = get_be32(pb);

        break;

    case 0x3D03:

        descriptor->sample_rate.num = get_be32(pb);

        descriptor->sample_rate.den = get_be32(pb);

        break;

    case 0x3D06: /* SoundEssenceCompression */

        get_buffer(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3D07:

        descriptor->channels = get_be32(pb);

        break;

    case 0x3D01:

        descriptor->bits_per_sample = get_be32(pb);

        break;

    case 0x3401:

        mxf_read_pixel_layout(pb, descriptor);

        break;

    default:

        /* Private uid used by SONY C0023S01.mxf */

        if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {

            descriptor->extradata = av_malloc(size);

            if (!descriptor->extradata)

                return -1;

            descriptor->extradata_size = size;

            get_buffer(pb, descriptor->extradata, size);

        }

        break;

    }

    return 0;

}


static void spapr_vio_busdev_realize(DeviceState *qdev, Error **errp)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    VIOsPAPRDevice *dev = (VIOsPAPRDevice *)qdev;

    VIOsPAPRDeviceClass *pc = VIO_SPAPR_DEVICE_GET_CLASS(dev);

    char *id;

    if (dev->reg != -1) {

        /*

         * Explicitly assigned address, just verify that no-one else

         * is using it.  other mechanism). We have to open code this

         * rather than using spapr_vio_find_by_reg() because sdev

         * itself is already in the list.

         */

        VIOsPAPRDevice *other = reg_conflict(dev);

        if (other) {

            error_setg(errp, "%s and %s devices conflict at address %#x",

                       object_get_typename(OBJECT(qdev)),

                       object_get_typename(OBJECT(&other->qdev)),

                       dev->reg);

            return;

        }

    } else {

        /* Need to assign an address */

        VIOsPAPRBus *bus = SPAPR_VIO_BUS(dev->qdev.parent_bus);

        do {

            dev->reg = bus->next_reg++;

        } while (reg_conflict(dev));

    }

    /* Don't overwrite ids assigned on the command line */

    if (!dev->qdev.id) {

        id = spapr_vio_get_dev_name(DEVICE(dev));

        dev->qdev.id = id;

    }

    dev->irq = xics_alloc(spapr->icp, 0, dev->irq, false);

    if (!dev->irq) {

        error_setg(errp, "can't allocate IRQ");

        return;

    }

    if (pc->rtce_window_size) {

        uint32_t liobn = SPAPR_VIO_LIOBN(dev->reg);

        memory_region_init(&dev->mrroot, OBJECT(dev), "iommu-spapr-root",

                           ram_size);

        memory_region_init_alias(&dev->mrbypass, OBJECT(dev),

                                 "iommu-spapr-bypass", get_system_memory(),

                                 0, ram_size);

        memory_region_add_subregion_overlap(&dev->mrroot, 0, &dev->mrbypass, 1);

        address_space_init(&dev->as, &dev->mrroot, qdev->id);

        dev->tcet = spapr_tce_new_table(qdev, liobn,

                                        0,

                                        SPAPR_TCE_PAGE_SHIFT,

                                        pc->rtce_window_size >>

                                        SPAPR_TCE_PAGE_SHIFT, false);

        dev->tcet->vdev = dev;

        memory_region_add_subregion_overlap(&dev->mrroot, 0,

                                            spapr_tce_get_iommu(dev->tcet), 2);

    }

    pc->realize(dev, errp);

}


static int tta_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TTAContext *s = avctx->priv_data;

    int i, ret;

    int cur_chan = 0, framelen = s->frame_length;

    int32_t *p;

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

    // FIXME: seeking

    s->total_frames--;

    if (!s->total_frames && s->last_frame_length)

        framelen = s->last_frame_length;

    /* get output buffer */

    s->frame.nb_samples = framelen;

    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {

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

        return ret;

    }

    // decode directly to output buffer for 24-bit sample format

    if (s->bps == 3)

        s->decode_buffer = (int32_t *)s->frame.data[0];

    // init per channel states

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

        s->ch_ctx[i].predictor = 0;

        ttafilter_init(&s->ch_ctx[i].filter, ttafilter_configs[s->bps-1][0], ttafilter_configs[s->bps-1][1]);

        rice_init(&s->ch_ctx[i].rice, 10, 10);

    }

    for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {

        int32_t *predictor = &s->ch_ctx[cur_chan].predictor;

        TTAFilter *filter = &s->ch_ctx[cur_chan].filter;

        TTARice *rice = &s->ch_ctx[cur_chan].rice;

        uint32_t unary, depth, k;

        int32_t value;

        unary = tta_get_unary(&s->gb);

        if (unary == 0) {

            depth = 0;

            k = rice->k0;

        } else {

            depth = 1;

            k = rice->k1;

            unary--;

        }

        if (get_bits_left(&s->gb) < k)

            return -1;

        if (k) {

            if (k > MIN_CACHE_BITS)

                return -1;

            value = (unary << k) + get_bits(&s->gb, k);

        } else

            value = unary;

        // FIXME: copy paste from original

        switch (depth) {

        case 1:

            rice->sum1 += value - (rice->sum1 >> 4);

            if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])

                rice->k1--;

            else if(rice->sum1 > shift_16[rice->k1 + 1])

                rice->k1++;

            value += shift_1[rice->k0];

        default:

            rice->sum0 += value - (rice->sum0 >> 4);

            if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])

                rice->k0--;

            else if(rice->sum0 > shift_16[rice->k0 + 1])

                rice->k0++;

        }

        // extract coded value

#define UNFOLD(x) (((x)&1) ? (++(x)>>1) : (-(x)>>1))

        *p = UNFOLD(value);

        // run hybrid filter

        ttafilter_process(filter, p, 0);

        // fixed order prediction

#define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)

        switch (s->bps) {

            case 1: *p += PRED(*predictor, 4); break;

            case 2:

            case 3: *p += PRED(*predictor, 5); break;

            case 4: *p += *predictor; break;

        }

        *predictor = *p;

        // flip channels

        if (cur_chan < (s->channels-1))

            cur_chan++;

        else {

            // decorrelate in case of stereo integer

            if (s->channels > 1) {

                int32_t *r = p - 1;

                for (*p += *r / 2; r > p - s->channels; r--)

                    *r = *(r + 1) - *r;

            }

            cur_chan = 0;

        }

    }

    if (get_bits_left(&s->gb) < 32)

        return -1;

    skip_bits_long(&s->gb, 32); // frame crc

    // convert to output buffer

    if (s->bps == 2) {

        int16_t *samples = (int16_t *)s->frame.data[0];

        for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)

            *samples++ = *p;

    } else {

        // shift samples for 24-bit sample format

        int32_t *samples = (int32_t *)s->frame.data[0];

        for (i = 0; i < framelen * s->channels; i++)

            *samples++ <<= 8;

        // reset decode buffer

        s->decode_buffer = NULL;

    }

    *got_frame_ptr   = 1;

    *(AVFrame *)data = s->frame;

    return buf_size;

}


uint32_t virtio_config_readl(VirtIODevice *vdev, uint32_t addr)

{

    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);

    uint32_t val;

    k->get_config(vdev, vdev->config);

    if (addr > (vdev->config_len - sizeof(val)))

        return (uint32_t)-1;

    val = ldl_p(vdev->config + addr);

    return val;

}