static int decode_slice(struct AVCodecContext *avctx, void *arg){

    H264Context *h = *(void**)arg;

    MpegEncContext * const s = &h->s;

    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;

    int lf_x_start = s->mb_x;

    s->mb_skip_run= -1;

    h->is_complex = FRAME_MBAFF || s->picture_structure != PICT_FRAME || s->codec_id != CODEC_ID_H264 ||

                    (CONFIG_GRAY && (s->flags&CODEC_FLAG_GRAY));

    if( h->pps.cabac ) {

        /* realign */

        align_get_bits( &s->gb );

        /* init cabac */

        ff_init_cabac_states( &h->cabac);

        ff_init_cabac_decoder( &h->cabac,

                               s->gb.buffer + get_bits_count(&s->gb)/8,

                               (get_bits_left(&s->gb) + 7)/8);

        ff_h264_init_cabac_states(h);

        for(;;){

//START_TIMER

            int ret = ff_h264_decode_mb_cabac(h);

            int eos;

//STOP_TIMER("decode_mb_cabac")

            if(ret>=0) ff_h264_hl_decode_mb(h);

            if( ret >= 0 && FRAME_MBAFF ) { //FIXME optimal? or let mb_decode decode 16x32 ?

                s->mb_y++;

                ret = ff_h264_decode_mb_cabac(h);

                if(ret>=0) ff_h264_hl_decode_mb(h);

                s->mb_y--;

            }

            eos = get_cabac_terminate( &h->cabac );

            if((s->workaround_bugs & FF_BUG_TRUNCATED) && h->cabac.bytestream > h->cabac.bytestream_end + 2){

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                if (s->mb_x >= lf_x_start) loop_filter(h, lf_x_start, s->mb_x + 1);

                return 0;

            }

            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 2) {

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d, bytestream (%td)\n", s->mb_x, s->mb_y, h->cabac.bytestream_end - h->cabac.bytestream);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if( ++s->mb_x >= s->mb_width ) {

                loop_filter(h, lf_x_start, s->mb_x);

                s->mb_x = lf_x_start = 0;

                decode_finish_row(h);

                ++s->mb_y;

                if(FIELD_OR_MBAFF_PICTURE) {

                    ++s->mb_y;

                    if(FRAME_MBAFF && s->mb_y < s->mb_height)

                        predict_field_decoding_flag(h);

                }

            }

            if( eos || s->mb_y >= s->mb_height ) {

                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);

                return 0;

            }

        }

    } else {

        for(;;){

            int ret = ff_h264_decode_mb_cavlc(h);

            if(ret>=0) ff_h264_hl_decode_mb(h);

            if(ret>=0 && FRAME_MBAFF){ //FIXME optimal? or let mb_decode decode 16x32 ?

                s->mb_y++;

                ret = ff_h264_decode_mb_cavlc(h);

                if(ret>=0) ff_h264_hl_decode_mb(h);

                s->mb_y--;

            }

            if(ret<0){

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if(++s->mb_x >= s->mb_width){

                loop_filter(h, lf_x_start, s->mb_x);

                s->mb_x = lf_x_start = 0;

                decode_finish_row(h);

                ++s->mb_y;

                if(FIELD_OR_MBAFF_PICTURE) {

                    ++s->mb_y;

                    if(FRAME_MBAFF && s->mb_y < s->mb_height)

                        predict_field_decoding_flag(h);

                }

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

                    tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                    if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return 0;

                    }else{

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return -1;

                    }

                }

            }

            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){

                tprintf(s->avctx, "slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                    if (s->mb_x > lf_x_start) loop_filter(h, lf_x_start, s->mb_x);

                    return 0;

                }else{

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                    return -1;

                }

            }

        }

    }

#if 0

    for(;s->mb_y < s->mb_height; s->mb_y++){

        for(;s->mb_x < s->mb_width; s->mb_x++){

            int ret= decode_mb(h);

            ff_h264_hl_decode_mb(h);

            if(ret<0){

                av_log(s->avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if(++s->mb_x >= s->mb_width){

                s->mb_x=0;

                if(++s->mb_y >= s->mb_height){

                    if(get_bits_count(s->gb) == s->gb.size_in_bits){

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return 0;

                    }else{

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return -1;

                    }

                }

            }

            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){

                if(get_bits_count(s->gb) == s->gb.size_in_bits){

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                    return 0;

                }else{

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                    return -1;

                }

            }

        }

        s->mb_x=0;

        ff_draw_horiz_band(s, 16*s->mb_y, 16);

    }

#endif

    return -1; //not reached

}


int spapr_tce_dma_write(VIOsPAPRDevice *dev, uint64_t taddr, const void *buf,
                        uint32_t size)
{
#ifdef DEBUG_TCE
    fprintf(stderr, "spapr_tce_dma_write taddr=0x%llx size=0x%x\n",
            (unsigned long long)taddr, size);
#endif
    while (size) {
        uint64_t tce;
        uint32_t lsize;
        uint64_t txaddr;
        /* Check if we are in bound */
        if (taddr >= dev->rtce_window_size) {
#ifdef DEBUG_TCE
            fprintf(stderr, "spapr_tce_dma_write out of bounds\n");
#endif
            return H_DEST_PARM;
        tce = dev->rtce_table[taddr >> SPAPR_VIO_TCE_PAGE_SHIFT].tce;
        /* How much til end of page ? */
        lsize = MIN(size, ((~taddr) & SPAPR_VIO_TCE_PAGE_MASK) + 1);
        /* Check TCE */
        if (!(tce & 2)) {
            return H_DEST_PARM;
        /* Translate */
        txaddr = (tce & ~SPAPR_VIO_TCE_PAGE_MASK) |
            (taddr & SPAPR_VIO_TCE_PAGE_MASK);
#ifdef DEBUG_TCE
        fprintf(stderr, " -> write to txaddr=0x%llx, size=0x%x\n",
                (unsigned long long)txaddr, lsize);
#endif
        /* Do it */
        cpu_physical_memory_write(txaddr, buf, lsize);
        buf += lsize;
        taddr += lsize;
        size -= lsize;


void updateMMXDitherTables(SwsContext *c, int dstY, int lumBufIndex, int chrBufIndex,
                           int lastInLumBuf, int lastInChrBuf)
{
    const int dstH= c->dstH;
    const int flags= c->flags;
    int16_t **lumPixBuf= c->lumPixBuf;
    int16_t **chrUPixBuf= c->chrUPixBuf;
    int16_t **alpPixBuf= c->alpPixBuf;
    const int vLumBufSize= c->vLumBufSize;
    const int vChrBufSize= c->vChrBufSize;
    int16_t *vLumFilterPos= c->vLumFilterPos;
    int16_t *vChrFilterPos= c->vChrFilterPos;
    int16_t *vLumFilter= c->vLumFilter;
    int16_t *vChrFilter= c->vChrFilter;
    int32_t *lumMmxFilter= c->lumMmxFilter;
    int32_t *chrMmxFilter= c->chrMmxFilter;
    int32_t av_unused *alpMmxFilter= c->alpMmxFilter;
    const int vLumFilterSize= c->vLumFilterSize;
    const int vChrFilterSize= c->vChrFilterSize;
    const int chrDstY= dstY>>c->chrDstVSubSample;
    const int firstLumSrcY= vLumFilterPos[dstY]; //First line needed as input
    const int firstChrSrcY= vChrFilterPos[chrDstY]; //First line needed as input
    c->blueDither= ff_dither8[dstY&1];
    if (c->dstFormat == PIX_FMT_RGB555 || c->dstFormat == PIX_FMT_BGR555)
        c->greenDither= ff_dither8[dstY&1];
    else
        c->greenDither= ff_dither4[dstY&1];
    c->redDither= ff_dither8[(dstY+1)&1];
    if (dstY < dstH - 2) {
        const int16_t **lumSrcPtr= (const int16_t **) lumPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize;
        const int16_t **chrUSrcPtr= (const int16_t **) chrUPixBuf + chrBufIndex + firstChrSrcY - lastInChrBuf + vChrBufSize;
        const int16_t **alpSrcPtr= (CONFIG_SWSCALE_ALPHA && alpPixBuf) ? (const int16_t **) alpPixBuf + lumBufIndex + firstLumSrcY - lastInLumBuf + vLumBufSize : NULL;
        int i;
        if (flags & SWS_ACCURATE_RND) {
            int s= APCK_SIZE / 8;
            for (i=0; i<vLumFilterSize; i+=2) {
                *(const void**)&lumMmxFilter[s*i              ]= lumSrcPtr[i  ];
                *(const void**)&lumMmxFilter[s*i+APCK_PTR2/4  ]= lumSrcPtr[i+(vLumFilterSize>1)];
                lumMmxFilter[s*i+APCK_COEF/4  ]=
                lumMmxFilter[s*i+APCK_COEF/4+1]= vLumFilter[dstY*vLumFilterSize + i    ]
                + (vLumFilterSize>1 ? vLumFilter[dstY*vLumFilterSize + i + 1]<<16 : 0);
                if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
                    *(const void**)&alpMmxFilter[s*i              ]= alpSrcPtr[i  ];
                    *(const void**)&alpMmxFilter[s*i+APCK_PTR2/4  ]= alpSrcPtr[i+(vLumFilterSize>1)];
                    alpMmxFilter[s*i+APCK_COEF/4  ]=
                    alpMmxFilter[s*i+APCK_COEF/4+1]= lumMmxFilter[s*i+APCK_COEF/4  ];
            for (i=0; i<vChrFilterSize; i+=2) {
                *(const void**)&chrMmxFilter[s*i              ]= chrUSrcPtr[i  ];
                *(const void**)&chrMmxFilter[s*i+APCK_PTR2/4  ]= chrUSrcPtr[i+(vChrFilterSize>1)];
                chrMmxFilter[s*i+APCK_COEF/4  ]=
                chrMmxFilter[s*i+APCK_COEF/4+1]= vChrFilter[chrDstY*vChrFilterSize + i    ]
                + (vChrFilterSize>1 ? vChrFilter[chrDstY*vChrFilterSize + i + 1]<<16 : 0);
        } else {
            for (i=0; i<vLumFilterSize; i++) {
                *(const void**)&lumMmxFilter[4*i+0]= lumSrcPtr[i];
                lumMmxFilter[4*i+2]=
                lumMmxFilter[4*i+3]=
                ((uint16_t)vLumFilter[dstY*vLumFilterSize + i])*0x10001;
                if (CONFIG_SWSCALE_ALPHA && alpPixBuf) {
                    *(const void**)&alpMmxFilter[4*i+0]= alpSrcPtr[i];
                    alpMmxFilter[4*i+2]=
                    alpMmxFilter[4*i+3]= lumMmxFilter[4*i+2];
            for (i=0; i<vChrFilterSize; i++) {
                *(const void**)&chrMmxFilter[4*i+0]= chrUSrcPtr[i];
                chrMmxFilter[4*i+2]=
                chrMmxFilter[4*i+3]=
                ((uint16_t)vChrFilter[chrDstY*vChrFilterSize + i])*0x10001;


static void mp3_parse_vbr_tags(AVFormatContext *s, AVStream *st, int64_t base)

{

    uint32_t v, spf;

    int frames = -1; /* Total number of frames in file */

    const int64_t xing_offtbl[2][2] = {{32, 17}, {17,9}};

    MPADecodeContext c;

    v = get_be32(s->pb);

    if(ff_mpa_check_header(v) < 0)

      return;

    ff_mpegaudio_decode_header(&c, v);

    if(c.layer != 3)

        return;

    /* Check for Xing / Info tag */

    url_fseek(s->pb, xing_offtbl[c.lsf == 1][c.nb_channels == 1], SEEK_CUR);

    v = get_be32(s->pb);

    if(v == MKBETAG('X', 'i', 'n', 'g') || v == MKBETAG('I', 'n', 'f', 'o')) {

        v = get_be32(s->pb);

        if(v & 0x1)

            frames = get_be32(s->pb);

    }

    /* Check for VBRI tag (always 32 bytes after end of mpegaudio header) */

    url_fseek(s->pb, base + 4 + 32, SEEK_SET);

    v = get_be32(s->pb);

    if(v == MKBETAG('V', 'B', 'R', 'I')) {

        /* Check tag version */

        if(get_be16(s->pb) == 1) {

            /* skip delay, quality and total bytes */

            url_fseek(s->pb, 8, SEEK_CUR);

            frames = get_be32(s->pb);

        }

    }

    if(frames < 0)

        return;

    spf = c.lsf ? 576 : 1152; /* Samples per frame, layer 3 */

    st->duration = av_rescale_q(frames, (AVRational){spf, c.sample_rate},

                                st->time_base);

}


void vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,

                        void *opaque)

{

    VMStateField *field = vmsd->fields;

    if (vmsd->pre_save) {

        vmsd->pre_save(opaque);

    while (field->name) {

        if (!field->field_exists ||

            field->field_exists(opaque, vmsd->version_id)) {

            void *base_addr = vmstate_base_addr(opaque, field);

            int i, n_elems = vmstate_n_elems(opaque, field);

            int size = vmstate_size(opaque, field);

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

                void *addr = base_addr + size * i;

                if (field->flags & VMS_ARRAY_OF_POINTER) {

                    addr = *(void **)addr;

                if (field->flags & VMS_STRUCT) {

                    vmstate_save_state(f, field->vmsd, addr);

                    field->info->put(f, addr, size);

        field++;

    vmstate_subsection_save(f, vmsd, opaque);


static int v9fs_synth_closedir(FsContext *ctx, V9fsFidOpenState *fs)

{

    V9fsSynthOpenState *synth_open = fs->private;

    V9fsSynthNode *node = synth_open->node;

    node->open_count--;

    g_free(synth_open);

    fs->private = NULL;

    return 0;

}


static void mdct512(int32_t *out, int16_t *in)

{

    int i, re, im, re1, im1;

    int16_t rot[MDCT_SAMPLES];

    IComplex x[MDCT_SAMPLES/4];

    /* shift to simplify computations */

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

        rot[i] = -in[i + 3*MDCT_SAMPLES/4];

    for (;i < MDCT_SAMPLES; i++)

        rot[i] =  in[i -   MDCT_SAMPLES/4];

    /* pre rotation */

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

        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;

        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;

        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);

    }

    fft(x, MDCT_NBITS - 2);

    /* post rotation */

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

        re = x[i].re;

        im = x[i].im;

        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);

        out[                 2*i] = im1;

        out[MDCT_SAMPLES/2-1-2*i] = re1;

    }

}


static int blk_root_inactivate(BdrvChild *child)

{

    BlockBackend *blk = child->opaque;

    if (blk->disable_perm) {

        return 0;

    }

    /* Only inactivate BlockBackends for guest devices (which are inactive at

     * this point because the VM is stopped) and unattached monitor-owned

     * BlockBackends. If there is still any other user like a block job, then

     * we simply can't inactivate the image. */

    if (!blk->dev && !blk_name(blk)[0]) {

        return -EPERM;

    }

    blk->disable_perm = true;

    if (blk->root) {

        bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);

    }

    return 0;

}


static inline void vmsvga_update_rect_flush(struct vmsvga_state_s *s)

{

    struct vmsvga_rect_s *rect;

    if (s->invalidated) {

        s->redraw_fifo_first = s->redraw_fifo_last;

        return;

    }

    /* Overlapping region updates can be optimised out here - if someone

     * knows a smart algorithm to do that, please share.  */

    while (s->redraw_fifo_first != s->redraw_fifo_last) {

        rect = &s->redraw_fifo[s->redraw_fifo_first ++];

        s->redraw_fifo_first &= REDRAW_FIFO_LEN - 1;

        vmsvga_update_rect(s, rect->x, rect->y, rect->w, rect->h);

    }

}


length_f(int argc, char **argv)

{

        int64_t size;

	char s1[64];

	size = bdrv_getlength(bs);

	if (size < 0) {

		printf("getlength: %s", strerror(size));

		return 0;

	}

	cvtstr(size, s1, sizeof(s1));

	printf("%s\n", s1);

	return 0;

}


static void kvm_arm_gic_get(GICState *s)

{

    /* TODO: there isn't currently a kernel interface to get the GIC state */

}


static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,

                                      void *data, int *data_size,

                                      const uint8_t *buf, int buf_size)

{

    /* Note, the only difference between the 15Bpp and 16Bpp */

    /* Format is the pixel format, the packets are processed the same. */

    FlicDecodeContext *s = avctx->priv_data;

    int stream_ptr = 0;

    int pixel_ptr;

    unsigned char palette_idx1;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j;

    int lines;

    int compressed_lines;

    signed short line_packets;

    int y_ptr;

    int byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    int pixel;

    unsigned int pixel_limit;

    s->frame.reference = 1;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

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

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

        return -1;

    }

    pixels = s->frame.data[0];

    pixel_limit = s->avctx->height * s->frame.linesize[0];

    frame_size = AV_RL32(&buf[stream_ptr]);

    stream_ptr += 6;  /* skip the magic number */

    num_chunks = AV_RL16(&buf[stream_ptr]);

    stream_ptr += 10;  /* skip padding */

    frame_size -= 16;

    /* iterate through the chunks */

    while ((frame_size > 0) && (num_chunks > 0)) {

        chunk_size = AV_RL32(&buf[stream_ptr]);

        stream_ptr += 4;

        chunk_type = AV_RL16(&buf[stream_ptr]);

        stream_ptr += 2;

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

            /* For some reason, it seems that non-palettized flics do

             * include one of these chunks in their first frame.

             * Why I do not know, it seems rather extraneous. */

/*            av_log(avctx, AV_LOG_ERROR, "Unexpected Palette chunk %d in non-paletised FLC\n",chunk_type);*/

            stream_ptr = stream_ptr + chunk_size - 6;

            break;

        case FLI_DELTA:

        case FLI_DTA_LC:

            y_ptr = 0;

            compressed_lines = AV_RL16(&buf[stream_ptr]);

            stream_ptr += 2;

            while (compressed_lines > 0) {

                line_packets = AV_RL16(&buf[stream_ptr]);

                stream_ptr += 2;

                if (line_packets < 0) {

                    line_packets = -line_packets;

                    y_ptr += line_packets * s->frame.linesize[0];

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    CHECK_PIXEL_PTR(0);

                    pixel_countdown = s->avctx->width;

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

                        /* account for the skip bytes */

                        pixel_skip = buf[stream_ptr++];

                        pixel_ptr += (pixel_skip*2); /* Pixel is 2 bytes wide */

                        pixel_countdown -= pixel_skip;

                        byte_run = (signed char)(buf[stream_ptr++]);

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            pixel    = AV_RL16(&buf[stream_ptr]);

                            stream_ptr += 2;

                            CHECK_PIXEL_PTR(2 * byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {

                                *((signed short*)(&pixels[pixel_ptr])) = pixel;

                                pixel_ptr += 2;

                            }

                        } else {

                            CHECK_PIXEL_PTR(2 * byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);

                                stream_ptr += 2;

                                pixel_ptr += 2;

                            }

                        }

                    }

                    y_ptr += s->frame.linesize[0];

                }

            }

            break;

        case FLI_LC:

            av_log(avctx, AV_LOG_ERROR, "Unexpected FLI_LC chunk in non-paletised FLC\n");

            stream_ptr = stream_ptr + chunk_size - 6;

            break;

        case FLI_BLACK:

            /* set the whole frame to 0x0000 which is black in both 15Bpp and 16Bpp modes. */

            memset(pixels, 0x0000,

                   s->frame.linesize[0] * s->avctx->height);

            break;

        case FLI_BRUN:

            y_ptr = 0;

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

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                stream_ptr++;

                pixel_countdown = (s->avctx->width * 2);

                while (pixel_countdown > 0) {

                    byte_run = (signed char)(buf[stream_ptr++]);

                    if (byte_run > 0) {

                        palette_idx1 = buf[stream_ptr++];

                        CHECK_PIXEL_PTR(byte_run);

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) (linea%d)\n",

                                       pixel_countdown, lines);

                        }

                    } else {  /* copy bytes if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(byte_run);

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

                            palette_idx1 = buf[stream_ptr++];

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",

                                       pixel_countdown, lines);

                        }

                    }

                }

                /* Now FLX is strange, in that it is "byte" as opposed to "pixel" run length compressed.

                 * This does not give us any good oportunity to perform word endian conversion

                 * during decompression. So if it is required (i.e., this is not a LE target, we do

                 * a second pass over the line here, swapping the bytes.

                 */

#if HAVE_BIGENDIAN

                pixel_ptr = y_ptr;

                pixel_countdown = s->avctx->width;

                while (pixel_countdown > 0) {

                    *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[pixel_ptr]);

                    pixel_ptr += 2;

                }

#endif

                y_ptr += s->frame.linesize[0];

            }

            break;

        case FLI_DTA_BRUN:

            y_ptr = 0;

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

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                stream_ptr++;

                pixel_countdown = s->avctx->width; /* Width is in pixels, not bytes */

                while (pixel_countdown > 0) {

                    byte_run = (signed char)(buf[stream_ptr++]);

                    if (byte_run > 0) {

                        pixel    = AV_RL16(&buf[stream_ptr]);

                        stream_ptr += 2;

                        CHECK_PIXEL_PTR(2 * byte_run);

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

                            *((signed short*)(&pixels[pixel_ptr])) = pixel;

                            pixel_ptr += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    } else {  /* copy pixels if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(2 * byte_run);

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

                            *((signed short*)(&pixels[pixel_ptr])) = AV_RL16(&buf[stream_ptr]);

                            stream_ptr += 2;

                            pixel_ptr  += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d)\n",

                                       pixel_countdown);

                        }

                    }

                }

                y_ptr += s->frame.linesize[0];

            }

            break;

        case FLI_COPY:

        case FLI_DTA_COPY:

            /* copy the chunk (uncompressed frame) */

            if (chunk_size - 6 > (unsigned int)(s->avctx->width * s->avctx->height)*2) {

                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \

                       "bigger than image, skipping chunk\n", chunk_size - 6);

                stream_ptr += chunk_size - 6;

            } else {

                for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;

                     y_ptr += s->frame.linesize[0]) {

                    pixel_countdown = s->avctx->width;

                    pixel_ptr = 0;

                    while (pixel_countdown > 0) {

                      *((signed short*)(&pixels[y_ptr + pixel_ptr])) = AV_RL16(&buf[stream_ptr+pixel_ptr]);

                      pixel_ptr += 2;

                      pixel_countdown--;

                    }

                    stream_ptr += s->avctx->width*2;

                }

            }

            break;

        case FLI_MINI:

            /* some sort of a thumbnail? disregard this chunk... */

            stream_ptr += chunk_size - 6;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);

            break;

        }

        frame_size -= chunk_size;

        num_chunks--;

    }

    /* by the end of the chunk, the stream ptr should equal the frame

     * size (minus 1, possibly); if it doesn't, issue a warning */

    if ((stream_ptr != buf_size) && (stream_ptr != buf_size - 1))

        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \

               "and final chunk ptr = %d\n", buf_size, stream_ptr);

    *data_size=sizeof(AVFrame);

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

    return buf_size;

}


static void init_proc_601 (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_601(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID5, "HID5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_601_HID15, "HID15",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

#if !defined(CONFIG_USER_ONLY)

    env->nb_tlb = 64;

    env->nb_ways = 2;

    env->id_tlbs = 0;

#endif

    init_excp_601(env);

    env->dcache_line_size = 64;

    env->icache_line_size = 64;

    /* XXX: TODO: allocate internal IRQ controller */

}


static int i6300esb_init(PCIDevice *dev)

{

    I6300State *d = DO_UPCAST(I6300State, dev, dev);

    uint8_t *pci_conf;

    int io_mem;

    static CPUReadMemoryFunc * const mem_read[3] = {

        i6300esb_mem_readb,

        i6300esb_mem_readw,

        i6300esb_mem_readl,

    };

    static CPUWriteMemoryFunc * const mem_write[3] = {

        i6300esb_mem_writeb,

        i6300esb_mem_writew,

        i6300esb_mem_writel,

    };

    i6300esb_debug("I6300State = %p\n", d);

    d->timer = qemu_new_timer_ns(vm_clock, i6300esb_timer_expired, d);

    d->previous_reboot_flag = 0;

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_ESB_9);

    pci_config_set_class(pci_conf, PCI_CLASS_SYSTEM_OTHER);

    io_mem = cpu_register_io_memory(mem_read, mem_write, d,

                                    DEVICE_NATIVE_ENDIAN);

    pci_register_bar_simple(&d->dev, 0, 0x10, 0, io_mem);

    /* qemu_register_coalesced_mmio (addr, 0x10); ? */

    return 0;

}


NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset,

                          off_t size, uint32_t nbdflags)

{

    NBDExport *exp = g_malloc0(sizeof(NBDExport));

    QSIMPLEQ_INIT(&exp->requests);

    exp->refcount = 1;

    QTAILQ_INIT(&exp->clients);

    exp->bs = bs;

    exp->dev_offset = dev_offset;

    exp->nbdflags = nbdflags;

    exp->size = size == -1 ? bdrv_getlength(bs) : size;

    return exp;

}


static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,

                                            int64_t sector_num,

                                            QEMUIOVector *qiov,

                                            int nb_sectors,

                                            BlockDriverCompletionFunc *cb,

                                            void *opaque,

                                            int is_write)

{

    BlockDriverAIOCBSync *acb;

    acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);

    acb->is_write = is_write;

    acb->qiov = qiov;

    acb->bounce = qemu_blockalign(bs, qiov->size);

    acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);

    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;

}


static void write_audio_frame(AVFormatContext *oc, AVStream *st)

{

    AVCodecContext *c;

    AVPacket pkt = { 0 }; // data and size must be 0;

    int got_packet, ret, dst_nb_samples;

    av_init_packet(&pkt);

    c = st->codec;

    get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);

    /* convert samples from native format to destination codec format, using the resampler */

    if (swr_ctx) {

        /* compute destination number of samples */

        dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,

                                        c->sample_rate, c->sample_rate, AV_ROUND_UP);

        if (dst_nb_samples > max_dst_nb_samples) {

            av_free(dst_samples_data[0]);

            ret = av_samples_alloc(dst_samples_data, &dst_samples_linesize, c->channels,

                                   dst_nb_samples, c->sample_fmt, 0);

            if (ret < 0)

                exit(1);

            max_dst_nb_samples = dst_nb_samples;

            dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,

                                                          c->sample_fmt, 0);

        }

        /* convert to destination format */

        ret = swr_convert(swr_ctx,

                          dst_samples_data, dst_nb_samples,

                          (const uint8_t **)src_samples_data, src_nb_samples);

        if (ret < 0) {

            fprintf(stderr, "Error while converting\n");

            exit(1);

        }

    } else {

        dst_nb_samples = src_nb_samples;

    }

    audio_frame->nb_samples = dst_nb_samples;

    audio_frame->pts = av_rescale_q(samples_count, (AVRational){1, c->sample_rate}, c->time_base);

    avcodec_fill_audio_frame(audio_frame, c->channels, c->sample_fmt,

                             dst_samples_data[0], dst_samples_size, 0);

    samples_count += dst_nb_samples;

    ret = avcodec_encode_audio2(c, &pkt, audio_frame, &got_packet);

    if (ret < 0) {

        fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));

        exit(1);

    }

    if (!got_packet)

        return;

    ret = write_frame(oc, &c->time_base, st, &pkt);

    if (ret != 0) {

        fprintf(stderr, "Error while writing audio frame: %s\n",

                av_err2str(ret));

        exit(1);

    }

}


static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,

                                   uint32_t event, uint32_t reason)

{

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    VirtIOSCSIReq *req = virtio_scsi_pop_req(s, vs->event_vq);

    VirtIOSCSIEvent *evt;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    int in_size;

    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        return;

    }

    if (!req) {

        s->events_dropped = true;

        return;

    }

    if (req->elem.out_num || req->elem.in_num != 1) {

        virtio_scsi_bad_req();

    }

    if (s->events_dropped) {

        event |= VIRTIO_SCSI_T_EVENTS_MISSED;

        s->events_dropped = false;

    }

    in_size = req->elem.in_sg[0].iov_len;

    if (in_size < sizeof(VirtIOSCSIEvent)) {

        virtio_scsi_bad_req();

    }

    evt = req->resp.event;

    memset(evt, 0, sizeof(VirtIOSCSIEvent));

    evt->event = event;

    evt->reason = reason;

    if (!dev) {

        assert(event == VIRTIO_SCSI_T_NO_EVENT);

    } else {

        evt->lun[0] = 1;

        evt->lun[1] = dev->id;

        /* Linux wants us to keep the same encoding we use for REPORT LUNS.  */

        if (dev->lun >= 256) {

            evt->lun[2] = (dev->lun >> 8) | 0x40;

        }

        evt->lun[3] = dev->lun & 0xFF;

    }

    virtio_scsi_complete_req(req);

}


AVFrame *avcodec_alloc_frame(void)

{

    AVFrame *frame = av_malloc(sizeof(AVFrame));

    if (frame == NULL)

        return NULL;

    avcodec_get_frame_defaults(frame);

    return frame;

}


static void ahci_irq_raise(AHCIState *s, AHCIDevice *dev)

{

    AHCIPCIState *d = container_of(s, AHCIPCIState, ahci);

    PCIDevice *pci_dev =

        (PCIDevice *)object_dynamic_cast(OBJECT(d), TYPE_PCI_DEVICE);

    DPRINTF(0, "raise irq\n");

    if (pci_dev && msi_enabled(pci_dev)) {

        msi_notify(pci_dev, 0);

    } else {

        qemu_irq_raise(s->irq);

    }

}


static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack *track)

{

    const char *descr, *hdlr, *hdlr_type;

    int64_t pos = url_ftell(pb);

    if (!track) { /* no media --> data handler */

        hdlr = "dhlr";

        hdlr_type = "url ";

        descr = "DataHandler";

    } else {

        hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";

        if (track->enc->codec_type == CODEC_TYPE_VIDEO) {

            hdlr_type = "vide";

            descr = "VideoHandler";

        } else if (track->enc->codec_type == CODEC_TYPE_AUDIO){

            hdlr_type = "soun";

            descr = "SoundHandler";

        } else if (track->enc->codec_type == CODEC_TYPE_SUBTITLE){

            if (track->mode == MODE_IPOD) hdlr_type = "sbtl";

            else                          hdlr_type = "text";

            descr = "SubtitleHandler";

        }

    }

    put_be32(pb, 0); /* size */

    put_tag(pb, "hdlr");

    put_be32(pb, 0); /* Version & flags */

    put_buffer(pb, hdlr, 4); /* handler */

    put_tag(pb, hdlr_type); /* handler type */

    put_be32(pb ,0); /* reserved */

    put_be32(pb ,0); /* reserved */

    put_be32(pb ,0); /* reserved */

    put_byte(pb, strlen(descr)); /* string counter */

    put_buffer(pb, descr, strlen(descr)); /* handler description */

    return updateSize(pb, pos);

}


static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)

{

    MPCContext *c = s->priv_data;

    int tag;

    int64_t size, pos, ppos[2];

    uint8_t *buf;

    int i, t, seekd;

    GetBitContext gb;

    if (s->nb_streams == 0) {

        av_log(s, AV_LOG_ERROR, "No stream added before parsing seek table\n");

        return;

    }

    avio_seek(s->pb, off, SEEK_SET);

    mpc8_get_chunk_header(s->pb, &tag, &size);

    if(tag != TAG_SEEKTABLE){

        av_log(s, AV_LOG_ERROR, "No seek table at given position\n");

        return;

    }

    if (size > INT_MAX/10 || size<=0) {

        av_log(s, AV_LOG_ERROR, "Bad seek table size\n");

        return;

    }

    if(!(buf = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE)))

        return;

    avio_read(s->pb, buf, size);

    memset(buf+size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

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

    size = gb_get_v(&gb);

    if(size > UINT_MAX/4 || size > c->samples/1152){

        av_log(s, AV_LOG_ERROR, "Seek table is too big\n");

        return;

    }

    seekd = get_bits(&gb, 4);

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

        pos = gb_get_v(&gb) + c->header_pos;

        ppos[1 - i] = pos;

        av_add_index_entry(s->streams[0], pos, i, 0, 0, AVINDEX_KEYFRAME);

    }

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

        t = get_unary(&gb, 1, 33) << 12;

        t += get_bits(&gb, 12);

        if(t & 1)

            t = -(t & ~1);

        pos = (t >> 1) + ppos[0]*2 - ppos[1];

        av_add_index_entry(s->streams[0], pos, i << seekd, 0, 0, AVINDEX_KEYFRAME);

        ppos[1] = ppos[0];

        ppos[0] = pos;

    }

    av_free(buf);

}


static int ftp_features(FTPContext *s)

{

    static const char *feat_command        = "FEAT\r\n";

    static const char *enable_utf8_command = "OPTS UTF8 ON\r\n";

    static const int feat_codes[] = {211, 0};

    static const int opts_codes[] = {200, 451};

    char *feat;

    if (ftp_send_command(s, feat_command, feat_codes, &feat) == 211) {

        if (av_stristr(feat, "UTF8"))

            ftp_send_command(s, enable_utf8_command, opts_codes, NULL);

    }

    return 0;

}


void run_on_cpu(CPUState *env, void (*func)(void *data), void *data)

{

    struct qemu_work_item wi;

    if (qemu_cpu_self(env)) {

        func(data);

        return;

    }

    wi.func = func;

    wi.data = data;

    if (!env->queued_work_first)

        env->queued_work_first = &wi;

    else

        env->queued_work_last->next = &wi;

    env->queued_work_last = &wi;

    wi.next = NULL;

    wi.done = false;

    qemu_cpu_kick(env);

    while (!wi.done) {

        CPUState *self_env = cpu_single_env;

        qemu_cond_wait(&qemu_work_cond, &qemu_global_mutex);

        cpu_single_env = self_env;

    }

}


static int ffserver_apply_stream_config(AVCodecContext *enc, const AVDictionary *conf, AVDictionary **opts)

{

    AVDictionaryEntry *e;

    int ret = 0;

    /* Return values from ffserver_set_*_param are ignored.

       Values are initially parsed and checked before inserting to AVDictionary. */

    //video params

    if ((e = av_dict_get(conf, "VideoBitRateRangeMin", NULL, 0)))

        ffserver_set_int_param(&enc->rc_min_rate, e->value, 1000, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoBitRateRangeMax", NULL, 0)))

        ffserver_set_int_param(&enc->rc_max_rate, e->value, 1000, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "Debug", NULL, 0)))

        ffserver_set_int_param(&enc->debug, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "Strict", NULL, 0)))

        ffserver_set_int_param(&enc->strict_std_compliance, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoBufferSize", NULL, 0)))

        ffserver_set_int_param(&enc->rc_buffer_size, e->value, 8*1024, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoBitRateTolerance", NULL, 0)))

        ffserver_set_int_param(&enc->bit_rate_tolerance, e->value, 1000, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoBitRate", NULL, 0)))

        ffserver_set_int_param(&enc->bit_rate, e->value, 1000, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoSizeWidth", NULL, 0)))

        ffserver_set_int_param(&enc->width, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoSizeHeight", NULL, 0)))

        ffserver_set_int_param(&enc->height, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "PixelFormat", NULL, 0))) {

        int val;

        ffserver_set_int_param(&val, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

        enc->pix_fmt = val;

    }

    if ((e = av_dict_get(conf, "VideoGopSize", NULL, 0)))

        ffserver_set_int_param(&enc->gop_size, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoFrameRateNum", NULL, 0)))

        ffserver_set_int_param(&enc->time_base.num, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoFrameRateDen", NULL, 0)))

        ffserver_set_int_param(&enc->time_base.den, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoQDiff", NULL, 0)))

        ffserver_set_int_param(&enc->max_qdiff, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoQMax", NULL, 0)))

        ffserver_set_int_param(&enc->qmax, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "VideoQMin", NULL, 0)))

        ffserver_set_int_param(&enc->qmin, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "LumiMask", NULL, 0)))

        ffserver_set_float_param(&enc->lumi_masking, e->value, 0, -FLT_MAX, FLT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "DarkMask", NULL, 0)))

        ffserver_set_float_param(&enc->dark_masking, e->value, 0, -FLT_MAX, FLT_MAX, NULL, 0, NULL);

    if (av_dict_get(conf, "BitExact", NULL, 0))

        enc->flags |= CODEC_FLAG_BITEXACT;

    if (av_dict_get(conf, "DctFastint", NULL, 0))

        enc->dct_algo  = FF_DCT_FASTINT;

    if (av_dict_get(conf, "IdctSimple", NULL, 0))

        enc->idct_algo = FF_IDCT_SIMPLE;

    if (av_dict_get(conf, "VideoHighQuality", NULL, 0))

        enc->mb_decision = FF_MB_DECISION_BITS;

    if ((e = av_dict_get(conf, "VideoTag", NULL, 0)))

        enc->codec_tag = MKTAG(e->value[0], e->value[1], e->value[2], e->value[3]);

    if (av_dict_get(conf, "Qscale", NULL, 0)) {

        enc->flags |= CODEC_FLAG_QSCALE;

        ffserver_set_int_param(&enc->global_quality, e->value, FF_QP2LAMBDA, INT_MIN, INT_MAX, NULL, 0, NULL);

    }

    if (av_dict_get(conf, "Video4MotionVector", NULL, 0)) {

        enc->mb_decision = FF_MB_DECISION_BITS; //FIXME remove

        enc->flags |= CODEC_FLAG_4MV;

    }

    //audio params

    if ((e = av_dict_get(conf, "AudioChannels", NULL, 0)))

        ffserver_set_int_param(&enc->channels, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "AudioSampleRate", NULL, 0)))

        ffserver_set_int_param(&enc->sample_rate, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    if ((e = av_dict_get(conf, "AudioBitRate", NULL, 0)))

        ffserver_set_int_param(&enc->bit_rate, e->value, 0, INT_MIN, INT_MAX, NULL, 0, NULL);

    av_opt_set_dict2(enc, opts, AV_OPT_SEARCH_CHILDREN);

    e = NULL;

    while (e = av_dict_get(*opts, "", e, AV_DICT_IGNORE_SUFFIX)) {

        av_log(NULL, AV_LOG_ERROR, "Provided AVOption '%s' doesn't match any existing option.\n", e->key);

        ret = AVERROR(EINVAL);

    }

    return ret;

}


static sd_rsp_type_t sd_normal_command(SDState *sd,

                                       SDRequest req)

{

    uint32_t rca = 0x0000;

    uint64_t addr = (sd->ocr & (1 << 30)) ? (uint64_t) req.arg << 9 : req.arg;

    if (sd_cmd_type[req.cmd] == sd_ac || sd_cmd_type[req.cmd] == sd_adtc)

        rca = req.arg >> 16;

    DPRINTF("CMD%d 0x%08x state %d\n", req.cmd, req.arg, sd->state);

    switch (req.cmd) {

    /* Basic commands (Class 0 and Class 1) */

    case 0:	/* CMD0:   GO_IDLE_STATE */

        switch (sd->state) {

        case sd_inactive_state:

            return sd->spi ? sd_r1 : sd_r0;

        default:

            sd->state = sd_idle_state;

            sd_reset(sd, sd->bdrv);

            return sd->spi ? sd_r1 : sd_r0;

        }

        break;

    case 1:	/* CMD1:   SEND_OP_CMD */

        if (!sd->spi)

            goto bad_cmd;

        sd->state = sd_transfer_state;

        return sd_r1;

    case 2:	/* CMD2:   ALL_SEND_CID */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_ready_state:

            sd->state = sd_identification_state;

            return sd_r2_i;

        default:

            break;

        }

        break;

    case 3:	/* CMD3:   SEND_RELATIVE_ADDR */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_identification_state:

        case sd_standby_state:

            sd->state = sd_standby_state;

            sd_set_rca(sd);

            return sd_r6;

        default:

            break;

        }

        break;

    case 4:	/* CMD4:   SEND_DSR */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_standby_state:

            break;

        default:

            break;

        }

        break;

    case 5: /* CMD5: reserved for SDIO cards */

        sd->card_status |= ILLEGAL_COMMAND;

        return sd_r0;

    case 6:	/* CMD6:   SWITCH_FUNCTION */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->mode) {

        case sd_data_transfer_mode:

            sd_function_switch(sd, req.arg);

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 7:	/* CMD7:   SELECT/DESELECT_CARD */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_standby_state:

            if (sd->rca != rca)

                return sd_r0;

            sd->state = sd_transfer_state;

            return sd_r1b;

        case sd_transfer_state:

        case sd_sendingdata_state:

            if (sd->rca == rca)

                break;

            sd->state = sd_standby_state;

            return sd_r1b;

        case sd_disconnect_state:

            if (sd->rca != rca)

                return sd_r0;

            sd->state = sd_programming_state;

            return sd_r1b;

        case sd_programming_state:

            if (sd->rca == rca)

                break;

            sd->state = sd_disconnect_state;

            return sd_r1b;

        default:

            break;

        }

        break;

    case 8:	/* CMD8:   SEND_IF_COND */

        /* Physical Layer Specification Version 2.00 command */

        switch (sd->state) {

        case sd_idle_state:

            sd->vhs = 0;

            /* No response if not exactly one VHS bit is set.  */

            if (!(req.arg >> 8) || (req.arg >> ffs(req.arg & ~0xff)))

                return sd->spi ? sd_r7 : sd_r0;

            /* Accept.  */

            sd->vhs = req.arg;

            return sd_r7;

        default:

            break;

        }

        break;

    case 9:	/* CMD9:   SEND_CSD */

        switch (sd->state) {

        case sd_standby_state:

            if (sd->rca != rca)

                return sd_r0;

            return sd_r2_s;

        case sd_transfer_state:

            if (!sd->spi)

                break;

            sd->state = sd_sendingdata_state;

            memcpy(sd->data, sd->csd, 16);

            sd->data_start = addr;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 10:	/* CMD10:  SEND_CID */

        switch (sd->state) {

        case sd_standby_state:

            if (sd->rca != rca)

                return sd_r0;

            return sd_r2_i;

        case sd_transfer_state:

            if (!sd->spi)

                break;

            sd->state = sd_sendingdata_state;

            memcpy(sd->data, sd->cid, 16);

            sd->data_start = addr;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 11:	/* CMD11:  READ_DAT_UNTIL_STOP */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = req.arg;

            sd->data_offset = 0;

            if (sd->data_start + sd->blk_len > sd->size)

                sd->card_status |= ADDRESS_ERROR;

            return sd_r0;

        default:

            break;

        }

        break;

    case 12:	/* CMD12:  STOP_TRANSMISSION */

        switch (sd->state) {

        case sd_sendingdata_state:

            sd->state = sd_transfer_state;

            return sd_r1b;

        case sd_receivingdata_state:

            sd->state = sd_programming_state;

            /* Bzzzzzzztt .... Operation complete.  */

            sd->state = sd_transfer_state;

            return sd_r1b;

        default:

            break;

        }

        break;

    case 13:	/* CMD13:  SEND_STATUS */

        switch (sd->mode) {

        case sd_data_transfer_mode:

            if (sd->rca != rca)

                return sd_r0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 15:	/* CMD15:  GO_INACTIVE_STATE */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->mode) {

        case sd_data_transfer_mode:

            if (sd->rca != rca)

                return sd_r0;

            sd->state = sd_inactive_state;

            return sd_r0;

        default:

            break;

        }

        break;

    /* Block read commands (Classs 2) */

    case 16:	/* CMD16:  SET_BLOCKLEN */

        switch (sd->state) {

        case sd_transfer_state:

            if (req.arg > (1 << HWBLOCK_SHIFT))

                sd->card_status |= BLOCK_LEN_ERROR;

            else

                sd->blk_len = req.arg;

            return sd_r1;

        default:

            break;

        }

        break;

    case 17:	/* CMD17:  READ_SINGLE_BLOCK */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = addr;

            sd->data_offset = 0;

            if (sd->data_start + sd->blk_len > sd->size)

                sd->card_status |= ADDRESS_ERROR;

            return sd_r1;

        default:

            break;

        }

        break;

    case 18:	/* CMD18:  READ_MULTIPLE_BLOCK */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = addr;

            sd->data_offset = 0;

            if (sd->data_start + sd->blk_len > sd->size)

                sd->card_status |= ADDRESS_ERROR;

            return sd_r1;

        default:

            break;

        }

        break;

    /* Block write commands (Class 4) */

    case 24:	/* CMD24:  WRITE_SINGLE_BLOCK */

        if (sd->spi)

            goto unimplemented_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            /* Writing in SPI mode not implemented.  */

            if (sd->spi)

                break;

            sd->state = sd_receivingdata_state;

            sd->data_start = addr;

            sd->data_offset = 0;

            sd->blk_written = 0;

            if (sd->data_start + sd->blk_len > sd->size)

                sd->card_status |= ADDRESS_ERROR;

            if (sd_wp_addr(sd, sd->data_start))

                sd->card_status |= WP_VIOLATION;

            if (sd->csd[14] & 0x30)

                sd->card_status |= WP_VIOLATION;

            return sd_r1;

        default:

            break;

        }

        break;

    case 25:	/* CMD25:  WRITE_MULTIPLE_BLOCK */

        if (sd->spi)

            goto unimplemented_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            /* Writing in SPI mode not implemented.  */

            if (sd->spi)

                break;

            sd->state = sd_receivingdata_state;

            sd->data_start = addr;

            sd->data_offset = 0;

            sd->blk_written = 0;

            if (sd->data_start + sd->blk_len > sd->size)

                sd->card_status |= ADDRESS_ERROR;

            if (sd_wp_addr(sd, sd->data_start))

                sd->card_status |= WP_VIOLATION;

            if (sd->csd[14] & 0x30)

                sd->card_status |= WP_VIOLATION;

            return sd_r1;

        default:

            break;

        }

        break;

    case 26:	/* CMD26:  PROGRAM_CID */

        if (sd->spi)

            goto bad_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_receivingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 27:	/* CMD27:  PROGRAM_CSD */

        if (sd->spi)

            goto unimplemented_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_receivingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    /* Write protection (Class 6) */

    case 28:	/* CMD28:  SET_WRITE_PROT */

        switch (sd->state) {

        case sd_transfer_state:

            if (addr >= sd->size) {

                sd->card_status |= ADDRESS_ERROR;

                return sd_r1b;

            }

            sd->state = sd_programming_state;

            sd->wp_groups[addr >> (HWBLOCK_SHIFT +

                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 1;

            /* Bzzzzzzztt .... Operation complete.  */

            sd->state = sd_transfer_state;

            return sd_r1b;

        default:

            break;

        }

        break;

    case 29:	/* CMD29:  CLR_WRITE_PROT */

        switch (sd->state) {

        case sd_transfer_state:

            if (addr >= sd->size) {

                sd->card_status |= ADDRESS_ERROR;

                return sd_r1b;

            }

            sd->state = sd_programming_state;

            sd->wp_groups[addr >> (HWBLOCK_SHIFT +

                            SECTOR_SHIFT + WPGROUP_SHIFT)] = 0;

            /* Bzzzzzzztt .... Operation complete.  */

            sd->state = sd_transfer_state;

            return sd_r1b;

        default:

            break;

        }

        break;

    case 30:	/* CMD30:  SEND_WRITE_PROT */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            *(uint32_t *) sd->data = sd_wpbits(sd, req.arg);

            sd->data_start = addr;

            sd->data_offset = 0;

            return sd_r1b;

        default:

            break;

        }

        break;

    /* Erase commands (Class 5) */

    case 32:	/* CMD32:  ERASE_WR_BLK_START */

        switch (sd->state) {

        case sd_transfer_state:

            sd->erase_start = req.arg;

            return sd_r1;

        default:

            break;

        }

        break;

    case 33:	/* CMD33:  ERASE_WR_BLK_END */

        switch (sd->state) {

        case sd_transfer_state:

            sd->erase_end = req.arg;

            return sd_r1;

        default:

            break;

        }

        break;

    case 38:	/* CMD38:  ERASE */

        switch (sd->state) {

        case sd_transfer_state:

            if (sd->csd[14] & 0x30) {

                sd->card_status |= WP_VIOLATION;

                return sd_r1b;

            }

            sd->state = sd_programming_state;

            sd_erase(sd);

            /* Bzzzzzzztt .... Operation complete.  */

            sd->state = sd_transfer_state;

            return sd_r1b;

        default:

            break;

        }

        break;

    /* Lock card commands (Class 7) */

    case 42:	/* CMD42:  LOCK_UNLOCK */

        if (sd->spi)

            goto unimplemented_cmd;

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_receivingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 52:

    case 53:

        /* CMD52, CMD53: reserved for SDIO cards

         * (see the SDIO Simplified Specification V2.0)

         * Handle as illegal command but do not complain

         * on stderr, as some OSes may use these in their

         * probing for presence of an SDIO card.

         */

        sd->card_status |= ILLEGAL_COMMAND;

        return sd_r0;

    /* Application specific commands (Class 8) */

    case 55:	/* CMD55:  APP_CMD */

        if (sd->rca != rca)

            return sd_r0;

        sd->card_status |= APP_CMD;

        return sd_r1;

    case 56:	/* CMD56:  GEN_CMD */

        fprintf(stderr, "SD: GEN_CMD 0x%08x\n", req.arg);

        switch (sd->state) {

        case sd_transfer_state:

            sd->data_offset = 0;

            if (req.arg & 1)

                sd->state = sd_sendingdata_state;

            else

                sd->state = sd_receivingdata_state;

            return sd_r1;

        default:

            break;

        }

        break;

    default:

    bad_cmd:

        sd->card_status |= ILLEGAL_COMMAND;

        fprintf(stderr, "SD: Unknown CMD%i\n", req.cmd);

        return sd_r0;

    unimplemented_cmd:

        /* Commands that are recognised but not yet implemented in SPI mode.  */

        sd->card_status |= ILLEGAL_COMMAND;

        fprintf(stderr, "SD: CMD%i not implemented in SPI mode\n", req.cmd);

        return sd_r0;

    }

    sd->card_status |= ILLEGAL_COMMAND;

    fprintf(stderr, "SD: CMD%i in a wrong state\n", req.cmd);

    return sd_r0;

}


int avfilter_graph_parse(AVFilterGraph *graph, const char *filters,

                         AVFilterInOut **open_inputs, AVFilterInOut **open_outputs,

                         void *log_ctx)

{

    int index = 0, ret;

    char chr = 0;

    AVFilterInOut *curr_inputs = NULL;

    do {

        AVFilterContext *filter;

        const char *filterchain = filters;

        filters += strspn(filters, WHITESPACES);

        if ((ret = parse_inputs(&filters, &curr_inputs, open_outputs, log_ctx)) < 0)

            goto fail;

        if ((ret = parse_filter(&filter, &filters, graph, index, log_ctx)) < 0)

            goto fail;

        if (filter->input_count == 1 && !curr_inputs && !index) {

            /* First input can be omitted if it is "[in]" */

            const char *tmp = "[in]";

            if ((ret = parse_inputs(&tmp, &curr_inputs, open_outputs, log_ctx)) < 0)

                goto fail;

        }

        if ((ret = link_filter_inouts(filter, &curr_inputs, open_inputs, log_ctx)) < 0)

            goto fail;

        if ((ret = parse_outputs(&filters, &curr_inputs, open_inputs, open_outputs,

                                 log_ctx)) < 0)

            goto fail;

        filters += strspn(filters, WHITESPACES);

        chr = *filters++;

        if (chr == ';' && curr_inputs) {

            av_log(log_ctx, AV_LOG_ERROR,

                   "Invalid filterchain containing an unlabelled output pad: \"%s\"\n",

                   filterchain);

            ret = AVERROR(EINVAL);

            goto fail;

        }

        index++;

    } while (chr == ',' || chr == ';');

    if (chr) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Unable to parse graph description substring: \"%s\"\n",

               filters - 1);

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if (*open_inputs && !strcmp((*open_inputs)->name, "out") && curr_inputs) {

        /* Last output can be omitted if it is "[out]" */

        const char *tmp = "[out]";

        if ((ret = parse_outputs(&tmp, &curr_inputs, open_inputs, open_outputs,

                                 log_ctx)) < 0)

            goto fail;

    }

    return 0;

 fail:

    for (; graph->filter_count > 0; graph->filter_count--)

        avfilter_free(graph->filters[graph->filter_count - 1]);

    av_freep(&graph->filters);

    avfilter_inout_free(open_inputs);

    avfilter_inout_free(open_outputs);

    avfilter_inout_free(&curr_inputs);

    return ret;

}


static int libopenjpeg_decode_frame(AVCodecContext *avctx,

                                    void *data, int *data_size,

                                    AVPacket *avpkt)

{

    uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    LibOpenJPEGContext *ctx = avctx->priv_data;

    AVFrame *picture = &ctx->image, *output = data;

    opj_dinfo_t *dec;

    opj_cio_t *stream;

    opj_image_t *image;

    int width, height, ret = -1;

    int pixel_size = 0;

    int ispacked = 0;

    *data_size = 0;

    // Check if input is a raw jpeg2k codestream or in jp2 wrapping

    if((AV_RB32(buf) == 12) &&

       (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&

       (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {

        dec = opj_create_decompress(CODEC_JP2);

    } else {

        // If the AVPacket contains a jp2c box, then skip to

        // the starting byte of the codestream.

        if (AV_RB32(buf + 4) == AV_RB32("jp2c"))

            buf += 8;

        dec = opj_create_decompress(CODEC_J2K);

    if(!dec) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");

    opj_set_event_mgr((opj_common_ptr)dec, NULL, NULL);

    ctx->dec_params.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;

    // Tie decoder with decoding parameters

    opj_setup_decoder(dec, &ctx->dec_params);

    stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);

    if(!stream) {

        av_log(avctx, AV_LOG_ERROR, "Codestream could not be opened for reading.\n");

    // Decode the header only

    image = opj_decode_with_info(dec, stream, NULL);

    opj_cio_close(stream);

    width  = image->x1 - image->x0;

    height = image->y1 - image->y0;

    if(av_image_check_size(width, height, 0, avctx) < 0) {

        av_log(avctx, AV_LOG_ERROR, "%dx%d dimension invalid.\n", width, height);

        goto done;

    avcodec_set_dimensions(avctx, width, height);

    switch (image->numcomps) {

    case 1:  avctx->pix_fmt = (image->comps[0].bpp == 8) ? PIX_FMT_GRAY8 : PIX_FMT_GRAY16;

             break;

    case 2:  avctx->pix_fmt = PIX_FMT_GRAY8A;

             break;

    case 3:

    case 4:  avctx->pix_fmt = check_image_attributes(avctx, image);

             break;

    default: av_log(avctx, AV_LOG_ERROR, "%d components unsupported.\n", image->numcomps);

             goto done;

    if(picture->data[0])

        ff_thread_release_buffer(avctx, picture);

    if(ff_thread_get_buffer(avctx, picture) < 0){

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

    ctx->dec_params.cp_limit_decoding = NO_LIMITATION;

    ctx->dec_params.cp_reduce = avctx->lowres;

    // Tie decoder with decoding parameters

    opj_setup_decoder(dec, &ctx->dec_params);

    stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);

    if(!stream) {

        av_log(avctx, AV_LOG_ERROR, "Codestream could not be opened for reading.\n");

    // Decode the codestream

    image = opj_decode_with_info(dec, stream, NULL);

    opj_cio_close(stream);

    pixel_size = av_pix_fmt_descriptors[avctx->pix_fmt].comp[0].step_minus1 + 1;

    ispacked = libopenjpeg_ispacked(avctx->pix_fmt);

    switch (pixel_size) {

    case 1:

        if (ispacked) {

            libopenjpeg_copy_to_packed8(picture, image);

        } else {

            libopenjpeg_copyto8(picture, image);

        break;

    case 2:

        if (ispacked) {

            libopenjpeg_copy_to_packed8(picture, image);

        } else {

            libopenjpeg_copyto16(picture, image);

        break;

    case 3:

    case 4:

        if (ispacked) {

            libopenjpeg_copy_to_packed8(picture, image);

        break;

    case 6:

    case 8:

        if (ispacked) {

            libopenjpeg_copy_to_packed16(picture, image);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "unsupported pixel size %d\n", pixel_size);

        goto done;

    *output    = ctx->image;

    *data_size = sizeof(AVPicture);

    ret = buf_size;

done:

    opj_image_destroy(image);

    return ret;


void ffv1_clear_slice_state(FFV1Context *f, FFV1Context *fs)

{

    int i, j;

    for (i = 0; i < f->plane_count; i++) {

        PlaneContext *p = &fs->plane[i];

        p->interlace_bit_state[0] = 128;

        p->interlace_bit_state[1] = 128;

        if (fs->ac) {

            if (f->initial_states[p->quant_table_index]) {

                memcpy(p->state, f->initial_states[p->quant_table_index],

                       CONTEXT_SIZE * p->context_count);

            } else

                memset(p->state, 128, CONTEXT_SIZE * p->context_count);

        } else {

            for (j = 0; j < p->context_count; j++) {

                p->vlc_state[j].drift     = 0;

                p->vlc_state[j].error_sum = 4;    //FFMAX((RANGE + 32)/64, 2);

                p->vlc_state[j].bias      = 0;

                p->vlc_state[j].count     = 1;

            }

        }

    }

}


static int av_buffersrc_add_frame_internal(AVFilterContext *ctx,

                                           AVFrame *frame, int flags)

{

    BufferSourceContext *s = ctx->priv;

    AVFrame *copy;

    int ret;

    if (!frame) {

        s->eof = 1;

        return 0;

    } else if (s->eof)

        return AVERROR(EINVAL);

    if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {

    switch (ctx->outputs[0]->type) {

    case AVMEDIA_TYPE_VIDEO:

        CHECK_VIDEO_PARAM_CHANGE(ctx, s, frame->width, frame->height,

                                 frame->format);

        break;

    case AVMEDIA_TYPE_AUDIO:

        CHECK_AUDIO_PARAM_CHANGE(ctx, s, frame->sample_rate, frame->channel_layout,

                                 frame->format);

        break;

    default:

        return AVERROR(EINVAL);

    }

    }

    if (!av_fifo_space(s->fifo) &&

        (ret = av_fifo_realloc2(s->fifo, av_fifo_size(s->fifo) +

                                         sizeof(copy))) < 0)

        return ret;

    if (!(copy = av_frame_alloc()))

        return AVERROR(ENOMEM);

    av_frame_move_ref(copy, frame);

    if ((ret = av_fifo_generic_write(s->fifo, &copy, sizeof(copy), NULL)) < 0) {

        av_frame_move_ref(frame, copy);

        av_frame_free(&copy);

        return ret;

    }

    if ((flags & AV_BUFFERSRC_FLAG_PUSH))

        if ((ret = ctx->output_pads[0].request_frame(ctx->outputs[0])) < 0)

            return ret;

    return 0;

}


static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)

{

    ASFContext *asf = s->priv_data;

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

    int64_t pos;

    int index;

    if (s->packet_size <= 0)

        return -1;

    /* Try using the protocol's read_seek if available */

    if(s->pb) {

        int ret = avio_seek_time(s->pb, stream_index, pts, flags);

        if(ret >= 0)

            asf_reset_header(s);

        if (ret != AVERROR(ENOSYS))

            return ret;

    }

    if (!asf->index_read)

        asf_build_simple_index(s, stream_index);

    if((asf->index_read && st->index_entries)){

        index= av_index_search_timestamp(st, pts, flags);

        if(index >= 0) {

            /* find the position */

            pos = st->index_entries[index].pos;

            /* do the seek */

            av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);

            avio_seek(s->pb, pos, SEEK_SET);

            asf_reset_header(s);

            return 0;

        }

    }

    /* no index or seeking by index failed */

    if(av_seek_frame_binary(s, stream_index, pts, flags)<0)

        return -1;

    asf_reset_header(s);

    return 0;

}


static void decode(RA288Context *ractx, float gain, int cb_coef)

{

    int i, j;

    double sumsum;

    float sum, buffer[5];

    memmove(ractx->sp_block + 5, ractx->sp_block, 36*sizeof(*ractx->sp_block));

    for (i=4; i >= 0; i--)

        ractx->sp_block[i] = -scalar_product_float(ractx->sp_block + i + 1,

                                             ractx->sp_lpc, 36);

    /* block 46 of G.728 spec */

    sum = 32. - scalar_product_float(ractx->gain_lpc, ractx->gain_block, 10);

    /* block 47 of G.728 spec */

    sum = av_clipf(sum, 0, 60);

    /* block 48 of G.728 spec */

    sumsum = exp(sum * 0.1151292546497) * gain; /* pow(10.0,sum/20)*gain */

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

        buffer[i] = codetable[cb_coef][i] * sumsum;

    sum = scalar_product_float(buffer, buffer, 5) / 5;

    sum = FFMAX(sum, 1);

    /* shift and store */

    memmove(ractx->gain_block, ractx->gain_block - 1,

            10 * sizeof(*ractx->gain_block));

    *ractx->gain_block = 10 * log10(sum) - 32;

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

        for (j=i-1; j >= 0; j--)

            buffer[i] -= ractx->sp_lpc[i-j-1] * buffer[j];

    /* output */

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

        ractx->sp_block[4-i] =

            av_clipf(ractx->sp_block[4-i] + buffer[i], -4095, 4095);

}


static void color16(WaveformContext *s, AVFrame *in, AVFrame *out,

                    int component, int intensity, int offset, int column)

{

    const int plane = s->desc->comp[component].plane;

    const int mirror = s->mirror;

    const int limit = s->size - 1;

    const uint16_t *c0_data = (const uint16_t *)in->data[plane + 0];

    const uint16_t *c1_data = (const uint16_t *)in->data[(plane + 1) % s->ncomp];

    const uint16_t *c2_data = (const uint16_t *)in->data[(plane + 2) % s->ncomp];

    const int c0_linesize = in->linesize[ plane + 0 ] / 2;

    const int c1_linesize = in->linesize[(plane + 1) % s->ncomp] / 2;

    const int c2_linesize = in->linesize[(plane + 2) % s->ncomp] / 2;

    const int d0_linesize = out->linesize[ plane + 0 ] / 2;

    const int d1_linesize = out->linesize[(plane + 1) % s->ncomp] / 2;

    const int d2_linesize = out->linesize[(plane + 2) % s->ncomp] / 2;

    const int src_h = in->height;

    const int src_w = in->width;

    int x, y;

    if (s->mode) {

        const int d0_signed_linesize = d0_linesize * (mirror == 1 ? -1 : 1);

        const int d1_signed_linesize = d1_linesize * (mirror == 1 ? -1 : 1);

        const int d2_signed_linesize = d2_linesize * (mirror == 1 ? -1 : 1);

        uint16_t *d0_data = (uint16_t *)out->data[plane] + offset * d0_linesize;

        uint16_t *d1_data = (uint16_t *)out->data[(plane + 1) % s->ncomp] + offset * d1_linesize;

        uint16_t *d2_data = (uint16_t *)out->data[(plane + 2) % s->ncomp] + offset * d2_linesize;

        uint16_t * const d0_bottom_line = d0_data + d0_linesize * (s->size - 1);

        uint16_t * const d0 = (mirror ? d0_bottom_line : d0_data);

        uint16_t * const d1_bottom_line = d1_data + d1_linesize * (s->size - 1);

        uint16_t * const d1 = (mirror ? d1_bottom_line : d1_data);

        uint16_t * const d2_bottom_line = d2_data + d2_linesize * (s->size - 1);

        uint16_t * const d2 = (mirror ? d2_bottom_line : d2_data);

        for (y = 0; y < src_h; y++) {

            for (x = 0; x < src_w; x++) {

                const int c0 = FFMIN(c0_data[x], limit);

                const int c1 = c1_data[x];

                const int c2 = c2_data[x];

                *(d0 + d0_signed_linesize * c0 + x) = c0;

                *(d1 + d1_signed_linesize * c0 + x) = c1;

                *(d2 + d2_signed_linesize * c0 + x) = c2;

            }

            c0_data += c0_linesize;

            c1_data += c1_linesize;

            c2_data += c2_linesize;

            d0_data += d0_linesize;

            d1_data += d1_linesize;

            d2_data += d2_linesize;

        }

    } else {

        uint16_t *d0_data = (uint16_t *)out->data[plane] + offset;

        uint16_t *d1_data = (uint16_t *)out->data[(plane + 1) % s->ncomp] + offset;

        uint16_t *d2_data = (uint16_t *)out->data[(plane + 2) % s->ncomp] + offset;

        if (mirror) {

            d0_data += s->size - 1;

            d1_data += s->size - 1;

            d2_data += s->size - 1;

        }

        for (y = 0; y < src_h; y++) {

            for (x = 0; x < src_w; x++) {

                const int c0 = FFMIN(c0_data[x], limit);

                const int c1 = c1_data[x];

                const int c2 = c2_data[x];

                if (mirror) {

                    *(d0_data - c0) = c0;

                    *(d1_data - c0) = c1;

                    *(d2_data - c0) = c2;

                } else {

                    *(d0_data + c0) = c0;

                    *(d1_data + c0) = c1;

                    *(d2_data + c0) = c2;

                }

            }

            c0_data += c0_linesize;

            c1_data += c1_linesize;

            c2_data += c2_linesize;

            d0_data += d0_linesize;

            d1_data += d1_linesize;

            d2_data += d2_linesize;

        }

    }

    envelope16(s, out, plane, plane);

}


static int get_uint8_equal(QEMUFile *f, void *pv, size_t size)

{

    uint8_t *v = pv;

    uint8_t v2;

    qemu_get_8s(f, &v2);

    if (*v == v2) {

        return 0;

    }

    return -EINVAL;

}


static void test_visitor_in_intList(TestInputVisitorData *data,

                                    const void *unused)

{

    int64_t value[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20};

    int16List *res = NULL, *tmp;

    Error *err = NULL;

    Visitor *v;

    int i = 0;

    v = visitor_input_test_init(data, "1,2,0,2-4,20,5-9,1-8");

    visit_type_int16List(v, NULL, &res, &error_abort);

    tmp = res;

    while (i < sizeof(value) / sizeof(value[0])) {

        g_assert(tmp);

        g_assert_cmpint(tmp->value, ==, value[i++]);

        tmp = tmp->next;

    }

    g_assert(!tmp);

    tmp = res;

    while (tmp) {

        res = res->next;

        g_free(tmp);

        tmp = res;

    }

    visitor_input_teardown(data, unused);

    v = visitor_input_test_init(data, "not an int list");

    visit_type_int16List(v, NULL, &res, &err);

    /* FIXME fix the visitor, then error_free_or_abort(&err) here */

}


gen_intermediate_code_internal(CPUState *env, TranslationBlock *tb,

                               int search_pc)

{

	uint16_t *gen_opc_end;

   	uint32_t pc_start;

	unsigned int insn_len;

	int j, lj;

	struct DisasContext *dc = &ctx;

	uint32_t next_page_start;

	pc_start = tb->pc;

	dc->env = env;

	dc->tb = tb;

	gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

	dc->is_jmp = DISAS_NEXT;

	dc->pc = pc_start;

	dc->singlestep_enabled = env->singlestep_enabled;

	dc->flagx_live = 0;

	dc->flags_x = 0;

	next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

	lj = -1;

	do

	{

		check_breakpoint(env, dc);

		if (dc->is_jmp == DISAS_JUMP)

			goto done;

		if (search_pc) {

			j = gen_opc_ptr - gen_opc_buf;

			if (lj < j) {

				lj++;

				while (lj < j)

					gen_opc_instr_start[lj++] = 0;

			}

			gen_opc_pc[lj] = dc->pc;

			gen_opc_instr_start[lj] = 1;

		}

		insn_len = cris_decoder(dc);

		STATS(gen_op_exec_insn());

		dc->pc += insn_len;

		if (!dc->flagx_live

		    || (dc->flagx_live &&

			!(dc->cc_op == CC_OP_FLAGS && dc->flags_x))) {

			gen_movl_T0_preg[PR_CCS]();

			gen_op_andl_T0_im(~X_FLAG);

			gen_movl_preg_T0[PR_CCS]();

			dc->flagx_live = 1;

			dc->flags_x = 0;

		}

		/* Check for delayed branches here. If we do it before

		   actually genereating any host code, the simulator will just

		   loop doing nothing for on this program location.  */

		if (dc->delayed_branch) {

			dc->delayed_branch--;

			if (dc->delayed_branch == 0)

			{

				if (dc->bcc == CC_A) {

					gen_op_jmp1 ();

					dc->is_jmp = DISAS_UPDATE;

				}

				else {

					/* Conditional jmp.  */

					gen_op_cc_jmp (dc->delayed_pc, dc->pc);

					dc->is_jmp = DISAS_UPDATE;

				}

			}

		}

		if (env->singlestep_enabled)

			break;

	} while (!dc->is_jmp && gen_opc_ptr < gen_opc_end

		 && dc->pc < next_page_start);

	if (!dc->is_jmp) {

		gen_op_movl_T0_im((long)dc->pc);

		gen_op_movl_pc_T0();

	}

	cris_evaluate_flags (dc);

  done:

	if (__builtin_expect(env->singlestep_enabled, 0)) {

		gen_op_debug();

	} else {

		switch(dc->is_jmp) {

			case DISAS_NEXT:

				gen_goto_tb(dc, 1, dc->pc);

				break;

			default:

			case DISAS_JUMP:

			case DISAS_UPDATE:

				/* indicate that the hash table must be used

				   to find the next TB */

				tcg_gen_exit_tb(0);

				break;

			case DISAS_TB_JUMP:

				/* nothing more to generate */

				break;

		}

	}

	*gen_opc_ptr = INDEX_op_end;

	if (search_pc) {

		j = gen_opc_ptr - gen_opc_buf;

		lj++;

		while (lj <= j)

			gen_opc_instr_start[lj++] = 0;

	} else {

		tb->size = dc->pc - pc_start;

	}

#ifdef DEBUG_DISAS

	if (loglevel & CPU_LOG_TB_IN_ASM) {

		fprintf(logfile, "--------------\n");

		fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start));

		target_disas(logfile, pc_start, dc->pc + 4 - pc_start, 0);

		fprintf(logfile, "\n");

	}

#endif

	return 0;

}


static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

	unsigned int width, unsigned int height,

	int lumStride, int chromStride, int dstStride, int vertLumPerChroma)

{

	unsigned y;

	const unsigned chromWidth= width>>1;

	for(y=0; y<height; y++)

	{

#ifdef HAVE_MMX

//FIXME handle 2 lines a once (fewer prefetch, reuse some chrom, but very likely limited by mem anyway)

		asm volatile(

			"xor %%"REG_a", %%"REG_a"	\n\t"

			".balign 16			\n\t"

			"1:				\n\t"

			PREFETCH" 32(%1, %%"REG_a", 2)	\n\t"

			PREFETCH" 32(%2, %%"REG_a")	\n\t"

			PREFETCH" 32(%3, %%"REG_a")	\n\t"

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

			"movq %%mm0, %%mm2		\n\t" // U(0)

			"movq (%3, %%"REG_a"), %%mm1	\n\t" // V(0)

			"punpcklbw %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"punpckhbw %%mm1, %%mm2		\n\t" // UVUV UVUV(8)

			"movq (%1, %%"REG_a",2), %%mm3	\n\t" // Y(0)

			"movq 8(%1, %%"REG_a",2), %%mm5	\n\t" // Y(8)

			"movq %%mm3, %%mm4		\n\t" // Y(0)

			"movq %%mm5, %%mm6		\n\t" // Y(8)

			"punpcklbw %%mm0, %%mm3		\n\t" // YUYV YUYV(0)

			"punpckhbw %%mm0, %%mm4		\n\t" // YUYV YUYV(4)

			"punpcklbw %%mm2, %%mm5		\n\t" // YUYV YUYV(8)

			"punpckhbw %%mm2, %%mm6		\n\t" // YUYV YUYV(12)

			MOVNTQ" %%mm3, (%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm4, 8(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm5, 16(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm6, 24(%0, %%"REG_a", 4)\n\t"

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

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

			" jb 1b				\n\t"

			::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" ((long)chromWidth)

			: "%"REG_a

		);

#else

#if defined ARCH_ALPHA && defined HAVE_MVI

#define pl2yuy2(n)					\

	y1 = yc[n];					\

	y2 = yc2[n];					\

	u = uc[n];					\

	v = vc[n];					\

	asm("unpkbw %1, %0" : "=r"(y1) : "r"(y1));	\

	asm("unpkbw %1, %0" : "=r"(y2) : "r"(y2));	\

	asm("unpkbl %1, %0" : "=r"(u) : "r"(u));	\

	asm("unpkbl %1, %0" : "=r"(v) : "r"(v));	\

	yuv1 = (u << 8) + (v << 24);			\

	yuv2 = yuv1 + y2;				\

	yuv1 += y1;					\

	qdst[n] = yuv1;					\

	qdst2[n] = yuv2;

		int i;

		uint64_t *qdst = (uint64_t *) dst;

		uint64_t *qdst2 = (uint64_t *) (dst + dstStride);

		const uint32_t *yc = (uint32_t *) ysrc;

		const uint32_t *yc2 = (uint32_t *) (ysrc + lumStride);

		const uint16_t *uc = (uint16_t*) usrc, *vc = (uint16_t*) vsrc;

		for(i = 0; i < chromWidth; i += 8){

			uint64_t y1, y2, yuv1, yuv2;

			uint64_t u, v;

			/* Prefetch */

			asm("ldq $31,64(%0)" :: "r"(yc));

			asm("ldq $31,64(%0)" :: "r"(yc2));

			asm("ldq $31,64(%0)" :: "r"(uc));

			asm("ldq $31,64(%0)" :: "r"(vc));

			pl2yuy2(0);

			pl2yuy2(1);

			pl2yuy2(2);

			pl2yuy2(3);

			yc += 4;

			yc2 += 4;

			uc += 4;

			vc += 4;

			qdst += 4;

			qdst2 += 4;

		}

		y++;

		ysrc += lumStride;

		dst += dstStride;

#elif __WORDSIZE >= 64

		int i;

		uint64_t *ldst = (uint64_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

			uint64_t k, l;

			k = yc[0] + (uc[0] << 8) +

			    (yc[1] << 16) + (vc[0] << 24);

			l = yc[2] + (uc[1] << 8) +

			    (yc[3] << 16) + (vc[1] << 24);

			*ldst++ = k + (l << 32);

			yc += 4;

			uc += 2;

			vc += 2;

		}

#else

		int i, *idst = (int32_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#ifdef WORDS_BIGENDIAN

			*idst++ = (yc[0] << 24)+ (uc[0] << 16) +

			    (yc[1] << 8) + (vc[0] << 0);

#else

			*idst++ = yc[0] + (uc[0] << 8) +

			    (yc[1] << 16) + (vc[0] << 24);

#endif

			yc += 2;

			uc++;

			vc++;

		}

#endif

#endif

		if((y&(vertLumPerChroma-1))==(vertLumPerChroma-1) )

		{

			usrc += chromStride;

			vsrc += chromStride;

		}

		ysrc += lumStride;

		dst += dstStride;

	}

#ifdef HAVE_MMX

asm(    EMMS" \n\t"

        SFENCE" \n\t"

        :::"memory");

#endif

}


static void vc1_inv_trans_4x4_dc_c(uint8_t *dest, int linesize, DCTELEM *block)

{

    int i;

    int dc = block[0];

    const uint8_t *cm;

    dc = (17 * dc +  4) >> 3;

    dc = (17 * dc + 64) >> 7;

    cm = ff_cropTbl + MAX_NEG_CROP + dc;

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

        dest[0] = cm[dest[0]];

        dest[1] = cm[dest[1]];

        dest[2] = cm[dest[2]];

        dest[3] = cm[dest[3]];

        dest += linesize;

    }

}


static void read_sbr_noise(SpectralBandReplication *sbr, GetBitContext *gb,

                           SBRData *ch_data, int ch)

{

    int i, j;

    VLC_TYPE (*t_huff)[2], (*f_huff)[2];

    int t_lav, f_lav;

    int delta = (ch == 1 && sbr->bs_coupling == 1) + 1;

    if (sbr->bs_coupling && ch) {

        t_huff = vlc_sbr[T_HUFFMAN_NOISE_BAL_3_0DB].table;

        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_BAL_3_0DB];

        f_huff = vlc_sbr[F_HUFFMAN_ENV_BAL_3_0DB].table;

        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_BAL_3_0DB];

    } else {

        t_huff = vlc_sbr[T_HUFFMAN_NOISE_3_0DB].table;

        t_lav  = vlc_sbr_lav[T_HUFFMAN_NOISE_3_0DB];

        f_huff = vlc_sbr[F_HUFFMAN_ENV_3_0DB].table;

        f_lav  = vlc_sbr_lav[F_HUFFMAN_ENV_3_0DB];

    }

#if USE_FIXED

    for (i = 0; i < ch_data->bs_num_noise; i++) {

        if (ch_data->bs_df_noise[i]) {

            for (j = 0; j < sbr->n_q; j++)

                ch_data->noise_facs[i + 1][j].mant = ch_data->noise_facs[i][j].mant + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);

        } else {

            ch_data->noise_facs[i + 1][0].mant = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level

            for (j = 1; j < sbr->n_q; j++)

                ch_data->noise_facs[i + 1][j].mant = ch_data->noise_facs[i + 1][j - 1].mant + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);

        }

    }

#else

    for (i = 0; i < ch_data->bs_num_noise; i++) {

        if (ch_data->bs_df_noise[i]) {

            for (j = 0; j < sbr->n_q; j++)

                ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i][j] + delta * (get_vlc2(gb, t_huff, 9, 2) - t_lav);

        } else {

            ch_data->noise_facs[i + 1][0] = delta * get_bits(gb, 5); // bs_noise_start_value_balance or bs_noise_start_value_level

            for (j = 1; j < sbr->n_q; j++)

                ch_data->noise_facs[i + 1][j] = ch_data->noise_facs[i + 1][j - 1] + delta * (get_vlc2(gb, f_huff, 9, 3) - f_lav);

        }

    }

#endif /* USE_FIXED */

    //assign 0th elements of noise_facs from last elements

    memcpy(ch_data->noise_facs[0], ch_data->noise_facs[ch_data->bs_num_noise],

           sizeof(ch_data->noise_facs[0]));

}


void bdrv_io_limits_disable(BlockDriverState *bs)

{

    bs->io_limits_enabled = false;

    bdrv_start_throttled_reqs(bs);

    throttle_destroy(&bs->throttle_state);

}


static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    BlockDriver *drv = bs->drv;

    BdrvTrackedRequest req;

    uint64_t align = bdrv_get_align(bs);

    uint8_t *head_buf = NULL;

    uint8_t *tail_buf = NULL;

    QEMUIOVector local_qiov;

    bool use_local_qiov = false;

    int ret;

    if (!drv) {

        return -ENOMEDIUM;

    }

    ret = bdrv_check_byte_request(bs, offset, bytes);

    if (ret < 0) {

        return ret;

    }

    if (bs->copy_on_read) {

        flags |= BDRV_REQ_COPY_ON_READ;

    }

    /* throttling disk I/O */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_intercept(bs, bytes, false);

    }

    /* Align read if necessary by padding qiov */

    if (offset & (align - 1)) {

        head_buf = qemu_blockalign(bs, align);

        qemu_iovec_init(&local_qiov, qiov->niov + 2);

        qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));

        qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

        use_local_qiov = true;

        bytes += offset & (align - 1);

        offset = offset & ~(align - 1);

    }

    if ((offset + bytes) & (align - 1)) {

        if (!use_local_qiov) {

            qemu_iovec_init(&local_qiov, qiov->niov + 1);

            qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

            use_local_qiov = true;

        }

        tail_buf = qemu_blockalign(bs, align);

        qemu_iovec_add(&local_qiov, tail_buf,

                       align - ((offset + bytes) & (align - 1)));

        bytes = ROUND_UP(bytes, align);

    }

    tracked_request_begin(&req, bs, offset, bytes, false);

    ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,

                              use_local_qiov ? &local_qiov : qiov,

                              flags);

    tracked_request_end(&req);

    if (use_local_qiov) {

        qemu_iovec_destroy(&local_qiov);

        qemu_vfree(head_buf);

        qemu_vfree(tail_buf);

    }

    return ret;

}


void kvmppc_update_sdr1(target_ulong sdr1)

{

    CPUState *cs;

    CPU_FOREACH(cs) {

        run_on_cpu(cs, kvmppc_pivot_hpt_cpu, RUN_ON_CPU_TARGET_PTR(sdr1));

    }

}


static void vfio_start_irqfd_injection(SysBusDevice *sbdev, qemu_irq irq)

{

    VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(sbdev);

    VFIOINTp *intp;

    if (!kvm_irqfds_enabled() || !kvm_resamplefds_enabled() ||

        !vdev->irqfd_allowed) {

        goto fail_irqfd;

    }

    QLIST_FOREACH(intp, &vdev->intp_list, next) {

        if (intp->qemuirq == irq) {

            break;

        }

    }

    assert(intp);

    if (kvm_irqchip_add_irqfd_notifier(kvm_state, &intp->interrupt,

                                   &intp->unmask, irq) < 0) {

        goto fail_irqfd;

    }

    if (vfio_set_trigger_eventfd(intp, NULL) < 0) {

        goto fail_vfio;

    }

    if (vfio_set_resample_eventfd(intp) < 0) {

        goto fail_vfio;

    }

    intp->kvm_accel = true;

    trace_vfio_platform_start_irqfd_injection(intp->pin,

                                     event_notifier_get_fd(&intp->interrupt),

                                     event_notifier_get_fd(&intp->unmask));

    return;

fail_vfio:

    kvm_irqchip_remove_irqfd_notifier(kvm_state, &intp->interrupt, irq);

    error_report("vfio: failed to start eventfd signaling for IRQ %d: %m",

                 intp->pin);

    abort();

fail_irqfd:

    vfio_start_eventfd_injection(sbdev, irq);

    return;

}


static void omap_mpuio_write(void *opaque, target_phys_addr_t addr,

                             uint64_t value, unsigned size)

{

    struct omap_mpuio_s *s = (struct omap_mpuio_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    uint16_t diff;

    int ln;

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    switch (offset) {

    case 0x04:	/* OUTPUT_REG */

        diff = (s->outputs ^ value) & ~s->dir;

        s->outputs = value;

        while ((ln = ffs(diff))) {

            ln --;

            if (s->handler[ln])

                qemu_set_irq(s->handler[ln], (value >> ln) & 1);

            diff &= ~(1 << ln);

        }

        break;

    case 0x08:	/* IO_CNTL */

        diff = s->outputs & (s->dir ^ value);

        s->dir = value;

        value = s->outputs & ~s->dir;

        while ((ln = ffs(diff))) {

            ln --;

            if (s->handler[ln])

                qemu_set_irq(s->handler[ln], (value >> ln) & 1);

            diff &= ~(1 << ln);

        }

        break;

    case 0x14:	/* KBC_REG */

        s->cols = value;

        omap_mpuio_kbd_update(s);

        break;

    case 0x18:	/* GPIO_EVENT_MODE_REG */

        s->event = value & 0x1f;

        break;

    case 0x1c:	/* GPIO_INT_EDGE_REG */

        s->edge = value;

        break;

    case 0x28:	/* KBD_MASKIT */

        s->kbd_mask = value & 1;

        omap_mpuio_kbd_update(s);

        break;

    case 0x2c:	/* GPIO_MASKIT */

        s->mask = value;

        break;

    case 0x30:	/* GPIO_DEBOUNCING_REG */

        s->debounce = value & 0x1ff;

        break;

    case 0x00:	/* INPUT_LATCH */

    case 0x10:	/* KBR_LATCH */

    case 0x20:	/* KBD_INT */

    case 0x24:	/* GPIO_INT */

    case 0x34:	/* GPIO_LATCH_REG */

        OMAP_RO_REG(addr);

        return;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


int net_init_tap(const NetClientOptions *opts, const char *name,

                 NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    const NetdevTapOptions *tap;

    int fd, vnet_hdr = 0, i = 0, queues;

    /* for the no-fd, no-helper case */

    const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */

    const char *downscript = NULL;

    Error *err = NULL;

    const char *vhostfdname;

    char ifname[128];

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);

    tap = opts->tap;

    queues = tap->has_queues ? tap->queues : 1;

    vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL;

    /* QEMU vlans does not support multiqueue tap, in this case peer is set.

     * For -netdev, peer is always NULL. */

    if (peer && (tap->has_queues || tap->has_fds || tap->has_vhostfds)) {

        error_report("Multiqueue tap cannot be used with QEMU vlans");

        return -1;

    }

    if (tap->has_fd) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_fds || tap->has_vhostfds) {

            error_report("ifname=, script=, downscript=, vnet_hdr=, "

                         "helper=, queues=, fds=, and vhostfds= "

                         "are invalid with fd=");

            return -1;

        }

        fd = monitor_fd_param(cur_mon, tap->fd, &err);

        if (fd == -1) {

            error_report_err(err);

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        net_init_tap_one(tap, peer, "tap", name, NULL,

                         script, downscript,

                         vhostfdname, vnet_hdr, fd, &err);

        if (err) {

            error_report_err(err);

            return -1;

        }

    } else if (tap->has_fds) {

        char *fds[MAX_TAP_QUEUES];

        char *vhost_fds[MAX_TAP_QUEUES];

        int nfds, nvhosts;

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_vhostfd) {

            error_report("ifname=, script=, downscript=, vnet_hdr=, "

                         "helper=, queues=, and vhostfd= "

                         "are invalid with fds=");

            return -1;

        }

        nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);

        if (tap->has_vhostfds) {

            nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);

            if (nfds != nvhosts) {

                error_report("The number of fds passed does not match the "

                             "number of vhostfds passed");

                return -1;

            }

        }

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

            fd = monitor_fd_param(cur_mon, fds[i], &err);

            if (fd == -1) {

                error_report_err(err);

                return -1;

            }

            fcntl(fd, F_SETFL, O_NONBLOCK);

            if (i == 0) {

                vnet_hdr = tap_probe_vnet_hdr(fd);

            } else if (vnet_hdr != tap_probe_vnet_hdr(fd)) {

                error_report("vnet_hdr not consistent across given tap fds");

                return -1;

            }

            net_init_tap_one(tap, peer, "tap", name, ifname,

                             script, downscript,

                             tap->has_vhostfds ? vhost_fds[i] : NULL,

                             vnet_hdr, fd, &err);

            if (err) {

                error_report_err(err);

                return -1;

            }

        }

    } else if (tap->has_helper) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_queues || tap->has_vhostfds) {

            error_report("ifname=, script=, downscript=, and vnet_hdr= "

                         "queues=, and vhostfds= are invalid with helper=");

            return -1;

        }

        fd = net_bridge_run_helper(tap->helper, DEFAULT_BRIDGE_INTERFACE,

                                   errp);

        if (fd == -1) {

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        net_init_tap_one(tap, peer, "bridge", name, ifname,

                         script, downscript, vhostfdname,

                         vnet_hdr, fd, &err);

        if (err) {

            error_report_err(err);

            close(fd);

            return -1;

        }

    } else {

        if (tap->has_vhostfds) {

            error_report("vhostfds= is invalid if fds= wasn't specified");

            return -1;

        }

        script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT;

        downscript = tap->has_downscript ? tap->downscript :

            DEFAULT_NETWORK_DOWN_SCRIPT;

        if (tap->has_ifname) {

            pstrcpy(ifname, sizeof ifname, tap->ifname);

        } else {

            ifname[0] = '\0';

        }

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

            fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,

                              ifname, sizeof ifname, queues > 1, &err);

            if (fd == -1) {

                error_report_err(err);

                return -1;

            }

            if (queues > 1 && i == 0 && !tap->has_ifname) {

                if (tap_fd_get_ifname(fd, ifname)) {

                    error_report("Fail to get ifname");

                    close(fd);

                    return -1;

                }

            }

            net_init_tap_one(tap, peer, "tap", name, ifname,

                             i >= 1 ? "no" : script,

                             i >= 1 ? "no" : downscript,

                             vhostfdname, vnet_hdr, fd, &err);

            if (err) {

                error_report_err(err);

                close(fd);

                return -1;

            }

        }

    }

    return 0;

}


int av_image_fill_pointers(uint8_t *data[4], enum PixelFormat pix_fmt, int height,

                           uint8_t *ptr, const int linesizes[4])

{

    int i, total_size, size[4], has_plane[4];

    const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[pix_fmt];

    memset(data     , 0, sizeof(data[0])*4);

    memset(size     , 0, sizeof(size));

    memset(has_plane, 0, sizeof(has_plane));

    if (desc->flags & PIX_FMT_HWACCEL)

        return AVERROR(EINVAL);

    data[0] = ptr;

    size[0] = linesizes[0] * height;

    if (desc->flags & PIX_FMT_PAL) {

        size[0] = (size[0] + 3) & ~3;

        data[1] = ptr + size[0]; /* palette is stored here as 256 32 bits words */

        return size[0] + 256 * 4;

    }

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

        has_plane[desc->comp[i].plane] = 1;

    total_size = size[0];

    for (i = 1; has_plane[i] && i < 4; i++) {

        int h, s = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;

        data[i] = data[i-1] + size[i-1];

        h = (height + (1 << s) - 1) >> s;

        size[i] = h * linesizes[i];

        total_size += size[i];

    }

    return total_size;

}