static int applehttp_open(URLContext *h, const char *uri, int flags)

{

    AppleHTTPContext *s;

    int ret, i;

    const char *nested_url;

    if (flags & AVIO_FLAG_WRITE)

        return AVERROR(ENOSYS);

    s = av_mallocz(sizeof(AppleHTTPContext));

    if (!s)

        return AVERROR(ENOMEM);

    h->priv_data = s;

    h->is_streamed = 1;

    if (av_strstart(uri, "applehttp+", &nested_url)) {

        av_strlcpy(s->playlisturl, nested_url, sizeof(s->playlisturl));

    } else if (av_strstart(uri, "applehttp://", &nested_url)) {

        av_strlcpy(s->playlisturl, "http://", sizeof(s->playlisturl));

        av_strlcat(s->playlisturl, nested_url, sizeof(s->playlisturl));

    } else {

        av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);

        ret = AVERROR(EINVAL);

        goto fail;

    }

    if ((ret = parse_playlist(h, s->playlisturl)) < 0)

        goto fail;

    if (s->n_segments == 0 && s->n_variants > 0) {

        int max_bandwidth = 0, maxvar = -1;

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

            if (s->variants[i]->bandwidth > max_bandwidth || i == 0) {

                max_bandwidth = s->variants[i]->bandwidth;

                maxvar = i;

            }

        }

        av_strlcpy(s->playlisturl, s->variants[maxvar]->url,

                   sizeof(s->playlisturl));

        if ((ret = parse_playlist(h, s->playlisturl)) < 0)

            goto fail;

    }

    if (s->n_segments == 0) {

        av_log(h, AV_LOG_WARNING, "Empty playlist\n");

        ret = AVERROR(EIO);

        goto fail;

    }

    s->cur_seq_no = s->start_seq_no;

    if (!s->finished && s->n_segments >= 3)

        s->cur_seq_no = s->start_seq_no + s->n_segments - 3;

    return 0;

fail:

    av_free(s);

    return ret;

}


static int mpeg_decode_slice(AVCodecContext *avctx,

                              AVPicture *pict,

                              int start_code,

                              UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int ret;

    start_code = (start_code - 1) & 0xff;

    if (start_code >= s->mb_height)

        return -1;

    s->last_dc[0] = 1 << (7 + s->intra_dc_precision);

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

    s->last_dc[2] = s->last_dc[0];

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

    s->mb_x = -1;

    s->mb_y = start_code;

    s->mb_incr = 0;

    /* start frame decoding */

    if (s->first_slice) {

        s->first_slice = 0;

        MPV_frame_start(s);

    }

    init_get_bits(&s->gb, buf, buf_size);

    s->qscale = get_qscale(s);

    /* extra slice info */

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

        skip_bits(&s->gb, 8);

    }

    for(;;) {

        clear_blocks(s->block[0]);

        emms_c();

        ret = mpeg_decode_mb(s, s->block);

        dprintf("ret=%d\n", ret);

        if (ret < 0)

            return -1;

        if (ret == 1)

            break;

        MPV_decode_mb(s, s->block);

    }

    emms_c();

    /* end of slice reached */

    if (s->mb_x == (s->mb_width - 1) &&

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

        /* end of image */

        UINT8 **picture;

        MPV_frame_end(s);

        /* XXX: incorrect reported qscale for mpeg2 */

        if (s->pict_type == B_TYPE) {

            picture = s->current_picture;

            avctx->quality = s->qscale;

        } else {

            /* latency of 1 frame for I and P frames */

            /* XXX: use another variable than picture_number */

            if (s->picture_number == 0) {

                picture = NULL;

            } else {

                picture = s->last_picture;

                avctx->quality = s->last_qscale;

            }

            s->last_qscale = s->qscale;

            s->picture_number++;

        }

        if (picture) {

            pict->data[0] = picture[0];

            pict->data[1] = picture[1];

            pict->data[2] = picture[2];

            pict->linesize[0] = s->linesize;

            pict->linesize[1] = s->linesize / 2;

            pict->linesize[2] = s->linesize / 2;

            return 1;

        } else {

            return 0;

        }

    } else {

        return 0;

    }

}


static int h264_handle_packet(AVFormatContext *ctx,
                              PayloadContext *data,
                              AVStream *st,
                              AVPacket * pkt,
                              uint32_t * timestamp,
                              const uint8_t * buf,
                              int len, int flags)
{
    uint8_t nal = buf[0];
    uint8_t type = (nal & 0x1f);
    int result= 0;
    uint8_t start_sequence[]= {0, 0, 1};
#ifdef DEBUG
    assert(data);
    assert(data->cookie == MAGIC_COOKIE);
#endif
    assert(buf);
    if (type >= 1 && type <= 23)
        type = 1;              // simplify the case. (these are all the nal types used internally by the h264 codec)
    switch (type) {
    case 0:                    // undefined;
        result= -1;
        break;
    case 1:
        av_new_packet(pkt, len+sizeof(start_sequence));
        memcpy(pkt->data, start_sequence, sizeof(start_sequence));
        memcpy(pkt->data+sizeof(start_sequence), buf, len);
#ifdef DEBUG
        data->packet_types_received[nal & 0x1f]++;
#endif
        break;
    case 24:                   // STAP-A (one packet, multiple nals)
        // consume the STAP-A NAL
        buf++;
        len--;
        // first we are going to figure out the total size....
        {
            int pass= 0;
            int total_length= 0;
            uint8_t *dst= NULL;
            for(pass= 0; pass<2; pass++) {
                const uint8_t *src= buf;
                int src_len= len;
                do {
                    uint16_t nal_size = AV_RB16(src); // this going to be a problem if unaligned (can it be?)
                    // consume the length of the aggregate...
                    src += 2;
                    src_len -= 2;
                    if (nal_size <= src_len) {
                        if(pass==0) {
                            // counting...
                            total_length+= sizeof(start_sequence)+nal_size;
                        } else {
                            // copying
                            assert(dst);
                            memcpy(dst, start_sequence, sizeof(start_sequence));
                            dst+= sizeof(start_sequence);
                            memcpy(dst, src, nal_size);
#ifdef DEBUG
                            data->packet_types_received[*src & 0x1f]++;
#endif
                            dst+= nal_size;
                        }
                    } else {
                        av_log(ctx, AV_LOG_ERROR,
                               "nal size exceeds length: %d %d\n", nal_size, src_len);
                    }
                    // eat what we handled...
                    src += nal_size;
                    src_len -= nal_size;
                    if (src_len < 0)
                        av_log(ctx, AV_LOG_ERROR,
                               "Consumed more bytes than we got! (%d)\n", src_len);
                } while (src_len > 2);      // because there could be rtp padding..
                if(pass==0) {
                    // now we know the total size of the packet (with the start sequences added)
                    av_new_packet(pkt, total_length);
                    dst= pkt->data;
                } else {
                    assert(dst-pkt->data==total_length);
                }
            }
        }
        break;
    case 25:                   // STAP-B
    case 26:                   // MTAP-16
    case 27:                   // MTAP-24
    case 29:                   // FU-B
        av_log(ctx, AV_LOG_ERROR,
               "Unhandled type (%d) (See RFC for implementation details\n",
               type);
        result= -1;
        break;
    case 28:                   // FU-A (fragmented nal)
        buf++;
        len--;                  // skip the fu_indicator
        {
            // these are the same as above, we just redo them here for clarity...
            uint8_t fu_indicator = nal;
            uint8_t fu_header = *buf;   // read the fu_header.
            uint8_t start_bit = fu_header >> 7;
//            uint8_t end_bit = (fu_header & 0x40) >> 6;
            uint8_t nal_type = (fu_header & 0x1f);
            uint8_t reconstructed_nal;
            // reconstruct this packet's true nal; only the data follows..
            reconstructed_nal = fu_indicator & (0xe0);  // the original nal forbidden bit and NRI are stored in this packet's nal;
            reconstructed_nal |= nal_type;
            // skip the fu_header...
            buf++;
            len--;
#ifdef DEBUG
            if (start_bit)
                data->packet_types_received[nal_type]++;
#endif
            if(start_bit) {
                // copy in the start sequence, and the reconstructed nal....
                av_new_packet(pkt, sizeof(start_sequence)+sizeof(nal)+len);
                memcpy(pkt->data, start_sequence, sizeof(start_sequence));
                pkt->data[sizeof(start_sequence)]= reconstructed_nal;
                memcpy(pkt->data+sizeof(start_sequence)+sizeof(nal), buf, len);
            } else {
                av_new_packet(pkt, len);
                memcpy(pkt->data, buf, len);
            }
        }
        break;
    case 30:                   // undefined
    case 31:                   // undefined
    default:
        av_log(ctx, AV_LOG_ERROR, "Undefined type (%d)", type);
        result= -1;
        break;
    }
    return result;
}


static inline void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc, const int16_t *chrSrc, const int16_t *alpSrc,

                                    uint8_t *dest, uint8_t *uDest, uint8_t *vDest, uint8_t *aDest, int dstW, int chrDstW)

{

    int i;

#if COMPILE_TEMPLATE_MMX

    if(!(c->flags & SWS_BITEXACT)) {

        long p= 4;

        const uint8_t *src[4]= {alpSrc + dstW, lumSrc + dstW, chrSrc + chrDstW, chrSrc + VOFW + chrDstW};

        uint8_t *dst[4]= {aDest, dest, uDest, vDest};

        x86_reg counter[4]= {dstW, dstW, chrDstW, chrDstW};

        if (c->flags & SWS_ACCURATE_RND) {

            while(p--) {

                if (dst[p]) {

                    __asm__ volatile(

                        YSCALEYUV2YV121_ACCURATE

                        :: "r" (src[p]), "r" (dst[p] + counter[p]),

                        "g" (-counter[p])

                        : "%"REG_a

                    );

                }

            }

        } else {

            while(p--) {

                if (dst[p]) {

                    __asm__ volatile(

                        YSCALEYUV2YV121

                        :: "r" (src[p]), "r" (dst[p] + counter[p]),

                        "g" (-counter[p])

                        : "%"REG_a

                    );

                }

            }

        }

        return;

    }

#endif

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

        int val= (lumSrc[i]+64)>>7;

        if (val&256) {

            if (val<0) val=0;

            else       val=255;

        }

        dest[i]= val;

    }

    if (uDest)

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

            int u=(chrSrc[i       ]+64)>>7;

            int v=(chrSrc[i + VOFW]+64)>>7;

            if ((u|v)&256) {

                if (u<0)        u=0;

                else if (u>255) u=255;

                if (v<0)        v=0;

                else if (v>255) v=255;

            }

            uDest[i]= u;

            vDest[i]= v;

        }

    if (CONFIG_SWSCALE_ALPHA && aDest)

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

            int val= (alpSrc[i]+64)>>7;

            aDest[i]= av_clip_uint8(val);

        }

}


static int interp(RA144Context *ractx, int16_t *out, int a,

                  int copyold, int energy)

{

    int work[10];

    int b = NBLOCKS - a;

    int i;

    // Interpolate block coefficients from the this frame's forth block and

    // last frame's forth block.

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

        out[i] = (a * ractx->lpc_coef[0][i] + b * ractx->lpc_coef[1][i])>> 2;

    if (eval_refl(work, out, ractx)) {

        // The interpolated coefficients are unstable, copy either new or old

        // coefficients.

        int_to_int16(out, ractx->lpc_coef[copyold]);

        return rescale_rms(ractx->lpc_refl_rms[copyold], energy);

    } else {

        return rescale_rms(rms(work), energy);

    }

}


static int dv_extract_audio(uint8_t *frame, uint8_t *ppcm[4],

                            const DVprofile *sys)

{

    int size, chan, i, j, d, of, smpls, freq, quant, half_ch;

    uint16_t lc, rc;

    const uint8_t *as_pack;

    uint8_t *pcm, ipcm;

    as_pack = dv_extract_pack(frame, dv_audio_source);

    if (!as_pack)    /* No audio ? */

        return 0;

    smpls = as_pack[1]      & 0x3f; /* samples in this frame - min. samples */

    freq  = as_pack[4] >> 3 & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */

    quant = as_pack[4]      & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */

    if (quant > 1)

        return -1;  /* unsupported quantization */

    if (freq >= FF_ARRAY_ELEMS(dv_audio_frequency))

        return AVERROR_INVALIDDATA;

    size    = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */

    half_ch = sys->difseg_size / 2;

    /* We work with 720p frames split in half, thus even frames have

     * channels 0,1 and odd 2,3. */

    ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;

    /* for each DIF channel */

    for (chan = 0; chan < sys->n_difchan; chan++) {

        /* next stereo channel (50Mbps and 100Mbps only) */

        pcm = ppcm[ipcm++];

        if (!pcm)

            break;

        /* for each DIF segment */

        for (i = 0; i < sys->difseg_size; i++) {

            frame += 6 * 80; /* skip DIF segment header */

            if (quant == 1 && i == half_ch) {

                /* next stereo channel (12bit mode only) */

                pcm = ppcm[ipcm++];

                if (!pcm)

                    break;

            }

            /* for each AV sequence */

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

                for (d = 8; d < 80; d += 2) {

                    if (quant == 0) {  /* 16bit quantization */

                        of = sys->audio_shuffle[i][j] +

                             (d - 8) / 2 * sys->audio_stride;

                        if (of * 2 >= size)

                            continue;

                        /* FIXME: maybe we have to admit that DV is a

                         * big-endian PCM */

                        pcm[of * 2]     = frame[d + 1];

                        pcm[of * 2 + 1] = frame[d];

                        if (pcm[of * 2 + 1] == 0x80 && pcm[of * 2] == 0x00)

                            pcm[of * 2 + 1] = 0;

                    } else {           /* 12bit quantization */

                        lc = ((uint16_t)frame[d]     << 4) |

                             ((uint16_t)frame[d + 2] >> 4);

                        rc = ((uint16_t)frame[d + 1] << 4) |

                             ((uint16_t)frame[d + 2] & 0x0f);

                        lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));

                        rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));

                        of = sys->audio_shuffle[i % half_ch][j] +

                             (d - 8) / 3 * sys->audio_stride;

                        if (of * 2 >= size)

                            continue;

                        /* FIXME: maybe we have to admit that DV is a

                         * big-endian PCM */

                        pcm[of * 2]     = lc & 0xff;

                        pcm[of * 2 + 1] = lc >> 8;

                        of = sys->audio_shuffle[i % half_ch + half_ch][j] +

                             (d - 8) / 3 * sys->audio_stride;

                        /* FIXME: maybe we have to admit that DV is a

                         * big-endian PCM */

                        pcm[of * 2]     = rc & 0xff;

                        pcm[of * 2 + 1] = rc >> 8;

                        ++d;

                    }

                }

                frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */

            }

        }

    }

    return size;

}


void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)

{

    if (min_size < *size)

        return ptr;

    min_size = FFMAX(17 * min_size / 16 + 32, min_size);

    ptr = av_realloc(ptr, min_size);

    /* we could set this to the unmodified min_size but this is safer

     * if the user lost the ptr and uses NULL now

     */

    if (!ptr)

        min_size = 0;

    *size = min_size;

    return ptr;

}


static inline int svq3_decode_block(GetBitContext *gb, DCTELEM *block,

                                    int index, const int type)

{

    static const uint8_t *const scan_patterns[4] =

    { luma_dc_zigzag_scan, zigzag_scan, svq3_scan, chroma_dc_scan };

    int run, level, sign, vlc, limit;

    const int intra           = 3 * type >> 2;

    const uint8_t *const scan = scan_patterns[type];

    for (limit = (16 >> intra); index < 16; index = limit, limit += 8) {

        for (; (vlc = svq3_get_ue_golomb(gb)) != 0; index++) {

            if (vlc == INVALID_VLC)

                return -1;

            sign = (vlc & 0x1) - 1;

            vlc  = vlc + 1 >> 1;

            if (type == 3) {

                if (vlc < 3) {

                    run   = 0;

                    level = vlc;

                } else if (vlc < 4) {

                    run   = 1;

                    level = 1;

                } else {

                    run   = vlc & 0x3;

                    level = (vlc + 9 >> 2) - run;

                }

            } else {

                if (vlc < 16) {

                    run   = svq3_dct_tables[intra][vlc].run;

                    level = svq3_dct_tables[intra][vlc].level;

                } else if (intra) {

                    run   = vlc & 0x7;

                    level = (vlc >> 3) +

                            ((run == 0) ? 8 : ((run < 2) ? 2 : ((run < 5) ? 0 : -1)));

                } else {

                    run   = vlc & 0xF;

                    level = (vlc >> 4) +

                            ((run == 0) ? 4 : ((run < 3) ? 2 : ((run < 10) ? 1 : 0)));

                }

            }

            if ((index += run) >= limit)

                return -1;

            block[scan[index]] = (level ^ sign) - sign;

        }

        if (type != 2) {

            break;

        }

    }

    return 0;

}


static int flac_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    FLACContext *s = avctx->priv_data;

    int metadata_last, metadata_type, metadata_size;

    int tmp = 0, i, j = 0, input_buf_size;

    int16_t *samples = data, *left, *right;

    *data_size = 0;

    s->avctx = avctx;

    if(s->max_framesize == 0){

        s->max_framesize= 8192; // should hopefully be enough for the first header

        s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);

    }

    if(1 && s->max_framesize){//FIXME truncated

            buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);

            input_buf_size= buf_size;

            if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){

//                printf("memmove\n");

                memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);

                s->bitstream_index=0;

            }

            memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);

            buf= &s->bitstream[s->bitstream_index];

            buf_size += s->bitstream_size;

            s->bitstream_size= buf_size;

            if(buf_size < s->max_framesize){

//                printf("wanna more data ...\n");

                return input_buf_size;

            }

    }

    init_get_bits(&s->gb, buf, buf_size*8);

    /* fLaC signature (be) */

    if (show_bits_long(&s->gb, 32) == bswap_32(ff_get_fourcc("fLaC")))

    {

        skip_bits(&s->gb, 32);

        av_log(s->avctx, AV_LOG_DEBUG, "STREAM HEADER\n");

        do {

            metadata_last = get_bits(&s->gb, 1);

            metadata_type = get_bits(&s->gb, 7);

            metadata_size = get_bits_long(&s->gb, 24);

            av_log(s->avctx, AV_LOG_DEBUG, " metadata block: flag = %d, type = %d, size = %d\n",

                metadata_last, metadata_type,

                metadata_size);

            if(metadata_size){

                switch(metadata_type)

                {

                case METADATA_TYPE_STREAMINFO:

                    if(metadata_size == 0)

                        av_log(s->avctx, AV_LOG_DEBUG, "size= 0 WTF!?\n");

                    metadata_streaminfo(s);

                    dump_headers(s);

                    break;

                default:

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

                        skip_bits(&s->gb, 8);

                }

            }

        } while(!metadata_last);

    }

    else

    {

         tmp = show_bits(&s->gb, 16);

        if(tmp != 0xFFF8){

            av_log(s->avctx, AV_LOG_ERROR, "FRAME HEADER not here\n");

            while(get_bits_count(&s->gb)/8+2 < buf_size && show_bits(&s->gb, 16) != 0xFFF8)

                skip_bits(&s->gb, 8);

            goto end; // we may not have enough bits left to decode a frame, so try next time

        }

        skip_bits(&s->gb, 16);

        if (decode_frame(s) < 0)

            return -1;

    }

#if 0

    /* fix the channel order here */

    if (s->order == MID_SIDE)

    {

        short *left = samples;

        short *right = samples + s->blocksize;

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

        {

            uint32_t x = s->decoded[0][i];

            uint32_t y = s->decoded[0][i+1];

            right[i] = x - (y / 2);

            left[i] = right[i] + y;

        }

        *data_size = 2 * s->blocksize;

    }

    else

    {

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

    {

        switch(s->order)

        {

            case INDEPENDENT:

                for (j = 0; j < s->blocksize; j++)

                    samples[(s->blocksize*i)+j] = s->decoded[i][j];

                break;

            case LEFT_SIDE:

            case RIGHT_SIDE:

                if (i == 0)

                    for (j = 0; j < s->blocksize; j++)

                        samples[(s->blocksize*i)+j] = s->decoded[0][j];

                else

                    for (j = 0; j < s->blocksize; j++)

                        samples[(s->blocksize*i)+j] = s->decoded[0][j] - s->decoded[i][j];

                break;

//            case MID_SIDE:

//                av_log(s->avctx, AV_LOG_DEBUG, "mid-side unsupported\n");

        }

        *data_size += s->blocksize;

    }

    }

#else

    switch(s->order)

    {

        case INDEPENDENT:

            for (j = 0; j < s->blocksize; j++)

            {

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

                    *(samples++) = s->decoded[i][j];

            }

            break;

        case LEFT_SIDE:

            assert(s->channels == 2);

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

            {

                *(samples++) = s->decoded[0][i];

                *(samples++) = s->decoded[0][i] - s->decoded[1][i];

            }

            break;

        case RIGHT_SIDE:

            assert(s->channels == 2);

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

            {

                *(samples++) = s->decoded[0][i] + s->decoded[1][i];

                *(samples++) = s->decoded[1][i];

            }

            break;

        case MID_SIDE:

            assert(s->channels == 2);

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

            {

                int mid, side;

                mid = s->decoded[0][i];

                side = s->decoded[1][i];

                mid <<= 1;

                if (side & 1)

                    mid++;

                *(samples++) = (mid + side) >> 1;

                *(samples++) = (mid - side) >> 1;

            }

            break;

    }

#endif

    *data_size = (int8_t *)samples - (int8_t *)data;

    av_log(s->avctx, AV_LOG_DEBUG, "data size: %d\n", *data_size);

//    s->last_blocksize = s->blocksize;

end:

    i= (get_bits_count(&s->gb)+7)/8;;

    if(i > buf_size){

        av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);

        return -1;

    }

    if(s->bitstream_size){

        s->bitstream_index += i;

        s->bitstream_size  -= i;

        return input_buf_size;

    }else

        return i;

}


int64_t avcodec_guess_channel_layout(int nb_channels, enum CodecID codec_id, const char *fmt_name)

{

    switch(nb_channels) {

    case 1: return AV_CH_LAYOUT_MONO;

    case 2: return AV_CH_LAYOUT_STEREO;

    case 3: return AV_CH_LAYOUT_SURROUND;

    case 4: return AV_CH_LAYOUT_QUAD;

    case 5: return AV_CH_LAYOUT_5POINT0;

    case 6: return AV_CH_LAYOUT_5POINT1;

    case 8: return AV_CH_LAYOUT_7POINT1;

    default: return 0;

    }

}


static inline void downmix_2f_1r_to_dolby(float *samples)

{

    int i;

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

        samples[i] -= samples[i + 512];

        samples[i + 256] += samples[i + 512];

        samples[i + 512] = 0;

    }

}


static int vc1_init_common(VC1Context *v)

{

    static int done = 0;

    int i = 0;

    static VLC_TYPE vlc_table[32372][2];

    v->hrd_rate = v->hrd_buffer = NULL;

    /* VLC tables */

    if (!done) {

        INIT_VLC_STATIC(&ff_vc1_bfraction_vlc, VC1_BFRACTION_VLC_BITS, 23,

                        ff_vc1_bfraction_bits, 1, 1,

                        ff_vc1_bfraction_codes, 1, 1, 1 << VC1_BFRACTION_VLC_BITS);

        INIT_VLC_STATIC(&ff_vc1_norm2_vlc, VC1_NORM2_VLC_BITS, 4,

                        ff_vc1_norm2_bits, 1, 1,

                        ff_vc1_norm2_codes, 1, 1, 1 << VC1_NORM2_VLC_BITS);

        INIT_VLC_STATIC(&ff_vc1_norm6_vlc, VC1_NORM6_VLC_BITS, 64,

                        ff_vc1_norm6_bits, 1, 1,

                        ff_vc1_norm6_codes, 2, 2, 556);

        INIT_VLC_STATIC(&ff_vc1_imode_vlc, VC1_IMODE_VLC_BITS, 7,

                        ff_vc1_imode_bits, 1, 1,

                        ff_vc1_imode_codes, 1, 1, 1 << VC1_IMODE_VLC_BITS);

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

            ff_vc1_ttmb_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 0]];

            ff_vc1_ttmb_vlc[i].table_allocated = vlc_offs[i * 3 + 1] - vlc_offs[i * 3 + 0];

            init_vlc(&ff_vc1_ttmb_vlc[i], VC1_TTMB_VLC_BITS, 16,

                     ff_vc1_ttmb_bits[i], 1, 1,

                     ff_vc1_ttmb_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);

            ff_vc1_ttblk_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 1]];

            ff_vc1_ttblk_vlc[i].table_allocated = vlc_offs[i * 3 + 2] - vlc_offs[i * 3 + 1];

            init_vlc(&ff_vc1_ttblk_vlc[i], VC1_TTBLK_VLC_BITS, 8,

                     ff_vc1_ttblk_bits[i], 1, 1,

                     ff_vc1_ttblk_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

            ff_vc1_subblkpat_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 2]];

            ff_vc1_subblkpat_vlc[i].table_allocated = vlc_offs[i * 3 + 3] - vlc_offs[i * 3 + 2];

            init_vlc(&ff_vc1_subblkpat_vlc[i], VC1_SUBBLKPAT_VLC_BITS, 15,

                     ff_vc1_subblkpat_bits[i], 1, 1,

                     ff_vc1_subblkpat_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

        }

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

            ff_vc1_4mv_block_pattern_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 9]];

            ff_vc1_4mv_block_pattern_vlc[i].table_allocated = vlc_offs[i * 3 + 10] - vlc_offs[i * 3 + 9];

            init_vlc(&ff_vc1_4mv_block_pattern_vlc[i], VC1_4MV_BLOCK_PATTERN_VLC_BITS, 16,

                     ff_vc1_4mv_block_pattern_bits[i], 1, 1,

                     ff_vc1_4mv_block_pattern_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

            ff_vc1_cbpcy_p_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 10]];

            ff_vc1_cbpcy_p_vlc[i].table_allocated = vlc_offs[i * 3 + 11] - vlc_offs[i * 3 + 10];

            init_vlc(&ff_vc1_cbpcy_p_vlc[i], VC1_CBPCY_P_VLC_BITS, 64,

                     ff_vc1_cbpcy_p_bits[i], 1, 1,

                     ff_vc1_cbpcy_p_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);

            ff_vc1_mv_diff_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 11]];

            ff_vc1_mv_diff_vlc[i].table_allocated = vlc_offs[i * 3 + 12] - vlc_offs[i * 3 + 11];

            init_vlc(&ff_vc1_mv_diff_vlc[i], VC1_MV_DIFF_VLC_BITS, 73,

                     ff_vc1_mv_diff_bits[i], 1, 1,

                     ff_vc1_mv_diff_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);

        }

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

            ff_vc1_ac_coeff_table[i].table           = &vlc_table[vlc_offs[i * 2 + 21]];

            ff_vc1_ac_coeff_table[i].table_allocated = vlc_offs[i * 2 + 22] - vlc_offs[i * 2 + 21];

            init_vlc(&ff_vc1_ac_coeff_table[i], AC_VLC_BITS, vc1_ac_sizes[i],

                     &vc1_ac_tables[i][0][1], 8, 4,

                     &vc1_ac_tables[i][0][0], 8, 4, INIT_VLC_USE_NEW_STATIC);

            /* initialize interlaced MVDATA tables (2-Ref) */

            ff_vc1_2ref_mvdata_vlc[i].table           = &vlc_table[vlc_offs[i * 2 + 22]];

            ff_vc1_2ref_mvdata_vlc[i].table_allocated = vlc_offs[i * 2 + 23] - vlc_offs[i * 2 + 22];

            init_vlc(&ff_vc1_2ref_mvdata_vlc[i], VC1_2REF_MVDATA_VLC_BITS, 126,

                     ff_vc1_2ref_mvdata_bits[i], 1, 1,

                     ff_vc1_2ref_mvdata_codes[i], 4, 4, INIT_VLC_USE_NEW_STATIC);

        }

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

            /* initialize 4MV MBMODE VLC tables for interlaced frame P picture */

            ff_vc1_intfr_4mv_mbmode_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 37]];

            ff_vc1_intfr_4mv_mbmode_vlc[i].table_allocated = vlc_offs[i * 3 + 38] - vlc_offs[i * 3 + 37];

            init_vlc(&ff_vc1_intfr_4mv_mbmode_vlc[i], VC1_INTFR_4MV_MBMODE_VLC_BITS, 15,

                     ff_vc1_intfr_4mv_mbmode_bits[i], 1, 1,

                     ff_vc1_intfr_4mv_mbmode_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);

            /* initialize NON-4MV MBMODE VLC tables for the same */

            ff_vc1_intfr_non4mv_mbmode_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 38]];

            ff_vc1_intfr_non4mv_mbmode_vlc[i].table_allocated = vlc_offs[i * 3 + 39] - vlc_offs[i * 3 + 38];

            init_vlc(&ff_vc1_intfr_non4mv_mbmode_vlc[i], VC1_INTFR_NON4MV_MBMODE_VLC_BITS, 9,

                     ff_vc1_intfr_non4mv_mbmode_bits[i], 1, 1,

                     ff_vc1_intfr_non4mv_mbmode_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

            /* initialize interlaced MVDATA tables (1-Ref) */

            ff_vc1_1ref_mvdata_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 39]];

            ff_vc1_1ref_mvdata_vlc[i].table_allocated = vlc_offs[i * 3 + 40] - vlc_offs[i * 3 + 39];

            init_vlc(&ff_vc1_1ref_mvdata_vlc[i], VC1_1REF_MVDATA_VLC_BITS, 72,

                     ff_vc1_1ref_mvdata_bits[i], 1, 1,

                     ff_vc1_1ref_mvdata_codes[i], 4, 4, INIT_VLC_USE_NEW_STATIC);

        }

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

            /* Initialize 2MV Block pattern VLC tables */

            ff_vc1_2mv_block_pattern_vlc[i].table           = &vlc_table[vlc_offs[i + 49]];

            ff_vc1_2mv_block_pattern_vlc[i].table_allocated = vlc_offs[i + 50] - vlc_offs[i + 49];

            init_vlc(&ff_vc1_2mv_block_pattern_vlc[i], VC1_2MV_BLOCK_PATTERN_VLC_BITS, 4,

                     ff_vc1_2mv_block_pattern_bits[i], 1, 1,

                     ff_vc1_2mv_block_pattern_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

        }

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

            /* Initialize interlaced CBPCY VLC tables (Table 124 - Table 131) */

            ff_vc1_icbpcy_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 53]];

            ff_vc1_icbpcy_vlc[i].table_allocated = vlc_offs[i * 3 + 54] - vlc_offs[i * 3 + 53];

            init_vlc(&ff_vc1_icbpcy_vlc[i], VC1_ICBPCY_VLC_BITS, 63,

                     ff_vc1_icbpcy_p_bits[i], 1, 1,

                     ff_vc1_icbpcy_p_codes[i], 2, 2, INIT_VLC_USE_NEW_STATIC);

            /* Initialize interlaced field picture MBMODE VLC tables */

            ff_vc1_if_mmv_mbmode_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 54]];

            ff_vc1_if_mmv_mbmode_vlc[i].table_allocated = vlc_offs[i * 3 + 55] - vlc_offs[i * 3 + 54];

            init_vlc(&ff_vc1_if_mmv_mbmode_vlc[i], VC1_IF_MMV_MBMODE_VLC_BITS, 8,

                     ff_vc1_if_mmv_mbmode_bits[i], 1, 1,

                     ff_vc1_if_mmv_mbmode_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

            ff_vc1_if_1mv_mbmode_vlc[i].table           = &vlc_table[vlc_offs[i * 3 + 55]];

            ff_vc1_if_1mv_mbmode_vlc[i].table_allocated = vlc_offs[i * 3 + 56] - vlc_offs[i * 3 + 55];

            init_vlc(&ff_vc1_if_1mv_mbmode_vlc[i], VC1_IF_1MV_MBMODE_VLC_BITS, 6,

                     ff_vc1_if_1mv_mbmode_bits[i], 1, 1,

                     ff_vc1_if_1mv_mbmode_codes[i], 1, 1, INIT_VLC_USE_NEW_STATIC);

        }

        done = 1;

    }

    /* Other defaults */

    v->pq      = -1;

    v->mvrange = 0; /* 7.1.1.18, p80 */

    return 0;

}


static int vp6_parse_header(VP56Context *s, const uint8_t *buf, int buf_size,

                            int *golden_frame)

{

    VP56RangeCoder *c = &s->c;

    int parse_filter_info = 0;

    int coeff_offset = 0;

    int vrt_shift = 0;

    int sub_version;

    int rows, cols;

    int res = 1;

    int separated_coeff = buf[0] & 1;

    s->framep[VP56_FRAME_CURRENT]->key_frame = !(buf[0] & 0x80);

    ff_vp56_init_dequant(s, (buf[0] >> 1) & 0x3F);

    if (s->framep[VP56_FRAME_CURRENT]->key_frame) {

        sub_version = buf[1] >> 3;

        if (sub_version > 8)

            return 0;

        s->filter_header = buf[1] & 0x06;

        if (buf[1] & 1) {

            av_log(s->avctx, AV_LOG_ERROR, "interlacing not supported\n");

            return 0;

        }

        if (separated_coeff || !s->filter_header) {

            coeff_offset = AV_RB16(buf+2) - 2;

            buf += 2;

            buf_size -= 2;

        }

        rows = buf[2];  /* number of stored macroblock rows */

        cols = buf[3];  /* number of stored macroblock cols */

        /* buf[4] is number of displayed macroblock rows */

        /* buf[5] is number of displayed macroblock cols */

        if (!s->macroblocks || /* first frame */

            16*cols != s->avctx->coded_width ||

            16*rows != s->avctx->coded_height) {

            avcodec_set_dimensions(s->avctx, 16*cols, 16*rows);

            if (s->avctx->extradata_size == 1) {

                s->avctx->width  -= s->avctx->extradata[0] >> 4;

                s->avctx->height -= s->avctx->extradata[0] & 0x0F;

            }

            res = 2;

        }

        ff_vp56_init_range_decoder(c, buf+6, buf_size-6);

        vp56_rac_gets(c, 2);

        parse_filter_info = s->filter_header;

        if (sub_version < 8)

            vrt_shift = 5;

        s->sub_version = sub_version;

    } else {

        if (!s->sub_version)

            return 0;

        if (separated_coeff || !s->filter_header) {

            coeff_offset = AV_RB16(buf+1) - 2;

            buf += 2;

            buf_size -= 2;

        }

        ff_vp56_init_range_decoder(c, buf+1, buf_size-1);

        *golden_frame = vp56_rac_get(c);

        if (s->filter_header) {

            s->deblock_filtering = vp56_rac_get(c);

            if (s->deblock_filtering)

                vp56_rac_get(c);

            if (s->sub_version > 7)

                parse_filter_info = vp56_rac_get(c);

        }

    }

    if (parse_filter_info) {

        if (vp56_rac_get(c)) {

            s->filter_mode = 2;

            s->sample_variance_threshold = vp56_rac_gets(c, 5) << vrt_shift;

            s->max_vector_length = 2 << vp56_rac_gets(c, 3);

        } else if (vp56_rac_get(c)) {

            s->filter_mode = 1;

        } else {

            s->filter_mode = 0;

        }

        if (s->sub_version > 7)

            s->filter_selection = vp56_rac_gets(c, 4);

        else

            s->filter_selection = 16;

    }

    s->use_huffman = vp56_rac_get(c);

    s->parse_coeff = vp6_parse_coeff;

    if (coeff_offset) {

        buf      += coeff_offset;

        buf_size -= coeff_offset;

        if (buf_size < 0)

            return 0;

        if (s->use_huffman) {

            s->parse_coeff = vp6_parse_coeff_huffman;

            init_get_bits(&s->gb, buf, buf_size<<3);

        } else {

            ff_vp56_init_range_decoder(&s->cc, buf, buf_size);

            s->ccp = &s->cc;

        }

    } else {

        s->ccp = &s->c;

    }

    return res;

}


int ff_network_wait_fd_timeout(int fd, int write, int64_t timeout, AVIOInterruptCB *int_cb)

{

    int ret;

    int64_t wait_start = 0;

    while (1) {

        ret = ff_network_wait_fd(fd, write);

        if (ret != AVERROR(EAGAIN))

            return ret;

        if (ff_check_interrupt(int_cb))

            return AVERROR_EXIT;

        if (timeout > 0) {

            if (!wait_start)

                wait_start = av_gettime();

            else if (av_gettime() - wait_start > timeout)

                return AVERROR(ETIMEDOUT);

        }

    }

}


GuestNetworkInterfaceList *qmp_guest_network_get_interfaces(Error **errp)

{

    GuestNetworkInterfaceList *head = NULL, *cur_item = NULL;

    struct ifaddrs *ifap, *ifa;

    if (getifaddrs(&ifap) < 0) {

        error_setg_errno(errp, errno, "getifaddrs failed");

        goto error;

    }

    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {

        GuestNetworkInterfaceList *info;

        GuestIpAddressList **address_list = NULL, *address_item = NULL;

        char addr4[INET_ADDRSTRLEN];

        char addr6[INET6_ADDRSTRLEN];

        int sock;

        struct ifreq ifr;

        unsigned char *mac_addr;

        void *p;

        g_debug("Processing %s interface", ifa->ifa_name);

        info = guest_find_interface(head, ifa->ifa_name);

        if (!info) {

            info = g_malloc0(sizeof(*info));

            info->value = g_malloc0(sizeof(*info->value));

            info->value->name = g_strdup(ifa->ifa_name);

            if (!cur_item) {

                head = cur_item = info;

            } else {

                cur_item->next = info;

                cur_item = info;

            }

        }

        if (!info->value->has_hardware_address &&

            ifa->ifa_flags & SIOCGIFHWADDR) {

            /* we haven't obtained HW address yet */

            sock = socket(PF_INET, SOCK_STREAM, 0);

            if (sock == -1) {

                error_setg_errno(errp, errno, "failed to create socket");

                goto error;

            }

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

            pstrcpy(ifr.ifr_name, IF_NAMESIZE, info->value->name);

            if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {

                error_setg_errno(errp, errno,

                                 "failed to get MAC address of %s",

                                 ifa->ifa_name);

                goto error;

            }

            mac_addr = (unsigned char *) &ifr.ifr_hwaddr.sa_data;

            info->value->hardware_address =

                g_strdup_printf("%02x:%02x:%02x:%02x:%02x:%02x",

                                (int) mac_addr[0], (int) mac_addr[1],

                                (int) mac_addr[2], (int) mac_addr[3],

                                (int) mac_addr[4], (int) mac_addr[5]);

            info->value->has_hardware_address = true;

            close(sock);

        }

        if (ifa->ifa_addr &&

            ifa->ifa_addr->sa_family == AF_INET) {

            /* interface with IPv4 address */

            address_item = g_malloc0(sizeof(*address_item));

            address_item->value = g_malloc0(sizeof(*address_item->value));

            p = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;

            if (!inet_ntop(AF_INET, p, addr4, sizeof(addr4))) {

                error_setg_errno(errp, errno, "inet_ntop failed");

                goto error;

            }

            address_item->value->ip_address = g_strdup(addr4);

            address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV4;

            if (ifa->ifa_netmask) {

                /* Count the number of set bits in netmask.

                 * This is safe as '1' and '0' cannot be shuffled in netmask. */

                p = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;

                address_item->value->prefix = ctpop32(((uint32_t *) p)[0]);

            }

        } else if (ifa->ifa_addr &&

                   ifa->ifa_addr->sa_family == AF_INET6) {

            /* interface with IPv6 address */

            address_item = g_malloc0(sizeof(*address_item));

            address_item->value = g_malloc0(sizeof(*address_item->value));

            p = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;

            if (!inet_ntop(AF_INET6, p, addr6, sizeof(addr6))) {

                error_setg_errno(errp, errno, "inet_ntop failed");

                goto error;

            }

            address_item->value->ip_address = g_strdup(addr6);

            address_item->value->ip_address_type = GUEST_IP_ADDRESS_TYPE_IPV6;

            if (ifa->ifa_netmask) {

                /* Count the number of set bits in netmask.

                 * This is safe as '1' and '0' cannot be shuffled in netmask. */

                p = &((struct sockaddr_in6 *)ifa->ifa_netmask)->sin6_addr;

                address_item->value->prefix =

                    ctpop32(((uint32_t *) p)[0]) +

                    ctpop32(((uint32_t *) p)[1]) +

                    ctpop32(((uint32_t *) p)[2]) +

                    ctpop32(((uint32_t *) p)[3]);

            }

        }

        if (!address_item) {

            continue;

        }

        address_list = &info->value->ip_addresses;

        while (*address_list && (*address_list)->next) {

            address_list = &(*address_list)->next;

        }

        if (!*address_list) {

            *address_list = address_item;

        } else {

            (*address_list)->next = address_item;

        }

        info->value->has_ip_addresses = true;

    }

    freeifaddrs(ifap);

    return head;

error:

    freeifaddrs(ifap);

    qapi_free_GuestNetworkInterfaceList(head);

    return NULL;

}


PPC_OP(mulli)

{

    T0 = (Ts0 * SPARAM(1));

    RETURN();

}


static int print_uint64(DeviceState *dev, Property *prop, char *dest, size_t len)

{

    uint64_t *ptr = qdev_get_prop_ptr(dev, prop);

    return snprintf(dest, len, "%" PRIu64, *ptr);

}


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

                                        int jobnr, int threadnr, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

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

    int mb_y = td->thread_mb_pos >> 16;

    int mb_x, mb_xy = mb_y * s->mb_width;

    int num_jobs = s->num_jobs;

    VP8Frame *curframe = s->curframe, *prev_frame = s->prev_frame;

    VP56RangeCoder *c  = &s->coeff_partition[mb_y & (s->num_coeff_partitions - 1)];

    VP8Macroblock *mb;

    uint8_t *dst[3] = {

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

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

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

    };

    if (mb_y == 0)

        prev_td = td;

    else

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

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

        next_td = td;

    else

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

    if (s->mb_layout == 1)

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

    else {

        // Make sure the previous frame has read its segmentation map,

        // if we re-use the same map.

        if (prev_frame && s->segmentation.enabled &&

            !s->segmentation.update_map)

            ff_thread_await_progress(&prev_frame->tf, mb_y, 0);

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

        memset(mb - 1, 0, sizeof(*mb)); // zero left macroblock

        AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101);

    }

    if (!is_vp7 || mb_y == 0)

        memset(td->left_nnz, 0, sizeof(td->left_nnz));

    s->mv_min.x = -MARGIN;

    s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;

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

        // Wait for previous thread to read mb_x+2, and reach mb_y-1.

        if (prev_td != td) {

            if (threadnr != 0) {

                check_thread_pos(td, prev_td,

                                 mb_x + (is_vp7 ? 2 : 1),

                                 mb_y - (is_vp7 ? 2 : 1));

            } else {

                check_thread_pos(td, prev_td,

                                 mb_x + (is_vp7 ? 2 : 1) + s->mb_width + 3,

                                 mb_y - (is_vp7 ? 2 : 1));

            }

        }

        s->vdsp.prefetch(dst[0] + (mb_x & 3) * 4 * s->linesize + 64,

                         s->linesize, 4);

        s->vdsp.prefetch(dst[1] + (mb_x & 7) * s->uvlinesize + 64,

                         dst[2] - dst[1], 2);

        if (!s->mb_layout)

            decode_mb_mode(s, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,

                           prev_frame && prev_frame->seg_map ?

                           prev_frame->seg_map->data + mb_xy : NULL, 0, is_vp7);

        prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_PREVIOUS);

        if (!mb->skip)

            decode_mb_coeffs(s, td, c, mb, s->top_nnz[mb_x], td->left_nnz, is_vp7);

        if (mb->mode <= MODE_I4x4)

            intra_predict(s, td, dst, mb, mb_x, mb_y, is_vp7);

        else

            inter_predict(s, td, dst, mb, mb_x, mb_y);

        prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN);

        if (!mb->skip) {

            idct_mb(s, td, dst, mb);

        } else {

            AV_ZERO64(td->left_nnz);

            AV_WN64(s->top_nnz[mb_x], 0);   // array of 9, so unaligned

            /* Reset DC block predictors if they would exist

             * if the mb had coefficients */

            if (mb->mode != MODE_I4x4 && mb->mode != VP8_MVMODE_SPLIT) {

                td->left_nnz[8]     = 0;

                s->top_nnz[mb_x][8] = 0;

            }

        }

        if (s->deblock_filter)

            filter_level_for_mb(s, mb, &td->filter_strength[mb_x], is_vp7);

        if (s->deblock_filter && num_jobs != 1 && threadnr == num_jobs - 1) {

            if (s->filter.simple)

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

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

            else

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

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

        }

        prefetch_motion(s, mb, mb_x, mb_y, mb_xy, VP56_FRAME_GOLDEN2);

        dst[0]      += 16;

        dst[1]      += 8;

        dst[2]      += 8;

        s->mv_min.x -= 64;

        s->mv_max.x -= 64;

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

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

        } else {

            update_pos(td, mb_y, mb_x);

        }

    }

}


static void yop_next_macroblock(YopDecContext *s)

{

    // If we are advancing to the next row of macroblocks

    if (s->row_pos == s->frame.linesize[0] - 2) {

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

        s->row_pos =  0;

    }else {

        s->row_pos += 2;

    }

    s->dstptr += 2;

}


static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist)

{

    AHCICmdHdr *cmd = ad->cur_cmd;

    uint32_t opts = le32_to_cpu(cmd->opts);

    uint64_t prdt_addr = le64_to_cpu(cmd->tbl_addr) + 0x80;

    int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN;

    dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG));

    dma_addr_t real_prdt_len = prdt_len;

    uint8_t *prdt;

    int i;

    int r = 0;

    if (!sglist_alloc_hint) {

        DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts);

        return -1;

    }

    /* map PRDT */

    if (!(prdt = dma_memory_map(ad->hba->dma, prdt_addr, &prdt_len,

                                DMA_DIRECTION_TO_DEVICE))){

        DPRINTF(ad->port_no, "map failed\n");

        return -1;

    }

    if (prdt_len < real_prdt_len) {

        DPRINTF(ad->port_no, "mapped less than expected\n");

        r = -1;

        goto out;

    }

    /* Get entries in the PRDT, init a qemu sglist accordingly */

    if (sglist_alloc_hint > 0) {

        AHCI_SG *tbl = (AHCI_SG *)prdt;

        qemu_sglist_init(sglist, sglist_alloc_hint, ad->hba->dma);

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

            /* flags_size is zero-based */

            qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr),

                            le32_to_cpu(tbl[i].flags_size) + 1);

        }

    }

out:

    dma_memory_unmap(ad->hba->dma, prdt, prdt_len,

                     DMA_DIRECTION_TO_DEVICE, prdt_len);

    return r;

}


static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
    MpegEncContext *s = &ctx->m;
    int width, height, vo_ver_id;
    /* vol header */
    skip_bits(gb, 1);                   /* random access */
    s->vo_type = get_bits(gb, 8);
    if (get_bits1(gb) != 0) {           /* is_ol_id */
        vo_ver_id = get_bits(gb, 4);    /* vo_ver_id */
        skip_bits(gb, 3);               /* vo_priority */
    } else {
        vo_ver_id = 1;
    s->aspect_ratio_info = get_bits(gb, 4);
    if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
        s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
        s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
    } else {
        s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
    if ((s->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
        int chroma_format = get_bits(gb, 2);
        if (chroma_format != CHROMA_420)
            av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
        s->low_delay = get_bits1(gb);
        if (get_bits1(gb)) {    /* vbv parameters */
            get_bits(gb, 15);   /* first_half_bitrate */
            skip_bits1(gb);     /* marker */
            get_bits(gb, 15);   /* latter_half_bitrate */
            skip_bits1(gb);     /* marker */
            get_bits(gb, 15);   /* first_half_vbv_buffer_size */
            skip_bits1(gb);     /* marker */
            get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
            get_bits(gb, 11);   /* first_half_vbv_occupancy */
            skip_bits1(gb);     /* marker */
            get_bits(gb, 15);   /* latter_half_vbv_occupancy */
            skip_bits1(gb);     /* marker */
    } else {
        /* is setting low delay flag only once the smartest thing to do?
         * low delay detection won't be overriden. */
        if (s->picture_number == 0)
            s->low_delay = 0;
    ctx->shape = get_bits(gb, 2); /* vol shape */
    if (ctx->shape != RECT_SHAPE)
        av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
    if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
        av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
        skip_bits(gb, 4);  /* video_object_layer_shape_extension */
    check_marker(gb, "before time_increment_resolution");
    s->avctx->time_base.den = get_bits(gb, 16);
    if (!s->avctx->time_base.den) {
        av_log(s->avctx, AV_LOG_ERROR, "time_base.den==0\n");
        s->avctx->time_base.num = 0;
        return -1;
    ctx->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
    if (ctx->time_increment_bits < 1)
        ctx->time_increment_bits = 1;
    check_marker(gb, "before fixed_vop_rate");
    if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
        s->avctx->time_base.num = get_bits(gb, ctx->time_increment_bits);
    else
        s->avctx->time_base.num = 1;
    ctx->t_frame = 0;
    if (ctx->shape != BIN_ONLY_SHAPE) {
        if (ctx->shape == RECT_SHAPE) {
            check_marker(gb, "before width");
            width = get_bits(gb, 13);
            check_marker(gb, "before height");
            height = get_bits(gb, 13);
            check_marker(gb, "after height");
            if (width && height &&  /* they should be non zero but who knows */
                !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
                if (s->width && s->height &&
                    (s->width != width || s->height != height))
                    s->context_reinit = 1;
                s->width  = width;
                s->height = height;
        s->progressive_sequence  =
        s->progressive_frame     = get_bits1(gb) ^ 1;
        s->interlaced_dct        = 0;
        if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
            av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
                   "MPEG4 OBMC not supported (very likely buggy encoder)\n");
        if (vo_ver_id == 1)
            ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
        else
            ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
        if (ctx->vol_sprite_usage == STATIC_SPRITE)
            av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
        if (ctx->vol_sprite_usage == STATIC_SPRITE ||
            ctx->vol_sprite_usage == GMC_SPRITE) {
            if (ctx->vol_sprite_usage == STATIC_SPRITE) {
                skip_bits(gb, 13); // sprite_width
                skip_bits1(gb); /* marker */
                skip_bits(gb, 13); // sprite_height
                skip_bits1(gb); /* marker */
                skip_bits(gb, 13); // sprite_left
                skip_bits1(gb); /* marker */
                skip_bits(gb, 13); // sprite_top
                skip_bits1(gb); /* marker */
            ctx->num_sprite_warping_points = get_bits(gb, 6);
            if (ctx->num_sprite_warping_points > 3) {
                av_log(s->avctx, AV_LOG_ERROR,
                       "%d sprite_warping_points\n",
                       ctx->num_sprite_warping_points);
                ctx->num_sprite_warping_points = 0;
                return -1;
            s->sprite_warping_accuracy  = get_bits(gb, 2);
            ctx->sprite_brightness_change = get_bits1(gb);
            if (ctx->vol_sprite_usage == STATIC_SPRITE)
                skip_bits1(gb); // low_latency_sprite
        // FIXME sadct disable bit if verid!=1 && shape not rect
        if (get_bits1(gb) == 1) {                   /* not_8_bit */
            s->quant_precision = get_bits(gb, 4);   /* quant_precision */
            if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
                av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
            if (s->quant_precision != 5)
                av_log(s->avctx, AV_LOG_ERROR,
                       "quant precision %d\n", s->quant_precision);
            if (s->quant_precision<3 || s->quant_precision>9) {
                s->quant_precision = 5;
        } else {
            s->quant_precision = 5;
        // FIXME a bunch of grayscale shape things
        if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
            int i, v;
            /* load default matrixes */
            for (i = 0; i < 64; i++) {
                int j = s->dsp.idct_permutation[i];
                v = ff_mpeg4_default_intra_matrix[i];
                s->intra_matrix[j]        = v;
                s->chroma_intra_matrix[j] = v;
                v = ff_mpeg4_default_non_intra_matrix[i];
                s->inter_matrix[j]        = v;
                s->chroma_inter_matrix[j] = v;
            /* load custom intra matrix */
            if (get_bits1(gb)) {
                int last = 0;
                for (i = 0; i < 64; i++) {
                    int j;
                    v = get_bits(gb, 8);
                    if (v == 0)
                        break;
                    last = v;
                    j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
                    s->intra_matrix[j]        = last;
                    s->chroma_intra_matrix[j] = last;
                /* replicate last value */
                for (; i < 64; i++) {
                    int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
                    s->intra_matrix[j]        = last;
                    s->chroma_intra_matrix[j] = last;
            /* load custom non intra matrix */
            if (get_bits1(gb)) {
                int last = 0;
                for (i = 0; i < 64; i++) {
                    int j;
                    v = get_bits(gb, 8);
                    if (v == 0)
                        break;
                    last = v;
                    j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
                    s->inter_matrix[j]        = v;
                    s->chroma_inter_matrix[j] = v;
                /* replicate last value */
                for (; i < 64; i++) {
                    int j = s->dsp.idct_permutation[ff_zigzag_direct[i]];
                    s->inter_matrix[j]        = last;
                    s->chroma_inter_matrix[j] = last;
            // FIXME a bunch of grayscale shape things
        if (vo_ver_id != 1)
            s->quarter_sample = get_bits1(gb);
        else
            s->quarter_sample = 0;
        if (!get_bits1(gb)) {
            int pos               = get_bits_count(gb);
            int estimation_method = get_bits(gb, 2);
            if (estimation_method < 2) {
                if (!get_bits1(gb)) {
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upampling */
                if (!get_bits1(gb)) {
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
                if (!check_marker(gb, "in complexity estimation part 1")) {
                    skip_bits_long(gb, pos - get_bits_count(gb));
                    goto no_cplx_est;
                if (!get_bits1(gb)) {
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
                    ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
                if (!get_bits1(gb)) {
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
                    ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
                if (!check_marker(gb, "in complexity estimation part 2")) {
                    skip_bits_long(gb, pos - get_bits_count(gb));
                    goto no_cplx_est;
                if (estimation_method == 1) {
                    ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
                    ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
            } else
                av_log(s->avctx, AV_LOG_ERROR,
                       "Invalid Complexity estimation method %d\n",
                       estimation_method);
        } else {
no_cplx_est:
            ctx->cplx_estimation_trash_i =
            ctx->cplx_estimation_trash_p =
            ctx->cplx_estimation_trash_b = 0;
        ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
        s->data_partitioning = get_bits1(gb);
        if (s->data_partitioning)
            ctx->rvlc = get_bits1(gb);
        if (vo_ver_id != 1) {
            ctx->new_pred = get_bits1(gb);
            if (ctx->new_pred) {
                av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
                skip_bits(gb, 2); /* requested upstream message type */
                skip_bits1(gb);   /* newpred segment type */
            if (get_bits1(gb)) // reduced_res_vop
                av_log(s->avctx, AV_LOG_ERROR,
                       "reduced resolution VOP not supported\n");
        } else {
            ctx->new_pred = 0;
        ctx->scalability = get_bits1(gb);
        if (ctx->scalability) {
            GetBitContext bak = *gb;
            int h_sampling_factor_n;
            int h_sampling_factor_m;
            int v_sampling_factor_n;
            int v_sampling_factor_m;
            skip_bits1(gb);    // hierarchy_type
            skip_bits(gb, 4);  /* ref_layer_id */
            skip_bits1(gb);    /* ref_layer_sampling_dir */
            h_sampling_factor_n = get_bits(gb, 5);
            h_sampling_factor_m = get_bits(gb, 5);
            v_sampling_factor_n = get_bits(gb, 5);
            v_sampling_factor_m = get_bits(gb, 5);
            ctx->enhancement_type = get_bits1(gb);
            if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
                v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
                /* illegal scalability header (VERY broken encoder),
                 * trying to workaround */
                ctx->scalability = 0;
                *gb            = bak;
            } else
                av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
            // bin shape stuff FIXME
    if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
        av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d,  %s%s%s%s\n",
               s->avctx->time_base.num, s->avctx->time_base.den,
               ctx->time_increment_bits,
               s->quant_precision,
               s->progressive_sequence,
               ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
               s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
        );
    return 0;


static int ac3_probe(AVProbeData *p)

{

    int max_frames, first_frames, frames;

    uint8_t *buf, *buf2, *end;

    AC3HeaderInfo hdr;

    if(p->buf_size < 7)

        return 0;

    max_frames = 0;

    buf = p->buf;

    end = buf + FFMIN(4096, p->buf_size - 7);

    for(; buf < end; buf++) {

        buf2 = buf;

        for(frames = 0; buf2 < end; frames++) {

            if(ff_ac3_parse_header(buf2, &hdr) < 0)

                break;

            buf2 += hdr.frame_size;

        }

        max_frames = FFMAX(max_frames, frames);

        if(buf == p->buf)

            first_frames = frames;

    }

    if   (first_frames>=3) return AVPROBE_SCORE_MAX * 3 / 4;

    else if(max_frames>=3) return AVPROBE_SCORE_MAX / 2;

    else if(max_frames>=1) return 1;

    else                   return 0;

}


static void virtio_ccw_device_plugged(DeviceState *d)

{

    VirtioCcwDevice *dev = VIRTIO_CCW_DEVICE(d);

    SubchDev *sch = dev->sch;

    sch->id.cu_model = virtio_bus_get_vdev_id(&dev->bus);

    css_generate_sch_crws(sch->cssid, sch->ssid, sch->schid,

                          d->hotplugged, 1);

}


static void digic_uart_write(void *opaque, hwaddr addr, uint64_t value,

                             unsigned size)

{

    DigicUartState *s = opaque;

    unsigned char ch = value;

    addr >>= 2;

    switch (addr) {

    case R_TX:

        if (s->chr) {

            qemu_chr_fe_write_all(s->chr, &ch, 1);

        }

        break;

    case R_ST:

        /*

         * Ignore write to R_ST.

         *

         * The point is that this register is actively used

         * during receiving and transmitting symbols,

         * but we don't know the function of most of bits.

         *

         * Ignoring writes to R_ST is only a simplification

         * of the model. It has no perceptible side effects

         * for existing guests.

         */

        break;

    default:

        qemu_log_mask(LOG_UNIMP,

                      "digic-uart: write access to unknown register 0x"

                      TARGET_FMT_plx, addr << 2);

    }

}


static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,

                                                           vorbis_residue *vr,

                                                           uint_fast8_t ch,

                                                           uint_fast8_t *do_not_decode,

                                                           float *vec,

                                                           uint_fast16_t vlen,

                                                           int vr_type)

{

    GetBitContext *gb = &vc->gb;

    uint_fast8_t c_p_c = vc->codebooks[vr->classbook].dimensions;

    uint_fast16_t ptns_to_read = vr->ptns_to_read;

    uint_fast8_t *classifs = vr->classifs;

    uint_fast8_t pass;

    uint_fast8_t ch_used;

    uint_fast8_t i,j,l;

    uint_fast16_t k;

    if (vr_type == 2) {

        for (j = 1; j < ch; ++j)

            do_not_decode[0] &= do_not_decode[j];  // FIXME - clobbering input

        if (do_not_decode[0])

            return 0;

        ch_used = 1;

    } else {

        ch_used = ch;

    }

    AV_DEBUG(" residue type 0/1/2 decode begin, ch: %d  cpc %d  \n", ch, c_p_c);

    for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?

        uint_fast16_t voffset;

        uint_fast16_t partition_count;

        uint_fast16_t j_times_ptns_to_read;

        voffset = vr->begin;

        for (partition_count = 0; partition_count < ptns_to_read;) {  // SPEC        error

            if (!pass) {

                uint_fast32_t inverse_class = ff_inverse[vr->classifications];

                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {

                    if (!do_not_decode[j]) {

                        uint_fast32_t temp = get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,

                        vc->codebooks[vr->classbook].nb_bits, 3);

                        AV_DEBUG("Classword: %d \n", temp);

                        assert(vr->classifications > 1 && temp <= 65536); //needed for inverse[]

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

                            uint_fast32_t temp2;

                            temp2 = (((uint_fast64_t)temp) * inverse_class) >> 32;

                            if (partition_count + c_p_c - 1 - i < ptns_to_read)

                                classifs[j_times_ptns_to_read + partition_count + c_p_c - 1 - i] = temp - temp2 * vr->classifications;

                            temp = temp2;

                        }

                    }

                    j_times_ptns_to_read += ptns_to_read;

                }

            }

            for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {

                for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {

                    uint_fast16_t voffs;

                    if (!do_not_decode[j]) {

                        uint_fast8_t vqclass = classifs[j_times_ptns_to_read+partition_count];

                        int_fast16_t vqbook = vr->books[vqclass][pass];

                        if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {

                            uint_fast16_t coffs;

                            unsigned dim =  vc->codebooks[vqbook].dimensions; // not uint_fast8_t: 64bit is slower here on amd64

                            uint_fast16_t step = dim == 1 ? vr->partition_size

                                                          : FASTDIV(vr->partition_size, dim);

                            vorbis_codebook codebook = vc->codebooks[vqbook];

                            if (vr_type == 0) {

                                voffs = voffset+j*vlen;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l)

                                        vec[voffs + k + l * step] += codebook.codevectors[coffs + l];  // FPMATH

                                }

                            } else if (vr_type == 1) {

                                voffs = voffset + j * vlen;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l, ++voffs) {

                                        vec[voffs]+=codebook.codevectors[coffs+l];  // FPMATH

                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d  \n", pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);

                                    }

                                }

                            } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized

                                voffs = voffset >> 1;

                                if (dim == 2) {

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

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;

                                        vec[voffs + k       ] += codebook.codevectors[coffs    ];  // FPMATH

                                        vec[voffs + k + vlen] += codebook.codevectors[coffs + 1];  // FPMATH

                                    }

                                } else if (dim == 4) {

                                    for (k = 0; k < step; ++k, voffs += 2) {

                                        coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;

                                        vec[voffs           ] += codebook.codevectors[coffs    ];  // FPMATH

                                        vec[voffs + 1       ] += codebook.codevectors[coffs + 2];  // FPMATH

                                        vec[voffs + vlen    ] += codebook.codevectors[coffs + 1];  // FPMATH

                                        vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3];  // FPMATH

                                    }

                                } else

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; l += 2, voffs++) {

                                        vec[voffs       ] += codebook.codevectors[coffs + l    ];  // FPMATH

                                        vec[voffs + vlen] += codebook.codevectors[coffs + l + 1];  // FPMATH

                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n", pass, voffset / ch + (voffs % ch) * vlen, vec[voffset / ch + (voffs % ch) * vlen], codebook.codevectors[coffs + l], coffs, l);

                                    }

                                }

                            } else if (vr_type == 2) {

                                voffs = voffset;

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

                                    coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;

                                    for (l = 0; l < dim; ++l, ++voffs) {

                                        vec[voffs / ch + (voffs % ch) * vlen] += codebook.codevectors[coffs + l];  // FPMATH FIXME use if and counter instead of / and %

                                        AV_DEBUG(" pass %d offs: %d curr: %f change: %f cv offs.: %d+%d  \n", pass, voffset / ch + (voffs % ch) * vlen, vec[voffset / ch + (voffs % ch) * vlen], codebook.codevectors[coffs + l], coffs, l);

                                    }

                                }

                            }

                        }

                    }

                    j_times_ptns_to_read += ptns_to_read;

                }

                ++partition_count;

                voffset += vr->partition_size;

            }

        }

    }

    return 0;

}


static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path,

                              const char *name, V9fsPath *target)

{

    if (dir_path) {

        v9fs_path_sprintf(target, "%s/%s", dir_path->data, name);

    } else {

        v9fs_path_sprintf(target, "%s", name);

    }

    return 0;

}


static inline void RENAME(bgr24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)

{

    int i;

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

        int b= src1[6*i + 0] + src1[6*i + 3];

        int g= src1[6*i + 1] + src1[6*i + 4];

        int r= src1[6*i + 2] + src1[6*i + 5];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);

        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);

    }

    assert(src1 == src2);

}


static int ftp_parse_entry_mlsd(char *mlsd, AVIODirEntry *next)

{

    char *fact, *value;

    av_dlog(NULL, "%s\n", mlsd);

    while(fact = av_strtok(mlsd, ";", &mlsd)) {

        if (fact[0] == ' ') {

            next->name = av_strdup(&fact[1]);

            continue;

        }

        fact = av_strtok(fact, "=", &value);

        if (!av_strcasecmp(fact, "type")) {

            if (!av_strcasecmp(value, "cdir") || !av_strcasecmp(value, "pdir"))

                return 1;

            if (!av_strcasecmp(value, "dir"))

                next->type = AVIO_ENTRY_DIRECTORY;

            else if (!av_strcasecmp(value, "file"))

                next->type = AVIO_ENTRY_FILE;

            else if (!av_strcasecmp(value, "OS.unix=slink:"))

                next->type = AVIO_ENTRY_SYMBOLIC_LINK;

        } else if (!av_strcasecmp(fact, "modify")) {

            next->modification_timestamp = ftp_parse_date(value);

        } else if (!av_strcasecmp(fact, "UNIX.mode")) {

            next->filemode = strtoumax(value, NULL, 8);

        } else if (!av_strcasecmp(fact, "UNIX.uid") || !av_strcasecmp(fact, "UNIX.owner"))

            next->user_id = strtoumax(value, NULL, 10);

        else if (!av_strcasecmp(fact, "UNIX.gid") || !av_strcasecmp(fact, "UNIX.group"))

            next->group_id = strtoumax(value, NULL, 10);

        else if (!av_strcasecmp(fact, "size") || !av_strcasecmp(fact, "sizd"))

            next->size = strtoll(value, NULL, 10);

    }

    return 0;

}


static int get_scale_idx(GetBitContext *gb, int ref)

{

    int t = get_vlc2(gb, dscf_vlc.table, MPC7_DSCF_BITS, 1) - 7;

    if (t == 8)

        return get_bits(gb, 6);

    return ref + t;

}


int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,

                    struct image_info * info)

{

    struct elfhdr elf_ex;

    struct elfhdr interp_elf_ex;

    struct exec interp_ex;

    int interpreter_fd = -1; /* avoid warning */

    abi_ulong load_addr, load_bias;

    int load_addr_set = 0;

    unsigned int interpreter_type = INTERPRETER_NONE;

    unsigned char ibcs2_interpreter;

    int i;

    abi_ulong mapped_addr;

    struct elf_phdr * elf_ppnt;

    struct elf_phdr *elf_phdata;

    abi_ulong k, elf_brk;

    int retval;

    char * elf_interpreter;

    abi_ulong elf_entry, interp_load_addr = 0;

    int status;

    abi_ulong start_code, end_code, start_data, end_data;

    abi_ulong reloc_func_desc = 0;

    abi_ulong elf_stack;

    char passed_fileno[6];

    ibcs2_interpreter = 0;

    status = 0;

    load_addr = 0;

    load_bias = 0;

    elf_ex = *((struct elfhdr *) bprm->buf);          /* exec-header */

    bswap_ehdr(&elf_ex);

    /* First of all, some simple consistency checks */

    if ((elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN) ||

        (! elf_check_arch(elf_ex.e_machine))) {

        return -ENOEXEC;

    }

    bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);

    bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);

    bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);

    if (!bprm->p) {

        retval = -E2BIG;

    }

    /* Now read in all of the header information */

    elf_phdata = (struct elf_phdr *)malloc(elf_ex.e_phentsize*elf_ex.e_phnum);

    if (elf_phdata == NULL) {

        return -ENOMEM;

    }

    i = elf_ex.e_phnum * sizeof(struct elf_phdr);

    if (elf_ex.e_phoff + i <= BPRM_BUF_SIZE) {

        memcpy(elf_phdata, bprm->buf + elf_ex.e_phoff, i);

    } else {

        retval = pread(bprm->fd, (char *) elf_phdata, i, elf_ex.e_phoff);

        if (retval != i) {

            perror("load_elf_binary");

            exit(-1);

        }

    }

    bswap_phdr(elf_phdata, elf_ex.e_phnum);

    elf_brk = 0;

    elf_stack = ~((abi_ulong)0UL);

    elf_interpreter = NULL;

    start_code = ~((abi_ulong)0UL);

    end_code = 0;

    start_data = 0;

    end_data = 0;

    interp_ex.a_info = 0;

    elf_ppnt = elf_phdata;

    for(i=0;i < elf_ex.e_phnum; i++) {

        if (elf_ppnt->p_type == PT_INTERP) {

            if ( elf_interpreter != NULL )

            {

                free (elf_phdata);

                free(elf_interpreter);

                close(bprm->fd);

                return -EINVAL;

            }

            /* This is the program interpreter used for

             * shared libraries - for now assume that this

             * is an a.out format binary

             */

            elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);

            if (elf_interpreter == NULL) {

                free (elf_phdata);

                close(bprm->fd);

                return -ENOMEM;

            }

            if (elf_ppnt->p_offset + elf_ppnt->p_filesz <= BPRM_BUF_SIZE) {

                memcpy(elf_interpreter, bprm->buf + elf_ppnt->p_offset,

                       elf_ppnt->p_filesz);

            } else {

                retval = pread(bprm->fd, elf_interpreter, elf_ppnt->p_filesz,

                               elf_ppnt->p_offset);

                if (retval != elf_ppnt->p_filesz) {

                    perror("load_elf_binary2");

                    exit(-1);

                }

            }

            /* If the program interpreter is one of these two,

               then assume an iBCS2 image. Otherwise assume

               a native linux image. */

            /* JRP - Need to add X86 lib dir stuff here... */

            if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||

                strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0) {

                ibcs2_interpreter = 1;

            }

            retval = open(path(elf_interpreter), O_RDONLY);

            if (retval < 0) {

                perror(elf_interpreter);

                exit(-1);

            }

            interpreter_fd = retval;

            retval = read(interpreter_fd, bprm->buf, BPRM_BUF_SIZE);

            if (retval < 0) {

                perror("load_elf_binary3");

                exit(-1);

            }

            if (retval < BPRM_BUF_SIZE) {

                memset(bprm->buf, 0, BPRM_BUF_SIZE - retval);

            }

            interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */

            interp_elf_ex = *((struct elfhdr *) bprm->buf); /* elf exec-header */

        }

        elf_ppnt++;

    }

    /* Some simple consistency checks for the interpreter */

    if (elf_interpreter){

        interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;

        /* Now figure out which format our binary is */

        if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&

            (N_MAGIC(interp_ex) != QMAGIC)) {

            interpreter_type = INTERPRETER_ELF;

        }

        if (interp_elf_ex.e_ident[0] != 0x7f ||

            strncmp((char *)&interp_elf_ex.e_ident[1], "ELF",3) != 0) {

            interpreter_type &= ~INTERPRETER_ELF;

        }

        if (!interpreter_type) {

            free(elf_interpreter);

            free(elf_phdata);

            close(bprm->fd);

            return -ELIBBAD;

        }

    }

    /* OK, we are done with that, now set up the arg stuff,

       and then start this sucker up */

    {

        char * passed_p;

        if (interpreter_type == INTERPRETER_AOUT) {

            snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);

            passed_p = passed_fileno;

            if (elf_interpreter) {

                bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);

                bprm->argc++;

            }

        }

        if (!bprm->p) {

            if (elf_interpreter) {

                free(elf_interpreter);

            }

            free (elf_phdata);

            close(bprm->fd);

            return -E2BIG;

        }

    }

    /* OK, This is the point of no return */

    info->end_data = 0;

    info->end_code = 0;

    info->start_mmap = (abi_ulong)ELF_START_MMAP;

    info->mmap = 0;

    elf_entry = (abi_ulong) elf_ex.e_entry;

#if defined(CONFIG_USE_GUEST_BASE)

    /*

     * In case where user has not explicitly set the guest_base, we

     * probe here that should we set it automatically.

     */

    if (!(have_guest_base || reserved_va)) {

        /*

         * Go through ELF program header table and find the address

         * range used by loadable segments.  Check that this is available on

         * the host, and if not find a suitable value for guest_base.  */

        abi_ulong app_start = ~0;

        abi_ulong app_end = 0;

        abi_ulong addr;

        unsigned long host_start;

        unsigned long real_start;

        unsigned long host_size;

        for (i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum;

             i++, elf_ppnt++) {

            if (elf_ppnt->p_type != PT_LOAD)

                continue;

            addr = elf_ppnt->p_vaddr;

            if (addr < app_start) {

                app_start = addr;

            }

            addr += elf_ppnt->p_memsz;

            if (addr > app_end) {

                app_end = addr;

            }

        }

        /* If we don't have any loadable segments then something

           is very wrong.  */

        assert(app_start < app_end);

        /* Round addresses to page boundaries.  */

        app_start = app_start & qemu_host_page_mask;

        app_end = HOST_PAGE_ALIGN(app_end);

        if (app_start < mmap_min_addr) {

            host_start = HOST_PAGE_ALIGN(mmap_min_addr);

        } else {

            host_start = app_start;

            if (host_start != app_start) {

                fprintf(stderr, "qemu: Address overflow loading ELF binary\n");

                abort();

            }

        }

        host_size = app_end - app_start;

        while (1) {

            /* Do not use mmap_find_vma here because that is limited to the

               guest address space.  We are going to make the

               guest address space fit whatever we're given.  */

            real_start = (unsigned long)mmap((void *)host_start, host_size,

                PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, -1, 0);

            if (real_start == (unsigned long)-1) {

                fprintf(stderr, "qemu: Virtual memory exausted\n");

                abort();

            }

            if (real_start == host_start) {

                break;

            }

            /* That address didn't work.  Unmap and try a different one.

               The address the host picked because is typically

               right at the top of the host address space and leaves the

               guest with no usable address space.  Resort to a linear search.

               We already compensated for mmap_min_addr, so this should not

               happen often.  Probably means we got unlucky and host address

               space randomization put a shared library somewhere

               inconvenient.  */

            munmap((void *)real_start, host_size);

            host_start += qemu_host_page_size;

            if (host_start == app_start) {

                /* Theoretically possible if host doesn't have any

                   suitably aligned areas.  Normally the first mmap will

                   fail.  */

                fprintf(stderr, "qemu: Unable to find space for application\n");

                abort();

            }

        }

        qemu_log("Relocating guest address space from 0x" TARGET_ABI_FMT_lx

                 " to 0x%lx\n", app_start, real_start);

        guest_base = real_start - app_start;

    }

#endif /* CONFIG_USE_GUEST_BASE */

    /* Do this so that we can load the interpreter, if need be.  We will

       change some of these later */

    info->rss = 0;

    bprm->p = setup_arg_pages(bprm->p, bprm, info);

    info->start_stack = bprm->p;

    /* Now we do a little grungy work by mmaping the ELF image into

     * the correct location in memory.  At this point, we assume that

     * the image should be loaded at fixed address, not at a variable

     * address.

     */

    for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {

        int elf_prot = 0;

        int elf_flags = 0;

        abi_ulong error;

        if (elf_ppnt->p_type != PT_LOAD)

            continue;

        if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;

        if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;

        if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;

        elf_flags = MAP_PRIVATE | MAP_DENYWRITE;

        if (elf_ex.e_type == ET_EXEC || load_addr_set) {

            elf_flags |= MAP_FIXED;

        } else if (elf_ex.e_type == ET_DYN) {

            /* Try and get dynamic programs out of the way of the default mmap

               base, as well as whatever program they might try to exec.  This

               is because the brk will follow the loader, and is not movable.  */

            /* NOTE: for qemu, we do a big mmap to get enough space

               without hardcoding any address */

            error = target_mmap(0, ET_DYN_MAP_SIZE,

                                PROT_NONE, MAP_PRIVATE | MAP_ANON,

                                -1, 0);

            if (error == -1) {

                perror("mmap");

                exit(-1);

            }

            load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);

        }

        error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),

                            (elf_ppnt->p_filesz +

                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),

                            elf_prot,

                            (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),

                            bprm->fd,

                            (elf_ppnt->p_offset -

                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));

        if (error == -1) {

            perror("mmap");

            exit(-1);

        }

#ifdef LOW_ELF_STACK

        if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)

            elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);

#endif

        if (!load_addr_set) {

            load_addr_set = 1;

            load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;

            if (elf_ex.e_type == ET_DYN) {

                load_bias += error -

                    TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);

                load_addr += load_bias;

                reloc_func_desc = load_bias;

            }

        }

        k = elf_ppnt->p_vaddr;

        if (k < start_code)

            start_code = k;

        if (start_data < k)

            start_data = k;

        k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;

        if ((elf_ppnt->p_flags & PF_X) && end_code <  k)

            end_code = k;

        if (end_data < k)

            end_data = k;

        k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;

        if (k > elf_brk) {

            elf_brk = TARGET_PAGE_ALIGN(k);

        }

        /* If the load segment requests extra zeros (e.g. bss), map it.  */

        if (elf_ppnt->p_filesz < elf_ppnt->p_memsz) {

            abi_ulong base = load_bias + elf_ppnt->p_vaddr;

            zero_bss(base + elf_ppnt->p_filesz,

                     base + elf_ppnt->p_memsz, elf_prot);

        }

    }

    elf_entry += load_bias;

    elf_brk += load_bias;

    start_code += load_bias;

    end_code += load_bias;

    start_data += load_bias;

    end_data += load_bias;

    if (elf_interpreter) {

        if (interpreter_type & 1) {

            elf_entry = load_aout_interp(&interp_ex, interpreter_fd);

        } else if (interpreter_type & 2) {

            elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,

                                        &interp_load_addr, bprm->buf);

        }

        reloc_func_desc = interp_load_addr;

        close(interpreter_fd);

        free(elf_interpreter);

        if (elf_entry == ~((abi_ulong)0UL)) {

            printf("Unable to load interpreter\n");

            free(elf_phdata);

            exit(-1);

            return 0;

        }

    }

    free(elf_phdata);

    if (qemu_log_enabled()) {

        load_symbols(&elf_ex, bprm->fd, load_bias);

    }

    if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);

    info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);

#ifdef LOW_ELF_STACK

    info->start_stack = bprm->p = elf_stack - 4;

#endif

    bprm->p = create_elf_tables(bprm->p,

                                bprm->argc,

                                bprm->envc,

                                &elf_ex,

                                load_addr, load_bias,

                                interp_load_addr,

                                (interpreter_type == INTERPRETER_AOUT ? 0 : 1),

                                info);

    info->load_addr = reloc_func_desc;

    info->start_brk = info->brk = elf_brk;

    info->end_code = end_code;

    info->start_code = start_code;

    info->start_data = start_data;

    info->end_data = end_data;

    info->start_stack = bprm->p;

#if 0

    printf("(start_brk) %x\n" , info->start_brk);

    printf("(end_code) %x\n" , info->end_code);

    printf("(start_code) %x\n" , info->start_code);

    printf("(end_data) %x\n" , info->end_data);

    printf("(start_stack) %x\n" , info->start_stack);

    printf("(brk) %x\n" , info->brk);

#endif

    if ( info->personality == PER_SVR4 )

    {

        /* Why this, you ask???  Well SVr4 maps page 0 as read-only,

           and some applications "depend" upon this behavior.

           Since we do not have the power to recompile these, we

           emulate the SVr4 behavior.  Sigh.  */

        mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,

                                  MAP_FIXED | MAP_PRIVATE, -1, 0);

    }

    info->entry = elf_entry;

#ifdef USE_ELF_CORE_DUMP

    bprm->core_dump = &elf_core_dump;

#endif

    return 0;

}


static sd_rsp_type_t sd_app_command(SDState *sd,

                                    SDRequest req)

{

    DPRINTF("ACMD%d 0x%08x\n", req.cmd, req.arg);

    sd->card_status |= APP_CMD;

    switch (req.cmd) {

    case 6:	/* ACMD6:  SET_BUS_WIDTH */

        switch (sd->state) {

        case sd_transfer_state:

            sd->sd_status[0] &= 0x3f;

            sd->sd_status[0] |= (req.arg & 0x03) << 6;

            return sd_r1;

        default:

            break;

        }

        break;

    case 13:	/* ACMD13: SD_STATUS */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 22:	/* ACMD22: SEND_NUM_WR_BLOCKS */

        switch (sd->state) {

        case sd_transfer_state:

            *(uint32_t *) sd->data = sd->blk_written;

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    case 23:	/* ACMD23: SET_WR_BLK_ERASE_COUNT */

        switch (sd->state) {

        case sd_transfer_state:

            return sd_r1;

        default:

            break;

        }

        break;

    case 41:	/* ACMD41: SD_APP_OP_COND */

        if (sd->spi) {

            /* SEND_OP_CMD */

            sd->state = sd_transfer_state;

            return sd_r1;

        }

        switch (sd->state) {

        case sd_idle_state:

            /* We accept any voltage.  10000 V is nothing.

             *

             * We don't model init delay so just advance straight to ready state

             * unless it's an enquiry ACMD41 (bits 23:0 == 0).

             */

            if (req.arg & ACMD41_ENQUIRY_MASK) {

                sd->state = sd_ready_state;

            }

            return sd_r3;

        default:

            break;

        }

        break;

    case 42:	/* ACMD42: SET_CLR_CARD_DETECT */

        switch (sd->state) {

        case sd_transfer_state:

            /* Bringing in the 50KOhm pull-up resistor... Done.  */

            return sd_r1;

        default:

            break;

        }

        break;

    case 51:	/* ACMD51: SEND_SCR */

        switch (sd->state) {

        case sd_transfer_state:

            sd->state = sd_sendingdata_state;

            sd->data_start = 0;

            sd->data_offset = 0;

            return sd_r1;

        default:

            break;

        }

        break;

    default:

        /* Fall back to standard commands.  */

        return sd_normal_command(sd, req);

    }

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

    return sd_illegal;

}


static void bt_dummy_lmp_connection_complete(struct bt_link_s *link)

{

    if (link->slave->reject_reason)

        fprintf(stderr, "%s: stray LMP_not_accepted received, fixme\n",

                        __func__);

    else

        fprintf(stderr, "%s: stray LMP_accepted received, fixme\n",

                        __func__);

    exit(-1);

}


static void add_flagname_to_bitmaps(const char *flagname, uint32_t *features,

                                    uint32_t *ext_features,

                                    uint32_t *ext2_features,

                                    uint32_t *ext3_features)

{

    int i;

    int found = 0;

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

        if (feature_name[i] && !strcmp (flagname, feature_name[i])) {

            *features |= 1 << i;

            found = 1;

        }

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

        if (ext_feature_name[i] && !strcmp (flagname, ext_feature_name[i])) {

            *ext_features |= 1 << i;

            found = 1;

        }

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

        if (ext2_feature_name[i] && !strcmp (flagname, ext2_feature_name[i])) {

            *ext2_features |= 1 << i;

            found = 1;

        }

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

        if (ext3_feature_name[i] && !strcmp (flagname, ext3_feature_name[i])) {

            *ext3_features |= 1 << i;

            found = 1;

        }

    if (!found) {

        fprintf(stderr, "CPU feature %s not found\n", flagname);

    }

}


struct pxa2xx_i2c_s *pxa2xx_i2c_init(target_phys_addr_t base,

                qemu_irq irq, int ioregister)

{

    int iomemtype;

    struct pxa2xx_i2c_s *s = (struct pxa2xx_i2c_s *)

            i2c_slave_init(i2c_init_bus(), 0, sizeof(struct pxa2xx_i2c_s));

    s->base = base;

    s->irq = irq;

    s->slave.event = pxa2xx_i2c_event;

    s->slave.recv = pxa2xx_i2c_rx;

    s->slave.send = pxa2xx_i2c_tx;

    s->bus = i2c_init_bus();

    if (ioregister) {

        iomemtype = cpu_register_io_memory(0, pxa2xx_i2c_readfn,

                        pxa2xx_i2c_writefn, s);

        cpu_register_physical_memory(s->base & 0xfffff000, 0xfff, iomemtype);

    }

    register_savevm("pxa2xx_i2c", base, 0,

                    pxa2xx_i2c_save, pxa2xx_i2c_load, s);

    return s;

}


static int v9fs_synth_link(FsContext *fs_ctx, V9fsPath *oldpath,

                           V9fsPath *newpath, const char *buf)

{

    errno = EPERM;

    return -1;

}


static bool pmsav7_rgnr_vmstate_validate(void *opaque, int version_id)

{

    ARMCPU *cpu = opaque;

    return cpu->env.pmsav7.rnr < cpu->pmsav7_dregion;

}


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

                  NetClientState *peer, Error **errp)

{

    int len, rc;

    const char *file;

    char def_file[128];

    const NetdevDumpOptions *dump;

    NetClientState *nc;

    DumpNetClient *dnc;

    assert(opts->type == NET_CLIENT_OPTIONS_KIND_DUMP);

    dump = opts->u.dump;

    assert(peer);

    if (dump->has_file) {

        file = dump->file;

    } else {

        int id;

        int ret;

        ret = net_hub_id_for_client(peer, &id);

        assert(ret == 0); /* peer must be on a hub */

        snprintf(def_file, sizeof(def_file), "qemu-vlan%d.pcap", id);

        file = def_file;

    }

    if (dump->has_len) {

        if (dump->len > INT_MAX) {

            error_setg(errp, "invalid length: %"PRIu64, dump->len);

            return -1;

        }

        len = dump->len;

    } else {

        len = 65536;

    }

    nc = qemu_new_net_client(&net_dump_info, peer, "dump", name);

    snprintf(nc->info_str, sizeof(nc->info_str),

             "dump to %s (len=%d)", file, len);

    dnc = DO_UPCAST(DumpNetClient, nc, nc);

    rc = net_dump_state_init(&dnc->ds, file, len, errp);

    if (rc) {

        qemu_del_net_client(nc);

    }

    return rc;

}