static void v9fs_write(void *opaque)

{

    int cnt;

    ssize_t err;

    int32_t fid;

    int64_t off;

    int32_t count;

    int32_t len = 0;

    int32_t total = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

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

    struct iovec *sg = iov;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dqdv", &fid, &off, &count, sg, &cnt);

    trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, cnt);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (fidp->fid_type == P9_FID_FILE) {

        if (fidp->fs.fd == -1) {

            err = -EINVAL;

            goto out;

        }

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

        /*

         * setxattr operation

         */

        err = v9fs_xattr_write(s, pdu, fidp, off, count, sg, cnt);

        goto out;

    } else {

        err = -EINVAL;

        goto out;

    }

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

    do {

        if (0) {

            print_sg(sg, cnt);

        }

        /* Loop in case of EINTR */

        do {

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

            if (len >= 0) {

                off   += len;

                total += 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 (total < count && len > 0);

    offset += pdu_marshal(pdu, offset, "d", total);

    err = offset;

    trace_v9fs_write_return(pdu->tag, pdu->id, total, err);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


void av_set_cpu_flags_mask(int mask)

{

    cpu_flags = get_cpu_flags() & mask;

}


static int decode_header_trees(SmackVContext *smk) {

    GetBitContext gb;

    int mmap_size, mclr_size, full_size, type_size, ret;

    mmap_size = AV_RL32(smk->avctx->extradata);

    mclr_size = AV_RL32(smk->avctx->extradata + 4);

    full_size = AV_RL32(smk->avctx->extradata + 8);

    type_size = AV_RL32(smk->avctx->extradata + 12);

    init_get_bits8(&gb, smk->avctx->extradata + 16, smk->avctx->extradata_size - 16);

    if(!get_bits1(&gb)) {

        av_log(smk->avctx, AV_LOG_INFO, "Skipping MMAP tree\n");

        smk->mmap_tbl = av_malloc(sizeof(int) * 2);

        if (!smk->mmap_tbl)

            return AVERROR(ENOMEM);

        smk->mmap_tbl[0] = 0;

        smk->mmap_last[0] = smk->mmap_last[1] = smk->mmap_last[2] = 1;

    } else {

        ret = smacker_decode_header_tree(smk, &gb, &smk->mmap_tbl, smk->mmap_last, mmap_size);

        if (ret < 0)

            return ret;

    }

    if(!get_bits1(&gb)) {

        av_log(smk->avctx, AV_LOG_INFO, "Skipping MCLR tree\n");

        smk->mclr_tbl = av_malloc(sizeof(int) * 2);

        if (!smk->mclr_tbl)

            return AVERROR(ENOMEM);

        smk->mclr_tbl[0] = 0;

        smk->mclr_last[0] = smk->mclr_last[1] = smk->mclr_last[2] = 1;

    } else {

        ret = smacker_decode_header_tree(smk, &gb, &smk->mclr_tbl, smk->mclr_last, mclr_size);

        if (ret < 0)

            return ret;

    }

    if(!get_bits1(&gb)) {

        av_log(smk->avctx, AV_LOG_INFO, "Skipping FULL tree\n");

        smk->full_tbl = av_malloc(sizeof(int) * 2);

        if (!smk->full_tbl)

            return AVERROR(ENOMEM);

        smk->full_tbl[0] = 0;

        smk->full_last[0] = smk->full_last[1] = smk->full_last[2] = 1;

    } else {

        ret = smacker_decode_header_tree(smk, &gb, &smk->full_tbl, smk->full_last, full_size);

        if (ret < 0)

            return ret;

    }

    if(!get_bits1(&gb)) {

        av_log(smk->avctx, AV_LOG_INFO, "Skipping TYPE tree\n");

        smk->type_tbl = av_malloc(sizeof(int) * 2);

        if (!smk->type_tbl)

            return AVERROR(ENOMEM);

        smk->type_tbl[0] = 0;

        smk->type_last[0] = smk->type_last[1] = smk->type_last[2] = 1;

    } else {

        ret = smacker_decode_header_tree(smk, &gb, &smk->type_tbl, smk->type_last, type_size);

        if (ret < 0)

            return ret;

    }

    return 0;

}


void aio_set_fd_handler(AioContext *ctx,

                        int fd,

                        IOHandler *io_read,

                        IOHandler *io_write,

                        AioFlushHandler *io_flush,

                        void *opaque)

{

    AioHandler *node;

    node = find_aio_handler(ctx, fd);

    /* Are we deleting the fd handler? */

    if (!io_read && !io_write) {

        if (node) {

            g_source_remove_poll(&ctx->source, &node->pfd);

            /* If the lock is held, just mark the node as deleted */

            if (ctx->walking_handlers) {

                node->deleted = 1;

                node->pfd.revents = 0;

            } else {

                /* Otherwise, delete it for real.  We can't just mark it as

                 * deleted because deleted nodes are only cleaned up after

                 * releasing the walking_handlers lock.

                 */

                QLIST_REMOVE(node, node);

                g_free(node);

            }

        }

    } else {

        if (node == NULL) {

            /* Alloc and insert if it's not already there */

            node = g_malloc0(sizeof(AioHandler));

            node->pfd.fd = fd;

            QLIST_INSERT_HEAD(&ctx->aio_handlers, node, node);

            g_source_add_poll(&ctx->source, &node->pfd);

        }

        /* Update handler with latest information */

        node->io_read = io_read;

        node->io_write = io_write;

        node->io_flush = io_flush;

        node->opaque = opaque;

        node->pollfds_idx = -1;

        node->pfd.events = (io_read ? G_IO_IN | G_IO_HUP | G_IO_ERR : 0);

        node->pfd.events |= (io_write ? G_IO_OUT | G_IO_ERR : 0);

    }

    aio_notify(ctx);

}


av_cold static int auto_matrix(SwrContext *s)

{

    int i, j, out_i;

    double matrix[64][64]={{0}};

    int64_t unaccounted, in_ch_layout, out_ch_layout;

    double maxcoef=0;

    char buf[128];

    const int matrix_encoding = s->matrix_encoding;

    float maxval;

    in_ch_layout = clean_layout(s, s->in_ch_layout);

    if(!sane_layout(in_ch_layout)){

        av_get_channel_layout_string(buf, sizeof(buf), -1, s->in_ch_layout);

        av_log(s, AV_LOG_ERROR, "Input channel layout '%s' is not supported\n", buf);

        return AVERROR(EINVAL);

    }

    out_ch_layout = clean_layout(s, s->out_ch_layout);

    if(!sane_layout(out_ch_layout)){

        av_get_channel_layout_string(buf, sizeof(buf), -1, s->out_ch_layout);

        av_log(s, AV_LOG_ERROR, "Output channel layout '%s' is not supported\n", buf);

        return AVERROR(EINVAL);

    }

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

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

        if(in_ch_layout & out_ch_layout & (1ULL<<i))

            matrix[i][i]= 1.0;

    }

    unaccounted= in_ch_layout & ~out_ch_layout;

//FIXME implement dolby surround

//FIXME implement full ac3

    if(unaccounted & AV_CH_FRONT_CENTER){

        if((out_ch_layout & AV_CH_LAYOUT_STEREO) == AV_CH_LAYOUT_STEREO){

            if(in_ch_layout & AV_CH_LAYOUT_STEREO) {

                matrix[ FRONT_LEFT][FRONT_CENTER]+= s->clev;

                matrix[FRONT_RIGHT][FRONT_CENTER]+= s->clev;

            } else {

                matrix[ FRONT_LEFT][FRONT_CENTER]+= M_SQRT1_2;

                matrix[FRONT_RIGHT][FRONT_CENTER]+= M_SQRT1_2;

            }

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_LAYOUT_STEREO){

        if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[FRONT_CENTER][ FRONT_LEFT]+= M_SQRT1_2;

            matrix[FRONT_CENTER][FRONT_RIGHT]+= M_SQRT1_2;

            if(in_ch_layout & AV_CH_FRONT_CENTER)

                matrix[FRONT_CENTER][ FRONT_CENTER] = s->clev*sqrt(2);

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_BACK_CENTER){

        if(out_ch_layout & AV_CH_BACK_LEFT){

            matrix[ BACK_LEFT][BACK_CENTER]+= M_SQRT1_2;

            matrix[BACK_RIGHT][BACK_CENTER]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_SIDE_LEFT){

            matrix[ SIDE_LEFT][BACK_CENTER]+= M_SQRT1_2;

            matrix[SIDE_RIGHT][BACK_CENTER]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY ||

                matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                if (unaccounted & (AV_CH_BACK_LEFT | AV_CH_SIDE_LEFT)) {

                    matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev * M_SQRT1_2;

                    matrix[FRONT_RIGHT][BACK_CENTER] += s->slev * M_SQRT1_2;

                } else {

                    matrix[FRONT_LEFT ][BACK_CENTER] -= s->slev;

                    matrix[FRONT_RIGHT][BACK_CENTER] += s->slev;

                }

            } else {

                matrix[ FRONT_LEFT][BACK_CENTER]+= s->slev*M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_CENTER]+= s->slev*M_SQRT1_2;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][BACK_CENTER]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_BACK_LEFT){

        if(out_ch_layout & AV_CH_BACK_CENTER){

            matrix[BACK_CENTER][ BACK_LEFT]+= M_SQRT1_2;

            matrix[BACK_CENTER][BACK_RIGHT]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_SIDE_LEFT){

            if(in_ch_layout & AV_CH_SIDE_LEFT){

                matrix[ SIDE_LEFT][ BACK_LEFT]+= M_SQRT1_2;

                matrix[SIDE_RIGHT][BACK_RIGHT]+= M_SQRT1_2;

            }else{

            matrix[ SIDE_LEFT][ BACK_LEFT]+= 1.0;

            matrix[SIDE_RIGHT][BACK_RIGHT]+= 1.0;

            }

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) {

                matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * M_SQRT1_2;

                matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * M_SQRT1_2;

            } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                matrix[FRONT_LEFT ][BACK_LEFT ] -= s->slev * SQRT3_2;

                matrix[FRONT_LEFT ][BACK_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev * SQRT3_2;

            } else {

                matrix[ FRONT_LEFT][ BACK_LEFT] += s->slev;

                matrix[FRONT_RIGHT][BACK_RIGHT] += s->slev;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][BACK_LEFT ]+= s->slev*M_SQRT1_2;

            matrix[ FRONT_CENTER][BACK_RIGHT]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_SIDE_LEFT){

        if(out_ch_layout & AV_CH_BACK_LEFT){

            /* if back channels do not exist in the input, just copy side

               channels to back channels, otherwise mix side into back */

            if (in_ch_layout & AV_CH_BACK_LEFT) {

                matrix[BACK_LEFT ][SIDE_LEFT ] += M_SQRT1_2;

                matrix[BACK_RIGHT][SIDE_RIGHT] += M_SQRT1_2;

            } else {

                matrix[BACK_LEFT ][SIDE_LEFT ] += 1.0;

                matrix[BACK_RIGHT][SIDE_RIGHT] += 1.0;

            }

        }else if(out_ch_layout & AV_CH_BACK_CENTER){

            matrix[BACK_CENTER][ SIDE_LEFT]+= M_SQRT1_2;

            matrix[BACK_CENTER][SIDE_RIGHT]+= M_SQRT1_2;

        }else if(out_ch_layout & AV_CH_FRONT_LEFT){

            if (matrix_encoding == AV_MATRIX_ENCODING_DOLBY) {

                matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * M_SQRT1_2;

                matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * M_SQRT1_2;

            } else if (matrix_encoding == AV_MATRIX_ENCODING_DPLII) {

                matrix[FRONT_LEFT ][SIDE_LEFT ] -= s->slev * SQRT3_2;

                matrix[FRONT_LEFT ][SIDE_RIGHT] -= s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_LEFT ] += s->slev * M_SQRT1_2;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev * SQRT3_2;

            } else {

                matrix[ FRONT_LEFT][ SIDE_LEFT] += s->slev;

                matrix[FRONT_RIGHT][SIDE_RIGHT] += s->slev;

            }

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][SIDE_LEFT ]+= s->slev*M_SQRT1_2;

            matrix[ FRONT_CENTER][SIDE_RIGHT]+= s->slev*M_SQRT1_2;

        }else

            av_assert0(0);

    }

    if(unaccounted & AV_CH_FRONT_LEFT_OF_CENTER){

        if(out_ch_layout & AV_CH_FRONT_LEFT){

            matrix[ FRONT_LEFT][ FRONT_LEFT_OF_CENTER]+= 1.0;

            matrix[FRONT_RIGHT][FRONT_RIGHT_OF_CENTER]+= 1.0;

        }else if(out_ch_layout & AV_CH_FRONT_CENTER){

            matrix[ FRONT_CENTER][ FRONT_LEFT_OF_CENTER]+= M_SQRT1_2;

            matrix[ FRONT_CENTER][FRONT_RIGHT_OF_CENTER]+= M_SQRT1_2;

        }else

            av_assert0(0);

    }

    /* mix LFE into front left/right or center */

    if (unaccounted & AV_CH_LOW_FREQUENCY) {

        if (out_ch_layout & AV_CH_FRONT_CENTER) {

            matrix[FRONT_CENTER][LOW_FREQUENCY] += s->lfe_mix_level;

        } else if (out_ch_layout & AV_CH_FRONT_LEFT) {

            matrix[FRONT_LEFT ][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2;

            matrix[FRONT_RIGHT][LOW_FREQUENCY] += s->lfe_mix_level * M_SQRT1_2;

        } else

            av_assert0(0);

    }

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

        double sum=0;

        int in_i=0;

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

            s->matrix[out_i][in_i]= matrix[i][j];

            if(matrix[i][j]){

                sum += fabs(matrix[i][j]);

            }

            if(in_ch_layout & (1ULL<<j))

                in_i++;

        }

        maxcoef= FFMAX(maxcoef, sum);

        if(out_ch_layout & (1ULL<<i))

            out_i++;

    }

    if(s->rematrix_volume  < 0)

        maxcoef = -s->rematrix_volume;

    if (s->rematrix_maxval > 0) {

        maxval = s->rematrix_maxval;

    } else if (   av_get_packed_sample_fmt(s->out_sample_fmt) < AV_SAMPLE_FMT_FLT

               || av_get_packed_sample_fmt(s->int_sample_fmt) < AV_SAMPLE_FMT_FLT) {

        maxval = 1.0;

    } else

        maxval = INT_MAX;

    if(maxcoef > maxval || s->rematrix_volume  < 0){

        maxcoef /= maxval;

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

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

                s->matrix[i][j] /= maxcoef;

            }

    }

    if(s->rematrix_volume > 0){

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

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

                s->matrix[i][j] *= s->rematrix_volume;

            }

    }

    for(i=0; i<av_get_channel_layout_nb_channels(out_ch_layout); i++){

        for(j=0; j<av_get_channel_layout_nb_channels(in_ch_layout); j++){

            av_log(NULL, AV_LOG_DEBUG, "%f ", s->matrix[i][j]);

        }

        av_log(NULL, AV_LOG_DEBUG, "\n");

    }

    return 0;

}


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

{

    const uint8_t *s = src;

    const uint8_t *end;

    const uint8_t *mm_end;

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

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

    __asm__ volatile(

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

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

        ::"m"(red_16mask),"m"(green_16mask));

    mm_end = end - 15;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        d += 4;

        s += 16;

    }

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

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

    while (s < end) {

        register int rgb = *(const uint32_t*)s; s += 4;

        *d++ = ((rgb&0xF8)<<8) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>19);

    }

}


static void g364fb_update_display(void *opaque)
{
    G364State *s = opaque;
    if (s->width == 0 || s->height == 0)
        return;
    if (s->width != ds_get_width(s->ds) || s->height != ds_get_height(s->ds)) {
        qemu_console_resize(s->ds, s->width, s->height);
    }
    if (s->ctla & CTLA_FORCE_BLANK) {
        g364fb_draw_blank(s);
    } else if (s->depth == 8) {
        g364fb_draw_graphic8(s);
    } else {
        error_report("g364: unknown guest depth %d", s->depth);
    }
    qemu_irq_raise(s->irq);
}


static int decode_pic(AVSContext *h)

{

    int ret;

    int skip_count    = -1;

    enum cavs_mb mb_type;

    if (!h->top_qp) {

        av_log(h->avctx, AV_LOG_ERROR, "No sequence header decoded yet\n");

        return AVERROR_INVALIDDATA;

    }

    av_frame_unref(h->cur.f);

    skip_bits(&h->gb, 16);//bbv_dwlay

    if (h->stc == PIC_PB_START_CODE) {

        h->cur.f->pict_type = get_bits(&h->gb, 2) + AV_PICTURE_TYPE_I;

        if (h->cur.f->pict_type > AV_PICTURE_TYPE_B) {

            av_log(h->avctx, AV_LOG_ERROR, "illegal picture type\n");

            return AVERROR_INVALIDDATA;

        }

        /* make sure we have the reference frames we need */

        if (!h->DPB[0].f->data[0] ||

           (!h->DPB[1].f->data[0] && h->cur.f->pict_type == AV_PICTURE_TYPE_B))

            return AVERROR_INVALIDDATA;

    } else {

        h->cur.f->pict_type = AV_PICTURE_TYPE_I;

        if (get_bits1(&h->gb))

            skip_bits(&h->gb, 24);//time_code

        /* old sample clips were all progressive and no low_delay,

           bump stream revision if detected otherwise */

        if (h->low_delay || !(show_bits(&h->gb, 9) & 1))

            h->stream_revision = 1;

        /* similarly test top_field_first and repeat_first_field */

        else if (show_bits(&h->gb, 11) & 3)

            h->stream_revision = 1;

        if (h->stream_revision > 0)

            skip_bits(&h->gb, 1); //marker_bit

    }

    ret = ff_get_buffer(h->avctx, h->cur.f, h->cur.f->pict_type == AV_PICTURE_TYPE_B ?

                        0 : AV_GET_BUFFER_FLAG_REF);

    if (ret < 0)

        return ret;

    if (!h->edge_emu_buffer) {

        int alloc_size = FFALIGN(FFABS(h->cur.f->linesize[0]) + 32, 32);

        h->edge_emu_buffer = av_mallocz(alloc_size * 2 * 24);

        if (!h->edge_emu_buffer)

            return AVERROR(ENOMEM);

    }

    if ((ret = ff_cavs_init_pic(h)) < 0)

        return ret;

    h->cur.poc = get_bits(&h->gb, 8) * 2;

    /* get temporal distances and MV scaling factors */

    if (h->cur.f->pict_type != AV_PICTURE_TYPE_B) {

        h->dist[0] = (h->cur.poc - h->DPB[0].poc) & 511;

    } else {

        h->dist[0] = (h->DPB[0].poc  - h->cur.poc) & 511;

    }

    h->dist[1] = (h->cur.poc - h->DPB[1].poc) & 511;

    h->scale_den[0] = h->dist[0] ? 512/h->dist[0] : 0;

    h->scale_den[1] = h->dist[1] ? 512/h->dist[1] : 0;

    if (h->cur.f->pict_type == AV_PICTURE_TYPE_B) {

        h->sym_factor = h->dist[0] * h->scale_den[1];

        if (FFABS(h->sym_factor) > 32768) {

            av_log(h->avctx, AV_LOG_ERROR, "sym_factor %d too large\n", h->sym_factor);

            return AVERROR_INVALIDDATA;

        }

    } else {

        h->direct_den[0] = h->dist[0] ? 16384 / h->dist[0] : 0;

        h->direct_den[1] = h->dist[1] ? 16384 / h->dist[1] : 0;

    }

    if (h->low_delay)

        get_ue_golomb(&h->gb); //bbv_check_times

    h->progressive   = get_bits1(&h->gb);

    h->pic_structure = 1;

    if (!h->progressive)

        h->pic_structure = get_bits1(&h->gb);

    if (!h->pic_structure && h->stc == PIC_PB_START_CODE)

        skip_bits1(&h->gb);     //advanced_pred_mode_disable

    skip_bits1(&h->gb);        //top_field_first

    skip_bits1(&h->gb);        //repeat_first_field

    h->pic_qp_fixed =

    h->qp_fixed = get_bits1(&h->gb);

    h->qp       = get_bits(&h->gb, 6);

    if (h->cur.f->pict_type == AV_PICTURE_TYPE_I) {

        if (!h->progressive && !h->pic_structure)

            skip_bits1(&h->gb);//what is this?

        skip_bits(&h->gb, 4);   //reserved bits

    } else {

        if (!(h->cur.f->pict_type == AV_PICTURE_TYPE_B && h->pic_structure == 1))

            h->ref_flag        = get_bits1(&h->gb);

        skip_bits(&h->gb, 4);   //reserved bits

        h->skip_mode_flag      = get_bits1(&h->gb);

    }

    h->loop_filter_disable     = get_bits1(&h->gb);

    if (!h->loop_filter_disable && get_bits1(&h->gb)) {

        h->alpha_offset        = get_se_golomb(&h->gb);

        h->beta_offset         = get_se_golomb(&h->gb);

    } else {

        h->alpha_offset = h->beta_offset  = 0;

    }

    if (h->cur.f->pict_type == AV_PICTURE_TYPE_I) {

        do {

            check_for_slice(h);

            decode_mb_i(h, 0);

        } while (ff_cavs_next_mb(h));

    } else if (h->cur.f->pict_type == AV_PICTURE_TYPE_P) {

        do {

            if (check_for_slice(h))

                skip_count = -1;

            if (h->skip_mode_flag && (skip_count < 0))

                skip_count = get_ue_golomb(&h->gb);

            if (h->skip_mode_flag && skip_count--) {

                decode_mb_p(h, P_SKIP);

            } else {

                mb_type = get_ue_golomb(&h->gb) + P_SKIP + h->skip_mode_flag;

                if (mb_type > P_8X8)

                    decode_mb_i(h, mb_type - P_8X8 - 1);

                else

                    decode_mb_p(h, mb_type);

            }

        } while (ff_cavs_next_mb(h));

    } else { /* AV_PICTURE_TYPE_B */

        do {

            if (check_for_slice(h))

                skip_count = -1;

            if (h->skip_mode_flag && (skip_count < 0))

                skip_count = get_ue_golomb(&h->gb);

            if (h->skip_mode_flag && skip_count--) {

                decode_mb_b(h, B_SKIP);

            } else {

                mb_type = get_ue_golomb(&h->gb) + B_SKIP + h->skip_mode_flag;

                if (mb_type > B_8X8)

                    decode_mb_i(h, mb_type - B_8X8 - 1);

                else

                    decode_mb_b(h, mb_type);

            }

        } while (ff_cavs_next_mb(h));

    }

    emms_c();

    if (h->cur.f->pict_type != AV_PICTURE_TYPE_B) {

        av_frame_unref(h->DPB[1].f);

        FFSWAP(AVSFrame, h->cur, h->DPB[1]);

        FFSWAP(AVSFrame, h->DPB[0], h->DPB[1]);

    }

    return 0;

}


static void bmds_set_aio_inflight(BlkMigDevState *bmds, int64_t sector_num,

                             int nb_sectors, int set)

{

    int64_t start, end;

    unsigned long val, idx, bit;

    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;

    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;

    for (; start <= end; start++) {

        idx = start / (sizeof(unsigned long) * 8);

        bit = start % (sizeof(unsigned long) * 8);

        val = bmds->aio_bitmap[idx];

        if (set) {

            val |= 1UL << bit;

        } else {

            val &= ~(1UL << bit);

        }

        bmds->aio_bitmap[idx] = val;

    }

}


static int decode_cell(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                       Plane *plane, Cell *cell, const uint8_t *data_ptr,

                       const uint8_t *last_ptr)

{

    int           x, mv_x, mv_y, mode, vq_index, prim_indx, second_indx;

    int           zoom_fac;

    int           offset, error = 0, swap_quads[2];

    uint8_t       code, *block, *ref_block = 0;

    const vqEntry *delta[2];

    const uint8_t *data_start = data_ptr;

    /* get coding mode and VQ table index from the VQ descriptor byte */

    code     = *data_ptr++;

    mode     = code >> 4;

    vq_index = code & 0xF;

    /* setup output and reference pointers */

    offset = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);

    block  =  plane->pixels[ctx->buf_sel] + offset;

    if (!cell->mv_ptr) {

        /* use previous line as reference for INTRA cells */

        ref_block = block - plane->pitch;

    } else if (mode >= 10) {

        /* for mode 10 and 11 INTER first copy the predicted cell into the current one */

        /* so we don't need to do data copying for each RLE code later */

        copy_cell(ctx, plane, cell);

    } else {

        /* set the pointer to the reference pixels for modes 0-4 INTER */

        mv_y      = cell->mv_ptr[0];

        mv_x      = cell->mv_ptr[1];

        offset   += mv_y * plane->pitch + mv_x;

        ref_block = plane->pixels[ctx->buf_sel ^ 1] + offset;

    /* select VQ tables as follows: */

    /* modes 0 and 3 use only the primary table for all lines in a block */

    /* while modes 1 and 4 switch between primary and secondary tables on alternate lines */

    if (mode == 1 || mode == 4) {

        code        = ctx->alt_quant[vq_index];

        prim_indx   = (code >> 4)  + ctx->cb_offset;

        second_indx = (code & 0xF) + ctx->cb_offset;

    } else {

        vq_index += ctx->cb_offset;

        prim_indx = second_indx = vq_index;

    if (prim_indx >= 24 || second_indx >= 24) {

        av_log(avctx, AV_LOG_ERROR, "Invalid VQ table indexes! Primary: %d, secondary: %d!\n",

               prim_indx, second_indx);

    delta[0] = &vq_tab[second_indx];

    delta[1] = &vq_tab[prim_indx];

    swap_quads[0] = second_indx >= 16;

    swap_quads[1] = prim_indx   >= 16;

    /* requantize the prediction if VQ index of this cell differs from VQ index */

    /* of the predicted cell in order to avoid overflows. */

    if (vq_index >= 8 && ref_block) {

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

            ref_block[x] = requant_tab[vq_index & 7][ref_block[x]];

    error = IV3_NOERR;

    switch (mode) {

    case 0: /*------------------ MODES 0 & 1 (4x4 block processing) --------------------*/

    case 1:

    case 3: /*------------------ MODES 3 & 4 (4x8 block processing) --------------------*/

    case 4:

        if (mode >= 3 && cell->mv_ptr) {

            av_log(avctx, AV_LOG_ERROR, "Attempt to apply Mode 3/4 to an INTER cell!\n");

        zoom_fac = mode >= 3;

        error = decode_cell_data(cell, block, ref_block, plane->pitch, 0, zoom_fac,

                                 mode, delta, swap_quads, &data_ptr, last_ptr);

        break;

    case 10: /*-------------------- MODE 10 (8x8 block processing) ---------------------*/

    case 11: /*----------------- MODE 11 (4x8 INTER block processing) ------------------*/

        if (mode == 10 && !cell->mv_ptr) { /* MODE 10 INTRA processing */

            error = decode_cell_data(cell, block, ref_block, plane->pitch, 1, 1,

                                     mode, delta, swap_quads, &data_ptr, last_ptr);

        } else { /* mode 10 and 11 INTER processing */

            if (mode == 11 && !cell->mv_ptr) {

               av_log(avctx, AV_LOG_ERROR, "Attempt to use Mode 11 for an INTRA cell!\n");

            zoom_fac = mode == 10;

            error = decode_cell_data(cell, block, ref_block, plane->pitch,

                                     zoom_fac, 1, mode, delta, swap_quads,

                                     &data_ptr, last_ptr);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Unsupported coding mode: %d\n", mode);

    }//switch mode

    switch (error) {

    case IV3_BAD_RLE:

        av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE code %X is not allowed at the current line\n",

               mode, data_ptr[-1]);

    case IV3_BAD_DATA:

        av_log(avctx, AV_LOG_ERROR, "Mode %d: invalid VQ data\n", mode);

    case IV3_BAD_COUNTER:

        av_log(avctx, AV_LOG_ERROR, "Mode %d: RLE-FB invalid counter: %d\n", mode, code);

    case IV3_UNSUPPORTED:

        av_log(avctx, AV_LOG_ERROR, "Mode %d: unsupported RLE code: %X\n", mode, data_ptr[-1]);

    case IV3_OUT_OF_DATA:

        av_log(avctx, AV_LOG_ERROR, "Mode %d: attempt to read past end of buffer\n", mode);

    return data_ptr - data_start; /* report number of bytes consumed from the input buffer */


void ff_riff_write_info_tag(AVIOContext *pb, const char *tag, const char *str)

{

    int len = strlen(str);

    if (len > 0) {

        len++;

        ffio_wfourcc(pb, tag);

        avio_wl32(pb, len);

        avio_put_str(pb, str);

        if (len & 1)

            avio_w8(pb, 0);

    }

}


static int mjpegb_decode_frame(AVCodecContext *avctx,

                              void *data, int *got_frame,

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MJpegDecodeContext *s = avctx->priv_data;

    const uint8_t *buf_end, *buf_ptr;

    GetBitContext hgb; /* for the header */

    uint32_t dqt_offs, dht_offs, sof_offs, sos_offs, second_field_offs;

    uint32_t field_size, sod_offs;

    int ret;

    buf_ptr = buf;

    buf_end = buf + buf_size;

    s->got_picture = 0;

read_header:

    /* reset on every SOI */

    s->restart_interval = 0;

    s->restart_count = 0;

    s->mjpb_skiptosod = 0;

    if (buf_end - buf_ptr >= 1 << 28)

        return AVERROR_INVALIDDATA;

    init_get_bits(&hgb, buf_ptr, /*buf_size*/(buf_end - buf_ptr)*8);

    skip_bits(&hgb, 32); /* reserved zeros */

    if (get_bits_long(&hgb, 32) != MKBETAG('m','j','p','g'))

    {

        av_log(avctx, AV_LOG_WARNING, "not mjpeg-b (bad fourcc)\n");

        return AVERROR_INVALIDDATA;

    }

    field_size = get_bits_long(&hgb, 32); /* field size */

    av_log(avctx, AV_LOG_DEBUG, "field size: 0x%x\n", field_size);

    skip_bits(&hgb, 32); /* padded field size */

    second_field_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "second_field_offs is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "second field offs: 0x%x\n", second_field_offs);

    dqt_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "dqt is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "dqt offs: 0x%x\n", dqt_offs);

    if (dqt_offs)

    {

        init_get_bits(&s->gb, buf_ptr+dqt_offs, (buf_end - (buf_ptr+dqt_offs))*8);

        s->start_code = DQT;

        if (ff_mjpeg_decode_dqt(s) < 0 &&

            (avctx->err_recognition & AV_EF_EXPLODE))

          return AVERROR_INVALIDDATA;

    }

    dht_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "dht is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "dht offs: 0x%x\n", dht_offs);

    if (dht_offs)

    {

        init_get_bits(&s->gb, buf_ptr+dht_offs, (buf_end - (buf_ptr+dht_offs))*8);

        s->start_code = DHT;

        ff_mjpeg_decode_dht(s);

    }

    sof_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sof is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sof offs: 0x%x\n", sof_offs);

    if (sof_offs)

    {

        init_get_bits(&s->gb, buf_ptr+sof_offs, (buf_end - (buf_ptr+sof_offs))*8);

        s->start_code = SOF0;

        if (ff_mjpeg_decode_sof(s) < 0)

            return -1;

    }

    sos_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sos is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sos offs: 0x%x\n", sos_offs);

    sod_offs = read_offs(avctx, &hgb, buf_end - buf_ptr, "sof is %d and size is %d\n");

    av_log(avctx, AV_LOG_DEBUG, "sod offs: 0x%x\n", sod_offs);

    if (sos_offs)

    {

        init_get_bits(&s->gb, buf_ptr + sos_offs,

                      8 * FFMIN(field_size, buf_end - buf_ptr - sos_offs));

        s->mjpb_skiptosod = (sod_offs - sos_offs - show_bits(&s->gb, 16));

        s->start_code = SOS;

        if (ff_mjpeg_decode_sos(s, NULL, NULL) < 0 &&

            (avctx->err_recognition & AV_EF_EXPLODE))

          return AVERROR_INVALIDDATA;

    }

    if (s->interlaced) {

        s->bottom_field ^= 1;

        /* if not bottom field, do not output image yet */

        if (s->bottom_field != s->interlace_polarity && second_field_offs)

        {

            buf_ptr = buf + second_field_offs;

            goto read_header;

            }

    }

    //XXX FIXME factorize, this looks very similar to the EOI code

    if(!s->got_picture) {

        av_log(avctx, AV_LOG_WARNING, "no picture\n");

        return buf_size;

    }

    if ((ret = av_frame_ref(data, s->picture_ptr)) < 0)

        return ret;

    *got_frame = 1;

    if (!s->lossless && avctx->debug & FF_DEBUG_QP) {

        av_log(avctx, AV_LOG_DEBUG, "QP: %d\n",

               FFMAX3(s->qscale[0], s->qscale[1], s->qscale[2]));

    }

    return buf_size;

}


void helper_wrpil(CPUSPARCState *env, target_ulong new_pil)

{

#if !defined(CONFIG_USER_ONLY)

    trace_win_helper_wrpil(env->psrpil, (uint32_t)new_pil);

    env->psrpil = new_pil;

    if (cpu_interrupts_enabled(env)) {

        cpu_check_irqs(env);

    }

#endif

}


const char *qdict_get_try_str(const QDict *qdict, const char *key)

{

    QObject *obj;

    obj = qdict_get(qdict, key);

    if (!obj || qobject_type(obj) != QTYPE_QSTRING)

        return NULL;

    return qstring_get_str(qobject_to_qstring(obj));

}


static void tricore_testboard_init(MachineState *machine, int board_id)

{

    TriCoreCPU *cpu;

    CPUTriCoreState *env;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ext_cram = g_new(MemoryRegion, 1);

    MemoryRegion *ext_dram = g_new(MemoryRegion, 1);

    MemoryRegion *int_cram = g_new(MemoryRegion, 1);

    MemoryRegion *int_dram = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_data = g_new(MemoryRegion, 1);

    MemoryRegion *pcp_text = g_new(MemoryRegion, 1);

    if (!machine->cpu_model) {

        machine->cpu_model = "tc1796";

    }

    cpu = cpu_tricore_init(machine->cpu_model);

    if (!cpu) {

        error_report("Unable to find CPU definition");

        exit(1);

    }

    env = &cpu->env;

    memory_region_init_ram(ext_cram, NULL, "powerlink_ext_c.ram", 2*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_cram);

    memory_region_init_ram(ext_dram, NULL, "powerlink_ext_d.ram", 4*1024*1024, &error_abort);

    vmstate_register_ram_global(ext_dram);

    memory_region_init_ram(int_cram, NULL, "powerlink_int_c.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_cram);

    memory_region_init_ram(int_dram, NULL, "powerlink_int_d.ram", 48*1024, &error_abort);

    vmstate_register_ram_global(int_dram);

    memory_region_init_ram(pcp_data, NULL, "powerlink_pcp_data.ram", 16*1024, &error_abort);

    vmstate_register_ram_global(pcp_data);

    memory_region_init_ram(pcp_text, NULL, "powerlink_pcp_text.ram", 32*1024, &error_abort);

    vmstate_register_ram_global(pcp_text);

    memory_region_add_subregion(sysmem, 0x80000000, ext_cram);

    memory_region_add_subregion(sysmem, 0xa1000000, ext_dram);

    memory_region_add_subregion(sysmem, 0xd4000000, int_cram);

    memory_region_add_subregion(sysmem, 0xd0000000, int_dram);

    memory_region_add_subregion(sysmem, 0xf0050000, pcp_data);

    memory_region_add_subregion(sysmem, 0xf0060000, pcp_text);

    tricoretb_binfo.ram_size = machine->ram_size;

    tricoretb_binfo.kernel_filename = machine->kernel_filename;

    if (machine->kernel_filename) {

        tricore_load_kernel(env);

    }

}


static void ahci_write_fis_sdb(AHCIState *s, int port, uint32_t finished)

{

    AHCIPortRegs *pr = &s->dev[port].port_regs;

    IDEState *ide_state;

    uint8_t *sdb_fis;

    if (!s->dev[port].res_fis ||

        !(pr->cmd & PORT_CMD_FIS_RX)) {

        return;

    }

    sdb_fis = &s->dev[port].res_fis[RES_FIS_SDBFIS];

    ide_state = &s->dev[port].port.ifs[0];

    /* clear memory */

    *(uint32_t*)sdb_fis = 0;

    /* write values */

    sdb_fis[0] = ide_state->error;

    sdb_fis[2] = ide_state->status & 0x77;

    s->dev[port].finished |= finished;

    *(uint32_t*)(sdb_fis + 4) = cpu_to_le32(s->dev[port].finished);

    ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_SDB_FIS);

}


int v9fs_set_xattr(FsContext *ctx, const char *path, const char *name,

                   void *value, size_t size, int flags)

{

    XattrOperations *xops = get_xattr_operations(ctx->xops, name);

    if (xops) {

        return xops->setxattr(ctx, path, name, value, size, flags);

    }

    errno = -EOPNOTSUPP;

    return -1;

}


void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)

{

    struct kvm_irq_routing_entry e;

    assert(pin < s->gsi_count);

    e.gsi = irq;

    e.type = KVM_IRQ_ROUTING_IRQCHIP;

    e.flags = 0;

    e.u.irqchip.irqchip = irqchip;

    e.u.irqchip.pin = pin;

    kvm_add_routing_entry(s, &e);

}


static inline void gen_op_evsrwu(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2)

{

    TCGv_i32 t0;

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    t0 = tcg_temp_local_new_i32();

    /* No error here: 6 bits are used */

    tcg_gen_andi_i32(t0, arg2, 0x3F);

    tcg_gen_brcondi_i32(TCG_COND_GE, t0, 32, l1);

    tcg_gen_shr_i32(ret, arg1, t0);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_movi_i32(ret, 0);

    gen_set_label(l2);

    tcg_temp_free_i32(t0);

}


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

                            int *got_picture_ptr, AVPacket *avpkt)

{

    HQXContext *ctx = avctx->priv_data;

    uint8_t *src = avpkt->data;

    uint32_t info_tag;

    int data_start;

    int i, ret;

    if (avpkt->size < 4 + 4) {

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

        return AVERROR_INVALIDDATA;

    }

    info_tag    = AV_RL32(src);

    if (info_tag == MKTAG('I', 'N', 'F', 'O')) {

        int info_offset = AV_RL32(src + 4);

        if (info_offset > UINT32_MAX - 8 || info_offset + 8 > avpkt->size) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid INFO header offset: 0x%08"PRIX32" is too large.\n",

                   info_offset);

            return AVERROR_INVALIDDATA;

        }

        ff_canopus_parse_info_tag(avctx, src + 8, info_offset);

        info_offset += 8;

        src         += info_offset;

    }

    data_start     = src - avpkt->data;

    ctx->data_size = avpkt->size - data_start;

    ctx->src       = src;

    ctx->pic       = data;

    if (ctx->data_size < HQX_HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "Frame too small.\n");

        return AVERROR_INVALIDDATA;

    }

    if (src[0] != 'H' || src[1] != 'Q') {

        av_log(avctx, AV_LOG_ERROR, "Not an HQX frame.\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->interlaced = !(src[2] & 0x80);

    ctx->format     = src[2] & 7;

    ctx->dcb        = (src[3] & 3) + 8;

    ctx->width      = AV_RB16(src + 4);

    ctx->height     = AV_RB16(src + 6);

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

        ctx->slice_off[i] = AV_RB24(src + 8 + i * 3);

    if (ctx->dcb == 8) {

        av_log(avctx, AV_LOG_ERROR, "Invalid DC precision %d.\n", ctx->dcb);

        return AVERROR_INVALIDDATA;

    }

    ret = av_image_check_size(ctx->width, ctx->height, 0, avctx);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Invalid stored dimenstions %dx%d.\n",

               ctx->width, ctx->height);

        return AVERROR_INVALIDDATA;

    }

    avctx->coded_width         = FFALIGN(ctx->width,  16);

    avctx->coded_height        = FFALIGN(ctx->height, 16);

    avctx->width               = ctx->width;

    avctx->height              = ctx->height;

    avctx->bits_per_raw_sample = 10;

    switch (ctx->format) {

    case HQX_422:

        avctx->pix_fmt = AV_PIX_FMT_YUV422P16;

        ctx->decode_func = hqx_decode_422;

        break;

    case HQX_444:

        avctx->pix_fmt = AV_PIX_FMT_YUV444P16;

        ctx->decode_func = hqx_decode_444;

        break;

    case HQX_422A:

        avctx->pix_fmt = AV_PIX_FMT_YUVA422P16;

        ctx->decode_func = hqx_decode_422a;

        break;

    case HQX_444A:

        avctx->pix_fmt = AV_PIX_FMT_YUVA444P16;

        ctx->decode_func = hqx_decode_444a;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Invalid format: %d.\n", ctx->format);

        return AVERROR_INVALIDDATA;

    }

    ret = ff_get_buffer(avctx, ctx->pic, 0);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");

        return ret;

    }

    avctx->execute2(avctx, decode_slice_thread, NULL, NULL, 16);

    ctx->pic->key_frame = 1;

    ctx->pic->pict_type = AV_PICTURE_TYPE_I;

    *got_picture_ptr = 1;

    return avpkt->size;

}


START_TEST(qlist_append_test)

{

    QInt *qi;

    QList *qlist;

    QListEntry *entry;

    qi = qint_from_int(42);

    qlist = qlist_new();

    qlist_append(qlist, qi);

    entry = QTAILQ_FIRST(&qlist->head);

    fail_unless(entry != NULL);

    fail_unless(entry->value == QOBJECT(qi));

    // destroy doesn't exist yet

    QDECREF(qi);

    g_free(entry);

    g_free(qlist);

}


static int parse_chr(DeviceState *dev, Property *prop, const char *str)

{

    CharDriverState **ptr = qdev_get_prop_ptr(dev, prop);

    *ptr = qemu_chr_find(str);

    if (*ptr == NULL)

        return -ENOENT;

    return 0;

}


static unsigned virtio_pci_get_features(void *opaque)

{

    unsigned ret = 0;

    ret |= (1 << VIRTIO_F_NOTIFY_ON_EMPTY);

    ret |= (1 << VIRTIO_RING_F_INDIRECT_DESC);

    ret |= (1 << VIRTIO_F_BAD_FEATURE);

    return ret;

}


target_ulong HELPER(mfspr)(CPUOpenRISCState *env,

                           target_ulong rd, target_ulong ra, uint32_t offset)

{

#ifndef CONFIG_USER_ONLY

    int spr = (ra | offset);

    int idx;

    OpenRISCCPU *cpu = openrisc_env_get_cpu(env);

    switch (spr) {

    case TO_SPR(0, 0): /* VR */

        return env->vr & SPR_VR;

    case TO_SPR(0, 1): /* UPR */

        return env->upr;    /* TT, DM, IM, UP present */

    case TO_SPR(0, 2): /* CPUCFGR */

        return env->cpucfgr;

    case TO_SPR(0, 3): /* DMMUCFGR */

        return env->dmmucfgr;    /* 1Way, 64 entries */

    case TO_SPR(0, 4): /* IMMUCFGR */

        return env->immucfgr;

    case TO_SPR(0, 16): /* NPC */

        return env->npc;

    case TO_SPR(0, 17): /* SR */

        return env->sr;

    case TO_SPR(0, 18): /* PPC */

        return env->ppc;

    case TO_SPR(0, 32): /* EPCR */

        return env->epcr;

    case TO_SPR(0, 48): /* EEAR */

        return env->eear;

    case TO_SPR(0, 64): /* ESR */

        return env->esr;

    case TO_SPR(1, 512) ... TO_SPR(1, 639): /* DTLBW0MR 0-127 */

        idx = spr - TO_SPR(1, 512);

        return env->tlb->dtlb[0][idx].mr;

    case TO_SPR(1, 640) ... TO_SPR(1, 767): /* DTLBW0TR 0-127 */

        idx = spr - TO_SPR(1, 640);

        return env->tlb->dtlb[0][idx].tr;

    case TO_SPR(1, 768) ... TO_SPR(1, 895):   /* DTLBW1MR 0-127 */

    case TO_SPR(1, 896) ... TO_SPR(1, 1023):  /* DTLBW1TR 0-127 */

    case TO_SPR(1, 1024) ... TO_SPR(1, 1151): /* DTLBW2MR 0-127 */

    case TO_SPR(1, 1152) ... TO_SPR(1, 1279): /* DTLBW2TR 0-127 */

    case TO_SPR(1, 1280) ... TO_SPR(1, 1407): /* DTLBW3MR 0-127 */

    case TO_SPR(1, 1408) ... TO_SPR(1, 1535): /* DTLBW3TR 0-127 */

        break;

    case TO_SPR(2, 512) ... TO_SPR(2, 639): /* ITLBW0MR 0-127 */

        idx = spr - TO_SPR(2, 512);

        return env->tlb->itlb[0][idx].mr;

    case TO_SPR(2, 640) ... TO_SPR(2, 767): /* ITLBW0TR 0-127 */

        idx = spr - TO_SPR(2, 640);

        return env->tlb->itlb[0][idx].tr;

    case TO_SPR(2, 768) ... TO_SPR(2, 895):   /* ITLBW1MR 0-127 */

    case TO_SPR(2, 896) ... TO_SPR(2, 1023):  /* ITLBW1TR 0-127 */

    case TO_SPR(2, 1024) ... TO_SPR(2, 1151): /* ITLBW2MR 0-127 */

    case TO_SPR(2, 1152) ... TO_SPR(2, 1279): /* ITLBW2TR 0-127 */

    case TO_SPR(2, 1280) ... TO_SPR(2, 1407): /* ITLBW3MR 0-127 */

    case TO_SPR(2, 1408) ... TO_SPR(2, 1535): /* ITLBW3TR 0-127 */

        break;

    case TO_SPR(9, 0):  /* PICMR */

        return env->picmr;

    case TO_SPR(9, 2):  /* PICSR */

        return env->picsr;

    case TO_SPR(10, 0): /* TTMR */

        return env->ttmr;

    case TO_SPR(10, 1): /* TTCR */

        cpu_openrisc_count_update(cpu);

        return env->ttcr;

    default:

        break;

    }

#endif

/*If we later need to add tracepoints (or debug printfs) for the return

value, it may be useful to structure the code like this:

target_ulong ret = 0;

switch() {

case x:

 ret = y;

 break;

case z:

 ret = 42;

 break;

...

}

later something like trace_spr_read(ret);

return ret;*/

    /* for rd is passed in, if rd unchanged, just keep it back.  */

    return rd;

}


ssize_t virtio_pdu_vunmarshal(V9fsPDU *pdu, size_t offset,

                              const char *fmt, va_list ap)

{

    V9fsState *s = pdu->s;

    V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);

    VirtQueueElement *elem = &v->elems[pdu->idx];

    return v9fs_iov_vunmarshal(elem->out_sg, elem->out_num, offset, 1, fmt, ap);

}


void do_td (int flags)

{

    if (!likely(!(((int64_t)T0 < (int64_t)T1 && (flags & 0x10)) ||

                  ((int64_t)T0 > (int64_t)T1 && (flags & 0x08)) ||

                  ((int64_t)T0 == (int64_t)T1 && (flags & 0x04)) ||

                  ((uint64_t)T0 < (uint64_t)T1 && (flags & 0x02)) ||

                  ((uint64_t)T0 > (uint64_t)T1 && (flags & 0x01)))))

        do_raise_exception_err(EXCP_PROGRAM, EXCP_TRAP);

}


static ssize_t block_crypto_read_func(QCryptoBlock *block,

                                      void *opaque,

                                      size_t offset,

                                      uint8_t *buf,

                                      size_t buflen,

                                      Error **errp)

{

    BlockDriverState *bs = opaque;

    ssize_t ret;

    ret = bdrv_pread(bs->file, offset, buf, buflen);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read encryption header");

        return ret;

    }

    return ret;

}


vnc_display_setup_auth(VncDisplay *vd,

                       bool password,

                       bool sasl,

                       bool websocket,

                       Error **errp)

{

    /*

     * We have a choice of 3 authentication options

     *

     *   1. none

     *   2. vnc

     *   3. sasl

     *

     * The channel can be run in 2 modes

     *

     *   1. clear

     *   2. tls

     *

     * And TLS can use 2 types of credentials

     *

     *   1. anon

     *   2. x509

     *

     * We thus have 9 possible logical combinations

     *

     *   1. clear + none

     *   2. clear + vnc

     *   3. clear + sasl

     *   4. tls + anon + none

     *   5. tls + anon + vnc

     *   6. tls + anon + sasl

     *   7. tls + x509 + none

     *   8. tls + x509 + vnc

     *   9. tls + x509 + sasl

     *

     * These need to be mapped into the VNC auth schemes

     * in an appropriate manner. In regular VNC, all the

     * TLS options get mapped into VNC_AUTH_VENCRYPT

     * sub-auth types.

     *

     * In websockets, the https:// protocol already provides

     * TLS support, so there is no need to make use of the

     * VeNCrypt extension. Furthermore, websockets browser

     * clients could not use VeNCrypt even if they wanted to,

     * as they cannot control when the TLS handshake takes

     * place. Thus there is no option but to rely on https://,

     * meaning combinations 4->6 and 7->9 will be mapped to

     * VNC auth schemes in the same way as combos 1->3.

     *

     * Regardless of fact that we have a different mapping to

     * VNC auth mechs for plain VNC vs websockets VNC, the end

     * result has the same security characteristics.

     */

    if (password) {

        if (vd->tlscreds) {

            vd->auth = VNC_AUTH_VENCRYPT;

            if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 password auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_X509VNC;

            } else if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS password auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_TLSVNC;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vd->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with password auth\n");

            vd->auth = VNC_AUTH_VNC;

            vd->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vd->ws_auth = VNC_AUTH_VNC;

        } else {

            vd->ws_auth = VNC_AUTH_INVALID;

        }

    } else if (sasl) {

        if (vd->tlscreds) {

            vd->auth = VNC_AUTH_VENCRYPT;

            if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_X509SASL;

            } else if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_TLSSASL;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vd->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with SASL auth\n");

            vd->auth = VNC_AUTH_SASL;

            vd->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vd->ws_auth = VNC_AUTH_SASL;

        } else {

            vd->ws_auth = VNC_AUTH_INVALID;

        }

    } else {

        if (vd->tlscreds) {

            vd->auth = VNC_AUTH_VENCRYPT;

            if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 no auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_X509NONE;

            } else if (object_dynamic_cast(OBJECT(vd->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS no auth\n");

                vd->subauth = VNC_AUTH_VENCRYPT_TLSNONE;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vd->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with no auth\n");

            vd->auth = VNC_AUTH_NONE;

            vd->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vd->ws_auth = VNC_AUTH_NONE;

        } else {

            vd->ws_auth = VNC_AUTH_INVALID;

        }

    }

    return 0;

}


static void fill_elf_note_phdr(struct elf_phdr *phdr, int sz, off_t offset)

{

    phdr->p_type = PT_NOTE;

    phdr->p_offset = offset;

    phdr->p_vaddr = 0;

    phdr->p_paddr = 0;

    phdr->p_filesz = sz;

    phdr->p_memsz = 0;

    phdr->p_flags = 0;

    phdr->p_align = 0;

#ifdef BSWAP_NEEDED

    bswap_phdr(phdr);

#endif

}


static av_cold int vaapi_encode_mjpeg_init_internal(AVCodecContext *avctx)

{

    static const VAConfigAttrib default_config_attributes[] = {

        { .type  = VAConfigAttribRTFormat,

          .value = VA_RT_FORMAT_YUV420 },

        { .type  = VAConfigAttribEncPackedHeaders,

          .value = VA_ENC_PACKED_HEADER_SEQUENCE },

    };

    VAAPIEncodeContext       *ctx = avctx->priv_data;

    VAAPIEncodeMJPEGContext *priv = ctx->priv_data;

    int i;

    ctx->va_profile    = VAProfileJPEGBaseline;

    ctx->va_entrypoint = VAEntrypointEncPicture;

    ctx->input_width    = avctx->width;

    ctx->input_height   = avctx->height;

    ctx->aligned_width  = FFALIGN(ctx->input_width,  8);

    ctx->aligned_height = FFALIGN(ctx->input_height, 8);

    for (i = 0; i < FF_ARRAY_ELEMS(default_config_attributes); i++) {

        ctx->config_attributes[ctx->nb_config_attributes++] =

            default_config_attributes[i];

    }

    priv->quality = avctx->global_quality;

    if (priv->quality < 1 || priv->quality > 100) {

        av_log(avctx, AV_LOG_ERROR, "Invalid quality value %d "

               "(must be 1-100).\n", priv->quality);

        return AVERROR(EINVAL);

    }

    vaapi_encode_mjpeg_init_tables(avctx);

    return 0;

}


static gboolean tcp_chr_chan_close(GIOChannel *channel, GIOCondition cond,

                                   void *opaque)

{

    CharDriverState *chr = opaque;

    if (cond != G_IO_HUP) {

        return FALSE;

    }

    /* connection closed */

    tcp_chr_disconnect(chr);

    if (chr->fd_hup_tag) {

        g_source_remove(chr->fd_hup_tag);

        chr->fd_hup_tag = 0;

    }

    return TRUE;

}


static void rtas_ibm_configure_pe(PowerPCCPU *cpu,

                                  sPAPREnvironment *spapr,

                                  uint32_t token, uint32_t nargs,

                                  target_ulong args, uint32_t nret,

                                  target_ulong rets)

{

    sPAPRPHBState *sphb;

    sPAPRPHBClass *spc;

    uint64_t buid;

    int ret;

    if ((nargs != 3) || (nret != 1)) {

        goto param_error_exit;

    }

    buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    sphb = find_phb(spapr, buid);

    if (!sphb) {

        goto param_error_exit;

    }

    spc = SPAPR_PCI_HOST_BRIDGE_GET_CLASS(sphb);

    if (!spc->eeh_configure) {

        goto param_error_exit;

    }

    ret = spc->eeh_configure(sphb);

    rtas_st(rets, 0, ret);

    return;

param_error_exit:

    rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

}


static void sigp_cpu_start(void *arg)

{

    CPUState *cs = arg;

    S390CPU *cpu = S390_CPU(cs);

    s390_cpu_set_state(CPU_STATE_OPERATING, cpu);

    DPRINTF("DONE: KVM cpu start: %p\n", &cpu->env);

}


static int dca_subsubframe(DCAContext *s, int base_channel, int block_index)

{

    int k, l;

    int subsubframe = s->current_subsubframe;

    const float *quant_step_table;

    /* FIXME */

    float (*subband_samples)[DCA_SUBBANDS][8] = s->subband_samples[block_index];

    LOCAL_ALIGNED_16(int32_t, block, [8 * DCA_SUBBANDS]);

    /*

     * Audio data

     */

    /* Select quantization step size table */

    if (s->bit_rate_index == 0x1f)

        quant_step_table = lossless_quant_d;

    else

        quant_step_table = lossy_quant_d;

    for (k = base_channel; k < s->prim_channels; k++) {

        float rscale[DCA_SUBBANDS];

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

            return AVERROR_INVALIDDATA;

        for (l = 0; l < s->vq_start_subband[k]; l++) {

            int m;

            /* Select the mid-tread linear quantizer */

            int abits = s->bitalloc[k][l];

            float quant_step_size = quant_step_table[abits];

            /*

             * Determine quantization index code book and its type

             */

            /* Select quantization index code book */

            int sel = s->quant_index_huffman[k][abits];

            /*

             * Extract bits from the bit stream

             */

            if (!abits) {

                rscale[l] = 0;

                memset(block + 8 * l, 0, 8 * sizeof(block[0]));

            } else {

                /* Deal with transients */

                int sfi = s->transition_mode[k][l] && subsubframe >= s->transition_mode[k][l];

                rscale[l] = quant_step_size * s->scale_factor[k][l][sfi] *

                               s->scalefactor_adj[k][sel];

                if (abits >= 11 || !dca_smpl_bitalloc[abits].vlc[sel].table) {

                    if (abits <= 7) {

                        /* Block code */

                        int block_code1, block_code2, size, levels, err;

                        size   = abits_sizes[abits - 1];

                        levels = abits_levels[abits - 1];

                        block_code1 = get_bits(&s->gb, size);

                        block_code2 = get_bits(&s->gb, size);

                        err = decode_blockcodes(block_code1, block_code2,

                                                levels, block + 8 * l);

                        if (err) {

                            av_log(s->avctx, AV_LOG_ERROR,

                                   "ERROR: block code look-up failed\n");

                            return AVERROR_INVALIDDATA;

                        }

                    } else {

                        /* no coding */

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

                            block[8 * l + m] = get_sbits(&s->gb, abits - 3);

                    }

                } else {

                    /* Huffman coded */

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

                        block[8 * l + m] = get_bitalloc(&s->gb,

                                                &dca_smpl_bitalloc[abits], sel);

                }

            }

        }

        s->fmt_conv.int32_to_float_fmul_array8(&s->fmt_conv, subband_samples[k][0],

                                               block, rscale, 8 * s->vq_start_subband[k]);

        for (l = 0; l < s->vq_start_subband[k]; l++) {

            int m;

            /*

             * Inverse ADPCM if in prediction mode

             */

            if (s->prediction_mode[k][l]) {

                int n;

                if (s->predictor_history)

                    subband_samples[k][l][0] += (adpcm_vb[s->prediction_vq[k][l]][0] *

                                                 s->subband_samples_hist[k][l][3] +

                                                 adpcm_vb[s->prediction_vq[k][l]][1] *

                                                 s->subband_samples_hist[k][l][2] +

                                                 adpcm_vb[s->prediction_vq[k][l]][2] *

                                                 s->subband_samples_hist[k][l][1] +

                                                 adpcm_vb[s->prediction_vq[k][l]][3] *

                                                 s->subband_samples_hist[k][l][0]) *

                                                (1.0f / 8192);

                for (m = 1; m < 8; m++) {

                    float sum = adpcm_vb[s->prediction_vq[k][l]][0] *

                                subband_samples[k][l][m - 1];

                    for (n = 2; n <= 4; n++)

                        if (m >= n)

                            sum += adpcm_vb[s->prediction_vq[k][l]][n - 1] *

                                   subband_samples[k][l][m - n];

                        else if (s->predictor_history)

                            sum += adpcm_vb[s->prediction_vq[k][l]][n - 1] *

                                   s->subband_samples_hist[k][l][m - n + 4];

                    subband_samples[k][l][m] += sum * 1.0f / 8192;

                }

            }

        }

        /*

         * Decode VQ encoded high frequencies

         */

        for (l = s->vq_start_subband[k]; l < s->subband_activity[k]; l++) {

            /* 1 vector -> 32 samples but we only need the 8 samples

             * for this subsubframe. */

            int hfvq = s->high_freq_vq[k][l];

            if (!s->debug_flag & 0x01) {

                av_log(s->avctx, AV_LOG_DEBUG,

                       "Stream with high frequencies VQ coding\n");

                s->debug_flag |= 0x01;

            }

            int8x8_fmul_int32(&s->dcadsp, subband_samples[k][l],

                              &high_freq_vq[hfvq][subsubframe * 8],

                              s->scale_factor[k][l][0]);

        }

    }

    /* Check for DSYNC after subsubframe */

    if (s->aspf || subsubframe == s->subsubframes[s->current_subframe] - 1) {

        if (0xFFFF == get_bits(&s->gb, 16)) {   /* 0xFFFF */

#ifdef TRACE

            av_log(s->avctx, AV_LOG_DEBUG, "Got subframe DSYNC\n");

#endif

        } else {

            av_log(s->avctx, AV_LOG_ERROR, "Didn't get subframe DSYNC\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* Backup predictor history for adpcm */

    for (k = base_channel; k < s->prim_channels; k++)

        for (l = 0; l < s->vq_start_subband[k]; l++)

            AV_COPY128(s->subband_samples_hist[k][l], &subband_samples[k][l][4]);

    return 0;

}


int ff_mpeg_update_thread_context(AVCodecContext *dst,

                                  const AVCodecContext *src)

{

    int i;

    MpegEncContext *s = dst->priv_data, *s1 = src->priv_data;

    if (dst == src)

        return 0;

    // FIXME can parameters change on I-frames?

    // in that case dst may need a reinit

    if (!s->context_initialized) {

        memcpy(s, s1, sizeof(MpegEncContext));

        s->avctx                 = dst;

        s->bitstream_buffer      = NULL;

        s->bitstream_buffer_size = s->allocated_bitstream_buffer_size = 0;

        if (s1->context_initialized){

            s->picture_range_start  += MAX_PICTURE_COUNT;

            s->picture_range_end    += MAX_PICTURE_COUNT;

            ff_MPV_common_init(s);

        }

    }

    if (s->height != s1->height || s->width != s1->width || s->context_reinit) {

        int err;

        s->context_reinit = 0;

        s->height = s1->height;

        s->width  = s1->width;

        if ((err = ff_MPV_common_frame_size_change(s)) < 0)

            return err;

    }

    s->avctx->coded_height  = s1->avctx->coded_height;

    s->avctx->coded_width   = s1->avctx->coded_width;

    s->avctx->width         = s1->avctx->width;

    s->avctx->height        = s1->avctx->height;

    s->coded_picture_number = s1->coded_picture_number;

    s->picture_number       = s1->picture_number;

    s->input_picture_number = s1->input_picture_number;

    memcpy(s->picture, s1->picture, s1->picture_count * sizeof(Picture));

    memcpy(&s->last_picture, &s1->last_picture,

           (char *) &s1->last_picture_ptr - (char *) &s1->last_picture);

    // reset s->picture[].f.extended_data to s->picture[].f.data

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

        s->picture[i].f.extended_data = s->picture[i].f.data;

    s->last_picture_ptr    = REBASE_PICTURE(s1->last_picture_ptr,    s, s1);

    s->current_picture_ptr = REBASE_PICTURE(s1->current_picture_ptr, s, s1);

    s->next_picture_ptr    = REBASE_PICTURE(s1->next_picture_ptr,    s, s1);

    // Error/bug resilience

    s->next_p_frame_damaged = s1->next_p_frame_damaged;

    s->workaround_bugs      = s1->workaround_bugs;

    s->padding_bug_score    = s1->padding_bug_score;

    // MPEG4 timing info

    memcpy(&s->time_increment_bits, &s1->time_increment_bits,

           (char *) &s1->shape - (char *) &s1->time_increment_bits);

    // B-frame info

    s->max_b_frames = s1->max_b_frames;

    s->low_delay    = s1->low_delay;

    s->dropable     = s1->dropable;

    // DivX handling (doesn't work)

    s->divx_packed  = s1->divx_packed;

    if (s1->bitstream_buffer) {

        if (s1->bitstream_buffer_size +

            FF_INPUT_BUFFER_PADDING_SIZE > s->allocated_bitstream_buffer_size)

            av_fast_malloc(&s->bitstream_buffer,

                           &s->allocated_bitstream_buffer_size,

                           s1->allocated_bitstream_buffer_size);

            s->bitstream_buffer_size = s1->bitstream_buffer_size;

        memcpy(s->bitstream_buffer, s1->bitstream_buffer,

               s1->bitstream_buffer_size);

        memset(s->bitstream_buffer + s->bitstream_buffer_size, 0,

               FF_INPUT_BUFFER_PADDING_SIZE);

    }

    // MPEG2/interlacing info

    memcpy(&s->progressive_sequence, &s1->progressive_sequence,

           (char *) &s1->rtp_mode - (char *) &s1->progressive_sequence);

    if (!s1->first_field) {

        s->last_pict_type = s1->pict_type;

        if (s1->current_picture_ptr)

            s->last_lambda_for[s1->pict_type] = s1->current_picture_ptr->f.quality;

        if (s1->pict_type != AV_PICTURE_TYPE_B) {

            s->last_non_b_pict_type = s1->pict_type;

        }

    }

    return 0;

}


static int h261_probe(AVProbeData *p)

{

    int code;

    const uint8_t *d;

    if (p->buf_size < 6)

        return 0;

    d = p->buf;

    code = (d[0] << 12) | (d[1] << 4) | (d[2] >> 4);

    if (code == 0x10) {

        return 50;

    }

    return 0;

}


static void netfilter_finalize(Object *obj)

{

    NetFilterState *nf = NETFILTER(obj);

    NetFilterClass *nfc = NETFILTER_GET_CLASS(obj);

    if (nfc->cleanup) {

        nfc->cleanup(nf);

    }

    if (nf->netdev && !QTAILQ_EMPTY(&nf->netdev->filters) &&

        nf->next.tqe_prev) {

        QTAILQ_REMOVE(&nf->netdev->filters, nf, next);

    }

    g_free(nf->netdev_id);

}


static void ne2000_cleanup(NetClientState *nc)

{

    NE2000State *s = qemu_get_nic_opaque(nc);

    s->nic = NULL;

}


static void sys_write(void *opaque, hwaddr addr,

                      uint64_t value, unsigned size)

{

    LM32SysState *s = opaque;

    char *testname;

    trace_lm32_sys_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_CTRL:

        qemu_system_shutdown_request();

        break;

    case R_PASSFAIL:

        s->regs[addr] = value;

        testname = (char *)s->testname;

        qemu_log("TC  %-16s %s\n", testname, (value) ? "FAILED" : "OK");

        break;

    case R_TESTNAME:

        s->regs[addr] = value;

        copy_testname(s);

        break;

    default:

        error_report("lm32_sys: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


static DeviceState *qbus_find_dev(BusState *bus, char *elem)

{

    DeviceState *dev;

    /*

     * try to match in order:

     *   (1) instance id, if present

     *   (2) driver name

     *   (3) driver alias, if present

     */

    LIST_FOREACH(dev, &bus->children, sibling) {

        if (dev->id  &&  strcmp(dev->id, elem) == 0) {

            return dev;

        }

    }

    LIST_FOREACH(dev, &bus->children, sibling) {

        if (strcmp(dev->info->name, elem) == 0) {

            return dev;

        }

    }

    LIST_FOREACH(dev, &bus->children, sibling) {

        if (dev->info->alias && strcmp(dev->info->alias, elem) == 0) {

            return dev;

        }

    }

    return NULL;

}


void scsi_req_cancel_async(SCSIRequest *req, Notifier *notifier)

{

    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);

    if (notifier) {

        notifier_list_add(&req->cancel_notifiers, notifier);

    }

    if (req->io_canceled) {

        return;

    }

    scsi_req_ref(req);

    scsi_req_dequeue(req);

    req->io_canceled = true;

    if (req->aiocb) {

        bdrv_aio_cancel_async(req->aiocb);

    }

}


static inline void temp_save(TCGContext *s, TCGTemp *ts,

                             TCGRegSet allocated_regs)

{

#ifdef USE_LIVENESS_ANALYSIS

    /* ??? Liveness does not yet incorporate indirect bases.  */

    if (!ts->indirect_base) {

        /* The liveness analysis already ensures that globals are back

           in memory. Keep an assert for safety. */

        tcg_debug_assert(ts->val_type == TEMP_VAL_MEM || ts->fixed_reg);

        return;

    }

#endif

    temp_sync(s, ts, allocated_regs);

    temp_dead(s, ts);

}


static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    if (c->fc->nb_streams < 1)

        return 0;

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

    ff_get_wav_header(pb, st->codec, atom.size);

    return 0;

}


static void register_multipage(AddressSpaceDispatch *d, MemoryRegionSection *section)

{

    target_phys_addr_t start_addr = section->offset_within_address_space;

    ram_addr_t size = section->size;

    target_phys_addr_t addr;

    uint16_t section_index = phys_section_add(section);

    assert(size);

    addr = start_addr;

    phys_page_set(d, addr >> TARGET_PAGE_BITS, size >> TARGET_PAGE_BITS,

                  section_index);

}


static int IRQ_get_next(OpenPICState *opp, IRQQueue *q)

{

    if (q->next == -1) {

        /* XXX: optimize */

        IRQ_check(opp, q);

    }

    return q->next;

}


static int enable_write_target(BDRVVVFATState *s)

{

    BlockDriver *bdrv_qcow;

    QEMUOptionParameter *options;

    Error *local_err = NULL;

    int ret;

    int size = sector2cluster(s, s->sector_count);

    s->used_clusters = calloc(size, 1);

    array_init(&(s->commits), sizeof(commit_t));

    s->qcow_filename = g_malloc(1024);

    ret = get_tmp_filename(s->qcow_filename, 1024);

    if (ret < 0) {

        goto err;

    }

    bdrv_qcow = bdrv_find_format("qcow");

    options = parse_option_parameters("", bdrv_qcow->create_options, NULL);

    set_option_parameter_int(options, BLOCK_OPT_SIZE, s->sector_count * 512);

    set_option_parameter(options, BLOCK_OPT_BACKING_FILE, "fat:");

    ret = bdrv_create(bdrv_qcow, s->qcow_filename, options, &local_err);

    if (ret < 0) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto err;

    }

    s->qcow = NULL;

    ret = bdrv_open(&s->qcow, s->qcow_filename, NULL, NULL,

            BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, bdrv_qcow,

            &local_err);

    if (ret < 0) {

        qerror_report_err(local_err);

        error_free(local_err);

        goto err;

    }

#ifndef _WIN32

    unlink(s->qcow_filename);

#endif

    s->bs->backing_hd = bdrv_new("");

    s->bs->backing_hd->drv = &vvfat_write_target;

    s->bs->backing_hd->opaque = g_malloc(sizeof(void*));

    *(void**)s->bs->backing_hd->opaque = s;

    return 0;

err:

    g_free(s->qcow_filename);

    s->qcow_filename = NULL;

    return ret;

}


static void dump_json_image_info_list(ImageInfoList *list)

{

    QString *str;

    QmpOutputVisitor *ov = qmp_output_visitor_new();

    QObject *obj;

    visit_type_ImageInfoList(qmp_output_get_visitor(ov), NULL, &list,

                             &error_abort);

    obj = qmp_output_get_qobject(ov);

    str = qobject_to_json_pretty(obj);

    assert(str != NULL);

    printf("%s\n", qstring_get_str(str));

    qobject_decref(obj);

    qmp_output_visitor_cleanup(ov);

    QDECREF(str);

}


static int get_segment32(CPUPPCState *env, struct mmu_ctx_hash32 *ctx,

                         target_ulong eaddr, int rw, int type)

{

    hwaddr hash;

    target_ulong vsid;

    int ds, pr, target_page_bits;

    int ret, ret2;

    target_ulong sr, pgidx;

    pr = msr_pr;

    ctx->eaddr = eaddr;

    sr = env->sr[eaddr >> 28];

    ctx->key = (((sr & SR32_KP) && (pr != 0)) ||

                ((sr & SR32_KS) && (pr == 0))) ? 1 : 0;

    ds = !!(sr & SR32_T);

    ctx->nx = !!(sr & SR32_NX);

    vsid = sr & SR32_VSID;

    target_page_bits = TARGET_PAGE_BITS;

    LOG_MMU("Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx " nip="

            TARGET_FMT_lx " lr=" TARGET_FMT_lx

            " ir=%d dr=%d pr=%d %d t=%d\n",

            eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,

            (int)msr_dr, pr != 0 ? 1 : 0, rw, type);

    pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;

    hash = vsid ^ pgidx;

    ctx->ptem = (vsid << 7) | (pgidx >> 10);

    LOG_MMU("pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",

            ctx->key, ds, ctx->nx, vsid);

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || ctx->nx == 0) {

            /* Page address translation */

            LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx

                    " hash " TARGET_FMT_plx "\n",

                    env->htab_base, env->htab_mask, hash);

            ctx->hash[0] = hash;

            ctx->hash[1] = ~hash;

            /* Initialize real address with an invalid value */

            ctx->raddr = (hwaddr)-1ULL;

            LOG_MMU("0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                    " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx

                    " hash=" TARGET_FMT_plx "\n",

                    env->htab_base, env->htab_mask, vsid, ctx->ptem,

                    ctx->hash[0]);

            /* Primary table lookup */

            ret = find_pte32(env, ctx, 0, rw, type, target_page_bits);

            if (ret < 0) {

                /* Secondary table lookup */

                LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                        " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx

                        " hash=" TARGET_FMT_plx "\n", env->htab_base,

                        env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);

                ret2 = find_pte32(env, ctx, 1, rw, type,

                                  target_page_bits);

                if (ret2 != -1) {

                    ret = ret2;

                }

            }

#if defined(DUMP_PAGE_TABLES)

            if (qemu_log_enabled()) {

                hwaddr curaddr;

                uint32_t a0, a1, a2, a3;

                qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx

                         "\n", sdr, mask + 0x80);

                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);

                     curaddr += 16) {

                    a0 = ldl_phys(curaddr);

                    a1 = ldl_phys(curaddr + 4);

                    a2 = ldl_phys(curaddr + 8);

                    a3 = ldl_phys(curaddr + 12);

                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {

                        qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",

                                 curaddr, a0, a1, a2, a3);

                    }

                }

            }

#endif

        } else {

            LOG_MMU("No access allowed\n");

            ret = -3;

        }

    } else {

        target_ulong sr;

        LOG_MMU("direct store...\n");

        /* Direct-store segment : absolutely *BUGGY* for now */

        /* Direct-store implies a 32-bit MMU.

         * Check the Segment Register's bus unit ID (BUID).

         */

        sr = env->sr[eaddr >> 28];

        if ((sr & 0x1FF00000) >> 20 == 0x07f) {

            /* Memory-forced I/O controller interface access */

            /* If T=1 and BUID=x'07F', the 601 performs a memory access

             * to SR[28-31] LA[4-31], bypassing all protection mechanisms.

             */

            ctx->raddr = ((sr & 0xF) << 28) | (eaddr & 0x0FFFFFFF);

            ctx->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

            return 0;

        }

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

            /* No code fetch is allowed in direct-store areas */

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            qemu_log("ERROR: instruction should not need "

                        "address translation\n");

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static int dmg_read_mish_block(BDRVDMGState *s, DmgHeaderState *ds,

                               uint8_t *buffer, uint32_t count)

{

    uint32_t type, i;

    int ret;

    size_t new_size;

    uint32_t chunk_count;

    int64_t offset = 0;

    uint64_t data_offset;

    uint64_t in_offset = ds->data_fork_offset;

    uint64_t out_offset;

    type = buff_read_uint32(buffer, offset);

    /* skip data that is not a valid MISH block (invalid magic or too small) */

    if (type != 0x6d697368 || count < 244) {

        /* assume success for now */

        return 0;

    }

    /* chunk offsets are relative to this sector number */

    out_offset = buff_read_uint64(buffer, offset + 8);

    /* location in data fork for (compressed) blob (in bytes) */

    data_offset = buff_read_uint64(buffer, offset + 0x18);

    in_offset += data_offset;

    /* move to begin of chunk entries */

    offset += 204;

    chunk_count = (count - 204) / 40;

    new_size = sizeof(uint64_t) * (s->n_chunks + chunk_count);

    s->types = g_realloc(s->types, new_size / 2);

    s->offsets = g_realloc(s->offsets, new_size);

    s->lengths = g_realloc(s->lengths, new_size);

    s->sectors = g_realloc(s->sectors, new_size);

    s->sectorcounts = g_realloc(s->sectorcounts, new_size);

    for (i = s->n_chunks; i < s->n_chunks + chunk_count; i++) {

        s->types[i] = buff_read_uint32(buffer, offset);

        offset += 4;

        if (s->types[i] != 0x80000005 && s->types[i] != 1 &&

            s->types[i] != 2) {

            chunk_count--;

            i--;

            offset += 36;

            continue;

        }

        offset += 4;

        s->sectors[i] = buff_read_uint64(buffer, offset);

        s->sectors[i] += out_offset;

        offset += 8;

        s->sectorcounts[i] = buff_read_uint64(buffer, offset);

        offset += 8;

        if (s->sectorcounts[i] > DMG_SECTORCOUNTS_MAX) {

            error_report("sector count %" PRIu64 " for chunk %" PRIu32

                         " is larger than max (%u)",

                         s->sectorcounts[i], i, DMG_SECTORCOUNTS_MAX);

            ret = -EINVAL;

            goto fail;

        }

        s->offsets[i] = buff_read_uint64(buffer, offset);

        s->offsets[i] += in_offset;

        offset += 8;

        s->lengths[i] = buff_read_uint64(buffer, offset);

        offset += 8;

        if (s->lengths[i] > DMG_LENGTHS_MAX) {

            error_report("length %" PRIu64 " for chunk %" PRIu32

                         " is larger than max (%u)",

                         s->lengths[i], i, DMG_LENGTHS_MAX);

            ret = -EINVAL;

            goto fail;

        }

        update_max_chunk_size(s, i, &ds->max_compressed_size,

                              &ds->max_sectors_per_chunk);

    }

    s->n_chunks += chunk_count;

    return 0;

fail:

    return ret;

}


static always_inline void gen_qemu_ldf (TCGv t0, TCGv t1, int flags)

{

    TCGv tmp = tcg_temp_new(TCG_TYPE_I32);

    tcg_gen_qemu_ld32u(tmp, t1, flags);

    tcg_gen_helper_1_1(helper_memory_to_f, t0, tmp);

    tcg_temp_free(tmp);

}


static int local_chmod(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp)

{

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    if (fs_ctx->fs_sm == SM_MAPPED) {

        return local_set_xattr(rpath(fs_ctx, path, buffer), credp);

    } else if ((fs_ctx->fs_sm == SM_PASSTHROUGH) ||

               (fs_ctx->fs_sm == SM_NONE)) {

        return chmod(rpath(fs_ctx, path, buffer), credp->fc_mode);

    }

    return -1;

}


static inline PageDesc *page_find(target_ulong index)

{

    PageDesc *p;

    p = l1_map[index >> L2_BITS];

    if (!p)

        return 0;

    return p + (index & (L2_SIZE - 1));

}


static int pcm_bluray_parse_header(AVCodecContext *avctx,

                                   const uint8_t *header)

{

    static const uint8_t bits_per_samples[4] = { 0, 16, 20, 24 };

    static const uint32_t channel_layouts[16] = {

        0, AV_CH_LAYOUT_MONO, 0, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_SURROUND,

        AV_CH_LAYOUT_2_1, AV_CH_LAYOUT_4POINT0, AV_CH_LAYOUT_2_2, AV_CH_LAYOUT_5POINT0,

        AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_7POINT0, AV_CH_LAYOUT_7POINT1, 0, 0, 0, 0

    };

    static const uint8_t channels[16] = {

        0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8, 0, 0, 0, 0

    };

    uint8_t channel_layout = header[2] >> 4;

    if (avctx->debug & FF_DEBUG_PICT_INFO)

        av_dlog(avctx, "pcm_bluray_parse_header: header = %02x%02x%02x%02x\n",

                header[0], header[1], header[2], header[3]);

    /* get the sample depth and derive the sample format from it */

    avctx->bits_per_coded_sample = bits_per_samples[header[3] >> 6];

    if (!avctx->bits_per_coded_sample) {

        av_log(avctx, AV_LOG_ERROR, "unsupported sample depth (0)\n");

        return -1;

    }

    avctx->sample_fmt = avctx->bits_per_coded_sample == 16 ? AV_SAMPLE_FMT_S16 :

                                                             AV_SAMPLE_FMT_S32;

    if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)

        avctx->bits_per_raw_sample = avctx->bits_per_coded_sample;

    /* get the sample rate. Not all values are known or exist. */

    switch (header[2] & 0x0f) {

    case 1:

        avctx->sample_rate = 48000;

        break;

    case 4:

        avctx->sample_rate = 96000;

        break;

    case 5:

        avctx->sample_rate = 192000;

        break;

    default:

        avctx->sample_rate = 0;

        av_log(avctx, AV_LOG_ERROR, "unsupported sample rate (%d)\n",

               header[2] & 0x0f);

        return -1;

    }

    /*

     * get the channel number (and mapping). Not all values are known or exist.

     * It must be noted that the number of channels in the MPEG stream can

     * differ from the actual meaningful number, e.g. mono audio still has two

     * channels, one being empty.

     */

    avctx->channel_layout  = channel_layouts[channel_layout];

    avctx->channels        =        channels[channel_layout];

    if (!avctx->channels) {

        av_log(avctx, AV_LOG_ERROR, "unsupported channel configuration (%d)\n",

               channel_layout);

        return -1;

    }

    avctx->bit_rate = avctx->channels * avctx->sample_rate *

                      avctx->bits_per_coded_sample;

    if (avctx->debug & FF_DEBUG_PICT_INFO)

        av_dlog(avctx,

                "pcm_bluray_parse_header: %d channels, %d bits per sample, %d kHz, %d kbit\n",

                avctx->channels, avctx->bits_per_coded_sample,

                avctx->sample_rate, avctx->bit_rate);

    return 0;

}


static int protocol_client_auth_sasl_mechname_len(VncState *vs, uint8_t *data, size_t len)

{

    uint32_t mechlen = read_u32(data, 0);

    VNC_DEBUG("Got client mechname len %d\n", mechlen);

    if (mechlen > 100) {

        VNC_DEBUG("Too long SASL mechname data %d\n", mechlen);

        vnc_client_error(vs);

        return -1;

    }

    if (mechlen < 1) {

        VNC_DEBUG("Too short SASL mechname %d\n", mechlen);

        vnc_client_error(vs);

        return -1;

    }

    vnc_read_when(vs, protocol_client_auth_sasl_mechname,mechlen);

    return 0;

}


static inline int ultrasparc_tag_match(SparcTLBEntry *tlb,

                                       uint64_t address, uint64_t context,

                                       target_phys_addr_t *physical,

                                       int is_nucleus)

{

    uint64_t mask;

    switch ((tlb->tte >> 61) & 3) {

    default:

    case 0x0: // 8k

        mask = 0xffffffffffffe000ULL;

        break;

    case 0x1: // 64k

        mask = 0xffffffffffff0000ULL;

        break;

    case 0x2: // 512k

        mask = 0xfffffffffff80000ULL;

        break;

    case 0x3: // 4M

        mask = 0xffffffffffc00000ULL;

        break;

    }

    // valid, context match, virtual address match?

    if (TTE_IS_VALID(tlb->tte) &&

        ((is_nucleus && compare_masked(0, tlb->tag, 0x1fff))

         || TTE_IS_GLOBAL(tlb->tte) || compare_masked(context, tlb->tag, 0x1fff))

        && compare_masked(address, tlb->tag, mask))

    {

        // decode physical address

        *physical = ((tlb->tte & mask) | (address & ~mask)) & 0x1ffffffe000ULL;

        return 1;

    }

    return 0;

}


int ff_dxva2_commit_buffer(AVCodecContext *avctx,

                           AVDXVAContext *ctx,

                           DECODER_BUFFER_DESC *dsc,

                           unsigned type, const void *data, unsigned size,

                           unsigned mb_count)

{

    void     *dxva_data;

    unsigned dxva_size;

    int      result;

    HRESULT hr;

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)

        hr = ID3D11VideoContext_GetDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context,

                                                 D3D11VA_CONTEXT(ctx)->decoder,

                                                 type,

                                                 &dxva_size, &dxva_data);

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)

        hr = IDirectXVideoDecoder_GetBuffer(DXVA2_CONTEXT(ctx)->decoder, type,

                                            &dxva_data, &dxva_size);

#endif

    if (FAILED(hr)) {

        av_log(avctx, AV_LOG_ERROR, "Failed to get a buffer for %u: 0x%lx\n",

               type, hr);

        return -1;

    }

    if (size <= dxva_size) {

        memcpy(dxva_data, data, size);

#if CONFIG_D3D11VA

        if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD) {

            D3D11_VIDEO_DECODER_BUFFER_DESC *dsc11 = dsc;

            memset(dsc11, 0, sizeof(*dsc11));

            dsc11->BufferType           = type;

            dsc11->DataSize             = size;

            dsc11->NumMBsInBuffer       = mb_count;

        }

#endif

#if CONFIG_DXVA2

        if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD) {

            DXVA2_DecodeBufferDesc *dsc2 = dsc;

            memset(dsc2, 0, sizeof(*dsc2));

            dsc2->CompressedBufferType = type;

            dsc2->DataSize             = size;

            dsc2->NumMBsInBuffer       = mb_count;

        }

#endif

        result = 0;

    } else {

        av_log(avctx, AV_LOG_ERROR, "Buffer for type %u was too small\n", type);

        result = -1;

    }

#if CONFIG_D3D11VA

    if (avctx->pix_fmt == AV_PIX_FMT_D3D11VA_VLD)

        hr = ID3D11VideoContext_ReleaseDecoderBuffer(D3D11VA_CONTEXT(ctx)->video_context, D3D11VA_CONTEXT(ctx)->decoder, type);

#endif

#if CONFIG_DXVA2

    if (avctx->pix_fmt == AV_PIX_FMT_DXVA2_VLD)

        hr = IDirectXVideoDecoder_ReleaseBuffer(DXVA2_CONTEXT(ctx)->decoder, type);

#endif

    if (FAILED(hr)) {

        av_log(avctx, AV_LOG_ERROR,

               "Failed to release buffer type %u: 0x%lx\n",

               type, hr);

        result = -1;

    }

    return result;

}


static void new_video_stream(AVFormatContext *oc, int file_idx)

{

    AVStream *st;

    AVOutputStream *ost;

    AVCodecContext *video_enc;

    enum CodecID codec_id;

    AVCodec *codec= NULL;

    st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);

    if (!st) {

        fprintf(stderr, "Could not alloc stream\n");

        ffmpeg_exit(1);

    }

    ost = new_output_stream(oc, file_idx);

    output_codecs = grow_array(output_codecs, sizeof(*output_codecs), &nb_output_codecs, nb_output_codecs + 1);

    if(!video_stream_copy){

        if (video_codec_name) {

            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,

                                         avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);

            codec = avcodec_find_encoder_by_name(video_codec_name);

            output_codecs[nb_output_codecs-1] = codec;

        } else {

            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);

            codec = avcodec_find_encoder(codec_id);

        }

    }

    avcodec_get_context_defaults3(st->codec, codec);

    ost->bitstream_filters = video_bitstream_filters;

    video_bitstream_filters= NULL;

    avcodec_thread_init(st->codec, thread_count);

    video_enc = st->codec;

    if(video_codec_tag)

        video_enc->codec_tag= video_codec_tag;

    if(   (video_global_header&1)

       || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){

        video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;

    }

    if(video_global_header&2){

        video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;

        avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags2|= CODEC_FLAG2_LOCAL_HEADER;

    }

    if (video_stream_copy) {

        st->stream_copy = 1;

        video_enc->codec_type = AVMEDIA_TYPE_VIDEO;

        video_enc->sample_aspect_ratio =

        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);

    } else {

        const char *p;

        int i;

        AVRational fps= frame_rate.num ? frame_rate : (AVRational){25,1};

        video_enc->codec_id = codec_id;

        set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);

        if (codec && codec->supported_framerates && !force_fps)

            fps = codec->supported_framerates[av_find_nearest_q_idx(fps, codec->supported_framerates)];

        video_enc->time_base.den = fps.num;

        video_enc->time_base.num = fps.den;

        video_enc->width = frame_width;

        video_enc->height = frame_height;

        video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);

        video_enc->pix_fmt = frame_pix_fmt;

        st->sample_aspect_ratio = video_enc->sample_aspect_ratio;

        choose_pixel_fmt(st, codec);

        if (intra_only)

            video_enc->gop_size = 0;

        if (video_qscale || same_quality) {

            video_enc->flags |= CODEC_FLAG_QSCALE;

            video_enc->global_quality=

                st->quality = FF_QP2LAMBDA * video_qscale;

        }

        if(intra_matrix)

            video_enc->intra_matrix = intra_matrix;

        if(inter_matrix)

            video_enc->inter_matrix = inter_matrix;

        p= video_rc_override_string;

        for(i=0; p; i++){

            int start, end, q;

            int e=sscanf(p, "%d,%d,%d", &start, &end, &q);

            if(e!=3){

                fprintf(stderr, "error parsing rc_override\n");

                ffmpeg_exit(1);

            }

            video_enc->rc_override=

                av_realloc(video_enc->rc_override,

                           sizeof(RcOverride)*(i+1));

            video_enc->rc_override[i].start_frame= start;

            video_enc->rc_override[i].end_frame  = end;

            if(q>0){

                video_enc->rc_override[i].qscale= q;

                video_enc->rc_override[i].quality_factor= 1.0;

            }

            else{

                video_enc->rc_override[i].qscale= 0;

                video_enc->rc_override[i].quality_factor= -q/100.0;

            }

            p= strchr(p, '/');

            if(p) p++;

        }

        video_enc->rc_override_count=i;

        if (!video_enc->rc_initial_buffer_occupancy)

            video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;

        video_enc->me_threshold= me_threshold;

        video_enc->intra_dc_precision= intra_dc_precision - 8;

        if (do_psnr)

            video_enc->flags|= CODEC_FLAG_PSNR;

        /* two pass mode */

        if (do_pass) {

            if (do_pass == 1) {

                video_enc->flags |= CODEC_FLAG_PASS1;

            } else {

                video_enc->flags |= CODEC_FLAG_PASS2;

            }

        }

        if (forced_key_frames)

            parse_forced_key_frames(forced_key_frames, ost, video_enc);

    }

    if (video_language) {

        av_metadata_set2(&st->metadata, "language", video_language, 0);

        av_freep(&video_language);

    }

    /* reset some key parameters */

    video_disable = 0;

    av_freep(&video_codec_name);

    av_freep(&forced_key_frames);

    video_stream_copy = 0;

    frame_pix_fmt = PIX_FMT_NONE;

}


static ExitStatus trans_fop_wew_0e(DisasContext *ctx, uint32_t insn,

                                   const DisasInsn *di)

{

    unsigned rt = assemble_rt64(insn);

    unsigned ra = assemble_ra64(insn);

    return do_fop_wew(ctx, rt, ra, di->f_wew);

}