static void mov_read_chapters(AVFormatContext *s)

{

    MOVContext *mov = s->priv_data;

    AVStream *st = NULL;

    MOVStreamContext *sc;

    int64_t cur_pos;

    int i;

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

        if (s->streams[i]->id == mov->chapter_track) {

            st = s->streams[i];

            break;

        }

    if (!st) {

        av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n");

        return;

    }

    st->discard = AVDISCARD_ALL;

    sc = st->priv_data;

    cur_pos = avio_tell(sc->pb);

    for (i = 0; i < st->nb_index_entries; i++) {

        AVIndexEntry *sample = &st->index_entries[i];

        int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration;

        uint8_t *title;

        uint16_t ch;

        int len, title_len;

        if (end < sample->timestamp) {

            av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n");

            end = AV_NOPTS_VALUE;

        }

        if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) {

            av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i);

            goto finish;

        }

        // the first two bytes are the length of the title

        len = avio_rb16(sc->pb);

        if (len > sample->size-2)

            continue;

        title_len = 2*len + 1;

        if (!(title = av_mallocz(title_len)))

            goto finish;

        // The samples could theoretically be in any encoding if there's an encd

        // atom following, but in practice are only utf-8 or utf-16, distinguished

        // instead by the presence of a BOM

        if (!len) {

            title[0] = 0;

        } else {

            ch = avio_rb16(sc->pb);

            if (ch == 0xfeff)

                avio_get_str16be(sc->pb, len, title, title_len);

            else if (ch == 0xfffe)

                avio_get_str16le(sc->pb, len, title, title_len);

            else {

                AV_WB16(title, ch);

                if (len == 1 || len == 2)

                    title[len] = 0;

                else

                    avio_get_str(sc->pb, INT_MAX, title + 2, len - 1);

            }

        }

        avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title);

        av_freep(&title);

    }

finish:

    avio_seek(sc->pb, cur_pos, SEEK_SET);

}


static int msrle_decode_pal4(AVCodecContext *avctx, AVFrame *pic,

                             GetByteContext *gb)

{

    unsigned char rle_code;

    unsigned char extra_byte, odd_pixel;

    unsigned char stream_byte;

    int pixel_ptr = 0;

    int line = avctx->height - 1;

    int i;

    while (line >= 0 && pixel_ptr <= avctx->width) {

        if (bytestream2_get_bytes_left(gb) <= 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "MS RLE: bytestream overrun, %dx%d left\n",

                   avctx->width - pixel_ptr, line);

            return AVERROR_INVALIDDATA;

        }

        rle_code = stream_byte = bytestream2_get_byteu(gb);

        if (rle_code == 0) {

            /* fetch the next byte to see how to handle escape code */

            stream_byte = bytestream2_get_byte(gb);

            if (stream_byte == 0) {

                /* line is done, goto the next one */

                line--;

                pixel_ptr = 0;

            } else if (stream_byte == 1) {

                /* decode is done */

                return 0;

            } else if (stream_byte == 2) {

                /* reposition frame decode coordinates */

                stream_byte = bytestream2_get_byte(gb);

                pixel_ptr += stream_byte;

                stream_byte = bytestream2_get_byte(gb);

                avpriv_request_sample(avctx, "Unused stream byte %X", stream_byte);

            } else {

                // copy pixels from encoded stream

                odd_pixel =  stream_byte & 1;

                rle_code = (stream_byte + 1) / 2;

                extra_byte = rle_code & 0x01;

                if (pixel_ptr + 2*rle_code - odd_pixel > avctx->width ||

                    bytestream2_get_bytes_left(gb) < rle_code) {

                    av_log(avctx, AV_LOG_ERROR,

                           "MS RLE: frame/stream ptr just went out of bounds (copy)\n");

                    return AVERROR_INVALIDDATA;

                }

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

                    if (pixel_ptr >= avctx->width)

                        break;

                    stream_byte = bytestream2_get_byteu(gb);

                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte >> 4;

                    pixel_ptr++;

                    if (i + 1 == rle_code && odd_pixel)

                        break;

                    if (pixel_ptr >= avctx->width)

                        break;

                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte & 0x0F;

                    pixel_ptr++;

                }

                // if the RLE code is odd, skip a byte in the stream

                if (extra_byte)

                    bytestream2_skip(gb, 1);

            }

        } else {

            // decode a run of data

            if (pixel_ptr + rle_code > avctx->width + 1) {

                av_log(avctx, AV_LOG_ERROR,

                       "MS RLE: frame ptr just went out of bounds (run) %d %d %d\n", pixel_ptr, rle_code, avctx->width);

                return AVERROR_INVALIDDATA;

            }

            stream_byte = bytestream2_get_byte(gb);

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

                if (pixel_ptr >= avctx->width)

                    break;

                if ((i & 1) == 0)

                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte >> 4;

                else

                    pic->data[0][line * pic->linesize[0] + pixel_ptr] = stream_byte & 0x0F;

                pixel_ptr++;

            }

        }

    }

    /* one last sanity check on the way out */

    if (bytestream2_get_bytes_left(gb)) {

        av_log(avctx, AV_LOG_ERROR,

               "MS RLE: ended frame decode with %d bytes left over\n",

               bytestream2_get_bytes_left(gb));

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void update_initial_durations(AVFormatContext *s, AVStream *st,

                                     int stream_index, int duration)

{

    AVPacketList *pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;

    int64_t cur_dts    = RELATIVE_TS_BASE;

    if (st->first_dts != AV_NOPTS_VALUE) {

        if (st->update_initial_durations_done)

            return;

        st->update_initial_durations_done = 1;

        cur_dts = st->first_dts;

        for (; pktl; pktl = get_next_pkt(s, st, pktl)) {

            if (pktl->pkt.stream_index == stream_index) {

                if (pktl->pkt.pts != pktl->pkt.dts  ||

                    pktl->pkt.dts != AV_NOPTS_VALUE ||

                    pktl->pkt.duration)

                    break;

                cur_dts -= duration;

            }

        }

        if (pktl && pktl->pkt.dts != st->first_dts) {

            av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",

                   av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);

            return;

        }

        if (!pktl) {

            av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));

            return;

        }

        pktl          = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;

        st->first_dts = cur_dts;

    } else if (st->cur_dts != RELATIVE_TS_BASE)

        return;

    for (; pktl; pktl = get_next_pkt(s, st, pktl)) {

        if (pktl->pkt.stream_index != stream_index)

            continue;

        if (pktl->pkt.pts == pktl->pkt.dts  &&

            (pktl->pkt.dts == AV_NOPTS_VALUE || pktl->pkt.dts == st->first_dts) &&

            !pktl->pkt.duration) {

            pktl->pkt.dts = cur_dts;

            if (!st->internal->avctx->has_b_frames)

                pktl->pkt.pts = cur_dts;

//            if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)

                pktl->pkt.duration = duration;

        } else

            break;

        cur_dts = pktl->pkt.dts + pktl->pkt.duration;

    }

    if (!pktl)

        st->cur_dts = cur_dts;

}


int poll(struct pollfd *fds, nfds_t numfds, int timeout)

{

    fd_set read_set;

    fd_set write_set;

    fd_set exception_set;

    nfds_t i;

    int n;

    int rc;

#ifdef __MINGW32__

    if (numfds >= FD_SETSIZE) {

        errno = EINVAL;

        return -1;

    }

#endif

    FD_ZERO(&read_set);

    FD_ZERO(&write_set);

    FD_ZERO(&exception_set);

    n = -1;

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

        if (fds[i].fd < 0)

            continue;

#ifndef __MINGW32__

        if (fds[i].fd >= FD_SETSIZE) {

            errno = EINVAL;

            return -1;

        }

#endif

        if (fds[i].events & POLLIN)  FD_SET(fds[i].fd, &read_set);

        if (fds[i].events & POLLOUT) FD_SET(fds[i].fd, &write_set);

        if (fds[i].events & POLLERR) FD_SET(fds[i].fd, &exception_set);

        if (fds[i].fd > n)

            n = fds[i].fd;

    };

    if (n == -1)

        /* Hey!? Nothing to poll, in fact!!! */

        return 0;

    if (timeout < 0)

        rc = select(n+1, &read_set, &write_set, &exception_set, NULL);

    else {

        struct timeval    tv;

        tv.tv_sec = timeout / 1000;

        tv.tv_usec = 1000 * (timeout % 1000);

        rc = select(n+1, &read_set, &write_set, &exception_set, &tv);

    };

    if (rc < 0)

        return rc;

    for(i = 0; i < (nfds_t) n; i++) {

        fds[i].revents = 0;

        if (FD_ISSET(fds[i].fd, &read_set))      fds[i].revents |= POLLIN;

        if (FD_ISSET(fds[i].fd, &write_set))     fds[i].revents |= POLLOUT;

        if (FD_ISSET(fds[i].fd, &exception_set)) fds[i].revents |= POLLERR;

    };

    return rc;

}


int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,

                        int wanted_stream_nb, int related_stream,

                        AVCodec **decoder_ret, int flags)

{

    int i, nb_streams = ic->nb_streams;

    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1, best_bitrate = -1, best_multiframe = -1, count, bitrate, multiframe;

    unsigned *program = NULL;

    const AVCodec *decoder = NULL, *best_decoder = NULL;

    if (related_stream >= 0 && wanted_stream_nb < 0) {

        AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);

        if (p) {

            program    = p->stream_index;

            nb_streams = p->nb_stream_indexes;

        }

    }

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

        int real_stream_index = program ? program[i] : i;

        AVStream *st          = ic->streams[real_stream_index];

        AVCodecContext *avctx = st->codec;

        if (avctx->codec_type != type)

            continue;

        if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)

            continue;

        if (wanted_stream_nb != real_stream_index &&

            st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED |

                               AV_DISPOSITION_VISUAL_IMPAIRED))

            continue;

        if (type == AVMEDIA_TYPE_AUDIO && !avctx->channels)

            continue;

        if (decoder_ret) {

            decoder = find_decoder(ic, st, st->codec->codec_id);

            if (!decoder) {

                if (ret < 0)

                    ret = AVERROR_DECODER_NOT_FOUND;

                continue;

            }

        }

        count = st->codec_info_nb_frames;

        bitrate = avctx->bit_rate;

        if (!bitrate)

            bitrate = avctx->rc_max_rate;

        multiframe = FFMIN(5, count);

        if ((best_multiframe >  multiframe) ||

            (best_multiframe == multiframe && best_bitrate >  bitrate) ||

            (best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))

            continue;

        best_count   = count;

        best_bitrate = bitrate;

        best_multiframe = multiframe;

        ret          = real_stream_index;

        best_decoder = decoder;

        if (program && i == nb_streams - 1 && ret < 0) {

            program    = NULL;

            nb_streams = ic->nb_streams;

            /* no related stream found, try again with everything */

            i = 0;

        }

    }

    if (decoder_ret)

        *decoder_ret = (AVCodec*)best_decoder;

    return ret;

}


static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)

{

    MpegTSContext *ts = filter->u.section_filter.opaque;

    SectionHeader h1, *h = &h1;

    PESContext *pes;

    AVStream *st;

    const uint8_t *p, *p_end, *desc_list_end, *desc_end;

    int program_info_length, pcr_pid, pid, stream_type;

    int desc_list_len, desc_len, desc_tag;

    int comp_page = 0, anc_page = 0; /* initialize to kill warnings */

    char language[4] = {0}; /* initialize to kill warnings */

#ifdef DEBUG_SI

    av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);

    av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);

#endif

    p_end = section + section_len - 4;

    p = section;

    if (parse_section_header(h, &p, p_end) < 0)

        return;

#ifdef DEBUG_SI

    av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",

           h->id, h->sec_num, h->last_sec_num);

#endif

    if (h->tid != PMT_TID)

        return;

    clear_program(ts, h->id);

    pcr_pid = get16(&p, p_end) & 0x1fff;

    if (pcr_pid < 0)

        return;

    add_pid_to_pmt(ts, h->id, pcr_pid);

#ifdef DEBUG_SI

    av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);

#endif

    program_info_length = get16(&p, p_end) & 0xfff;

    if (program_info_length < 0)

        return;

    p += program_info_length;

    if (p >= p_end)

        return;

    for(;;) {

        language[0] = 0;

        st = 0;

        stream_type = get8(&p, p_end);

        if (stream_type < 0)

            break;

        pid = get16(&p, p_end) & 0x1fff;

        if (pid < 0)

            break;

        desc_list_len = get16(&p, p_end) & 0xfff;

        if (desc_list_len < 0)

            break;

        desc_list_end = p + desc_list_len;

        if (desc_list_end > p_end)

            break;

        for(;;) {

            desc_tag = get8(&p, desc_list_end);

            if (desc_tag < 0)

                break;

            if (stream_type == STREAM_TYPE_PRIVATE_DATA) {

                if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {

                    /*assume DVB AC-3 Audio*/

                    stream_type = STREAM_TYPE_AUDIO_AC3;

                } else if(desc_tag == 0x7B) {

                    /* DVB DTS audio */

                    stream_type = STREAM_TYPE_AUDIO_DTS;

                }

            }

            desc_len = get8(&p, desc_list_end);

            desc_end = p + desc_len;

            if (desc_end > desc_list_end)

                break;

#ifdef DEBUG_SI

            av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",

                   desc_tag, desc_len);

#endif

            switch(desc_tag) {

            case DVB_SUBT_DESCID:

                if (stream_type == STREAM_TYPE_PRIVATE_DATA)

                    stream_type = STREAM_TYPE_SUBTITLE_DVB;

                language[0] = get8(&p, desc_end);

                language[1] = get8(&p, desc_end);

                language[2] = get8(&p, desc_end);

                language[3] = 0;

                get8(&p, desc_end);

                comp_page = get16(&p, desc_end);

                anc_page = get16(&p, desc_end);

                break;

            case 0x0a: /* ISO 639 language descriptor */

                language[0] = get8(&p, desc_end);

                language[1] = get8(&p, desc_end);

                language[2] = get8(&p, desc_end);

                language[3] = 0;

                break;

            default:

                break;

            }

            p = desc_end;

        }

        p = desc_list_end;

#ifdef DEBUG_SI

        av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",

               stream_type, pid);

#endif

        /* now create ffmpeg stream */

        switch(stream_type) {

        case STREAM_TYPE_AUDIO_MPEG1:

        case STREAM_TYPE_AUDIO_MPEG2:

        case STREAM_TYPE_VIDEO_MPEG1:

        case STREAM_TYPE_VIDEO_MPEG2:

        case STREAM_TYPE_VIDEO_MPEG4:

        case STREAM_TYPE_VIDEO_H264:

        case STREAM_TYPE_VIDEO_VC1:

        case STREAM_TYPE_AUDIO_AAC:

        case STREAM_TYPE_AUDIO_AC3:

        case STREAM_TYPE_AUDIO_DTS:

        case STREAM_TYPE_SUBTITLE_DVB:

            if(ts->pids[pid]){

                assert(ts->pids[pid]->type == MPEGTS_PES);

                pes= ts->pids[pid]->u.pes_filter.opaque;

                st= pes->st;

            }else{

                pes = add_pes_stream(ts, pid, pcr_pid, stream_type);

                if (pes)

                    st = new_pes_av_stream(pes, 0);

            }

            add_pid_to_pmt(ts, h->id, pid);

            if(st)

                av_program_add_stream_index(ts->stream, h->id, st->index);

            break;

        default:

            /* we ignore the other streams */

            break;

        }

        if (st) {

            if (language[0] != 0) {

                memcpy(st->language, language, 4);

            }

            if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {

                st->codec->sub_id = (anc_page << 16) | comp_page;

            }

        }

    }

    /* all parameters are there */

    ts->stop_parse++;

    mpegts_close_filter(ts, filter);

}


static inline void RENAME(yuv2yuvX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,

                                    const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize, const int16_t **alpSrc,

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

{

#if COMPILE_TEMPLATE_MMX

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

        if (c->flags & SWS_ACCURATE_RND) {

            if (uDest) {

                YSCALEYUV2YV12X_ACCURATE(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)

                YSCALEYUV2YV12X_ACCURATE(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)

            }

            if (CONFIG_SWSCALE_ALPHA && aDest) {

                YSCALEYUV2YV12X_ACCURATE(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)

            }

            YSCALEYUV2YV12X_ACCURATE("0", LUM_MMX_FILTER_OFFSET, dest, dstW)

        } else {

            if (uDest) {

                YSCALEYUV2YV12X(   "0", CHR_MMX_FILTER_OFFSET, uDest, chrDstW)

                YSCALEYUV2YV12X(AV_STRINGIFY(VOF), CHR_MMX_FILTER_OFFSET, vDest, chrDstW)

            }

            if (CONFIG_SWSCALE_ALPHA && aDest) {

                YSCALEYUV2YV12X(   "0", ALP_MMX_FILTER_OFFSET, aDest, dstW)

            }

            YSCALEYUV2YV12X("0", LUM_MMX_FILTER_OFFSET, dest, dstW)

        }

        return;

    }

#endif

#if COMPILE_TEMPLATE_ALTIVEC

    yuv2yuvX_altivec_real(lumFilter, lumSrc, lumFilterSize,

                          chrFilter, chrSrc, chrFilterSize,

                          dest, uDest, vDest, dstW, chrDstW);

#else //COMPILE_TEMPLATE_ALTIVEC

    yuv2yuvXinC(lumFilter, lumSrc, lumFilterSize,

                chrFilter, chrSrc, chrFilterSize,

                alpSrc, dest, uDest, vDest, aDest, dstW, chrDstW);

#endif //!COMPILE_TEMPLATE_ALTIVEC

}


static int qcow_make_empty(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    uint32_t l1_length = s->l1_size * sizeof(uint64_t);

    int ret;

    memset(s->l1_table, 0, l1_length);

    if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)

	return -1;

    ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);

    if (ret < 0)

        return ret;

    memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));

    memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));

    memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));

    return 0;

}


static inline void vc1_pred_mv_intfr(VC1Context *v, int n, int dmv_x, int dmv_y,

                                     int mvn, int r_x, int r_y, uint8_t* is_intra, int dir)

{

    MpegEncContext *s = &v->s;

    int xy, wrap, off = 0;

    int A[2], B[2], C[2];

    int px, py;

    int a_valid = 0, b_valid = 0, c_valid = 0;

    int field_a, field_b, field_c; // 0: same, 1: opposit

    int total_valid, num_samefield, num_oppfield;

    int pos_c, pos_b, n_adj;

    wrap = s->b8_stride;

    xy = s->block_index[n];

    if (s->mb_intra) {

        s->mv[0][n][0] = s->current_picture.motion_val[0][xy][0] = 0;

        s->mv[0][n][1] = s->current_picture.motion_val[0][xy][1] = 0;

        s->current_picture.motion_val[1][xy][0] = 0;

        s->current_picture.motion_val[1][xy][1] = 0;

        if (mvn == 1) { /* duplicate motion data for 1-MV block */

            s->current_picture.motion_val[0][xy + 1][0]        = 0;

            s->current_picture.motion_val[0][xy + 1][1]        = 0;

            s->current_picture.motion_val[0][xy + wrap][0]     = 0;

            s->current_picture.motion_val[0][xy + wrap][1]     = 0;

            s->current_picture.motion_val[0][xy + wrap + 1][0] = 0;

            s->current_picture.motion_val[0][xy + wrap + 1][1] = 0;

            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;

            s->current_picture.motion_val[1][xy + 1][0]        = 0;

            s->current_picture.motion_val[1][xy + 1][1]        = 0;

            s->current_picture.motion_val[1][xy + wrap][0]     = 0;

            s->current_picture.motion_val[1][xy + wrap][1]     = 0;

            s->current_picture.motion_val[1][xy + wrap + 1][0] = 0;

            s->current_picture.motion_val[1][xy + wrap + 1][1] = 0;

        }

        return;

    }

    off = ((n == 0) || (n == 1)) ? 1 : -1;

    /* predict A */

    if (s->mb_x || (n == 1) || (n == 3)) {

        if ((v->blk_mv_type[xy]) // current block (MB) has a field MV

            || (!v->blk_mv_type[xy] && !v->blk_mv_type[xy - 1])) { // or both have frame MV

            A[0] = s->current_picture.motion_val[dir][xy - 1][0];

            A[1] = s->current_picture.motion_val[dir][xy - 1][1];

            a_valid = 1;

        } else { // current block has frame mv and cand. has field MV (so average)

            A[0] = (s->current_picture.motion_val[dir][xy - 1][0]

                    + s->current_picture.motion_val[dir][xy - 1 + off * wrap][0] + 1) >> 1;

            A[1] = (s->current_picture.motion_val[dir][xy - 1][1]

                    + s->current_picture.motion_val[dir][xy - 1 + off * wrap][1] + 1) >> 1;

            a_valid = 1;

        }

        if (!(n & 1) && v->is_intra[s->mb_x - 1]) {

            a_valid = 0;

            A[0] = A[1] = 0;

        }

    } else

        A[0] = A[1] = 0;

    /* Predict B and C */

    B[0] = B[1] = C[0] = C[1] = 0;

    if (n == 0 || n == 1 || v->blk_mv_type[xy]) {

        if (!s->first_slice_line) {

            if (!v->is_intra[s->mb_x - s->mb_stride]) {

                b_valid = 1;

                n_adj   = n | 2;

                pos_b   = s->block_index[n_adj] - 2 * wrap;

                if (v->blk_mv_type[pos_b] && v->blk_mv_type[xy]) {

                    n_adj = (n & 2) | (n & 1);

                }

                B[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap][0];

                B[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap][1];

                if (v->blk_mv_type[pos_b] && !v->blk_mv_type[xy]) {

                    B[0] = (B[0] + s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap][0] + 1) >> 1;

                    B[1] = (B[1] + s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap][1] + 1) >> 1;

                }

            }

            if (s->mb_width > 1) {

                if (!v->is_intra[s->mb_x - s->mb_stride + 1]) {

                    c_valid = 1;

                    n_adj   = 2;

                    pos_c   = s->block_index[2] - 2 * wrap + 2;

                    if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                        n_adj = n & 2;

                    }

                    C[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap + 2][0];

                    C[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap + 2][1];

                    if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                        C[0] = (1 + C[0] + (s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap + 2][0])) >> 1;

                        C[1] = (1 + C[1] + (s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap + 2][1])) >> 1;

                    }

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

                        if (!v->is_intra[s->mb_x - s->mb_stride - 1]) {

                            c_valid = 1;

                            n_adj   = 3;

                            pos_c   = s->block_index[3] - 2 * wrap - 2;

                            if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                                n_adj = n | 1;

                            }

                            C[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap - 2][0];

                            C[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap - 2][1];

                            if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                                C[0] = (1 + C[0] + s->current_picture.motion_val[dir][s->block_index[1] - 2 * wrap - 2][0]) >> 1;

                                C[1] = (1 + C[1] + s->current_picture.motion_val[dir][s->block_index[1] - 2 * wrap - 2][1]) >> 1;

                            }

                        } else

                            c_valid = 0;

                    }

                }

            }

        }

    } else {

        pos_b   = s->block_index[1];

        b_valid = 1;

        B[0]    = s->current_picture.motion_val[dir][pos_b][0];

        B[1]    = s->current_picture.motion_val[dir][pos_b][1];

        pos_c   = s->block_index[0];

        c_valid = 1;

        C[0]    = s->current_picture.motion_val[dir][pos_c][0];

        C[1]    = s->current_picture.motion_val[dir][pos_c][1];

    }

    total_valid = a_valid + b_valid + c_valid;

    // check if predictor A is out of bounds

    if (!s->mb_x && !(n == 1 || n == 3)) {

        A[0] = A[1] = 0;

    }

    // check if predictor B is out of bounds

    if ((s->first_slice_line && v->blk_mv_type[xy]) || (s->first_slice_line && !(n & 2))) {

        B[0] = B[1] = C[0] = C[1] = 0;

    }

    if (!v->blk_mv_type[xy]) {

        if (s->mb_width == 1) {

            px = B[0];

            py = B[1];

        } else {

            if (total_valid >= 2) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (total_valid) {

                if      (a_valid) { px = A[0]; py = A[1]; }

                else if (b_valid) { px = B[0]; py = B[1]; }

                else if (c_valid) { px = C[0]; py = C[1]; }

                else av_assert2(0);

            } else

                px = py = 0;

        }

    } else {

        if (a_valid)

            field_a = (A[1] & 4) ? 1 : 0;

        else

            field_a = 0;

        if (b_valid)

            field_b = (B[1] & 4) ? 1 : 0;

        else

            field_b = 0;

        if (c_valid)

            field_c = (C[1] & 4) ? 1 : 0;

        else

            field_c = 0;

        num_oppfield  = field_a + field_b + field_c;

        num_samefield = total_valid - num_oppfield;

        if (total_valid == 3) {

            if ((num_samefield == 3) || (num_oppfield == 3)) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (num_samefield >= num_oppfield) {

                /* take one MV from same field set depending on priority

                the check for B may not be necessary */

                px = !field_a ? A[0] : B[0];

                py = !field_a ? A[1] : B[1];

            } else {

                px =  field_a ? A[0] : B[0];

                py =  field_a ? A[1] : B[1];

            }

        } else if (total_valid == 2) {

            if (num_samefield >= num_oppfield) {

                if (!field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (!field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                } else px = py = 0;

            } else {

                if (field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                } else px = py = 0;

            }

        } else if (total_valid == 1) {

            px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);

            py = (a_valid) ? A[1] : ((b_valid) ? B[1] : C[1]);

        } else

            px = py = 0;

    }

    /* store MV using signed modulus of MV range defined in 4.11 */

    s->mv[dir][n][0] = s->current_picture.motion_val[dir][xy][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;

    s->mv[dir][n][1] = s->current_picture.motion_val[dir][xy][1] = ((py + dmv_y + r_y) & ((r_y << 1) - 1)) - r_y;

    if (mvn == 1) { /* duplicate motion data for 1-MV block */

        s->current_picture.motion_val[dir][xy +    1    ][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy +    1    ][1] = s->current_picture.motion_val[dir][xy][1];

        s->current_picture.motion_val[dir][xy + wrap    ][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + wrap    ][1] = s->current_picture.motion_val[dir][xy][1];

        s->current_picture.motion_val[dir][xy + wrap + 1][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + wrap + 1][1] = s->current_picture.motion_val[dir][xy][1];

    } else if (mvn == 2) { /* duplicate motion data for 2-Field MV block */

        s->current_picture.motion_val[dir][xy + 1][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + 1][1] = s->current_picture.motion_val[dir][xy][1];

        s->mv[dir][n + 1][0] = s->mv[dir][n][0];

        s->mv[dir][n + 1][1] = s->mv[dir][n][1];

    }

}


void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp)

{

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char tmp_filename[PATH_MAX + 1];

    int64_t total_size;

    BlockDriver *bdrv_qcow2;

    QEMUOptionParameter *create_options;

    QDict *snapshot_options;

    BlockDriverState *bs_snapshot;

    Error *local_err;

    int ret;

    /* if snapshot, we create a temporary backing file and open it

       instead of opening 'filename' directly */

    /* Get the required size from the image */

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        error_setg_errno(errp, -total_size, "Could not get image size");

        return;

    }

    total_size &= BDRV_SECTOR_MASK;

    /* Create the temporary image */

    ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not get temporary filename");

        return;

    }

    bdrv_qcow2 = bdrv_find_format("qcow2");

    create_options = parse_option_parameters("", bdrv_qcow2->create_options,

                                             NULL);

    set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);

    ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);

    free_option_parameters(create_options);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not create temporary overlay "

                         "'%s': %s", tmp_filename,

                         error_get_pretty(local_err));

        error_free(local_err);

        return;

    }

    /* Prepare a new options QDict for the temporary file */

    snapshot_options = qdict_new();

    qdict_put(snapshot_options, "file.driver",

              qstring_from_str("file"));

    qdict_put(snapshot_options, "file.filename",

              qstring_from_str(tmp_filename));

    bs_snapshot = bdrv_new("", &error_abort);

    bs_snapshot->is_temporary = 1;

    ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,

                    bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return;

    }

    bdrv_append(bs_snapshot, bs);

}


int nbd_client_co_flush(BlockDriverState *bs)

{

    NBDClientSession *client = nbd_get_client_session(bs);

    NBDRequest request = { .type = NBD_CMD_FLUSH };

    NBDReply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_FLUSH)) {

        return 0;

    }

    request.from = 0;

    request.len = 0;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(bs, &request, NULL);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL);

    }

    nbd_coroutine_end(bs, &request);

    return -reply.error;

}


int do_sigaction(int sig, const struct target_sigaction *act,

                 struct target_sigaction *oact)

{

    struct emulated_sigaction *k;

    if (sig < 1 || sig > TARGET_NSIG)

        return -EINVAL;

    k = &sigact_table[sig - 1];

#if defined(DEBUG_SIGNAL) && 0

    fprintf(stderr, "sigaction sig=%d act=0x%08x, oact=0x%08x\n",

            sig, (int)act, (int)oact);

#endif

    if (oact) {

        oact->_sa_handler = tswapl(k->sa._sa_handler);

        oact->sa_flags = tswapl(k->sa.sa_flags);

        oact->sa_restorer = tswapl(k->sa.sa_restorer);

        oact->sa_mask = k->sa.sa_mask;

    }

    if (act) {

        k->sa._sa_handler = tswapl(act->_sa_handler);

        k->sa.sa_flags = tswapl(act->sa_flags);

        k->sa.sa_restorer = tswapl(act->sa_restorer);

        k->sa.sa_mask = act->sa_mask;

    }

    return 0;

}


DeviceState *qdev_try_create(BusState *bus, const char *name)

{

    DeviceState *dev;

    dev = DEVICE(object_new(name));

    if (!dev) {

    if (!bus) {

        bus = sysbus_get_default();

    qdev_set_parent_bus(dev, bus);

    qdev_prop_set_globals(dev);

    return dev;


const AVOption *av_set_string(void *obj, const char *name, const char *val){

    const AVOption *o= av_find_opt(obj, name, NULL, 0, 0);

    if(o && o->offset==0 && o->type == FF_OPT_TYPE_CONST && o->unit){

        return set_all_opt(obj, o->unit, o->default_val);

    }

    if(!o || !val || o->offset<=0)

        return NULL;

    if(o->type != FF_OPT_TYPE_STRING){

        for(;;){

            int i;

            char buf[256];

            int cmd=0;

            double d;

            char *error = NULL;

            if(*val == '+' || *val == '-')

                cmd= *(val++);

            for(i=0; i<sizeof(buf)-1 && val[i] && val[i]!='+' && val[i]!='-'; i++)

                buf[i]= val[i];

            buf[i]=0;

            val+= i;

            d = ff_eval2(buf, const_values, const_names, NULL, NULL, NULL, NULL, NULL, &error);

            if(isnan(d)) {

                const AVOption *o_named= av_find_opt(obj, buf, o->unit, 0, 0);

                if(o_named && o_named->type == FF_OPT_TYPE_CONST)

                    d= o_named->default_val;

                else if(!strcmp(buf, "default")) d= o->default_val;

                else if(!strcmp(buf, "max"    )) d= o->max;

                else if(!strcmp(buf, "min"    )) d= o->min;

                else if(!strcmp(buf, "none"   )) d= 0;

                else if(!strcmp(buf, "all"    )) d= ~0;

                else {

                    if (!error)

                        av_log(NULL, AV_LOG_ERROR, "Unable to parse option value \"%s\": %s\n", val, error);

                    return NULL;

                }

            }

            if(o->type == FF_OPT_TYPE_FLAGS){

                if     (cmd=='+') d= av_get_int(obj, name, NULL) | (int64_t)d;

                else if(cmd=='-') d= av_get_int(obj, name, NULL) &~(int64_t)d;

            }else if(cmd=='-')

                d= -d;

            av_set_number(obj, name, d, 1, 1);

            if(!*val)

                return o;

        }

        return NULL;

    }

    memcpy(((uint8_t*)obj) + o->offset, val, sizeof(val));

    return o;

}


int ff_h2645_extract_rbsp(const uint8_t *src, int length,

                          H2645NAL *nal, int small_padding)

{

    int i, si, di;

    uint8_t *dst;

    int64_t padding = small_padding ? AV_INPUT_BUFFER_PADDING_SIZE : MAX_MBPAIR_SIZE;

    nal->skipped_bytes = 0;

#define STARTCODE_TEST                                                  \

        if (i + 2 < length && src[i + 1] == 0 && src[i + 2] <= 3) {     \

            if (src[i + 2] != 3 && src[i + 2] != 0) {                   \

                /* startcode, so we must be past the end */             \

                length = i;                                             \

            }                                                           \

            break;                                                      \

        }

#if HAVE_FAST_UNALIGNED

#define FIND_FIRST_ZERO                                                 \

        if (i > 0 && !src[i])                                           \

            i--;                                                        \

        while (src[i])                                                  \

            i++

#if HAVE_FAST_64BIT

    for (i = 0; i + 1 < length; i += 9) {

        if (!((~AV_RN64A(src + i) &

               (AV_RN64A(src + i) - 0x0100010001000101ULL)) &

              0x8000800080008080ULL))

            continue;

        FIND_FIRST_ZERO;

        STARTCODE_TEST;

        i -= 7;

    }

#else

    for (i = 0; i + 1 < length; i += 5) {

        if (!((~AV_RN32A(src + i) &

               (AV_RN32A(src + i) - 0x01000101U)) &

              0x80008080U))

            continue;

        FIND_FIRST_ZERO;

        STARTCODE_TEST;

        i -= 3;

    }

#endif /* HAVE_FAST_64BIT */

#else

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

        if (src[i])

            continue;

        if (i > 0 && src[i - 1] == 0)

            i--;

        STARTCODE_TEST;

    }

#endif /* HAVE_FAST_UNALIGNED */

    if (i >= length - 1 && small_padding) { // no escaped 0

        nal->data     =

        nal->raw_data = src;

        nal->size     =

        nal->raw_size = length;

        return length;

    }

    av_fast_malloc(&nal->rbsp_buffer, &nal->rbsp_buffer_size,

                   length + padding);

    if (!nal->rbsp_buffer)

        return AVERROR(ENOMEM);

    dst = nal->rbsp_buffer;

    memcpy(dst, src, i);

    si = di = i;

    while (si + 2 < length) {

        // remove escapes (very rare 1:2^22)

        if (src[si + 2] > 3) {

            dst[di++] = src[si++];

            dst[di++] = src[si++];

        } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) {

            if (src[si + 2] == 3) { // escape

                dst[di++] = 0;

                dst[di++] = 0;

                si       += 3;

                if (nal->skipped_bytes_pos) {

                    nal->skipped_bytes++;

                    if (nal->skipped_bytes_pos_size < nal->skipped_bytes) {

                        nal->skipped_bytes_pos_size *= 2;

                        av_assert0(nal->skipped_bytes_pos_size >= nal->skipped_bytes);

                        av_reallocp_array(&nal->skipped_bytes_pos,

                                nal->skipped_bytes_pos_size,

                                sizeof(*nal->skipped_bytes_pos));

                        if (!nal->skipped_bytes_pos) {

                            nal->skipped_bytes_pos_size = 0;

                            return AVERROR(ENOMEM);

                        }

                    }

                    if (nal->skipped_bytes_pos)

                        nal->skipped_bytes_pos[nal->skipped_bytes-1] = di - 1;

                }

                continue;

            } else // next start code

                goto nsc;

        }

        dst[di++] = src[si++];

    }

    while (si < length)

        dst[di++] = src[si++];

nsc:

    memset(dst + di, 0, AV_INPUT_BUFFER_PADDING_SIZE);

    nal->data = dst;

    nal->size = di;

    nal->raw_data = src;

    nal->raw_size = si;

    return si;

}


static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,

                           BdrvCheckMode fix, bool *rebuild,

                           uint16_t **refcount_table, int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i, size;

    int ret;

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset_into_cluster(s, offset)) {

            fprintf(stderr, "ERROR refcount block %" PRId64 " is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            *rebuild = true;

            continue;

        }

        if (cluster >= *nb_clusters) {

            fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",

                    fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);

            if (fix & BDRV_FIX_ERRORS) {

                int64_t new_nb_clusters;

                if (offset > INT64_MAX - s->cluster_size) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                ret = bdrv_truncate(bs->file, offset + s->cluster_size);

                if (ret < 0) {

                    goto resize_fail;

                }

                size = bdrv_getlength(bs->file);

                if (size < 0) {

                    ret = size;

                    goto resize_fail;

                }

                new_nb_clusters = size_to_clusters(s, size);

                assert(new_nb_clusters >= *nb_clusters);

                ret = realloc_refcount_array(s, refcount_table,

                                             nb_clusters, new_nb_clusters);

                if (ret < 0) {

                    res->check_errors++;

                    return ret;

                }

                if (cluster >= *nb_clusters) {

                    ret = -EINVAL;

                    goto resize_fail;

                }

                res->corruptions_fixed++;

                ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                                    offset, s->cluster_size);

                if (ret < 0) {

                    return ret;

                }

                /* No need to check whether the refcount is now greater than 1:

                 * This area was just allocated and zeroed, so it can only be

                 * exactly 1 after inc_refcounts() */

                continue;

resize_fail:

                res->corruptions++;

                *rebuild = true;

                fprintf(stderr, "ERROR could not resize image: %s\n",

                        strerror(-ret));

            } else {

                res->corruptions++;

            }

            continue;

        }

        if (offset != 0) {

            ret = inc_refcounts(bs, res, refcount_table, nb_clusters,

                                offset, s->cluster_size);

            if (ret < 0) {

                return ret;

            }

            if ((*refcount_table)[cluster] != 1) {

                fprintf(stderr, "ERROR refcount block %" PRId64

                        " refcount=%d\n", i, (*refcount_table)[cluster]);

                res->corruptions++;

                *rebuild = true;

            }

        }

    }

    return 0;

}


static void choose_pixel_fmt(AVStream *st, AVCodec *codec)

{

    if(codec && codec->pix_fmts){

        const enum PixelFormat *p= codec->pix_fmts;

        if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){

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

                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};

            }else if(st->codec->codec_id==CODEC_ID_LJPEG){

                p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};

            }

        }

        for(; *p!=-1; p++){

            if(*p == st->codec->pix_fmt)

                break;

        }

        if (*p == -1) {

            av_log(NULL, AV_LOG_WARNING,

                   "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",

                   av_pix_fmt_descriptors[st->codec->pix_fmt].name,

                   codec->name,

                   av_pix_fmt_descriptors[codec->pix_fmts[0]].name);

            st->codec->pix_fmt = codec->pix_fmts[0];

        }

    }

}


static void virtio_gpu_reset(VirtIODevice *vdev)

{

    VirtIOGPU *g = VIRTIO_GPU(vdev);

    struct virtio_gpu_simple_resource *res, *tmp;

    int i;

    g->enable = 0;

    QTAILQ_FOREACH_SAFE(res, &g->reslist, next, tmp) {

        virtio_gpu_resource_destroy(g, res);

    }

    for (i = 0; i < g->conf.max_outputs; i++) {

#if 0

        g->req_state[i].x = 0;

        g->req_state[i].y = 0;

        if (i == 0) {

            g->req_state[0].width = 1024;

            g->req_state[0].height = 768;

        } else {

            g->req_state[i].width = 0;

            g->req_state[i].height = 0;

        }

#endif

        g->scanout[i].resource_id = 0;

        g->scanout[i].width = 0;

        g->scanout[i].height = 0;

        g->scanout[i].x = 0;

        g->scanout[i].y = 0;

        g->scanout[i].ds = NULL;

    }

    g->enabled_output_bitmask = 1;

#ifdef CONFIG_VIRGL

    if (g->use_virgl_renderer) {

        virtio_gpu_virgl_reset(g);

        g->use_virgl_renderer = 0;

    }

#endif

}


static void gen_divu(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)

{

    TCGv sr_cy = tcg_temp_new();

    TCGv t0 = tcg_temp_new();

    tcg_gen_setcondi_tl(TCG_COND_EQ, sr_cy, srcb, 0);

    /* The result of divide-by-zero is undefined.

       Supress the host-side exception by dividing by 1.  */

    tcg_gen_or_tl(t0, srcb, sr_cy);

    tcg_gen_divu_tl(dest, srca, t0);

    tcg_temp_free(t0);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_cy, ctz32(SR_CY), 1);

    gen_ove_cy(dc, sr_cy);

    tcg_temp_free(sr_cy);

}


av_cold int vp56_free(AVCodecContext *avctx)
{
    VP56Context *s = avctx->priv_data;
    int pt;
    av_freep(&s->qscale_table);
    av_freep(&s->above_blocks);
    av_freep(&s->macroblocks);
    av_freep(&s->edge_emu_buffer_alloc);
    if (s->framep[VP56_FRAME_GOLDEN]->data[0])
        avctx->release_buffer(avctx, s->framep[VP56_FRAME_GOLDEN]);
    if (s->framep[VP56_FRAME_GOLDEN2]->data[0])
        avctx->release_buffer(avctx, s->framep[VP56_FRAME_GOLDEN2]);
    if (s->framep[VP56_FRAME_PREVIOUS]->data[0])
        avctx->release_buffer(avctx, s->framep[VP56_FRAME_PREVIOUS]);
    return 0;


static void decode_block_params(DiracContext *s, DiracArith arith[8], DiracBlock *block,

                                int stride, int x, int y)

{

    int i;

    block->ref  = pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF1);

    block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF1);

    if (s->num_refs == 2) {

        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_REF2);

        block->ref ^= dirac_get_arith_bit(arith, CTX_PMODE_REF2) << 1;

    }

    if (!block->ref) {

        pred_block_dc(block, stride, x, y);

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

            block->u.dc[i] += dirac_get_arith_int(arith+1+i, CTX_DC_F1, CTX_DC_DATA);

        return;

    }

    if (s->globalmc_flag) {

        block->ref |= pred_block_mode(block, stride, x, y, DIRAC_REF_MASK_GLOBAL);

        block->ref ^= dirac_get_arith_bit(arith, CTX_GLOBAL_BLOCK) << 2;

    }

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

        if (block->ref & (i+1)) {

            if (block->ref & DIRAC_REF_MASK_GLOBAL) {

                global_mv(s, block, x, y, i);

            } else {

                pred_mv(block, stride, x, y, i);

                block->u.mv[i][0] += dirac_get_arith_int(arith + 4 + 2 * i, CTX_MV_F1, CTX_MV_DATA);

                block->u.mv[i][1] += dirac_get_arith_int(arith + 5 + 2 * i, CTX_MV_F1, CTX_MV_DATA);

            }

        }

}


static void adb_mouse_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    ADBDeviceClass *adc = ADB_DEVICE_CLASS(oc);

    ADBMouseClass *amc = ADB_MOUSE_CLASS(oc);

    amc->parent_realize = dc->realize;

    dc->realize = adb_mouse_realizefn;

    set_bit(DEVICE_CATEGORY_INPUT, dc->categories);

    adc->devreq = adb_mouse_request;

    dc->reset = adb_mouse_reset;

    dc->vmsd = &vmstate_adb_mouse;

}


static int do_sd_create(char *filename, int64_t vdi_size,

                        uint32_t base_vid, uint32_t *vdi_id, int snapshot,

                        const char *addr, const char *port)

{

    SheepdogVdiReq hdr;

    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;

    int fd, ret;

    unsigned int wlen, rlen = 0;

    char buf[SD_MAX_VDI_LEN];

    fd = connect_to_sdog(addr, port);

    if (fd < 0) {

        return fd;

    }

    memset(buf, 0, sizeof(buf));

    strncpy(buf, filename, SD_MAX_VDI_LEN);

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

    hdr.opcode = SD_OP_NEW_VDI;

    hdr.base_vdi_id = base_vid;

    wlen = SD_MAX_VDI_LEN;

    hdr.flags = SD_FLAG_CMD_WRITE;

    hdr.snapid = snapshot;

    hdr.data_length = wlen;

    hdr.vdi_size = vdi_size;

    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);

    closesocket(fd);

    if (ret) {

        return ret;

    }

    if (rsp->result != SD_RES_SUCCESS) {

        error_report("%s, %s", sd_strerror(rsp->result), filename);

        return -EIO;

    }

    if (vdi_id) {

        *vdi_id = rsp->vdi_id;

    }

    return 0;

}


int ff_rv34_decode_frame(AVCodecContext *avctx,
                            void *data, int *got_picture_ptr,
                            AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    RV34DecContext *r = avctx->priv_data;
    MpegEncContext *s = &r->s;
    AVFrame *pict = data;
    SliceInfo si;
    int i;
    int slice_count;
    const uint8_t *slices_hdr = NULL;
    int last = 0;
    /* no supplementary picture */
    if (buf_size == 0) {
        /* special case for last picture */
        if (s->low_delay==0 && s->next_picture_ptr) {
            *pict = s->next_picture_ptr->f;
            s->next_picture_ptr = NULL;
            *got_picture_ptr = 1;
        }
        return 0;
    }
    if(!avctx->slice_count){
        slice_count = (*buf++) + 1;
        slices_hdr = buf + 4;
        buf += 8 * slice_count;
        buf_size -= 1 + 8 * slice_count;
    }else
        slice_count = avctx->slice_count;
    //parse first slice header to check whether this frame can be decoded
    if(get_slice_offset(avctx, slices_hdr, 0) < 0 ||
       get_slice_offset(avctx, slices_hdr, 0) > buf_size){
        av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");
    }
    init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), (buf_size-get_slice_offset(avctx, slices_hdr, 0))*8);
    if(r->parse_slice_header(r, &r->s.gb, &si) < 0 || si.start){
        av_log(avctx, AV_LOG_ERROR, "First slice header is incorrect\n");
    }
    if ((!s->last_picture_ptr || !s->last_picture_ptr->f.data[0]) &&
        si.type == AV_PICTURE_TYPE_B) {
        av_log(avctx, AV_LOG_ERROR, "Invalid decoder state: B-frame without "
               "reference data.\n");
    }
    if(   (avctx->skip_frame >= AVDISCARD_NONREF && si.type==AV_PICTURE_TYPE_B)
       || (avctx->skip_frame >= AVDISCARD_NONKEY && si.type!=AV_PICTURE_TYPE_I)
       ||  avctx->skip_frame >= AVDISCARD_ALL)
        return avpkt->size;
    /* first slice */
    if (si.start == 0) {
        if (s->mb_num_left > 0) {
            av_log(avctx, AV_LOG_ERROR, "New frame but still %d MB left.\n",
                   s->mb_num_left);
            ff_er_frame_end(s);
            ff_MPV_frame_end(s);
        }
        if (s->width != si.width || s->height != si.height) {
            int err;
            av_log(s->avctx, AV_LOG_WARNING, "Changing dimensions to %dx%d\n",
                   si.width, si.height);
            s->width  = si.width;
            s->height = si.height;
            avcodec_set_dimensions(s->avctx, s->width, s->height);
            if ((err = ff_MPV_common_frame_size_change(s)) < 0)
                return err;
            if ((err = rv34_decoder_realloc(r)) < 0)
                return err;
        }
        s->pict_type = si.type ? si.type : AV_PICTURE_TYPE_I;
        if (ff_MPV_frame_start(s, s->avctx) < 0)
            return -1;
        ff_er_frame_start(s);
        if (!r->tmp_b_block_base) {
            int i;
            r->tmp_b_block_base = av_malloc(s->linesize * 48);
            for (i = 0; i < 2; i++)
                r->tmp_b_block_y[i] = r->tmp_b_block_base
                                      + i * 16 * s->linesize;
            for (i = 0; i < 4; i++)
                r->tmp_b_block_uv[i] = r->tmp_b_block_base + 32 * s->linesize
                                       + (i >> 1) * 8 * s->uvlinesize
                                       + (i &  1) * 16;
        }
        r->cur_pts = si.pts;
        if (s->pict_type != AV_PICTURE_TYPE_B) {
            r->last_pts = r->next_pts;
            r->next_pts = r->cur_pts;
        } else {
            int refdist = GET_PTS_DIFF(r->next_pts, r->last_pts);
            int dist0   = GET_PTS_DIFF(r->cur_pts,  r->last_pts);
            int dist1   = GET_PTS_DIFF(r->next_pts, r->cur_pts);
            if(!refdist){
                r->mv_weight1 = r->mv_weight2 = r->weight1 = r->weight2 = 8192;
                r->scaled_weight = 0;
            }else{
                r->mv_weight1 = (dist0 << 14) / refdist;
                r->mv_weight2 = (dist1 << 14) / refdist;
                if((r->mv_weight1|r->mv_weight2) & 511){
                    r->weight1 = r->mv_weight1;
                    r->weight2 = r->mv_weight2;
                    r->scaled_weight = 0;
                }else{
                    r->weight1 = r->mv_weight1 >> 9;
                    r->weight2 = r->mv_weight2 >> 9;
                    r->scaled_weight = 1;
                }
            }
        }
        s->mb_x = s->mb_y = 0;
        ff_thread_finish_setup(s->avctx);
    } else if (HAVE_THREADS &&
               (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
        av_log(s->avctx, AV_LOG_ERROR, "Decoder needs full frames in frame "
               "multithreading mode (start MB is %d).\n", si.start);
    }
    for(i = 0; i < slice_count; i++){
        int offset = get_slice_offset(avctx, slices_hdr, i);
        int size;
        if(i+1 == slice_count)
            size = buf_size - offset;
        else
            size = get_slice_offset(avctx, slices_hdr, i+1) - offset;
        if(offset < 0 || offset > buf_size){
            av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");
            break;
        }
        r->si.end = s->mb_width * s->mb_height;
        s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;
        if(i+1 < slice_count){
            if (get_slice_offset(avctx, slices_hdr, i+1) < 0 ||
                get_slice_offset(avctx, slices_hdr, i+1) > buf_size) {
                av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");
                break;
            }
            init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, i+1), (buf_size-get_slice_offset(avctx, slices_hdr, i+1))*8);
            if(r->parse_slice_header(r, &r->s.gb, &si) < 0){
                if(i+2 < slice_count)
                    size = get_slice_offset(avctx, slices_hdr, i+2) - offset;
                else
                    size = buf_size - offset;
            }else
                r->si.end = si.start;
        }
        if (size < 0 || size > buf_size - offset) {
            av_log(avctx, AV_LOG_ERROR, "Slice size is invalid\n");
            break;
        }
        last = rv34_decode_slice(r, r->si.end, buf + offset, size);
        if(last)
            break;
    }
    if (s->current_picture_ptr) {
        if (last) {
            if(r->loop_filter)
                r->loop_filter(r, s->mb_height - 1);
            *got_picture_ptr = finish_frame(avctx, pict);
        } else if (HAVE_THREADS &&
                   (s->avctx->active_thread_type & FF_THREAD_FRAME)) {
            av_log(avctx, AV_LOG_INFO, "marking unfished frame as finished\n");
            /* always mark the current frame as finished, frame-mt supports
             * only complete frames */
            ff_er_frame_end(s);
            ff_MPV_frame_end(s);
            s->mb_num_left = 0;
            ff_thread_report_progress(&s->current_picture_ptr->f, INT_MAX, 0);
        }
    }
    return avpkt->size;
}


static int flic_decode_frame_15_16BPP(AVCodecContext *avctx,

                                      void *data, int *got_frame,

                                      const uint8_t *buf, int buf_size)

{

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

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

    FlicDecodeContext *s = avctx->priv_data;

    GetByteContext g2;

    int pixel_ptr;

    unsigned char palette_idx1;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j, ret;

    int lines;

    int compressed_lines;

    signed short line_packets;

    int y_ptr;

    int byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    int pixel;

    unsigned int pixel_limit;

    bytestream2_init(&g2, buf, buf_size);

    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)

        return ret;

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

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

    frame_size = bytestream2_get_le32(&g2);

    bytestream2_skip(&g2, 2);  /* skip the magic number */

    num_chunks = bytestream2_get_le16(&g2);

    bytestream2_skip(&g2, 8);  /* skip padding */

    if (frame_size > buf_size)

        frame_size = buf_size;

    frame_size -= 16;

    /* iterate through the chunks */

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

            bytestream2_get_bytes_left(&g2) >= 4) {

        int stream_ptr_after_chunk;

        chunk_size = bytestream2_get_le32(&g2);

        if (chunk_size > frame_size) {

            av_log(avctx, AV_LOG_WARNING,

                   "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size);

            chunk_size = frame_size;

        }

        stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size;

        chunk_type = bytestream2_get_le16(&g2);

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

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

             * include one of these chunks in their first frame.

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

            ff_dlog(avctx,

                    "Unexpected Palette chunk %d in non-palettized FLC\n",

                    chunk_type);

            bytestream2_skip(&g2, chunk_size - 6);

            break;

        case FLI_DELTA:

        case FLI_DTA_LC:

            y_ptr = 0;

            compressed_lines = bytestream2_get_le16(&g2);

            while (compressed_lines > 0) {

                if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                    break;

                line_packets = bytestream2_get_le16(&g2);

                if (line_packets < 0) {

                    line_packets = -line_packets;

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

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    CHECK_PIXEL_PTR(0);

                    pixel_countdown = s->avctx->width;

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

                        /* account for the skip bytes */

                        if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                            break;

                        pixel_skip = bytestream2_get_byte(&g2);

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

                        pixel_countdown -= pixel_skip;

                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            pixel    = bytestream2_get_le16(&g2);

                            CHECK_PIXEL_PTR(2 * byte_run);

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

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

                                pixel_ptr += 2;

                            }

                        } else {

                            if (bytestream2_tell(&g2) + 2*byte_run > stream_ptr_after_chunk)

                                break;

                            CHECK_PIXEL_PTR(2 * byte_run);

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

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

                                pixel_ptr += 2;

                            }

                        }

                    }

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

                }

            }

            break;

        case FLI_LC:

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

            bytestream2_skip(&g2, chunk_size - 6);

            break;

        case FLI_BLACK:

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

            memset(pixels, 0x0000,

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

            break;

        case FLI_BRUN:

            y_ptr = 0;

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

                pixel_ptr = y_ptr;

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

                 * pixels on a row */

                bytestream2_skip(&g2, 1);

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

                while (pixel_countdown > 0) {

                    if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                        break;

                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                    if (byte_run > 0) {

                        palette_idx1 = bytestream2_get_byte(&g2);

                        CHECK_PIXEL_PTR(byte_run);

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

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

                                       pixel_countdown, lines);

                        }

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

                        byte_run = -byte_run;

                        if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)

                            break;

                        CHECK_PIXEL_PTR(byte_run);

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

                            palette_idx1 = bytestream2_get_byte(&g2);

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

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

                                       pixel_countdown, lines);

                        }

                    }

                }

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

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

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

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

                 */

#if HAVE_BIGENDIAN

                pixel_ptr = y_ptr;

                pixel_countdown = s->avctx->width;

                while (pixel_countdown > 0) {

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

                    pixel_ptr += 2;

                }

#endif

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

            }

            break;

        case FLI_DTA_BRUN:

            y_ptr = 0;

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

                pixel_ptr = y_ptr;

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

                 * pixels on a row */

                bytestream2_skip(&g2, 1);

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

                while (pixel_countdown > 0) {

                    if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                        break;

                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                    if (byte_run > 0) {

                        pixel    = bytestream2_get_le16(&g2);

                        CHECK_PIXEL_PTR(2 * byte_run);

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

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

                            pixel_ptr += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

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

                                       pixel_countdown);

                        }

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

                        byte_run = -byte_run;

                        if (bytestream2_tell(&g2) + 2 * byte_run > stream_ptr_after_chunk)

                            break;

                        CHECK_PIXEL_PTR(2 * byte_run);

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

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

                            pixel_ptr  += 2;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

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

                                       pixel_countdown);

                        }

                    }

                }

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

            }

            break;

        case FLI_COPY:

        case FLI_DTA_COPY:

            /* copy the chunk (uncompressed frame) */

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

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

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

                bytestream2_skip(&g2, chunk_size - 6);

            } else {

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

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

                    pixel_countdown = s->avctx->width;

                    pixel_ptr = 0;

                    while (pixel_countdown > 0) {

                      *((signed short*)(&pixels[y_ptr + pixel_ptr])) = bytestream2_get_le16(&g2);

                      pixel_ptr += 2;

                      pixel_countdown--;

                    }

                    if (s->avctx->width & 1)

                        bytestream2_skip(&g2, 2);

                }

            }

            break;

        case FLI_MINI:

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

            bytestream2_skip(&g2, chunk_size - 6);

            break;

        default:

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

            break;

        }

        if (stream_ptr_after_chunk - bytestream2_tell(&g2) >= 0) {

            bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2));

        } else {

            av_log(avctx, AV_LOG_ERROR, "Chunk overread\n");

            break;

        }

        frame_size -= chunk_size;

        num_chunks--;

    }

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

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

    if ((bytestream2_get_bytes_left(&g2) != 0) && (bytestream2_get_bytes_left(&g2) != 1))

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

               "and final chunk ptr = %d\n", buf_size, bytestream2_tell(&g2));

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

        return ret;

    *got_frame = 1;

    return buf_size;

}


void gen_intermediate_code(CPUState *cs, TranslationBlock * tb)

{

    CPUSPARCState *env = cs->env_ptr;

    target_ulong pc_start, last_pc;

    DisasContext dc1, *dc = &dc1;

    int num_insns;

    int max_insns;

    unsigned int insn;

    memset(dc, 0, sizeof(DisasContext));

    dc->tb = tb;

    pc_start = tb->pc;

    dc->pc = pc_start;

    last_pc = dc->pc;

    dc->npc = (target_ulong) tb->cs_base;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->mem_idx = tb->flags & TB_FLAG_MMU_MASK;

    dc->def = &env->def;

    dc->fpu_enabled = tb_fpu_enabled(tb->flags);

    dc->address_mask_32bit = tb_am_enabled(tb->flags);

    dc->singlestep = (cs->singlestep_enabled || singlestep);

#ifndef CONFIG_USER_ONLY

    dc->supervisor = (tb->flags & TB_FLAG_SUPER) != 0;

#endif

#ifdef TARGET_SPARC64

    dc->fprs_dirty = 0;

    dc->asi = (tb->flags >> TB_FLAG_ASI_SHIFT) & 0xff;

#ifndef CONFIG_USER_ONLY

    dc->hypervisor = (tb->flags & TB_FLAG_HYPER) != 0;

#endif

#endif

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    if (max_insns > TCG_MAX_INSNS) {

        max_insns = TCG_MAX_INSNS;

    }

    gen_tb_start(tb);

    do {

        if (dc->npc & JUMP_PC) {

            assert(dc->jump_pc[1] == dc->pc + 4);

            tcg_gen_insn_start(dc->pc, dc->jump_pc[0] | JUMP_PC);

        } else {

            tcg_gen_insn_start(dc->pc, dc->npc);

        }

        num_insns++;

        last_pc = dc->pc;

        if (unlikely(cpu_breakpoint_test(cs, dc->pc, BP_ANY))) {

            if (dc->pc != pc_start) {

                save_state(dc);

            }

            gen_helper_debug(cpu_env);

            tcg_gen_exit_tb(0);

            dc->is_br = 1;

            goto exit_gen_loop;

        }

        if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        insn = cpu_ldl_code(env, dc->pc);

        disas_sparc_insn(dc, insn);

        if (dc->is_br)

            break;

        /* if the next PC is different, we abort now */

        if (dc->pc != (last_pc + 4))

            break;

        /* if we reach a page boundary, we stop generation so that the

           PC of a TT_TFAULT exception is always in the right page */

        if ((dc->pc & (TARGET_PAGE_SIZE - 1)) == 0)

            break;

        /* if single step mode, we generate only one instruction and

           generate an exception */

        if (dc->singlestep) {

            break;

        }

    } while (!tcg_op_buf_full() &&

             (dc->pc - pc_start) < (TARGET_PAGE_SIZE - 32) &&

             num_insns < max_insns);

 exit_gen_loop:

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (!dc->is_br) {

        if (dc->pc != DYNAMIC_PC &&

            (dc->npc != DYNAMIC_PC && dc->npc != JUMP_PC)) {

            /* static PC and NPC: we can use direct chaining */

            gen_goto_tb(dc, 0, dc->pc, dc->npc);

        } else {

            if (dc->pc != DYNAMIC_PC) {

                tcg_gen_movi_tl(cpu_pc, dc->pc);

            }

            save_npc(dc);

            tcg_gen_exit_tb(0);

        }

    }

    gen_tb_end(tb, num_insns);

    tb->size = last_pc + 4 - pc_start;

    tb->icount = num_insns;

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)

        && qemu_log_in_addr_range(pc_start)) {

        qemu_log_lock();

        qemu_log("--------------\n");

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

        log_target_disas(cs, pc_start, last_pc + 4 - pc_start, 0);

        qemu_log("\n");

        qemu_log_unlock();

    }

#endif

}


static void cortex_a15_initfn(Object *obj)

{

    ARMCPU *cpu = ARM_CPU(obj);

    set_feature(&cpu->env, ARM_FEATURE_V7);

    set_feature(&cpu->env, ARM_FEATURE_VFP4);

    set_feature(&cpu->env, ARM_FEATURE_VFP_FP16);

    set_feature(&cpu->env, ARM_FEATURE_NEON);

    set_feature(&cpu->env, ARM_FEATURE_THUMB2EE);

    set_feature(&cpu->env, ARM_FEATURE_ARM_DIV);

    set_feature(&cpu->env, ARM_FEATURE_V7MP);

    set_feature(&cpu->env, ARM_FEATURE_GENERIC_TIMER);

    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);

    cpu->midr = 0x412fc0f1;

    cpu->reset_fpsid = 0x410430f0;

    cpu->mvfr0 = 0x10110222;

    cpu->mvfr1 = 0x11111111;

    cpu->ctr = 0x8444c004;

    cpu->reset_sctlr = 0x00c50078;

    cpu->id_pfr0 = 0x00001131;

    cpu->id_pfr1 = 0x00011011;

    cpu->id_dfr0 = 0x02010555;

    cpu->id_afr0 = 0x00000000;

    cpu->id_mmfr0 = 0x10201105;

    cpu->id_mmfr1 = 0x20000000;

    cpu->id_mmfr2 = 0x01240000;

    cpu->id_mmfr3 = 0x02102211;

    cpu->id_isar0 = 0x02101110;

    cpu->id_isar1 = 0x13112111;

    cpu->id_isar2 = 0x21232041;

    cpu->id_isar3 = 0x11112131;

    cpu->id_isar4 = 0x10011142;

    cpu->clidr = 0x0a200023;

    cpu->ccsidr[0] = 0x701fe00a; /* 32K L1 dcache */

    cpu->ccsidr[1] = 0x201fe00a; /* 32K L1 icache */

    cpu->ccsidr[2] = 0x711fe07a; /* 4096K L2 unified cache */

    define_arm_cp_regs(cpu, cortexa15_cp_reginfo);

}


void OPPROTO op_check_reservation_64 (void)

{

    if ((uint64_t)env->reserve == (uint64_t)(T0 & ~0x00000003))

        env->reserve = -1;

    RETURN();

}


static int vp8_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                            AVPacket *avpkt)

{

    VP8Context *s = avctx->priv_data;

    int ret, mb_x, mb_y, i, y, referenced;

    enum AVDiscard skip_thresh;

    AVFrame *av_uninit(curframe), *prev_frame;

    release_queued_segmaps(s, 0);

    if ((ret = decode_frame_header(s, avpkt->data, avpkt->size)) < 0)

        return ret;

    prev_frame = s->framep[VP56_FRAME_CURRENT];

    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT

                                || s->update_altref == VP56_FRAME_CURRENT;

    skip_thresh = !referenced ? AVDISCARD_NONREF :

                    !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL;

    if (avctx->skip_frame >= skip_thresh) {

        s->invisible = 1;

        goto skip_decode;

    }

    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;

    // release no longer referenced frames

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

        if (s->frames[i].data[0] &&

            &s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])

            vp8_release_frame(s, &s->frames[i], 1, 0);

    // find a free buffer

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

        if (&s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) {

            curframe = s->framep[VP56_FRAME_CURRENT] = &s->frames[i];

            break;

        }

    if (i == 5) {

        av_log(avctx, AV_LOG_FATAL, "Ran out of free frames!\n");

        abort();

    }

    if (curframe->data[0])

        vp8_release_frame(s, curframe, 1, 0);

    curframe->key_frame = s->keyframe;

    curframe->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;

    curframe->reference = referenced ? 3 : 0;

    if ((ret = vp8_alloc_frame(s, curframe))) {

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

        return ret;

    }

    // check if golden and altref are swapped

    if (s->update_altref != VP56_FRAME_NONE) {

        s->next_framep[VP56_FRAME_GOLDEN2]  = s->framep[s->update_altref];

    } else {

        s->next_framep[VP56_FRAME_GOLDEN2]  = s->framep[VP56_FRAME_GOLDEN2];

    }

    if (s->update_golden != VP56_FRAME_NONE) {

        s->next_framep[VP56_FRAME_GOLDEN]   = s->framep[s->update_golden];

    } else {

        s->next_framep[VP56_FRAME_GOLDEN]   = s->framep[VP56_FRAME_GOLDEN];

    }

    if (s->update_last) {

        s->next_framep[VP56_FRAME_PREVIOUS] = curframe;

    } else {

        s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];

    }

    s->next_framep[VP56_FRAME_CURRENT]      = curframe;

    ff_thread_finish_setup(avctx);

    // Given that arithmetic probabilities are updated every frame, it's quite likely

    // that the values we have on a random interframe are complete junk if we didn't

    // start decode on a keyframe. So just don't display anything rather than junk.

    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||

                         !s->framep[VP56_FRAME_GOLDEN] ||

                         !s->framep[VP56_FRAME_GOLDEN2])) {

        av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n");

        return AVERROR_INVALIDDATA;

    }

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

    s->uvlinesize = curframe->linesize[1];

    if (!s->edge_emu_buffer)

        s->edge_emu_buffer = av_malloc(21*s->linesize);

    memset(s->top_nnz, 0, s->mb_width*sizeof(*s->top_nnz));

    /* Zero macroblock structures for top/top-left prediction from outside the frame. */

    memset(s->macroblocks + s->mb_height*2 - 1, 0, (s->mb_width+1)*sizeof(*s->macroblocks));

    // top edge of 127 for intra prediction

    if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {

        s->top_border[0][15] = s->top_border[0][23] = 127;

        memset(s->top_border[1]-1, 127, s->mb_width*sizeof(*s->top_border)+1);

    }

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

    if (s->keyframe)

        memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width*4);

#define MARGIN (16 << 2)

    s->mv_min.y = -MARGIN;

    s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;

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

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

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

        int mb_xy = mb_y*s->mb_width;

        uint8_t *dst[3] = {

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

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

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

        };

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

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

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

        // left edge of 129 for intra prediction

        if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {

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

                for (y = 0; y < 16>>!!i; y++)

                    dst[i][y*curframe->linesize[i]-1] = 129;

            if (mb_y == 1) // top left edge is also 129

                s->top_border[0][15] = s->top_border[0][23] = s->top_border[0][31] = 129;

        }

        s->mv_min.x = -MARGIN;

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

        if (prev_frame && s->segmentation.enabled && !s->segmentation.update_map)

            ff_thread_await_progress(prev_frame, mb_y, 0);

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

            /* Prefetch the current frame, 4 MBs ahead */

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

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

            decode_mb_mode(s, mb, mb_x, mb_y, curframe->ref_index[0] + mb_xy,

                           prev_frame && prev_frame->ref_index[0] ? prev_frame->ref_index[0] + mb_xy : NULL);

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

            if (!mb->skip)

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

            if (mb->mode <= MODE_I4x4)

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

            else

                inter_predict(s, 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, dst, mb);

            } else {

                AV_ZERO64(s->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) {

                    s->left_nnz[8]      = 0;

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

                }

            }

            if (s->deblock_filter)

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

            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 (s->deblock_filter) {

            if (s->filter.simple)

                filter_mb_row_simple(s, curframe, mb_y);

            else

                filter_mb_row(s, curframe, mb_y);

        }

        s->mv_min.y -= 64;

        s->mv_max.y -= 64;

        ff_thread_report_progress(curframe, mb_y, 0);

    }

    ff_thread_report_progress(curframe, INT_MAX, 0);

skip_decode:

    // if future frames don't use the updated probabilities,

    // reset them to the values we saved

    if (!s->update_probabilities)

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

    memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);

    if (!s->invisible) {

        *(AVFrame*)data = *curframe;

        *data_size = sizeof(AVFrame);

    }

    return avpkt->size;

}


static void serial_update_parameters(SerialState *s)

{

    int speed, parity, data_bits, stop_bits, frame_size;

    QEMUSerialSetParams ssp;

    if (s->divider == 0)

        return;

    /* Start bit. */

    frame_size = 1;

    if (s->lcr & 0x08) {

        /* Parity bit. */

        frame_size++;

        if (s->lcr & 0x10)

            parity = 'E';

        else

            parity = 'O';

    } else {

            parity = 'N';

    }

    if (s->lcr & 0x04)

        stop_bits = 2;

    else

        stop_bits = 1;

    data_bits = (s->lcr & 0x03) + 5;

    frame_size += data_bits + stop_bits;

    speed = s->baudbase / s->divider;

    ssp.speed = speed;

    ssp.parity = parity;

    ssp.data_bits = data_bits;

    ssp.stop_bits = stop_bits;

    s->char_transmit_time =  (NANOSECONDS_PER_SECOND / speed) * frame_size;

    qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_PARAMS, &ssp);

    DPRINTF("speed=%d parity=%c data=%d stop=%d\n",

           speed, parity, data_bits, stop_bits);

}


static void generate_noise(G723_1_Context *p)

{

    int i, j, idx, t;

    int off[SUBFRAMES];

    int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];

    int tmp[SUBFRAME_LEN * 2];

    int16_t *vector_ptr;

    int64_t sum;

    int b0, c, delta, x, shift;

    p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;

    p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;

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

        p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;

        p->subframe[i].ad_cb_lag  = cng_adaptive_cb_lag[i];

    }

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

        t = cng_rand(&p->cng_random_seed, 1 << 13);

        off[i * 2]     =   t       & 1;

        off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;

        t >>= 2;

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

            signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;

            t >>= 1;

        }

    }

    idx = 0;

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

        for (j = 0; j < SUBFRAME_LEN / 2; j++)

            tmp[j] = j;

        t = SUBFRAME_LEN / 2;

        for (j = 0; j < pulses[i]; j++, idx++) {

            int idx2 = cng_rand(&p->cng_random_seed, t);

            pos[idx]  = tmp[idx2] * 2 + off[i];

            tmp[idx2] = tmp[--t];

        }

    }

    vector_ptr = p->audio + LPC_ORDER;

    memcpy(vector_ptr, p->prev_excitation,

           PITCH_MAX * sizeof(*p->excitation));

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

        ff_g723_1_gen_acb_excitation(vector_ptr, vector_ptr,

                                     p->pitch_lag[i >> 1], &p->subframe[i],

                                     p->cur_rate);

        ff_g723_1_gen_acb_excitation(vector_ptr + SUBFRAME_LEN,

                                     vector_ptr + SUBFRAME_LEN,

                                     p->pitch_lag[i >> 1], &p->subframe[i + 1],

                                     p->cur_rate);

        t = 0;

        for (j = 0; j < SUBFRAME_LEN * 2; j++)

            t |= FFABS(vector_ptr[j]);

        t = FFMIN(t, 0x7FFF);

        if (!t) {

            shift = 0;

        } else {

            shift = -10 + av_log2(t);

            if (shift < -2)

                shift = -2;

        }

        sum = 0;

        if (shift < 0) {

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

               t      = vector_ptr[j] << -shift;

               sum   += t * t;

               tmp[j] = t;

           }

        } else {

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

               t      = vector_ptr[j] >> shift;

               sum   += t * t;

               tmp[j] = t;

           }

        }

        b0 = 0;

        for (j = 0; j < 11; j++)

            b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];

        b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11

        c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);

        if (shift * 2 + 3 >= 0)

            c >>= shift * 2 + 3;

        else

            c <<= -(shift * 2 + 3);

        c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;

        delta = b0 * b0 * 2 - c;

        if (delta <= 0) {

            x = -b0;

        } else {

            delta = square_root(delta);

            x     = delta - b0;

            t     = delta + b0;

            if (FFABS(t) < FFABS(x))

                x = -t;

        }

        shift++;

        if (shift < 0)

           x >>= -shift;

        else

           x <<= shift;

        x = av_clip(x, -10000, 10000);

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

            idx = (i / 2) * 11 + j;

            vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +

                                                 (x * signs[idx] >> 15));

        }

        /* copy decoded data to serve as a history for the next decoded subframes */

        memcpy(vector_ptr + PITCH_MAX, vector_ptr,

               sizeof(*vector_ptr) * SUBFRAME_LEN * 2);

        vector_ptr += SUBFRAME_LEN * 2;

    }

    /* Save the excitation for the next frame */

    memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,

           PITCH_MAX * sizeof(*p->excitation));

}


struct GuestFileRead *qmp_guest_file_read(int64_t handle, bool has_count,

                                          int64_t count, Error **errp)

{

    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);

    GuestFileRead *read_data = NULL;

    guchar *buf;

    FILE *fh;

    size_t read_count;

    if (!gfh) {

        return NULL;

    }

    if (!has_count) {

        count = QGA_READ_COUNT_DEFAULT;

    } else if (count < 0) {

        error_setg(errp, "value '%" PRId64 "' is invalid for argument count",

                   count);

        return NULL;

    }

    fh = gfh->fh;

    buf = g_malloc0(count+1);

    read_count = fread(buf, 1, count, fh);

    if (ferror(fh)) {

        error_setg_errno(errp, errno, "failed to read file");

        slog("guest-file-read failed, handle: %" PRId64, handle);

    } else {

        buf[read_count] = 0;

        read_data = g_malloc0(sizeof(GuestFileRead));

        read_data->count = read_count;

        read_data->eof = feof(fh);

        if (read_count) {

            read_data->buf_b64 = g_base64_encode(buf, read_count);

        }

    }

    g_free(buf);

    clearerr(fh);

    return read_data;

}


static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,

    int is_read)

{

    BlockInterfaceErrorAction action =

        drive_get_on_error(req->dev->bs, is_read);

    VirtIOBlock *s = req->dev;

    if (action == BLOCK_ERR_IGNORE) {

        bdrv_mon_event(req->dev->bs, BDRV_ACTION_IGNORE, is_read);

        return 0;

    }

    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)

            || action == BLOCK_ERR_STOP_ANY) {

        req->next = s->rq;

        s->rq = req;

        bdrv_mon_event(req->dev->bs, BDRV_ACTION_STOP, is_read);

        vm_stop(0);

    } else {

        virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);

        bdrv_mon_event(req->dev->bs, BDRV_ACTION_REPORT, is_read);

    }

    return 1;

}


int av_read_pause(AVFormatContext *s)

{

    if (s->iformat->read_pause)

        return s->iformat->read_pause(s);

    if (s->pb && s->pb->read_pause)

        return av_url_read_fpause(s->pb, 1);

    return AVERROR(ENOSYS);

}


static BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
        unsigned long int req, void *buf,
        BlockCompletionFunc *cb, void *opaque)
{
    IscsiLun *iscsilun = bs->opaque;
    struct iscsi_context *iscsi = iscsilun->iscsi;
    struct iscsi_data data;
    IscsiAIOCB *acb;
    acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
    acb->iscsilun = iscsilun;
    acb->bh          = NULL;
    acb->status      = -EINPROGRESS;
    acb->buf         = NULL;
    acb->ioh         = buf;
    if (req != SG_IO) {
        iscsi_ioctl_handle_emulated(acb, req, buf);
        return &acb->common;
    acb->task = malloc(sizeof(struct scsi_task));
    if (acb->task == NULL) {
        error_report("iSCSI: Failed to allocate task for scsi command. %s",
                     iscsi_get_error(iscsi));
    memset(acb->task, 0, sizeof(struct scsi_task));
    switch (acb->ioh->dxfer_direction) {
    case SG_DXFER_TO_DEV:
        acb->task->xfer_dir = SCSI_XFER_WRITE;
        break;
    case SG_DXFER_FROM_DEV:
        acb->task->xfer_dir = SCSI_XFER_READ;
        break;
    default:
        acb->task->xfer_dir = SCSI_XFER_NONE;
        break;
    acb->task->cdb_size = acb->ioh->cmd_len;
    memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
    acb->task->expxferlen = acb->ioh->dxfer_len;
    data.size = 0;
    if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
        if (acb->ioh->iovec_count == 0) {
            data.data = acb->ioh->dxferp;
            data.size = acb->ioh->dxfer_len;
        } else {
            scsi_task_set_iov_out(acb->task,
                                 (struct scsi_iovec *) acb->ioh->dxferp,
                                 acb->ioh->iovec_count);
    if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
                                 iscsi_aio_ioctl_cb,
                                 (data.size > 0) ? &data : NULL,
                                 acb) != 0) {
        scsi_free_scsi_task(acb->task);
    /* tell libiscsi to read straight into the buffer we got from ioctl */
    if (acb->task->xfer_dir == SCSI_XFER_READ) {
        if (acb->ioh->iovec_count == 0) {
            scsi_task_add_data_in_buffer(acb->task,
                                         acb->ioh->dxfer_len,
                                         acb->ioh->dxferp);
        } else {
            scsi_task_set_iov_in(acb->task,
                                 (struct scsi_iovec *) acb->ioh->dxferp,
                                 acb->ioh->iovec_count);
    iscsi_set_events(iscsilun);
    return &acb->common;


static void *thread_function(void *data)

{

    GMainLoop *loop;

    loop = g_main_loop_new(NULL, FALSE);

    g_main_loop_run(loop);

    return NULL;

}


static DisplaySurface* sdl_create_displaysurface(int width, int height)

{

    DisplaySurface *surface = (DisplaySurface*) g_malloc0(sizeof(DisplaySurface));

    if (surface == NULL) {

        fprintf(stderr, "sdl_create_displaysurface: malloc failed\n");

        exit(1);

    }

    surface->width = width;

    surface->height = height;

    if (scaling_active) {

        int linesize;

        PixelFormat pf;

        if (host_format.BytesPerPixel != 2 && host_format.BytesPerPixel != 4) {

            linesize = width * 4;

            pf = qemu_default_pixelformat(32);

        } else {

            linesize = width * host_format.BytesPerPixel;

            pf = sdl_to_qemu_pixelformat(&host_format);

        }

        qemu_alloc_display(surface, width, height, linesize, pf, 0);

        return surface;

    }

    if (host_format.BitsPerPixel == 16)

        do_sdl_resize(width, height, 16);

    else

        do_sdl_resize(width, height, 32);

    surface->pf = sdl_to_qemu_pixelformat(real_screen->format);

    surface->linesize = real_screen->pitch;

    surface->data = real_screen->pixels;

#ifdef HOST_WORDS_BIGENDIAN

    surface->flags = QEMU_REALPIXELS_FLAG | QEMU_BIG_ENDIAN_FLAG;

#else

    surface->flags = QEMU_REALPIXELS_FLAG;

#endif

    allocator = 1;

    return surface;

}


static int _get_transform_coeffs(uint8_t *exps, uint8_t *bap, float chcoeff,

        float *samples, int start, int end, int dith_flag, GetBitContext *gb,

        dither_state *state)

{

    int16_t mantissa;

    int i;

    int gcode;

    mant_group l3_grp, l5_grp, l11_grp;

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

        l3_grp.gcodes[i] = l5_grp.gcodes[i] = l11_grp.gcodes[i] = -1;

    l3_grp.gcptr = l5_grp.gcptr = 3;

    l11_grp.gcptr = 2;

    i = 0;

    while (i < start)

        samples[i++] = 0;

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

        switch (bap[i]) {

            case 0:

                if (!dith_flag)

                    mantissa = 0;

                else

                    mantissa = dither_int16(state);

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 1:

                if (l3_grp.gcptr > 2) {

                    gcode = get_bits(gb, qntztab[1]);

                    if (gcode > 26)

                        return -1;

                    l3_grp.gcodes[0] = gcode / 9;

                    l3_grp.gcodes[1] = (gcode % 9) / 3;

                    l3_grp.gcodes[2] = (gcode % 9) % 3;

                    l3_grp.gcptr = 0;

                }

                mantissa = l3_q_tab[l3_grp.gcodes[l3_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 2:

                if (l5_grp.gcptr > 2) {

                    gcode = get_bits(gb, qntztab[2]);

                    if (gcode > 124)

                        return -1;

                    l5_grp.gcodes[0] = gcode / 25;

                    l5_grp.gcodes[1] = (gcode % 25) / 5;

                    l5_grp.gcodes[2] = (gcode % 25) % 5;

                    l5_grp.gcptr = 0;

                }

                mantissa = l5_q_tab[l5_grp.gcodes[l5_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 3:

                mantissa = get_bits(gb, qntztab[3]);

                if (mantissa > 6)

                    return -1;

                mantissa = l7_q_tab[mantissa];

                samples[i] = to_float(exps[i], mantissa);

                break;

            case 4:

                if (l11_grp.gcptr > 1) {

                    gcode = get_bits(gb, qntztab[4]);

                    if (gcode > 120)

                        return -1;

                    l11_grp.gcodes[0] = gcode / 11;

                    l11_grp.gcodes[1] = gcode % 11;

                }

                mantissa = l11_q_tab[l11_grp.gcodes[l11_grp.gcptr++]];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            case 5:

                mantissa = get_bits(gb, qntztab[5]);

                if (mantissa > 14)

                    return -1;

                mantissa = l15_q_tab[mantissa];

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

            default:

                mantissa = get_bits(gb, qntztab[bap[i]]) << (16 - qntztab[bap[i]]);

                samples[i] = to_float(exps[i], mantissa) * chcoeff;

                break;

        }

    }

    i = end;

    while (i < 256)

        samples[i++] = 0;

    return 0;

}