int ff_celp_lp_synthesis_filter(int16_t *out,

                                const int16_t* filter_coeffs,

                                const int16_t* in,

                                int buffer_length,

                                int filter_length,

                                int stop_on_overflow,

                                int rounder)

{

    int i,n;

    // Avoids a +1 in the inner loop.

    filter_length++;

    for (n = 0; n < buffer_length; n++) {

        int sum = rounder;

        for (i = 1; i < filter_length; i++)

            sum -= filter_coeffs[i-1] * out[n-i];

        sum = (sum >> 12) + in[n];

        if (sum + 0x8000 > 0xFFFFU) {

            if (stop_on_overflow)

                return 1;

            sum = (sum >> 31) ^ 32767;

        }

        out[n] = sum;

    }

    return 0;

}


ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,

                    AVStream *st, RMStream *ast, int len, AVPacket *pkt,

                    int *seq, int flags, int64_t timestamp)

{

    RMDemuxContext *rm = s->priv_data;

    int ret;

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

        rm->current_stream= st->id;

        ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, &timestamp);

        if(ret)

            return ret < 0 ? ret : -1; //got partial frame or error

    } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

        if ((ast->deint_id == DEINT_ID_GENR) ||

            (ast->deint_id == DEINT_ID_INT4) ||

            (ast->deint_id == DEINT_ID_SIPR)) {

            int x;

            int sps = ast->sub_packet_size;

            int cfs = ast->coded_framesize;

            int h = ast->sub_packet_h;

            int y = ast->sub_packet_cnt;

            int w = ast->audio_framesize;

            if (flags & 2)

                y = ast->sub_packet_cnt = 0;

            if (!y)

                ast->audiotimestamp = timestamp;

            switch (ast->deint_id) {

                case DEINT_ID_INT4:

                    for (x = 0; x < h/2; x++)

                        readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs);

                    break;

                case DEINT_ID_GENR:

                    for (x = 0; x < w/sps; x++)

                        readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);

                    break;

                case DEINT_ID_SIPR:

                    readfull(s, pb, ast->pkt.data + y * w, w);

                    break;

            }

            if (++(ast->sub_packet_cnt) < h)

                return -1;

            if (ast->deint_id == DEINT_ID_SIPR)

                ff_rm_reorder_sipr_data(ast->pkt.data, h, w);

             ast->sub_packet_cnt = 0;

             rm->audio_stream_num = st->index;

             rm->audio_pkt_cnt = h * w / st->codec->block_align;

        } else if ((ast->deint_id == DEINT_ID_VBRF) ||

                   (ast->deint_id == DEINT_ID_VBRS)) {

            int x;

            rm->audio_stream_num = st->index;

            ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4;

            if (ast->sub_packet_cnt) {

                for (x = 0; x < ast->sub_packet_cnt; x++)

                    ast->sub_packet_lengths[x] = avio_rb16(pb);

                rm->audio_pkt_cnt = ast->sub_packet_cnt;

                ast->audiotimestamp = timestamp;

            } else

                return -1;

        } else {

            av_get_packet(pb, pkt, len);

            rm_ac3_swap_bytes(st, pkt);

        }

    } else

        av_get_packet(pb, pkt, len);

    pkt->stream_index = st->index;

#if 0

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

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

            int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);

            av_log(s, AV_LOG_DEBUG, "%d %"PRId64" %d\n", *timestamp, *timestamp*512LL/25, seq);

            seq |= (timestamp&~0x3FFF);

            if(seq - timestamp >  0x2000) seq -= 0x4000;

            if(seq - timestamp < -0x2000) seq += 0x4000;

        }

    }

#endif

    pkt->pts = timestamp;

    if (flags & 2)

        pkt->flags |= AV_PKT_FLAG_KEY;

    return st->codec->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;

}


static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)

{

    ALSSpecificConfig *sconf = &ctx->sconf;

    AVCodecContext *avctx    = ctx->avctx;

    GetBitContext *gb        = &ctx->gb;

    unsigned int k;

    unsigned int s[8];

    unsigned int sx[8];

    unsigned int sub_blocks, log2_sub_blocks, sb_length;

    unsigned int start      = 0;

    unsigned int opt_order;

    int          sb;

    int32_t      *quant_cof = bd->quant_cof;

    int32_t      *current_res;

    // ensure variable block decoding by reusing this field

    bd->const_block = 0;

    bd->opt_order   = 1;

    bd->js_blocks   = get_bits1(gb);

    opt_order       = bd->opt_order;

    // determine the number of subblocks for entropy decoding

    if (!sconf->bgmc && !sconf->sb_part) {

        log2_sub_blocks = 0;

    } else {

        if (sconf->bgmc && sconf->sb_part)

            log2_sub_blocks = get_bits(gb, 2);

        else

            log2_sub_blocks = 2 * get_bits1(gb);

    }

    sub_blocks = 1 << log2_sub_blocks;

    // do not continue in case of a damaged stream since

    // block_length must be evenly divisible by sub_blocks

    if (bd->block_length & (sub_blocks - 1)) {

        av_log(avctx, AV_LOG_WARNING,

               "Block length is not evenly divisible by the number of subblocks.\n");

        return -1;

    }

    sb_length = bd->block_length >> log2_sub_blocks;

    if (sconf->bgmc) {

        s[0] = get_bits(gb, 8 + (sconf->resolution > 1));

        for (k = 1; k < sub_blocks; k++)

            s[k] = s[k - 1] + decode_rice(gb, 2);

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

            sx[k]   = s[k] & 0x0F;

            s [k] >>= 4;

        }

    } else {

        s[0] = get_bits(gb, 4 + (sconf->resolution > 1));

        for (k = 1; k < sub_blocks; k++)

            s[k] = s[k - 1] + decode_rice(gb, 0);

    }

    if (get_bits1(gb))

        bd->shift_lsbs = get_bits(gb, 4) + 1;

    bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || bd->shift_lsbs;

    if (!sconf->rlslms) {

        if (sconf->adapt_order) {

            int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,

                                                2, sconf->max_order + 1));

            bd->opt_order        = get_bits(gb, opt_order_length);

        } else {

            bd->opt_order = sconf->max_order;

        }

        opt_order = bd->opt_order;

        if (opt_order) {

            int add_base;

            if (sconf->coef_table == 3) {

                add_base = 0x7F;

                // read coefficient 0

                quant_cof[0] = 32 * parcor_scaled_values[get_bits(gb, 7)];

                // read coefficient 1

                if (opt_order > 1)

                    quant_cof[1] = -32 * parcor_scaled_values[get_bits(gb, 7)];

                // read coefficients 2 to opt_order

                for (k = 2; k < opt_order; k++)

                    quant_cof[k] = get_bits(gb, 7);

            } else {

                int k_max;

                add_base = 1;

                // read coefficient 0 to 19

                k_max = FFMIN(opt_order, 20);

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

                    int rice_param = parcor_rice_table[sconf->coef_table][k][1];

                    int offset     = parcor_rice_table[sconf->coef_table][k][0];

                    quant_cof[k] = decode_rice(gb, rice_param) + offset;

                }

                // read coefficients 20 to 126

                k_max = FFMIN(opt_order, 127);

                for (; k < k_max; k++)

                    quant_cof[k] = decode_rice(gb, 2) + (k & 1);

                // read coefficients 127 to opt_order

                for (; k < opt_order; k++)

                    quant_cof[k] = decode_rice(gb, 1);

                quant_cof[0] = 32 * parcor_scaled_values[quant_cof[0] + 64];

                if (opt_order > 1)

                    quant_cof[1] = -32 * parcor_scaled_values[quant_cof[1] + 64];

            }

            for (k = 2; k < opt_order; k++)

                quant_cof[k] = (quant_cof[k] << 14) + (add_base << 13);

        }

    }

    // read LTP gain and lag values

    if (sconf->long_term_prediction) {

        *bd->use_ltp = get_bits1(gb);

        if (*bd->use_ltp) {

            bd->ltp_gain[0]   = decode_rice(gb, 1) << 3;

            bd->ltp_gain[1]   = decode_rice(gb, 2) << 3;

            bd->ltp_gain[2]   = ltp_gain_values[get_unary(gb, 0, 4)][get_bits(gb, 2)];

            bd->ltp_gain[3]   = decode_rice(gb, 2) << 3;

            bd->ltp_gain[4]   = decode_rice(gb, 1) << 3;

            *bd->ltp_lag      = get_bits(gb, ctx->ltp_lag_length);

            *bd->ltp_lag     += FFMAX(4, opt_order + 1);

        }

    }

    // read first value and residuals in case of a random access block

    if (bd->ra_block) {

        if (opt_order)

            bd->raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);

        if (opt_order > 1)

            bd->raw_samples[1] = decode_rice(gb, s[0] + 3);

        if (opt_order > 2)

            bd->raw_samples[2] = decode_rice(gb, s[0] + 1);

        start = FFMIN(opt_order, 3);

    }

    // read all residuals

    if (sconf->bgmc) {

        unsigned int delta[sub_blocks];

        unsigned int k    [sub_blocks];

        unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);

        unsigned int i = start;

        // read most significant bits

        unsigned int high;

        unsigned int low;

        unsigned int value;

        ff_bgmc_decode_init(gb, &high, &low, &value);

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, i = 0) {

            k    [sb] = s[sb] > b ? s[sb] - b : 0;

            delta[sb] = 5 - s[sb] + k[sb];

            ff_bgmc_decode(gb, sb_length, current_res,

                        delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);

            current_res += sb_length;

        }

        ff_bgmc_decode_end(gb);

        // read least significant bits and tails

        i = start;

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, i = 0) {

            unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];

            unsigned int cur_k         = k[sb];

            unsigned int cur_s         = s[sb];

            for (; i < sb_length; i++) {

                int32_t res = *current_res;

                if (res == cur_tail_code) {

                    unsigned int max_msb =   (2 + (sx[sb] > 2) + (sx[sb] > 10))

                                          << (5 - delta[sb]);

                    res = decode_rice(gb, cur_s);

                    if (res >= 0) {

                        res += (max_msb    ) << cur_k;

                    } else {

                        res -= (max_msb - 1) << cur_k;

                    }

                } else {

                    if (res > cur_tail_code)

                        res--;

                    if (res & 1)

                        res = -res;

                    res >>= 1;

                    if (cur_k) {

                        res <<= cur_k;

                        res  |= get_bits_long(gb, cur_k);

                    }

                }

                *current_res++ = res;

            }

        }

    } else {

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, start = 0)

            for (; start < sb_length; start++)

                *current_res++ = decode_rice(gb, s[sb]);

     }

    if (!sconf->mc_coding || ctx->js_switch)

        align_get_bits(gb);

    return 0;

}


static inline void RENAME(yuv2packed1)(SwsContext *c, const uint16_t *buf0, const uint16_t *uvbuf0, const uint16_t *uvbuf1,

                          const uint16_t *abuf0, uint8_t *dest, int dstW, int uvalpha, enum PixelFormat dstFormat, int flags, int y)

{

    const int yalpha1=0;

    int i;

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    const int yalpha= 4096; //FIXME ...

    if (flags&SWS_FULL_CHR_H_INT) {

        c->yuv2packed2(c, buf0, buf0, uvbuf0, uvbuf1, abuf0, abuf0, dest, dstW, 0, uvalpha, y);

        return;

    }

#if COMPILE_TEMPLATE_MMX

    if(!(flags & SWS_BITEXACT)) {

        if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

            switch(dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    __asm__ volatile(

                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                        "push %%"REG_BP"                        \n\t"

                        YSCALEYUV2RGB1(%%REGBP, %5)

                        YSCALEYUV2RGB1_ALPHA(%%REGBP)

                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                        "pop %%"REG_BP"                         \n\t"

                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                        "a" (&c->redDither)

                    );

                } else {

                    __asm__ volatile(

                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                        "push %%"REG_BP"                        \n\t"

                        YSCALEYUV2RGB1(%%REGBP, %5)

                        "pcmpeqd %%mm7, %%mm7                   \n\t"

                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                        "pop %%"REG_BP"                         \n\t"

                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                        "a" (&c->redDither)

                    );

                }

                return;

            case PIX_FMT_BGR24:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1(%%REGBP, %5)

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

                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_RGB555:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1(%%REGBP, %5)

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

                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_RGB565:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1(%%REGBP, %5)

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

                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_YUYV422:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2PACKED1(%%REGBP, %5)

                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            }

        } else {

            switch(dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    __asm__ volatile(

                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                        "push %%"REG_BP"                        \n\t"

                        YSCALEYUV2RGB1b(%%REGBP, %5)

                        YSCALEYUV2RGB1_ALPHA(%%REGBP)

                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                        "pop %%"REG_BP"                         \n\t"

                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                        :: "c" (buf0), "d" (abuf0), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                        "a" (&c->redDither)

                    );

                } else {

                    __asm__ volatile(

                        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                        "push %%"REG_BP"                        \n\t"

                        YSCALEYUV2RGB1b(%%REGBP, %5)

                        "pcmpeqd %%mm7, %%mm7                   \n\t"

                        WRITEBGR32(%%REGb, 8280(%5), %%REGBP, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                        "pop %%"REG_BP"                         \n\t"

                        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                        :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                        "a" (&c->redDither)

                    );

                }

                return;

            case PIX_FMT_BGR24:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1b(%%REGBP, %5)

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

                    WRITEBGR24(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_RGB555:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1b(%%REGBP, %5)

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

                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                    WRITERGB15(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_RGB565:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2RGB1b(%%REGBP, %5)

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

                    /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                    "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

                    "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

                    "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

                    WRITERGB16(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            case PIX_FMT_YUYV422:

                __asm__ volatile(

                    "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

                    "push %%"REG_BP"                        \n\t"

                    YSCALEYUV2PACKED1b(%%REGBP, %5)

                    WRITEYUY2(%%REGb, 8280(%5), %%REGBP)

                    "pop %%"REG_BP"                         \n\t"

                    "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

                    :: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

                    "a" (&c->redDither)

                );

                return;

            }

        }

    }

#endif /* COMPILE_TEMPLATE_MMX */

    if (uvalpha < 2048) {

        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1_C, YSCALE_YUV_2_PACKED1_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)

    } else {

        YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1B_C, YSCALE_YUV_2_PACKED1B_C(void,0), YSCALE_YUV_2_GRAY16_1_C, YSCALE_YUV_2_MONO2_C)

    }

}


static int flic_read_header(AVFormatContext *s,

                            AVFormatParameters *ap)

{

    FlicDemuxContext *flic = s->priv_data;

    ByteIOContext *pb = &s->pb;

    unsigned char header[FLIC_HEADER_SIZE];

    AVStream *st;

    int speed;

    int magic_number;

    flic->pts = 0;

    /* load the whole header and pull out the width and height */

    if (get_buffer(pb, header, FLIC_HEADER_SIZE) != FLIC_HEADER_SIZE)

        return AVERROR(EIO);

    magic_number = AV_RL16(&header[4]);

    speed = AV_RL32(&header[0x10]);

    /* initialize the decoder streams */

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    flic->video_stream_index = st->index;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_FLIC;

    st->codec->codec_tag = 0;  /* no fourcc */

    st->codec->width = AV_RL16(&header[0x08]);

    st->codec->height = AV_RL16(&header[0x0A]);

    if (!st->codec->width || !st->codec->height)

        return AVERROR_INVALIDDATA;

    /* send over the whole 128-byte FLIC header */

    st->codec->extradata_size = FLIC_HEADER_SIZE;

    st->codec->extradata = av_malloc(FLIC_HEADER_SIZE);

    memcpy(st->codec->extradata, header, FLIC_HEADER_SIZE);

    av_set_pts_info(st, 33, 1, 90000);

    /* Time to figure out the framerate: If there is a FLIC chunk magic

     * number at offset 0x10, assume this is from the Bullfrog game,

     * Magic Carpet. */

    if (AV_RL16(&header[0x10]) == FLIC_CHUNK_MAGIC_1) {

        flic->frame_pts_inc = FLIC_MC_PTS_INC;

        /* rewind the stream since the first chunk is at offset 12 */

        url_fseek(pb, 12, SEEK_SET);

        /* send over abbreviated FLIC header chunk */

        av_free(st->codec->extradata);

        st->codec->extradata_size = 12;

        st->codec->extradata = av_malloc(12);

        memcpy(st->codec->extradata, header, 12);

    } else if (magic_number == FLIC_FILE_MAGIC_1) {

        /*

         * in this case, the speed (n) is number of 1/70s ticks between frames:

         *

         *    pts        n * frame #

         *  --------  =  -----------  => pts = n * (90000/70) * frame #

         *   90000           70

         *

         *  therefore, the frame pts increment = n * 1285.7

         */

        flic->frame_pts_inc = speed * 1285.7;

    } else if ((magic_number == FLIC_FILE_MAGIC_2) ||

               (magic_number == FLIC_FILE_MAGIC_3)) {

        /*

         * in this case, the speed (n) is number of milliseconds between frames:

         *

         *    pts        n * frame #

         *  --------  =  -----------  => pts = n * 90 * frame #

         *   90000          1000

         *

         *  therefore, the frame pts increment = n * 90

         */

        flic->frame_pts_inc = speed * 90;

    } else {

        av_log(s, AV_LOG_INFO, "Invalid or unsupported magic chunk in file\n");

        return AVERROR_INVALIDDATA;

    }

    if (flic->frame_pts_inc == 0)

        flic->frame_pts_inc = FLIC_DEFAULT_PTS_INC;

    return 0;

}


static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)

{

    char val_str[128];

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

    writer_print_section_header(w, SECTION_ID_FORMAT);

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

    print_int("nb_streams",       fmt_ctx->nb_streams);

    print_int("nb_programs",      fmt_ctx->nb_programs);

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

    if (!do_bitexact) {

        if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);

        else                             print_str_opt("format_long_name", "unknown");

    }

    print_time("start_time",      fmt_ctx->start_time, &AV_TIME_BASE_Q);

    print_time("duration",        fmt_ctx->duration,   &AV_TIME_BASE_Q);

    if (size >= 0) print_val    ("size", size, unit_byte_str);

    else           print_str_opt("size", "N/A");

    if (fmt_ctx->bit_rate > 0) print_val    ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);

    else                       print_str_opt("bit_rate", "N/A");

    print_int("probe_score", av_format_get_probe_score(fmt_ctx));

    show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);

    writer_print_section_footer(w);

    fflush(stdout);

}


static void flush_encoders(OutputStream *ost_table, int nb_ostreams)

{

    int i, ret;

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

        OutputStream   *ost = &ost_table[i];

        AVCodecContext *enc = ost->st->codec;

        AVFormatContext *os = output_files[ost->file_index].ctx;

        if (!ost->encoding_needed)

            continue;

        if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)

            continue;

        if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))

            continue;

        for(;;) {

            AVPacket pkt;

            int fifo_bytes;

            av_init_packet(&pkt);

            pkt.stream_index= ost->index;

            switch (ost->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                fifo_bytes = av_fifo_size(ost->fifo);

                ret = 0;

                /* encode any samples remaining in fifo */

                if (fifo_bytes > 0) {

                    int osize = av_get_bytes_per_sample(enc->sample_fmt);

                    int fs_tmp = enc->frame_size;

                    av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);

                    if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {

                        enc->frame_size = fifo_bytes / (osize * enc->channels);

                    } else { /* pad */

                        int frame_bytes = enc->frame_size*osize*enc->channels;

                        if (allocated_audio_buf_size < frame_bytes)

                            exit_program(1);

                        generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);

                    }

                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);

                    pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,

                                              ost->st->time_base.num, enc->sample_rate);

                    enc->frame_size = fs_tmp;

                }

                if (ret <= 0) {

                    ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);

                }

                if (ret < 0) {

                    av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");

                    exit_program(1);

                }

                audio_size += ret;

                pkt.flags |= AV_PKT_FLAG_KEY;

                break;

            case AVMEDIA_TYPE_VIDEO:

                ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);

                if (ret < 0) {

                    av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

                    exit_program(1);

                }

                video_size += ret;

                if(enc->coded_frame && enc->coded_frame->key_frame)

                    pkt.flags |= AV_PKT_FLAG_KEY;

                if (ost->logfile && enc->stats_out) {

                    fprintf(ost->logfile, "%s", enc->stats_out);

                }

                break;

            default:

                ret=-1;

            }

            if (ret <= 0)

                break;

            pkt.data = bit_buffer;

            pkt.size = ret;

            if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)

                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

            write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);

        }

    }

}


static int mkv_write_chapters(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *pb = s->pb;

    ebml_master chapters, editionentry;

    AVRational scale = {1, 1E9};

    int i, ret;

    if (!s->nb_chapters || mkv->wrote_chapters)

        return 0;

    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CHAPTERS, avio_tell(pb));

    if (ret < 0) return ret;

    chapters     = start_ebml_master(pb, MATROSKA_ID_CHAPTERS    , 0);

    editionentry = start_ebml_master(pb, MATROSKA_ID_EDITIONENTRY, 0);

    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGDEFAULT, 1);

    put_ebml_uint(pb, MATROSKA_ID_EDITIONFLAGHIDDEN , 0);

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

        ebml_master chapteratom, chapterdisplay;

        AVChapter *c     = s->chapters[i];

        AVDictionaryEntry *t = NULL;

        chapteratom = start_ebml_master(pb, MATROSKA_ID_CHAPTERATOM, 0);

        put_ebml_uint(pb, MATROSKA_ID_CHAPTERUID, c->id);

        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMESTART,

                      av_rescale_q(c->start, c->time_base, scale));

        put_ebml_uint(pb, MATROSKA_ID_CHAPTERTIMEEND,

                      av_rescale_q(c->end,   c->time_base, scale));

        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGHIDDEN , 0);

        put_ebml_uint(pb, MATROSKA_ID_CHAPTERFLAGENABLED, 1);

        if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {

            chapterdisplay = start_ebml_master(pb, MATROSKA_ID_CHAPTERDISPLAY, 0);

            put_ebml_string(pb, MATROSKA_ID_CHAPSTRING, t->value);

            put_ebml_string(pb, MATROSKA_ID_CHAPLANG  , "und");

            end_ebml_master(pb, chapterdisplay);

        }

        end_ebml_master(pb, chapteratom);

    }

    end_ebml_master(pb, editionentry);

    end_ebml_master(pb, chapters);

    mkv->wrote_chapters = 1;

    return 0;

}


static uint64_t ppc_hash64_page_shift(ppc_slb_t *slb)

{

    uint64_t epnshift;

    /* Page size according to the SLB, which we use to generate the

     * EPN for hash table lookup..  When we implement more recent MMU

     * extensions this might be different from the actual page size

     * encoded in the PTE */

    if ((slb->vsid & SLB_VSID_LLP_MASK) == SLB_VSID_4K) {

        epnshift = TARGET_PAGE_BITS;

    } else if ((slb->vsid & SLB_VSID_LLP_MASK) == SLB_VSID_64K) {

        epnshift = TARGET_PAGE_BITS_64K;

    } else {

        epnshift = TARGET_PAGE_BITS_16M;

    }

    return epnshift;

}


static av_always_inline void filter_mb_row(AVCodecContext *avctx, void *tdata,

                              int jobnr, int threadnr, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

    VP8ThreadData *td = &s->thread_data[threadnr];

    int mb_x, mb_y = td->thread_mb_pos >> 16, num_jobs = s->num_jobs;

    AVFrame *curframe = s->curframe->tf.f;

    VP8Macroblock *mb;

    VP8ThreadData *prev_td, *next_td;

    uint8_t *dst[3] = {

        curframe->data[0] + 16 * mb_y * s->linesize,

        curframe->data[1] +  8 * mb_y * s->uvlinesize,

        curframe->data[2] +  8 * mb_y * s->uvlinesize

    };

    if (s->mb_layout == 1)

        mb = s->macroblocks_base + ((s->mb_width + 1) * (mb_y + 1) + 1);

    else

        mb = s->macroblocks + (s->mb_height - mb_y - 1) * 2;

    if (mb_y == 0)

        prev_td = td;

    else

        prev_td = &s->thread_data[(jobnr + num_jobs - 1) % num_jobs];

    if (mb_y == s->mb_height - 1)

        next_td = td;

    else

        next_td = &s->thread_data[(jobnr + 1) % num_jobs];

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

        VP8FilterStrength *f = &td->filter_strength[mb_x];

        if (prev_td != td)

            check_thread_pos(td, prev_td,

                             (mb_x + 1) + (s->mb_width + 3), mb_y - 1);

        if (next_td != td)

            if (next_td != &s->thread_data[0])

                check_thread_pos(td, next_td, mb_x + 1, mb_y + 1);

        if (num_jobs == 1) {

            if (s->filter.simple)

                backup_mb_border(s->top_border[mb_x + 1], dst[0],

                                 NULL, NULL, s->linesize, 0, 1);

            else

                backup_mb_border(s->top_border[mb_x + 1], dst[0],

                                 dst[1], dst[2], s->linesize, s->uvlinesize, 0);

        }

        if (s->filter.simple)

            filter_mb_simple(s, dst[0], f, mb_x, mb_y);

        else

            filter_mb(s, dst, f, mb_x, mb_y, is_vp7);

        dst[0] += 16;

        dst[1] += 8;

        dst[2] += 8;

        update_pos(td, mb_y, (s->mb_width + 3) + mb_x);

    }

}


static int decode_frame(FLACContext *s)

{

    int i, ret;

    GetBitContext *gb = &s->gb;

    FLACFrameInfo fi;

    if ((ret = ff_flac_decode_frame_header(s->avctx, gb, &fi, 0)) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid frame header\n");

        return ret;

    }

    if (s->channels && fi.channels != s->channels && s->got_streaminfo) {

        s->channels = s->avctx->channels = fi.channels;

        ff_flac_set_channel_layout(s->avctx);

        ret = allocate_buffers(s);

        if (ret < 0)

            return ret;

    }

    s->channels = s->avctx->channels = fi.channels;

    if (!s->avctx->channel_layout)

        ff_flac_set_channel_layout(s->avctx);

    s->ch_mode = fi.ch_mode;

    if (!s->bps && !fi.bps) {

        av_log(s->avctx, AV_LOG_ERROR, "bps not found in STREAMINFO or frame header\n");

        return AVERROR_INVALIDDATA;

    }

    if (!fi.bps) {

        fi.bps = s->bps;

    } else if (s->bps && fi.bps != s->bps) {

        av_log(s->avctx, AV_LOG_ERROR, "switching bps mid-stream is not "

                                       "supported\n");

        return AVERROR_INVALIDDATA;

    }

    if (!s->bps) {

        s->bps = s->avctx->bits_per_raw_sample = fi.bps;

        flac_set_bps(s);

    }

    if (!s->max_blocksize)

        s->max_blocksize = FLAC_MAX_BLOCKSIZE;

    if (fi.blocksize > s->max_blocksize) {

        av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", fi.blocksize,

               s->max_blocksize);

        return AVERROR_INVALIDDATA;

    }

    s->blocksize = fi.blocksize;

    if (!s->samplerate && !fi.samplerate) {

        av_log(s->avctx, AV_LOG_ERROR, "sample rate not found in STREAMINFO"

                                        " or frame header\n");

        return AVERROR_INVALIDDATA;

    }

    if (fi.samplerate == 0)

        fi.samplerate = s->samplerate;

    s->samplerate = s->avctx->sample_rate = fi.samplerate;

    if (!s->got_streaminfo) {

        ret = allocate_buffers(s);

        if (ret < 0)

            return ret;

        ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->channels, s->bps);

        s->got_streaminfo = 1;

        dump_headers(s->avctx, (FLACStreaminfo *)s);

    }

//    dump_headers(s->avctx, (FLACStreaminfo *)s);

    /* subframes */

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

        if ((ret = decode_subframe(s, i)) < 0)

            return ret;

    }

    align_get_bits(gb);

    /* frame footer */

    skip_bits(gb, 16); /* data crc */

    return 0;

}


static void invalid_array_comma(void)

{

    QObject *obj = qobject_from_json("[32,}", NULL);

    g_assert(obj == NULL);

}


static void vmxnet3_ack_events(VMXNET3State *s, uint32_t val)

{

    uint32_t events;

    VMW_CBPRN("Clearing events: 0x%x", val);

    events = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, ecr) & ~val;

    VMXNET3_WRITE_DRV_SHARED32(s->drv_shmem, ecr, events);

}


static void grlib_gptimer_enable(GPTimer *timer)

{

    assert(timer != NULL);

    ptimer_stop(timer->ptimer);

    if (!(timer->config & GPTIMER_ENABLE)) {

        /* Timer disabled */

        trace_grlib_gptimer_disabled(timer->id, timer->config);

        return;

    }

    /* ptimer is triggered when the counter reach 0 but GPTimer is triggered at

       underflow. Set count + 1 to simulate the GPTimer behavior. */

    trace_grlib_gptimer_enable(timer->id, timer->counter + 1);

    ptimer_set_count(timer->ptimer, timer->counter + 1);

    ptimer_run(timer->ptimer, 1);

}


static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len,

                               char *dst, int dstlen)

{

    char *p = dst;

    char *end = dst+dstlen-1;

    int i;

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

        uint8_t t, c = avio_r8(pb);

        if (c < 0x80 && p < end)

            *p++ = c;

        else

            PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;);

    }

    *p = 0;

    return p - dst;

}


altivec_yuv2packedX (SwsContext *c,

		       int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

		       int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

		       uint8_t *dest, int dstW, int dstY)

{

  int i,j;

  vector signed short X,X0,X1,Y0,U0,V0,Y1,U1,V1,U,V;

  vector signed short R0,G0,B0,R1,G1,B1;

  vector unsigned char R,G,B;

  vector unsigned char *out,*nout;

  vector signed short   RND = vec_splat_s16(1<<3);

  vector unsigned short SCL = vec_splat_u16(4);

  unsigned long scratch[16] __attribute__ ((aligned (16)));

  vector signed short *YCoeffs, *CCoeffs;

  YCoeffs = c->vYCoeffsBank+dstY*lumFilterSize;

  CCoeffs = c->vCCoeffsBank+dstY*chrFilterSize;

  out = (vector unsigned char *)dest;

  for(i=0; i<dstW; i+=16){

    Y0 = RND;

    Y1 = RND;

    /* extract 16 coeffs from lumSrc */

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

      X0 = vec_ld (0,  &lumSrc[j][i]);

      X1 = vec_ld (16, &lumSrc[j][i]);

      Y0 = vec_mradds (X0, YCoeffs[j], Y0);

      Y1 = vec_mradds (X1, YCoeffs[j], Y1);

    }

    U = RND;

    V = RND;

    /* extract 8 coeffs from U,V */

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

      X  = vec_ld (0, &chrSrc[j][i/2]);

      U  = vec_mradds (X, CCoeffs[j], U);

      X  = vec_ld (0, &chrSrc[j][i/2+2048]);

      V  = vec_mradds (X, CCoeffs[j], V);

    }

    /* scale and clip signals */

    Y0 = vec_sra (Y0, SCL);

    Y1 = vec_sra (Y1, SCL);

    U  = vec_sra (U,  SCL);

    V  = vec_sra (V,  SCL);

    Y0 = vec_clip_s16 (Y0);

    Y1 = vec_clip_s16 (Y1);

    U  = vec_clip_s16 (U);

    V  = vec_clip_s16 (V);

    /* now we have

      Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

      U= u0 u1 u2 u3 u4 u5 u6 u7      V= v0 v1 v2 v3 v4 v5 v6 v7

      Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

      U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

      V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

    */

    U0 = vec_mergeh (U,U);

    V0 = vec_mergeh (V,V);

    U1 = vec_mergel (U,U);

    V1 = vec_mergel (V,V);

    cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

    cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

    R  = vec_packclp (R0,R1);

    G  = vec_packclp (G0,G1);

    B  = vec_packclp (B0,B1);

    switch(c->dstFormat) {

      case PIX_FMT_ABGR: out_abgr (R,G,B,out); break;

      case PIX_FMT_BGRA: out_bgra (R,G,B,out); break;

      case PIX_FMT_RGBA: out_rgba (R,G,B,out); break;

      case PIX_FMT_ARGB: out_argb (R,G,B,out); break;

      case PIX_FMT_RGB24: out_rgb24 (R,G,B,out); break;

      case PIX_FMT_BGR24: out_bgr24 (R,G,B,out); break;

      default:

        {

          /* If this is reached, the caller should have called yuv2packedXinC

             instead. */

          static int printed_error_message;

          if(!printed_error_message) {

            av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                    sws_format_name(c->dstFormat));

            printed_error_message=1;

          }

          return;

        }

    }

  }

  if (i < dstW) {

    i -= 16;

    Y0 = RND;

    Y1 = RND;

    /* extract 16 coeffs from lumSrc */

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

      X0 = vec_ld (0,  &lumSrc[j][i]);

      X1 = vec_ld (16, &lumSrc[j][i]);

      Y0 = vec_mradds (X0, YCoeffs[j], Y0);

      Y1 = vec_mradds (X1, YCoeffs[j], Y1);

    }

    U = RND;

    V = RND;

    /* extract 8 coeffs from U,V */

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

      X  = vec_ld (0, &chrSrc[j][i/2]);

      U  = vec_mradds (X, CCoeffs[j], U);

      X  = vec_ld (0, &chrSrc[j][i/2+2048]);

      V  = vec_mradds (X, CCoeffs[j], V);

    }

    /* scale and clip signals */

    Y0 = vec_sra (Y0, SCL);

    Y1 = vec_sra (Y1, SCL);

    U  = vec_sra (U,  SCL);

    V  = vec_sra (V,  SCL);

    Y0 = vec_clip_s16 (Y0);

    Y1 = vec_clip_s16 (Y1);

    U  = vec_clip_s16 (U);

    V  = vec_clip_s16 (V);

    /* now we have

       Y0= y0 y1 y2 y3 y4 y5 y6 y7     Y1= y8 y9 y10 y11 y12 y13 y14 y15

       U= u0 u1 u2 u3 u4 u5 u6 u7      V= v0 v1 v2 v3 v4 v5 v6 v7

       Y0= y0 y1 y2 y3 y4 y5 y6 y7    Y1= y8 y9 y10 y11 y12 y13 y14 y15

       U0= u0 u0 u1 u1 u2 u2 u3 u3    U1= u4 u4 u5 u5 u6 u6 u7 u7

       V0= v0 v0 v1 v1 v2 v2 v3 v3    V1= v4 v4 v5 v5 v6 v6 v7 v7

    */

    U0 = vec_mergeh (U,U);

    V0 = vec_mergeh (V,V);

    U1 = vec_mergel (U,U);

    V1 = vec_mergel (V,V);

    cvtyuvtoRGB (c, Y0,U0,V0,&R0,&G0,&B0);

    cvtyuvtoRGB (c, Y1,U1,V1,&R1,&G1,&B1);

    R  = vec_packclp (R0,R1);

    G  = vec_packclp (G0,G1);

    B  = vec_packclp (B0,B1);

    nout = (vector unsigned char *)scratch;

    switch(c->dstFormat) {

      case PIX_FMT_ABGR: out_abgr (R,G,B,nout); break;

      case PIX_FMT_BGRA: out_bgra (R,G,B,nout); break;

      case PIX_FMT_RGBA: out_rgba (R,G,B,nout); break;

      case PIX_FMT_ARGB: out_argb (R,G,B,nout); break;

      case PIX_FMT_RGB24: out_rgb24 (R,G,B,nout); break;

      case PIX_FMT_BGR24: out_bgr24 (R,G,B,nout); break;

      default:

        /* Unreachable, I think. */

        av_log(c, AV_LOG_ERROR, "altivec_yuv2packedX doesn't support %s output\n",

                sws_format_name(c->dstFormat));

        return;

    }

    memcpy (&((uint32_t*)dest)[i], scratch, (dstW-i)/4);

  }

}


int unix_listen_opts(QemuOpts *opts, Error **errp)

{

    struct sockaddr_un un;

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

    int sock, fd;

    sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        error_setg_errno(errp, errno, "Failed to create Unix socket");

        return -1;

    }

    memset(&un, 0, sizeof(un));

    un.sun_family = AF_UNIX;

    if (path && strlen(path)) {

        snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);

    } else {

        const char *tmpdir = getenv("TMPDIR");

        tmpdir = tmpdir ? tmpdir : "/tmp";

        if (snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",

                     tmpdir) >= sizeof(un.sun_path)) {

            error_setg_errno(errp, errno,

                             "TMPDIR environment variable (%s) too large", tmpdir);

            goto err;

        }

        /*

         * This dummy fd usage silences the mktemp() unsecure warning.

         * Using mkstemp() doesn't make things more secure here

         * though.  bind() complains about existing files, so we have

         * to unlink first and thus re-open the race window.  The

         * worst case possible is bind() failing, i.e. a DoS attack.

         */

        fd = mkstemp(un.sun_path);

        if (fd < 0) {

            error_setg_errno(errp, errno,

                             "Failed to make a temporary socket name in %s", tmpdir);

            goto err;

        }

        close(fd);

        qemu_opt_set(opts, "path", un.sun_path, &error_abort);

    }

    if ((access(un.sun_path, F_OK) == 0) &&

        unlink(un.sun_path) < 0) {

        error_setg_errno(errp, errno,

                         "Failed to unlink socket %s", un.sun_path);

        goto err;

    }

    if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

        error_setg_errno(errp, errno, "Failed to bind socket to %s", un.sun_path);

        goto err;

    }

    if (listen(sock, 1) < 0) {

        error_setg_errno(errp, errno, "Failed to listen on socket");

        goto err;

    }

    return sock;

err:

    closesocket(sock);

    return -1;

}


static void rv40_h_strong_loop_filter(uint8_t *src, const int stride,

                                      const int alpha, const int lims,

                                      const int dmode, const int chroma)

{

    rv40_strong_loop_filter(src, stride, 1, alpha, lims, dmode, chroma);

}


static void copy_frame(J2kEncoderContext *s)

{

    int tileno, compno, i, y, x;

    uint8_t *line;

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){

        J2kTile *tile = s->tile + tileno;

        if (s->planar){

            for (compno = 0; compno < s->ncomponents; compno++){

                J2kComponent *comp = tile->comp + compno;

                int *dst = comp->data;

                line = s->picture->data[compno]

                       + comp->coord[1][0] * s->picture->linesize[compno]

                       + comp->coord[0][0];

                for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){

                    uint8_t *ptr = line;

                    for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)

                        *dst++ = *ptr++ - (1 << 7);

                    line += s->picture->linesize[compno];

                }

            }

        } else{

            line = s->picture->data[0] + tile->comp[0].coord[1][0] * s->picture->linesize[0]

                   + tile->comp[0].coord[0][0] * s->ncomponents;

            i = 0;

            for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){

                uint8_t *ptr = line;

                for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){

                    for (compno = 0; compno < s->ncomponents; compno++){

                        tile->comp[compno].data[i] = *ptr++  - (1 << 7);

                    }

                }

                line += s->picture->linesize[0];

            }

        }

    }

}


static void migrate_fd_cleanup(void *opaque)

{

    MigrationState *s = opaque;

    qemu_bh_delete(s->cleanup_bh);

    s->cleanup_bh = NULL;

    if (s->file) {

        trace_migrate_fd_cleanup();

        qemu_mutex_unlock_iothread();

        qemu_thread_join(&s->thread);

        qemu_mutex_lock_iothread();

        qemu_fclose(s->file);

        s->file = NULL;

    }

    assert(s->state != MIG_STATE_ACTIVE);

    if (s->state != MIG_STATE_COMPLETED) {

        qemu_savevm_state_cancel();

        if (s->state == MIG_STATE_CANCELLING) {

            migrate_set_state(s, MIG_STATE_CANCELLING, MIG_STATE_CANCELLED);

        }

    }

    notifier_list_notify(&migration_state_notifiers, s);

}


static void uhci_async_cancel_device(UHCIState *s, USBDevice *dev)

{

    UHCIAsync *curr, *n;

    QTAILQ_FOREACH_SAFE(curr, &s->async_pending, next, n) {

        if (curr->packet.owner == NULL ||

            curr->packet.owner->dev != dev) {

            continue;

        }

        uhci_async_unlink(s, curr);

        uhci_async_cancel(s, curr);

    }

}


static TraceEvent* find_trace_event_by_name(const char *tname)

{

    unsigned int i;

    if (!tname) {

        return NULL;

    }

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

        if (!strcmp(trace_list[i].tp_name, tname)) {

            return &trace_list[i];

        }

    }

    return NULL; /* indicates end of list reached without a match */

}


i2c_slave *twl92230_init(i2c_bus *bus, qemu_irq irq)

{

    struct menelaus_s *s = (struct menelaus_s *)

            i2c_slave_init(bus, 0, sizeof(struct menelaus_s));

    s->i2c.event = menelaus_event;

    s->i2c.recv = menelaus_rx;

    s->i2c.send = menelaus_tx;

    s->irq = irq;

    s->rtc.hz = qemu_new_timer(rt_clock, menelaus_rtc_hz, s);

    s->in = qemu_allocate_irqs(menelaus_gpio_set, s, 3);

    s->pwrbtn = qemu_allocate_irqs(menelaus_pwrbtn_set, s, 1)[0];

    menelaus_reset(&s->i2c);

    register_savevm("menelaus", -1, 0, menelaus_save, menelaus_load, s);

    return &s->i2c;

}


static int av_seek_frame_generic(AVFormatContext *s,

                                 int stream_index, int64_t timestamp, int flags)

{

    int index;

    AVStream *st;

    AVIndexEntry *ie;

    st = s->streams[stream_index];

    index = av_index_search_timestamp(st, timestamp, flags);

    if(index < 0 || index==st->nb_index_entries-1){

        int i;

        AVPacket pkt;

        if(st->nb_index_entries){

            assert(st->index_entries);

            ie= &st->index_entries[st->nb_index_entries-1];

            url_fseek(s->pb, ie->pos, SEEK_SET);

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

        }else

            url_fseek(s->pb, 0, SEEK_SET);

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

            int ret = av_read_frame(s, &pkt);

            if(ret<0)

                break;

            av_free_packet(&pkt);

            if(stream_index == pkt.stream_index){

                if((pkt.flags & PKT_FLAG_KEY) && pkt.dts > timestamp)

                    break;

            }

        }

        index = av_index_search_timestamp(st, timestamp, flags);

    }

    if (index < 0)

        return -1;

    av_read_frame_flush(s);

    if (s->iformat->read_seek){

        if(s->iformat->read_seek(s, stream_index, timestamp, flags) >= 0)

            return 0;

    }

    ie = &st->index_entries[index];

    url_fseek(s->pb, ie->pos, SEEK_SET);

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

    return 0;

}


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

{

    struct ogg *ogg;

    struct ogg_stream *os;

    int idx, ret;

    int pstart, psize;

    int64_t fpos, pts, dts;

    if (s->io_repositioned) {

        ogg_reset(s);

        s->io_repositioned = 0;

    //Get an ogg packet

retry:

    do {

        ret = ogg_packet(s, &idx, &pstart, &psize, &fpos);

        if (ret < 0)

            return ret;

    } while (idx < 0 || !s->streams[idx]);

    ogg = s->priv_data;

    os  = ogg->streams + idx;

    // pflags might not be set until after this

    pts = ogg_calc_pts(s, idx, &dts);

    ogg_validate_keyframe(s, idx, pstart, psize);

    if (os->keyframe_seek && !(os->pflags & AV_PKT_FLAG_KEY))

        goto retry;

    os->keyframe_seek = 0;

    //Alloc a pkt

    ret = av_new_packet(pkt, psize);

    if (ret < 0)

        return ret;

    pkt->stream_index = idx;

    memcpy(pkt->data, os->buf + pstart, psize);

    pkt->pts      = pts;

    pkt->dts      = dts;

    pkt->flags    = os->pflags;

    pkt->duration = os->pduration;

    pkt->pos      = fpos;

    if (os->end_trimming) {

        uint8_t *side_data = av_packet_new_side_data(pkt,

                                                     AV_PKT_DATA_SKIP_SAMPLES,

                                                     10);

        AV_WL32(side_data + 4, os->end_trimming);

        os->end_trimming = 0;

    if (os->new_metadata) {

        uint8_t *side_data = av_packet_new_side_data(pkt,

                                                     AV_PKT_DATA_METADATA_UPDATE,

                                                     os->new_metadata_size);

        memcpy(side_data, os->new_metadata, os->new_metadata_size);

        av_freep(&os->new_metadata);

        os->new_metadata_size = 0;

    return psize;


static void slirp_cleanup(void)

{

    WSACleanup();

}


static int read_sl_header(PESContext *pes, SLConfigDescr *sl,

                          const uint8_t *buf, int buf_size)

{

    GetBitContext gb;

    int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;

    int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;

    int dts_flag = -1, cts_flag = -1;

    int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;

    init_get_bits(&gb, buf, buf_size * 8);

    if (sl->use_au_start)

        au_start_flag = get_bits1(&gb);

    if (sl->use_au_end)

        au_end_flag = get_bits1(&gb);

    if (!sl->use_au_start && !sl->use_au_end)

        au_start_flag = au_end_flag = 1;

    if (sl->ocr_len > 0)

        ocr_flag = get_bits1(&gb);

    if (sl->use_idle)

        idle_flag = get_bits1(&gb);

    if (sl->use_padding)

        padding_flag = get_bits1(&gb);

    if (padding_flag)

        padding_bits = get_bits(&gb, 3);

    if (!idle_flag && (!padding_flag || padding_bits != 0)) {

        if (sl->packet_seq_num_len)

            skip_bits_long(&gb, sl->packet_seq_num_len);

        if (sl->degr_prior_len)

            if (get_bits1(&gb))

                skip_bits(&gb, sl->degr_prior_len);

        if (ocr_flag)

            skip_bits_long(&gb, sl->ocr_len);

        if (au_start_flag) {

            if (sl->use_rand_acc_pt)

                get_bits1(&gb);

            if (sl->au_seq_num_len > 0)

                skip_bits_long(&gb, sl->au_seq_num_len);

            if (sl->use_timestamps) {

                dts_flag = get_bits1(&gb);

                cts_flag = get_bits1(&gb);

            }

        }

        if (sl->inst_bitrate_len)

            inst_bitrate_flag = get_bits1(&gb);

        if (dts_flag == 1)

            dts = get_ts64(&gb, sl->timestamp_len);

        if (cts_flag == 1)

            cts = get_ts64(&gb, sl->timestamp_len);

        if (sl->au_len > 0)

            skip_bits_long(&gb, sl->au_len);

        if (inst_bitrate_flag)

            skip_bits_long(&gb, sl->inst_bitrate_len);

    }

    if (dts != AV_NOPTS_VALUE)

        pes->dts = dts;

    if (cts != AV_NOPTS_VALUE)

        pes->pts = cts;

    if (sl->timestamp_len && sl->timestamp_res)

        avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);

    return (get_bits_count(&gb) + 7) >> 3;

}


static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal)

{

    HEVCLocalContext *lc = s->HEVClc;

    GetBitContext *gb    = &lc->gb;

    int ctb_addr_ts, ret;

    *gb              = nal->gb;

    s->nal_unit_type = nal->type;

    s->temporal_id   = nal->temporal_id;

    switch (s->nal_unit_type) {

    case HEVC_NAL_VPS:

        ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps);

        if (ret < 0)

            goto fail;

        break;

    case HEVC_NAL_SPS:

        ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps,

                                     s->apply_defdispwin);

        if (ret < 0)

            goto fail;

        break;

    case HEVC_NAL_PPS:

        ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps);

        if (ret < 0)

            goto fail;

        break;

    case HEVC_NAL_SEI_PREFIX:

    case HEVC_NAL_SEI_SUFFIX:

        ret = ff_hevc_decode_nal_sei(s);

        if (ret < 0)

            goto fail;

        break;

    case HEVC_NAL_TRAIL_R:

    case HEVC_NAL_TRAIL_N:

    case HEVC_NAL_TSA_N:

    case HEVC_NAL_TSA_R:

    case HEVC_NAL_STSA_N:

    case HEVC_NAL_STSA_R:

    case HEVC_NAL_BLA_W_LP:

    case HEVC_NAL_BLA_W_RADL:

    case HEVC_NAL_BLA_N_LP:

    case HEVC_NAL_IDR_W_RADL:

    case HEVC_NAL_IDR_N_LP:

    case HEVC_NAL_CRA_NUT:

    case HEVC_NAL_RADL_N:

    case HEVC_NAL_RADL_R:

    case HEVC_NAL_RASL_N:

    case HEVC_NAL_RASL_R:

        ret = hls_slice_header(s);

        if (ret < 0)

            return ret;

        if (s->max_ra == INT_MAX) {

            if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) {

                s->max_ra = s->poc;

            } else {

                if (IS_IDR(s))

                    s->max_ra = INT_MIN;

            }

        }

        if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) &&

            s->poc <= s->max_ra) {

            s->is_decoded = 0;

            break;

        } else {

            if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra)

                s->max_ra = INT_MIN;

        }

        if (s->sh.first_slice_in_pic_flag) {

            ret = hevc_frame_start(s);

            if (ret < 0)

                return ret;

        } else if (!s->ref) {

            av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");

            goto fail;

        }

        if (s->nal_unit_type != s->first_nal_type) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Non-matching NAL types of the VCL NALUs: %d %d\n",

                   s->first_nal_type, s->nal_unit_type);

            return AVERROR_INVALIDDATA;

        }

        if (!s->sh.dependent_slice_segment_flag &&

            s->sh.slice_type != HEVC_SLICE_I) {

            ret = ff_hevc_slice_rpl(s);

            if (ret < 0) {

                av_log(s->avctx, AV_LOG_WARNING,

                       "Error constructing the reference lists for the current slice.\n");

                goto fail;

            }

        }

        if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) {

            ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0);

            if (ret < 0)

                goto fail;

        }

        if (s->avctx->hwaccel) {

            ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size);

            if (ret < 0)

                goto fail;

        } else {

            if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0)

                ctb_addr_ts = hls_slice_data_wpp(s, nal);

            else

                ctb_addr_ts = hls_slice_data(s);

            if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) {

                s->is_decoded = 1;

            }

            if (ctb_addr_ts < 0) {

                ret = ctb_addr_ts;

                goto fail;

            }

        }

        break;

    case HEVC_NAL_EOS_NUT:

    case HEVC_NAL_EOB_NUT:

        s->seq_decode = (s->seq_decode + 1) & 0xff;

        s->max_ra     = INT_MAX;

        break;

    case HEVC_NAL_AUD:

    case HEVC_NAL_FD_NUT:

        break;

    default:

        av_log(s->avctx, AV_LOG_INFO,

               "Skipping NAL unit %d\n", s->nal_unit_type);

    }

    return 0;

fail:

    if (s->avctx->err_recognition & AV_EF_EXPLODE)

        return ret;

    return 0;

}


static bool gen_rsr_ccount(DisasContext *dc, TCGv_i32 d, uint32_t sr)

{

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_update_ccount(cpu_env);

    tcg_gen_mov_i32(d, cpu_SR[sr]);

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        return true;

    }

    return false;

}


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

                              int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    ADPCMDecodeContext *c = avctx->priv_data;

    ADPCMChannelStatus *cs;

    int n, m, channel, i;

    short *samples;

    const uint8_t *src;

    int st; /* stereo */

    int count1, count2;

    int nb_samples, coded_samples, ret;

    nb_samples = get_nb_samples(avctx, buf, buf_size, &coded_samples);

    if (nb_samples <= 0) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of samples in packet\n");

        return AVERROR_INVALIDDATA;

    }

    /* get output buffer */

    c->frame.nb_samples = nb_samples;

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

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

        return ret;

    }

    samples = (short *)c->frame.data[0];

    /* use coded_samples when applicable */

    /* it is always <= nb_samples, so the output buffer will be large enough */

    if (coded_samples) {

        if (coded_samples != nb_samples)

            av_log(avctx, AV_LOG_WARNING, "mismatch in coded sample count\n");

        c->frame.nb_samples = nb_samples = coded_samples;

    }

    src = buf;

    st = avctx->channels == 2 ? 1 : 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT:

        /* In QuickTime, IMA is encoded by chunks of 34 bytes (=64 samples).

           Channel data is interleaved per-chunk. */

        for (channel = 0; channel < avctx->channels; channel++) {

            int16_t predictor;

            int step_index;

            cs = &(c->status[channel]);

            /* (pppppp) (piiiiiii) */

            /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */

            predictor = AV_RB16(src);

            step_index = predictor & 0x7F;

            predictor &= 0xFF80;

            src += 2;

            if (cs->step_index == step_index) {

                int diff = (int)predictor - cs->predictor;

                if (diff < 0)

                    diff = - diff;

                if (diff > 0x7f)

                    goto update;

            } else {

            update:

                cs->step_index = step_index;

                cs->predictor = predictor;

            }

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            samples = (short *)c->frame.data[0] + channel;

            for (m = 0; m < 32; m++) {

                *samples = adpcm_ima_qt_expand_nibble(cs, src[0] & 0x0F, 3);

                samples += avctx->channels;

                *samples = adpcm_ima_qt_expand_nibble(cs, src[0] >> 4  , 3);

                samples += avctx->channels;

                src ++;

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

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

            cs = &(c->status[i]);

            cs->predictor = *samples++ = (int16_t)bytestream_get_le16(&src);

            cs->step_index = *src++;

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */

        }

        for (n = (nb_samples - 1) / 8; n > 0; n--) {

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

                cs = &c->status[i];

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

                    uint8_t v = *src++;

                    *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);

                    samples += avctx->channels;

                    *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 3);

                    samples += avctx->channels;

                }

                samples -= 8 * avctx->channels - 1;

            }

            samples += 7 * avctx->channels;

        }

        break;

    case CODEC_ID_ADPCM_4XM:

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

            c->status[i].predictor= (int16_t)bytestream_get_le16(&src);

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

            c->status[i].step_index= (int16_t)bytestream_get_le16(&src);

            c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

        }

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

            samples = (short *)c->frame.data[0] + i;

            cs = &c->status[i];

            for (n = nb_samples >> 1; n > 0; n--, src++) {

                uint8_t v = *src;

                *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 4);

                samples += avctx->channels;

                *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 4);

                samples += avctx->channels;

            }

        }

        break;

    case CODEC_ID_ADPCM_MS:

    {

        int block_predictor;

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        block_predictor = av_clip(*src++, 0, 6);

        c->status[0].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor];

        c->status[0].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor];

        if (st) {

            block_predictor = av_clip(*src++, 0, 6);

            c->status[1].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor];

            c->status[1].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor];

        }

        c->status[0].idelta = (int16_t)bytestream_get_le16(&src);

        if (st){

            c->status[1].idelta = (int16_t)bytestream_get_le16(&src);

        }

        c->status[0].sample1 = bytestream_get_le16(&src);

        if (st) c->status[1].sample1 = bytestream_get_le16(&src);

        c->status[0].sample2 = bytestream_get_le16(&src);

        if (st) c->status[1].sample2 = bytestream_get_le16(&src);

        *samples++ = c->status[0].sample2;

        if (st) *samples++ = c->status[1].sample2;

        *samples++ = c->status[0].sample1;

        if (st) *samples++ = c->status[1].sample1;

        for(n = (nb_samples - 2) >> (1 - st); n > 0; n--, src++) {

            *samples++ = adpcm_ms_expand_nibble(&c->status[0 ], src[0] >> 4  );

            *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);

        }

        break;

    }

    case CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        for (channel = 0; channel < avctx->channels; channel++) {

            cs = &c->status[channel];

            cs->predictor  = (int16_t)bytestream_get_le16(&src);

            cs->step_index = av_clip(*src++, 0, 88);

            src++;

            *samples++ = cs->predictor;

        }

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            uint8_t v = *src;

            *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v >> 4  , 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK3:

    {

        unsigned char last_byte = 0;

        unsigned char nibble;

        int decode_top_nibble_next = 0;

        int end_of_packet = 0;

        int diff_channel;

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        c->status[0].predictor  = (int16_t)AV_RL16(src + 10);

        c->status[1].predictor  = (int16_t)AV_RL16(src + 12);

        c->status[0].step_index = av_clip(src[14], 0, 88);

        c->status[1].step_index = av_clip(src[15], 0, 88);

        /* sign extend the predictors */

        src += 16;

        diff_channel = c->status[1].predictor;

        /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when

         * the buffer is consumed */

        while (1) {

            /* for this algorithm, c->status[0] is the sum channel and

             * c->status[1] is the diff channel */

            /* process the first predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the diff channel predictor */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[1], nibble, 3);

            /* process the first pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

            /* process the second predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the second pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

        }

        break;

    }

    case CODEC_ID_ADPCM_IMA_ISS:

        for (channel = 0; channel < avctx->channels; channel++) {

            cs = &c->status[channel];

            cs->predictor  = (int16_t)bytestream_get_le16(&src);

            cs->step_index = av_clip(*src++, 0, 88);

            src++;

        }

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            uint8_t v1, v2;

            uint8_t v = *src;

            /* nibbles are swapped for mono */

            if (st) {

                v1 = v >> 4;

                v2 = v & 0x0F;

            } else {

                v2 = v >> 4;

                v1 = v & 0x0F;

            }

            *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v1, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v2, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_APC:

        while (src < buf + buf_size) {

            uint8_t v = *src++;

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],  v >> 4  , 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        for (channel = 0; channel < avctx->channels; channel++) {

            const uint8_t *src0;

            int src_stride;

            int16_t *smp = samples + channel;

            if (c->vqa_version == 3) {

                src0 = src + channel * buf_size / 2;

                src_stride = 1;

            } else {

                src0 = src + channel;

                src_stride = avctx->channels;

            }

            for (n = nb_samples / 2; n > 0; n--) {

                uint8_t v = *src0;

                src0 += src_stride;

                *smp = adpcm_ima_expand_nibble(&c->status[channel], v >> 4  , 3);

                smp += avctx->channels;

                *smp = adpcm_ima_expand_nibble(&c->status[channel], v & 0x0F, 3);

                smp += avctx->channels;

            }

        }

        src = buf + buf_size;

        break;

    case CODEC_ID_ADPCM_XA:

        while (buf_size >= 128) {

            xa_decode(samples, src, &c->status[0], &c->status[1],

                avctx->channels);

            src += 128;

            samples += 28 * 8;

            buf_size -= 128;

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_EACS:

        src += 4; // skip sample count (already read)

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

            c->status[i].step_index = av_clip(bytestream_get_le32(&src), 0, 88);

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

            c->status[i].predictor  = bytestream_get_le32(&src);

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],  *src>>4,   3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], *src&0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_SEAD:

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[0] >> 4, 6);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st],src[0]&0x0F, 6);

        }

        break;

    case CODEC_ID_ADPCM_EA:

    {

        int32_t previous_left_sample, previous_right_sample;

        int32_t current_left_sample, current_right_sample;

        int32_t next_left_sample, next_right_sample;

        int32_t coeff1l, coeff2l, coeff1r, coeff2r;

        uint8_t shift_left, shift_right;

        /* Each EA ADPCM frame has a 12-byte header followed by 30-byte pieces,

           each coding 28 stereo samples. */

        src += 4; // skip sample count (already read)

        current_left_sample   = (int16_t)bytestream_get_le16(&src);

        previous_left_sample  = (int16_t)bytestream_get_le16(&src);

        current_right_sample  = (int16_t)bytestream_get_le16(&src);

        previous_right_sample = (int16_t)bytestream_get_le16(&src);

        for (count1 = 0; count1 < nb_samples / 28; count1++) {

            coeff1l = ea_adpcm_table[ *src >> 4       ];

            coeff2l = ea_adpcm_table[(*src >> 4  ) + 4];

            coeff1r = ea_adpcm_table[*src & 0x0F];

            coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];

            src++;

            shift_left  = 20 - (*src >> 4);

            shift_right = 20 - (*src & 0x0F);

            src++;

            for (count2 = 0; count2 < 28; count2++) {

                next_left_sample  = sign_extend(*src >> 4, 4) << shift_left;

                next_right_sample = sign_extend(*src,      4) << shift_right;

                src++;

                next_left_sample = (next_left_sample +

                    (current_left_sample * coeff1l) +

                    (previous_left_sample * coeff2l) + 0x80) >> 8;

                next_right_sample = (next_right_sample +

                    (current_right_sample * coeff1r) +

                    (previous_right_sample * coeff2r) + 0x80) >> 8;

                previous_left_sample = current_left_sample;

                current_left_sample = av_clip_int16(next_left_sample);

                previous_right_sample = current_right_sample;

                current_right_sample = av_clip_int16(next_right_sample);

                *samples++ = (unsigned short)current_left_sample;

                *samples++ = (unsigned short)current_right_sample;

            }

        }

        if (src - buf == buf_size - 2)

            src += 2; // Skip terminating 0x0000

        break;

    }

    case CODEC_ID_ADPCM_EA_MAXIS_XA:

    {

        int coeff[2][2], shift[2];

        for(channel = 0; channel < avctx->channels; channel++) {

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

                coeff[channel][i] = ea_adpcm_table[(*src >> 4) + 4*i];

            shift[channel] = 20 - (*src & 0x0F);

            src++;

        }

        for (count1 = 0; count1 < nb_samples / 2; count1++) {

            for(i = 4; i >= 0; i-=4) { /* Pairwise samples LL RR (st) or LL LL (mono) */

                for(channel = 0; channel < avctx->channels; channel++) {

                    int32_t sample = sign_extend(src[channel] >> i, 4) << shift[channel];

                    sample = (sample +

                             c->status[channel].sample1 * coeff[channel][0] +

                             c->status[channel].sample2 * coeff[channel][1] + 0x80) >> 8;

                    c->status[channel].sample2 = c->status[channel].sample1;

                    c->status[channel].sample1 = av_clip_int16(sample);

                    *samples++ = c->status[channel].sample1;

                }

            }

            src+=avctx->channels;

        }

        /* consume whole packet */

        src = buf + buf_size;

        break;

    }

    case CODEC_ID_ADPCM_EA_R1:

    case CODEC_ID_ADPCM_EA_R2:

    case CODEC_ID_ADPCM_EA_R3: {

        /* channel numbering

           2chan: 0=fl, 1=fr

           4chan: 0=fl, 1=rl, 2=fr, 3=rr

           6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */

        const int big_endian = avctx->codec->id == CODEC_ID_ADPCM_EA_R3;

        int32_t previous_sample, current_sample, next_sample;

        int32_t coeff1, coeff2;

        uint8_t shift;

        unsigned int channel;

        uint16_t *samplesC;

        const uint8_t *srcC;

        const uint8_t *src_end = buf + buf_size;

        int count = 0;

        src += 4; // skip sample count (already read)

        for (channel=0; channel<avctx->channels; channel++) {

            int32_t offset = (big_endian ? bytestream_get_be32(&src)

                                         : bytestream_get_le32(&src))

                           + (avctx->channels-channel-1) * 4;

            if ((offset < 0) || (offset >= src_end - src - 4)) break;

            srcC  = src + offset;

            samplesC = samples + channel;

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

                current_sample  = (int16_t)bytestream_get_le16(&srcC);

                previous_sample = (int16_t)bytestream_get_le16(&srcC);

            } else {

                current_sample  = c->status[channel].predictor;

                previous_sample = c->status[channel].prev_sample;

            }

            for (count1 = 0; count1 < nb_samples / 28; count1++) {

                if (*srcC == 0xEE) {  /* only seen in R2 and R3 */

                    srcC++;

                    if (srcC > src_end - 30*2) break;

                    current_sample  = (int16_t)bytestream_get_be16(&srcC);

                    previous_sample = (int16_t)bytestream_get_be16(&srcC);

                    for (count2=0; count2<28; count2++) {

                        *samplesC = (int16_t)bytestream_get_be16(&srcC);

                        samplesC += avctx->channels;

                    }

                } else {

                    coeff1 = ea_adpcm_table[ *srcC>>4     ];

                    coeff2 = ea_adpcm_table[(*srcC>>4) + 4];

                    shift = 20 - (*srcC++ & 0x0F);

                    if (srcC > src_end - 14) break;

                    for (count2=0; count2<28; count2++) {

                        if (count2 & 1)

                            next_sample = sign_extend(*srcC++,    4) << shift;

                        else

                            next_sample = sign_extend(*srcC >> 4, 4) << shift;

                        next_sample += (current_sample  * coeff1) +

                                       (previous_sample * coeff2);

                        next_sample = av_clip_int16(next_sample >> 8);

                        previous_sample = current_sample;

                        current_sample  = next_sample;

                        *samplesC = current_sample;

                        samplesC += avctx->channels;

                    }

                }

            }

            if (!count) {

                count = count1;

            } else if (count != count1) {

                av_log(avctx, AV_LOG_WARNING, "per-channel sample count mismatch\n");

                count = FFMAX(count, count1);

            }

            if (avctx->codec->id != CODEC_ID_ADPCM_EA_R1) {

                c->status[channel].predictor   = current_sample;

                c->status[channel].prev_sample = previous_sample;

            }

        }

        c->frame.nb_samples = count * 28;

        src = src_end;

        break;

    }

    case CODEC_ID_ADPCM_EA_XAS:

        for (channel=0; channel<avctx->channels; channel++) {

            int coeff[2][4], shift[4];

            short *s2, *s = &samples[channel];

            for (n=0; n<4; n++, s+=32*avctx->channels) {

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

                    coeff[i][n] = ea_adpcm_table[(src[0]&0x0F)+4*i];

                shift[n] = 20 - (src[2] & 0x0F);

                for (s2=s, i=0; i<2; i++, src+=2, s2+=avctx->channels)

                    s2[0] = (src[0]&0xF0) + (src[1]<<8);

            }

            for (m=2; m<32; m+=2) {

                s = &samples[m*avctx->channels + channel];

                for (n=0; n<4; n++, src++, s+=32*avctx->channels) {

                    for (s2=s, i=0; i<8; i+=4, s2+=avctx->channels) {

                        int level = sign_extend(*src >> (4 - i), 4) << shift[n];

                        int pred  = s2[-1*avctx->channels] * coeff[0][n]

                                  + s2[-2*avctx->channels] * coeff[1][n];

                        s2[0] = av_clip_int16((level + pred + 0x80) >> 8);

                    }

                }

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_AMV:

    case CODEC_ID_ADPCM_IMA_SMJPEG:

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

            c->status[0].predictor = sign_extend(bytestream_get_le16(&src), 16);

            c->status[0].step_index = av_clip(bytestream_get_le16(&src), 0, 88);

            src += 4;

        } else {

            c->status[0].predictor = sign_extend(bytestream_get_be16(&src), 16);

            c->status[0].step_index = av_clip(bytestream_get_byte(&src), 0, 88);

            src += 1;

        }

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            char hi, lo;

            lo = *src & 0x0F;

            hi = *src >> 4;

            if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

                FFSWAP(char, hi, lo);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                lo, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                hi, 3);

        }

        break;

    case CODEC_ID_ADPCM_CT:

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            uint8_t v = *src;

            *samples++ = adpcm_ct_expand_nibble(&c->status[0 ], v >> 4  );

            *samples++ = adpcm_ct_expand_nibble(&c->status[st], v & 0x0F);

        }

        break;

    case CODEC_ID_ADPCM_SBPRO_4:

    case CODEC_ID_ADPCM_SBPRO_3:

    case CODEC_ID_ADPCM_SBPRO_2:

        if (!c->status[0].step_index) {

            /* the first byte is a raw sample */

            *samples++ = 128 * (*src++ - 0x80);

            if (st)

              *samples++ = 128 * (*src++ - 0x80);

            c->status[0].step_index = 1;

            nb_samples--;

        }

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

            for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] >> 4, 4, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x0F, 4, 0);

            }

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

            for (n = nb_samples / 3; n > 0; n--, src++) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 5        , 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] & 0x03, 2, 0);

            }

        } else {

            for (n = nb_samples >> (2 - st); n > 0; n--, src++) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 6        , 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    (src[0] >> 4) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x03, 2, 2);

            }

        }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        GetBitContext gb;

        const int *table;

        int k0, signmask, nb_bits, count;

        int size = buf_size*8;

        init_get_bits(&gb, buf, size);

        //read bits & initial values

        nb_bits = get_bits(&gb, 2)+2;

        //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);

        table = swf_index_tables[nb_bits-2];

        k0 = 1 << (nb_bits-2);

        signmask = 1 << (nb_bits-1);

        while (get_bits_count(&gb) <= size - 22*avctx->channels) {

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

                *samples++ = c->status[i].predictor = get_sbits(&gb, 16);

                c->status[i].step_index = get_bits(&gb, 6);

            }

            for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {

                int i;

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

                    // similar to IMA adpcm

                    int delta = get_bits(&gb, nb_bits);

                    int step = ff_adpcm_step_table[c->status[i].step_index];

                    long vpdiff = 0; // vpdiff = (delta+0.5)*step/4

                    int k = k0;

                    do {

                        if (delta & k)

                            vpdiff += step;

                        step >>= 1;

                        k >>= 1;

                    } while(k);

                    vpdiff += step;

                    if (delta & signmask)

                        c->status[i].predictor -= vpdiff;

                    else

                        c->status[i].predictor += vpdiff;

                    c->status[i].step_index += table[delta & (~signmask)];

                    c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

                    c->status[i].predictor = av_clip_int16(c->status[i].predictor);

                    *samples++ = c->status[i].predictor;

                }

            }

        }

        src += buf_size;

        break;

    }

    case CODEC_ID_ADPCM_YAMAHA:

        for (n = nb_samples >> (1 - st); n > 0; n--, src++) {

            uint8_t v = *src;

            *samples++ = adpcm_yamaha_expand_nibble(&c->status[0 ], v & 0x0F);

            *samples++ = adpcm_yamaha_expand_nibble(&c->status[st], v >> 4  );

        }

        break;

    case CODEC_ID_ADPCM_THP:

    {

        int table[2][16];

        int prev[2][2];

        int ch;

        src += 4; // skip channel size

        src += 4; // skip number of samples (already read)

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

            table[0][i] = (int16_t)bytestream_get_be16(&src);

        /* Initialize the previous sample.  */

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

            prev[0][i] = (int16_t)bytestream_get_be16(&src);

        for (ch = 0; ch <= st; ch++) {

            samples = (short *)c->frame.data[0] + ch;

            /* Read in every sample for this channel.  */

            for (i = 0; i < nb_samples / 14; i++) {

                int index = (*src >> 4) & 7;

                unsigned int exp = *src++ & 15;

                int factor1 = table[ch][index * 2];

                int factor2 = table[ch][index * 2 + 1];

                /* Decode 14 samples.  */

                for (n = 0; n < 14; n++) {

                    int32_t sampledat;

                    if(n&1) sampledat = sign_extend(*src++, 4);

                    else    sampledat = sign_extend(*src >> 4, 4);

                    sampledat = ((prev[ch][0]*factor1

                                + prev[ch][1]*factor2) >> 11) + (sampledat << exp);

                    *samples = av_clip_int16(sampledat);

                    prev[ch][1] = prev[ch][0];

                    prev[ch][0] = *samples++;

                    /* In case of stereo, skip one sample, this sample

                       is for the other channel.  */

                    samples += st;

                }

            }

        }

        break;

    }

    default:

        return -1;

    }

    *got_frame_ptr   = 1;

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

    return src - buf;

}


static void noise_scale(int *coefs, int scale, int band_energy, int len)

{

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

    int s = FFABS(scale);

    unsigned int round;

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

    int nlz = 0;

    while (band_energy > 0x7fff) {

        band_energy >>= 1;

        nlz++;

    }

    c /= band_energy;

    s = 21 + nlz - (s >> 2);

    if (s > 0) {

        round = 1 << (s-1);

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

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

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

        }

    }

    else {

        s = s + 32;

        round = 1 << (s-1);

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

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

            coefs[i] = out * ssign;

        }

    }

}


int kvm_arch_insert_hw_breakpoint(target_ulong addr, target_ulong len, int type)

{

    return -EINVAL;

}


void *g_malloc(size_t size)

{

    char * p;

    size += 16;

    p = bsd_vmalloc(size);

    *(size_t *)p = size;

    return p + 16;

}


int ff_dirac_golomb_read_16bit(DiracGolombLUT *lut_ctx, const uint8_t *buf,

                               int bytes, uint8_t *_dst, int coeffs)

{

    int i, b, c_idx = 0;

    int16_t *dst = (int16_t *)_dst;

    DiracGolombLUT *future[4], *l = &lut_ctx[2*LUT_SIZE + buf[0]];

    INIT_RESIDUE(res, 0, 0);

#define APPEND_RESIDUE(N, M)         \

    N          |= M >> (N ## _bits); \

    N ## _bits +=      (M ## _bits)

    for (b = 1; b <= bytes; b++) {

        future[0] = &lut_ctx[buf[b]];

        future[1] = future[0] + 1*LUT_SIZE;

        future[2] = future[0] + 2*LUT_SIZE;

        future[3] = future[0] + 3*LUT_SIZE;

        if ((c_idx + 1) > coeffs)

            return c_idx;

        if (res_bits && l->sign) {

            int32_t coeff = 1;

            APPEND_RESIDUE(res, l->preamble);

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

                coeff <<= 1;

                coeff |= (res >> (RSIZE_BITS - 2*i - 2)) & 1;

            }

            dst[c_idx++] = l->sign * (coeff - 1);

            res_bits = res = 0;

        }

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

            dst[c_idx + i] = l->ready[i];

        c_idx += l->ready_num;

        APPEND_RESIDUE(res, l->leftover);

        l = future[l->need_s ? 3 : !res_bits ? 2 : res_bits & 1];

    }

    return c_idx;

}


static void spapr_tce_table_finalize(Object *obj)

{

    sPAPRTCETable *tcet = SPAPR_TCE_TABLE(obj);

    QLIST_REMOVE(tcet, list);

    if (!kvm_enabled() ||

        (kvmppc_remove_spapr_tce(tcet->table, tcet->fd,

                                 tcet->nb_table) != 0)) {

        g_free(tcet->table);

    }

}


int ff_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)

{

    uint8_t *src[4], *dst[4];

    int i, j, vsub, ret;

    int (*draw_slice)(AVFilterLink *, int, int, int);

    FF_TPRINTF_START(NULL, draw_slice); ff_tlog_link(NULL, link, 0); ff_tlog(NULL, " y:%d h:%d dir:%d\n", y, h, slice_dir);

    /* copy the slice if needed for permission reasons */

    if (link->src_buf) {

        vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;

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

            if (link->src_buf->data[i]) {

                src[i] = link->src_buf-> data[i] +

                    (y >> (i==1 || i==2 ? vsub : 0)) * link->src_buf-> linesize[i];

                dst[i] = link->cur_buf->data[i] +

                    (y >> (i==1 || i==2 ? vsub : 0)) * link->cur_buf->linesize[i];

            } else

                src[i] = dst[i] = NULL;

        }

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

            int planew =

                av_image_get_linesize(link->format, link->cur_buf->video->w, i);

            if (!src[i]) continue;

            for (j = 0; j < h >> (i==1 || i==2 ? vsub : 0); j++) {

                memcpy(dst[i], src[i], planew);

                src[i] += link->src_buf->linesize[i];

                dst[i] += link->cur_buf->linesize[i];

            }

        }

    }

    if (!(draw_slice = link->dstpad->draw_slice))

        draw_slice = default_draw_slice;

    ret = draw_slice(link, y, h, slice_dir);

    if (ret < 0)

        clear_link(link);

    return ret;

}


int qcrypto_cipher_encrypt(QCryptoCipher *cipher,
                           const void *in,
                           void *out,
                           size_t len,
                           Error **errp)
{
    QCryptoCipherBuiltin *ctxt = cipher->opaque;
    return ctxt->encrypt(cipher, in, out, len, errp);


static void e1000e_pci_foreach_callback(QPCIDevice *dev, int devfn, void *data)

{

    *(QPCIDevice **) data = dev;

}


static int rm_read_index(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    unsigned int size, n_pkts, str_id, next_off, n, pos, pts;

    AVStream *st;

    do {

        if (avio_rl32(pb) != MKTAG('I','N','D','X'))

            return -1;

        size     = avio_rb32(pb);

        if (size < 20)

            return -1;

        avio_skip(pb, 2);

        n_pkts   = avio_rb32(pb);

        str_id   = avio_rb16(pb);

        next_off = avio_rb32(pb);

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

            if (s->streams[n]->id == str_id) {

                st = s->streams[n];

                break;

            }

        if (n == s->nb_streams)

            goto skip;

        for (n = 0; n < n_pkts; n++) {

            avio_skip(pb, 2);

            pts = avio_rb32(pb);

            pos = avio_rb32(pb);

            avio_skip(pb, 4); /* packet no. */

            av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);

        }

skip:

        if (next_off && avio_tell(pb) != next_off &&

            avio_seek(pb, next_off, SEEK_SET) < 0)

            return -1;

    } while (next_off);

    return 0;

}


int ff_huff_gen_len_table(uint8_t *dst, const uint64_t *stats, int stats_size, int skip0)

{

    HeapElem *h  = av_malloc_array(sizeof(*h), stats_size);

    int *up      = av_malloc_array(sizeof(*up) * 2, stats_size);

    uint8_t *len = av_malloc_array(sizeof(*len) * 2, stats_size);

    uint16_t *map= av_malloc_array(sizeof(*map), stats_size);

    int offset, i, next;

    int size = 0;

    int ret = 0;

    if (!h || !up || !len) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

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

        dst[i] = 255;

        if (stats[i] || !skip0)

            map[size++] = i;

    }

    for (offset = 1; ; offset <<= 1) {

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

            h[i].name = i;

            h[i].val = (stats[map[i]] << 14) + offset;

        }

        for (i = size / 2 - 1; i >= 0; i--)

            heap_sift(h, i, size);

        for (next = size; next < size * 2 - 1; next++) {

            // merge the two smallest entries, and put it back in the heap

            uint64_t min1v = h[0].val;

            up[h[0].name] = next;

            h[0].val = INT64_MAX;

            heap_sift(h, 0, size);

            up[h[0].name] = next;

            h[0].name = next;

            h[0].val += min1v;

            heap_sift(h, 0, size);

        }

        len[2 * size - 2] = 0;

        for (i = 2 * size - 3; i >= size; i--)

            len[i] = len[up[i]] + 1;

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

            dst[map[i]] = len[up[i]] + 1;

            if (dst[map[i]] >= 32) break;

        }

        if (i==size) break;

    }

end:

    av_free(h);

    av_free(up);

    av_free(len);

    av_free(map);

    return ret;

}


static int dec_scc_r(CPUCRISState *env, DisasContext *dc)

{

    int cond = dc->op2;

    LOG_DIS("s%s $r%u\n",

            cc_name(cond), dc->op1);

    if (cond != CC_A) {

        int l1;

        gen_tst_cc(dc, cpu_R[dc->op1], cond);

        l1 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_R[dc->op1], 0, l1);

        tcg_gen_movi_tl(cpu_R[dc->op1], 1);

        gen_set_label(l1);

    } else {

        tcg_gen_movi_tl(cpu_R[dc->op1], 1);

    }

    cris_cc_mask(dc, 0);

    return 2;

}


static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,

                                      int64_t sector_num,

                                      QEMUIOVector *qiov,

                                      int nb_sectors,

                                      BlockCompletionFunc *cb,

                                      void *opaque,

                                      int is_write)

{

    BlockAIOCBSync *acb;

    acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);

    acb->is_write = is_write;

    acb->qiov = qiov;

    acb->bounce = qemu_try_blockalign(bs, qiov->size);

    acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);

    if (acb->bounce == NULL) {

        acb->ret = -ENOMEM;

    } else if (is_write) {

        qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);

        acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);

    } else {

        acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);

    }

    qemu_bh_schedule(acb->bh);

    return &acb->common;

}