void ff_hevc_luma_mv_mvp_mode(HEVCContext *s, int x0, int y0, int nPbW,

                              int nPbH, int log2_cb_size, int part_idx,

                              int merge_idx, MvField *mv,

                              int mvp_lx_flag, int LX)

{

    HEVCLocalContext *lc = s->HEVClc;

    MvField *tab_mvf = s->ref->tab_mvf;

    int isScaledFlag_L0 = 0;

    int availableFlagLXA0 = 1;

    int availableFlagLXB0 = 1;

    int numMVPCandLX = 0;

    int min_pu_width = s->sps->min_pu_width;

    int xA0, yA0;

    int is_available_a0;

    int xA1, yA1;

    int is_available_a1;

    int xB0, yB0;

    int is_available_b0;

    int xB1, yB1;

    int is_available_b1;

    int xB2, yB2;

    int is_available_b2;

    Mv mvpcand_list[2] = { { 0 } };

    Mv mxA;

    Mv mxB;

    int ref_idx_curr = 0;

    int ref_idx = 0;

    int pred_flag_index_l0;

    int pred_flag_index_l1;

    const int cand_bottom_left = lc->na.cand_bottom_left;

    const int cand_left        = lc->na.cand_left;

    const int cand_up_left     = lc->na.cand_up_left;

    const int cand_up          = lc->na.cand_up;

    const int cand_up_right    = lc->na.cand_up_right_sap;

    ref_idx_curr       = LX;

    ref_idx            = mv->ref_idx[LX];

    pred_flag_index_l0 = LX;

    pred_flag_index_l1 = !LX;

    // left bottom spatial candidate

    xA0 = x0 - 1;

    yA0 = y0 + nPbH;

    is_available_a0 = AVAILABLE(cand_bottom_left, A0) &&

                      yA0 < s->sps->height &&

                      PRED_BLOCK_AVAILABLE(A0);

    //left spatial merge candidate

    xA1    = x0 - 1;

    yA1    = y0 + nPbH - 1;

    is_available_a1 = AVAILABLE(cand_left, A1);

    if (is_available_a0 || is_available_a1)

        isScaledFlag_L0 = 1;

    if (is_available_a0) {

        if (MP_MX(A0, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX(A0, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a1) {

        if (MP_MX(A1, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX(A1, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a0) {

        if (MP_MX_LT(A0, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX_LT(A0, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    if (is_available_a1) {

        if (MP_MX_LT(A1, pred_flag_index_l0, mxA)) {

            goto b_candidates;

        }

        if (MP_MX_LT(A1, pred_flag_index_l1, mxA)) {

            goto b_candidates;

        }

    }

    availableFlagLXA0 = 0;

b_candidates:

    // B candidates

    // above right spatial merge candidate

    xB0    = x0 + nPbW;

    yB0    = y0 - 1;

    is_available_b0 =  AVAILABLE(cand_up_right, B0) &&

                       xB0 < s->sps->width &&

                       PRED_BLOCK_AVAILABLE(B0);

    if (is_available_b0) {

        if (MP_MX(B0, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B0, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    // above spatial merge candidate

    xB1    = x0 + nPbW - 1;

    yB1    = y0 - 1;

    is_available_b1 = AVAILABLE(cand_up, B1);

    if (is_available_b1) {

        if (MP_MX(B1, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B1, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    // above left spatial merge candidate

    xB2 = x0 - 1;

    yB2 = y0 - 1;

    is_available_b2 = AVAILABLE(cand_up_left, B2);

    if (is_available_b2) {

        if (MP_MX(B2, pred_flag_index_l0, mxB)) {

            goto scalef;

        }

        if (MP_MX(B2, pred_flag_index_l1, mxB)) {

            goto scalef;

        }

    }

    availableFlagLXB0 = 0;

scalef:

    if (!isScaledFlag_L0) {

        if (availableFlagLXB0) {

            availableFlagLXA0 = 1;

            mxA = mxB;

        }

        availableFlagLXB0 = 0;

        // XB0 and L1

        if (is_available_b0) {

            availableFlagLXB0 = MP_MX_LT(B0, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B0, pred_flag_index_l1, mxB);

        }

        if (is_available_b1 && !availableFlagLXB0) {

            availableFlagLXB0 = MP_MX_LT(B1, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B1, pred_flag_index_l1, mxB);

        }

        if (is_available_b2 && !availableFlagLXB0) {

            availableFlagLXB0 = MP_MX_LT(B2, pred_flag_index_l0, mxB);

            if (!availableFlagLXB0)

                availableFlagLXB0 = MP_MX_LT(B2, pred_flag_index_l1, mxB);

        }

    }

    if (availableFlagLXA0)

        mvpcand_list[numMVPCandLX++] = mxA;

    if (availableFlagLXB0 && (!availableFlagLXA0 || mxA.x != mxB.x || mxA.y != mxB.y))

        mvpcand_list[numMVPCandLX++] = mxB;

    //temporal motion vector prediction candidate

    if (numMVPCandLX < 2 && s->sh.slice_temporal_mvp_enabled_flag &&

        mvp_lx_flag == numMVPCandLX) {

        Mv mv_col;

        int available_col = temporal_luma_motion_vector(s, x0, y0, nPbW,

                                                        nPbH, ref_idx,

                                                        &mv_col, LX);

        if (available_col)

            mvpcand_list[numMVPCandLX++] = mv_col;

    }

    mv->mv[LX] = mvpcand_list[mvp_lx_flag];

}


static void gen_ove_cyov(DisasContext *dc, TCGv cy, TCGv ov)

{

    if (dc->tb_flags & SR_OVE) {

        TCGv t0 = tcg_temp_new();

        tcg_gen_or_tl(t0, cy, ov);

        gen_helper_ove(cpu_env, t0);

        tcg_temp_free(t0);

    }

}


static void put_uint16(QEMUFile *f, void *pv, size_t size)

{

    uint16_t *v = pv;

    qemu_put_be16s(f, v);

}


static int vqa_decode_chunk(VqaContext *s)

{

    unsigned int chunk_type;

    unsigned int chunk_size;

    int byte_skip;

    unsigned int index = 0;

    int i;

    unsigned char r, g, b;

    int index_shift;

    int res;

    int cbf0_chunk = -1;

    int cbfz_chunk = -1;

    int cbp0_chunk = -1;

    int cbpz_chunk = -1;

    int cpl0_chunk = -1;

    int cplz_chunk = -1;

    int vptz_chunk = -1;

    int x, y;

    int lines = 0;

    int pixel_ptr;

    int vector_index = 0;

    int lobyte = 0;

    int hibyte = 0;

    int lobytes = 0;

    int hibytes = s->decode_buffer_size / 2;

    /* first, traverse through the frame and find the subchunks */

    while (bytestream2_get_bytes_left(&s->gb) >= 8) {

        chunk_type = bytestream2_get_be32u(&s->gb);

        index      = bytestream2_tell(&s->gb);

        chunk_size = bytestream2_get_be32u(&s->gb);

        switch (chunk_type) {

        case CBF0_TAG:

            cbf0_chunk = index;

            break;

        case CBFZ_TAG:

            cbfz_chunk = index;

            break;

        case CBP0_TAG:

            cbp0_chunk = index;

            break;

        case CBPZ_TAG:

            cbpz_chunk = index;

            break;

        case CPL0_TAG:

            cpl0_chunk = index;

            break;

        case CPLZ_TAG:

            cplz_chunk = index;

            break;

        case VPTZ_TAG:

            vptz_chunk = index;

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "Found unknown chunk type: %c%c%c%c (%08X)\n",

            (chunk_type >> 24) & 0xFF,

            (chunk_type >> 16) & 0xFF,

            (chunk_type >>  8) & 0xFF,

            (chunk_type >>  0) & 0xFF,

            chunk_type);

            break;

        }

        byte_skip = chunk_size & 0x01;

        bytestream2_skip(&s->gb, chunk_size + byte_skip);

    }

    /* next, deal with the palette */

    if ((cpl0_chunk != -1) && (cplz_chunk != -1)) {

        /* a chunk should not have both chunk types */

        av_log(s->avctx, AV_LOG_ERROR, "problem: found both CPL0 and CPLZ chunks\n");

        return AVERROR_INVALIDDATA;

    }

    /* decompress the palette chunk */

    if (cplz_chunk != -1) {

/* yet to be handled */

    }

    /* convert the RGB palette into the machine's endian format */

    if (cpl0_chunk != -1) {

        bytestream2_seek(&s->gb, cpl0_chunk, SEEK_SET);

        chunk_size = bytestream2_get_be32(&s->gb);

        /* sanity check the palette size */

        if (chunk_size / 3 > 256 || chunk_size > bytestream2_get_bytes_left(&s->gb)) {

            av_log(s->avctx, AV_LOG_ERROR, "problem: found a palette chunk with %d colors\n",

                chunk_size / 3);

            return AVERROR_INVALIDDATA;

        }

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

            /* scale by 4 to transform 6-bit palette -> 8-bit */

            r = bytestream2_get_byteu(&s->gb) * 4;

            g = bytestream2_get_byteu(&s->gb) * 4;

            b = bytestream2_get_byteu(&s->gb) * 4;

            s->palette[i] = 0xFF << 24 | r << 16 | g << 8 | b;

            s->palette[i] |= s->palette[i] >> 6 & 0x30303;

        }

    }

    /* next, look for a full codebook */

    if ((cbf0_chunk != -1) && (cbfz_chunk != -1)) {

        /* a chunk should not have both chunk types */

        av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBF0 and CBFZ chunks\n");

        return AVERROR_INVALIDDATA;

    }

    /* decompress the full codebook chunk */

    if (cbfz_chunk != -1) {

        bytestream2_seek(&s->gb, cbfz_chunk, SEEK_SET);

        chunk_size = bytestream2_get_be32(&s->gb);

        if ((res = decode_format80(s, chunk_size, s->codebook,

                                   s->codebook_size, 0)) < 0)

            return res;

    }

    /* copy a full codebook */

    if (cbf0_chunk != -1) {

        bytestream2_seek(&s->gb, cbf0_chunk, SEEK_SET);

        chunk_size = bytestream2_get_be32(&s->gb);

        /* sanity check the full codebook size */

        if (chunk_size > MAX_CODEBOOK_SIZE) {

            av_log(s->avctx, AV_LOG_ERROR, "problem: CBF0 chunk too large (0x%X bytes)\n",

                chunk_size);

            return AVERROR_INVALIDDATA;

        }

        bytestream2_get_buffer(&s->gb, s->codebook, chunk_size);

    }

    /* decode the frame */

    if (vptz_chunk == -1) {

        /* something is wrong if there is no VPTZ chunk */

        av_log(s->avctx, AV_LOG_ERROR, "problem: no VPTZ chunk found\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_seek(&s->gb, vptz_chunk, SEEK_SET);

    chunk_size = bytestream2_get_be32(&s->gb);

    if ((res = decode_format80(s, chunk_size,

                               s->decode_buffer, s->decode_buffer_size, 1)) < 0)

        return res;

    /* render the final PAL8 frame */

    if (s->vector_height == 4)

        index_shift = 4;

    else

        index_shift = 3;

    for (y = 0; y < s->height; y += s->vector_height) {

        for (x = 0; x < s->width; x += 4, lobytes++, hibytes++) {

            pixel_ptr = y * s->frame.linesize[0] + x;

            /* get the vector index, the method for which varies according to

             * VQA file version */

            switch (s->vqa_version) {

            case 1:

                lobyte = s->decode_buffer[lobytes * 2];

                hibyte = s->decode_buffer[(lobytes * 2) + 1];

                vector_index = ((hibyte << 8) | lobyte) >> 3;

                vector_index <<= index_shift;

                lines = s->vector_height;

                /* uniform color fill - a quick hack */

                if (hibyte == 0xFF) {

                    while (lines--) {

                        s->frame.data[0][pixel_ptr + 0] = 255 - lobyte;

                        s->frame.data[0][pixel_ptr + 1] = 255 - lobyte;

                        s->frame.data[0][pixel_ptr + 2] = 255 - lobyte;

                        s->frame.data[0][pixel_ptr + 3] = 255 - lobyte;

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

                    }

                    lines=0;

                }

                break;

            case 2:

                lobyte = s->decode_buffer[lobytes];

                hibyte = s->decode_buffer[hibytes];

                vector_index = (hibyte << 8) | lobyte;

                vector_index <<= index_shift;

                lines = s->vector_height;

                break;

            case 3:

/* not implemented yet */

                lines = 0;

                break;

            }

            while (lines--) {

                s->frame.data[0][pixel_ptr + 0] = s->codebook[vector_index++];

                s->frame.data[0][pixel_ptr + 1] = s->codebook[vector_index++];

                s->frame.data[0][pixel_ptr + 2] = s->codebook[vector_index++];

                s->frame.data[0][pixel_ptr + 3] = s->codebook[vector_index++];

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

            }

        }

    }

    /* handle partial codebook */

    if ((cbp0_chunk != -1) && (cbpz_chunk != -1)) {

        /* a chunk should not have both chunk types */

        av_log(s->avctx, AV_LOG_ERROR, "problem: found both CBP0 and CBPZ chunks\n");

        return AVERROR_INVALIDDATA;

    }

    if (cbp0_chunk != -1) {

        bytestream2_seek(&s->gb, cbp0_chunk, SEEK_SET);

        chunk_size = bytestream2_get_be32(&s->gb);

        /* accumulate partial codebook */

        bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index],

                               chunk_size);

        s->next_codebook_buffer_index += chunk_size;

        s->partial_countdown--;

        if (s->partial_countdown <= 0) {

            /* time to replace codebook */

            memcpy(s->codebook, s->next_codebook_buffer,

                s->next_codebook_buffer_index);

            /* reset accounting */

            s->next_codebook_buffer_index = 0;

            s->partial_countdown = s->partial_count;

        }

    }

    if (cbpz_chunk != -1) {

        bytestream2_seek(&s->gb, cbpz_chunk, SEEK_SET);

        chunk_size = bytestream2_get_be32(&s->gb);

        /* accumulate partial codebook */

        bytestream2_get_buffer(&s->gb, &s->next_codebook_buffer[s->next_codebook_buffer_index],

                               chunk_size);

        s->next_codebook_buffer_index += chunk_size;

        s->partial_countdown--;

        if (s->partial_countdown <= 0) {

            GetByteContext gb;

            bytestream2_init(&gb, s->next_codebook_buffer, s->next_codebook_buffer_index);

            /* decompress codebook */

            if ((res = decode_format80(s, s->next_codebook_buffer_index,

                                       s->codebook, s->codebook_size, 0)) < 0)

                return res;

            /* reset accounting */

            s->next_codebook_buffer_index = 0;

            s->partial_countdown = s->partial_count;

        }

    }

    return 0;

}


static int hls_read(URLContext *h, uint8_t *buf, int size)

{

    HLSContext *s = h->priv_data;

    const char *url;

    int ret;

    int64_t reload_interval;

start:

    if (s->seg_hd) {

        ret = ffurl_read(s->seg_hd, buf, size);

        if (ret > 0)

            return ret;

    }

    if (s->seg_hd) {

        ffurl_close(s->seg_hd);

        s->seg_hd = NULL;

        s->cur_seq_no++;

    }

    reload_interval = s->n_segments > 0 ?

                      s->segments[s->n_segments - 1]->duration :

                      s->target_duration;

    reload_interval *= 1000000;

retry:

    if (!s->finished) {

        int64_t now = av_gettime();

        if (now - s->last_load_time >= reload_interval) {

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

                return ret;

            /* If we need to reload the playlist again below (if

             * there's still no more segments), switch to a reload

             * interval of half the target duration. */

            reload_interval = s->target_duration * 500000;

        }

    }

    if (s->cur_seq_no < s->start_seq_no) {

        av_log(h, AV_LOG_WARNING,

               "skipping %d segments ahead, expired from playlist\n",

               s->start_seq_no - s->cur_seq_no);

        s->cur_seq_no = s->start_seq_no;

    }

    if (s->cur_seq_no - s->start_seq_no >= s->n_segments) {

        if (s->finished)

            return AVERROR_EOF;

        while (av_gettime() - s->last_load_time < reload_interval) {

            if (ff_check_interrupt(&h->interrupt_callback))

                return AVERROR_EXIT;

            av_usleep(100*1000);

        }

        goto retry;

    }

    url = s->segments[s->cur_seq_no - s->start_seq_no]->url,

    av_log(h, AV_LOG_DEBUG, "opening %s\n", url);

    ret = ffurl_open(&s->seg_hd, url, AVIO_FLAG_READ,

                     &h->interrupt_callback, NULL);

    if (ret < 0) {

        if (ff_check_interrupt(&h->interrupt_callback))

            return AVERROR_EXIT;

        av_log(h, AV_LOG_WARNING, "Unable to open %s\n", url);

        s->cur_seq_no++;

        goto retry;

    }

    goto start;

}


static inline void ff_h264_biweight_WxH_mmx2(uint8_t *dst, uint8_t *src, int stride, int log2_denom, int weightd, int weights, int offsetd, int offsets, int w, int h)

{

    int x, y;

    int offset = ((offsets + offsetd + 1) | 1) << log2_denom;

    asm volatile(

        "movd    %0, %%mm3        \n\t"

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

        "movd    %2, %%mm5        \n\t"

        "movd    %3, %%mm6        \n\t"

        "pshufw  $0, %%mm3, %%mm3 \n\t"

        "pshufw  $0, %%mm4, %%mm4 \n\t"

        "pshufw  $0, %%mm5, %%mm5 \n\t"

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

        :: "g"(weightd), "g"(weights), "g"(offset), "g"(log2_denom+1)

    );

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

        for(x=0; x<w; x+=4){

            asm volatile(

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

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

                "punpcklbw %%mm7, %%mm0 \n\t"

                "punpcklbw %%mm7, %%mm1 \n\t"

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

                "pmullw    %%mm4, %%mm1 \n\t"

                "paddw     %%mm5, %%mm0 \n\t"

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

                "psraw     %%mm6, %%mm0 \n\t"

                "packuswb  %%mm0, %%mm0 \n\t"

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

                : "+m"(*(uint32_t*)(dst+x))

                :  "m"(*(uint32_t*)(src+x))

            );

        }

        src += stride;

        dst += stride;

    }

}


static int dpx_probe(AVProbeData *p)

{

    const uint8_t *b = p->buf;

    if (AV_RN32(b) == AV_RN32("SDPX") || AV_RN32(b) == AV_RN32("XPDS"))

        return AVPROBE_SCORE_EXTENSION + 1;

    return 0;

}


static int yop_read_seek(AVFormatContext *s, int stream_index,

                         int64_t timestamp, int flags)

{

    YopDecContext *yop = s->priv_data;

    int64_t frame_pos, pos_min, pos_max;

    int frame_count;

    av_free_packet(&yop->video_packet);

    if (!stream_index)

        return -1;

    pos_min        = s->data_offset;

    pos_max        = avio_size(s->pb) - yop->frame_size;

    frame_count    = (pos_max - pos_min) / yop->frame_size;

    timestamp      = FFMAX(0, FFMIN(frame_count, timestamp));

    frame_pos      = timestamp * yop->frame_size + pos_min;

    yop->odd_frame = timestamp & 1;

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

    return 0;

}


static int film_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

    FilmDemuxContext *film = s->priv_data;

    AVIOContext *pb = s->pb;

    film_sample *sample;

    int ret = 0;

    int i;

    int left, right;

    if (film->current_sample >= film->sample_count)

        return AVERROR(EIO);

    sample = &film->sample_table[film->current_sample];

    /* position the stream (will probably be there anyway) */

    avio_seek(pb, sample->sample_offset, SEEK_SET);

    /* do a special song and dance when loading FILM Cinepak chunks */

    if ((sample->stream == film->video_stream_index) &&

        (film->video_type == AV_CODEC_ID_CINEPAK)) {

        pkt->pos= avio_tell(pb);

        if (av_new_packet(pkt, sample->sample_size))

            return AVERROR(ENOMEM);

        avio_read(pb, pkt->data, sample->sample_size);

    } else if ((sample->stream == film->audio_stream_index) &&

        (film->audio_channels == 2) &&

        (film->audio_type != AV_CODEC_ID_ADPCM_ADX)) {

        /* stereo PCM needs to be interleaved */

        if (av_new_packet(pkt, sample->sample_size))

            return AVERROR(ENOMEM);

        /* make sure the interleave buffer is large enough */

        if (sample->sample_size > film->stereo_buffer_size) {

            av_free(film->stereo_buffer);

            film->stereo_buffer_size = sample->sample_size;

            film->stereo_buffer = av_malloc(film->stereo_buffer_size);

            if (!film->stereo_buffer) {

                film->stereo_buffer_size = 0;

                return AVERROR(ENOMEM);

            }

        }

        pkt->pos= avio_tell(pb);

        ret = avio_read(pb, film->stereo_buffer, sample->sample_size);

        if (ret != sample->sample_size)

            ret = AVERROR(EIO);

        left = 0;

        right = sample->sample_size / 2;

        for (i = 0; i < sample->sample_size; ) {

            if (film->audio_bits == 8) {

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[right++];

            } else {

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[right++];

                pkt->data[i++] = film->stereo_buffer[right++];

            }

        }

    } else {

        ret= av_get_packet(pb, pkt, sample->sample_size);

        if (ret != sample->sample_size)

            ret = AVERROR(EIO);

    }

    pkt->stream_index = sample->stream;

    pkt->pts = sample->pts;

    film->current_sample++;

    return ret;

}


void qdist_init(struct qdist *dist)

{

    dist->entries = g_malloc(sizeof(*dist->entries));

    dist->size = 1;

    dist->n = 0;

}


void arm_v7m_cpu_do_interrupt(CPUState *cs)

{

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    uint32_t lr;

    arm_log_exception(cs->exception_index);

    /* For exceptions we just mark as pending on the NVIC, and let that

       handle it.  */

    switch (cs->exception_index) {

    case EXCP_UDEF:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_UNDEFINSTR_MASK;

        break;

    case EXCP_NOCP:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_NOCP_MASK;

        break;

    case EXCP_INVSTATE:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE, env->v7m.secure);

        env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_INVSTATE_MASK;

        break;

    case EXCP_SWI:

        /* The PC already points to the next instruction.  */

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC, env->v7m.secure);

        break;

    case EXCP_PREFETCH_ABORT:

    case EXCP_DATA_ABORT:

        /* Note that for M profile we don't have a guest facing FSR, but

         * the env->exception.fsr will be populated by the code that

         * raises the fault, in the A profile short-descriptor format.

         */

        switch (env->exception.fsr & 0xf) {

        case 0x8: /* External Abort */

            switch (cs->exception_index) {

            case EXCP_PREFETCH_ABORT:

                env->v7m.cfsr[M_REG_NS] |= R_V7M_CFSR_IBUSERR_MASK;

                qemu_log_mask(CPU_LOG_INT, "...with CFSR.IBUSERR\n");

                break;

            case EXCP_DATA_ABORT:

                env->v7m.cfsr[M_REG_NS] |=

                    (R_V7M_CFSR_PRECISERR_MASK | R_V7M_CFSR_BFARVALID_MASK);

                env->v7m.bfar = env->exception.vaddress;

                qemu_log_mask(CPU_LOG_INT,

                              "...with CFSR.PRECISERR and BFAR 0x%x\n",

                              env->v7m.bfar);

                break;

            }

            armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_BUS, false);

            break;

        default:

            /* All other FSR values are either MPU faults or "can't happen

             * for M profile" cases.

             */

            switch (cs->exception_index) {

            case EXCP_PREFETCH_ABORT:

                env->v7m.cfsr[env->v7m.secure] |= R_V7M_CFSR_IACCVIOL_MASK;

                qemu_log_mask(CPU_LOG_INT, "...with CFSR.IACCVIOL\n");

                break;

            case EXCP_DATA_ABORT:

                env->v7m.cfsr[env->v7m.secure] |=

                    (R_V7M_CFSR_DACCVIOL_MASK | R_V7M_CFSR_MMARVALID_MASK);

                env->v7m.mmfar[env->v7m.secure] = env->exception.vaddress;

                qemu_log_mask(CPU_LOG_INT,

                              "...with CFSR.DACCVIOL and MMFAR 0x%x\n",

                              env->v7m.mmfar[env->v7m.secure]);

                break;

            }

            armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM,

                                    env->v7m.secure);

            break;

        }

        break;

    case EXCP_BKPT:

        if (semihosting_enabled()) {

            int nr;

            nr = arm_lduw_code(env, env->regs[15], arm_sctlr_b(env)) & 0xff;

            if (nr == 0xab) {

                env->regs[15] += 2;

                qemu_log_mask(CPU_LOG_INT,

                              "...handling as semihosting call 0x%x\n",

                              env->regs[0]);

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG, false);

        break;

    case EXCP_IRQ:

        break;

    case EXCP_EXCEPTION_EXIT:

        do_v7m_exception_exit(cpu);

        return;

    default:

        cpu_abort(cs, "Unhandled exception 0x%x\n", cs->exception_index);

        return; /* Never happens.  Keep compiler happy.  */

    }

    lr = R_V7M_EXCRET_RES1_MASK |

        R_V7M_EXCRET_S_MASK |

        R_V7M_EXCRET_DCRS_MASK |

        R_V7M_EXCRET_FTYPE_MASK |

        R_V7M_EXCRET_ES_MASK;

    if (env->v7m.control[env->v7m.secure] & R_V7M_CONTROL_SPSEL_MASK) {

        lr |= R_V7M_EXCRET_SPSEL_MASK;

    }

    if (!arm_v7m_is_handler_mode(env)) {

        lr |= R_V7M_EXCRET_MODE_MASK;

    }

    v7m_push_stack(cpu);

    v7m_exception_taken(cpu, lr);

    qemu_log_mask(CPU_LOG_INT, "... as %d\n", env->v7m.exception);

}


static void socket_sendf(int fd, const char *fmt, va_list ap)

{

    gchar *str;

    size_t size, offset;

    str = g_strdup_vprintf(fmt, ap);

    size = strlen(str);

    offset = 0;

    while (offset < size) {

        ssize_t len;

        len = write(fd, str + offset, size - offset);

        if (len == -1 && errno == EINTR) {

            continue;

        }

        g_assert_no_errno(len);

        g_assert_cmpint(len, >, 0);

        offset += len;

    }

}


int vhost_dev_init(struct vhost_dev *hdev, int devfd, bool force)

{

    uint64_t features;

    int r;

    if (devfd >= 0) {

        hdev->control = devfd;

    } else {

        hdev->control = open("/dev/vhost-net", O_RDWR);

        if (hdev->control < 0) {

            return -errno;

        }

    }

    r = ioctl(hdev->control, VHOST_SET_OWNER, NULL);

    if (r < 0) {

        goto fail;

    }

    r = ioctl(hdev->control, VHOST_GET_FEATURES, &features);

    if (r < 0) {

        goto fail;

    }

    hdev->features = features;

    hdev->client.set_memory = vhost_client_set_memory;

    hdev->client.sync_dirty_bitmap = vhost_client_sync_dirty_bitmap;

    hdev->client.migration_log = vhost_client_migration_log;

    hdev->client.log_start = NULL;

    hdev->client.log_stop = NULL;

    hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));

    hdev->log = NULL;

    hdev->log_size = 0;

    hdev->log_enabled = false;

    hdev->started = false;

    cpu_register_phys_memory_client(&hdev->client);

    hdev->force = force;

    return 0;

fail:

    r = -errno;

    close(hdev->control);

    return r;

}


static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst,

                                        int dstWidth, const uint8_t *src1,

                                        const uint8_t *src2, int srcW, int xInc)

{

#if ARCH_X86

#if COMPILE_TEMPLATE_MMX2

    int32_t *filterPos = c->hChrFilterPos;

    int16_t *filter    = c->hChrFilter;

    int     canMMX2BeUsed  = c->canMMX2BeUsed;

    void    *mmx2FilterCode= c->chrMmx2FilterCode;

    int i;

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

    if (canMMX2BeUsed) {

        __asm__ volatile(

#if defined(PIC)

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

#endif

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

            "mov                 %0, %%"REG_c"  \n\t"

            "mov                 %1, %%"REG_D"  \n\t"

            "mov                 %2, %%"REG_d"  \n\t"

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

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

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

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

            "mov                 %5, %%"REG_c"  \n\t" // src

            "mov                 %1, %%"REG_D"  \n\t" // buf1

            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

            CALL_MMX2_FILTER_CODE

#if defined(PIC)

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

#endif

            :: "m" (src1), "m" (dst), "m" (filter), "m" (filterPos),

            "m" (mmx2FilterCode), "m" (src2)

#if defined(PIC)

            ,"m" (ebxsave)

#endif

            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

            ,"%"REG_b

#endif

        );

        for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {

            //printf("%d %d %d\n", dstWidth, i, srcW);

            dst[i] = src1[srcW-1]*128;

            dst[i+VOFW] = src2[srcW-1]*128;

        }

    } else {

#endif /* COMPILE_TEMPLATE_MMX2 */

        x86_reg dstWidth_reg = dstWidth;

        x86_reg xInc_shr16 = (x86_reg) (xInc >> 16);

        uint16_t xInc_mask = xInc & 0xffff;

        __asm__ volatile(

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

            "xor %%"REG_d", %%"REG_d"               \n\t" // xx

            "xorl    %%ecx, %%ecx                   \n\t" // xalpha

            ASMALIGN(4)

            "1:                                     \n\t"

            "mov        %0, %%"REG_S"               \n\t"

            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]

            "movzbl 1(%%"REG_S", %%"REG_d"), %%esi  \n\t" //src[xx+1]

            FAST_BILINEAR_X86

            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"

            "movzbl    (%5, %%"REG_d"), %%edi       \n\t" //src[xx]

            "movzbl   1(%5, %%"REG_d"), %%esi       \n\t" //src[xx+1]

            FAST_BILINEAR_X86

            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"

            "addw       %4, %%cx                    \n\t" //xalpha += xInc&0xFFFF

            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>16 + carry

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

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

            " jb        1b                          \n\t"

/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,

which is needed to support GCC 4.0. */

#if ARCH_X86_64 && AV_GCC_VERSION_AT_LEAST(3,4)

            :: "m" (src1), "m" (dst), "g" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),

#else

            :: "m" (src1), "m" (dst), "m" (dstWidth_reg), "m" (xInc_shr16), "m" (xInc_mask),

#endif

            "r" (src2)

            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

        );

#if COMPILE_TEMPLATE_MMX2

    } //if MMX2 can't be used

#endif

#else

    int i;

    unsigned int xpos=0;

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

        register unsigned int xx=xpos>>16;

        register unsigned int xalpha=(xpos&0xFFFF)>>9;

        dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

        dst[i+VOFW]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

        /* slower

        dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;

        dst[i+VOFW]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;

        */

        xpos+=xInc;

    }

#endif /* ARCH_X86 */

}


static int decode_mb_info(IVI45DecContext *ctx, IVIBandDesc *band,
                          IVITile *tile, AVCodecContext *avctx)
{
    int         x, y, mv_x, mv_y, mv_delta, offs, mb_offset,
                mv_scale, blks_per_mb;
    IVIMbInfo   *mb, *ref_mb;
    int         row_offset = band->mb_size * band->pitch;
    mb     = tile->mbs;
    ref_mb = tile->ref_mbs;
    offs   = tile->ypos * band->pitch + tile->xpos;
    if (!ref_mb &&
        ((band->qdelta_present && band->inherit_qdelta) || band->inherit_mv))
    /* scale factor for motion vectors */
    mv_scale = (ctx->planes[0].bands[0].mb_size >> 3) - (band->mb_size >> 3);
    mv_x = mv_y = 0;
    for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) {
        mb_offset = offs;
        for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) {
            mb->xpos     = x;
            mb->ypos     = y;
            mb->buf_offs = mb_offset;
            if (get_bits1(&ctx->gb)) {
                if (ctx->frame_type == FRAMETYPE_INTRA) {
                    av_log(avctx, AV_LOG_ERROR, "Empty macroblock in an INTRA picture!\n");
                    return -1;
                mb->type = 1; /* empty macroblocks are always INTER */
                mb->cbp  = 0; /* all blocks are empty */
                mb->q_delta = 0;
                if (!band->plane && !band->band_num && (ctx->frame_flags & 8)) {
                    mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                           IVI_VLC_BITS, 1);
                    mb->q_delta = IVI_TOSIGNED(mb->q_delta);
                mb->mv_x = mb->mv_y = 0; /* no motion vector coded */
                if (band->inherit_mv){
                    /* motion vector inheritance */
                    if (mv_scale) {
                        mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
                        mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
                    } else {
                        mb->mv_x = ref_mb->mv_x;
                        mb->mv_y = ref_mb->mv_y;
            } else {
                if (band->inherit_mv) {
                    mb->type = ref_mb->type; /* copy mb_type from corresponding reference mb */
                } else if (ctx->frame_type == FRAMETYPE_INTRA) {
                    mb->type = 0; /* mb_type is always INTRA for intra-frames */
                } else {
                    mb->type = get_bits1(&ctx->gb);
                blks_per_mb = band->mb_size != band->blk_size ? 4 : 1;
                mb->cbp = get_bits(&ctx->gb, blks_per_mb);
                mb->q_delta = 0;
                if (band->qdelta_present) {
                    if (band->inherit_qdelta) {
                        if (ref_mb) mb->q_delta = ref_mb->q_delta;
                    } else if (mb->cbp || (!band->plane && !band->band_num &&
                                           (ctx->frame_flags & 8))) {
                        mb->q_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                               IVI_VLC_BITS, 1);
                        mb->q_delta = IVI_TOSIGNED(mb->q_delta);
                if (!mb->type) {
                    mb->mv_x = mb->mv_y = 0; /* there is no motion vector in intra-macroblocks */
                } else {
                    if (band->inherit_mv){
                        /* motion vector inheritance */
                        if (mv_scale) {
                            mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);
                            mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);
                        } else {
                            mb->mv_x = ref_mb->mv_x;
                            mb->mv_y = ref_mb->mv_y;
                    } else {
                        /* decode motion vector deltas */
                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                            IVI_VLC_BITS, 1);
                        mv_y += IVI_TOSIGNED(mv_delta);
                        mv_delta = get_vlc2(&ctx->gb, ctx->mb_vlc.tab->table,
                                            IVI_VLC_BITS, 1);
                        mv_x += IVI_TOSIGNED(mv_delta);
                        mb->mv_x = mv_x;
                        mb->mv_y = mv_y;
            mb++;
            if (ref_mb)
                ref_mb++;
            mb_offset += band->mb_size;
        offs += row_offset;
    align_get_bits(&ctx->gb);
    return 0;


static void decode_nal_sei_frame_packing_arrangement(HEVCContext *s)

{

    GetBitContext *gb = &s->HEVClc->gb;

    int cancel, type, quincunx, content;

    get_ue_golomb(gb);                  // frame_packing_arrangement_id

    cancel = get_bits1(gb);             // frame_packing_cancel_flag

    if (cancel == 0) {

        type     = get_bits(gb, 7);     // frame_packing_arrangement_type

        quincunx = get_bits1(gb);       // quincunx_sampling_flag

        content  = get_bits(gb, 6);     // content_interpretation_type

        // the following skips spatial_flipping_flag frame0_flipped_flag

        // field_views_flag current_frame_is_frame0_flag

        // frame0_self_contained_flag frame1_self_contained_flag

        skip_bits(gb, 6);

        if (quincunx == 0 && type != 5)

            skip_bits(gb, 16);  // frame[01]_grid_position_[xy]

        skip_bits(gb, 8);       // frame_packing_arrangement_reserved_byte

        skip_bits1(gb);         // frame_packing_arrangement_persistance_flag

    }

    skip_bits1(gb);             // upsampled_aspect_ratio_flag

    s->sei_frame_packing_present      = (cancel == 0);

    s->frame_packing_arrangement_type = type;

    s->content_interpretation_type    = content;

    s->quincunx_subsampling           = quincunx;

}


static int gdb_get_spe_reg(CPUState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

#if defined(TARGET_PPC64)

        stl_p(mem_buf, env->gpr[n] >> 32);

#else

        stl_p(mem_buf, env->gprh[n]);

#endif

        return 4;

    }

    if (n == 33) {

        stq_p(mem_buf, env->spe_acc);

        return 8;

    }

    if (n == 34) {

        /* SPEFSCR not implemented */

        memset(mem_buf, 0, 4);

        return 4;

    }

    return 0;

}


static void virtio_pci_device_unplugged(DeviceState *d)

{

    PCIDevice *pci_dev = PCI_DEVICE(d);

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    virtio_pci_stop_ioeventfd(proxy);

    msix_uninit_exclusive_bar(pci_dev);

}


static int virtio_pci_stop_ioeventfd(VirtIOPCIProxy *proxy)

{

    int n;

    if (!proxy->ioeventfd_started) {

        return 0;

    }

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

        if (!virtio_queue_get_num(proxy->vdev, n)) {

            continue;

        }

        virtio_pci_set_host_notifier_fd_handler(proxy, n, false);

        virtio_pci_set_host_notifier_internal(proxy, n, false);

    }

    proxy->ioeventfd_started = false;

    return 0;

}


static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)

{

    int ret, clen;

    s->zstream.avail_out = len;

    s->zstream.next_out = buf;

    while (s->zstream.avail_out > 0) {

        if (s->zstream.avail_in == 0) {

            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)

                return -1;

            clen = qemu_get_be16(s->f);

            if (clen > IOBUF_SIZE)

                return -1;

            qemu_get_buffer(s->f, s->buf, clen);

            s->zstream.avail_in = clen;

            s->zstream.next_in = s->buf;

        }

        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);

        if (ret != Z_OK && ret != Z_STREAM_END) {

            return -1;

        }

    }

    return 0;

}


void avfilter_free(AVFilterContext *filter)

{

    int i;

    AVFilterLink *link;

    if (filter->filter->uninit)

        filter->filter->uninit(filter);

    for (i = 0; i < filter->input_count; i++) {

        if ((link = filter->inputs[i])) {

            if (link->src)

                link->src->outputs[link->srcpad - link->src->output_pads] = NULL;

            avfilter_formats_unref(&link->in_formats);

            avfilter_formats_unref(&link->out_formats);

        }

        av_freep(&link);

    }

    for (i = 0; i < filter->output_count; i++) {

        if ((link = filter->outputs[i])) {

            if (link->dst)

                link->dst->inputs[link->dstpad - link->dst->input_pads] = NULL;

            avfilter_formats_unref(&link->in_formats);

            avfilter_formats_unref(&link->out_formats);

        }

        av_freep(&link);

    }

    av_freep(&filter->name);

    av_freep(&filter->input_pads);

    av_freep(&filter->output_pads);

    av_freep(&filter->inputs);

    av_freep(&filter->outputs);

    av_freep(&filter->priv);

    av_free(filter);

}


void gtk_display_init(DisplayState *ds)

{

    GtkDisplayState *s = g_malloc0(sizeof(*s));

    gtk_init(NULL, NULL);

    ds->opaque = s;

    s->ds = ds;

    s->dcl.ops = &dcl_ops;

    s->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

#if GTK_CHECK_VERSION(3, 2, 0)

    s->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);

#else

    s->vbox = gtk_vbox_new(FALSE, 0);

#endif

    s->notebook = gtk_notebook_new();

    s->drawing_area = gtk_drawing_area_new();

    s->menu_bar = gtk_menu_bar_new();

    s->scale_x = 1.0;

    s->scale_y = 1.0;

    s->free_scale = FALSE;

    setlocale(LC_ALL, "");

    bindtextdomain("qemu", CONFIG_QEMU_LOCALEDIR);

    textdomain("qemu");

    s->null_cursor = gdk_cursor_new(GDK_BLANK_CURSOR);

    s->mouse_mode_notifier.notify = gd_mouse_mode_change;

    qemu_add_mouse_mode_change_notifier(&s->mouse_mode_notifier);

    qemu_add_vm_change_state_handler(gd_change_runstate, s);

    gtk_notebook_append_page(GTK_NOTEBOOK(s->notebook), s->drawing_area, gtk_label_new("VGA"));

    gd_create_menus(s);

    gd_connect_signals(s);

    gtk_widget_add_events(s->drawing_area,

                          GDK_POINTER_MOTION_MASK |

                          GDK_BUTTON_PRESS_MASK |

                          GDK_BUTTON_RELEASE_MASK |

                          GDK_BUTTON_MOTION_MASK |

                          GDK_ENTER_NOTIFY_MASK |

                          GDK_LEAVE_NOTIFY_MASK |

                          GDK_SCROLL_MASK |

                          GDK_KEY_PRESS_MASK);

    gtk_widget_set_double_buffered(s->drawing_area, FALSE);

    gtk_widget_set_can_focus(s->drawing_area, TRUE);

    gtk_notebook_set_show_tabs(GTK_NOTEBOOK(s->notebook), FALSE);

    gtk_notebook_set_show_border(GTK_NOTEBOOK(s->notebook), FALSE);

    gd_update_caption(s);

    gtk_box_pack_start(GTK_BOX(s->vbox), s->menu_bar, FALSE, TRUE, 0);

    gtk_box_pack_start(GTK_BOX(s->vbox), s->notebook, TRUE, TRUE, 0);

    gtk_container_add(GTK_CONTAINER(s->window), s->vbox);

    gtk_widget_show_all(s->window);

    register_displaychangelistener(ds, &s->dcl);

    global_state = s;

}


void vnc_display_init(DisplayState *ds)

{

    VncDisplay *vs = g_malloc0(sizeof(*vs));

    dcl = g_malloc0(sizeof(DisplayChangeListener));

    ds->opaque = vs;

    dcl->idle = 1;

    vnc_display = vs;

    vs->lsock = -1;

#ifdef CONFIG_VNC_WS

    vs->lwebsock = -1;

#endif

    vs->ds = ds;

    QTAILQ_INIT(&vs->clients);

    vs->expires = TIME_MAX;

    if (keyboard_layout)

        vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);

    else

        vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");

    if (!vs->kbd_layout)

        exit(1);

    qemu_mutex_init(&vs->mutex);

    vnc_start_worker_thread();

    dcl->ops = &dcl_ops;

    register_displaychangelistener(ds, dcl);

}


static int mpegts_handle_packet(AVFormatContext *ctx, PayloadContext *data,

                                AVStream *st, AVPacket *pkt, uint32_t *timestamp,

                                const uint8_t *buf, int len, uint16_t seq,

                                int flags)

{

    int ret;

    // We don't want to use the RTP timestamps at all. If the mpegts demuxer

    // doesn't set any pts/dts, the generic rtpdec code shouldn't try to

    // fill it in either, since the mpegts and RTP timestamps are in totally

    // different ranges.

    *timestamp = RTP_NOTS_VALUE;

    if (!data->ts)

        return AVERROR(EINVAL);

    if (!buf) {

        if (data->read_buf_index >= data->read_buf_size)

            return AVERROR(EAGAIN);

        ret = ff_mpegts_parse_packet(data->ts, pkt, data->buf + data->read_buf_index,

                                     data->read_buf_size - data->read_buf_index);

        if (ret < 0)

            return AVERROR(EAGAIN);

        data->read_buf_index += ret;

        if (data->read_buf_index < data->read_buf_size)

            return 1;

        else

            return 0;

    }

    ret = ff_mpegts_parse_packet(data->ts, pkt, buf, len);

    /* The only error that can be returned from ff_mpegts_parse_packet

     * is "no more data to return from the provided buffer", so return

     * AVERROR(EAGAIN) for all errors */

    if (ret < 0)

        return AVERROR(EAGAIN);

    if (ret < len) {

        data->read_buf_size = FFMIN(len - ret, sizeof(data->buf));

        memcpy(data->buf, buf + ret, data->read_buf_size);

        data->read_buf_index = 0;

        return 1;

    }

    return 0;

}


static int monitor_fdset_dup_fd_find_remove(int dup_fd, bool remove)

{

    MonFdset *mon_fdset;

    MonFdsetFd *mon_fdset_fd_dup;

    QLIST_FOREACH(mon_fdset, &mon_fdsets, next) {

        QLIST_FOREACH(mon_fdset_fd_dup, &mon_fdset->dup_fds, next) {

            if (mon_fdset_fd_dup->fd == dup_fd) {

                if (remove) {

                    QLIST_REMOVE(mon_fdset_fd_dup, next);

                    if (QLIST_EMPTY(&mon_fdset->dup_fds)) {

                        monitor_fdset_cleanup(mon_fdset);

                    }

                }

                return mon_fdset->id;

            }

        }

    }

    return -1;

}


static always_inline void powerpc_excp (CPUState *env,

                                        int excp_model, int excp)

{

    target_ulong msr, new_msr, vector;

    int srr0, srr1, asrr0, asrr1;

#if defined(TARGET_PPC64H)

    int lpes0, lpes1, lev;

    lpes0 = (env->spr[SPR_LPCR] >> 1) & 1;

    lpes1 = (env->spr[SPR_LPCR] >> 2) & 1;

#endif

    if (loglevel & CPU_LOG_INT) {

        fprintf(logfile, "Raise exception at 0x" ADDRX " => 0x%08x (%02x)\n",

                env->nip, excp, env->error_code);

    }

    msr = env->msr;

    new_msr = msr;

    srr0 = SPR_SRR0;

    srr1 = SPR_SRR1;

    asrr0 = -1;

    asrr1 = -1;

    msr &= ~((target_ulong)0x783F0000);

    switch (excp) {

    case POWERPC_EXCP_NONE:

        /* Should never happen */

        return;

    case POWERPC_EXCP_CRITICAL:    /* Critical input                         */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        switch (excp_model) {

        case POWERPC_EXCP_40x:

            srr0 = SPR_40x_SRR2;

            srr1 = SPR_40x_SRR3;

            break;

        case POWERPC_EXCP_BOOKE:

            srr0 = SPR_BOOKE_CSRR0;

            srr1 = SPR_BOOKE_CSRR1;

            break;

        case POWERPC_EXCP_G2:

            break;

        default:

            goto excp_invalid;

        }

        goto store_next;

    case POWERPC_EXCP_MCHECK:    /* Machine check exception                  */

        if (msr_me == 0) {

            /* Machine check exception is not enabled.

             * Enter checkstop state.

             */

            if (loglevel != 0) {

                fprintf(logfile, "Machine check while not allowed. "

                        "Entering checkstop state\n");

            } else {

                fprintf(stderr, "Machine check while not allowed. "

                        "Entering checkstop state\n");

            }

            env->halted = 1;

            env->interrupt_request |= CPU_INTERRUPT_EXITTB;

        }

        new_msr &= ~((target_ulong)1 << MSR_RI);

        new_msr &= ~((target_ulong)1 << MSR_ME);

#if defined(TARGET_PPC64H)

        new_msr |= (target_ulong)1 << MSR_HV;

#endif

        /* XXX: should also have something loaded in DAR / DSISR */

        switch (excp_model) {

        case POWERPC_EXCP_40x:

            srr0 = SPR_40x_SRR2;

            srr1 = SPR_40x_SRR3;

            break;

        case POWERPC_EXCP_BOOKE:

            srr0 = SPR_BOOKE_MCSRR0;

            srr1 = SPR_BOOKE_MCSRR1;

            asrr0 = SPR_BOOKE_CSRR0;

            asrr1 = SPR_BOOKE_CSRR1;

            break;

        default:

            break;

        }

        goto store_next;

    case POWERPC_EXCP_DSI:       /* Data storage exception                   */

#if defined (DEBUG_EXCEPTIONS)

        if (loglevel != 0) {

            fprintf(logfile, "DSI exception: DSISR=0x" ADDRX" DAR=0x" ADDRX

                    "\n", env->spr[SPR_DSISR], env->spr[SPR_DAR]);

        }

#endif

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

    case POWERPC_EXCP_ISI:       /* Instruction storage exception            */

#if defined (DEBUG_EXCEPTIONS)

        if (loglevel != 0) {

            fprintf(logfile, "ISI exception: msr=0x" ADDRX ", nip=0x" ADDRX

                    "\n", msr, env->nip);

        }

#endif

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        msr |= env->error_code;

        goto store_next;

    case POWERPC_EXCP_EXTERNAL:  /* External input                           */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes0 == 1)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

    case POWERPC_EXCP_ALIGN:     /* Alignment exception                      */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        /* XXX: this is false */

        /* Get rS/rD and rA from faulting opcode */

        env->spr[SPR_DSISR] |= (ldl_code((env->nip - 4)) & 0x03FF0000) >> 16;

        goto store_current;

    case POWERPC_EXCP_PROGRAM:   /* Program exception                        */

        switch (env->error_code & ~0xF) {

        case POWERPC_EXCP_FP:

            if ((msr_fe0 == 0 && msr_fe1 == 0) || msr_fp == 0) {

#if defined (DEBUG_EXCEPTIONS)

                if (loglevel != 0) {

                    fprintf(logfile, "Ignore floating point exception\n");

                }

#endif

                env->exception_index = POWERPC_EXCP_NONE;

                env->error_code = 0;

                return;

            }

            new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

            if (lpes1 == 0)

                new_msr |= (target_ulong)1 << MSR_HV;

#endif

            msr |= 0x00100000;

            if (msr_fe0 == msr_fe1)

                goto store_next;

            msr |= 0x00010000;

            break;

        case POWERPC_EXCP_INVAL:

#if defined (DEBUG_EXCEPTIONS)

            if (loglevel != 0) {

                fprintf(logfile, "Invalid instruction at 0x" ADDRX "\n",

                        env->nip);

            }

#endif

            new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

            if (lpes1 == 0)

                new_msr |= (target_ulong)1 << MSR_HV;

#endif

            msr |= 0x00080000;

            break;

        case POWERPC_EXCP_PRIV:

            new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

            if (lpes1 == 0)

                new_msr |= (target_ulong)1 << MSR_HV;

#endif

            msr |= 0x00040000;

            break;

        case POWERPC_EXCP_TRAP:

            new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

            if (lpes1 == 0)

                new_msr |= (target_ulong)1 << MSR_HV;

#endif

            msr |= 0x00020000;

            break;

        default:

            /* Should never occur */

            cpu_abort(env, "Invalid program exception %d. Aborting\n",

                      env->error_code);

            break;

        }

        goto store_current;

    case POWERPC_EXCP_FPU:       /* Floating-point unavailable exception     */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_current;

    case POWERPC_EXCP_SYSCALL:   /* System call exception                    */

        /* NOTE: this is a temporary hack to support graphics OSI

           calls from the MOL driver */

        /* XXX: To be removed */

        if (env->gpr[3] == 0x113724fa && env->gpr[4] == 0x77810f9b &&

            env->osi_call) {

            if (env->osi_call(env) != 0) {

                env->exception_index = POWERPC_EXCP_NONE;

                env->error_code = 0;

                return;

            }

        }

        if (loglevel & CPU_LOG_INT) {

            dump_syscall(env);

        }

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        lev = env->error_code;

        if (lev == 1 || (lpes0 == 0 && lpes1 == 0))

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

    case POWERPC_EXCP_APU:       /* Auxiliary processor unavailable          */

        new_msr &= ~((target_ulong)1 << MSR_RI);

        goto store_current;

    case POWERPC_EXCP_DECR:      /* Decrementer exception                    */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

    case POWERPC_EXCP_FIT:       /* Fixed-interval timer interrupt           */

        /* FIT on 4xx */

#if defined (DEBUG_EXCEPTIONS)

        if (loglevel != 0)

            fprintf(logfile, "FIT exception\n");

#endif

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_next;

    case POWERPC_EXCP_WDT:       /* Watchdog timer interrupt                 */

#if defined (DEBUG_EXCEPTIONS)

        if (loglevel != 0)

            fprintf(logfile, "WDT exception\n");

#endif

        switch (excp_model) {

        case POWERPC_EXCP_BOOKE:

            srr0 = SPR_BOOKE_CSRR0;

            srr1 = SPR_BOOKE_CSRR1;

            break;

        default:

            break;

        }

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_next;

    case POWERPC_EXCP_DTLB:      /* Data TLB error                           */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_next;

    case POWERPC_EXCP_ITLB:      /* Instruction TLB error                    */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_next;

    case POWERPC_EXCP_DEBUG:     /* Debug interrupt                          */

        switch (excp_model) {

        case POWERPC_EXCP_BOOKE:

            srr0 = SPR_BOOKE_DSRR0;

            srr1 = SPR_BOOKE_DSRR1;

            asrr0 = SPR_BOOKE_CSRR0;

            asrr1 = SPR_BOOKE_CSRR1;

            break;

        default:

            break;

        }

        /* XXX: TODO */

        cpu_abort(env, "Debug exception is not implemented yet !\n");

        goto store_next;

#if defined(TARGET_PPCEMB)

    case POWERPC_EXCP_SPEU:      /* SPE/embedded floating-point unavailable  */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_current;

    case POWERPC_EXCP_EFPDI:     /* Embedded floating-point data interrupt   */

        /* XXX: TODO */

        cpu_abort(env, "Embedded floating point data exception "

                  "is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_EFPRI:     /* Embedded floating-point round interrupt  */

        /* XXX: TODO */

        cpu_abort(env, "Embedded floating point round exception "

                  "is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_EPERFM:    /* Embedded performance monitor interrupt   */

        new_msr &= ~((target_ulong)1 << MSR_RI);

        /* XXX: TODO */

        cpu_abort(env,

                  "Performance counter exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_DOORI:     /* Embedded doorbell interrupt              */

        /* XXX: TODO */

        cpu_abort(env,

                  "Embedded doorbell interrupt is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_DOORCI:    /* Embedded doorbell critical interrupt     */

        switch (excp_model) {

        case POWERPC_EXCP_BOOKE:

            srr0 = SPR_BOOKE_CSRR0;

            srr1 = SPR_BOOKE_CSRR1;

            break;

        default:

            break;

        }

        /* XXX: TODO */

        cpu_abort(env, "Embedded doorbell critical interrupt "

                  "is not implemented yet !\n");

        goto store_next;

#endif /* defined(TARGET_PPCEMB) */

    case POWERPC_EXCP_RESET:     /* System reset exception                   */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

#if defined(TARGET_PPC64)

    case POWERPC_EXCP_DSEG:      /* Data segment exception                   */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

    case POWERPC_EXCP_ISEG:      /* Instruction segment exception            */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

#endif /* defined(TARGET_PPC64) */

#if defined(TARGET_PPC64H)

    case POWERPC_EXCP_HDECR:     /* Hypervisor decrementer exception         */

        srr0 = SPR_HSRR0;

        srr1 = SPR_HSRR1;

        new_msr |= (target_ulong)1 << MSR_HV;

        goto store_next;

#endif

    case POWERPC_EXCP_TRACE:     /* Trace exception                          */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_next;

#if defined(TARGET_PPC64H)

    case POWERPC_EXCP_HDSI:      /* Hypervisor data storage exception        */

        srr0 = SPR_HSRR0;

        srr1 = SPR_HSRR1;

        new_msr |= (target_ulong)1 << MSR_HV;

        goto store_next;

    case POWERPC_EXCP_HISI:      /* Hypervisor instruction storage exception */

        srr0 = SPR_HSRR0;

        srr1 = SPR_HSRR1;

        new_msr |= (target_ulong)1 << MSR_HV;

        goto store_next;

    case POWERPC_EXCP_HDSEG:     /* Hypervisor data segment exception        */

        srr0 = SPR_HSRR0;

        srr1 = SPR_HSRR1;

        new_msr |= (target_ulong)1 << MSR_HV;

        goto store_next;

    case POWERPC_EXCP_HISEG:     /* Hypervisor instruction segment exception */

        srr0 = SPR_HSRR0;

        srr1 = SPR_HSRR1;

        new_msr |= (target_ulong)1 << MSR_HV;

        goto store_next;

#endif /* defined(TARGET_PPC64H) */

    case POWERPC_EXCP_VPU:       /* Vector unavailable exception             */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        goto store_current;

    case POWERPC_EXCP_PIT:       /* Programmable interval timer interrupt    */

#if defined (DEBUG_EXCEPTIONS)

        if (loglevel != 0)

            fprintf(logfile, "PIT exception\n");

#endif

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

        goto store_next;

    case POWERPC_EXCP_IO:        /* IO error exception                       */

        /* XXX: TODO */

        cpu_abort(env, "601 IO error exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_RUNM:      /* Run mode exception                       */

        /* XXX: TODO */

        cpu_abort(env, "601 run mode exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_EMUL:      /* Emulation trap exception                 */

        /* XXX: TODO */

        cpu_abort(env, "602 emulation trap exception "

                  "is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_IFTLB:     /* Instruction fetch TLB error              */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

#if defined(TARGET_PPC64H) /* XXX: check this */

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        switch (excp_model) {

        case POWERPC_EXCP_602:

        case POWERPC_EXCP_603:

        case POWERPC_EXCP_603E:

        case POWERPC_EXCP_G2:

            goto tlb_miss_tgpr;

        case POWERPC_EXCP_7x5:

            goto tlb_miss;

        case POWERPC_EXCP_74xx:

            goto tlb_miss_74xx;

        default:

            cpu_abort(env, "Invalid instruction TLB miss exception\n");

            break;

        }

        break;

    case POWERPC_EXCP_DLTLB:     /* Data load TLB miss                       */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

#if defined(TARGET_PPC64H) /* XXX: check this */

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        switch (excp_model) {

        case POWERPC_EXCP_602:

        case POWERPC_EXCP_603:

        case POWERPC_EXCP_603E:

        case POWERPC_EXCP_G2:

            goto tlb_miss_tgpr;

        case POWERPC_EXCP_7x5:

            goto tlb_miss;

        case POWERPC_EXCP_74xx:

            goto tlb_miss_74xx;

        default:

            cpu_abort(env, "Invalid data load TLB miss exception\n");

            break;

        }

        break;

    case POWERPC_EXCP_DSTLB:     /* Data store TLB miss                      */

        new_msr &= ~((target_ulong)1 << MSR_RI); /* XXX: check this */

#if defined(TARGET_PPC64H) /* XXX: check this */

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        switch (excp_model) {

        case POWERPC_EXCP_602:

        case POWERPC_EXCP_603:

        case POWERPC_EXCP_603E:

        case POWERPC_EXCP_G2:

        tlb_miss_tgpr:

            /* Swap temporary saved registers with GPRs */

            if (!(new_msr & ((target_ulong)1 << MSR_TGPR))) {

                new_msr |= (target_ulong)1 << MSR_TGPR;

                hreg_swap_gpr_tgpr(env);

            }

            goto tlb_miss;

        case POWERPC_EXCP_7x5:

        tlb_miss:

#if defined (DEBUG_SOFTWARE_TLB)

            if (loglevel != 0) {

                const unsigned char *es;

                target_ulong *miss, *cmp;

                int en;

                if (excp == POWERPC_EXCP_IFTLB) {

                    es = "I";

                    en = 'I';

                    miss = &env->spr[SPR_IMISS];

                    cmp = &env->spr[SPR_ICMP];

                } else {

                    if (excp == POWERPC_EXCP_DLTLB)

                        es = "DL";

                    else

                        es = "DS";

                    en = 'D';

                    miss = &env->spr[SPR_DMISS];

                    cmp = &env->spr[SPR_DCMP];

                }

                fprintf(logfile, "6xx %sTLB miss: %cM " ADDRX " %cC " ADDRX

                        " H1 " ADDRX " H2 " ADDRX " %08x\n",

                        es, en, *miss, en, *cmp,

                        env->spr[SPR_HASH1], env->spr[SPR_HASH2],

                        env->error_code);

            }

#endif

            msr |= env->crf[0] << 28;

            msr |= env->error_code; /* key, D/I, S/L bits */

            /* Set way using a LRU mechanism */

            msr |= ((env->last_way + 1) & (env->nb_ways - 1)) << 17;

            break;

        case POWERPC_EXCP_74xx:

        tlb_miss_74xx:

#if defined (DEBUG_SOFTWARE_TLB)

            if (loglevel != 0) {

                const unsigned char *es;

                target_ulong *miss, *cmp;

                int en;

                if (excp == POWERPC_EXCP_IFTLB) {

                    es = "I";

                    en = 'I';

                    miss = &env->spr[SPR_TLBMISS];

                    cmp = &env->spr[SPR_PTEHI];

                } else {

                    if (excp == POWERPC_EXCP_DLTLB)

                        es = "DL";

                    else

                        es = "DS";

                    en = 'D';

                    miss = &env->spr[SPR_TLBMISS];

                    cmp = &env->spr[SPR_PTEHI];

                }

                fprintf(logfile, "74xx %sTLB miss: %cM " ADDRX " %cC " ADDRX

                        " %08x\n",

                        es, en, *miss, en, *cmp, env->error_code);

            }

#endif

            msr |= env->error_code; /* key bit */

            break;

        default:

            cpu_abort(env, "Invalid data store TLB miss exception\n");

            break;

        }

        goto store_next;

    case POWERPC_EXCP_FPA:       /* Floating-point assist exception          */

        /* XXX: TODO */

        cpu_abort(env, "Floating point assist exception "

                  "is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_IABR:      /* Instruction address breakpoint           */

        /* XXX: TODO */

        cpu_abort(env, "IABR exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_SMI:       /* System management interrupt              */

        /* XXX: TODO */

        cpu_abort(env, "SMI exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_THERM:     /* Thermal interrupt                        */

        /* XXX: TODO */

        cpu_abort(env, "Thermal management exception "

                  "is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_PERFM:     /* Embedded performance monitor interrupt   */

        new_msr &= ~((target_ulong)1 << MSR_RI);

#if defined(TARGET_PPC64H)

        if (lpes1 == 0)

            new_msr |= (target_ulong)1 << MSR_HV;

#endif

        /* XXX: TODO */

        cpu_abort(env,

                  "Performance counter exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_VPUA:      /* Vector assist exception                  */

        /* XXX: TODO */

        cpu_abort(env, "VPU assist exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_SOFTP:     /* Soft patch exception                     */

        /* XXX: TODO */

        cpu_abort(env,

                  "970 soft-patch exception is not implemented yet !\n");

        goto store_next;

    case POWERPC_EXCP_MAINT:     /* Maintenance exception                    */

        /* XXX: TODO */

        cpu_abort(env,

                  "970 maintenance exception is not implemented yet !\n");

        goto store_next;

    default:

    excp_invalid:

        cpu_abort(env, "Invalid PowerPC exception %d. Aborting\n", excp);

        break;

    store_current:

        /* save current instruction location */

        env->spr[srr0] = env->nip - 4;

        break;

    store_next:

        /* save next instruction location */

        env->spr[srr0] = env->nip;

        break;

    }

    /* Save MSR */

    env->spr[srr1] = msr;

    /* If any alternate SRR register are defined, duplicate saved values */

    if (asrr0 != -1)

        env->spr[asrr0] = env->spr[srr0];

    if (asrr1 != -1)

        env->spr[asrr1] = env->spr[srr1];

    /* If we disactivated any translation, flush TLBs */

    if (new_msr & ((1 << MSR_IR) | (1 << MSR_DR)))

        tlb_flush(env, 1);

    /* reload MSR with correct bits */

    new_msr &= ~((target_ulong)1 << MSR_EE);

    new_msr &= ~((target_ulong)1 << MSR_PR);

    new_msr &= ~((target_ulong)1 << MSR_FP);

    new_msr &= ~((target_ulong)1 << MSR_FE0);

    new_msr &= ~((target_ulong)1 << MSR_SE);

    new_msr &= ~((target_ulong)1 << MSR_BE);

    new_msr &= ~((target_ulong)1 << MSR_FE1);

    new_msr &= ~((target_ulong)1 << MSR_IR);

    new_msr &= ~((target_ulong)1 << MSR_DR);

#if 0 /* Fix this: not on all targets */

    new_msr &= ~((target_ulong)1 << MSR_PMM);

#endif

    new_msr &= ~((target_ulong)1 << MSR_LE);

    if (msr_ile)

        new_msr |= (target_ulong)1 << MSR_LE;

    else

        new_msr &= ~((target_ulong)1 << MSR_LE);

    /* Jump to handler */

    vector = env->excp_vectors[excp];

    if (vector == (target_ulong)-1) {

        cpu_abort(env, "Raised an exception without defined vector %d\n",

                  excp);

    }

    vector |= env->excp_prefix;

#if defined(TARGET_PPC64)

    if (excp_model == POWERPC_EXCP_BOOKE) {

        if (!msr_icm) {

            new_msr &= ~((target_ulong)1 << MSR_CM);

            vector = (uint32_t)vector;

        } else {

            new_msr |= (target_ulong)1 << MSR_CM;

        }

    } else {

        if (!msr_isf) {

            new_msr &= ~((target_ulong)1 << MSR_SF);

            vector = (uint32_t)vector;

        } else {

            new_msr |= (target_ulong)1 << MSR_SF;

        }

    }

#endif

    /* XXX: we don't use hreg_store_msr here as already have treated

     *      any special case that could occur. Just store MSR and update hflags

     */

    env->msr = new_msr;

    env->hflags_nmsr = 0x00000000;

    hreg_compute_hflags(env);

    env->nip = vector;

    /* Reset exception state */

    env->exception_index = POWERPC_EXCP_NONE;

    env->error_code = 0;

}


static void compute_default_clut(AVSubtitleRect *rect, int w, int h)

{

    uint8_t list[256] = {0};

    uint8_t list_inv[256];

    int counttab[256] = {0};

    int count, i, x, y;

#define V(x,y) rect->data[0][(x) + (y)*rect->linesize[0]]

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

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

            int v = V(x,y) + 1;

            int vl = x     ? V(x-1,y) + 1 : 0;

            int vr = x+1<w ? V(x+1,y) + 1 : 0;

            int vt = y     ? V(x,y-1) + 1 : 0;

            int vb = y+1<h ? V(x,y+1) + 1 : 0;

            counttab[v-1] += !!((v!=vl) + (v!=vr) + (v!=vt) + (v!=vb));

        }

    }

#define L(x,y) list[ rect->data[0][(x) + (y)*rect->linesize[0]] ]

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

        int scoretab[256] = {0};

        int bestscore = 0;

        int bestv = 0;

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

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

                int v = rect->data[0][x + y*rect->linesize[0]];

                int l_m = list[v];

                int l_l = x     ? L(x-1, y) : 1;

                int l_r = x+1<w ? L(x+1, y) : 1;

                int l_t = y     ? L(x, y-1) : 1;

                int l_b = y+1<h ? L(x, y+1) : 1;

                int score;

                if (l_m)

                    continue;

                scoretab[v] += l_l + l_r + l_t + l_b;

                score = 1024LL*scoretab[v] / counttab[v];

                if (score > bestscore) {

                    bestscore = score;

                    bestv = v;

                }

            }

        }

        if (!bestscore)

            break;

        list    [ bestv ] = 1;

        list_inv[     i ] = bestv;

    }

    count = i - 1;

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

        int v = i*255/count;

        AV_WN32(rect->data[1] + 4*list_inv[i], RGBA(v/2,v,v/2,v));

    }

}


static void qcow_close(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    g_free(s->l1_table);

    g_free(s->l2_cache);

    g_free(s->cluster_cache);

    g_free(s->cluster_data);

    migrate_del_blocker(s->migration_blocker);

    error_free(s->migration_blocker);

}


static int pvf_read_header(AVFormatContext *s)

{

    char buffer[32];

    AVStream *st;

    int bps, channels, sample_rate;

    avio_skip(s->pb, 5);

    ff_get_line(s->pb, buffer, sizeof(buffer));

    if (sscanf(buffer, "%d %d %d",

               &channels,

               &sample_rate,

               &bps) != 3)

        return AVERROR_INVALIDDATA;

    if (channels <= 0 || bps <= 0 || sample_rate <= 0)

        return AVERROR_INVALIDDATA;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;

    st->codecpar->channels    = channels;

    st->codecpar->sample_rate = sample_rate;

    st->codecpar->codec_id    = ff_get_pcm_codec_id(bps, 0, 1, 0xFFFF);

    st->codecpar->bits_per_coded_sample = bps;

    st->codecpar->block_align = bps * st->codecpar->channels / 8;

    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

    return 0;

}


iscsi_readv_writev_bh_cb(void *p)

{

    IscsiAIOCB *acb = p;

    qemu_bh_delete(acb->bh);

    if (!acb->canceled) {

        acb->common.cb(acb->common.opaque, acb->status);

    }

    qemu_aio_release(acb);

    if (acb->canceled) {

        return;

    }

    scsi_free_scsi_task(acb->task);

    acb->task = NULL;

}


static void vmmouse_reset(DeviceState *d)
{
    VMMouseState *s = container_of(d, VMMouseState, dev.qdev);
    s->status = 0xffff;
    s->queue_size = VMMOUSE_QUEUE_SIZE;
}


static int doTest(uint8_t *ref[4], int refStride[4], int w, int h,

                  enum AVPixelFormat srcFormat, enum AVPixelFormat dstFormat,

                  int srcW, int srcH, int dstW, int dstH, int flags,

                  struct Results *r)

{

    static enum AVPixelFormat cur_srcFormat;

    static int cur_srcW, cur_srcH;

    static uint8_t *src[4];

    static int srcStride[4];

    uint8_t *dst[4] = { 0 };

    uint8_t *out[4] = { 0 };

    int dstStride[4];

    int i;

    uint64_t ssdY, ssdU = 0, ssdV = 0, ssdA = 0;

    struct SwsContext *dstContext = NULL, *outContext = NULL;

    uint32_t crc = 0;

    int res      = 0;

    if (cur_srcFormat != srcFormat || cur_srcW != srcW || cur_srcH != srcH) {

        struct SwsContext *srcContext = NULL;

        int p;

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

            av_freep(&src[p]);

        av_image_fill_linesizes(srcStride, srcFormat, srcW);

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

            srcStride[p] = FFALIGN(srcStride[p], 16);

            if (srcStride[p])

                src[p] = av_mallocz(srcStride[p] * srcH + 16);

            if (srcStride[p] && !src[p]) {

                perror("Malloc");

                res = -1;

                goto end;

            }

        }

        srcContext = sws_getContext(w, h, AV_PIX_FMT_YUVA420P, srcW, srcH,

                                    srcFormat, SWS_BILINEAR, NULL, NULL, NULL);

        if (!srcContext) {

            fprintf(stderr, "Failed to get %s ---> %s\n",

                    av_pix_fmt_descriptors[AV_PIX_FMT_YUVA420P].name,

                    av_pix_fmt_descriptors[srcFormat].name);

            res = -1;

            goto end;

        }

        sws_scale(srcContext, ref, refStride, 0, h, src, srcStride);

        sws_freeContext(srcContext);

        cur_srcFormat = srcFormat;

        cur_srcW      = srcW;

        cur_srcH      = srcH;

    }

    av_image_fill_linesizes(dstStride, dstFormat, dstW);

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

        /* Image buffers passed into libswscale can be allocated any way you

         * prefer, as long as they're aligned enough for the architecture, and

         * they're freed appropriately (such as using av_free for buffers

         * allocated with av_malloc). */

        /* An extra 16 bytes is being allocated because some scalers may write

         * out of bounds. */

        dstStride[i] = FFALIGN(dstStride[i], 16);

        if (dstStride[i])

            dst[i] = av_mallocz(dstStride[i] * dstH + 16);

        if (dstStride[i] && !dst[i]) {

            perror("Malloc");

            res = -1;

            goto end;

        }

    }

    dstContext = sws_getContext(srcW, srcH, srcFormat, dstW, dstH, dstFormat,

                                flags, NULL, NULL, NULL);

    if (!dstContext) {

        fprintf(stderr, "Failed to get %s ---> %s\n",

                av_pix_fmt_descriptors[srcFormat].name,

                av_pix_fmt_descriptors[dstFormat].name);

        res = -1;

        goto end;

    }

    printf(" %s %dx%d -> %s %3dx%3d flags=%2d",

           av_pix_fmt_descriptors[srcFormat].name, srcW, srcH,

           av_pix_fmt_descriptors[dstFormat].name, dstW, dstH,

           flags);

    fflush(stdout);

    sws_scale(dstContext, src, srcStride, 0, srcH, dst, dstStride);

    for (i = 0; i < 4 && dstStride[i]; i++)

        crc = av_crc(av_crc_get_table(AV_CRC_32_IEEE), crc, dst[i],

                     dstStride[i] * dstH);

    if (r && crc == r->crc) {

        ssdY = r->ssdY;

        ssdU = r->ssdU;

        ssdV = r->ssdV;

        ssdA = r->ssdA;

    } else {

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

            refStride[i] = FFALIGN(refStride[i], 16);

            if (refStride[i])

                out[i] = av_mallocz(refStride[i] * h);

            if (refStride[i] && !out[i]) {

                perror("Malloc");

                res = -1;

                goto end;

            }

        }

        outContext = sws_getContext(dstW, dstH, dstFormat, w, h,

                                    AV_PIX_FMT_YUVA420P, SWS_BILINEAR,

                                    NULL, NULL, NULL);

        if (!outContext) {

            fprintf(stderr, "Failed to get %s ---> %s\n",

                    av_pix_fmt_descriptors[dstFormat].name,

                    av_pix_fmt_descriptors[AV_PIX_FMT_YUVA420P].name);

            res = -1;

            goto end;

        }

        sws_scale(outContext, dst, dstStride, 0, dstH, out, refStride);

        ssdY = getSSD(ref[0], out[0], refStride[0], refStride[0], w, h);

        if (hasChroma(srcFormat) && hasChroma(dstFormat)) {

            //FIXME check that output is really gray

            ssdU = getSSD(ref[1], out[1], refStride[1], refStride[1],

                          (w + 1) >> 1, (h + 1) >> 1);

            ssdV = getSSD(ref[2], out[2], refStride[2], refStride[2],

                          (w + 1) >> 1, (h + 1) >> 1);

        }

        if (isALPHA(srcFormat) && isALPHA(dstFormat))

            ssdA = getSSD(ref[3], out[3], refStride[3], refStride[3], w, h);

        ssdY /= w * h;

        ssdU /= w * h / 4;

        ssdV /= w * h / 4;

        ssdA /= w * h;

        sws_freeContext(outContext);

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

            if (refStride[i])

                av_free(out[i]);

    }

    printf(" CRC=%08x SSD=%5"PRId64 ",%5"PRId64 ",%5"PRId64 ",%5"PRId64 "\n",

           crc, ssdY, ssdU, ssdV, ssdA);

end:

    sws_freeContext(dstContext);

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

        if (dstStride[i])

            av_free(dst[i]);

    return res;

}


char *object_property_get_str(Object *obj, const char *name,

                              Error **errp)

{

    QObject *ret = object_property_get_qobject(obj, name, errp);

    QString *qstring;

    char *retval;

    if (!ret) {

        return NULL;

    }

    qstring = qobject_to_qstring(ret);

    if (!qstring) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name, "string");

        retval = NULL;

    } else {

        retval = g_strdup(qstring_get_str(qstring));

    }

    QDECREF(qstring);

    return retval;

}


ip_input(struct mbuf *m)

{

	Slirp *slirp = m->slirp;

	register struct ip *ip;

	int hlen;

	DEBUG_CALL("ip_input");

	DEBUG_ARG("m = %p", m);

	DEBUG_ARG("m_len = %d", m->m_len);

	if (m->m_len < sizeof (struct ip)) {

		return;

	}

	ip = mtod(m, struct ip *);

	if (ip->ip_v != IPVERSION) {

		goto bad;

	}

	hlen = ip->ip_hl << 2;

	if (hlen<sizeof(struct ip ) || hlen>m->m_len) {/* min header length */

	  goto bad;                                  /* or packet too short */

	}

        /* keep ip header intact for ICMP reply

	 * ip->ip_sum = cksum(m, hlen);

	 * if (ip->ip_sum) {

	 */

	if(cksum(m,hlen)) {

	  goto bad;

	}

	/*

	 * Convert fields to host representation.

	 */

	NTOHS(ip->ip_len);

	if (ip->ip_len < hlen) {

		goto bad;

	}

	NTOHS(ip->ip_id);

	NTOHS(ip->ip_off);

	/*

	 * Check that the amount of data in the buffers

	 * is as at least much as the IP header would have us expect.

	 * Trim mbufs if longer than we expect.

	 * Drop packet if shorter than we expect.

	 */

	if (m->m_len < ip->ip_len) {

		goto bad;

	}

	/* Should drop packet if mbuf too long? hmmm... */

	if (m->m_len > ip->ip_len)

	   m_adj(m, ip->ip_len - m->m_len);

	/* check ip_ttl for a correct ICMP reply */

	if (ip->ip_ttl == 0) {

	    icmp_send_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, 0, "ttl");

	    goto bad;

	}

	/*

	 * If offset or IP_MF are set, must reassemble.

	 * Otherwise, nothing need be done.

	 * (We could look in the reassembly queue to see

	 * if the packet was previously fragmented,

	 * but it's not worth the time; just let them time out.)

	 *

	 * XXX This should fail, don't fragment yet

	 */

	if (ip->ip_off &~ IP_DF) {

	  register struct ipq *fp;

      struct qlink *l;

		/*

		 * Look for queue of fragments

		 * of this datagram.

		 */

		for (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;

		     l = l->next) {

            fp = container_of(l, struct ipq, ip_link);

            if (ip->ip_id == fp->ipq_id &&

                    ip->ip_src.s_addr == fp->ipq_src.s_addr &&

                    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&

                    ip->ip_p == fp->ipq_p)

		    goto found;

        }

        fp = NULL;

	found:

		/*

		 * Adjust ip_len to not reflect header,

		 * set ip_mff if more fragments are expected,

		 * convert offset of this to bytes.

		 */

		ip->ip_len -= hlen;

		if (ip->ip_off & IP_MF)

		  ip->ip_tos |= 1;

		else

		  ip->ip_tos &= ~1;

		ip->ip_off <<= 3;

		/*

		 * If datagram marked as having more fragments

		 * or if this is not the first fragment,

		 * attempt reassembly; if it succeeds, proceed.

		 */

		if (ip->ip_tos & 1 || ip->ip_off) {

			ip = ip_reass(slirp, ip, fp);

                        if (ip == NULL)

				return;

			m = dtom(slirp, ip);

		} else

			if (fp)

		   	   ip_freef(slirp, fp);

	} else

		ip->ip_len -= hlen;

	/*

	 * Switch out to protocol's input routine.

	 */

	switch (ip->ip_p) {

	 case IPPROTO_TCP:

		tcp_input(m, hlen, (struct socket *)NULL, AF_INET);

		break;

	 case IPPROTO_UDP:

		udp_input(m, hlen);

		break;

	 case IPPROTO_ICMP:

		icmp_input(m, hlen);

		break;

	 default:

		m_free(m);

	}

	return;

bad:

	m_free(m);

}


static inline void RENAME(yuv2yuv1)(int16_t *lumSrc, int16_t *chrSrc,

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

{

#ifdef HAVE_MMX

	if(uDest != NULL)

	{

		asm volatile(

				YSCALEYUV2YV121

				:: "r" (chrSrc + chrDstW), "r" (uDest + chrDstW),

				"g" ((long)-chrDstW)

				: "%"REG_a

			);

		asm volatile(

				YSCALEYUV2YV121

				:: "r" (chrSrc + 2048 + chrDstW), "r" (vDest + chrDstW),

				"g" ((long)-chrDstW)

				: "%"REG_a

			);

	}

	asm volatile(

		YSCALEYUV2YV121

		:: "r" (lumSrc + dstW), "r" (dest + dstW),

		"g" ((long)-dstW)

		: "%"REG_a

	);

#else

	int i;

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

	{

		int val= lumSrc[i]>>7;

		if(val&256){

			if(val<0) val=0;

			else      val=255;

		}

		dest[i]= val;

	}

	if(uDest != NULL)

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

		{

			int u=chrSrc[i]>>7;

			int v=chrSrc[i + 2048]>>7;

			if((u|v)&256){

				if(u<0)         u=0;

				else if (u>255) u=255;

				if(v<0)         v=0;

				else if (v>255) v=255;

			}

			uDest[i]= u;

			vDest[i]= v;

		}

#endif

}


static int read_dialogue(ASSContext *ass, AVBPrint *dst, const uint8_t *p,

                         int64_t *start, int *duration)

{

    int pos;

    int64_t end;

    int hh1, mm1, ss1, ms1;

    int hh2, mm2, ss2, ms2;

    if (sscanf(p, "Dialogue: %*[^,],%d:%d:%d%*c%d,%d:%d:%d%*c%d,%n",

               &hh1, &mm1, &ss1, &ms1,

               &hh2, &mm2, &ss2, &ms2, &pos) >= 8) {

        /* This is not part of the sscanf itself in order to handle an actual

         * number (which would be the Layer) or the form "Marked=N" (which is

         * the old SSA field, now replaced by Layer, and will be lead to Layer

         * being 0 here). */

        const int layer = atoi(p + 10);

        end    = (hh2*3600LL + mm2*60LL + ss2) * 100LL + ms2;

        *start = (hh1*3600LL + mm1*60LL + ss1) * 100LL + ms1;

        *duration = end - *start;

        av_bprint_clear(dst);

        av_bprintf(dst, "%u,%d,%s", ass->readorder++, layer, p + pos);

        /* right strip the buffer */

        while (dst->len > 0 &&

               dst->str[dst->len - 1] == '\r' ||

               dst->str[dst->len - 1] == '\n')

            dst->str[--dst->len] = 0;

        return 0;

    }

    return -1;

}


static void quantize_bands(int (*out)[2], const float *in, const float *scaled,

                           int size, float Q34, int is_signed, int maxval)

{

    int i;

    double qc;

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

        qc = scaled[i] * Q34;

        out[i][0] = (int)FFMIN((int)qc,            maxval);

        out[i][1] = (int)FFMIN((int)(qc + 0.4054), maxval);

        if (is_signed && in[i] < 0.0f) {

            out[i][0] = -out[i][0];

            out[i][1] = -out[i][1];

        }

    }

}


av_cold int vaapi_device_init(const char *device)
{
    int err;
    err = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,
                                 device, NULL, 0);
    if (err < 0) {
        av_log(&vaapi_log, AV_LOG_ERROR, "Failed to create a VAAPI device\n");
        return err;
    }
    return 0;
}


static int qemu_chr_open_pty(QemuOpts *opts, CharDriverState **_chr)

{

    CharDriverState *chr;

    PtyCharDriver *s;

    struct termios tty;

    int slave_fd, len;

#if defined(__OpenBSD__) || defined(__DragonFly__)

    char pty_name[PATH_MAX];

#define q_ptsname(x) pty_name

#else

    char *pty_name = NULL;

#define q_ptsname(x) ptsname(x)

#endif

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(PtyCharDriver));

    if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {

        return -errno;

    }

    /* Set raw attributes on the pty. */

    tcgetattr(slave_fd, &tty);

    cfmakeraw(&tty);

    tcsetattr(slave_fd, TCSAFLUSH, &tty);

    close(slave_fd);

    len = strlen(q_ptsname(s->fd)) + 5;

    chr->filename = g_malloc(len);

    snprintf(chr->filename, len, "pty:%s", q_ptsname(s->fd));

    qemu_opt_set(opts, "path", q_ptsname(s->fd));

    fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));

    chr->opaque = s;

    chr->chr_write = pty_chr_write;

    chr->chr_update_read_handler = pty_chr_update_read_handler;

    chr->chr_close = pty_chr_close;

    s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);

    *_chr = chr;

    return 0;

}


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

                            AVPacket *avpkt)

{

    const AVPixFmtDescriptor *desc;

    SMVJpegDecodeContext *s = avctx->priv_data;

    AVFrame* mjpeg_data = s->picture[0];

    int i, cur_frame = 0, ret = 0;

    cur_frame = avpkt->pts % s->frames_per_jpeg;

    /* Are we at the start of a block? */

    if (!cur_frame) {

        av_frame_unref(mjpeg_data);

        ret = avcodec_decode_video2(s->avctx, mjpeg_data, &s->mjpeg_data_size, avpkt);

        if (ret < 0) {

            s->mjpeg_data_size = 0;

            return ret;

        }

    } else if (!s->mjpeg_data_size)

        return AVERROR(EINVAL);

    desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);

    if (desc && mjpeg_data->height % (s->frames_per_jpeg << desc->log2_chroma_h)) {

        av_log(avctx, AV_LOG_ERROR, "Invalid height\n");

        return AVERROR_INVALIDDATA;

    }

    /*use the last lot... */

    *data_size = s->mjpeg_data_size;

    avctx->pix_fmt = s->avctx->pix_fmt;

    /* We shouldn't get here if frames_per_jpeg <= 0 because this was rejected

       in init */

    ret = ff_set_dimensions(avctx, mjpeg_data->width, mjpeg_data->height / s->frames_per_jpeg);

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "Failed to set dimensions\n");

        return ret;

    }

    if (*data_size) {

        s->picture[1]->extended_data = NULL;

        s->picture[1]->width         = avctx->width;

        s->picture[1]->height        = avctx->height;

        s->picture[1]->format        = avctx->pix_fmt;

        /* ff_init_buffer_info(avctx, &s->picture[1]); */

        smv_img_pnt(s->picture[1]->data, mjpeg_data->data, mjpeg_data->linesize,

                    avctx->pix_fmt, avctx->width, avctx->height, cur_frame);

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

            s->picture[1]->linesize[i] = mjpeg_data->linesize[i];

        ret = av_frame_ref(data, s->picture[1]);

    }

    return ret;

}


static void tpm_display_backend_drivers(void)

{

    int i;

    fprintf(stderr, "Supported TPM types (choose only one):\n");

    for (i = 0; i < TPM_MAX_DRIVERS && be_drivers[i] != NULL; i++) {

        fprintf(stderr, "%12s   %s\n",

                TpmType_lookup[be_drivers[i]->type], be_drivers[i]->desc());

    }

    fprintf(stderr, "\n");

}


static void rtsp_parse_rtp_info(RTSPState *rt, const char *p)

{

    int read = 0;

    char key[20], value[1024], url[1024] = "";

    uint32_t seq = 0, rtptime = 0;

    for (;;) {

        p += strspn(p, SPACE_CHARS);

        if (!*p)

            break;

        get_word_sep(key, sizeof(key), "=", &p);

        if (*p != '=')

            break;

        p++;

        get_word_sep(value, sizeof(value), ";, ", &p);

        read++;

        if (!strcmp(key, "url"))

            av_strlcpy(url, value, sizeof(url));

        else if (!strcmp(key, "seq"))

            seq = strtol(value, NULL, 10);

        else if (!strcmp(key, "rtptime"))

            rtptime = strtol(value, NULL, 10);

        if (*p == ',') {

            handle_rtp_info(rt, url, seq, rtptime);

            url[0] = '\0';

            seq = rtptime = 0;

            read = 0;

        }

        if (*p)

            p++;

    }

    if (read > 0)

        handle_rtp_info(rt, url, seq, rtptime);

}