static void avc_h_loop_filter_luma_mbaff_intra_msa(uint8_t *src,

                                                   int32_t stride,

                                                   int32_t alpha_in,

                                                   int32_t beta_in)

{

    uint64_t load0, load1;

    uint32_t out0, out2;

    uint16_t out1, out3;

    v8u16 src0_r, src1_r, src2_r, src3_r, src4_r, src5_r, src6_r, src7_r;

    v8u16 dst0_r, dst1_r, dst4_r, dst5_r;

    v8u16 dst2_x_r, dst2_y_r, dst3_x_r, dst3_y_r;

    v16u8 dst0, dst1, dst4, dst5, dst2_x, dst2_y, dst3_x, dst3_y;

    v8i16 tmp0, tmp1, tmp2, tmp3;

    v16u8 alpha, beta;

    v16u8 p0_asub_q0, p1_asub_p0, q1_asub_q0, p2_asub_p0, q2_asub_q0;

    v16u8 is_less_than, is_less_than_alpha, is_less_than_beta;

    v16u8 is_less_than_beta1, is_less_than_beta2;

    v16i8 src0 = { 0 };

    v16i8 src1 = { 0 };

    v16i8 src2 = { 0 };

    v16i8 src3 = { 0 };

    v16i8 src4 = { 0 };

    v16i8 src5 = { 0 };

    v16i8 src6 = { 0 };

    v16i8 src7 = { 0 };

    v16i8 zeros = { 0 };

    load0 = LOAD_DWORD(src - 4);

    load1 = LOAD_DWORD(src + stride - 4);

    src0 = (v16i8) __msa_insert_d((v2i64) src0, 0, load0);

    src1 = (v16i8) __msa_insert_d((v2i64) src1, 0, load1);

    load0 = LOAD_DWORD(src + (2 * stride) - 4);

    load1 = LOAD_DWORD(src + (3 * stride) - 4);

    src2 = (v16i8) __msa_insert_d((v2i64) src2, 0, load0);

    src3 = (v16i8) __msa_insert_d((v2i64) src3, 0, load1);

    load0 = LOAD_DWORD(src + (4 * stride) - 4);

    load1 = LOAD_DWORD(src + (5 * stride) - 4);

    src4 = (v16i8) __msa_insert_d((v2i64) src4, 0, load0);

    src5 = (v16i8) __msa_insert_d((v2i64) src5, 0, load1);

    load0 = LOAD_DWORD(src + (6 * stride) - 4);

    load1 = LOAD_DWORD(src + (7 * stride) - 4);

    src6 = (v16i8) __msa_insert_d((v2i64) src6, 0, load0);

    src7 = (v16i8) __msa_insert_d((v2i64) src7, 0, load1);

    src0 = __msa_ilvr_b(src1, src0);

    src1 = __msa_ilvr_b(src3, src2);

    src2 = __msa_ilvr_b(src5, src4);

    src3 = __msa_ilvr_b(src7, src6);

    tmp0 = __msa_ilvr_h((v8i16) src1, (v8i16) src0);

    tmp1 = __msa_ilvl_h((v8i16) src1, (v8i16) src0);

    tmp2 = __msa_ilvr_h((v8i16) src3, (v8i16) src2);

    tmp3 = __msa_ilvl_h((v8i16) src3, (v8i16) src2);

    src6 = (v16i8) __msa_ilvr_w((v4i32) tmp2, (v4i32) tmp0);

    src0 = __msa_sldi_b(zeros, src6, 8);

    src1 = (v16i8) __msa_ilvl_w((v4i32) tmp2, (v4i32) tmp0);

    src2 = __msa_sldi_b(zeros, src1, 8);

    src3 = (v16i8) __msa_ilvr_w((v4i32) tmp3, (v4i32) tmp1);

    src4 = __msa_sldi_b(zeros, src3, 8);

    src5 = (v16i8) __msa_ilvl_w((v4i32) tmp3, (v4i32) tmp1);

    src7 = __msa_sldi_b(zeros, src5, 8);

    p0_asub_q0 = __msa_asub_u_b((v16u8) src2, (v16u8) src3);

    p1_asub_p0 = __msa_asub_u_b((v16u8) src1, (v16u8) src2);

    q1_asub_q0 = __msa_asub_u_b((v16u8) src4, (v16u8) src3);

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    is_less_than_alpha = (p0_asub_q0 < alpha);

    is_less_than_beta = (p1_asub_p0 < beta);

    is_less_than = is_less_than_alpha & is_less_than_beta;

    is_less_than_beta = (q1_asub_q0 < beta);

    is_less_than = is_less_than & is_less_than_beta;

    alpha >>= 2;

    alpha += 2;

    is_less_than_alpha = (p0_asub_q0 < alpha);

    p2_asub_p0 = __msa_asub_u_b((v16u8) src0, (v16u8) src2);

    is_less_than_beta1 = (p2_asub_p0 < beta);

    q2_asub_q0 = __msa_asub_u_b((v16u8) src5, (v16u8) src3);

    is_less_than_beta2 = (q2_asub_q0 < beta);

    src0_r = (v8u16) __msa_ilvr_b(zeros, src0);

    src1_r = (v8u16) __msa_ilvr_b(zeros, src1);

    src2_r = (v8u16) __msa_ilvr_b(zeros, src2);

    src3_r = (v8u16) __msa_ilvr_b(zeros, src3);

    src4_r = (v8u16) __msa_ilvr_b(zeros, src4);

    src5_r = (v8u16) __msa_ilvr_b(zeros, src5);

    src6_r = (v8u16) __msa_ilvr_b(zeros, src6);

    src7_r = (v8u16) __msa_ilvr_b(zeros, src7);

    dst2_x_r = src1_r + src2_r + src3_r;

    dst2_x_r = src0_r + (2 * (dst2_x_r)) + src4_r;

    dst2_x_r = (v8u16) __msa_srari_h((v8i16) dst2_x_r, 3);

    dst1_r = src0_r + src1_r + src2_r + src3_r;

    dst1_r = (v8u16) __msa_srari_h((v8i16) dst1_r, 2);

    dst0_r = (2 * src6_r) + (3 * src0_r);

    dst0_r += src1_r + src2_r + src3_r;

    dst0_r = (v8u16) __msa_srari_h((v8i16) dst0_r, 3);

    dst2_y_r = (2 * src1_r) + src2_r + src4_r;

    dst2_y_r = (v8u16) __msa_srari_h((v8i16) dst2_y_r, 2);

    dst2_x = (v16u8) __msa_pckev_b((v16i8) dst2_x_r, (v16i8) dst2_x_r);

    dst2_y = (v16u8) __msa_pckev_b((v16i8) dst2_y_r, (v16i8) dst2_y_r);

    dst2_x = __msa_bmnz_v(dst2_y, dst2_x, is_less_than_beta1);

    dst3_x_r = src2_r + src3_r + src4_r;

    dst3_x_r = src1_r + (2 * dst3_x_r) + src5_r;

    dst3_x_r = (v8u16) __msa_srari_h((v8i16) dst3_x_r, 3);

    dst4_r = src2_r + src3_r + src4_r + src5_r;

    dst4_r = (v8u16) __msa_srari_h((v8i16) dst4_r, 2);

    dst5_r = (2 * src7_r) + (3 * src5_r);

    dst5_r += src4_r + src3_r + src2_r;

    dst5_r = (v8u16) __msa_srari_h((v8i16) dst5_r, 3);

    dst3_y_r = (2 * src4_r) + src3_r + src1_r;

    dst3_y_r = (v8u16) __msa_srari_h((v8i16) dst3_y_r, 2);

    dst3_x = (v16u8) __msa_pckev_b((v16i8) dst3_x_r, (v16i8) dst3_x_r);

    dst3_y = (v16u8) __msa_pckev_b((v16i8) dst3_y_r, (v16i8) dst3_y_r);

    dst3_x = __msa_bmnz_v(dst3_y, dst3_x, is_less_than_beta2);

    dst2_y_r = (2 * src1_r) + src2_r + src4_r;

    dst2_y_r = (v8u16) __msa_srari_h((v8i16) dst2_y_r, 2);

    dst3_y_r = (2 * src4_r) + src3_r + src1_r;

    dst3_y_r = (v8u16) __msa_srari_h((v8i16) dst3_y_r, 2);

    dst2_y = (v16u8) __msa_pckev_b((v16i8) dst2_y_r, (v16i8) dst2_y_r);

    dst3_y = (v16u8) __msa_pckev_b((v16i8) dst3_y_r, (v16i8) dst3_y_r);

    dst2_x = __msa_bmnz_v(dst2_y, dst2_x, is_less_than_alpha);

    dst3_x = __msa_bmnz_v(dst3_y, dst3_x, is_less_than_alpha);

    dst2_x = __msa_bmnz_v((v16u8) src2, dst2_x, is_less_than);

    dst3_x = __msa_bmnz_v((v16u8) src3, dst3_x, is_less_than);

    is_less_than = is_less_than_alpha & is_less_than;

    dst1 = (v16u8) __msa_pckev_b((v16i8) dst1_r, (v16i8) dst1_r);

    is_less_than_beta1 = is_less_than_beta1 & is_less_than;

    dst1 = __msa_bmnz_v((v16u8) src1, dst1, is_less_than_beta1);

    dst0 = (v16u8) __msa_pckev_b((v16i8) dst0_r, (v16i8) dst0_r);

    dst0 = __msa_bmnz_v((v16u8) src0, dst0, is_less_than_beta1);

    dst4 = (v16u8) __msa_pckev_b((v16i8) dst4_r, (v16i8) dst4_r);

    is_less_than_beta2 = is_less_than_beta2 & is_less_than;

    dst4 = __msa_bmnz_v((v16u8) src4, dst4, is_less_than_beta2);

    dst5 = (v16u8) __msa_pckev_b((v16i8) dst5_r, (v16i8) dst5_r);

    dst5 = __msa_bmnz_v((v16u8) src5, dst5, is_less_than_beta2);

    dst0 = (v16u8) __msa_ilvr_b((v16i8) dst1, (v16i8) dst0);

    dst1 = (v16u8) __msa_ilvr_b((v16i8) dst3_x, (v16i8) dst2_x);

    dst2_x = (v16u8) __msa_ilvr_b((v16i8) dst5, (v16i8) dst4);

    tmp0 = __msa_ilvr_h((v8i16) dst1, (v8i16) dst0);

    tmp1 = __msa_ilvl_h((v8i16) dst1, (v8i16) dst0);

    tmp2 = __msa_ilvr_h((v8i16) zeros, (v8i16) dst2_x);

    tmp3 = __msa_ilvl_h((v8i16) zeros, (v8i16) dst2_x);

    dst0 = (v16u8) __msa_ilvr_w((v4i32) tmp2, (v4i32) tmp0);

    dst1 = (v16u8) __msa_sldi_b(zeros, (v16i8) dst0, 8);

    dst2_x = (v16u8) __msa_ilvl_w((v4i32) tmp2, (v4i32) tmp0);

    dst3_x = (v16u8) __msa_sldi_b(zeros, (v16i8) dst2_x, 8);

    dst4 = (v16u8) __msa_ilvr_w((v4i32) tmp3, (v4i32) tmp1);

    dst5 = (v16u8) __msa_sldi_b(zeros, (v16i8) dst4, 8);

    dst2_y = (v16u8) __msa_ilvl_w((v4i32) tmp3, (v4i32) tmp1);

    dst3_y = (v16u8) __msa_sldi_b(zeros, (v16i8) dst2_y, 8);

    out0 = __msa_copy_u_w((v4i32) dst0, 0);

    out1 = __msa_copy_u_h((v8i16) dst0, 2);

    out2 = __msa_copy_u_w((v4i32) dst1, 0);

    out3 = __msa_copy_u_h((v8i16) dst1, 2);

    STORE_WORD((src - 3), out0);

    STORE_HWORD((src + 1), out1);

    src += stride;

    STORE_WORD((src - 3), out2);

    STORE_HWORD((src + 1), out3);

    src += stride;

    out0 = __msa_copy_u_w((v4i32) dst2_x, 0);

    out1 = __msa_copy_u_h((v8i16) dst2_x, 2);

    out2 = __msa_copy_u_w((v4i32) dst3_x, 0);

    out3 = __msa_copy_u_h((v8i16) dst3_x, 2);

    STORE_WORD((src - 3), out0);

    STORE_HWORD((src + 1), out1);

    src += stride;

    STORE_WORD((src - 3), out2);

    STORE_HWORD((src + 1), out3);

    src += stride;

    out0 = __msa_copy_u_w((v4i32) dst4, 0);

    out1 = __msa_copy_u_h((v8i16) dst4, 2);

    out2 = __msa_copy_u_w((v4i32) dst5, 0);

    out3 = __msa_copy_u_h((v8i16) dst5, 2);

    STORE_WORD((src - 3), out0);

    STORE_HWORD((src + 1), out1);

    src += stride;

    STORE_WORD((src - 3), out2);

    STORE_HWORD((src + 1), out3);

    src += stride;

    out0 = __msa_copy_u_w((v4i32) dst2_y, 0);

    out1 = __msa_copy_u_h((v8i16) dst2_y, 2);

    out2 = __msa_copy_u_w((v4i32) dst3_y, 0);

    out3 = __msa_copy_u_h((v8i16) dst3_y, 2);

    STORE_WORD((src - 3), out0);

    STORE_HWORD((src + 1), out1);

    src += stride;

    STORE_WORD((src - 3), out2);

    STORE_HWORD((src + 1), out3);

}


static int mov_read_tkhd(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    int i;

    int width;

    int height;

    int64_t disp_transform[2];

    int display_matrix[3][2];

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

    MOVStreamContext *sc = st->priv_data;

    int version = get_byte(pb);

    get_be24(pb); /* flags */

    /*

    MOV_TRACK_ENABLED 0x0001

    MOV_TRACK_IN_MOVIE 0x0002

    MOV_TRACK_IN_PREVIEW 0x0004

    MOV_TRACK_IN_POSTER 0x0008

    */

    if (version == 1) {

        get_be64(pb);

        get_be64(pb);

    } else {

        get_be32(pb); /* creation time */

        get_be32(pb); /* modification time */

    }

    st->id = (int)get_be32(pb); /* track id (NOT 0 !)*/

    get_be32(pb); /* reserved */

    /* highlevel (considering edits) duration in movie timebase */

    (version == 1) ? get_be64(pb) : get_be32(pb);

    get_be32(pb); /* reserved */

    get_be32(pb); /* reserved */

    get_be16(pb); /* layer */

    get_be16(pb); /* alternate group */

    get_be16(pb); /* volume */

    get_be16(pb); /* reserved */

    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)

    // they're kept in fixed point format through all calculations

    // ignore u,v,z b/c we don't need the scale factor to calc aspect ratio

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

        display_matrix[i][0] = get_be32(pb);   // 16.16 fixed point

        display_matrix[i][1] = get_be32(pb);   // 16.16 fixed point

        get_be32(pb);           // 2.30 fixed point (not used)

    }

    width = get_be32(pb);       // 16.16 fixed point track width

    height = get_be32(pb);      // 16.16 fixed point track height

    sc->width = width >> 16;

    sc->height = height >> 16;

    //transform the display width/height according to the matrix

    // skip this if the display matrix is the default identity matrix

    // to keep the same scale, use [width height 1<<16]

    if (width && height &&

        (display_matrix[0][0] != 65536 || display_matrix[0][1]           ||

        display_matrix[1][0]           || display_matrix[1][1] != 65536  ||

        display_matrix[2][0]           || display_matrix[2][1])) {

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

            disp_transform[i] =

                (int64_t)  width  * display_matrix[0][i] +

                (int64_t)  height * display_matrix[1][i] +

                ((int64_t) display_matrix[2][i] << 16);

        //sample aspect ratio is new width/height divided by old width/height

        st->sample_aspect_ratio = av_d2q(

            ((double) disp_transform[0] * height) /

            ((double) disp_transform[1] * width), INT_MAX);

    }

    return 0;

}


static void v9fs_read(void *opaque)

{

    int32_t fid;

    int64_t off;

    ssize_t err = 0;

    int32_t count = 0;

    size_t offset = 7;

    int32_t max_count;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &max_count);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (fidp->fid_type == P9_FID_DIR) {

        if (off == 0) {

            v9fs_co_rewinddir(pdu, fidp);

        }

        count = v9fs_do_readdir_with_stat(pdu, fidp, max_count);

        if (count < 0) {

            err = count;

            goto out;

        }

        err = offset;

        err += pdu_marshal(pdu, offset, "d", count);

        err += count;

    } else if (fidp->fid_type == P9_FID_FILE) {

        int32_t cnt;

        int32_t len;

        struct iovec *sg;

        struct iovec iov[128]; /* FIXME: bad, bad, bad */

        sg = iov;

        pdu_marshal(pdu, offset + 4, "v", sg, &cnt);

        sg = cap_sg(sg, max_count, &cnt);

        do {

            if (0) {

                print_sg(sg, cnt);

            }

            /* Loop in case of EINTR */

            do {

                len = v9fs_co_preadv(pdu, fidp, sg, cnt, off);

                if (len >= 0) {

                    off   += len;

                    count += len;

                }

            } while (len == -EINTR && !pdu->cancelled);

            if (len < 0) {

                /* IO error return the error */

                err = len;

                goto out;

            }

            sg = adjust_sg(sg, len, &cnt);

        } while (count < max_count && len > 0);

        err = offset;

        err += pdu_marshal(pdu, offset, "d", count);

        err += count;

    } else if (fidp->fid_type == P9_FID_XATTR) {

        err = v9fs_xattr_read(s, pdu, fidp, off, max_count);

    } else {

        err = -EINVAL;

    }

out:

    put_fid(pdu, fidp);

out_nofid:

    trace_v9fs_read_return(pdu->tag, pdu->id, count, err);

    complete_pdu(s, pdu, err);

}


int qio_channel_readv_all(QIOChannel *ioc,

                          const struct iovec *iov,

                          size_t niov,

                          Error **errp)

{

    int ret = -1;

    struct iovec *local_iov = g_new(struct iovec, niov);

    struct iovec *local_iov_head = local_iov;

    unsigned int nlocal_iov = niov;

    nlocal_iov = iov_copy(local_iov, nlocal_iov,

                          iov, niov,

                          0, iov_size(iov, niov));

    while (nlocal_iov > 0) {

        ssize_t len;

        len = qio_channel_readv(ioc, local_iov, nlocal_iov, errp);

        if (len == QIO_CHANNEL_ERR_BLOCK) {

            if (qemu_in_coroutine()) {

                qio_channel_yield(ioc, G_IO_IN);

            } else {

                qio_channel_wait(ioc, G_IO_IN);

            }

            continue;

        } else if (len < 0) {

            goto cleanup;

        } else if (len == 0) {

            error_setg(errp,

                       "Unexpected end-of-file before all bytes were read");

            goto cleanup;

        }

        iov_discard_front(&local_iov, &nlocal_iov, len);

    }

    ret = 0;

 cleanup:

    g_free(local_iov_head);

    return ret;

}


void qvirtio_pci_device_disable(QVirtioPCIDevice *d)

{

    qpci_iounmap(d->pdev, d->addr);

    d->addr = NULL;

}


static void vfio_vga_quirk_teardown(VFIODevice *vdev)

{

    int i;

    for (i = 0; i < ARRAY_SIZE(vdev->vga.region); i++) {

        while (!QLIST_EMPTY(&vdev->vga.region[i].quirks)) {

            VFIOQuirk *quirk = QLIST_FIRST(&vdev->vga.region[i].quirks);

            memory_region_del_subregion(&vdev->vga.region[i].mem, &quirk->mem);

            QLIST_REMOVE(quirk, next);

            g_free(quirk);

        }

    }

}


int ff_v4l2_m2m_codec_full_reinit(V4L2m2mContext *s)

{

    void *log_ctx = s->avctx;

    int ret;

    av_log(log_ctx, AV_LOG_DEBUG, "%s full reinit\n", s->devname);

    /* wait for pending buffer references */

    if (atomic_load(&s->refcount))

        while(sem_wait(&s->refsync) == -1 && errno == EINTR);

    /* close the driver */

    ff_v4l2_m2m_codec_end(s->avctx);

    /* start again now that we know the stream dimensions */

    s->draining = 0;

    s->reinit = 0;

    s->fd = open(s->devname, O_RDWR | O_NONBLOCK, 0);

    if (s->fd < 0)

        return AVERROR(errno);

    ret = v4l2_prepare_contexts(s);

    if (ret < 0)

        goto error;

    /* if a full re-init was requested - probe didn't run - we need to populate

     * the format for each context

     */

    ret = ff_v4l2_context_get_format(&s->output);

    if (ret) {

        av_log(log_ctx, AV_LOG_DEBUG, "v4l2 output format not supported\n");

        goto error;

    }

    ret = ff_v4l2_context_get_format(&s->capture);

    if (ret) {

        av_log(log_ctx, AV_LOG_DEBUG, "v4l2 capture format not supported\n");

        goto error;

    }

    ret = ff_v4l2_context_set_format(&s->output);

    if (ret) {

        av_log(log_ctx, AV_LOG_ERROR, "can't set v4l2 output format\n");

        goto error;

    }

    ret = ff_v4l2_context_set_format(&s->capture);

    if (ret) {

        av_log(log_ctx, AV_LOG_ERROR, "can't to set v4l2 capture format\n");

        goto error;

    }

    ret = ff_v4l2_context_init(&s->output);

    if (ret) {

        av_log(log_ctx, AV_LOG_ERROR, "no v4l2 output context's buffers\n");

        goto error;

    }

    /* decoder's buffers need to be updated at a later stage */

    if (!av_codec_is_decoder(s->avctx->codec)) {

        ret = ff_v4l2_context_init(&s->capture);

        if (ret) {

            av_log(log_ctx, AV_LOG_ERROR, "no v4l2 capture context's buffers\n");

            goto error;

        }

    }

    return 0;

error:

    if (close(s->fd) < 0) {

        ret = AVERROR(errno);

        av_log(log_ctx, AV_LOG_ERROR, "error closing %s (%s)\n",

            s->devname, av_err2str(AVERROR(errno)));

    }

    s->fd = -1;

    return ret;

}


static av_cold int wmv2_decode_init(AVCodecContext *avctx){

    Wmv2Context * const w= avctx->priv_data;

    if(avctx->idct_algo==FF_IDCT_AUTO){

        avctx->idct_algo=FF_IDCT_WMV2;

    }

    if(ff_msmpeg4_decode_init(avctx) < 0)

        return -1;

    ff_wmv2_common_init(w);

    ff_intrax8_common_init(&w->x8,&w->s);

    return 0;

}


static inline int divide3(int x)

{

    return ((x+1)*21845 + 10922) >> 16;

}


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

    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 ) {

        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_v_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

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

    }

}


static void show_format(AVFormatContext *fmt_ctx)

{

    AVDictionaryEntry *tag = NULL;

    char val_str[128];

    int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;

    print_format_entry(NULL, "[FORMAT]");

    print_format_entry("filename",         fmt_ctx->filename);

    snprintf(val_str, sizeof(val_str) - 1, "%d", fmt_ctx->nb_streams);

    print_format_entry("nb_streams",       val_str);

    print_format_entry("format_name",      fmt_ctx->iformat->name);

    print_format_entry("format_long_name", fmt_ctx->iformat->long_name);

    print_format_entry("start_time",

                       time_value_string(val_str, sizeof(val_str),

                                         fmt_ctx->start_time, &AV_TIME_BASE_Q));

    print_format_entry("duration",

                       time_value_string(val_str, sizeof(val_str),

                                         fmt_ctx->duration, &AV_TIME_BASE_Q));

    print_format_entry("size",

                       size >= 0 ? value_string(val_str, sizeof(val_str),

                                                size, unit_byte_str)

                                  : "unknown");

    print_format_entry("bit_rate",

                       value_string(val_str, sizeof(val_str),

                                    fmt_ctx->bit_rate, unit_bit_per_second_str));

    while ((tag = av_dict_get(fmt_ctx->metadata, "", tag,

                              AV_DICT_IGNORE_SUFFIX))) {

        snprintf(val_str, sizeof(val_str) - 1, "TAG:%s", tag->key);

        print_format_entry(val_str, tag->value);

    }

    print_format_entry(NULL, "[/FORMAT]");

}


static void spatial_compose97i(IDWTELEM *buffer, int width, int height, int stride){

    dwt_compose_t cs;

    spatial_compose97i_init(&cs, buffer, height, stride);

    while(cs.y <= height)

        spatial_compose97i_dy(&cs, buffer, width, height, stride);

}


static void *get_surface(const AVFrame *frame)

{

    return frame->data[3];

}


static uint32_t pci_reg_read4(void *opaque, target_phys_addr_t addr)

{

    PPCE500PCIState *pci = opaque;

    unsigned long win;

    uint32_t value = 0;

    win = addr & 0xfe0;

    switch (win) {

    case PPCE500_PCI_OW1:

    case PPCE500_PCI_OW2:

    case PPCE500_PCI_OW3:

    case PPCE500_PCI_OW4:

        switch (addr & 0xC) {

        case PCI_POTAR:

            value = pci->pob[(addr >> 5) & 0x7].potar;

            break;

        case PCI_POTEAR:

            value = pci->pob[(addr >> 5) & 0x7].potear;

            break;

        case PCI_POWBAR:

            value = pci->pob[(addr >> 5) & 0x7].powbar;

            break;

        case PCI_POWAR:

            value = pci->pob[(addr >> 5) & 0x7].powar;

            break;

        default:

            break;

        }

        break;

    case PPCE500_PCI_IW3:

    case PPCE500_PCI_IW2:

    case PPCE500_PCI_IW1:

        switch (addr & 0xC) {

        case PCI_PITAR:

            value = pci->pib[(addr >> 5) & 0x3].pitar;

            break;

        case PCI_PIWBAR:

            value = pci->pib[(addr >> 5) & 0x3].piwbar;

            break;

        case PCI_PIWBEAR:

            value = pci->pib[(addr >> 5) & 0x3].piwbear;

            break;

        case PCI_PIWAR:

            value = pci->pib[(addr >> 5) & 0x3].piwar;

            break;

        default:

            break;

        };

        break;

    case PPCE500_PCI_GASKET_TIMR:

        value = pci->gasket_time;

        break;

    default:

        break;

    }

    pci_debug("%s: win:%lx(addr:" TARGET_FMT_plx ") -> value:%x\n", __func__,

              win, addr, value);

    return value;

}


static void win32_rearm_timer(struct qemu_alarm_timer *t,

                              int64_t nearest_delta_ns)

{

    HANDLE hTimer = t->timer;

    int nearest_delta_ms;

    BOOLEAN success;

    nearest_delta_ms = (nearest_delta_ns + 999999) / 1000000;

    if (nearest_delta_ms < 1) {

        nearest_delta_ms = 1;

    }

    success = ChangeTimerQueueTimer(NULL,

                                    hTimer,

                                    nearest_delta_ms,

                                    3600000);

    if (!success) {

        fprintf(stderr, "Failed to rearm win32 alarm timer: %ld\n",

                GetLastError());

        exit(-1);

    }

}


static void add_entry(TiffEncoderContext * s,

                      enum TiffTags tag, enum TiffTypes type, int count,

                      const void *ptr_val)

{

    uint8_t *entries_ptr = s->entries + 12 * s->num_entries;

    av_assert0(s->num_entries < TIFF_MAX_ENTRY);

    bytestream_put_le16(&entries_ptr, tag);

    bytestream_put_le16(&entries_ptr, type);

    bytestream_put_le32(&entries_ptr, count);

    if (type_sizes[type] * count <= 4) {

        tnput(&entries_ptr, count, ptr_val, type, 0);

    } else {

        bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start);

        check_size(s, count * type_sizes2[type]);

        tnput(s->buf, count, ptr_val, type, 0);

    }

    s->num_entries++;

}


static int decode_extended_mips16_opc (CPUMIPSState *env, DisasContext *ctx,

                                       int *is_branch)

{

    int extend = cpu_lduw_code(env, ctx->pc + 2);

    int op, rx, ry, funct, sa;

    int16_t imm, offset;

    ctx->opcode = (ctx->opcode << 16) | extend;

    op = (ctx->opcode >> 11) & 0x1f;

    sa = (ctx->opcode >> 22) & 0x1f;

    funct = (ctx->opcode >> 8) & 0x7;

    rx = xlat((ctx->opcode >> 8) & 0x7);

    ry = xlat((ctx->opcode >> 5) & 0x7);

    offset = imm = (int16_t) (((ctx->opcode >> 16) & 0x1f) << 11

                              | ((ctx->opcode >> 21) & 0x3f) << 5

                              | (ctx->opcode & 0x1f));

    /* The extended opcodes cleverly reuse the opcodes from their 16-bit

       counterparts.  */

    switch (op) {

    case M16_OPC_ADDIUSP:

        gen_arith_imm(ctx, OPC_ADDIU, rx, 29, imm);

        break;

    case M16_OPC_ADDIUPC:

        gen_addiupc(ctx, rx, imm, 0, 1);

        break;

    case M16_OPC_B:

        gen_compute_branch(ctx, OPC_BEQ, 4, 0, 0, offset << 1);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_BEQZ:

        gen_compute_branch(ctx, OPC_BEQ, 4, rx, 0, offset << 1);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_BNEQZ:

        gen_compute_branch(ctx, OPC_BNE, 4, rx, 0, offset << 1);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_SHIFT:

        switch (ctx->opcode & 0x3) {

        case 0x0:

            gen_shift_imm(ctx, OPC_SLL, rx, ry, sa);

            break;

        case 0x1:

#if defined(TARGET_MIPS64)

            check_mips_64(ctx);

            gen_shift_imm(ctx, OPC_DSLL, rx, ry, sa);

#else

            generate_exception(ctx, EXCP_RI);

#endif

            break;

        case 0x2:

            gen_shift_imm(ctx, OPC_SRL, rx, ry, sa);

            break;

        case 0x3:

            gen_shift_imm(ctx, OPC_SRA, rx, ry, sa);

            break;

        }

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_LD:

            check_mips_64(ctx);

        gen_ld(ctx, OPC_LD, ry, rx, offset);

        break;

#endif

    case M16_OPC_RRIA:

        imm = ctx->opcode & 0xf;

        imm = imm | ((ctx->opcode >> 20) & 0x7f) << 4;

        imm = imm | ((ctx->opcode >> 16) & 0xf) << 11;

        imm = (int16_t) (imm << 1) >> 1;

        if ((ctx->opcode >> 4) & 0x1) {

#if defined(TARGET_MIPS64)

            check_mips_64(ctx);

            gen_arith_imm(ctx, OPC_DADDIU, ry, rx, imm);

#else

            generate_exception(ctx, EXCP_RI);

#endif

        } else {

            gen_arith_imm(ctx, OPC_ADDIU, ry, rx, imm);

        }

        break;

    case M16_OPC_ADDIU8:

        gen_arith_imm(ctx, OPC_ADDIU, rx, rx, imm);

        break;

    case M16_OPC_SLTI:

        gen_slt_imm(ctx, OPC_SLTI, 24, rx, imm);

        break;

    case M16_OPC_SLTIU:

        gen_slt_imm(ctx, OPC_SLTIU, 24, rx, imm);

        break;

    case M16_OPC_I8:

        switch (funct) {

        case I8_BTEQZ:

            gen_compute_branch(ctx, OPC_BEQ, 4, 24, 0, offset << 1);

            break;

        case I8_BTNEZ:

            gen_compute_branch(ctx, OPC_BNE, 4, 24, 0, offset << 1);

            break;

        case I8_SWRASP:

            gen_st(ctx, OPC_SW, 31, 29, imm);

            break;

        case I8_ADJSP:

            gen_arith_imm(ctx, OPC_ADDIU, 29, 29, imm);

            break;

        case I8_SVRS:

            {

                int xsregs = (ctx->opcode >> 24) & 0x7;

                int aregs = (ctx->opcode >> 16) & 0xf;

                int do_ra = (ctx->opcode >> 6) & 0x1;

                int do_s0 = (ctx->opcode >> 5) & 0x1;

                int do_s1 = (ctx->opcode >> 4) & 0x1;

                int framesize = (((ctx->opcode >> 20) & 0xf) << 4

                                 | (ctx->opcode & 0xf)) << 3;

                if (ctx->opcode & (1 << 7)) {

                    gen_mips16_save(ctx, xsregs, aregs,

                                    do_ra, do_s0, do_s1,

                                    framesize);

                } else {

                    gen_mips16_restore(ctx, xsregs, aregs,

                                       do_ra, do_s0, do_s1,

                                       framesize);

                }

            }

            break;

        default:

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case M16_OPC_LI:

        tcg_gen_movi_tl(cpu_gpr[rx], (uint16_t) imm);

        break;

    case M16_OPC_CMPI:

        tcg_gen_xori_tl(cpu_gpr[24], cpu_gpr[rx], (uint16_t) imm);

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_SD:

        gen_st(ctx, OPC_SD, ry, rx, offset);

        break;

#endif

    case M16_OPC_LB:

        gen_ld(ctx, OPC_LB, ry, rx, offset);

        break;

    case M16_OPC_LH:

        gen_ld(ctx, OPC_LH, ry, rx, offset);

        break;

    case M16_OPC_LWSP:

        gen_ld(ctx, OPC_LW, rx, 29, offset);

        break;

    case M16_OPC_LW:

        gen_ld(ctx, OPC_LW, ry, rx, offset);

        break;

    case M16_OPC_LBU:

        gen_ld(ctx, OPC_LBU, ry, rx, offset);

        break;

    case M16_OPC_LHU:

        gen_ld(ctx, OPC_LHU, ry, rx, offset);

        break;

    case M16_OPC_LWPC:

        gen_ld(ctx, OPC_LWPC, rx, 0, offset);

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_LWU:

        gen_ld(ctx, OPC_LWU, ry, rx, offset);

        break;

#endif

    case M16_OPC_SB:

        gen_st(ctx, OPC_SB, ry, rx, offset);

        break;

    case M16_OPC_SH:

        gen_st(ctx, OPC_SH, ry, rx, offset);

        break;

    case M16_OPC_SWSP:

        gen_st(ctx, OPC_SW, rx, 29, offset);

        break;

    case M16_OPC_SW:

        gen_st(ctx, OPC_SW, ry, rx, offset);

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_I64:

        decode_i64_mips16(ctx, ry, funct, offset, 1);

        break;

#endif

    default:

        generate_exception(ctx, EXCP_RI);

        break;

    }

    return 4;

}


static void set_pixel_format(VncState *vs,

                             int bits_per_pixel, int depth,

                             int big_endian_flag, int true_color_flag,

                             int red_max, int green_max, int blue_max,

                             int red_shift, int green_shift, int blue_shift)

{

    if (!true_color_flag) {

        vnc_client_error(vs);

        return;

    }

    vs->clientds = vs->serverds;

    vs->clientds.pf.rmax = red_max;

    count_bits(vs->clientds.pf.rbits, red_max);

    vs->clientds.pf.rshift = red_shift;

    vs->clientds.pf.rmask = red_max << red_shift;

    vs->clientds.pf.gmax = green_max;

    count_bits(vs->clientds.pf.gbits, green_max);

    vs->clientds.pf.gshift = green_shift;

    vs->clientds.pf.gmask = green_max << green_shift;

    vs->clientds.pf.bmax = blue_max;

    count_bits(vs->clientds.pf.bbits, blue_max);

    vs->clientds.pf.bshift = blue_shift;

    vs->clientds.pf.bmask = blue_max << blue_shift;

    vs->clientds.pf.bits_per_pixel = bits_per_pixel;

    vs->clientds.pf.bytes_per_pixel = bits_per_pixel / 8;

    vs->clientds.pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;

    vs->clientds.flags = big_endian_flag ? QEMU_BIG_ENDIAN_FLAG : 0x00;

    set_pixel_conversion(vs);

    vga_hw_invalidate();

    vga_hw_update();

}


int virtio_load(VirtIODevice *vdev, QEMUFile *f)

{

    int num, i, ret;

    uint32_t features;

    uint32_t supported_features =

        vdev->binding->get_features(vdev->binding_opaque);

    if (vdev->binding->load_config) {

        ret = vdev->binding->load_config(vdev->binding_opaque, f);

        if (ret)

            return ret;

    }

    qemu_get_8s(f, &vdev->status);

    qemu_get_8s(f, &vdev->isr);

    qemu_get_be16s(f, &vdev->queue_sel);

    qemu_get_be32s(f, &features);

    if (features & ~supported_features) {

        fprintf(stderr, "Features 0x%x unsupported. Allowed features: 0x%x\n",

                features, supported_features);

        return -1;

    }

    if (vdev->set_features)

        vdev->set_features(vdev, features);

    vdev->guest_features = features;

    vdev->config_len = qemu_get_be32(f);

    qemu_get_buffer(f, vdev->config, vdev->config_len);

    num = qemu_get_be32(f);

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

        vdev->vq[i].vring.num = qemu_get_be32(f);

        vdev->vq[i].pa = qemu_get_be64(f);

        qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);

        if (vdev->vq[i].pa) {

            virtqueue_init(&vdev->vq[i]);

        }

	num_heads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;

	/* Check it isn't doing very strange things with descriptor numbers. */

	if (num_heads > vdev->vq[i].vring.num) {

		fprintf(stderr, "VQ %d size 0x%x Guest index 0x%x "

                        "inconsistent with Host index 0x%x: delta 0x%x\n",

			i, vdev->vq[i].vring.num,

                        vring_avail_idx(&vdev->vq[i]),

                        vdev->vq[i].last_avail_idx, num_heads);

		return -1;

	}

        if (vdev->binding->load_queue) {

            ret = vdev->binding->load_queue(vdev->binding_opaque, i, f);

            if (ret)

                return ret;

        }

    }

    virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);

    return 0;

}


static inline void RENAME(hyscale)(uint16_t *dst, int dstWidth, uint8_t *src, int srcW, int xInc,

				   int flags, int canMMX2BeUsed, int16_t *hLumFilter,

				   int16_t *hLumFilterPos, int hLumFilterSize, void *funnyYCode,

				   int srcFormat, uint8_t *formatConvBuffer, int16_t *mmx2Filter,

				   int32_t *mmx2FilterPos)

{

    if(srcFormat==IMGFMT_YUY2)

    {

	RENAME(yuy2ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_UYVY)

    {

	RENAME(uyvyToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR32)

    {

	RENAME(bgr32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR24)

    {

	RENAME(bgr24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR16)

    {

	RENAME(bgr16ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_BGR15)

    {

	RENAME(bgr15ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_RGB32)

    {

	RENAME(rgb32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==IMGFMT_RGB24)

    {

	RENAME(rgb24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if th mmx2 cant be used (its faster than the x86asm one)

    if(!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if(!(flags&SWS_FAST_BILINEAR))

#endif

    {

    	RENAME(hScale)(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#ifdef ARCH_X86

#ifdef HAVE_MMX2

	int i;

	if(canMMX2BeUsed)

	{

		asm volatile(

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

			"movl %0, %%ecx			\n\t"

			"movl %1, %%edi			\n\t"

			"movl %2, %%edx			\n\t"

			"movl %3, %%ebx			\n\t"

			"xorl %%eax, %%eax		\n\t" // i

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

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

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

#define FUNNY_Y_CODE \

			"movl (%%ebx), %%esi		\n\t"\

			"call *%4			\n\t"\

			"addl (%%ebx, %%eax), %%ecx	\n\t"\

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

			"xorl %%eax, %%eax		\n\t"\

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

			:: "m" (src), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

			"m" (funnyYCode)

			: "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi"

		);

		for(i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;

	}

	else

	{

#endif

	//NO MMX just normal asm ...

	asm volatile(

		"xorl %%eax, %%eax		\n\t" // i

		"xorl %%ebx, %%ebx		\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		".balign 16			\n\t"

		"1:				\n\t"

		"movzbl  (%0, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%edi, %%eax, 2)	\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adcl %3, %%ebx			\n\t" //xx+= xInc>>8 + carry

		"movzbl (%0, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, 2(%%edi, %%eax, 2)	\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adcl %3, %%ebx			\n\t" //xx+= xInc>>8 + carry

		"addl $2, %%eax			\n\t"

		"cmpl %2, %%eax			\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "m" (dst), "m" (dstWidth), "m" (xInc>>16), "m" (xInc&0xFFFF)

		: "%eax", "%ebx", "%ecx", "%edi", "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 cant be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

		register unsigned int xalpha=(xpos&0xFFFF)>>9;

		dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

		xpos+=xInc;

	}

#endif

    }

}


qcrypto_tls_session_check_credentials(QCryptoTLSSession *session,

                                      Error **errp)

{

    if (object_dynamic_cast(OBJECT(session->creds),

                            TYPE_QCRYPTO_TLS_CREDS_ANON)) {

        return 0;

    } else if (object_dynamic_cast(OBJECT(session->creds),

                            TYPE_QCRYPTO_TLS_CREDS_X509)) {

        if (session->creds->verifyPeer) {

            return qcrypto_tls_session_check_certificate(session,

                                                         errp);

        } else {

            return 0;

        }

    } else {

        error_setg(errp, "Unexpected credential type %s",

                   object_get_typename(OBJECT(session->creds)));

        return -1;

    }

}


static QObject *qmp_output_first(QmpOutputVisitor *qov)

{

    QStackEntry *e = QTAILQ_LAST(&qov->stack, QStack);

    /* FIXME - find a better way to deal with NULL values */

    if (!e) {

        return NULL;

    }

    return e->value;

}


yuv2422_2_c_template(SwsContext *c, const int16_t *buf[2],

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

                     const int16_t *abuf[2], uint8_t *dest, int dstW,

                     int yalpha, int uvalpha, int y,

                     enum PixelFormat target)

{

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

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

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

    int  yalpha1 = 4095 - yalpha;

    int uvalpha1 = 4095 - uvalpha;

    int i;

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

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

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

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha) >> 19;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha) >> 19;

        Y1 = av_clip_uint8(Y1);

        Y2 = av_clip_uint8(Y2);

        U  = av_clip_uint8(U);

        V  = av_clip_uint8(V);

        output_pixels(i * 4, Y1, U, Y2, V);

    }

}


PCIDevice *pci_create_simple(PCIBus *bus, int devfn, const char *name)

{

    PCIDevice *dev = pci_create(bus, devfn, name);

    qdev_init(&dev->qdev);

    return dev;

}


PPC_OP(test_ctr)

{

    T0 = regs->ctr;

    RETURN();

}


static void ppc_heathrow_init (ram_addr_t ram_size,

                               const char *boot_device,

                               const char *kernel_filename,

                               const char *kernel_cmdline,

                               const char *initrd_filename,

                               const char *cpu_model)

{

    CPUState *env = NULL, *envs[MAX_CPUS];

    char *filename;

    qemu_irq *pic, **heathrow_irqs;

    int linux_boot, i;

    ram_addr_t ram_offset, bios_offset, vga_bios_offset;

    uint32_t kernel_base, initrd_base;

    int32_t kernel_size, initrd_size;

    PCIBus *pci_bus;

    MacIONVRAMState *nvr;

    int vga_bios_size, bios_size;

    int pic_mem_index, nvram_mem_index, dbdma_mem_index, cuda_mem_index;

    int escc_mem_index, ide_mem_index[2];

    uint16_t ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    void *dbdma;

    uint8_t *vga_bios_ptr;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "G3";

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

        env = cpu_init(cpu_model);

        if (!env) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        /* Set time-base frequency to 16.6 Mhz */

        cpu_ppc_tb_init(env,  16600000UL);

        env->osi_call = vga_osi_call;

        qemu_register_reset(&cpu_ppc_reset, env);

        envs[i] = env;

    }

    /* allocate RAM */

    if (ram_size > (2047 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 2047 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    ram_offset = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0, ram_size, ram_offset);

    /* allocate and load BIOS */

    bios_offset = qemu_ram_alloc(BIOS_SIZE);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    cpu_register_physical_memory(PROM_ADDR, BIOS_SIZE, bios_offset | IO_MEM_ROM);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, 0, NULL, NULL, NULL,

                               1, ELF_MACHINE, 0);

        qemu_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    /* allocate and load VGA BIOS */

    vga_bios_offset = qemu_ram_alloc(VGA_BIOS_SIZE);

    vga_bios_ptr = qemu_get_ram_ptr(vga_bios_offset);

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, VGABIOS_FILENAME);

    if (filename) {

        vga_bios_size = load_image(filename, vga_bios_ptr + 8);

        qemu_free(filename);

    } else {

        vga_bios_size = -1;

    }

    if (vga_bios_size < 0) {

        /* if no bios is present, we can still work */

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

                VGABIOS_FILENAME);

        vga_bios_size = 0;

    } else {

        /* set a specific header (XXX: find real Apple format for NDRV

           drivers) */

        vga_bios_ptr[0] = 'N';

        vga_bios_ptr[1] = 'D';

        vga_bios_ptr[2] = 'R';

        vga_bios_ptr[3] = 'V';

        cpu_to_be32w((uint32_t *)(vga_bios_ptr + 4), vga_bios_size);

        vga_bios_size += 8;

        /* Round to page boundary */

        vga_bios_size = (vga_bios_size + TARGET_PAGE_SIZE - 1) &

            TARGET_PAGE_MASK;

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        /* Now we can load the kernel. The first step tries to load the kernel

           supposing PhysAddr = 0x00000000. If that was wrong the kernel is

           loaded again, the new PhysAddr being computed from lowaddr. */

        kernel_size = load_elf(kernel_filename, kernel_base, NULL, &lowaddr, NULL,

                               1, ELF_MACHINE, 0);

        if (kernel_size > 0 && lowaddr != KERNEL_LOAD_ADDR) {

            kernel_size = load_elf(kernel_filename, (2 * kernel_base) - lowaddr,

                                   NULL, NULL, NULL, 1, ELF_MACHINE, 0);

        }

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

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

                      kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                         initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        for (i = 0; boot_device[i] != '\0'; i++) {

            /* TOFIX: for now, the second IDE channel is not properly

             *        used by OHW. The Mac floppy disk are not emulated.

             *        For now, OHW cannot boot from the network.

             */

#if 0

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

#else

            if (boot_device[i] >= 'c' && boot_device[i] <= 'd') {

                ppc_boot_device = boot_device[i];

                break;

            }

#endif

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for G3 Beige machine\n");

            exit(1);

        }

    }

    isa_mem_base = 0x80000000;

    /* Register 2 MB of ISA IO space */

    isa_mmio_init(0xfe000000, 0x00200000);

    /* XXX: we register only 1 output pin for heathrow PIC */

    heathrow_irqs = qemu_mallocz(smp_cpus * sizeof(qemu_irq *));

    heathrow_irqs[0] =

        qemu_mallocz(smp_cpus * sizeof(qemu_irq) * 1);

    /* Connect the heathrow PIC outputs to the 6xx bus */

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

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            heathrow_irqs[i] = heathrow_irqs[0] + (i * 1);

            heathrow_irqs[i][0] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            break;

        default:

            hw_error("Bus model not supported on OldWorld Mac machine\n");

        }

    }

    /* init basic PC hardware */

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on heathrow machine\n");

    }

    pic = heathrow_pic_init(&pic_mem_index, 1, heathrow_irqs);

    pci_bus = pci_grackle_init(0xfec00000, pic);

    pci_vga_init(pci_bus, vga_bios_offset, vga_bios_size);

    escc_mem_index = escc_init(0x80013000, pic[0x0f], pic[0x10], serial_hds[0],

                               serial_hds[1], ESCC_CLOCK, 4);

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

        pci_nic_init(&nd_table[i], "ne2k_pci", NULL);

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

        exit(1);

    }

    /* First IDE channel is a MAC IDE on the MacIO bus */

    hd[0] = drive_get(IF_IDE, 0, 0);

    hd[1] = drive_get(IF_IDE, 0, 1);

    dbdma = DBDMA_init(&dbdma_mem_index);

    ide_mem_index[0] = -1;

    ide_mem_index[1] = pmac_ide_init(hd, pic[0x0D], dbdma, 0x16, pic[0x02]);

    /* Second IDE channel is a CMD646 on the PCI bus */

    hd[0] = drive_get(IF_IDE, 1, 0);

    hd[1] = drive_get(IF_IDE, 1, 1);

    hd[3] = hd[2] = NULL;

    pci_cmd646_ide_init(pci_bus, hd, 0);

    /* cuda also initialize ADB */

    cuda_init(&cuda_mem_index, pic[0x12]);

    adb_kbd_init(&adb_bus);

    adb_mouse_init(&adb_bus);

    nvr = macio_nvram_init(&nvram_mem_index, 0x2000, 4);

    pmac_format_nvram_partition(nvr, 0x2000);

    macio_init(pci_bus, PCI_DEVICE_ID_APPLE_343S1201, 1, pic_mem_index,

               dbdma_mem_index, cuda_mem_index, nvr, 2, ide_mem_index,

               escc_mem_index);

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, ARCH_HEATHROW);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, CMDLINE_ADDR);

        pstrcpy_targphys(CMDLINE_ADDR, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


SYNTH_FILTER_FUNC(sse2)

SYNTH_FILTER_FUNC(avx)

av_cold void ff_synth_filter_init_x86(SynthFilterContext *s)

{

#if HAVE_YASM

    int cpu_flags = av_get_cpu_flags();

#if ARCH_X86_32

    if (EXTERNAL_SSE(cpu_flags)) {

        s->synth_filter_float = synth_filter_sse;

    }

    if (EXTERNAL_SSE2(cpu_flags)) {

        s->synth_filter_float = synth_filter_sse2;

    }

    if (EXTERNAL_AVX(cpu_flags)) {

        s->synth_filter_float = synth_filter_avx;

    }

}


static int rd_strip(CinepakEncContext *s, int y, int h, int keyframe, AVPicture *last_pict, AVPicture *pict, AVPicture *scratch_pict, unsigned char *buf, int64_t *best_score)

{

    int64_t score = 0;

    int best_size = 0, v1_size, v4_size, v4, mb_count = s->w * h / MB_AREA;

    strip_info info;

    CinepakMode best_mode;

    int v4_codebooks[CODEBOOK_NUM][CODEBOOK_MAX*VECTOR_MAX];

    if(!keyframe)

        calculate_skip_errors(s, h, last_pict, pict, &info);

    //precompute V4 codebooks

    for(v4_size = 1, v4 = 0; v4_size <= 256; v4_size <<= 2, v4++) {

        info.v4_codebook = v4_codebooks[v4];

        quantize(s, h, pict, 0, v4_size, v4, &info);

    }

    //try all powers of 4 for the size of the codebooks

    //constraint the v4 codebook to be no bigger than the v1 codebook

    for(v1_size = 1; v1_size <= 256; v1_size <<= 2) {

        //compute V1 codebook

        quantize(s, h, pict, 1, v1_size, -1, &info);

        for(v4_size = 0, v4 = -1; v4_size <= v1_size; v4_size = v4_size ? v4_size << 2 : v1_size >= 4 ? v1_size >> 2 : 1, v4++) {

            //try all modes

            for(CinepakMode mode = 0; mode < MODE_COUNT; mode++) {

                //don't allow MODE_MC in inter frames

                if(keyframe && mode == MODE_MC)

                    continue;

                //only allow V1-only mode if v4 codebook is empty

                if(!v4_size && mode != MODE_V1_ONLY)

                    continue;

                info.v4_codebook = v4 >= 0 ? v4_codebooks[v4] : NULL;

                score = calculate_mode_score(s, mode, h, v1_size, v4_size, v4, &info);

                //av_log(s->avctx, AV_LOG_INFO, "%3i %3i score = %li\n", v1_size, v4_size, score);

                if(best_size == 0 || score < *best_score) {

                    *best_score = score;

                    best_size = encode_mode(s, mode, h, v1_size, v4_size, v4, scratch_pict, &info, s->strip_buf + STRIP_HEADER_SIZE);

                    best_mode = mode;

                    av_log(s->avctx, AV_LOG_INFO, "mode %i, %3i, %3i: %18li %i B\n", mode, v1_size, v4_size, score, best_size);

#ifdef CINEPAKENC_DEBUG

                    //save MB encoding choices

                    memcpy(s->best_mb, s->mb, mb_count*sizeof(mb_info));

#endif

                    //memcpy(strip_temp + STRIP_HEADER_SIZE, strip_temp, best_size);

                    write_strip_header(s, y, h, keyframe, s->strip_buf, best_size);

                }

            }

        }

    }

#ifdef CINEPAKENC_DEBUG

    //gather stats. this will only work properly of MAX_STRIPS == 1

    if(best_mode == MODE_V1_ONLY) {

        s->num_v1_mode++;

        s->num_v1_encs += s->w*h/MB_AREA;

    } else {

        if(best_mode == MODE_V1_V4)

            s->num_v4_mode++;

        else

            s->num_mc_mode++;

        int x;

        for(x = 0; x < s->w*h/MB_AREA; x++)

            if(s->best_mb[x].best_encoding == ENC_V1)

                s->num_v1_encs++;

            else if(s->best_mb[x].best_encoding == ENC_V4)

                s->num_v4_encs++;

            else

                s->num_skips++;

    }

#endif

    best_size += STRIP_HEADER_SIZE;

    memcpy(buf, s->strip_buf, best_size);

    return best_size;

}


void ide_sector_read(IDEState *s)
{
    int64_t sector_num;
    int n;
    s->status = READY_STAT | SEEK_STAT;
    s->error = 0; /* not needed by IDE spec, but needed by Windows */
    sector_num = ide_get_sector(s);
    n = s->nsector;
    if (n == 0) {
        ide_transfer_stop(s);
    s->status |= BUSY_STAT;
    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
#if defined(DEBUG_IDE)
    printf("sector=%" PRId64 "\n", sector_num);
#endif
    s->iov.iov_base = s->io_buffer;
    s->iov.iov_len  = n * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&s->qiov, &s->iov, 1);
    bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
    s->pio_aiocb = bdrv_aio_readv(s->bs, sector_num, &s->qiov, n,
                                  ide_sector_read_cb, s);


static void pc_compat_1_5(QEMUMachineInitArgs *args)

{

    pc_compat_1_6(args);

    has_pvpanic = true;

}


int ff_v4l2_m2m_codec_init(AVCodecContext *avctx)

{

    int ret = AVERROR(EINVAL);

    struct dirent *entry;

    char node[PATH_MAX];

    DIR *dirp;

    V4L2m2mContext *s = avctx->priv_data;

    s->avctx = avctx;

    dirp = opendir("/dev");

    if (!dirp)

        return AVERROR(errno);

    for (entry = readdir(dirp); entry; entry = readdir(dirp)) {

        if (strncmp(entry->d_name, "video", 5))

            continue;

        snprintf(node, sizeof(node), "/dev/%s", entry->d_name);

        av_log(s->avctx, AV_LOG_DEBUG, "probing device %s\n", node);

        strncpy(s->devname, node, strlen(node) + 1);

        ret = v4l2_probe_driver(s);

        if (!ret)

                break;

    }

    closedir(dirp);

    if (ret) {

        av_log(s->avctx, AV_LOG_ERROR, "Could not find a valid device\n");

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

        return ret;

    }

    av_log(s->avctx, AV_LOG_INFO, "Using device %s\n", node);

    return v4l2_configure_contexts(s);

}


static int decode_frame_ilbm(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    IffContext *s = avctx->priv_data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    const uint8_t *buf_end = buf+buf_size;

    int y, plane;

    if (avctx->reget_buffer(avctx, &s->frame) < 0){

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

        return -1;

    }

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

        uint8_t *row = &s->frame.data[0][ y*s->frame.linesize[0] ];

        memset(row, 0, avctx->pix_fmt == PIX_FMT_PAL8 ? avctx->width : (avctx->width * 4));

        for (plane = 0; plane < avctx->bits_per_coded_sample && buf < buf_end; plane++) {

            if (avctx->pix_fmt == PIX_FMT_PAL8) {

                decodeplane8(row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane);

            } else { // PIX_FMT_BGR32

                decodeplane32(row, buf, FFMIN(s->planesize, buf_end - buf), avctx->bits_per_coded_sample, plane);

            }

            buf += s->planesize;

        }

    }

    *data_size = sizeof(AVFrame);

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

    return buf_size;

}


static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,

                    int flags)

{

    MP3DecContext *mp3 = s->priv_data;

    AVIndexEntry *ie, ie1;

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

    int64_t ret  = av_index_search_timestamp(st, timestamp, flags);

    int64_t best_pos;

    int fast_seek = (s->flags & AVFMT_FLAG_FAST_SEEK) ? 1 : 0;

    int64_t filesize = mp3->header_filesize;

    if (mp3->usetoc == 2)

        return -1; // generic index code

    if (filesize <= 0) {

        int64_t size = avio_size(s->pb);

        if (size > 0 && size > s->internal->data_offset)

            filesize = size - s->internal->data_offset;

    }

    if (   (mp3->is_cbr || fast_seek)

        && (mp3->usetoc == 0 || !mp3->xing_toc)

        && st->duration > 0

        && filesize > 0) {

        ie = &ie1;

        timestamp = av_clip64(timestamp, 0, st->duration);

        ie->timestamp = timestamp;

        ie->pos       = av_rescale(timestamp, filesize, st->duration) + s->internal->data_offset;

    } else if (mp3->xing_toc) {

        if (ret < 0)

            return ret;

        ie = &st->index_entries[ret];

    } else {

        return -1;

    }

    best_pos = mp3_sync(s, ie->pos, flags);

    if (best_pos < 0)

        return best_pos;

    if (mp3->is_cbr && ie == &ie1 && mp3->frames) {

        int frame_duration = av_rescale(st->duration, 1, mp3->frames);

        ie1.timestamp = frame_duration * av_rescale(best_pos - s->internal->data_offset, mp3->frames, mp3->header_filesize);

    }

    ff_update_cur_dts(s, st, ie->timestamp);

    return 0;

}


static int handle_secondary_tcp_pkt(NetFilterState *nf,

                                    Connection *conn,

                                    Packet *pkt)

{

    struct tcphdr *tcp_pkt;

    tcp_pkt = (struct tcphdr *)pkt->transport_header;

    if (trace_event_get_state(TRACE_COLO_FILTER_REWRITER_DEBUG)) {

        char *sdebug, *ddebug;

        sdebug = strdup(inet_ntoa(pkt->ip->ip_src));

        ddebug = strdup(inet_ntoa(pkt->ip->ip_dst));

        trace_colo_filter_rewriter_pkt_info(__func__, sdebug, ddebug,

                    ntohl(tcp_pkt->th_seq), ntohl(tcp_pkt->th_ack),

                    tcp_pkt->th_flags);

        trace_colo_filter_rewriter_conn_offset(conn->offset);

        g_free(sdebug);

        g_free(ddebug);

    }

    if (((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == (TH_ACK | TH_SYN))) {

        /*

         * save offset = secondary_seq and then

         * in handle_primary_tcp_pkt make offset

         * = secondary_seq - primary_seq

         */

        conn->offset = ntohl(tcp_pkt->th_seq);

    }

    if ((tcp_pkt->th_flags & (TH_ACK | TH_SYN)) == TH_ACK) {

        /* handle packets to the primary from the secondary*/

        tcp_pkt->th_seq = htonl(ntohl(tcp_pkt->th_seq) - conn->offset);

        net_checksum_calculate((uint8_t *)pkt->data, pkt->size);

    }

    return 0;

}


static inline bool cpu_handle_halt(CPUState *cpu)

{

    if (cpu->halted) {

#if defined(TARGET_I386) && !defined(CONFIG_USER_ONLY)

        if ((cpu->interrupt_request & CPU_INTERRUPT_POLL)

            && replay_interrupt()) {

            X86CPU *x86_cpu = X86_CPU(cpu);

            qemu_mutex_lock_iothread();

            apic_poll_irq(x86_cpu->apic_state);

            cpu_reset_interrupt(cpu, CPU_INTERRUPT_POLL);

            qemu_mutex_unlock_iothread();

        }

#endif

        if (!cpu_has_work(cpu)) {

            current_cpu = NULL;

            return true;

        }

        cpu->halted = 0;

    }

    return false;

}


static inline CopyRet copy_frame(AVCodecContext *avctx,

                                 BC_DTS_PROC_OUT *output,

                                 void *data, int *got_frame)

{

    BC_STATUS ret;

    BC_DTS_STATUS decoder_status = { 0, };

    uint8_t trust_interlaced;

    uint8_t interlaced;

    CHDContext *priv = avctx->priv_data;

    int64_t pkt_pts  = AV_NOPTS_VALUE;

    uint8_t pic_type = 0;

    uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==

                           VDEC_FLAG_BOTTOMFIELD;

    uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);

    int width    = output->PicInfo.width;

    int height   = output->PicInfo.height;

    int bwidth;

    uint8_t *src = output->Ybuff;

    int sStride;

    uint8_t *dst;

    int dStride;

    if (output->PicInfo.timeStamp != 0) {

        OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);

        if (node) {

            pkt_pts = node->reordered_opaque;

            pic_type = node->pic_type;

            av_free(node);

        } else {

            /*

             * We will encounter a situation where a timestamp cannot be

             * popped if a second field is being returned. In this case,

             * each field has the same timestamp and the first one will

             * cause it to be popped. To keep subsequent calculations

             * simple, pic_type should be set a FIELD value - doesn't

             * matter which, but I chose BOTTOM.

             */

            pic_type = PICT_BOTTOM_FIELD;

        }

        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",

               output->PicInfo.timeStamp);

        av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",

               pic_type);

    }

    ret = DtsGetDriverStatus(priv->dev, &decoder_status);

    if (ret != BC_STS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR,

               "CrystalHD: GetDriverStatus failed: %u\n", ret);

       return RET_ERROR;

    }

    /*

     * For most content, we can trust the interlaced flag returned

     * by the hardware, but sometimes we can't. These are the

     * conditions under which we can trust the flag:

     *

     * 1) It's not h.264 content

     * 2) The UNKNOWN_SRC flag is not set

     * 3) We know we're expecting a second field

     * 4) The hardware reports this picture and the next picture

     *    have the same picture number.

     *

     * Note that there can still be interlaced content that will

     * fail this check, if the hardware hasn't decoded the next

     * picture or if there is a corruption in the stream. (In either

     * case a 0 will be returned for the next picture number)

     */

    trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 ||

                       !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||

                       priv->need_second_field ||

                       (decoder_status.picNumFlags & ~0x40000000) ==

                       output->PicInfo.picture_number;

    /*

     * If we got a false negative for trust_interlaced on the first field,

     * we will realise our mistake here when we see that the picture number is that

     * of the previous picture. We cannot recover the frame and should discard the

     * second field to keep the correct number of output frames.

     */

    if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {

        av_log(avctx, AV_LOG_WARNING,

               "Incorrectly guessed progressive frame. Discarding second field\n");

        /* Returning without providing a picture. */

        return RET_OK;

    }

    interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&

                 trust_interlaced;

    if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {

        av_log(avctx, AV_LOG_VERBOSE,

               "Next picture number unknown. Assuming progressive frame.\n");

    }

    av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",

           interlaced, trust_interlaced);

    if (priv->pic->data[0] && !priv->need_second_field)

        av_frame_unref(priv->pic);

    priv->need_second_field = interlaced && !priv->need_second_field;

    if (!priv->pic->data[0]) {

        if (ff_get_buffer(avctx, priv->pic, AV_GET_BUFFER_FLAG_REF) < 0)

            return RET_ERROR;

    }

    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);

    if (priv->is_70012) {

        int pStride;

        if (width <= 720)

            pStride = 720;

        else if (width <= 1280)

            pStride = 1280;

        else pStride = 1920;

        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);

    } else {

        sStride = bwidth;

    }

    dStride = priv->pic->linesize[0];

    dst     = priv->pic->data[0];

    av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");

    if (interlaced) {

        int dY = 0;

        int sY = 0;

        height /= 2;

        if (bottom_field) {

            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");

            dY = 1;

        } else {

            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");

            dY = 0;

        }

        for (sY = 0; sY < height; dY++, sY++) {

            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);

            dY++;

        }

    } else {

        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);

    }

    priv->pic->interlaced_frame = interlaced;

    if (interlaced)

        priv->pic->top_field_first = !bottom_first;

    priv->pic->pts = pkt_pts;

#if FF_API_PKT_PTS

FF_DISABLE_DEPRECATION_WARNINGS

    priv->pic->pkt_pts = pkt_pts;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    if (!priv->need_second_field) {

        *got_frame       = 1;

        if ((ret = av_frame_ref(data, priv->pic)) < 0) {

            return ret;

        }

    }

    /*

     * Two types of PAFF content have been observed. One form causes the

     * hardware to return a field pair and the other individual fields,

     * even though the input is always individual fields. We must skip

     * copying on the next decode() call to maintain pipeline length in

     * the first case.

     */

    if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&

        (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {

        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");

        return RET_SKIP_NEXT_COPY;

    }

    /*

     * The logic here is purely based on empirical testing with samples.

     * If we need a second field, it could come from a second input packet,

     * or it could come from the same field-pair input packet at the current

     * field. In the first case, we should return and wait for the next time

     * round to get the second field, while in the second case, we should

     * ask the decoder for it immediately.

     *

     * Testing has shown that we are dealing with the fieldpair -> two fields

     * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture

     * type was PICT_FRAME (in this second case, the flag might still be set)

     */

    return priv->need_second_field &&

           (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||

            pic_type == PICT_FRAME) ?

           RET_COPY_NEXT_FIELD : RET_OK;

}


static av_cold int prores_encode_init(AVCodecContext *avctx)

{

    int i;

    ProresContext* ctx = avctx->priv_data;

    if (avctx->pix_fmt != PIX_FMT_YUV422P10LE) {

        av_log(avctx, AV_LOG_ERROR, "need YUV422P10\n");

        return -1;

    }

    if (avctx->width & 0x1) {

        av_log(avctx, AV_LOG_ERROR,

                "frame width needs to be multiple of 2\n");

        return -1;

    }

    if ((avctx->height & 0xf) || (avctx->width & 0xf)) {

        ctx->fill_y = av_malloc(DEFAULT_SLICE_MB_WIDTH << 9);

        ctx->fill_u = av_malloc(DEFAULT_SLICE_MB_WIDTH << 8);

        ctx->fill_v = av_malloc(DEFAULT_SLICE_MB_WIDTH << 8);

    }

    if (avctx->profile == FF_PROFILE_UNKNOWN) {

        avctx->profile = FF_PROFILE_PRORES_STANDARD;

        av_log(avctx, AV_LOG_INFO,

                "encoding with ProRes standard (apcn) profile\n");

    } else if (avctx->profile < FF_PROFILE_PRORES_PROXY

            || avctx->profile > FF_PROFILE_PRORES_HQ) {

        av_log(

                avctx,

                AV_LOG_ERROR,

                "unknown profile %d, use [0 - apco, 1 - apcs, 2 - apcn (default), 3 - apch]\n",

                avctx->profile);

        return -1;

    }

    avctx->codec_tag = AV_RL32((const uint8_t*)profiles[avctx->profile].name);

    for (i = 1; i <= 16; i++) {

        scale_mat(QMAT_LUMA[avctx->profile]  , ctx->qmat_luma[i - 1]  , i);

        scale_mat(QMAT_CHROMA[avctx->profile], ctx->qmat_chroma[i - 1], i);

    }

    avctx->coded_frame = avcodec_alloc_frame();

    avctx->coded_frame->key_frame = 1;

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    return 0;

}


static void test_visitor_out_union_flat(TestOutputVisitorData *data,

                                        const void *unused)

{

    QObject *arg;

    QDict *qdict;

    UserDefFlatUnion *tmp = g_malloc0(sizeof(UserDefFlatUnion));

    tmp->enum1 = ENUM_ONE_VALUE1;

    tmp->string = g_strdup("str");

    tmp->u.value1 = g_malloc0(sizeof(UserDefA));

    tmp->integer = 41;

    tmp->u.value1->boolean = true;

    visit_type_UserDefFlatUnion(data->ov, NULL, &tmp, &error_abort);

    arg = qmp_output_get_qobject(data->qov);

    g_assert(qobject_type(arg) == QTYPE_QDICT);

    qdict = qobject_to_qdict(arg);

    g_assert_cmpstr(qdict_get_str(qdict, "enum1"), ==, "value1");

    g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, "str");

    g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, 41);

    g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, true);

    qapi_free_UserDefFlatUnion(tmp);

    QDECREF(qdict);

}


int estimate_motion(MpegEncContext * s,

		    int mb_x, int mb_y,

		    int *mx_ptr, int *my_ptr)

{

    UINT8 *pix, *ppix;

    int sum, varc, vard, mx, my, range, dmin, xx, yy;

    int xmin, ymin, xmax, ymax;

    int rel_xmin, rel_ymin, rel_xmax, rel_ymax;

    int pred_x=0, pred_y=0;

    int P[5][2];

    const int shift= 1+s->quarter_sample;

    range = 8 * (1 << (s->f_code - 1));

    /* XXX: temporary kludge to avoid overflow for msmpeg4 */

    if (s->out_format == FMT_H263 && !s->h263_msmpeg4)

	range = range * 2;

    if (s->unrestricted_mv) {

        xmin = -16;

        ymin = -16;

        if (s->h263_plus)

            range *= 2;

        if(s->avctx==NULL || s->avctx->codec->id!=CODEC_ID_MPEG4){

            xmax = s->mb_width*16;

            ymax = s->mb_height*16;

        }else {

            /* XXX: dunno if this is correct but ffmpeg4 decoder wont like it otherwise

	            (cuz the drawn edge isnt large enough))*/

            xmax = s->width;

            ymax = s->height;

        }

    } else {

        xmin = 0;

        ymin = 0;

        xmax = s->mb_width*16 - 16;

        ymax = s->mb_height*16 - 16;

    }

    switch(s->full_search) {

    case ME_ZERO:

    default:

	no_motion_search(s, &mx, &my);

        dmin = 0;

        break;

    case ME_FULL:

	dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax);

        break;

    case ME_LOG:

	dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax);

        break;

    case ME_PHODS:

	dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax);

        break;

    case ME_X1: // just reserving some space for experiments ...

    case ME_EPZS:

        rel_xmin= xmin - s->mb_x*16;

        rel_xmax= xmax - s->mb_x*16;

        rel_ymin= ymin - s->mb_y*16;

        rel_ymax= ymax - s->mb_y*16;

        if(s->out_format == FMT_H263){

            static const int off[4]= {2, 1, 1, -1};

            const int mot_stride = s->block_wrap[0];

            const int mot_xy = s->block_index[0];

            P[0][0] = s->motion_val[mot_xy    ][0];

            P[0][1] = s->motion_val[mot_xy    ][1];

            P[1][0] = s->motion_val[mot_xy - 1][0];

            P[1][1] = s->motion_val[mot_xy - 1][1];

            if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift);

            /* special case for first line */

            if ((s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) {

                pred_x = P[1][0];

                pred_y = P[1][1];

            } else {

                P[2][0] = s->motion_val[mot_xy - mot_stride             ][0];

                P[2][1] = s->motion_val[mot_xy - mot_stride             ][1];

                P[3][0] = s->motion_val[mot_xy - mot_stride + off[0]    ][0];

                P[3][1] = s->motion_val[mot_xy - mot_stride + off[0]    ][1];

                if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift);

                if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift);

                if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift);

                P[4][0]= pred_x = mid_pred(P[1][0], P[2][0], P[3][0]);

                P[4][1]= pred_y = mid_pred(P[1][1], P[2][1], P[3][1]);

            }

        }else {

            const int xy= s->mb_y*s->mb_width + s->mb_x;

            pred_x= s->last_mv[0][0][0];

            pred_y= s->last_mv[0][0][1];

            P[0][0]= s->mv_table[0][xy  ];

            P[0][1]= s->mv_table[1][xy  ];

            if(s->mb_x == 0){

                P[1][0]= 0;

                P[1][1]= 0;

            }else{

                P[1][0]= s->mv_table[0][xy-1];

                P[1][1]= s->mv_table[1][xy-1];

                if(P[1][0] > (rel_xmax<<shift)) P[1][0]= (rel_xmax<<shift);

            }

            if (!(s->mb_y == 0 || s->first_slice_line || s->first_gob_line)) {

                P[2][0] = s->mv_table[0][xy - s->mb_width];

                P[2][1] = s->mv_table[1][xy - s->mb_width];

                P[3][0] = s->mv_table[0][xy - s->mb_width+1];

                P[3][1] = s->mv_table[1][xy - s->mb_width+1];

                if(P[2][1] > (rel_ymax<<shift)) P[2][1]= (rel_ymax<<shift);

                if(P[3][0] > (rel_xmax<<shift)) P[3][0]= (rel_xmax<<shift);

                if(P[3][0] < (rel_xmin<<shift)) P[3][0]= (rel_xmin<<shift);

                if(P[3][1] > (rel_ymax<<shift)) P[3][1]= (rel_ymax<<shift);

                P[4][0]= mid_pred(P[1][0], P[2][0], P[3][0]);

                P[4][1]= mid_pred(P[1][1], P[2][1], P[3][1]);

            }

        }

	dmin = epzs_motion_search(s, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax);

        mx+= s->mb_x*16;

        my+= s->mb_y*16;

        break;

    }

    /* intra / predictive decision */

    xx = mb_x * 16;

    yy = mb_y * 16;

    pix = s->new_picture[0] + (yy * s->linesize) + xx;

    /* At this point (mx,my) are full-pell and the absolute displacement */

    ppix = s->last_picture[0] + (my * s->linesize) + mx;

    sum = pix_sum(pix, s->linesize);

    varc = pix_norm1(pix, s->linesize);

    vard = pix_norm(pix, ppix, s->linesize);

    vard = vard >> 8;

    sum = sum >> 8;

    varc = (varc >> 8) - (sum * sum);

    s->mb_var[s->mb_width * mb_y + mb_x] = varc;

    s->avg_mb_var += varc;

    s->mc_mb_var += vard;

#if 0

    printf("varc=%4d avg_var=%4d (sum=%4d) vard=%4d mx=%2d my=%2d\n",

	   varc, s->avg_mb_var, sum, vard, mx - xx, my - yy);

#endif

    if (vard <= 64 || vard < varc) {

        if (s->full_search != ME_ZERO) {

            halfpel_motion_search(s, &mx, &my, dmin, xmin, ymin, xmax, ymax, pred_x, pred_y);

        } else {

            mx -= 16 * s->mb_x;

            my -= 16 * s->mb_y;

        }

	*mx_ptr = mx;

	*my_ptr = my;

	return 0;

    } else {

	*mx_ptr = 0;

	*my_ptr = 0;

	return 1;

    }

}


static int bad_mode_switch(CPUARMState *env, int mode)

{

    /* Return true if it is not valid for us to switch to

     * this CPU mode (ie all the UNPREDICTABLE cases in

     * the ARM ARM CPSRWriteByInstr pseudocode).

     */

    switch (mode) {

    case ARM_CPU_MODE_USR:

    case ARM_CPU_MODE_SYS:

    case ARM_CPU_MODE_SVC:

    case ARM_CPU_MODE_ABT:

    case ARM_CPU_MODE_UND:

    case ARM_CPU_MODE_IRQ:

    case ARM_CPU_MODE_FIQ:

        /* Note that we don't implement the IMPDEF NSACR.RFR which in v7

         * allows FIQ mode to be Secure-only. (In v8 this doesn't exist.)

         */

        return 0;

    case ARM_CPU_MODE_HYP:

        return !arm_feature(env, ARM_FEATURE_EL2)

            || arm_current_el(env) < 2 || arm_is_secure(env);

    case ARM_CPU_MODE_MON:

        return !arm_is_secure(env);

    default:

        return 1;

    }

}


static void scsi_write_complete(void * opaque, int ret)

{

    SCSIDiskReq *r = (SCSIDiskReq *)opaque;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    uint32_t n;

    if (r->req.aiocb != NULL) {

        r->req.aiocb = NULL;

        bdrv_acct_done(s->qdev.conf.bs, &r->acct);

    }

    if (ret < 0) {

        if (scsi_handle_rw_error(r, -ret)) {

            goto done;

        }

    }

    n = r->qiov.size / 512;

    r->sector += n;

    r->sector_count -= n;

    if (r->sector_count == 0) {

        scsi_req_complete(&r->req, GOOD);

    } else {

        scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);

        DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size);

        scsi_req_data(&r->req, r->qiov.size);

    }

done:

    if (!r->req.io_canceled) {

        scsi_req_unref(&r->req);

    }

}


static void subband_scale(int *dst, int *src, int scale, int offset, int len)

{

    int ssign = scale < 0 ? -1 : 1;

    int s = FFABS(scale);

    unsigned int round;

    int i, out, c = exp2tab[s & 3];

    s = offset - (s >> 2);

    if (s > 31) {

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

            dst[i] = 0;

        }

    } else if (s > 0) {

        round = 1 << (s-1);

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

            out = (int)(((int64_t)src[i] * c) >> 32);

            dst[i] = ((int)(out+round) >> s) * ssign;

        }

    }

    else {

        s = s + 32;

        round = 1U << (s-1);

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

            out = (int)((int64_t)((int64_t)src[i] * c + round) >> s);

            dst[i] = out * ssign;

        }

    }

}


static void pmsav5_insn_ap_write(CPUARMState *env, const ARMCPRegInfo *ri,

                                 uint64_t value)

{

    env->cp15.c5_insn = extended_mpu_ap_bits(value);

}


qht_entry_move(struct qht_bucket *to, int i, struct qht_bucket *from, int j)

{

    qht_debug_assert(!(to == from && i == j));

    qht_debug_assert(to->pointers[i]);

    qht_debug_assert(from->pointers[j]);

    to->hashes[i] = from->hashes[j];

    atomic_set(&to->pointers[i], from->pointers[j]);

    from->hashes[j] = 0;

    atomic_set(&from->pointers[j], NULL);

}


static int atrac3_decode_frame(AVCodecContext *avctx,

            void *data, int *data_size,

            AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    ATRAC3Context *q = avctx->priv_data;

    int result = 0;

    const uint8_t* databuf;

    float *samples = data;

    if (buf_size < avctx->block_align) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame too small (%d bytes). Truncated file?\n", buf_size);

        *data_size = 0;

        return buf_size;

    }

    /* Check if we need to descramble and what buffer to pass on. */

    if (q->scrambled_stream) {

        decode_bytes(buf, q->decoded_bytes_buffer, avctx->block_align);

        databuf = q->decoded_bytes_buffer;

    } else {

        databuf = buf;

    }

    result = decodeFrame(q, databuf, q->channels == 2 ? q->outSamples : &samples);

    if (result != 0) {

        av_log(NULL,AV_LOG_ERROR,"Frame decoding error!\n");

        return -1;

    }

    /* interleave */

    if (q->channels == 2) {

        q->fmt_conv.float_interleave(samples, (const float **)q->outSamples,

                                     1024, 2);

    }

    *data_size = 1024 * q->channels * av_get_bytes_per_sample(avctx->sample_fmt);

    return avctx->block_align;

}


static int flic_probe(AVProbeData *p)

{

    int magic_number;

    if (p->buf_size < 6)

        return 0;

    magic_number = AV_RL16(&p->buf[4]);

    if ((magic_number != FLIC_FILE_MAGIC_1) &&

        (magic_number != FLIC_FILE_MAGIC_2) &&

        (magic_number != FLIC_FILE_MAGIC_3))

        return 0;

    return AVPROBE_SCORE_MAX;

}


static int jp2_find_codestream(J2kDecoderContext *s)

{

    uint32_t atom_size;

    int found_codestream = 0, search_range = 10;

    // skip jpeg2k signature atom

    s->buf += 12;

    while(!found_codestream && search_range && s->buf_end - s->buf >= 8) {

        atom_size = AV_RB32(s->buf);

        if(AV_RB32(s->buf + 4) == JP2_CODESTREAM) {

            found_codestream = 1;

            s->buf += 8;

        } else {

            if (s->buf_end - s->buf < atom_size)

                return 0;

            s->buf += atom_size;

            search_range--;

        }

    }

    if(found_codestream)

        return 1;

    return 0;

}


static void tswap_siginfo(target_siginfo_t *tinfo,

                          const target_siginfo_t *info)

{

    int sig = info->si_signo;

    tinfo->si_signo = tswap32(sig);

    tinfo->si_errno = tswap32(info->si_errno);

    tinfo->si_code = tswap32(info->si_code);

    if (sig == TARGET_SIGILL || sig == TARGET_SIGFPE || sig == TARGET_SIGSEGV

        || sig == TARGET_SIGBUS || sig == TARGET_SIGTRAP) {

        tinfo->_sifields._sigfault._addr

            = tswapal(info->_sifields._sigfault._addr);

    } else if (sig == TARGET_SIGIO) {

        tinfo->_sifields._sigpoll._band

            = tswap32(info->_sifields._sigpoll._band);

        tinfo->_sifields._sigpoll._fd = tswap32(info->_sifields._sigpoll._fd);

    } else if (sig == TARGET_SIGCHLD) {

        tinfo->_sifields._sigchld._pid

            = tswap32(info->_sifields._sigchld._pid);

        tinfo->_sifields._sigchld._uid

            = tswap32(info->_sifields._sigchld._uid);

        tinfo->_sifields._sigchld._status

            = tswap32(info->_sifields._sigchld._status);

        tinfo->_sifields._sigchld._utime

            = tswapal(info->_sifields._sigchld._utime);

        tinfo->_sifields._sigchld._stime

            = tswapal(info->_sifields._sigchld._stime);

    } else if (sig >= TARGET_SIGRTMIN) {

        tinfo->_sifields._rt._pid = tswap32(info->_sifields._rt._pid);

        tinfo->_sifields._rt._uid = tswap32(info->_sifields._rt._uid);

        tinfo->_sifields._rt._sigval.sival_ptr

            = tswapal(info->_sifields._rt._sigval.sival_ptr);

    }

}


void axisdev88_init (ram_addr_t ram_size,

                     const char *boot_device,

                     const char *kernel_filename, const char *kernel_cmdline,

                     const char *initrd_filename, const char *cpu_model)

{

    CPUState *env;

    DeviceState *dev;

    SysBusDevice *s;

    qemu_irq irq[30], nmi[2], *cpu_irq;

    void *etraxfs_dmac;

    struct etraxfs_dma_client *eth[2] = {NULL, NULL};

    int kernel_size;

    int i;

    int nand_regs;

    int gpio_regs;

    ram_addr_t phys_ram;

    ram_addr_t phys_intmem;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "crisv32";

    }

    env = cpu_init(cpu_model);

    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */

    phys_ram = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0x40000000, ram_size, phys_ram | IO_MEM_RAM);

    /* The ETRAX-FS has 128Kb on chip ram, the docs refer to it as the

       internal memory.  */

    phys_intmem = qemu_ram_alloc(INTMEM_SIZE);

    cpu_register_physical_memory(0x38000000, INTMEM_SIZE,

                                 phys_intmem | IO_MEM_RAM);

      /* Attach a NAND flash to CS1.  */

    nand_state.nand = nand_init(NAND_MFR_STMICRO, 0x39);

    nand_regs = cpu_register_io_memory(nand_read, nand_write, &nand_state);

    cpu_register_physical_memory(0x10000000, 0x05000000, nand_regs);

    gpio_state.nand = &nand_state;

    gpio_regs = cpu_register_io_memory(gpio_read, gpio_write, &gpio_state);

    cpu_register_physical_memory(0x3001a000, 0x5c, gpio_regs);

    cpu_irq = cris_pic_init_cpu(env);

    dev = qdev_create(NULL, "etraxfs,pic");

    /* FIXME: Is there a proper way to signal vectors to the CPU core?  */

    qdev_prop_set_ptr(dev, "interrupt_vector", &env->interrupt_vector);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_mmio_map(s, 0, 0x3001c000);

    sysbus_connect_irq(s, 0, cpu_irq[0]);

    sysbus_connect_irq(s, 1, cpu_irq[1]);

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

        irq[i] = qdev_get_gpio_in(dev, i);

    }

    nmi[0] = qdev_get_gpio_in(dev, 30);

    nmi[1] = qdev_get_gpio_in(dev, 31);

    etraxfs_dmac = etraxfs_dmac_init(0x30000000, 10);

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

        /* On ETRAX, odd numbered channels are inputs.  */

        etraxfs_dmac_connect(etraxfs_dmac, i, irq + 7 + i, i & 1);

    }

    /* Add the two ethernet blocks.  */

    eth[0] = etraxfs_eth_init(&nd_table[0], 0x30034000, 1);

    if (nb_nics > 1)

        eth[1] = etraxfs_eth_init(&nd_table[1], 0x30036000, 2);

    /* The DMA Connector block is missing, hardwire things for now.  */

    etraxfs_dmac_connect_client(etraxfs_dmac, 0, eth[0]);

    etraxfs_dmac_connect_client(etraxfs_dmac, 1, eth[0] + 1);

    if (eth[1]) {

        etraxfs_dmac_connect_client(etraxfs_dmac, 6, eth[1]);

        etraxfs_dmac_connect_client(etraxfs_dmac, 7, eth[1] + 1);

    }

    /* 2 timers.  */

    sysbus_create_varargs("etraxfs,timer", 0x3001e000, irq[0x1b], nmi[1], NULL);

    sysbus_create_varargs("etraxfs,timer", 0x3005e000, irq[0x1b], nmi[1], NULL);

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

        sysbus_create_simple("etraxfs,serial", 0x30026000 + i * 0x2000,

                             irq[0x14 + i]);

    }

    if (kernel_filename) {

        uint64_t entry, high;

        int kcmdline_len;

        /* Boots a kernel elf binary, os/linux-2.6/vmlinux from the axis

           devboard SDK.  */

        kernel_size = load_elf(kernel_filename, -0x80000000LL,

                               &entry, NULL, &high, 0, ELF_MACHINE, 0);

        bootstrap_pc = entry;

        if (kernel_size < 0) {

            /* Takes a kimage from the axis devboard SDK.  */

            kernel_size = load_image_targphys(kernel_filename, 0x40004000,

                                              ram_size);

            bootstrap_pc = 0x40004000;

            env->regs[9] = 0x40004000 + kernel_size;

        }

        env->regs[8] = 0x56902387; /* RAM init magic.  */

        if (kernel_cmdline && (kcmdline_len = strlen(kernel_cmdline))) {

            if (kcmdline_len > 256) {

                fprintf(stderr, "Too long CRIS kernel cmdline (max 256)\n");

                exit(1);

            }

            /* Let the kernel know we are modifying the cmdline.  */

            env->regs[10] = 0x87109563;

            env->regs[11] = 0x40000000;

            pstrcpy_targphys(env->regs[11], 256, kernel_cmdline);

        }

    }

    env->pc = bootstrap_pc;

    printf ("pc =%x\n", env->pc);

    printf ("ram size =%ld\n", ram_size);

}


static int decode_pic_timing(HEVCContext *s)

{

    GetBitContext *gb = &s->HEVClc->gb;

    HEVCSPS *sps = (HEVCSPS*)s->sps_list[s->active_seq_parameter_set_id]->data;

    if (!sps)

        return(AVERROR(ENOMEM));

    if (sps->vui.frame_field_info_present_flag) {

        int pic_struct = get_bits(gb, 4);

        s->picture_struct = AV_PICTURE_STRUCTURE_UNKNOWN;

        if (pic_struct == 2) {

            av_log(s->avctx, AV_LOG_DEBUG, "BOTTOM Field\n");

            s->picture_struct = AV_PICTURE_STRUCTURE_BOTTOM_FIELD;

        } else if (pic_struct == 1) {

            av_log(s->avctx, AV_LOG_DEBUG, "TOP Field\n");

            s->picture_struct = AV_PICTURE_STRUCTURE_TOP_FIELD;

        }

        get_bits(gb, 2);                   // source_scan_type

        get_bits(gb, 1);                   // duplicate_flag

    }

    return 1;

}


static void *circular_buffer_task( void *_URLContext)

{

    URLContext *h = _URLContext;

    UDPContext *s = h->priv_data;

    fd_set rfds;

    struct timeval tv;

    while(!s->exit_thread) {

        int left;

        int ret;

        int len;

        if (ff_check_interrupt(&h->interrupt_callback)) {

            s->circular_buffer_error = AVERROR(EINTR);

            goto end;

        }

        FD_ZERO(&rfds);

        FD_SET(s->udp_fd, &rfds);

        tv.tv_sec = 1;

        tv.tv_usec = 0;

        ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);

        if (ret < 0) {

            if (ff_neterrno() == AVERROR(EINTR))

                continue;

            s->circular_buffer_error = AVERROR(EIO);

            goto end;

        }

        if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))

            continue;

        /* How much do we have left to the end of the buffer */

        /* Whats the minimum we can read so that we dont comletely fill the buffer */

        left = av_fifo_space(s->fifo);

        /* No Space left, error, what do we do now */

        if(left < UDP_MAX_PKT_SIZE + 4) {

            av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n");

            s->circular_buffer_error = AVERROR(EIO);

            goto end;

        }

        len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);

        if (len < 0) {

            if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {

                s->circular_buffer_error = AVERROR(EIO);

                goto end;

            }

            continue;

        }

        AV_WL32(s->tmp, len);

        pthread_mutex_lock(&s->mutex);

        av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);

        pthread_cond_signal(&s->cond);

        pthread_mutex_unlock(&s->mutex);

    }

end:

    pthread_mutex_lock(&s->mutex);

    pthread_cond_signal(&s->cond);

    pthread_mutex_unlock(&s->mutex);

    return NULL;

}


static int decode_rle(uint8_t *bitmap, int linesize, int w, int h,
                      const uint8_t *buf, int start, int buf_size, int is_8bit)
{
    GetBitContext gb;
    int bit_len;
    int x, y, len, color;
    uint8_t *d;
    if (start >= buf_size)
    bit_len = (buf_size - start) * 8;
    init_get_bits(&gb, buf + start, bit_len);
    x = 0;
    y = 0;
    d = bitmap;
    for(;;) {
        if (get_bits_count(&gb) > bit_len)
        if (is_8bit)
            len = decode_run_8bit(&gb, &color);
        else
            len = decode_run_2bit(&gb, &color);
        len = FFMIN(len, w - x);
        memset(d + x, color, len);
        x += len;
        if (x >= w) {
            y++;
            if (y >= h)
                break;
            d += linesize;
            x = 0;
            /* byte align */
            align_get_bits(&gb);
        }
    }
    return 0;
}


void bdrv_eject(BlockDriverState *bs, int eject_flag)

{

    BlockDriver *drv = bs->drv;

    int ret;

    if (!drv || !drv->bdrv_eject) {

        ret = -ENOTSUP;

    } else {

        ret = drv->bdrv_eject(bs, eject_flag);

    }

    if (ret == -ENOTSUP) {

        if (eject_flag)

            bdrv_close(bs);

    }

}


static MemTxResult memory_region_write_with_attrs_accessor(MemoryRegion *mr,

                                                           hwaddr addr,

                                                           uint64_t *value,

                                                           unsigned size,

                                                           unsigned shift,

                                                           uint64_t mask,

                                                           MemTxAttrs attrs)

{

    uint64_t tmp;

    tmp = (*value >> shift) & mask;

    if (mr->subpage) {

        trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);

    } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {

        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);

        trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);

    }

    return mr->ops->write_with_attrs(mr->opaque, addr, tmp, size, attrs);

}


static void usbredir_realize(USBDevice *udev, Error **errp)

{

    USBRedirDevice *dev = USB_REDIRECT(udev);

    int i;

    if (!qemu_chr_fe_get_driver(&dev->cs)) {

        error_setg(errp, QERR_MISSING_PARAMETER, "chardev");

        return;

    }

    if (dev->filter_str) {

        i = usbredirfilter_string_to_rules(dev->filter_str, ":", "|",

                                           &dev->filter_rules,

                                           &dev->filter_rules_count);

        if (i) {

            error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "filter",

                       "a usb device filter string");

            return;

        }

    }

    dev->chardev_close_bh = qemu_bh_new(usbredir_chardev_close_bh, dev);

    dev->device_reject_bh = qemu_bh_new(usbredir_device_reject_bh, dev);

    dev->attach_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, usbredir_do_attach, dev);

    packet_id_queue_init(&dev->cancelled, dev, "cancelled");

    packet_id_queue_init(&dev->already_in_flight, dev, "already-in-flight");

    usbredir_init_endpoints(dev);

    /* We'll do the attach once we receive the speed from the usb-host */

    udev->auto_attach = 0;

    /* Will be cleared during setup when we find conflicts */

    dev->compatible_speedmask = USB_SPEED_MASK_FULL | USB_SPEED_MASK_HIGH;

    /* Let the backend know we are ready */

    qemu_chr_fe_set_handlers(&dev->cs, usbredir_chardev_can_read,

                             usbredir_chardev_read, usbredir_chardev_event,

                             dev, NULL, true);

    qemu_add_vm_change_state_handler(usbredir_vm_state_change, dev);

}


static void coroutine_fn v9fs_lcreate(void *opaque)

{

    int32_t dfid, flags, mode;

    gid_t gid;

    ssize_t err = 0;

    ssize_t offset = 7;

    V9fsString name;

    V9fsFidState *fidp;

    struct stat stbuf;

    V9fsQID qid;

    int32_t iounit;

    V9fsPDU *pdu = opaque;

    v9fs_string_init(&name);

    err = pdu_unmarshal(pdu, offset, "dsddd", &dfid,

                        &name, &flags, &mode, &gid);

    if (err < 0) {

        goto out_nofid;

    trace_v9fs_lcreate(pdu->tag, pdu->id, dfid, flags, mode, gid);

    if (name_is_illegal(name.data)) {

        err = -ENOENT;

        goto out_nofid;

    if (!strcmp(".", name.data) || !strcmp("..", name.data)) {

        err = -EEXIST;

        goto out_nofid;

    fidp = get_fid(pdu, dfid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    flags = get_dotl_openflags(pdu->s, flags);

    err = v9fs_co_open2(pdu, fidp, &name, gid,

                        flags | O_CREAT, mode, &stbuf);

    if (err < 0) {

    fidp->fid_type = P9_FID_FILE;

    fidp->open_flags = flags;

    if (flags & O_EXCL) {

        /*

         * We let the host file system do O_EXCL check

         * We should not reclaim such fd

         */

        fidp->flags |= FID_NON_RECLAIMABLE;

    iounit =  get_iounit(pdu, &fidp->path);

    stat_to_qid(&stbuf, &qid);

    err = pdu_marshal(pdu, offset, "Qd", &qid, iounit);

    if (err < 0) {

    err += offset;

    trace_v9fs_lcreate_return(pdu->tag, pdu->id,

                              qid.type, qid.version, qid.path, iounit);

out:

    put_fid(pdu, fidp);

out_nofid:

    pdu_complete(pdu, err);

    v9fs_string_free(&name);


static inline int array_ensure_allocated(array_t* array, int index)

{

    if((index + 1) * array->item_size > array->size) {

        int new_size = (index + 32) * array->item_size;

        array->pointer = g_realloc(array->pointer, new_size);

        if (!array->pointer)

            return -1;

        array->size = new_size;

        array->next = index + 1;

    }

    return 0;

}


static inline TranslationBlock *tb_find_fast(void)

{

    TranslationBlock *tb;

    target_ulong cs_base, pc;

    uint64_t flags;

    /* we record a subset of the CPU state. It will

       always be the same before a given translated block

       is executed. */

#if defined(TARGET_I386)

    flags = env->hflags;

    flags |= (env->eflags & (IOPL_MASK | TF_MASK | VM_MASK));

    flags |= env->intercept;

    cs_base = env->segs[R_CS].base;

    pc = cs_base + env->eip;

#elif defined(TARGET_ARM)

    flags = env->thumb | (env->vfp.vec_len << 1)

            | (env->vfp.vec_stride << 4);

    if ((env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR)

        flags |= (1 << 6);

    if (env->vfp.xregs[ARM_VFP_FPEXC] & (1 << 30))

        flags |= (1 << 7);

    flags |= (env->condexec_bits << 8);

    cs_base = 0;

    pc = env->regs[15];

#elif defined(TARGET_SPARC)

#ifdef TARGET_SPARC64

    // Combined FPU enable bits . PRIV . DMMU enabled . IMMU enabled

    flags = (((env->pstate & PS_PEF) >> 1) | ((env->fprs & FPRS_FEF) << 2))

        | (env->pstate & PS_PRIV) | ((env->lsu & (DMMU_E | IMMU_E)) >> 2);

#else

    // FPU enable . Supervisor

    flags = (env->psref << 4) | env->psrs;

#endif

    cs_base = env->npc;

    pc = env->pc;

#elif defined(TARGET_PPC)

    flags = env->hflags;

    cs_base = 0;

    pc = env->nip;

#elif defined(TARGET_MIPS)

    flags = env->hflags & (MIPS_HFLAG_TMASK | MIPS_HFLAG_BMASK);

    cs_base = 0;

    pc = env->PC[env->current_tc];

#elif defined(TARGET_M68K)

    flags = (env->fpcr & M68K_FPCR_PREC)  /* Bit  6 */

            | (env->sr & SR_S)            /* Bit  13 */

            | ((env->macsr >> 4) & 0xf);  /* Bits 0-3 */

    cs_base = 0;

    pc = env->pc;

#elif defined(TARGET_SH4)

    flags = env->flags;

    cs_base = 0;

    pc = env->pc;

#elif defined(TARGET_ALPHA)

    flags = env->ps;

    cs_base = 0;

    pc = env->pc;

#elif defined(TARGET_CRIS)

    flags = env->pregs[PR_CCS] & (U_FLAG | X_FLAG);

    cs_base = 0;

    pc = env->pc;

#else

#error unsupported CPU

#endif

    tb = env->tb_jmp_cache[tb_jmp_cache_hash_func(pc)];

    if (__builtin_expect(!tb || tb->pc != pc || tb->cs_base != cs_base ||

                         tb->flags != flags, 0)) {

        tb = tb_find_slow(pc, cs_base, flags);

        /* Note: we do it here to avoid a gcc bug on Mac OS X when

           doing it in tb_find_slow */

        if (tb_invalidated_flag) {

            /* as some TB could have been invalidated because

               of memory exceptions while generating the code, we

               must recompute the hash index here */

            T0 = 0;

        }

    }

    return tb;

}