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

                              const AVFrame *frame, int *got_packet_ptr)

{

    SonicContext *s = avctx->priv_data;

    RangeCoder c;

    int i, j, ch, quant = 0, x = 0;

    int ret;

    const short *samples = (const int16_t*)frame->data[0];

    uint8_t state[32];

    if ((ret = ff_alloc_packet2(avctx, avpkt, s->frame_size * 5 + 1000)) < 0)

        return ret;

    ff_init_range_encoder(&c, avpkt->data, avpkt->size);

    ff_build_rac_states(&c, 0.05*(1LL<<32), 256-8);

    memset(state, 128, sizeof(state));

    // short -> internal

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

        s->int_samples[i] = samples[i];

    if (!s->lossless)

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

            s->int_samples[i] = s->int_samples[i] << SAMPLE_SHIFT;

    switch(s->decorrelation)

    {

        case MID_SIDE:

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

            {

                s->int_samples[i] += s->int_samples[i+1];

                s->int_samples[i+1] -= shift(s->int_samples[i], 1);

            }

            break;

        case LEFT_SIDE:

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

                s->int_samples[i+1] -= s->int_samples[i];

            break;

        case RIGHT_SIDE:

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

                s->int_samples[i] -= s->int_samples[i+1];

            break;

    }

    memset(s->window, 0, 4* s->window_size);

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

        s->window[x++] = s->tail[i];

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

        s->window[x++] = s->int_samples[i];

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

        s->window[x++] = 0;

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

        s->tail[i] = s->int_samples[s->frame_size - s->tail_size + i];

    // generate taps

    modified_levinson_durbin(s->window, s->window_size,

                s->predictor_k, s->num_taps, s->channels, s->tap_quant);

    if ((ret = intlist_write(&c, state, s->predictor_k, s->num_taps, 0)) < 0)

        return ret;

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

    {

        x = s->tail_size+ch;

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

        {

            int sum = 0;

            for (j = 0; j < s->downsampling; j++, x += s->channels)

                sum += s->window[x];

            s->coded_samples[ch][i] = sum;

        }

    }

    // simple rate control code

    if (!s->lossless)

    {

        double energy1 = 0.0, energy2 = 0.0;

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

        {

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

            {

                double sample = s->coded_samples[ch][i];

                energy2 += sample*sample;

                energy1 += fabs(sample);

            }

        }

        energy2 = sqrt(energy2/(s->channels*s->block_align));

        energy1 = M_SQRT2*energy1/(s->channels*s->block_align);

        // increase bitrate when samples are like a gaussian distribution

        // reduce bitrate when samples are like a two-tailed exponential distribution

        if (energy2 > energy1)

            energy2 += (energy2-energy1)*RATE_VARIATION;

        quant = (int)(BASE_QUANT*s->quantization*energy2/SAMPLE_FACTOR);

//        av_log(avctx, AV_LOG_DEBUG, "quant: %d energy: %f / %f\n", quant, energy1, energy2);

        quant = av_clip(quant, 1, 65534);

        put_symbol(&c, state, quant, 0, NULL, NULL);

        quant *= SAMPLE_FACTOR;

    }

    // write out coded samples

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

    {

        if (!s->lossless)

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

                s->coded_samples[ch][i] = ROUNDED_DIV(s->coded_samples[ch][i], quant);

        if ((ret = intlist_write(&c, state, s->coded_samples[ch], s->block_align, 1)) < 0)

            return ret;

    }

//    av_log(avctx, AV_LOG_DEBUG, "used bytes: %d\n", (put_bits_count(&pb)+7)/8);

    avpkt->size = ff_rac_terminate(&c);

    *got_packet_ptr = 1;

    return 0;

}


int tpm_register_driver(const TPMDriverOps *tdo)

{

    int i;

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

        if (!be_drivers[i]) {

            be_drivers[i] = tdo;

            return 0;

        }

    }

    error_report("Could not register TPM driver");

    return 1;

}


static void xilinx_axidma_init(Object *obj)

{

    XilinxAXIDMA *s = XILINX_AXI_DMA(obj);

    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    object_property_add_link(obj, "axistream-connected", TYPE_STREAM_SLAVE,

                             (Object **)&s->tx_data_dev, &error_abort);

    object_property_add_link(obj, "axistream-control-connected",

                             TYPE_STREAM_SLAVE,

                             (Object **)&s->tx_control_dev, &error_abort);

    object_initialize(&s->rx_data_dev, sizeof(s->rx_data_dev),

                      TYPE_XILINX_AXI_DMA_DATA_STREAM);

    object_initialize(&s->rx_control_dev, sizeof(s->rx_control_dev),

                      TYPE_XILINX_AXI_DMA_CONTROL_STREAM);

    object_property_add_child(OBJECT(s), "axistream-connected-target",

                              (Object *)&s->rx_data_dev, &error_abort);

    object_property_add_child(OBJECT(s), "axistream-control-connected-target",

                              (Object *)&s->rx_control_dev, &error_abort);

    sysbus_init_irq(sbd, &s->streams[0].irq);

    sysbus_init_irq(sbd, &s->streams[1].irq);

    memory_region_init_io(&s->iomem, obj, &axidma_ops, s,

                          "xlnx.axi-dma", R_MAX * 4 * 2);

    sysbus_init_mmio(sbd, &s->iomem);

}


static int count_contiguous_free_clusters(int nb_clusters, uint64_t *l2_table)

{

    int i;

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

        int type = qcow2_get_cluster_type(be64_to_cpu(l2_table[i]));

        if (type != QCOW2_CLUSTER_UNALLOCATED) {

            break;

        }

    }

    return i;

}


void ide_init_ioport(IDEBus *bus, ISADevice *dev, int iobase, int iobase2)

{

    /* ??? Assume only ISA and PCI configurations, and that the PCI-ISA

       bridge has been setup properly to always register with ISA.  */

    isa_register_portio_list(dev, iobase, ide_portio_list, bus, "ide");

    if (iobase2) {

        isa_register_portio_list(dev, iobase2, ide_portio2_list, bus, "ide");

    }

}


static int read_huffman_tables(HYuvContext *s, uint8_t *src, int length){

    GetBitContext gb;

    int i;

    init_get_bits(&gb, src, length*8);

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

        read_len_table(s->len[i], &gb);

        if(generate_bits_table(s->bits[i], s->len[i])<0){

            return -1;

        }

#if 0

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

printf("%6X, %2d,  %3d\n", s->bits[i][j], s->len[i][j], j);

}

#endif

        free_vlc(&s->vlc[i]);

        init_vlc(&s->vlc[i], VLC_BITS, 256, s->len[i], 1, 1, s->bits[i], 4, 4, 0);

    }

    generate_joint_tables(s);

    return (get_bits_count(&gb)+7)/8;

}


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

{

    if (!strcasecmp(str, "on"))

        bit_prop_set(dev, prop, true);

    else if (!strcasecmp(str, "off"))

        bit_prop_set(dev, prop, false);

    else

        return -EINVAL;

    return 0;

}


int ff_hevc_cu_qp_delta_abs(HEVCContext *s)

{

    int prefix_val = 0;

    int suffix_val = 0;

    int inc = 0;

    while (prefix_val < 5 && GET_CABAC(elem_offset[CU_QP_DELTA] + inc)) {

        prefix_val++;

        inc = 1;

    }

    if (prefix_val >= 5) {

        int k = 0;

        while (k < CABAC_MAX_BIN && get_cabac_bypass(&s->HEVClc->cc)) {

            suffix_val += 1 << k;

            k++;

        }

        if (k == CABAC_MAX_BIN)

            av_log(s->avctx, AV_LOG_ERROR, "CABAC_MAX_BIN : %d\n", k);

        while (k--)

            suffix_val += get_cabac_bypass(&s->HEVClc->cc) << k;

    }

    return prefix_val + suffix_val;

}


static inline void gdb_continue(GDBState *s)

{

#ifdef CONFIG_USER_ONLY

    s->running_state = 1;

#else

    vm_start();

#endif

}


av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
{
    NVENCContext *ctx               = avctx->priv_data;
    NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
    int i;
    av_fifo_free(ctx->timestamps);
    av_fifo_free(ctx->pending);
    av_fifo_free(ctx->ready);
    if (ctx->in) {
        for (i = 0; i < ctx->nb_surfaces; ++i) {
            nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->in[i].in);
            nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->out[i].out);
    av_freep(&ctx->in);
    av_freep(&ctx->out);
    if (ctx->nvenc_ctx)
        nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
    if (ctx->cu_context)
        ctx->nvel.cu_ctx_destroy(ctx->cu_context);
    if (ctx->nvel.nvenc)
        dlclose(ctx->nvel.nvenc);
    if (ctx->nvel.cuda)
        dlclose(ctx->nvel.cuda);
    return 0;


static void trigger_console_data(void *opaque, int n, int level)

{

    sclp_service_interrupt(0);

}


static void dec_modu(DisasContext *dc)

{

    int l1;

    LOG_DIS("modu r%d, r%d, %d\n", dc->r2, dc->r0, dc->r1);

    if (!(dc->env->features & LM32_FEATURE_DIVIDE)) {

        cpu_abort(dc->env, "hardware divider is not available\n");

    }

    l1 = gen_new_label();

    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_R[dc->r1], 0, l1);

    tcg_gen_movi_tl(cpu_pc, dc->pc);

    t_gen_raise_exception(dc, EXCP_DIVIDE_BY_ZERO);

    gen_set_label(l1);

    tcg_gen_remu_tl(cpu_R[dc->r2], cpu_R[dc->r0], cpu_R[dc->r1]);

}


static void rv40_loop_filter(RV34DecContext *r, int row)

{

    MpegEncContext *s = &r->s;

    int mb_pos, mb_x;

    int i, j, k;

    uint8_t *Y, *C;

    int alpha, beta, betaY, betaC;

    int q;

    int mbtype[4];   ///< current macroblock and its neighbours types

    /**

     * flags indicating that macroblock can be filtered with strong filter

     * it is set only for intra coded MB and MB with DCs coded separately

     */

    int mb_strong[4];

    int clip[4];     ///< MB filter clipping value calculated from filtering strength

    /**

     * coded block patterns for luma part of current macroblock and its neighbours

     * Format:

     * LSB corresponds to the top left block,

     * each nibble represents one row of subblocks.

     */

    int cbp[4];

    /**

     * coded block patterns for chroma part of current macroblock and its neighbours

     * Format is the same as for luma with two subblocks in a row.

     */

    int uvcbp[4][2];

    /**

     * This mask represents the pattern of luma subblocks that should be filtered

     * in addition to the coded ones because because they lie at the edge of

     * 8x8 block with different enough motion vectors

     */

    unsigned mvmasks[4];

    mb_pos = row * s->mb_stride;

    for(mb_x = 0; mb_x < s->mb_width; mb_x++, mb_pos++){

        int mbtype = s->current_picture_ptr->mb_type[mb_pos];

        if(IS_INTRA(mbtype) || IS_SEPARATE_DC(mbtype))

            r->cbp_luma  [mb_pos] = r->deblock_coefs[mb_pos] = 0xFFFF;

        if(IS_INTRA(mbtype))

            r->cbp_chroma[mb_pos] = 0xFF;

    }

    mb_pos = row * s->mb_stride;

    for(mb_x = 0; mb_x < s->mb_width; mb_x++, mb_pos++){

        int y_h_deblock, y_v_deblock;

        int c_v_deblock[2], c_h_deblock[2];

        int clip_left;

        int avail[4];

        unsigned y_to_deblock;

        int c_to_deblock[2];

        q = s->current_picture_ptr->qscale_table[mb_pos];

        alpha = rv40_alpha_tab[q];

        beta  = rv40_beta_tab [q];

        betaY = betaC = beta * 3;

        if(s->width * s->height <= 176*144)

            betaY += beta;

        avail[0] = 1;

        avail[1] = row;

        avail[2] = mb_x;

        avail[3] = row < s->mb_height - 1;

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

            if(avail[i]){

                int pos = mb_pos + neighbour_offs_x[i] + neighbour_offs_y[i]*s->mb_stride;

                mvmasks[i] = r->deblock_coefs[pos];

                mbtype [i] = s->current_picture_ptr->mb_type[pos];

                cbp    [i] = r->cbp_luma[pos];

                uvcbp[i][0] = r->cbp_chroma[pos] & 0xF;

                uvcbp[i][1] = r->cbp_chroma[pos] >> 4;

            }else{

                mvmasks[i] = 0;

                mbtype [i] = mbtype[0];

                cbp    [i] = 0;

                uvcbp[i][0] = uvcbp[i][1] = 0;

            }

            mb_strong[i] = IS_INTRA(mbtype[i]) || IS_SEPARATE_DC(mbtype[i]);

            clip[i] = rv40_filter_clip_tbl[mb_strong[i] + 1][q];

        }

        y_to_deblock =  mvmasks[POS_CUR]

                     | (mvmasks[POS_BOTTOM] << 16);

        /* This pattern contains bits signalling that horizontal edges of

         * the current block can be filtered.

         * That happens when either of adjacent subblocks is coded or lies on

         * the edge of 8x8 blocks with motion vectors differing by more than

         * 3/4 pel in any component (any edge orientation for some reason).

         */

        y_h_deblock =   y_to_deblock

                    | ((cbp[POS_CUR]                           <<  4) & ~MASK_Y_TOP_ROW)

                    | ((cbp[POS_TOP]        & MASK_Y_LAST_ROW) >> 12);

        /* This pattern contains bits signalling that vertical edges of

         * the current block can be filtered.

         * That happens when either of adjacent subblocks is coded or lies on

         * the edge of 8x8 blocks with motion vectors differing by more than

         * 3/4 pel in any component (any edge orientation for some reason).

         */

        y_v_deblock =   y_to_deblock

                    | ((cbp[POS_CUR]                      << 1) & ~MASK_Y_LEFT_COL)

                    | ((cbp[POS_LEFT] & MASK_Y_RIGHT_COL) >> 3);

        if(!mb_x)

            y_v_deblock &= ~MASK_Y_LEFT_COL;

        if(!row)

            y_h_deblock &= ~MASK_Y_TOP_ROW;

        if(row == s->mb_height - 1 || (mb_strong[POS_CUR] | mb_strong[POS_BOTTOM]))

            y_h_deblock &= ~(MASK_Y_TOP_ROW << 16);

        /* Calculating chroma patterns is similar and easier since there is

         * no motion vector pattern for them.

         */

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

            c_to_deblock[i] = (uvcbp[POS_BOTTOM][i] << 4) | uvcbp[POS_CUR][i];

            c_v_deblock[i] =   c_to_deblock[i]

                           | ((uvcbp[POS_CUR] [i]                       << 1) & ~MASK_C_LEFT_COL)

                           | ((uvcbp[POS_LEFT][i]   & MASK_C_RIGHT_COL) >> 1);

            c_h_deblock[i] =   c_to_deblock[i]

                           | ((uvcbp[POS_TOP][i]    & MASK_C_LAST_ROW)  >> 2)

                           |  (uvcbp[POS_CUR][i]                        << 2);

            if(!mb_x)

                c_v_deblock[i] &= ~MASK_C_LEFT_COL;

            if(!row)

                c_h_deblock[i] &= ~MASK_C_TOP_ROW;

            if(row == s->mb_height - 1 || (mb_strong[POS_CUR] | mb_strong[POS_BOTTOM]))

                c_h_deblock[i] &= ~(MASK_C_TOP_ROW << 4);

        }

        for(j = 0; j < 16; j += 4){

            Y = s->current_picture_ptr->f.data[0] + mb_x*16 + (row*16 + j) * s->linesize;

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

                int ij = i + j;

                int clip_cur = y_to_deblock & (MASK_CUR << ij) ? clip[POS_CUR] : 0;

                int dither = j ? ij : i*4;

                // if bottom block is coded then we can filter its top edge

                // (or bottom edge of this block, which is the same)

                if(y_h_deblock & (MASK_BOTTOM << ij)){

                    rv40_adaptive_loop_filter(&r->rdsp, Y+4*s->linesize,

                                              s->linesize, dither,

                                              y_to_deblock & (MASK_BOTTOM << ij) ? clip[POS_CUR] : 0,

                                              clip_cur, alpha, beta, betaY,

                                              0, 0, 0);

                }

                // filter left block edge in ordinary mode (with low filtering strength)

                if(y_v_deblock & (MASK_CUR << ij) && (i || !(mb_strong[POS_CUR] | mb_strong[POS_LEFT]))){

                    if(!i)

                        clip_left = mvmasks[POS_LEFT] & (MASK_RIGHT << j) ? clip[POS_LEFT] : 0;

                    else

                        clip_left = y_to_deblock & (MASK_CUR << (ij-1)) ? clip[POS_CUR] : 0;

                    rv40_adaptive_loop_filter(&r->rdsp, Y, s->linesize, dither,

                                              clip_cur,

                                              clip_left,

                                              alpha, beta, betaY, 0, 0, 1);

                }

                // filter top edge of the current macroblock when filtering strength is high

                if(!j && y_h_deblock & (MASK_CUR << i) && (mb_strong[POS_CUR] | mb_strong[POS_TOP])){

                    rv40_adaptive_loop_filter(&r->rdsp, Y, s->linesize, dither,

                                       clip_cur,

                                       mvmasks[POS_TOP] & (MASK_TOP << i) ? clip[POS_TOP] : 0,

                                       alpha, beta, betaY, 0, 1, 0);

                }

                // filter left block edge in edge mode (with high filtering strength)

                if(y_v_deblock & (MASK_CUR << ij) && !i && (mb_strong[POS_CUR] | mb_strong[POS_LEFT])){

                    clip_left = mvmasks[POS_LEFT] & (MASK_RIGHT << j) ? clip[POS_LEFT] : 0;

                    rv40_adaptive_loop_filter(&r->rdsp, Y, s->linesize, dither,

                                       clip_cur,

                                       clip_left,

                                       alpha, beta, betaY, 0, 1, 1);

                }

            }

        }

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

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

                C = s->current_picture_ptr->f.data[k + 1] + mb_x*8 + (row*8 + j*4) * s->uvlinesize;

                for(i = 0; i < 2; i++, C += 4){

                    int ij = i + j*2;

                    int clip_cur = c_to_deblock[k] & (MASK_CUR << ij) ? clip[POS_CUR] : 0;

                    if(c_h_deblock[k] & (MASK_CUR << (ij+2))){

                        int clip_bot = c_to_deblock[k] & (MASK_CUR << (ij+2)) ? clip[POS_CUR] : 0;

                        rv40_adaptive_loop_filter(&r->rdsp, C+4*s->uvlinesize, s->uvlinesize, i*8,

                                           clip_bot,

                                           clip_cur,

                                           alpha, beta, betaC, 1, 0, 0);

                    }

                    if((c_v_deblock[k] & (MASK_CUR << ij)) && (i || !(mb_strong[POS_CUR] | mb_strong[POS_LEFT]))){

                        if(!i)

                            clip_left = uvcbp[POS_LEFT][k] & (MASK_CUR << (2*j+1)) ? clip[POS_LEFT] : 0;

                        else

                            clip_left = c_to_deblock[k]    & (MASK_CUR << (ij-1))  ? clip[POS_CUR]  : 0;

                        rv40_adaptive_loop_filter(&r->rdsp, C, s->uvlinesize, j*8,

                                           clip_cur,

                                           clip_left,

                                           alpha, beta, betaC, 1, 0, 1);

                    }

                    if(!j && c_h_deblock[k] & (MASK_CUR << ij) && (mb_strong[POS_CUR] | mb_strong[POS_TOP])){

                        int clip_top = uvcbp[POS_TOP][k] & (MASK_CUR << (ij+2)) ? clip[POS_TOP] : 0;

                        rv40_adaptive_loop_filter(&r->rdsp, C, s->uvlinesize, i*8,

                                           clip_cur,

                                           clip_top,

                                           alpha, beta, betaC, 1, 1, 0);

                    }

                    if(c_v_deblock[k] & (MASK_CUR << ij) && !i && (mb_strong[POS_CUR] | mb_strong[POS_LEFT])){

                        clip_left = uvcbp[POS_LEFT][k] & (MASK_CUR << (2*j+1)) ? clip[POS_LEFT] : 0;

                        rv40_adaptive_loop_filter(&r->rdsp, C, s->uvlinesize, j*8,

                                           clip_cur,

                                           clip_left,

                                           alpha, beta, betaC, 1, 1, 1);

                    }

                }

            }

        }

    }

}


static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)

{

    struct video_data *s = ctx->priv_data;

    struct v4l2_buffer buf = {

        .type   = V4L2_BUF_TYPE_VIDEO_CAPTURE,

        .memory = V4L2_MEMORY_MMAP

    };

    int res;

    pkt->size = 0;

    /* FIXME: Some special treatment might be needed in case of loss of signal... */

    while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));

    if (res < 0) {

        if (errno == EAGAIN)

            return AVERROR(EAGAIN);

        res = AVERROR(errno);

        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",

               av_err2str(res));

        return res;

    }

    if (buf.index >= s->buffers) {

        av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");

        return AVERROR(EINVAL);

    }

    atomic_fetch_add(&s->buffers_queued, -1);

    // always keep at least one buffer queued

    av_assert0(atomic_load(&s->buffers_queued) >= 1);

#ifdef V4L2_BUF_FLAG_ERROR

    if (buf.flags & V4L2_BUF_FLAG_ERROR) {

        av_log(ctx, AV_LOG_WARNING,

               "Dequeued v4l2 buffer contains corrupted data (%d bytes).\n",

               buf.bytesused);

        buf.bytesused = 0;

    } else

#endif

    {

        /* CPIA is a compressed format and we don't know the exact number of bytes

         * used by a frame, so set it here as the driver announces it. */

        if (ctx->video_codec_id == AV_CODEC_ID_CPIA)

            s->frame_size = buf.bytesused;

        if (s->frame_size > 0 && buf.bytesused != s->frame_size) {

            av_log(ctx, AV_LOG_ERROR,

                   "Dequeued v4l2 buffer contains %d bytes, but %d were expected. Flags: 0x%08X.\n",

                   buf.bytesused, s->frame_size, buf.flags);

            enqueue_buffer(s, &buf);

            return AVERROR_INVALIDDATA;

        }

    }

    /* Image is at s->buff_start[buf.index] */

    if (atomic_load(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {

        /* when we start getting low on queued buffers, fall back on copying data */

        res = av_new_packet(pkt, buf.bytesused);

        if (res < 0) {

            av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");

            enqueue_buffer(s, &buf);

            return res;

        }

        memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);

        res = enqueue_buffer(s, &buf);

        if (res) {

            av_packet_unref(pkt);

            return res;

        }

    } else {

        struct buff_data *buf_descriptor;

        pkt->data     = s->buf_start[buf.index];

        pkt->size     = buf.bytesused;

        buf_descriptor = av_malloc(sizeof(struct buff_data));

        if (!buf_descriptor) {

            /* Something went wrong... Since av_malloc() failed, we cannot even

             * allocate a buffer for memcpying into it

             */

            av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");

            enqueue_buffer(s, &buf);

            return AVERROR(ENOMEM);

        }

        buf_descriptor->index = buf.index;

        buf_descriptor->s     = s;

        pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,

                                    buf_descriptor, 0);

        if (!pkt->buf) {

            av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");

            enqueue_buffer(s, &buf);

            av_freep(&buf_descriptor);

            return AVERROR(ENOMEM);

        }

    }

    pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;

    convert_timestamp(ctx, &pkt->pts);

    return pkt->size;

}


static int seg_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    SegmentContext *seg = s->priv_data;

    AVStream *st = s->streams[pkt->stream_index];

    int64_t end_pts = INT64_MAX, offset;

    int start_frame = INT_MAX;

    int ret;

    struct tm ti;

    int64_t usecs;

    int64_t wrapped_val;

    if (!seg->avf)

        return AVERROR(EINVAL);

calc_times:

    if (seg->times) {

        end_pts = seg->segment_count < seg->nb_times ?

            seg->times[seg->segment_count] : INT64_MAX;

    } else if (seg->frames) {

        start_frame = seg->segment_count < seg->nb_frames ?

            seg->frames[seg->segment_count] : INT_MAX;

    } else {

        if (seg->use_clocktime) {

            int64_t avgt = av_gettime();

            time_t sec = avgt / 1000000;

            localtime_r(&sec, &ti);

            usecs = (int64_t)(ti.tm_hour * 3600 + ti.tm_min * 60 + ti.tm_sec) * 1000000 + (avgt % 1000000);

            wrapped_val = (usecs + seg->clocktime_offset) % seg->time;

            if (seg->last_cut != usecs && wrapped_val < seg->last_val && wrapped_val < seg->clocktime_wrap_duration) {

                seg->cut_pending = 1;

                seg->last_cut = usecs;

            }

            seg->last_val = wrapped_val;

        } else {

            end_pts = seg->time * (seg->segment_count + 1);

        }

    }

    ff_dlog(s, "packet stream:%d pts:%s pts_time:%s duration_time:%s is_key:%d frame:%d\n",

            pkt->stream_index, av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),

            av_ts2timestr(pkt->duration, &st->time_base),

            pkt->flags & AV_PKT_FLAG_KEY,

            pkt->stream_index == seg->reference_stream_index ? seg->frame_count : -1);

    if (pkt->stream_index == seg->reference_stream_index &&

        (pkt->flags & AV_PKT_FLAG_KEY || seg->break_non_keyframes) &&

        (seg->segment_frame_count > 0 || seg->write_empty) &&

        (seg->cut_pending || seg->frame_count >= start_frame ||

         (pkt->pts != AV_NOPTS_VALUE &&

          av_compare_ts(pkt->pts, st->time_base,

                        end_pts - seg->time_delta, AV_TIME_BASE_Q) >= 0))) {

        /* sanitize end time in case last packet didn't have a defined duration */

        if (seg->cur_entry.last_duration == 0)

            seg->cur_entry.end_time = (double)pkt->pts * av_q2d(st->time_base);

        if ((ret = segment_end(s, seg->individual_header_trailer, 0)) < 0)

            goto fail;

        if ((ret = segment_start(s, seg->individual_header_trailer)) < 0)

            goto fail;

        seg->cut_pending = 0;

        seg->cur_entry.index = seg->segment_idx + seg->segment_idx_wrap * seg->segment_idx_wrap_nb;

        seg->cur_entry.start_time = (double)pkt->pts * av_q2d(st->time_base);

        seg->cur_entry.start_pts = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);

        seg->cur_entry.end_time = seg->cur_entry.start_time;

        if (seg->times || (!seg->frames && !seg->use_clocktime) && seg->write_empty)

            goto calc_times;

    }

    if (pkt->stream_index == seg->reference_stream_index) {

        if (pkt->pts != AV_NOPTS_VALUE)

            seg->cur_entry.end_time =

                FFMAX(seg->cur_entry.end_time, (double)(pkt->pts + pkt->duration) * av_q2d(st->time_base));

        seg->cur_entry.last_duration = pkt->duration;

    }

    if (seg->segment_frame_count == 0) {

        av_log(s, AV_LOG_VERBOSE, "segment:'%s' starts with packet stream:%d pts:%s pts_time:%s frame:%d\n",

               seg->avf->filename, pkt->stream_index,

               av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base), seg->frame_count);

    }

    av_log(s, AV_LOG_DEBUG, "stream:%d start_pts_time:%s pts:%s pts_time:%s dts:%s dts_time:%s",

           pkt->stream_index,

           av_ts2timestr(seg->cur_entry.start_pts, &AV_TIME_BASE_Q),

           av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),

           av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));

    /* compute new timestamps */

    offset = av_rescale_q(seg->initial_offset - (seg->reset_timestamps ? seg->cur_entry.start_pts : 0),

                          AV_TIME_BASE_Q, st->time_base);

    if (pkt->pts != AV_NOPTS_VALUE)

        pkt->pts += offset;

    if (pkt->dts != AV_NOPTS_VALUE)

        pkt->dts += offset;

    av_log(s, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",

           av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),

           av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));

    ret = ff_write_chained(seg->avf, pkt->stream_index, pkt, s, seg->initial_offset || seg->reset_timestamps);

fail:

    if (pkt->stream_index == seg->reference_stream_index) {

        seg->frame_count++;

        seg->segment_frame_count++;

    }

    return ret;

}


static int reap_filters(int flush)

{

    AVFrame *filtered_frame = NULL;

    int i;

    /* Reap all buffers present in the buffer sinks */

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

        OutputStream *ost = output_streams[i];

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

        AVFilterContext *filter;

        AVCodecContext *enc = ost->enc_ctx;

        int ret = 0;

        if (!ost->filter || !ost->filter->graph->graph)

            continue;

        filter = ost->filter->filter;

        if (!ost->initialized) {

            char error[1024];

            ret = init_output_stream(ost, error, sizeof(error));

            if (ret < 0) {

                av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",

                       ost->file_index, ost->index, error);

                exit_program(1);

            }

        }

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

            return AVERROR(ENOMEM);

        }

        filtered_frame = ost->filtered_frame;

        while (1) {

            double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision

            ret = av_buffersink_get_frame_flags(filter, filtered_frame,

                                               AV_BUFFERSINK_FLAG_NO_REQUEST);

            if (ret < 0) {

                if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {

                    av_log(NULL, AV_LOG_WARNING,

                           "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));

                } else if (flush && ret == AVERROR_EOF) {

                    if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)

                        do_video_out(of, ost, NULL, AV_NOPTS_VALUE);

                }

                break;

            }

            if (ost->finished) {

                av_frame_unref(filtered_frame);

                continue;

            }

            if (filtered_frame->pts != AV_NOPTS_VALUE) {

                int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;

                AVRational filter_tb = av_buffersink_get_time_base(filter);

                AVRational tb = enc->time_base;

                int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);

                tb.den <<= extra_bits;

                float_pts =

                    av_rescale_q(filtered_frame->pts, filter_tb, tb) -

                    av_rescale_q(start_time, AV_TIME_BASE_Q, tb);

                float_pts /= 1 << extra_bits;

                // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers

                float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);

                filtered_frame->pts =

                    av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -

                    av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);

            }

            //if (ost->source_index >= 0)

            //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold

            switch (av_buffersink_get_type(filter)) {

            case AVMEDIA_TYPE_VIDEO:

                if (!ost->frame_aspect_ratio.num)

                    enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;

                if (debug_ts) {

                    av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",

                            av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),

                            float_pts,

                            enc->time_base.num, enc->time_base.den);

                }

                do_video_out(of, ost, filtered_frame, float_pts);

                break;

            case AVMEDIA_TYPE_AUDIO:

                if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&

                    enc->channels != av_frame_get_channels(filtered_frame)) {

                    av_log(NULL, AV_LOG_ERROR,

                           "Audio filter graph output is not normalized and encoder does not support parameter changes\n");

                    break;

                }

                do_audio_out(of, ost, filtered_frame);

                break;

            default:

                // TODO support subtitle filters

                av_assert0(0);

            }

            av_frame_unref(filtered_frame);

        }

    }

    return 0;

}


static int decode_p_picture_primary_header(VC9Context *v)

{

    /* INTERFRM, FRMCNT, RANGEREDFRM read in caller */

    GetBitContext *gb = &v->s.gb;

    int lowquant, pqindex, status = 0;

    pqindex = get_bits(gb, 5);

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = pquant_table[0][pqindex];

    else

    {

        v->pq = pquant_table[v->quantizer_mode-1][pqindex];

    }

    if (pqindex < 9) v->halfpq = get_bits(gb, 1);

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits(gb, 1);

    av_log(v->s.avctx, AV_LOG_DEBUG, "P Frame: QP=%i (+%i/2)\n",

           v->pq, v->halfpq);

    if (v->extended_mv == 1) v->mvrange = get_prefix(gb, 0, 3);

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        if (v->postprocflag) v->postproc = get_bits(gb, 1);

    }

    else

#endif

        if (v->multires) v->respic = get_bits(gb, 2);

    lowquant = (v->pquantizer>12) ? 0 : 1;

    v->mv_mode = mv_pmode_table[lowquant][get_prefix(gb, 1, 4)];

    if (v->mv_mode == MV_PMODE_INTENSITY_COMP)

    {

        v->mv_mode2 = mv_pmode_table[lowquant][get_prefix(gb, 1, 3)];

        v->lumscale = get_bits(gb, 6);

        v->lumshift = get_bits(gb, 6);

    }

    return 0;

}


static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){

    RMDemuxContext *rm = s->priv_data;

    ByteIOContext *pb = s->pb;

    int len, num, res, i;

    AVStream *st;

    uint32_t state=0xFFFFFFFF;

    while(!url_feof(pb)){

        *pos= url_ftell(pb) - 3;

        if(rm->remaining_len > 0){

            num= rm->current_stream;

            len= rm->remaining_len;

            *timestamp = AV_NOPTS_VALUE;

            *flags= 0;

        }else{

            state= (state<<8) + get_byte(pb);

            if(state == MKBETAG('I', 'N', 'D', 'X')){

                len = get_be16(pb) - 6;

                if(len<0)

                    continue;

                goto skip;

            }

            if(state > (unsigned)0xFFFF || state < 12)

                continue;

            len=state;

            state= 0xFFFFFFFF;

            num = get_be16(pb);

            *timestamp = get_be32(pb);

            res= get_byte(pb); /* reserved */

            *flags = get_byte(pb); /* flags */

            len -= 12;

        }

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

            st = s->streams[i];

            if (num == st->id)

                break;

        }

        if (i == s->nb_streams) {

skip:

            /* skip packet if unknown number */

            url_fskip(pb, len);

            rm->remaining_len -= len;

            continue;

        }

        *stream_index= i;

        return len;

    }

    return -1;

}


int mpeg4_decode_picture_header(MpegEncContext * s)

{

    int time_incr, startcode, state, v;

 redo:

    /* search next start code */

    align_get_bits(&s->gb);

    state = 0xff;

    for(;;) {

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

        if (state == 0x000001) {

            state = ((state << 8) | v) & 0xffffff;

            startcode = state;

            break;

        }

        state = ((state << 8) | v) & 0xffffff;

        if( get_bits_count(&s->gb) > s->gb.size*8-32){

            printf("no VOP startcode found\n");

            return -1;

        }

    }

//printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));

    if (startcode == 0x120) { // Video Object Layer

        int width, height, vo_ver_id;

        /* vol header */

        skip_bits(&s->gb, 1); /* random access */

        skip_bits(&s->gb, 8); /* vo_type */

        if (get_bits1(&s->gb) != 0) { /* is_ol_id */

            vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */

            skip_bits(&s->gb, 3); /* vo_priority */

        } else {

            vo_ver_id = 1;

        }

        s->aspect_ratio_info= get_bits(&s->gb, 4);

	if(s->aspect_ratio_info == EXTENDET_PAR){

            skip_bits(&s->gb, 8); //par_width

            skip_bits(&s->gb, 8); // par_height

        }

        if(get_bits1(&s->gb)){ /* vol control parameter */

            printf("vol control parameter not supported\n");

            return -1;

        }

        s->shape = get_bits(&s->gb, 2); /* vol shape */

        if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");

        if(s->shape == GRAY_SHAPE && vo_ver_id != 1){

            printf("Gray shape not supported\n");

            skip_bits(&s->gb, 4);  //video_object_layer_shape_extension

        }

        skip_bits1(&s->gb);   /* marker */

        s->time_increment_resolution = get_bits(&s->gb, 16);

        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;

        if (s->time_increment_bits < 1)

            s->time_increment_bits = 1;

        skip_bits1(&s->gb);   /* marker */

        if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */

            skip_bits(&s->gb, s->time_increment_bits);

        }

        if (s->shape != BIN_ONLY_SHAPE) {

            if (s->shape == RECT_SHAPE) {

                skip_bits1(&s->gb);   /* marker */

                width = get_bits(&s->gb, 13);

                skip_bits1(&s->gb);   /* marker */

                height = get_bits(&s->gb, 13);

                skip_bits1(&s->gb);   /* marker */

                if(width && height){ /* they should be non zero but who knows ... */

                    s->width = width;

                    s->height = height;

//                    printf("%d %d\n", width, height);

                }

            }

            if(get_bits1(&s->gb)) printf("interlaced not supported\n");   /* interlaced */

            if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */

            if (vo_ver_id == 1) {

                s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */

            } else {

                s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */

            }

            if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");

            if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){

                if(s->vol_sprite_usage==STATIC_SPRITE){

                    s->sprite_width = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_height= get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_left  = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_top   = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                }

                s->num_sprite_warping_points= get_bits(&s->gb, 6);

                s->sprite_warping_accuracy = get_bits(&s->gb, 2);

                s->sprite_brightness_change= get_bits1(&s->gb);

                if(s->vol_sprite_usage==STATIC_SPRITE)

                    s->low_latency_sprite= get_bits1(&s->gb);

            }

            // FIXME sadct disable bit if verid!=1 && shape not rect

            if (get_bits1(&s->gb) == 1) {   /* not_8_bit */

                s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */

                if(get_bits(&s->gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */

            } else {

                s->quant_precision = 5;

            }

            // FIXME a bunch of grayscale shape things

            if(get_bits1(&s->gb)) printf("Quant-Type not supported\n");  /* vol_quant_type */ //FIXME

            if(vo_ver_id != 1)

                 s->quarter_sample= get_bits1(&s->gb);

            else s->quarter_sample=0;

            if(!get_bits1(&s->gb)) printf("Complexity estimation not supported\n");

#if 0

            if(get_bits1(&s->gb)) printf("resync disable\n");

#else

            skip_bits1(&s->gb);   /* resync_marker_disabled */

#endif

            s->data_partioning= get_bits1(&s->gb);

            if(s->data_partioning){

                printf("data partitioning not supported\n");

                skip_bits1(&s->gb); // reversible vlc

            }

            if(vo_ver_id != 1) {

                s->new_pred= get_bits1(&s->gb);

                if(s->new_pred){

                    printf("new pred not supported\n");

                    skip_bits(&s->gb, 2); /* requested upstream message type */

                    skip_bits1(&s->gb); /* newpred segment type */

                }

                s->reduced_res_vop= get_bits1(&s->gb);

                if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");

            }

            else{

                s->new_pred=0;

                s->reduced_res_vop= 0;

            }

            s->scalability= get_bits1(&s->gb);

            if (s->scalability) {

                printf("bad scalability!!!\n");

                return -1;

            }

        }

//printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);

        goto redo;

    } else if (startcode == 0x1b2) { //userdata

        char buf[256];

        int i;

        int e;

        int ver, build;

//printf("user Data %X\n", show_bits(&s->gb, 32));

        buf[0]= show_bits(&s->gb, 8);

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

            buf[i]= show_bits(&s->gb, 16)&0xFF;

            if(buf[i]==0) break;

            skip_bits(&s->gb, 8);

        }

        buf[255]=0;

        e=sscanf(buf, "DivX%dBuild%d", &ver, &build);

        if(e==2){

            s->divx_version= ver;

            s->divx_build= build;

            if(s->picture_number==0){

                printf("This file was encoded with DivX%d Build%d\n", ver, build);

                if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...

                    printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");

                }else{

                    printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"

                           "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");

                }

            }

        }

//printf("User Data: %s\n", buf);

        goto redo;

    } else if (startcode != 0x1b6) { //VOP

        goto redo;

    }

    s->pict_type = get_bits(&s->gb, 2) + 1;	/* pict type: I = 0 , P = 1 */

//printf("pic: %d\n", s->pict_type);

    time_incr=0;

    while (get_bits1(&s->gb) != 0)

        time_incr++;

    check_marker(&s->gb, "before time_increment");

    s->time_increment= get_bits(&s->gb, s->time_increment_bits);

    if(s->pict_type!=B_TYPE){

        s->time_base+= time_incr;

        s->last_non_b_time[1]= s->last_non_b_time[0];

        s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;

    }else{

        s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;

        s->time+= s->time_increment;

    }

    if(check_marker(&s->gb, "before vop_coded")==0 && s->picture_number==0){

        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");

        for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){

            if(get_bits1(&s->gb)) break;

        }

        printf("my guess is %d bits ;)\n",s->time_increment_bits);

    }

    /* vop coded */

    if (get_bits1(&s->gb) != 1)

        goto redo;

//printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,

//s->time, s->last_non_b_time[0], s->last_non_b_time[1]);

    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE

                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {

        /* rounding type for motion estimation */

	s->no_rounding = get_bits1(&s->gb);

    } else {

	s->no_rounding = 0;

    }

//FIXME reduced res stuff

     if (s->shape != RECT_SHAPE) {

         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {

             int width, height, hor_spat_ref, ver_spat_ref;

             width = get_bits(&s->gb, 13);

             skip_bits1(&s->gb);   /* marker */

             height = get_bits(&s->gb, 13);

             skip_bits1(&s->gb);   /* marker */

             hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */

             skip_bits1(&s->gb);   /* marker */

             ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */

         }

         skip_bits1(&s->gb); /* change_CR_disable */

         if (get_bits1(&s->gb) != 0) {

             skip_bits(&s->gb, 8); /* constant_alpha_value */

         }

     }

//FIXME complexity estimation stuff

     if (s->shape != BIN_ONLY_SHAPE) {

         skip_bits(&s->gb, 3); /* intra dc VLC threshold */

         //FIXME interlaced specific bits

     }

     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){

         if(s->num_sprite_warping_points){

             mpeg4_decode_sprite_trajectory(s);

         }

         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");

         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");

     }

     if (s->shape != BIN_ONLY_SHAPE) {

         /* note: we do not use quant_precision to avoid problem if no

            MPEG4 vol header as it is found on some old opendivx

            movies */

         s->qscale = get_bits(&s->gb, 5);

         if(s->qscale==0){

             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");

             return -1; // makes no sense to continue, as there is nothing left from the image then

         }

         if (s->pict_type != I_TYPE) {

             s->f_code = get_bits(&s->gb, 3);	/* fcode_for */

             if(s->f_code==0){

                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");

                 return -1; // makes no sense to continue, as the MV decoding will break very quickly

             }

         }

         if (s->pict_type == B_TYPE) {

             s->b_code = get_bits(&s->gb, 3);

//printf("b-code %d\n", s->b_code);

         }

//printf("quant:%d fcode:%d\n", s->qscale, s->f_code);

         if(!s->scalability){

             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {

                 skip_bits1(&s->gb); // vop shape coding type

             }

         }

     }

     s->picture_number++; // better than pic number==0 allways ;)

     return 0;

}


static int encode_init(AVCodecContext * avctx){

    WMACodecContext *s = avctx->priv_data;

    int i, flags1, flags2;

    uint8_t *extradata;

    s->avctx = avctx;

    if(avctx->channels > MAX_CHANNELS) {

        av_log(avctx, AV_LOG_ERROR, "too many channels: got %i, need %i or fewer",

               avctx->channels, MAX_CHANNELS);

        return AVERROR(EINVAL);

    }

    if(avctx->bit_rate < 24*1000) {

        av_log(avctx, AV_LOG_ERROR, "bitrate too low: got %i, need 24000 or higher\n",

               avctx->bit_rate);

        return AVERROR(EINVAL);

    }

    /* extract flag infos */

    flags1 = 0;

    flags2 = 1;

    if (avctx->codec->id == CODEC_ID_WMAV1) {

        extradata= av_malloc(4);

        avctx->extradata_size= 4;

        AV_WL16(extradata, flags1);

        AV_WL16(extradata+2, flags2);

    } else if (avctx->codec->id == CODEC_ID_WMAV2) {

        extradata= av_mallocz(10);

        avctx->extradata_size= 10;

        AV_WL32(extradata, flags1);

        AV_WL16(extradata+4, flags2);

    }else

        assert(0);

    avctx->extradata= extradata;

    s->use_exp_vlc = flags2 & 0x0001;

    s->use_bit_reservoir = flags2 & 0x0002;

    s->use_variable_block_len = flags2 & 0x0004;

    ff_wma_init(avctx, flags2);

    /* init MDCT */

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

        ff_mdct_init(&s->mdct_ctx[i], s->frame_len_bits - i + 1, 0, 1.0);

    avctx->block_align=

    s->block_align= avctx->bit_rate*(int64_t)s->frame_len / (avctx->sample_rate*8);

//av_log(NULL, AV_LOG_ERROR, "%d %d %d %d\n", s->block_align, avctx->bit_rate, s->frame_len, avctx->sample_rate);

    avctx->frame_size= s->frame_len;

    return 0;

}


static int txd_read_header(AVFormatContext *s, AVFormatParameters *ap) {
    AVStream *st;
    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);
    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codec->codec_id = CODEC_ID_TXD;
    st->codec->time_base.den = 5;
    st->codec->time_base.num = 1;
    /* the parameters will be extracted from the compressed bitstream */
    return 0;
}


static int output_frame(AVFilterLink *outlink, int nb_samples)

{

    AVFilterContext *ctx = outlink->src;

    MixContext      *s = ctx->priv;

    AVFilterBufferRef *out_buf, *in_buf;

    int i;

    calculate_scales(s, nb_samples);

    out_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);

    if (!out_buf)

        return AVERROR(ENOMEM);

    in_buf = ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);

    if (!in_buf)

        return AVERROR(ENOMEM);

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

        if (s->input_state[i] == INPUT_ON) {

            int planes, plane_size, p;

            av_audio_fifo_read(s->fifos[i], (void **)in_buf->extended_data,

                               nb_samples);

            planes     = s->planar ? s->nb_channels : 1;

            plane_size = nb_samples * (s->planar ? 1 : s->nb_channels);

            plane_size = FFALIGN(plane_size, 16);

            for (p = 0; p < planes; p++) {

                s->fdsp.vector_fmac_scalar((float *)out_buf->extended_data[p],

                                           (float *) in_buf->extended_data[p],

                                           s->input_scale[i], plane_size);

            }

        }

    }

    avfilter_unref_buffer(in_buf);

    out_buf->pts = s->next_pts;

    if (s->next_pts != AV_NOPTS_VALUE)

        s->next_pts += nb_samples;

    return ff_filter_samples(outlink, out_buf);

}


MAKE_ACCESSORS(AVVDPAUContext, vdpau_hwaccel, AVVDPAU_Render2, render2)
int ff_vdpau_common_init(AVCodecContext *avctx, VdpDecoderProfile profile,
                         int level)
{
    VDPAUHWContext *hwctx = avctx->hwaccel_context;
    VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;
    VdpDecoderCreate *create;
    void *func;
    VdpStatus status;
    /* See vdpau/vdpau.h for alignment constraints. */
    uint32_t width  = (avctx->coded_width + 1) & ~1;
    uint32_t height = (avctx->coded_height + 3) & ~3;
    if (hwctx->context.decoder != VDP_INVALID_HANDLE) {
        vdctx->decoder = hwctx->context.decoder;
        vdctx->render  = hwctx->context.render;
        return 0; /* Decoder created by user */
    vdctx->device           = hwctx->device;
    vdctx->get_proc_address = hwctx->get_proc_address;
    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_CREATE,
                                     &func);
    if (status != VDP_STATUS_OK)
        return vdpau_error(status);
    else
        create = func;
    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_RENDER,
                                     &func);
    if (status != VDP_STATUS_OK)
        return vdpau_error(status);
    else
        vdctx->render = func;
    status = create(vdctx->device, profile, width, height, avctx->refs,
                    &vdctx->decoder);
    return vdpau_error(status);


static inline int mpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded, int intra, int rvlc)

{

    int level, i, last, run;

    int dc_pred_dir;

    RLTable * rl;

    RL_VLC_ELEM * rl_vlc;

    const uint8_t * scan_table;

    int qmul, qadd;

    //Note intra & rvlc should be optimized away if this is inlined

    if(intra) {

      if(s->use_intra_dc_vlc){

        /* DC coef */

        if(s->partitioned_frame){

            level = s->dc_val[0][ s->block_index[n] ];

            if(n<4) level= FASTDIV((level + (s->y_dc_scale>>1)), s->y_dc_scale);

            else    level= FASTDIV((level + (s->c_dc_scale>>1)), s->c_dc_scale);

            dc_pred_dir= (s->pred_dir_table[s->mb_x + s->mb_y*s->mb_stride]<<n)&32;

        }else{

            level = mpeg4_decode_dc(s, n, &dc_pred_dir);

            if (level < 0)

                return -1;

        }

        block[0] = level;

        i = 0;

      }else{

            i = -1;

            ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);

      }

        if (!coded)

            goto not_coded;

        if(rvlc){

            rl = &rvlc_rl_intra;

            rl_vlc = rvlc_rl_intra.rl_vlc[0];

        }else{

            rl = &rl_intra;

            rl_vlc = rl_intra.rl_vlc[0];

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        qmul=1;

        qadd=0;

    } else {

        i = -1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        if(rvlc) rl = &rvlc_rl_inter;

        else     rl = &rl_inter;

        scan_table = s->intra_scantable.permutated;

        if(s->mpeg_quant){

            qmul=1;

            qadd=0;

            if(rvlc){

                rl_vlc = rvlc_rl_inter.rl_vlc[0];

            }else{

                rl_vlc = rl_inter.rl_vlc[0];

            }

        }else{

            qmul = s->qscale << 1;

            qadd = (s->qscale - 1) | 1;

            if(rvlc){

                rl_vlc = rvlc_rl_inter.rl_vlc[s->qscale];

            }else{

                rl_vlc = rl_inter.rl_vlc[s->qscale];

            }

        }

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);

        if (level==0) {

          /* escape */

          if(rvlc){

                if(SHOW_UBITS(re, &s->gb, 1)==0){

                    av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in rvlc esc\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 1);

                last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);

                SKIP_COUNTER(re, &s->gb, 1+1+6);

                UPDATE_CACHE(re, &s->gb);

                if(SHOW_UBITS(re, &s->gb, 1)==0){

                    av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in rvlc esc\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 1);

                level= SHOW_UBITS(re, &s->gb, 11); SKIP_CACHE(re, &s->gb, 11);

                if(SHOW_UBITS(re, &s->gb, 5)!=0x10){

                    av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");

                    return -1;

                }; SKIP_CACHE(re, &s->gb, 5);

                level=  level * qmul + qadd;

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1); LAST_SKIP_CACHE(re, &s->gb, 1);

                SKIP_COUNTER(re, &s->gb, 1+11+5+1);

                i+= run + 1;

                if(last) i+=192;

          }else{

            int cache;

            cache= GET_CACHE(re, &s->gb);

            if(IS_3IV1)

                cache ^= 0xC0000000;

            if (cache&0x80000000) {

                if (cache&0x40000000) {

                    /* third escape */

                    SKIP_CACHE(re, &s->gb, 2);

                    last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                    run=   SHOW_UBITS(re, &s->gb, 6); LAST_SKIP_CACHE(re, &s->gb, 6);

                    SKIP_COUNTER(re, &s->gb, 2+1+6);

                    UPDATE_CACHE(re, &s->gb);

                    if(IS_3IV1){

                        level= SHOW_SBITS(re, &s->gb, 12); LAST_SKIP_BITS(re, &s->gb, 12);

                    }else{

                        if(SHOW_UBITS(re, &s->gb, 1)==0){

                            av_log(s->avctx, AV_LOG_ERROR, "1. marker bit missing in 3. esc\n");

                            return -1;

                        }; SKIP_CACHE(re, &s->gb, 1);

                        level= SHOW_SBITS(re, &s->gb, 12); SKIP_CACHE(re, &s->gb, 12);

                        if(SHOW_UBITS(re, &s->gb, 1)==0){

                            av_log(s->avctx, AV_LOG_ERROR, "2. marker bit missing in 3. esc\n");

                            return -1;

                        }; LAST_SKIP_CACHE(re, &s->gb, 1);

                        SKIP_COUNTER(re, &s->gb, 1+12+1);

                    }

#if 0

                    if(s->error_resilience >= FF_ER_COMPLIANT){

                        const int abs_level= FFABS(level);

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            const int run1= run - rl->max_run[last][abs_level] - 1;

                            if(abs_level <= rl->max_level[last][run]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");

                                return -1;

                            }

                            if(s->error_resilience > FF_ER_COMPLIANT){

                                if(abs_level <= rl->max_level[last][run]*2){

                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");

                                    return -1;

                                }

                                if(run1 >= 0 && abs_level <= rl->max_level[last][run1]){

                                    av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");

                                    return -1;

                                }

                            }

                        }

                    }

#endif

                    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

                    if((unsigned)(level + 2048) > 4095){

                        if(s->error_resilience > FF_ER_COMPLIANT){

                            if(level > 2560 || level<-2560){

                                av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc, qp=%d\n", s->qscale);

                                return -1;

                            }

                        }

                        level= level<0 ? -2048 : 2047;

                    }

                    i+= run + 1;

                    if(last) i+=192;

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 20

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                    i+= run + rl->max_run[run>>7][level/qmul] +1; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 19

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

            }

          }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (intra) {

        if(!s->use_intra_dc_vlc){

            block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);

            i -= i>>31; //if(i == -1) i=0;

        }

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


static void check_watchpoint(int offset, int len, int flags)

{

    CPUState *cpu = current_cpu;

    CPUArchState *env = cpu->env_ptr;

    target_ulong pc, cs_base;

    target_ulong vaddr;

    CPUWatchpoint *wp;

    int cpu_flags;

    if (cpu->watchpoint_hit) {

        /* We re-entered the check after replacing the TB. Now raise

         * the debug interrupt so that is will trigger after the

         * current instruction. */

        cpu_interrupt(cpu, CPU_INTERRUPT_DEBUG);

        return;

    }

    vaddr = (cpu->mem_io_vaddr & TARGET_PAGE_MASK) + offset;

    QTAILQ_FOREACH(wp, &cpu->watchpoints, entry) {

        if (cpu_watchpoint_address_matches(wp, vaddr, len)

            && (wp->flags & flags)) {

            if (flags == BP_MEM_READ) {

                wp->flags |= BP_WATCHPOINT_HIT_READ;

            } else {

                wp->flags |= BP_WATCHPOINT_HIT_WRITE;

            }

            wp->hitaddr = vaddr;

            if (!cpu->watchpoint_hit) {

                cpu->watchpoint_hit = wp;

                tb_check_watchpoint(cpu);

                if (wp->flags & BP_STOP_BEFORE_ACCESS) {

                    cpu->exception_index = EXCP_DEBUG;

                    cpu_loop_exit(cpu);

                } else {

                    cpu_get_tb_cpu_state(env, &pc, &cs_base, &cpu_flags);

                    tb_gen_code(cpu, pc, cs_base, cpu_flags, 1);

                    cpu_resume_from_signal(cpu, NULL);

                }

            }

        } else {

            wp->flags &= ~BP_WATCHPOINT_HIT;

        }

    }

}


int ff_mov_read_esds(AVFormatContext *fc, ByteIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    int tag, len;

    if (fc->nb_streams < 1)

        return 0;

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

    get_be32(pb); /* version + flags */

    len = mp4_read_descr(fc, pb, &tag);

    if (tag == MP4ESDescrTag) {

        get_be16(pb); /* ID */

        get_byte(pb); /* priority */

    } else

        get_be16(pb); /* ID */

    len = mp4_read_descr(fc, pb, &tag);

    if (tag == MP4DecConfigDescrTag) {

        int object_type_id = get_byte(pb);

        get_byte(pb); /* stream type */

        get_be24(pb); /* buffer size db */

        get_be32(pb); /* max bitrate */

        get_be32(pb); /* avg bitrate */

        st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);

        dprintf(fc, "esds object type id 0x%02x\n", object_type_id);

        len = mp4_read_descr(fc, pb, &tag);

        if (tag == MP4DecSpecificDescrTag) {

            dprintf(fc, "Specific MPEG4 header len=%d\n", len);

            if((uint64_t)len > (1<<30))

                return -1;

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

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

            get_buffer(pb, st->codec->extradata, len);

            st->codec->extradata_size = len;

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

                MPEG4AudioConfig cfg;

                ff_mpeg4audio_get_config(&cfg, st->codec->extradata,

                                         st->codec->extradata_size);

                st->codec->channels = cfg.channels;

                if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4

                    st->codec->sample_rate = ff_mpa_freq_tab[cfg.sampling_index];

                else if (cfg.ext_sample_rate)

                    st->codec->sample_rate = cfg.ext_sample_rate;

                else

                    st->codec->sample_rate = cfg.sample_rate;

                dprintf(fc, "mp4a config channels %d obj %d ext obj %d "

                        "sample rate %d ext sample rate %d\n", st->codec->channels,

                        cfg.object_type, cfg.ext_object_type,

                        cfg.sample_rate, cfg.ext_sample_rate);

                if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,

                                                            cfg.object_type)))

                    st->codec->codec_id = CODEC_ID_AAC;

            }

        }

    }

    return 0;

}


static inline void gen_op_arith_subf(DisasContext *ctx, TCGv ret, TCGv arg1,

                                     TCGv arg2, bool add_ca, bool compute_ca,

                                     bool compute_ov, bool compute_rc0)

{

    TCGv t0 = ret;

    if (compute_ca || compute_ov) {

        t0 = tcg_temp_new();

    }

    if (compute_ca) {

        /* dest = ~arg1 + arg2 [+ ca].  */

        if (NARROW_MODE(ctx)) {

            /* Caution: a non-obvious corner case of the spec is that we

               must produce the *entire* 64-bit addition, but produce the

               carry into bit 32.  */

            TCGv inv1 = tcg_temp_new();

            TCGv t1 = tcg_temp_new();

            tcg_gen_not_tl(inv1, arg1);

            if (add_ca) {

                tcg_gen_add_tl(t0, arg2, cpu_ca);

            } else {

                tcg_gen_addi_tl(t0, arg2, 1);

            }

            tcg_gen_xor_tl(t1, arg2, inv1);         /* add without carry */

            tcg_gen_add_tl(t0, t0, inv1);

            tcg_gen_xor_tl(cpu_ca, t0, t1);         /* bits changes w/ carry */

            tcg_temp_free(t1);

            tcg_gen_shri_tl(cpu_ca, cpu_ca, 32);    /* extract bit 32 */

            tcg_gen_andi_tl(cpu_ca, cpu_ca, 1);

        } else if (add_ca) {

            TCGv zero, inv1 = tcg_temp_new();

            tcg_gen_not_tl(inv1, arg1);

            zero = tcg_const_tl(0);

            tcg_gen_add2_tl(t0, cpu_ca, arg2, zero, cpu_ca, zero);

            tcg_gen_add2_tl(t0, cpu_ca, t0, cpu_ca, inv1, zero);

            tcg_temp_free(zero);

        } else {

            tcg_gen_setcond_tl(TCG_COND_GEU, cpu_ca, arg2, arg1);

            tcg_gen_sub_tl(t0, arg2, arg1);

        }

    } else if (add_ca) {

        /* Since we're ignoring carry-out, we can simplify the

           standard ~arg1 + arg2 + ca to arg2 - arg1 + ca - 1.  */

        tcg_gen_sub_tl(t0, arg2, arg1);

        tcg_gen_add_tl(t0, t0, cpu_ca);

        tcg_gen_subi_tl(t0, t0, 1);

    } else {

        tcg_gen_sub_tl(t0, arg2, arg1);

    }

    if (compute_ov) {

        gen_op_arith_compute_ov(ctx, t0, arg1, arg2, 1);

    }

    if (unlikely(compute_rc0)) {

        gen_set_Rc0(ctx, t0);

    }

    if (!TCGV_EQUAL(t0, ret)) {

        tcg_gen_mov_tl(ret, t0);

        tcg_temp_free(t0);

    }

}


static int64_t coroutine_fn vpc_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)

{

    BDRVVPCState *s = bs->opaque;

    VHDFooter *footer = (VHDFooter*) s->footer_buf;

    int64_t start, offset;

    bool allocated;

    int64_t ret;

    int n;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        *pnum = nb_sectors;

        *file = bs->file->bs;

        return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID |

               (sector_num << BDRV_SECTOR_BITS);

    }

    qemu_co_mutex_lock(&s->lock);

    offset = get_image_offset(bs, sector_num << BDRV_SECTOR_BITS, false);

    start = offset;

    allocated = (offset != -1);

    *pnum = 0;

    ret = 0;

    do {

        /* All sectors in a block are contiguous (without using the bitmap) */

        n = ROUND_UP(sector_num + 1, s->block_size / BDRV_SECTOR_SIZE)

          - sector_num;

        n = MIN(n, nb_sectors);

        *pnum += n;

        sector_num += n;

        nb_sectors -= n;

        /* *pnum can't be greater than one block for allocated

         * sectors since there is always a bitmap in between. */

        if (allocated) {

            *file = bs->file->bs;

            ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;

            break;

        }

        if (nb_sectors == 0) {

            break;

        }

        offset = get_image_offset(bs, sector_num << BDRV_SECTOR_BITS, false);

    } while (offset == -1);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


struct pxa2xx_mmci_s *pxa2xx_mmci_init(target_phys_addr_t base,

                qemu_irq irq, void *dma)

{

    int iomemtype;

    struct pxa2xx_mmci_s *s;

    s = (struct pxa2xx_mmci_s *) qemu_mallocz(sizeof(struct pxa2xx_mmci_s));

    s->base = base;

    s->irq = irq;

    s->dma = dma;

    iomemtype = cpu_register_io_memory(0, pxa2xx_mmci_readfn,

                    pxa2xx_mmci_writefn, s);

    cpu_register_physical_memory(base, 0x000fffff, iomemtype);

    /* Instantiate the actual storage */

    s->card = sd_init(sd_bdrv);

    register_savevm("pxa2xx_mmci", 0, 0,

                    pxa2xx_mmci_save, pxa2xx_mmci_load, s);

    return s;

}


void kvmppc_set_papr(CPUPPCState *env)

{

    struct kvm_enable_cap cap = {};

    struct kvm_one_reg reg = {};

    struct kvm_sregs sregs = {};

    int ret;

    uint64_t hior = env->spr[SPR_HIOR];

    cap.cap = KVM_CAP_PPC_PAPR;

    ret = kvm_vcpu_ioctl(env, KVM_ENABLE_CAP, &cap);

    if (ret) {

        goto fail;

    }

    /*

     * XXX We set HIOR here. It really should be a qdev property of

     *     the CPU node, but we don't have CPUs converted to qdev yet.

     *

     *     Once we have qdev CPUs, move HIOR to a qdev property and

     *     remove this chunk.

     */

    reg.id = KVM_REG_PPC_HIOR;

    reg.addr = (uintptr_t)&hior;

    ret = kvm_vcpu_ioctl(env, KVM_SET_ONE_REG, &reg);

    if (ret) {

        fprintf(stderr, "Couldn't set HIOR. Maybe you're running an old \n"

                        "kernel with support for HV KVM but no PAPR PR \n"

                        "KVM in which case things will work. If they don't \n"

                        "please update your host kernel!\n");

    }

    /* Set SDR1 so kernel space finds the HTAB */

    ret = kvm_vcpu_ioctl(env, KVM_GET_SREGS, &sregs);

    if (ret) {

        goto fail;

    }

    sregs.u.s.sdr1 = env->spr[SPR_SDR1];

    ret = kvm_vcpu_ioctl(env, KVM_SET_SREGS, &sregs);

    if (ret) {

        goto fail;

    }

    return;

fail:

    cpu_abort(env, "This KVM version does not support PAPR\n");

}


static void send_ext_key_event_ack(VncState *vs)

{

    vnc_lock_output(vs);

    vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);

    vnc_write_u8(vs, 0);

    vnc_write_u16(vs, 1);

    vnc_framebuffer_update(vs, 0, 0,

                           surface_width(vs->vd->ds),

                           surface_height(vs->vd->ds),

                           VNC_ENCODING_EXT_KEY_EVENT);

    vnc_unlock_output(vs);

    vnc_flush(vs);

}


static inline void RENAME(rgb24to15)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

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

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

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

	mm_end = end - 11;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		d += 4;

		s += 12;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int b= *s++;

		const int g= *s++;

		const int r= *s++;

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

	}

}


void *HELPER(lookup_tb_ptr)(CPUArchState *env)

{

    CPUState *cpu = ENV_GET_CPU(env);

    TranslationBlock *tb;

    target_ulong cs_base, pc;

    uint32_t flags, hash;

    cpu_get_tb_cpu_state(env, &pc, &cs_base, &flags);

    hash = tb_jmp_cache_hash_func(pc);

    tb = atomic_rcu_read(&cpu->tb_jmp_cache[hash]);

    if (unlikely(!(tb

                   && tb->pc == pc

                   && tb->cs_base == cs_base

                   && tb->flags == flags

                   && tb->trace_vcpu_dstate == *cpu->trace_dstate))) {

        tb = tb_htable_lookup(cpu, pc, cs_base, flags);

        if (!tb) {

            return tcg_ctx.code_gen_epilogue;

        }

        atomic_set(&cpu->tb_jmp_cache[hash], tb);

    }

    qemu_log_mask_and_addr(CPU_LOG_EXEC, pc,

                           "Chain %p [%d: " TARGET_FMT_lx "] %s\n",

                           tb->tc_ptr, cpu->cpu_index, pc,

                           lookup_symbol(pc));

    return tb->tc_ptr;

}


void ff_mpeg_draw_horiz_band(MpegEncContext *s, int y, int h)

{

    ff_draw_horiz_band(s->avctx, &s->current_picture.f,

                       &s->last_picture.f, y, h, s->picture_structure,

                       s->first_field, s->low_delay);

}


int load_image_targphys(const char *filename,

			target_phys_addr_t addr, int max_sz)

{

    int size;

    size = get_image_size(filename);

    if (size > 0)

        rom_add_file_fixed(filename, addr, -1);

    return size;

}


static void ccid_handle_bulk_out(USBCCIDState *s, USBPacket *p)

{

    CCID_Header *ccid_header;

    if (p->iov.size + s->bulk_out_pos > BULK_OUT_DATA_SIZE) {

        goto err;

    }

    usb_packet_copy(p, s->bulk_out_data + s->bulk_out_pos, p->iov.size);

    s->bulk_out_pos += p->iov.size;

    if (s->bulk_out_pos < 10) {

        DPRINTF(s, 1, "%s: header incomplete\n", __func__);

        goto err;

    }

    ccid_header = (CCID_Header *)s->bulk_out_data;

    if (p->iov.size == CCID_MAX_PACKET_SIZE) {

        DPRINTF(s, D_VERBOSE,

            "usb-ccid: bulk_in: expecting more packets (%zd/%d)\n",

            p->iov.size, ccid_header->dwLength);

        return;

    }

    DPRINTF(s, D_MORE_INFO, "%s %x %s\n", __func__,

            ccid_header->bMessageType,

            ccid_message_type_to_str(ccid_header->bMessageType));

    switch (ccid_header->bMessageType) {

    case CCID_MESSAGE_TYPE_PC_to_RDR_GetSlotStatus:

        ccid_write_slot_status(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOn:

        DPRINTF(s, 1, "%s: PowerOn: %d\n", __func__,

                ((CCID_IccPowerOn *)(ccid_header))->bPowerSelect);

        s->powered = true;

        if (!ccid_card_inserted(s)) {

            ccid_report_error_failed(s, ERROR_ICC_MUTE);

        }

        /* atr is written regardless of error. */

        ccid_write_data_block_atr(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_IccPowerOff:

        ccid_reset_error_status(s);

        s->powered = false;

        ccid_write_slot_status(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_XfrBlock:

        ccid_on_apdu_from_guest(s, (CCID_XferBlock *)s->bulk_out_data);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_SetParameters:

        ccid_reset_error_status(s);

        ccid_set_parameters(s, ccid_header);

        ccid_write_parameters(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_ResetParameters:

        ccid_reset_error_status(s);

        ccid_reset_parameters(s);

        ccid_write_parameters(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_GetParameters:

        ccid_reset_error_status(s);

        ccid_write_parameters(s, ccid_header);

        break;

    case CCID_MESSAGE_TYPE_PC_to_RDR_Mechanical:

        ccid_report_error_failed(s, 0);

        ccid_write_slot_status(s, ccid_header);

        break;

    default:

        DPRINTF(s, 1,

                "handle_data: ERROR: unhandled message type %Xh\n",

                ccid_header->bMessageType);

        /*

         * The caller is expecting the device to respond, tell it we

         * don't support the operation.

         */

        ccid_report_error_failed(s, ERROR_CMD_NOT_SUPPORTED);

        ccid_write_slot_status(s, ccid_header);

        break;

    }

    s->bulk_out_pos = 0;

    return;

err:

    p->status = USB_RET_STALL;

    s->bulk_out_pos = 0;

    return;

}


static av_cold int vcr1_decode_init(AVCodecContext *avctx)
{
    avctx->pix_fmt = AV_PIX_FMT_YUV410P;
    return 0;


static void *sparc32_dma_init(target_phys_addr_t daddr, qemu_irq parent_irq,

                              void *iommu, qemu_irq *dev_irq)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "sparc32_dma");

    qdev_prop_set_ptr(dev, "iommu_opaque", iommu);

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_connect_irq(s, 0, parent_irq);

    *dev_irq = qdev_get_gpio_in(dev, 0);

    sysbus_mmio_map(s, 0, daddr);

    return s;

}


int monitor_read_block_device_key(Monitor *mon, const char *device,

                                  BlockCompletionFunc *completion_cb,

                                  void *opaque)

{

    Error *err = NULL;

    BlockBackend *blk;

    blk = blk_by_name(device);

    if (!blk) {

        monitor_printf(mon, "Device not found %s\n", device);

        return -1;

    }

    if (!blk_bs(blk)) {

        monitor_printf(mon, "Device '%s' has no medium\n", device);

        return -1;

    }

    bdrv_add_key(blk_bs(blk), NULL, &err);

    if (err) {

        error_free(err);

        return monitor_read_bdrv_key_start(mon, blk_bs(blk), completion_cb, opaque);

    }

    if (completion_cb) {

        completion_cb(opaque, 0);

    }

    return 0;

}


static void migrate_set_state(MigrationState *s, int old_state, int new_state)

{

    if (atomic_cmpxchg(&s->state, old_state, new_state) == new_state) {

        trace_migrate_set_state(new_state);

    }

}