static av_always_inline void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64], int lowres_flag)

{

    int mb_x, mb_y;

    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;

#ifdef HAVE_XVMC

    if(s->avctx->xvmc_acceleration){

        XVMC_decode_mb(s);//xvmc uses pblocks

        return;

    }

#endif

    mb_x = s->mb_x;

    mb_y = s->mb_y;

    if(s->avctx->debug&FF_DEBUG_DCT_COEFF) {

       /* save DCT coefficients */

       int i,j;

       DCTELEM *dct = &s->current_picture.dct_coeff[mb_xy*64*6];

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

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

               *dct++ = block[i][s->dsp.idct_permutation[j]];

    }

    s->current_picture.qscale_table[mb_xy]= s->qscale;

    /* update DC predictors for P macroblocks */

    if (!s->mb_intra) {

        if (s->h263_pred || s->h263_aic) {

            if(s->mbintra_table[mb_xy])

                ff_clean_intra_table_entries(s);

        } else {

            s->last_dc[0] =

            s->last_dc[1] =

            s->last_dc[2] = 128 << s->intra_dc_precision;

        }

    }

    else if (s->h263_pred || s->h263_aic)

        s->mbintra_table[mb_xy]=1;

    if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==B_TYPE) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc

        uint8_t *dest_y, *dest_cb, *dest_cr;

        int dct_linesize, dct_offset;

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics

        const int uvlinesize= s->current_picture.linesize[1];

        const int readable= s->pict_type != B_TYPE || s->encoding || s->avctx->draw_horiz_band || lowres_flag;

        const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;

        /* avoid copy if macroblock skipped in last frame too */

        /* skip only during decoding as we might trash the buffers during encoding a bit */

        if(!s->encoding){

            uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];

            const int age= s->current_picture.age;

            assert(age);

            if (s->mb_skipped) {

                s->mb_skipped= 0;

                assert(s->pict_type!=I_TYPE);

                (*mbskip_ptr) ++; /* indicate that this time we skipped it */

                if(*mbskip_ptr >99) *mbskip_ptr= 99;

                /* if previous was skipped too, then nothing to do !  */

                if (*mbskip_ptr >= age && s->current_picture.reference){

                    return;

                }

            } else if(!s->current_picture.reference){

                (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */

                if(*mbskip_ptr >99) *mbskip_ptr= 99;

            } else{

                *mbskip_ptr = 0; /* not skipped */

            }

        }

        dct_linesize = linesize << s->interlaced_dct;

        dct_offset =(s->interlaced_dct)? linesize : linesize*block_size;

        if(readable){

            dest_y=  s->dest[0];

            dest_cb= s->dest[1];

            dest_cr= s->dest[2];

        }else{

            dest_y = s->b_scratchpad;

            dest_cb= s->b_scratchpad+16*linesize;

            dest_cr= s->b_scratchpad+32*linesize;

        }

        if (!s->mb_intra) {

            /* motion handling */

            /* decoding or more than one mb_type (MC was already done otherwise) */

            if(!s->encoding){

                if(lowres_flag){

                    h264_chroma_mc_func *op_pix = s->dsp.put_h264_chroma_pixels_tab;

                    if (s->mv_dir & MV_DIR_FORWARD) {

                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix);

                        op_pix = s->dsp.avg_h264_chroma_pixels_tab;

                    }

                    if (s->mv_dir & MV_DIR_BACKWARD) {

                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix);

                    }

                }else{

                    op_qpix= s->me.qpel_put;

                    if ((!s->no_rounding) || s->pict_type==B_TYPE){

                        op_pix = s->dsp.put_pixels_tab;

                    }else{

                        op_pix = s->dsp.put_no_rnd_pixels_tab;

                    }

                    if (s->mv_dir & MV_DIR_FORWARD) {

                        MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);

                        op_pix = s->dsp.avg_pixels_tab;

                        op_qpix= s->me.qpel_avg;

                    }

                    if (s->mv_dir & MV_DIR_BACKWARD) {

                        MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);

                    }

                }

            }

            /* skip dequant / idct if we are really late ;) */

            if(s->hurry_up>1) goto skip_idct;

            if(s->avctx->skip_idct){

                if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == B_TYPE)

                   ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != I_TYPE)

                   || s->avctx->skip_idct >= AVDISCARD_ALL)

                    goto skip_idct;

            }

            /* add dct residue */

            if(s->encoding || !(   s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO

                                || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){

                add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    if (s->chroma_y_shift){

                        add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_linesize >>= 1;

                        dct_offset >>=1;

                        add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            } else if(s->codec_id != CODEC_ID_WMV2){

                add_dct(s, block[0], 0, dest_y                          , dct_linesize);

                add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);

                add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);

                add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){//Chroma420

                        add_dct(s, block[4], 4, dest_cb, uvlinesize);

                        add_dct(s, block[5], 5, dest_cr, uvlinesize);

                    }else{

                        //chroma422

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;

                        add_dct(s, block[4], 4, dest_cb, dct_linesize);

                        add_dct(s, block[5], 5, dest_cr, dct_linesize);

                        add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);

                        add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);

                        if(!s->chroma_x_shift){//Chroma444

                            add_dct(s, block[8], 8, dest_cb+8, dct_linesize);

                            add_dct(s, block[9], 9, dest_cr+8, dct_linesize);

                            add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);

                            add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);

                        }

                    }

                }//fi gray

            }

            else if (ENABLE_WMV2) {

                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);

            }

        } else {

            /* dct only in intra block */

            if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){

                put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){

                        put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_offset >>=1;

                        dct_linesize >>=1;

                        put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            }else{

                s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);

                s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);

                s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);

                s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);

                if(!(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){

                        s->dsp.idct_put(dest_cb, uvlinesize, block[4]);

                        s->dsp.idct_put(dest_cr, uvlinesize, block[5]);

                    }else{

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;

                        s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);

                        s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);

                        s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);

                        s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);

                        if(!s->chroma_x_shift){//Chroma444

                            s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);

                            s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);

                            s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);

                            s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);

                        }

                    }

                }//gray

            }

        }

skip_idct:

        if(!readable){

            s->dsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);

            s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);

            s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);

        }

    }

}


static int compute_send_delay(HTTPContext *c)

{

    int datarate = 8 * get_longterm_datarate(&c->datarate, c->data_count);

    if (datarate > c->stream->bandwidth * 2000) {

        return 1000;

    }

    return 0;

}


void OPPROTO op_check_addo (void)

{

    if (likely(!(((uint32_t)T2 ^ (uint32_t)T1 ^ UINT32_MAX) &

                 ((uint32_t)T2 ^ (uint32_t)T0) & (1UL << 31)))) {

        xer_ov = 0;

    } else {

        xer_so = 1;

        xer_ov = 1;

    }

    RETURN();

}


static gpointer writeout_thread(gpointer opaque)

{

    TraceRecord *recordptr;

    union {

        TraceRecord rec;

        uint8_t bytes[sizeof(TraceRecord) + sizeof(uint64_t)];

    } dropped;

    unsigned int idx = 0;

    int dropped_count;

    size_t unused __attribute__ ((unused));

    for (;;) {

        wait_for_trace_records_available();

        if (g_atomic_int_get(&dropped_events)) {

            dropped.rec.event = DROPPED_EVENT_ID,

            dropped.rec.timestamp_ns = get_clock();

            dropped.rec.length = sizeof(TraceRecord) + sizeof(uint64_t),

            dropped.rec.reserved = 0;

            while (1) {

                dropped_count = g_atomic_int_get(&dropped_events);

                if (g_atomic_int_compare_and_exchange(&dropped_events,

                                                      dropped_count, 0)) {

                    break;

                }

            }

            dropped.rec.arguments[0] = dropped_count;

            unused = fwrite(&dropped.rec, dropped.rec.length, 1, trace_fp);

        }

        while (get_trace_record(idx, &recordptr)) {

            unused = fwrite(recordptr, recordptr->length, 1, trace_fp);

            writeout_idx += recordptr->length;

            free(recordptr); /* dont use g_free, can deadlock when traced */

            idx = writeout_idx % TRACE_BUF_LEN;

        }

        fflush(trace_fp);

    }

    return NULL;

}


static int handle_renames_and_mkdirs(BDRVVVFATState* s)

{

    int i;

#ifdef DEBUG

    fprintf(stderr, "handle_renames\n");

    for (i = 0; i < s->commits.next; i++) {

	commit_t* commit = array_get(&(s->commits), i);

	fprintf(stderr, "%d, %s (%d, %d)\n", i, commit->path ? commit->path : "(null)", commit->param.rename.cluster, commit->action);

    }

#endif

    for (i = 0; i < s->commits.next;) {

	commit_t* commit = array_get(&(s->commits), i);

	if (commit->action == ACTION_RENAME) {

	    mapping_t* mapping = find_mapping_for_cluster(s,

		    commit->param.rename.cluster);

	    char* old_path = mapping->path;

	    assert(commit->path);

	    mapping->path = commit->path;

	    if (rename(old_path, mapping->path))

		return -2;

	    if (mapping->mode & MODE_DIRECTORY) {

		int l1 = strlen(mapping->path);

		int l2 = strlen(old_path);

		int diff = l1 - l2;

		direntry_t* direntry = array_get(&(s->directory),

			mapping->info.dir.first_dir_index);

		uint32_t c = mapping->begin;

		int i = 0;

		/* recurse */

		while (!fat_eof(s, c)) {

		    do {

			direntry_t* d = direntry + i;

			if (is_file(d) || (is_directory(d) && !is_dot(d))) {

			    mapping_t* m = find_mapping_for_cluster(s,

				    begin_of_direntry(d));

			    int l = strlen(m->path);

			    char* new_path = g_malloc(l + diff + 1);

			    assert(!strncmp(m->path, mapping->path, l2));

                            pstrcpy(new_path, l + diff + 1, mapping->path);

                            pstrcpy(new_path + l1, l + diff + 1 - l1,

                                    m->path + l2);

			    schedule_rename(s, m->begin, new_path);

			}

			i++;

		    } while((i % (0x10 * s->sectors_per_cluster)) != 0);

		    c = fat_get(s, c);

		}

	    }

	    free(old_path);

	    array_remove(&(s->commits), i);

	    continue;

	} else if (commit->action == ACTION_MKDIR) {

	    mapping_t* mapping;

	    int j, parent_path_len;

#ifdef __MINGW32__

            if (mkdir(commit->path))

                return -5;

#else

            if (mkdir(commit->path, 0755))

                return -5;

#endif

	    mapping = insert_mapping(s, commit->param.mkdir.cluster,

		    commit->param.mkdir.cluster + 1);

	    if (mapping == NULL)

		return -6;

	    mapping->mode = MODE_DIRECTORY;

	    mapping->read_only = 0;

	    mapping->path = commit->path;

	    j = s->directory.next;

	    assert(j);

	    insert_direntries(s, s->directory.next,

		    0x10 * s->sectors_per_cluster);

	    mapping->info.dir.first_dir_index = j;

	    parent_path_len = strlen(commit->path)

		- strlen(get_basename(commit->path)) - 1;

	    for (j = 0; j < s->mapping.next; j++) {

		mapping_t* m = array_get(&(s->mapping), j);

		if (m->first_mapping_index < 0 && m != mapping &&

			!strncmp(m->path, mapping->path, parent_path_len) &&

			strlen(m->path) == parent_path_len)

		    break;

	    }

	    assert(j < s->mapping.next);

	    mapping->info.dir.parent_mapping_index = j;

	    array_remove(&(s->commits), i);

	    continue;

	}

	i++;

    }

    return 0;

}


AUXBus *aux_init_bus(DeviceState *parent, const char *name)

{

    AUXBus *bus;

    bus = AUX_BUS(qbus_create(TYPE_AUX_BUS, parent, name));

    bus->bridge = AUXTOI2C(qdev_create(BUS(bus), TYPE_AUXTOI2C));

    /* Memory related. */

    bus->aux_io = g_malloc(sizeof(*bus->aux_io));

    memory_region_init(bus->aux_io, OBJECT(bus), "aux-io", (1 << 20));

    address_space_init(&bus->aux_addr_space, bus->aux_io, "aux-io");

    return bus;

}


static int vc1_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame, AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size, n_slices = 0, i, ret;
    VC1Context *v = avctx->priv_data;
    MpegEncContext *s = &v->s;
    AVFrame *pict = data;
    uint8_t *buf2 = NULL;
    const uint8_t *buf_start = buf;
    int mb_height, n_slices1;
    struct {
        uint8_t *buf;
        GetBitContext gb;
        int mby_start;
    } *slices = NULL, *tmp;
    /* no supplementary picture */
    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == VC1_CODE_ENDOFSEQ)) {
        /* special case for last picture */
        if (s->low_delay == 0 && s->next_picture_ptr) {
            if ((ret = av_frame_ref(pict, s->next_picture_ptr->f)) < 0)
                return ret;
            s->next_picture_ptr = NULL;
            *got_frame = 1;
        return 0;
    //for advanced profile we may need to parse and unescape data
    if (avctx->codec_id == AV_CODEC_ID_VC1 || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
        int buf_size2 = 0;
        buf2 = av_mallocz(buf_size + AV_INPUT_BUFFER_PADDING_SIZE);
        if (IS_MARKER(AV_RB32(buf))) { /* frame starts with marker and needs to be parsed */
            const uint8_t *start, *end, *next;
            int size;
            next = buf;
            for (start = buf, end = buf + buf_size; next < end; start = next) {
                next = find_next_marker(start + 4, end);
                size = next - start - 4;
                if (size <= 0) continue;
                switch (AV_RB32(start)) {
                case VC1_CODE_FRAME:
                    if (avctx->hwaccel)
                        buf_start = start;
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
                    break;
                case VC1_CODE_FIELD: {
                    int buf_size3;
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
                    slices = tmp;
                    slices[n_slices].buf = av_mallocz(buf_size + AV_INPUT_BUFFER_PADDING_SIZE);
                    if (!slices[n_slices].buf)
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    /* assuming that the field marker is at the exact middle,
                       hope it's correct */
                    slices[n_slices].mby_start = s->mb_height >> 1;
                    n_slices1 = n_slices - 1; // index of the last slice of the first field
                    n_slices++;
                    break;
                case VC1_CODE_ENTRYPOINT: /* it should be before frame data */
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
                    init_get_bits(&s->gb, buf2, buf_size2 * 8);
                    ff_vc1_decode_entry_point(avctx, v, &s->gb);
                    break;
                case VC1_CODE_SLICE: {
                    int buf_size3;
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
                    slices = tmp;
                    slices[n_slices].buf = av_mallocz(buf_size + AV_INPUT_BUFFER_PADDING_SIZE);
                    if (!slices[n_slices].buf)
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    slices[n_slices].mby_start = get_bits(&slices[n_slices].gb, 9);
                    n_slices++;
                    break;
        } else if (v->interlace && ((buf[0] & 0xC0) == 0xC0)) { /* WVC1 interlaced stores both fields divided by marker */
            const uint8_t *divider;
            int buf_size3;
            divider = find_next_marker(buf, buf + buf_size);
            if ((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD) {
                av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
            } else { // found field marker, unescape second field
                tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                if (!tmp)
                slices = tmp;
                slices[n_slices].buf = av_mallocz(buf_size + AV_INPUT_BUFFER_PADDING_SIZE);
                if (!slices[n_slices].buf)
                buf_size3 = vc1_unescape_buffer(divider + 4, buf + buf_size - divider - 4, slices[n_slices].buf);
                init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                              buf_size3 << 3);
                slices[n_slices].mby_start = s->mb_height >> 1;
                n_slices1 = n_slices - 1;
                n_slices++;
            buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2);
        } else {
            buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2);
        init_get_bits(&s->gb, buf2, buf_size2*8);
    } else
        init_get_bits(&s->gb, buf, buf_size*8);
    if (v->res_sprite) {
        v->new_sprite  = !get_bits1(&s->gb);
        v->two_sprites =  get_bits1(&s->gb);
        /* res_sprite means a Windows Media Image stream, AV_CODEC_ID_*IMAGE means
           we're using the sprite compositor. These are intentionally kept separate
           so you can get the raw sprites by using the wmv3 decoder for WMVP or
           the vc1 one for WVP2 */
        if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
            if (v->new_sprite) {
                // switch AVCodecContext parameters to those of the sprites
                avctx->width  = avctx->coded_width  = v->sprite_width;
                avctx->height = avctx->coded_height = v->sprite_height;
            } else {
                goto image;
    if (s->context_initialized &&
        (s->width  != avctx->coded_width ||
         s->height != avctx->coded_height)) {
        ff_vc1_decode_end(avctx);
    if (!s->context_initialized) {
        if (ff_msmpeg4_decode_init(avctx) < 0)
        if (ff_vc1_decode_init_alloc_tables(v) < 0) {
            ff_mpv_common_end(s);
        s->low_delay = !avctx->has_b_frames || v->res_sprite;
        if (v->profile == PROFILE_ADVANCED) {
            s->h_edge_pos = avctx->coded_width;
            s->v_edge_pos = avctx->coded_height;
    // do parse frame header
    v->pic_header_flag = 0;
    v->first_pic_header_flag = 1;
    if (v->profile < PROFILE_ADVANCED) {
        if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {
    } else {
        if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
    v->first_pic_header_flag = 0;
    if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)
        && s->pict_type != AV_PICTURE_TYPE_I) {
        av_log(v->s.avctx, AV_LOG_ERROR, "Sprite decoder: expected I-frame\n");
    // for skipping the frame
    s->current_picture.f->pict_type = s->pict_type;
    s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
    /* skip B-frames if we don't have reference frames */
    if (!s->last_picture_ptr && (s->pict_type == AV_PICTURE_TYPE_B || s->droppable)) {
        goto end;
    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
        (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||
         avctx->skip_frame >= AVDISCARD_ALL) {
        goto end;
    if (s->next_p_frame_damaged) {
        if (s->pict_type == AV_PICTURE_TYPE_B)
            goto end;
        else
            s->next_p_frame_damaged = 0;
    if (ff_mpv_frame_start(s, avctx) < 0) {
    // process pulldown flags
    s->current_picture_ptr->f->repeat_pict = 0;
    // Pulldown flags are only valid when 'broadcast' has been set.
    // So ticks_per_frame will be 2
    if (v->rff) {
        // repeat field
        s->current_picture_ptr->f->repeat_pict = 1;
    } else if (v->rptfrm) {
        // repeat frames
        s->current_picture_ptr->f->repeat_pict = v->rptfrm * 2;
    s->me.qpel_put = s->qdsp.put_qpel_pixels_tab;
    s->me.qpel_avg = s->qdsp.avg_qpel_pixels_tab;
    if (avctx->hwaccel) {
        if (avctx->hwaccel->start_frame(avctx, buf, buf_size) < 0)
        if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
        if (avctx->hwaccel->end_frame(avctx) < 0)
    } else {
        int header_ret = 0;
        ff_mpeg_er_frame_start(s);
        v->bits = buf_size * 8;
        v->end_mb_x = s->mb_width;
        if (v->field_mode) {
            s->current_picture.f->linesize[0] <<= 1;
            s->current_picture.f->linesize[1] <<= 1;
            s->current_picture.f->linesize[2] <<= 1;
            s->linesize                      <<= 1;
            s->uvlinesize                    <<= 1;
        mb_height = s->mb_height >> v->field_mode;
        if (!mb_height) {
            av_log(v->s.avctx, AV_LOG_ERROR, "Invalid mb_height.\n");
        for (i = 0; i <= n_slices; i++) {
            if (i > 0 &&  slices[i - 1].mby_start >= mb_height) {
                if (v->field_mode <= 0) {
                    av_log(v->s.avctx, AV_LOG_ERROR, "Slice %d starts beyond "
                           "picture boundary (%d >= %d)\n", i,
                           slices[i - 1].mby_start, mb_height);
                    continue;
                v->second_field = 1;
                v->blocks_off   = s->mb_width  * s->mb_height << 1;
                v->mb_off       = s->mb_stride * s->mb_height >> 1;
            } else {
                v->second_field = 0;
                v->blocks_off   = 0;
                v->mb_off       = 0;
            if (i) {
                v->pic_header_flag = 0;
                if (v->field_mode && i == n_slices1 + 2) {
                    if ((header_ret = ff_vc1_parse_frame_header_adv(v, &s->gb)) < 0) {
                        av_log(v->s.avctx, AV_LOG_ERROR, "Field header damaged\n");
                        if (avctx->err_recognition & AV_EF_EXPLODE)
                        continue;
                } else if (get_bits1(&s->gb)) {
                    v->pic_header_flag = 1;
                    if ((header_ret = ff_vc1_parse_frame_header_adv(v, &s->gb)) < 0) {
                        av_log(v->s.avctx, AV_LOG_ERROR, "Slice header damaged\n");
                        if (avctx->err_recognition & AV_EF_EXPLODE)
                        continue;
            if (header_ret < 0)
                continue;
            s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);
            if (!v->field_mode || v->second_field)
                s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
            else
                s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
            ff_vc1_decode_blocks(v);
            if (i != n_slices)
                s->gb = slices[i].gb;
        if (v->field_mode) {
            v->second_field = 0;
            s->current_picture.f->linesize[0] >>= 1;
            s->current_picture.f->linesize[1] >>= 1;
            s->current_picture.f->linesize[2] >>= 1;
            s->linesize                      >>= 1;
            s->uvlinesize                    >>= 1;
            if (v->s.pict_type != AV_PICTURE_TYPE_BI && v->s.pict_type != AV_PICTURE_TYPE_B) {
                FFSWAP(uint8_t *, v->mv_f_next[0], v->mv_f[0]);
                FFSWAP(uint8_t *, v->mv_f_next[1], v->mv_f[1]);
        ff_dlog(s->avctx, "Consumed %i/%i bits\n",
                get_bits_count(&s->gb), s->gb.size_in_bits);
//  if (get_bits_count(&s->gb) > buf_size * 8)
//      return -1;
        if (!v->field_mode)
            ff_er_frame_end(&s->er);
    ff_mpv_frame_end(s);
    if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
image:
        avctx->width  = avctx->coded_width  = v->output_width;
        avctx->height = avctx->coded_height = v->output_height;
        if (avctx->skip_frame >= AVDISCARD_NONREF)
            goto end;
#if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER
        if (vc1_decode_sprites(v, &s->gb))
#endif
        if ((ret = av_frame_ref(pict, v->sprite_output_frame)) < 0)
        *got_frame = 1;
    } else {
        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
            if ((ret = av_frame_ref(pict, s->current_picture_ptr->f)) < 0)
            ff_print_debug_info(s, s->current_picture_ptr);
            *got_frame = 1;
        } else if (s->last_picture_ptr) {
            if ((ret = av_frame_ref(pict, s->last_picture_ptr->f)) < 0)
            ff_print_debug_info(s, s->last_picture_ptr);
            *got_frame = 1;
end:
    av_free(buf2);
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
    return buf_size;
err:
    av_free(buf2);
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
    return -1;


static void qdev_print_devinfo(DeviceClass *dc)

{

    error_printf("name \"%s\"", object_class_get_name(OBJECT_CLASS(dc)));

    if (dc->bus_type) {

        error_printf(", bus %s", dc->bus_type);

    }

    if (qdev_class_has_alias(dc)) {

        error_printf(", alias \"%s\"", qdev_class_get_alias(dc));

    }

    if (dc->desc) {

        error_printf(", desc \"%s\"", dc->desc);

    }

    if (dc->no_user) {

        error_printf(", no-user");

    }

    error_printf("\n");

}


static void switch_tss(int tss_selector,

                       uint32_t e1, uint32_t e2, int source)

{

    int tss_limit, tss_limit_max, type, old_tss_limit_max, old_type, v1, v2, i;

    uint8_t *tss_base;

    uint32_t new_regs[8], new_segs[6];

    uint32_t new_eflags, new_eip, new_cr3, new_ldt, new_trap;

    uint32_t old_eflags, eflags_mask;

    SegmentCache *dt;

    int index;

    uint8_t *ptr;

    type = (e2 >> DESC_TYPE_SHIFT) & 0xf;

#ifdef DEBUG_PCALL

    if (loglevel)

        fprintf(logfile, "switch_tss: sel=0x%04x type=%d src=%d\n", tss_selector, type, source);

#endif

    /* if task gate, we read the TSS segment and we load it */

    if (type == 5) {

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);

        tss_selector = e1 >> 16;

        if (tss_selector & 4)

            raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);

        if (load_segment(&e1, &e2, tss_selector) != 0)

            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);

        if (e2 & DESC_S_MASK)

            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);

        type = (e2 >> DESC_TYPE_SHIFT) & 0xf;

        if ((type & 7) != 1)

            raise_exception_err(EXCP0D_GPF, tss_selector & 0xfffc);

    }

    if (!(e2 & DESC_P_MASK))

        raise_exception_err(EXCP0B_NOSEG, tss_selector & 0xfffc);

    if (type & 8)

        tss_limit_max = 103;

    else

        tss_limit_max = 43;

    tss_limit = get_seg_limit(e1, e2);

    tss_base = get_seg_base(e1, e2);

    if ((tss_selector & 4) != 0 ||

        tss_limit < tss_limit_max)

        raise_exception_err(EXCP0A_TSS, tss_selector & 0xfffc);

    old_type = (env->tr.flags >> DESC_TYPE_SHIFT) & 0xf;

    if (old_type & 8)

        old_tss_limit_max = 103;

    else

        old_tss_limit_max = 43;

    /* read all the registers from the new TSS */

    if (type & 8) {

        /* 32 bit */

        new_cr3 = ldl_kernel(tss_base + 0x1c);

        new_eip = ldl_kernel(tss_base + 0x20);

        new_eflags = ldl_kernel(tss_base + 0x24);

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

            new_regs[i] = ldl_kernel(tss_base + (0x28 + i * 4));

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

            new_segs[i] = lduw_kernel(tss_base + (0x48 + i * 4));

        new_ldt = lduw_kernel(tss_base + 0x60);

        new_trap = ldl_kernel(tss_base + 0x64);

    } else {

        /* 16 bit */

        new_cr3 = 0;

        new_eip = lduw_kernel(tss_base + 0x0e);

        new_eflags = lduw_kernel(tss_base + 0x10);

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

            new_regs[i] = lduw_kernel(tss_base + (0x12 + i * 2)) | 0xffff0000;

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

            new_segs[i] = lduw_kernel(tss_base + (0x22 + i * 4));

        new_ldt = lduw_kernel(tss_base + 0x2a);

        new_segs[R_FS] = 0;

        new_segs[R_GS] = 0;

        new_trap = 0;

    }

    /* NOTE: we must avoid memory exceptions during the task switch,

       so we make dummy accesses before */

    /* XXX: it can still fail in some cases, so a bigger hack is

       necessary to valid the TLB after having done the accesses */

    v1 = ldub_kernel(env->tr.base);

    v2 = ldub(env->tr.base + old_tss_limit_max);

    stb_kernel(env->tr.base, v1);

    stb_kernel(env->tr.base + old_tss_limit_max, v2);

    /* clear busy bit (it is restartable) */

    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_IRET) {

        uint8_t *ptr;

        uint32_t e2;

        ptr = env->gdt.base + (env->tr.selector << 3);

        e2 = ldl_kernel(ptr + 4);

        e2 &= ~DESC_TSS_BUSY_MASK;

        stl_kernel(ptr + 4, e2);

    }

    old_eflags = compute_eflags();

    if (source == SWITCH_TSS_IRET)

        old_eflags &= ~NT_MASK;

    /* save the current state in the old TSS */

    if (type & 8) {

        /* 32 bit */

        stl_kernel(env->tr.base + 0x20, env->eip);

        stl_kernel(env->tr.base + 0x24, old_eflags);

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

            stl_kernel(env->tr.base + (0x28 + i * 4), env->regs[i]);

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

            stw_kernel(env->tr.base + (0x48 + i * 4), env->segs[i].selector);

    } else {

        /* 16 bit */

        stw_kernel(env->tr.base + 0x0e, new_eip);

        stw_kernel(env->tr.base + 0x10, old_eflags);

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

            stw_kernel(env->tr.base + (0x12 + i * 2), env->regs[i]);

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

            stw_kernel(env->tr.base + (0x22 + i * 4), env->segs[i].selector);

    }

    /* now if an exception occurs, it will occurs in the next task

       context */

    if (source == SWITCH_TSS_CALL) {

        stw_kernel(tss_base, env->tr.selector);

        new_eflags |= NT_MASK;

    }

    /* set busy bit */

    if (source == SWITCH_TSS_JMP || source == SWITCH_TSS_CALL) {

        uint8_t *ptr;

        uint32_t e2;

        ptr = env->gdt.base + (tss_selector << 3);

        e2 = ldl_kernel(ptr + 4);

        e2 |= DESC_TSS_BUSY_MASK;

        stl_kernel(ptr + 4, e2);

    }

    /* set the new CPU state */

    /* from this point, any exception which occurs can give problems */

    env->cr[0] |= CR0_TS_MASK;

    env->tr.selector = tss_selector;

    env->tr.base = tss_base;

    env->tr.limit = tss_limit;

    env->tr.flags = e2 & ~DESC_TSS_BUSY_MASK;

    if ((type & 8) && (env->cr[0] & CR0_PG_MASK)) {

        env->cr[3] = new_cr3;

        cpu_x86_update_cr3(env);

    }

    /* load all registers without an exception, then reload them with

       possible exception */

    env->eip = new_eip;

    eflags_mask = TF_MASK | AC_MASK | ID_MASK |

        IF_MASK | IOPL_MASK | VM_MASK | RF_MASK | NT_MASK;

    if (!(type & 8))

        eflags_mask &= 0xffff;

    load_eflags(new_eflags, eflags_mask);

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

        env->regs[i] = new_regs[i];

    if (new_eflags & VM_MASK) {

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

            load_seg_vm(i, new_segs[i]);

        /* in vm86, CPL is always 3 */

        cpu_x86_set_cpl(env, 3);

    } else {

        /* CPL is set the RPL of CS */

        cpu_x86_set_cpl(env, new_segs[R_CS] & 3);

        /* first just selectors as the rest may trigger exceptions */

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

            cpu_x86_load_seg_cache(env, i, new_segs[i], NULL, 0, 0);

    }

    env->ldt.selector = new_ldt & ~4;

    env->ldt.base = NULL;

    env->ldt.limit = 0;

    env->ldt.flags = 0;

    /* load the LDT */

    if (new_ldt & 4)

        raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);

    if ((new_ldt & 0xfffc) != 0) {

        dt = &env->gdt;

        index = new_ldt & ~7;

        if ((index + 7) > dt->limit)

            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);

        ptr = dt->base + index;

        e1 = ldl_kernel(ptr);

        e2 = ldl_kernel(ptr + 4);

        if ((e2 & DESC_S_MASK) || ((e2 >> DESC_TYPE_SHIFT) & 0xf) != 2)

            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0A_TSS, new_ldt & 0xfffc);

        load_seg_cache_raw_dt(&env->ldt, e1, e2);

    }

    /* load the segments */

    if (!(new_eflags & VM_MASK)) {

        tss_load_seg(R_CS, new_segs[R_CS]);

        tss_load_seg(R_SS, new_segs[R_SS]);

        tss_load_seg(R_ES, new_segs[R_ES]);

        tss_load_seg(R_DS, new_segs[R_DS]);

        tss_load_seg(R_FS, new_segs[R_FS]);

        tss_load_seg(R_GS, new_segs[R_GS]);

    }

    /* check that EIP is in the CS segment limits */

    if (new_eip > env->segs[R_CS].limit) {

        raise_exception_err(EXCP0D_GPF, 0);

    }

}


uint32_t HELPER(neon_acgt_f32)(uint32_t a, uint32_t b)

{

    float32 f0 = float32_abs(make_float32(a));

    float32 f1 = float32_abs(make_float32(b));

    if (float32_compare_quiet(f0, f1, NFS) == float_relation_greater) {

        return ~0;

    }

    return 0;

}


sosendto(struct socket *so, struct mbuf *m)

{

	Slirp *slirp = so->slirp;

	int ret;

	struct sockaddr_in addr;

	DEBUG_CALL("sosendto");

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

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

        addr.sin_family = AF_INET;

	if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==

	    slirp->vnetwork_addr.s_addr) {

	  /* It's an alias */

	  if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {

	    if (get_dns_addr(&addr.sin_addr) < 0)

	      addr.sin_addr = loopback_addr;

	  } else {

	    addr.sin_addr = loopback_addr;

	  }

	} else

	  addr.sin_addr = so->so_faddr;

	addr.sin_port = so->so_fport;

	DEBUG_MISC((dfd, " sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\n", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));

	/* Don't care what port we get */

	ret = sendto(so->s, m->m_data, m->m_len, 0,

		     (struct sockaddr *)&addr, sizeof (struct sockaddr));

	if (ret < 0)

		return -1;

	/*

	 * Kill the socket if there's no reply in 4 minutes,

	 * but only if it's an expirable socket

	 */

	if (so->so_expire)

		so->so_expire = curtime + SO_EXPIRE;

	so->so_state &= SS_PERSISTENT_MASK;

	so->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */

	return 0;

}


void ff_hevc_hls_filter(HEVCContext *s, int x, int y, int ctb_size)

{

    deblocking_filter_CTB(s, x, y);

    if (s->sps->sao_enabled) {

        int x_end = x >= s->sps->width  - ctb_size;

        int y_end = y >= s->sps->height - ctb_size;

        if (y && x)

            sao_filter_CTB(s, x - ctb_size, y - ctb_size);

        if (x && y_end)

            sao_filter_CTB(s, x - ctb_size, y);

        if (y && x_end) {

            sao_filter_CTB(s, x, y - ctb_size);

            if (s->threads_type & FF_THREAD_FRAME )

                ff_thread_report_progress(&s->ref->tf, y - ctb_size, 0);

        }

        if (x_end && y_end) {

            sao_filter_CTB(s, x , y);

            if (s->threads_type & FF_THREAD_FRAME )

                ff_thread_report_progress(&s->ref->tf, y, 0);

        }

    } else {

        if (y && x >= s->sps->width - ctb_size)

            if (s->threads_type & FF_THREAD_FRAME )

                ff_thread_report_progress(&s->ref->tf, y, 0);

    }

}


static int advanced_decode_picture_primary_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    static const int type_table[4] = { P_TYPE, B_TYPE, I_TYPE, BI_TYPE };

    int type, i;

    if (v->interlace)

    {

        v->fcm = get_bits(gb, 1);

        if (v->fcm) v->fcm = 2+get_bits(gb, 1);

    }

    type = get_prefix(gb, 0, 4);

    if (type > 4 || type < 0) return FRAME_SKIPED;

    v->s.pict_type = type_table[type];

    av_log(v->s.avctx, AV_LOG_INFO, "AP Frame Type: %i\n", v->s.pict_type);

    if (v->tfcntrflag) v->tfcntr = get_bits(gb, 8);

    if (v->broadcast)

    {

        if (!v->interlace) v->rptfrm = get_bits(gb, 2);

        else

        {

            v->tff = get_bits(gb, 1);

            v->rff = get_bits(gb, 1);

        }

    }

    if (v->panscanflag)

    {

#if 0

        for (i=0; i<v->numpanscanwin; i++)

        {

            v->topleftx[i] = get_bits(gb, 16);

            v->toplefty[i] = get_bits(gb, 16);

            v->bottomrightx[i] = get_bits(gb, 16);

            v->bottomrighty[i] = get_bits(gb, 16);

        }

#else

        skip_bits(gb, 16*4*v->numpanscanwin);

#endif

    }

    v->s.no_rounding = !get_bits(gb, 1);

    v->uvsamp = get_bits(gb, 1);

    if (v->finterpflag == 1) v->interpfrm = get_bits(gb, 1);

    switch(v->s.pict_type)

    {

    case I_TYPE: if (decode_i_picture_header(v) < 0) return -1;

    case P_TYPE: if (decode_p_picture_primary_header(v) < 0) return -1;

    case BI_TYPE:

    case B_TYPE: if (decode_b_picture_primary_header(v) < 0) return FRAME_SKIPED;

    default: break;

    }

    return 0;

}


static double get_video_clock(VideoState *is)

{

    if (is->paused) {

        return is->video_current_pts;

    } else {

        return is->video_current_pts + (av_gettime() - is->video_current_pts_time) / 1000000.0;

    }

}


long do_rt_sigreturn(CPUSH4State *regs)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr;

    sigset_t blocked;

    target_ulong r0;

    frame_addr = regs->gregs[15];

    trace_user_do_rt_sigreturn(regs, frame_addr);

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    target_to_host_sigset(&blocked, &frame->uc.tuc_sigmask);

    do_sigprocmask(SIG_SETMASK, &blocked, NULL);

    restore_sigcontext(regs, &frame->uc.tuc_mcontext, &r0);

    if (do_sigaltstack(frame_addr +

                       offsetof(struct target_rt_sigframe, uc.tuc_stack),

                       0, get_sp_from_cpustate(regs)) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return r0;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static void patch_reloc(uint8_t *code_ptr, int type,

                        intptr_t value, intptr_t addend)

{

    uint32_t insn;

    value += addend;

    switch (type) {

    case R_SPARC_32:

        if (value != (uint32_t)value) {

            tcg_abort();

        }

        *(uint32_t *)code_ptr = value;

        break;

    case R_SPARC_WDISP16:

        value -= (intptr_t)code_ptr;

        if (!check_fit_tl(value >> 2, 16)) {

            tcg_abort();

        }

        insn = *(uint32_t *)code_ptr;

        insn &= ~INSN_OFF16(-1);

        insn |= INSN_OFF16(value);

        *(uint32_t *)code_ptr = insn;

        break;

    case R_SPARC_WDISP19:

        value -= (intptr_t)code_ptr;

        if (!check_fit_tl(value >> 2, 19)) {

            tcg_abort();

        }

        insn = *(uint32_t *)code_ptr;

        insn &= ~INSN_OFF19(-1);

        insn |= INSN_OFF19(value);

        *(uint32_t *)code_ptr = insn;

        break;

    default:

        tcg_abort();

    }

}


static int v9fs_synth_unlinkat(FsContext *ctx, V9fsPath *dir,

                               const char *name, int flags)

{

    errno = EPERM;

    return -1;

}


void json_start_object(QJSON *json, const char *name)

{

    json_emit_element(json, name);

    qstring_append(json->str, "{ ");

    json->omit_comma = true;

}


START_TEST(qdict_get_int_test)

{

    int ret;

    const int value = 100;

    const char *key = "int";

    qdict_put(tests_dict, key, qint_from_int(value));

    ret = qdict_get_int(tests_dict, key);

    fail_unless(ret == value);

}


static void float64_maddsub_update_excp(CPUPPCState *env, float64 arg1,

                                        float64 arg2, float64 arg3,

                                        unsigned int madd_flags)

{

    if (unlikely((float64_is_infinity(arg1) && float64_is_zero(arg2)) ||

                 (float64_is_zero(arg1) && float64_is_infinity(arg2)))) {

        /* Multiplication of zero by infinity */

        arg1 = float_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ, 1);

    } else if (unlikely(float64_is_signaling_nan(arg1, &env->fp_status) ||

                        float64_is_signaling_nan(arg2, &env->fp_status) ||

                        float64_is_signaling_nan(arg3, &env->fp_status))) {

        /* sNaN operation */

        float_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN, 1);

    } else if ((float64_is_infinity(arg1) || float64_is_infinity(arg2)) &&

               float64_is_infinity(arg3)) {

        uint8_t aSign, bSign, cSign;

        aSign = float64_is_neg(arg1);

        bSign = float64_is_neg(arg2);

        cSign = float64_is_neg(arg3);

        if (madd_flags & float_muladd_negate_c) {

            cSign ^= 1;

        }

        if (aSign ^ bSign ^ cSign) {

            float_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI, 1);

        }

    }

}


static uint32_t check_alarm(RTCState *s)

{

    uint8_t alarm_hour, alarm_min, alarm_sec;

    uint8_t cur_hour, cur_min, cur_sec;

    alarm_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS_ALARM]);

    alarm_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES_ALARM]);

    alarm_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS_ALARM]);

    alarm_hour = convert_hour(s, alarm_hour);

    cur_sec = rtc_from_bcd(s, s->cmos_data[RTC_SECONDS]);

    cur_min = rtc_from_bcd(s, s->cmos_data[RTC_MINUTES]);

    cur_hour = rtc_from_bcd(s, s->cmos_data[RTC_HOURS]);

    cur_hour = convert_hour(s, cur_hour);

    if (((s->cmos_data[RTC_SECONDS_ALARM] & 0xc0) == 0xc0

                || alarm_sec == cur_sec) &&

            ((s->cmos_data[RTC_MINUTES_ALARM] & 0xc0) == 0xc0

             || alarm_min == cur_min) &&

            ((s->cmos_data[RTC_HOURS_ALARM] & 0xc0) == 0xc0

             || alarm_hour == cur_hour)) {

        return 1;

    }

    return 0;

}


static int get_dns_addr(struct in_addr *pdns_addr)

{

    char buff[512];

    char buff2[257];

    FILE *f;

    int found = 0;

    struct in_addr tmp_addr;

    f = fopen("/etc/resolv.conf", "r");

    if (!f)

        return -1;

#ifdef DEBUG

    lprint("IP address of your DNS(s): ");

#endif

    while (fgets(buff, 512, f) != NULL) {

        if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1) {

            if (!inet_aton(buff2, &tmp_addr))

                continue;

            if (tmp_addr.s_addr == loopback_addr.s_addr)

                tmp_addr = our_addr;

            /* If it's the first one, set it to dns_addr */

            if (!found)

                *pdns_addr = tmp_addr;

#ifdef DEBUG

            else

                lprint(", ");

#endif

            if (++found > 3) {

#ifdef DEBUG

                lprint("(more)");

#endif

                break;

            }

#ifdef DEBUG

            else

                lprint("%s", inet_ntoa(tmp_addr));

#endif

        }

    }

    fclose(f);

    if (!found)

        return -1;

    return 0;

}


static bool aio_epoll_try_enable(AioContext *ctx)

{

    AioHandler *node;

    struct epoll_event event;

    QLIST_FOREACH(node, &ctx->aio_handlers, node) {

        int r;

        if (node->deleted || !node->pfd.events) {

            continue;

        }

        event.events = epoll_events_from_pfd(node->pfd.events);

        event.data.ptr = node;

        r = epoll_ctl(ctx->epollfd, EPOLL_CTL_ADD, node->pfd.fd, &event);

        if (r) {

            return false;

        }

    }

    ctx->epoll_enabled = true;

    return true;

}


static int bt_parse(const char *opt)

{

    const char *endp, *p;

    int vlan;

    if (strstart(opt, "hci", &endp)) {

        if (!*endp || *endp == ',') {

            if (*endp)

                if (!strstart(endp, ",vlan=", 0))

                    opt = endp + 1;

            return bt_hci_parse(opt);

       }

    } else if (strstart(opt, "vhci", &endp)) {

        if (!*endp || *endp == ',') {

            if (*endp) {

                if (strstart(endp, ",vlan=", &p)) {

                    vlan = strtol(p, (char **) &endp, 0);

                    if (*endp) {

                        fprintf(stderr, "qemu: bad scatternet '%s'\n", p);

                        return 1;

                    }

                } else {

                    fprintf(stderr, "qemu: bad parameter '%s'\n", endp + 1);

                    return 1;

                }

            } else

                vlan = 0;

            bt_vhci_add(vlan);

            return 0;

        }

    } else if (strstart(opt, "device:", &endp))

        return !bt_device_add(endp);

    fprintf(stderr, "qemu: bad bluetooth parameter '%s'\n", opt);

    return 1;

}


static void omap_mpui_io_write(void *opaque, target_phys_addr_t addr,

                               uint64_t value, unsigned size)

{

    /* FIXME: infinite loop */

    omap_badwidth_write16(opaque, addr, value);

}


static int ipvideo_decode_block_opcode_0xC(IpvideoContext *s)

{

    int x, y;

    /* 16-color block encoding: each 2x2 block is a different color */

    CHECK_STREAM_PTR(16);

    for (y = 0; y < 8; y += 2) {

        for (x = 0; x < 8; x += 2) {

            s->pixel_ptr[x                ] =

            s->pixel_ptr[x + 1            ] =

            s->pixel_ptr[x +     s->stride] =

            s->pixel_ptr[x + 1 + s->stride] = *s->stream_ptr++;

        }

        s->pixel_ptr += s->stride * 2;

    }

    /* report success */

    return 0;

}


static void term_handle_command(char *cmdline)

{

    char *p, *pstart;

    int argc;

    const char *args[MAX_ARGS + 1];

    term_cmd_t *cmd;

#ifdef DEBUG

    term_printf("command='%s'\n", cmdline);

#endif

    /* split command in words */

    argc = 0;

    p = cmdline;

    for(;;) {

        while (isspace(*p))

            p++;

        if (*p == '\0')

            break;

        pstart = p;

        while (*p != '\0' && !isspace(*p))

            p++;

        args[argc] = pstart;

        argc++;

        if (argc >= MAX_ARGS)

            break;

        if (*p == '\0')

            break;

        *p++ = '\0';

    }

    args[argc] = NULL;

#ifdef DEBUG

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

        term_printf(" '%s'", args[i]);

    }

    term_printf("\n");

#endif

    if (argc <= 0)

        return;

    for(cmd = term_cmds; cmd->name != NULL; cmd++) {

        if (compare_cmd(args[0], cmd->name))

            goto found;

    }

    term_printf("unknown command: '%s'\n", args[0]);

    return;

 found:

    cmd->handler(argc, args);

}


static void m5206_mbar_writew(void *opaque, target_phys_addr_t offset,

                              uint32_t value)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    int width;

    offset &= 0x3ff;

    if (offset > 0x200) {

        hw_error("Bad MBAR write offset 0x%x", (int)offset);

    }

    width = m5206_mbar_width[offset >> 2];

    if (width > 2) {

        uint32_t tmp;

        tmp = m5206_mbar_readl(opaque, offset & ~3);

        if (offset & 3) {

            tmp = (tmp & 0xffff0000) | value;

        } else {

            tmp = (tmp & 0x0000ffff) | (value << 16);

        }

        m5206_mbar_writel(opaque, offset & ~3, tmp);

        return;

    } else if (width < 2) {

        m5206_mbar_writeb(opaque, offset, value >> 8);

        m5206_mbar_writeb(opaque, offset + 1, value & 0xff);

        return;

    }

    m5206_mbar_write(s, offset, value, 2);

}


static void test_ivshmem_server(bool msi)

{

    IVState state1, state2, *s1, *s2;

    ServerThread thread;

    IvshmemServer server;

    int ret, vm1, vm2;

    int nvectors = 2;

    guint64 end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;

    ret = ivshmem_server_init(&server, tmpserver, tmpshm, true,

                              TMPSHMSIZE, nvectors,

                              g_test_verbose());

    g_assert_cmpint(ret, ==, 0);

    ret = ivshmem_server_start(&server);

    g_assert_cmpint(ret, ==, 0);

    setup_vm_with_server(&state1, nvectors, msi);

    s1 = &state1;

    setup_vm_with_server(&state2, nvectors, msi);

    s2 = &state2;

    /* check state before server sends stuff */

    g_assert_cmpuint(in_reg(s1, IVPOSITION), ==, 0xffffffff);

    g_assert_cmpuint(in_reg(s2, IVPOSITION), ==, 0xffffffff);

    g_assert_cmpuint(qtest_readb(s1->qtest, (uintptr_t)s1->mem_base), ==, 0x00);

    thread.server = &server;

    ret = pipe(thread.pipe);

    g_assert_cmpint(ret, ==, 0);

    thread.thread = g_thread_new("ivshmem-server", server_thread, &thread);

    g_assert(thread.thread != NULL);

    /* waiting for devices to become operational */

    while (g_get_monotonic_time() < end_time) {

        g_usleep(1000);

        if ((int)in_reg(s1, IVPOSITION) >= 0 &&

            (int)in_reg(s2, IVPOSITION) >= 0) {

            break;

        }

    }

    /* check got different VM ids */

    vm1 = in_reg(s1, IVPOSITION);

    vm2 = in_reg(s2, IVPOSITION);

    g_assert_cmpuint(vm1, !=, vm2);

    /* check number of MSI-X vectors */

    global_qtest = s1->qtest;

    if (msi) {

        ret = qpci_msix_table_size(s1->dev);

        g_assert_cmpuint(ret, ==, nvectors);

    }

    /* TODO test behavior before MSI-X is enabled */

    /* ping vm2 -> vm1 on vector 0 */

    if (msi) {

        ret = qpci_msix_pending(s1->dev, 0);

        g_assert_cmpuint(ret, ==, 0);

    } else {

        g_assert_cmpuint(in_reg(s1, INTRSTATUS), ==, 0);

    }

    out_reg(s2, DOORBELL, vm1 << 16);

    do {

        g_usleep(10000);

        ret = msi ? qpci_msix_pending(s1->dev, 0) : in_reg(s1, INTRSTATUS);

    } while (ret == 0 && g_get_monotonic_time() < end_time);

    g_assert_cmpuint(ret, !=, 0);

    /* ping vm1 -> vm2 on vector 1 */

    global_qtest = s2->qtest;

    if (msi) {

        ret = qpci_msix_pending(s2->dev, 1);

        g_assert_cmpuint(ret, ==, 0);

    } else {

        g_assert_cmpuint(in_reg(s2, INTRSTATUS), ==, 0);

    }

    out_reg(s1, DOORBELL, vm2 << 16 | 1);

    do {

        g_usleep(10000);

        ret = msi ? qpci_msix_pending(s2->dev, 1) : in_reg(s2, INTRSTATUS);

    } while (ret == 0 && g_get_monotonic_time() < end_time);

    g_assert_cmpuint(ret, !=, 0);

    cleanup_vm(s2);

    cleanup_vm(s1);

    if (qemu_write_full(thread.pipe[1], "q", 1) != 1) {

        g_error("qemu_write_full: %s", g_strerror(errno));

    }

    g_thread_join(thread.thread);

    ivshmem_server_close(&server);

    close(thread.pipe[1]);

    close(thread.pipe[0]);

}


int qemu_peek_byte(QEMUFile *f, int offset)

{

    int index = f->buf_index + offset;

    assert(!qemu_file_is_writable(f));

    assert(offset < IO_BUF_SIZE);

    if (index >= f->buf_size) {

        qemu_fill_buffer(f);

        index = f->buf_index + offset;

        if (index >= f->buf_size) {

            return 0;

        }

    }

    return f->buf[index];

}


static void FUNCC(pred8x8_horizontal)(uint8_t *_src, int stride){

    int i;

    pixel *src = (pixel*)_src;

    stride /= sizeof(pixel);

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

        ((pixel4*)(src+i*stride))[0]=

        ((pixel4*)(src+i*stride))[1]= PIXEL_SPLAT_X4(src[-1+i*stride]);

    }

}


monitor_protocol_event_queue(MonitorEvent event,

                             QObject *data)

{

    MonitorEventState *evstate;

    int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    assert(event < QEVENT_MAX);

    qemu_mutex_lock(&monitor_event_state_lock);

    evstate = &(monitor_event_state[event]);

    trace_monitor_protocol_event_queue(event,

                                       data,

                                       evstate->rate,

                                       evstate->last,

                                       now);

    /* Rate limit of 0 indicates no throttling */

    if (!evstate->rate) {

        monitor_protocol_event_emit(event, data);

        evstate->last = now;

    } else {

        int64_t delta = now - evstate->last;

        if (evstate->data ||

            delta < evstate->rate) {

            /* If there's an existing event pending, replace

             * it with the new event, otherwise schedule a

             * timer for delayed emission

             */

            if (evstate->data) {

                qobject_decref(evstate->data);

            } else {

                int64_t then = evstate->last + evstate->rate;

                timer_mod_ns(evstate->timer, then);

            }

            evstate->data = data;

            qobject_incref(evstate->data);

        } else {

            monitor_protocol_event_emit(event, data);

            evstate->last = now;

        }

    }

    qemu_mutex_unlock(&monitor_event_state_lock);

}


static int qemu_gluster_create(const char *filename,

                               QemuOpts *opts, Error **errp)

{

    struct glfs *glfs;

    struct glfs_fd *fd;

    int ret = 0;

    int prealloc = 0;

    int64_t total_size = 0;

    char *tmp = NULL;

    GlusterConf *gconf = g_malloc0(sizeof(GlusterConf));

    glfs = qemu_gluster_init(gconf, filename, errp);

    if (!glfs) {

        ret = -errno;

        goto out;

    }

    total_size =

        qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / BDRV_SECTOR_SIZE;

    tmp = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);

    if (!tmp || !strcmp(tmp, "off")) {

        prealloc = 0;

    } else if (!strcmp(tmp, "full") &&

               gluster_supports_zerofill()) {

        prealloc = 1;

    } else {

        error_setg(errp, "Invalid preallocation mode: '%s'"

            " or GlusterFS doesn't support zerofill API",

            tmp);

        ret = -EINVAL;

        goto out;

    }

    fd = glfs_creat(glfs, gconf->image,

        O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR);

    if (!fd) {

        ret = -errno;

    } else {

        if (!glfs_ftruncate(fd, total_size * BDRV_SECTOR_SIZE)) {

            if (prealloc && qemu_gluster_zerofill(fd, 0,

                    total_size * BDRV_SECTOR_SIZE)) {

                ret = -errno;

            }

        } else {

            ret = -errno;

        }

        if (glfs_close(fd) != 0) {

            ret = -errno;

        }

    }

out:

    g_free(tmp);

    qemu_gluster_gconf_free(gconf);

    if (glfs) {

        glfs_fini(glfs);

    }

    return ret;

}


void *qemu_memalign(size_t alignment, size_t size)

{

    if (!size) {

        abort();

    }

    return oom_check(VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE));

}


static void decode_parameters(SiprParameters* parms, GetBitContext *pgb,

                              const SiprModeParam *p)

{

    int i, j;

    parms->ma_pred_switch           = get_bits(pgb, p->ma_predictor_bits);

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

        parms->vq_indexes[i]        = get_bits(pgb, p->vq_indexes_bits[i]);

    for (i = 0; i < p->subframe_count; i++) {

        parms->pitch_delay[i]       = get_bits(pgb, p->pitch_delay_bits[i]);

        parms->gp_index[i]          = get_bits(pgb, p->gp_index_bits);

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

            parms->fc_indexes[i][j] = get_bits(pgb, p->fc_index_bits[j]);

        parms->gc_index[i]          = get_bits(pgb, p->gc_index_bits);

    }

}


static void slow_bar_writel(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    AssignedDevRegion *d = opaque;

    uint32_t *out = (uint32_t *)(d->u.r_virtbase + addr);

    DEBUG("slow_bar_writel addr=0x" TARGET_FMT_plx " val=0x%08x\n", addr, val);

    *out = val;

}


SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, DriveInfo *dinfo, int unit)

{

    const char *driver;

    DeviceState *dev;

    driver = bdrv_is_sg(dinfo->bdrv) ? "scsi-generic" : "scsi-disk";

    dev = qdev_create(&bus->qbus, driver);

    qdev_prop_set_uint32(dev, "scsi-id", unit);

    qdev_prop_set_drive(dev, "drive", dinfo);

    if (qdev_init(dev) < 0)

        return NULL;

    return DO_UPCAST(SCSIDevice, qdev, dev);

}


static void xen_log_stop(MemoryListener *listener, MemoryRegionSection *section)

{

    XenIOState *state = container_of(listener, XenIOState, memory_listener);

    state->log_for_dirtybit = NULL;

    /* Disable dirty bit tracking */

    xc_hvm_track_dirty_vram(xen_xc, xen_domid, 0, 0, NULL);

}


static int vtd_int_remap(X86IOMMUState *iommu, MSIMessage *src,

                         MSIMessage *dst, uint16_t sid)

{

    return vtd_interrupt_remap_msi(INTEL_IOMMU_DEVICE(iommu), src, dst);

}


static void core_region_nop(MemoryListener *listener,

                            MemoryRegionSection *section)

{

    cpu_register_physical_memory_log(section, section->readonly);

}


float32 uint64_to_float32( uint64 a STATUS_PARAM )

{

    int8 shiftCount;

    if ( a == 0 ) return 0;

    shiftCount = countLeadingZeros64( a ) - 40;

    if ( 0 <= shiftCount ) {

        return packFloat32( 1 > 0, 0x95 - shiftCount, a<<shiftCount );

    }

    else {

        shiftCount += 7;

        if ( shiftCount < 0 ) {

            shift64RightJamming( a, - shiftCount, &a );

        }

        else {

            a <<= shiftCount;

        }

        return roundAndPackFloat32( 1 > 0, 0x9C - shiftCount, a STATUS_VAR );

    }

}


static void do_change_vnc(const char *target, const char *arg)

{

    if (strcmp(target, "passwd") == 0 ||

	strcmp(target, "password") == 0) {

	char password[9];

	if (arg) {

	    strncpy(password, arg, sizeof(password));

	    password[sizeof(password) - 1] = '\0';

	} else

	    monitor_readline("Password: ", 1, password, sizeof(password));

	if (vnc_display_password(NULL, password) < 0)

	    term_printf("could not set VNC server password\n");

    } else {

	if (vnc_display_open(NULL, target) < 0)

	    term_printf("could not start VNC server on %s\n", target);

    }

}


static struct scsi_task *iscsi_do_inquiry(struct iscsi_context *iscsi, int lun,

                                          int evpd, int pc, Error **errp)

{

    int full_size;

    struct scsi_task *task = NULL;

    task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, 64);

    if (task == NULL || task->status != SCSI_STATUS_GOOD) {

        goto fail;

    }

    full_size = scsi_datain_getfullsize(task);

    if (full_size > task->datain.size) {

        scsi_free_scsi_task(task);

        /* we need more data for the full list */

        task = iscsi_inquiry_sync(iscsi, lun, evpd, pc, full_size);

        if (task == NULL || task->status != SCSI_STATUS_GOOD) {

            goto fail;

        }

    }

    return task;

fail:

    error_setg(errp, "iSCSI: Inquiry command failed : %s",

               iscsi_get_error(iscsi));

    if (task) {

        scsi_free_scsi_task(task);

        return NULL;

    }

    return NULL;

}


av_cold void rgb2rgb_init_x86(void)

{

#if HAVE_INLINE_ASM

    int cpu_flags = av_get_cpu_flags();

    if (cpu_flags & AV_CPU_FLAG_MMX)

        rgb2rgb_init_MMX();

    if (HAVE_AMD3DNOW && cpu_flags & AV_CPU_FLAG_3DNOW)

        rgb2rgb_init_3DNOW();

    if (HAVE_MMXEXT   && cpu_flags & AV_CPU_FLAG_MMXEXT)

        rgb2rgb_init_MMX2();

    if (HAVE_SSE      && cpu_flags & AV_CPU_FLAG_SSE2)

        rgb2rgb_init_SSE2();

#endif /* HAVE_INLINE_ASM */

}


static int mp3_header_compress(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,

                     uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size, int keyframe){

    uint32_t header;

    int mode_extension;

    if(avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL){

        av_log(avctx, AV_LOG_ERROR, "not standards compliant\n");

        return -1;

    }

    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];

    mode_extension= (header>>4)&3;

    if(ff_mpa_check_header(header) < 0 || (header&0x70000) != 0x30000){

        *poutbuf= (uint8_t *) buf;

        *poutbuf_size= buf_size;

        av_log(avctx, AV_LOG_INFO, "cannot compress %08X\n", header);

        return 0;

    }

    *poutbuf_size= buf_size - 4;

    *poutbuf= av_malloc(buf_size - 4 + FF_INPUT_BUFFER_PADDING_SIZE);

    memcpy(*poutbuf, buf + 4, buf_size - 4 + FF_INPUT_BUFFER_PADDING_SIZE);

    if(avctx->channels==2){

        if((header & (3<<19)) != 3<<19){

            (*poutbuf)[1] &= 0x3F;

            (*poutbuf)[1] |= mode_extension<<6;

            FFSWAP(int, (*poutbuf)[1], (*poutbuf)[2]);

        }else{

            (*poutbuf)[1] &= 0x8F;

            (*poutbuf)[1] |= mode_extension<<4;

        }

    }

    return 1;

}


static void virtio_net_add_queue(VirtIONet *n, int index)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    n->vqs[index].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx);

    if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {

        n->vqs[index].tx_vq =

            virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer);

        n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                              virtio_net_tx_timer,

                                              &n->vqs[index]);

    } else {

        n->vqs[index].tx_vq =

            virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh);

        n->vqs[index].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[index]);

    }

    n->vqs[index].tx_waiting = 0;

    n->vqs[index].n = n;

}


static int grackle_pci_host_init(PCIDevice *d)

{

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_MOTOROLA);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_MOTOROLA_MPC106);

    d->config[0x08] = 0x00; // revision

    d->config[0x09] = 0x01;

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    return 0;

}


static void icp_realize(DeviceState *dev, Error **errp)

{

    ICPState *icp = ICP(dev);

    ICPStateClass *icpc = ICP_GET_CLASS(dev);

    Object *obj;

    Error *err = NULL;

    obj = object_property_get_link(OBJECT(dev), ICP_PROP_XICS, &err);

    if (!obj) {

        error_setg(errp, "%s: required link '" ICP_PROP_XICS "' not found: %s",

                   __func__, error_get_pretty(err));

        return;

    }

    icp->xics = XICS_FABRIC(obj);

    if (icpc->realize) {

        icpc->realize(dev, errp);

    }

    qemu_register_reset(icp_reset, dev);

}


static void test_visitor_in_native_list_int(TestInputVisitorData *data,

                                            const void *unused)

{

    test_native_list_integer_helper(data, unused,

                                    USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER);

}


static void test_qemu_strtoull_max(void)

{

    char *str = g_strdup_printf("%llu", ULLONG_MAX);

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, ULLONG_MAX);

    g_assert(endptr == str + strlen(str));

    g_free(str);

}


static inline void* array_get_next(array_t* array) {

    unsigned int next = array->next;

    void* result;

    if (array_ensure_allocated(array, next) < 0)

	return NULL;

    array->next = next + 1;

    result = array_get(array, next);

    return result;

}


static int raw_read(BlockDriverState *bs, int64_t sector_num,

                    uint8_t *buf, int nb_sectors)

{

    return bdrv_read(bs->file, sector_num, buf, nb_sectors);

}


static uint32_t omap2_gpio_module_readp(void *opaque, target_phys_addr_t addr)

{

    return omap2_gpio_module_readp(opaque, addr) >> ((addr & 3) << 3);

}


static void guest_fsfreeze_cleanup(void)

{

    int64_t ret;

    Error *err = NULL;

    if (ga_is_frozen(ga_state) == GUEST_FSFREEZE_STATUS_FROZEN) {

        ret = qmp_guest_fsfreeze_thaw(&err);

        if (ret < 0 || err) {

            slog("failed to clean up frozen filesystems");

        }

    }

}


static int set_segment_filename(AVFormatContext *s)

{

    SegmentContext *seg = s->priv_data;

    AVFormatContext *oc = seg->avf;

    size_t size;

    if (seg->segment_idx_wrap)

        seg->segment_idx %= seg->segment_idx_wrap;

    if (seg->use_strftime) {

        time_t now0;

        struct tm *tm, tmpbuf;

        time(&now0);

        tm = localtime_r(&now0, &tmpbuf);

        if (!strftime(oc->filename, sizeof(oc->filename), s->filename, tm)) {

            av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");

            return AVERROR(EINVAL);

        }

    } else if (av_get_frame_filename(oc->filename, sizeof(oc->filename),

                                     s->filename, seg->segment_idx) < 0) {

        av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", s->filename);

        return AVERROR(EINVAL);

    }

    /* copy modified name in list entry */

    size = strlen(av_basename(oc->filename)) + 1;

    if (seg->entry_prefix)

        size += strlen(seg->entry_prefix);

    seg->cur_entry.filename = av_mallocz(size);

    if (!seg->cur_entry.filename)

        return AVERROR(ENOMEM);

    snprintf(seg->cur_entry.filename, size, "%s%s",

             seg->entry_prefix ? seg->entry_prefix : "",

             av_basename(oc->filename));

    return 0;

}


petalogix_s3adsp1800_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    DeviceState *dev;

    MicroBlazeCPU *cpu;

    DriveInfo *dinfo;

    int i;

    hwaddr ddr_base = MEMORY_BASEADDR;

    MemoryRegion *phys_lmb_bram = g_new(MemoryRegion, 1);

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    qemu_irq irq[32];

    MemoryRegion *sysmem = get_system_memory();

    cpu = MICROBLAZE_CPU(object_new(TYPE_MICROBLAZE_CPU));

    object_property_set_bool(OBJECT(cpu), true, "realized", &error_abort);

    /* Attach emulated BRAM through the LMB.  */

    memory_region_init_ram(phys_lmb_bram, NULL,

                           "petalogix_s3adsp1800.lmb_bram", LMB_BRAM_SIZE,

                           &error_abort);

    vmstate_register_ram_global(phys_lmb_bram);

    memory_region_add_subregion(sysmem, 0x00000000, phys_lmb_bram);

    memory_region_init_ram(phys_ram, NULL, "petalogix_s3adsp1800.ram",

                           ram_size, &error_abort);

    vmstate_register_ram_global(phys_ram);

    memory_region_add_subregion(sysmem, ddr_base, phys_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    pflash_cfi01_register(FLASH_BASEADDR,

                          NULL, "petalogix_s3adsp1800.flash", FLASH_SIZE,

                          dinfo ? blk_by_legacy_dinfo(dinfo) : NULL,

                          (64 * 1024), FLASH_SIZE >> 16,

                          1, 0x89, 0x18, 0x0000, 0x0, 1);

    dev = qdev_create(NULL, "xlnx.xps-intc");

    qdev_prop_set_uint32(dev, "kind-of-intr",

                         1 << ETHLITE_IRQ | 1 << UARTLITE_IRQ);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, INTC_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0,

                       qdev_get_gpio_in(DEVICE(cpu), MB_CPU_IRQ));

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

        irq[i] = qdev_get_gpio_in(dev, i);

    }

    sysbus_create_simple("xlnx.xps-uartlite", UARTLITE_BASEADDR,

                         irq[UARTLITE_IRQ]);

    /* 2 timers at irq 2 @ 62 Mhz.  */

    dev = qdev_create(NULL, "xlnx.xps-timer");

    qdev_prop_set_uint32(dev, "one-timer-only", 0);

    qdev_prop_set_uint32(dev, "clock-frequency", 62 * 1000000);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, TIMER_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq[TIMER_IRQ]);

    qemu_check_nic_model(&nd_table[0], "xlnx.xps-ethernetlite");

    dev = qdev_create(NULL, "xlnx.xps-ethernetlite");

    qdev_set_nic_properties(dev, &nd_table[0]);

    qdev_prop_set_uint32(dev, "tx-ping-pong", 0);

    qdev_prop_set_uint32(dev, "rx-ping-pong", 0);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, ETHLITE_BASEADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq[ETHLITE_IRQ]);

    microblaze_load_kernel(cpu, ddr_base, ram_size,

                           machine->initrd_filename,

                           BINARY_DEVICE_TREE_FILE,

                           NULL);

}


static ssize_t flush_buf(VirtIOSerialPort *port,
                         const uint8_t *buf, ssize_t len)
{
    VirtConsole *vcon = VIRTIO_CONSOLE(port);
    ssize_t ret;
    if (!vcon->chr) {
        /* If there's no backend, we can just say we consumed all data. */
        return len;
    }
    ret = qemu_chr_fe_write(vcon->chr, buf, len);
    trace_virtio_console_flush_buf(port->id, len, ret);
    if (ret < len) {
        VirtIOSerialPortClass *k = VIRTIO_SERIAL_PORT_GET_CLASS(port);
        /*
         * Ideally we'd get a better error code than just -1, but
         * that's what the chardev interface gives us right now.  If
         * we had a finer-grained message, like -EPIPE, we could close
         * this connection.
        if (ret < 0)
            ret = 0;
        if (!k->is_console) {
            virtio_serial_throttle_port(port, true);
            if (!vcon->watch) {
                vcon->watch = qemu_chr_fe_add_watch(vcon->chr,
                                                    G_IO_OUT|G_IO_HUP,
                                                    chr_write_unblocked, vcon);
            }
        }
    }
    return ret;
}


static void tcp_chr_read(void *opaque)

{

    CharDriverState *chr = opaque;

    TCPCharDriver *s = chr->opaque;

    uint8_t buf[READ_BUF_LEN];

    int len, size;

    if (!s->connected || s->max_size <= 0)

        return;

    len = sizeof(buf);

    if (len > s->max_size)

        len = s->max_size;

    size = tcp_chr_recv(chr, (void *)buf, len);

    if (size == 0) {

        /* connection closed */

        s->connected = 0;

        if (s->listen_fd >= 0) {

            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);

        }

        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);

        closesocket(s->fd);

        s->fd = -1;

        qemu_chr_event(chr, CHR_EVENT_CLOSED);

    } else if (size > 0) {

        if (s->do_telnetopt)

            tcp_chr_process_IAC_bytes(chr, s, buf, &size);

        if (size > 0)

            qemu_chr_read(chr, buf, size);

        if (s->msgfd != -1) {

            close(s->msgfd);

            s->msgfd = -1;

        }

    }

}


static int hwmap_filter_frame(AVFilterLink *link, AVFrame *input)

{

    AVFilterContext *avctx = link->dst;

    AVFilterLink  *outlink = avctx->outputs[0];

    HWMapContext      *ctx = avctx->priv;

    AVFrame *map = NULL;

    int err;

    av_log(ctx, AV_LOG_DEBUG, "Filter input: %s, %ux%u (%"PRId64").\n",

           av_get_pix_fmt_name(input->format),

           input->width, input->height, input->pts);

    map = av_frame_alloc();

    if (!map) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    map->format = outlink->format;

    map->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);

    if (!map->hw_frames_ctx) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    if (ctx->map_backwards && !input->hw_frames_ctx) {

        // If we mapped backwards from hardware to software, we need

        // to attach the hardware frame context to the input frame to

        // make the mapping visible to av_hwframe_map().

        input->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);

        if (!input->hw_frames_ctx) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

    }

    err = av_hwframe_map(map, input, ctx->mode);

    if (err < 0) {

        av_log(avctx, AV_LOG_ERROR, "Failed to map frame: %d.\n", err);

        goto fail;

    }

    err = av_frame_copy_props(map, input);

    if (err < 0)

        goto fail;

    av_frame_free(&input);

    av_log(ctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",

           av_get_pix_fmt_name(map->format),

           map->width, map->height, map->pts);

    return ff_filter_frame(outlink, map);

fail:

    av_frame_free(&input);

    av_frame_free(&map);

    return err;

}


void virtio_panic(const char *string)

{

    sclp_print(string);

    disabled_wait();

    while (1) { }

}


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

                              int *got_frame_ptr, AVPacket *avpkt)

{

    OpusContext *c      = avctx->priv_data;

    AVFrame *frame      = data;

    const uint8_t *buf  = avpkt->data;

    int buf_size        = avpkt->size;

    int coded_samples   = 0;

    int decoded_samples = 0;

    int i, ret;

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

        OpusStreamContext *s = &c->streams[i];

        s->out[0] =

        s->out[1] = NULL;

    }

    /* decode the header of the first sub-packet to find out the sample count */

    if (buf) {

        OpusPacket *pkt = &c->streams[0].packet;

        ret = ff_opus_parse_packet(pkt, buf, buf_size, c->nb_streams > 1);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");

            return ret;

        }

        coded_samples += pkt->frame_count * pkt->frame_duration;

        c->streams[0].silk_samplerate = get_silk_samplerate(pkt->config);

    }

    frame->nb_samples = coded_samples + c->streams[0].delayed_samples;

    /* no input or buffered data => nothing to do */

    if (!frame->nb_samples) {

        *got_frame_ptr = 0;

        return 0;

    }

    /* setup the data buffers */

    ret = ff_get_buffer(avctx, frame, 0);

    if (ret < 0)

        return ret;

    frame->nb_samples = 0;

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

        ChannelMap *map = &c->channel_maps[i];

        if (!map->copy)

            c->streams[map->stream_idx].out[map->channel_idx] = (float*)frame->extended_data[i];

    }

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

        c->streams[i].out_size = frame->linesize[0];

    /* decode each sub-packet */

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

        OpusStreamContext *s = &c->streams[i];

        if (i && buf) {

            ret = ff_opus_parse_packet(&s->packet, buf, buf_size, i != c->nb_streams - 1);

            if (ret < 0) {

                av_log(avctx, AV_LOG_ERROR, "Error parsing the packet header.\n");

                return ret;

            }

            if (coded_samples != s->packet.frame_count * s->packet.frame_duration) {

                av_log(avctx, AV_LOG_ERROR,

                       "Mismatching coded sample count in substream %d.\n", i);

                return AVERROR_INVALIDDATA;

            }

            s->silk_samplerate = get_silk_samplerate(s->packet.config);

        }

        ret = opus_decode_subpacket(&c->streams[i], buf,

                                    s->packet.data_size, coded_samples);

        if (ret < 0)

            return ret;

        if (decoded_samples && ret != decoded_samples) {

            av_log(avctx, AV_LOG_ERROR, "Different numbers of decoded samples "

                   "in a multi-channel stream\n");

            return AVERROR_INVALIDDATA;

        }

        decoded_samples = ret;

        buf      += s->packet.packet_size;

        buf_size -= s->packet.packet_size;

    }

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

        ChannelMap *map = &c->channel_maps[i];

        /* handle copied channels */

        if (map->copy) {

            memcpy(frame->extended_data[i],

                   frame->extended_data[map->copy_idx],

                   frame->linesize[0]);

        } else if (map->silence) {

            memset(frame->extended_data[i], 0, frame->linesize[0]);

        }

        if (c->gain_i) {

            c->fdsp->vector_fmul_scalar((float*)frame->extended_data[i],

                                       (float*)frame->extended_data[i],

                                       c->gain, FFALIGN(decoded_samples, 8));

        }

    }

    frame->nb_samples = decoded_samples;

    *got_frame_ptr    = !!decoded_samples;

    return avpkt->size;

}


bool migrate_zero_blocks(void)

{

    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];

}


static void av_always_inline filter_mb_dir(H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize, int mb_xy, int mb_type, int mvy_limit, int first_vertical_edge_done, int dir) {

    MpegEncContext * const s = &h->s;

    int edge;

    const int mbm_xy = dir == 0 ? mb_xy -1 : h->top_mb_xy;

    const int mbm_type = s->current_picture.mb_type[mbm_xy];

    int (*ref2frm) [64] = h->ref2frm[ h->slice_num          &(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);

    int (*ref2frmm)[64] = h->ref2frm[ h->slice_table[mbm_xy]&(MAX_SLICES-1) ][0] + (MB_MBAFF ? 20 : 2);

    int start = h->slice_table[mbm_xy] == 0xFFFF ? 1 : 0;

    const int edges = (mb_type & (MB_TYPE_16x16|MB_TYPE_SKIP))

                              == (MB_TYPE_16x16|MB_TYPE_SKIP) ? 1 : 4;

    // how often to recheck mv-based bS when iterating between edges

    const int mask_edge = (mb_type & (MB_TYPE_16x16 | (MB_TYPE_16x8 << dir))) ? 3 :

                          (mb_type & (MB_TYPE_8x16 >> dir)) ? 1 : 0;

    // how often to recheck mv-based bS when iterating along each edge

    const int mask_par0 = mb_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir));

    if (first_vertical_edge_done) {

        start = 1;

    }

    if (h->deblocking_filter==2 && h->slice_table[mbm_xy] != h->slice_table[mb_xy])

        start = 1;

    if (FRAME_MBAFF && (dir == 1) && ((mb_y&1) == 0) && start == 0

        && !IS_INTERLACED(mb_type)

        && IS_INTERLACED(mbm_type)

        ) {

        // This is a special case in the norm where the filtering must

        // be done twice (one each of the field) even if we are in a

        // frame macroblock.

        //

        static const int nnz_idx[4] = {4,5,6,3};

        unsigned int tmp_linesize   = 2 *   linesize;

        unsigned int tmp_uvlinesize = 2 * uvlinesize;

        int mbn_xy = mb_xy - 2 * s->mb_stride;

        int qp;

        int i, j;

        int16_t bS[4];

        for(j=0; j<2; j++, mbn_xy += s->mb_stride){

            if( IS_INTRA(mb_type) ||

                IS_INTRA(s->current_picture.mb_type[mbn_xy]) ) {

                bS[0] = bS[1] = bS[2] = bS[3] = 3;

            } else {

                const uint8_t *mbn_nnz = h->non_zero_count[mbn_xy];

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

                    if( h->non_zero_count_cache[scan8[0]+i] != 0 ||

                        mbn_nnz[nnz_idx[i]] != 0 )

                        bS[i] = 2;

                    else

                        bS[i] = 1;

                }

            }

            // Do not use s->qscale as luma quantizer because it has not the same

            // value in IPCM macroblocks.

            qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;

            tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, tmp_linesize, tmp_uvlinesize);

            { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }

            filter_mb_edgeh( h, &img_y[j*linesize], tmp_linesize, bS, qp );

            filter_mb_edgech( h, &img_cb[j*uvlinesize], tmp_uvlinesize, bS,

                              ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

            filter_mb_edgech( h, &img_cr[j*uvlinesize], tmp_uvlinesize, bS,

                              ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

        }

        start = 1;

    }

    /* Calculate bS */

    for( edge = start; edge < edges; edge++ ) {

        /* mbn_xy: neighbor macroblock */

        const int mbn_xy = edge > 0 ? mb_xy : mbm_xy;

        const int mbn_type = s->current_picture.mb_type[mbn_xy];

        int (*ref2frmn)[64] = edge > 0 ? ref2frm : ref2frmm;

        int16_t bS[4];

        int qp;

        if( (edge&1) && IS_8x8DCT(mb_type) )

            continue;

        if( IS_INTRA(mb_type) ||

            IS_INTRA(mbn_type) ) {

            int value;

            if (edge == 0) {

                if (   (!IS_INTERLACED(mb_type) && !IS_INTERLACED(mbm_type))

                    || ((FRAME_MBAFF || (s->picture_structure != PICT_FRAME)) && (dir == 0))

                ) {

                    value = 4;

                } else {

                    value = 3;

                }

            } else {

                value = 3;

            }

            bS[0] = bS[1] = bS[2] = bS[3] = value;

        } else {

            int i, l;

            int mv_done;

            if( edge & mask_edge ) {

                bS[0] = bS[1] = bS[2] = bS[3] = 0;

                mv_done = 1;

            }

            else if( FRAME_MBAFF && IS_INTERLACED(mb_type ^ mbn_type)) {

                bS[0] = bS[1] = bS[2] = bS[3] = 1;

                mv_done = 1;

            }

            else if( mask_par0 && (edge || (mbn_type & (MB_TYPE_16x16 | (MB_TYPE_8x16 >> dir)))) ) {

                int b_idx= 8 + 4 + edge * (dir ? 8:1);

                int bn_idx= b_idx - (dir ? 8:1);

                int v = 0;

                for( l = 0; !v && l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {

                    v |= ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[l][h->ref_cache[l][bn_idx]] ||

                         FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||

                         FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit;

                }

                if(h->slice_type_nos == FF_B_TYPE && v){

                    v=0;

                    for( l = 0; !v && l < 2; l++ ) {

                        int ln= 1-l;

                        v |= ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[ln][h->ref_cache[ln][bn_idx]] ||

                            FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||

                            FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit;

                    }

                }

                bS[0] = bS[1] = bS[2] = bS[3] = v;

                mv_done = 1;

            }

            else

                mv_done = 0;

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

                int x = dir == 0 ? edge : i;

                int y = dir == 0 ? i    : edge;

                int b_idx= 8 + 4 + x + 8*y;

                int bn_idx= b_idx - (dir ? 8:1);

                if( h->non_zero_count_cache[b_idx] != 0 ||

                    h->non_zero_count_cache[bn_idx] != 0 ) {

                    bS[i] = 2;

                }

                else if(!mv_done)

                {

                    bS[i] = 0;

                    for( l = 0; l < 1 + (h->slice_type_nos == FF_B_TYPE); l++ ) {

                        if( ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[l][h->ref_cache[l][bn_idx]] ||

                            FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[l][bn_idx][0] ) >= 4 ||

                            FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[l][bn_idx][1] ) >= mvy_limit ) {

                            bS[i] = 1;

                            break;

                        }

                    }

                    if(h->slice_type_nos == FF_B_TYPE && bS[i]){

                        bS[i] = 0;

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

                            int ln= 1-l;

                            if( ref2frm[l][h->ref_cache[l][b_idx]] != ref2frmn[ln][h->ref_cache[ln][bn_idx]] ||

                                FFABS( h->mv_cache[l][b_idx][0] - h->mv_cache[ln][bn_idx][0] ) >= 4 ||

                                FFABS( h->mv_cache[l][b_idx][1] - h->mv_cache[ln][bn_idx][1] ) >= mvy_limit ) {

                                bS[i] = 1;

                                break;

                            }

                        }

                    }

                }

            }

            if(bS[0]+bS[1]+bS[2]+bS[3] == 0)

                continue;

        }

        /* Filter edge */

        // Do not use s->qscale as luma quantizer because it has not the same

        // value in IPCM macroblocks.

        qp = ( s->current_picture.qscale_table[mb_xy] + s->current_picture.qscale_table[mbn_xy] + 1 ) >> 1;

        //tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d, QPc:%d, QPcn:%d\n", mb_x, mb_y, dir, edge, qp, h->chroma_qp, s->current_picture.qscale_table[mbn_xy]);

        tprintf(s->avctx, "filter mb:%d/%d dir:%d edge:%d, QPy:%d ls:%d uvls:%d", mb_x, mb_y, dir, edge, qp, linesize, uvlinesize);

        { int i; for (i = 0; i < 4; i++) tprintf(s->avctx, " bS[%d]:%d", i, bS[i]); tprintf(s->avctx, "\n"); }

        if( dir == 0 ) {

            filter_mb_edgev( h, &img_y[4*edge], linesize, bS, qp );

            if( (edge&1) == 0 ) {

                filter_mb_edgecv( h, &img_cb[2*edge], uvlinesize, bS,

                                  ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                filter_mb_edgecv( h, &img_cr[2*edge], uvlinesize, bS,

                                  ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

            }

        } else {

            filter_mb_edgeh( h, &img_y[4*edge*linesize], linesize, bS, qp );

            if( (edge&1) == 0 ) {

                filter_mb_edgech( h, &img_cb[2*edge*uvlinesize], uvlinesize, bS,

                                  ( h->chroma_qp[0] + get_chroma_qp( h, 0, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

                filter_mb_edgech( h, &img_cr[2*edge*uvlinesize], uvlinesize, bS,

                                  ( h->chroma_qp[1] + get_chroma_qp( h, 1, s->current_picture.qscale_table[mbn_xy] ) + 1 ) >> 1);

            }

        }

    }

}


static int ehci_state_executing(EHCIQueue *q)

{

    EHCIPacket *p = QTAILQ_FIRST(&q->packets);

    int again = 0;

    assert(p != NULL);

    assert(p->qtdaddr == q->qtdaddr);

    ehci_execute_complete(q);

    if (p->usb_status == USB_RET_ASYNC) {

        goto out;

    }

    if (p->usb_status == USB_RET_PROCERR) {

        again = -1;

        goto out;

    }

    // 4.10.3

    if (!q->async) {

        int transactCtr = get_field(q->qh.epcap, QH_EPCAP_MULT);

        transactCtr--;

        set_field(&q->qh.epcap, transactCtr, QH_EPCAP_MULT);

        // 4.10.3, bottom of page 82, should exit this state when transaction

        // counter decrements to 0

    }

    /* 4.10.5 */

    if (p->usb_status == USB_RET_NAK) {

        ehci_set_state(q->ehci, q->async, EST_HORIZONTALQH);

    } else {

        ehci_set_state(q->ehci, q->async, EST_WRITEBACK);

    }

    again = 1;

out:

    ehci_flush_qh(q);

    return again;

}


static void qemu_spice_create_update(SimpleSpiceDisplay *ssd)

{

    static const int blksize = 32;

    int blocks = (surface_width(ssd->ds) + blksize - 1) / blksize;

    int dirty_top[blocks];

    int y, yoff, x, xoff, blk, bw;

    int bpp = surface_bytes_per_pixel(ssd->ds);

    uint8_t *guest, *mirror;

    if (qemu_spice_rect_is_empty(&ssd->dirty)) {

        return;

    };

    for (blk = 0; blk < blocks; blk++) {

        dirty_top[blk] = -1;

    }

    guest = surface_data(ssd->ds);

    mirror = (void *)pixman_image_get_data(ssd->mirror);

    for (y = ssd->dirty.top; y < ssd->dirty.bottom; y++) {

        yoff = y * surface_stride(ssd->ds);

        for (x = ssd->dirty.left; x < ssd->dirty.right; x += blksize) {

            xoff = x * bpp;

            blk = x / blksize;

            bw = MIN(blksize, ssd->dirty.right - x);

            if (memcmp(guest + yoff + xoff,

                       mirror + yoff + xoff,

                       bw * bpp) == 0) {

                if (dirty_top[blk] != -1) {

                    QXLRect update = {

                        .top    = dirty_top[blk],

                        .bottom = y,

                        .left   = x,

                        .right  = x + bw,

                    };

                    qemu_spice_create_one_update(ssd, &update);

                    dirty_top[blk] = -1;

                }

            } else {

                if (dirty_top[blk] == -1) {

                    dirty_top[blk] = y;

                }

            }

        }

    }

    for (x = ssd->dirty.left; x < ssd->dirty.right; x += blksize) {

        blk = x / blksize;

        bw = MIN(blksize, ssd->dirty.right - x);

        if (dirty_top[blk] != -1) {

            QXLRect update = {

                .top    = dirty_top[blk],

                .bottom = ssd->dirty.bottom,

                .left   = x,

                .right  = x + bw,

            };

            qemu_spice_create_one_update(ssd, &update);

            dirty_top[blk] = -1;

        }

    }

    memset(&ssd->dirty, 0, sizeof(ssd->dirty));

}


void tcp_connect(struct socket *inso)

{

    Slirp *slirp = inso->slirp;

    struct socket *so;

    struct sockaddr_in addr;

    socklen_t addrlen = sizeof(struct sockaddr_in);

    struct tcpcb *tp;

    int s, opt;

    DEBUG_CALL("tcp_connect");

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

    /*

     * If it's an SS_ACCEPTONCE socket, no need to socreate()

     * another socket, just use the accept() socket.

     */

    if (inso->so_state & SS_FACCEPTONCE) {

        /* FACCEPTONCE already have a tcpcb */

        so = inso;

    } else {

        so = socreate(slirp);

        if (so == NULL) {

            /* If it failed, get rid of the pending connection */

            closesocket(accept(inso->s, (struct sockaddr *)&addr, &addrlen));

            return;

        }

        if (tcp_attach(so) < 0) {

            free(so); /* NOT sofree */

            return;

        }

        so->so_lfamily = AF_INET;

        so->so_laddr = inso->so_laddr;

        so->so_lport = inso->so_lport;

    }

    tcp_mss(sototcpcb(so), 0);

    s = accept(inso->s, (struct sockaddr *)&addr, &addrlen);

    if (s < 0) {

        tcp_close(sototcpcb(so)); /* This will sofree() as well */

        return;

    }

    qemu_set_nonblock(s);

    socket_set_fast_reuse(s);

    opt = 1;

    qemu_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(int));

    socket_set_nodelay(s);

    so->so_ffamily = AF_INET;

    so->so_fport = addr.sin_port;

    so->so_faddr = addr.sin_addr;

    /* Translate connections from localhost to the real hostname */

    if (so->so_faddr.s_addr == 0 ||

        (so->so_faddr.s_addr & loopback_mask) ==

        (loopback_addr.s_addr & loopback_mask)) {

        so->so_faddr = slirp->vhost_addr;

    }

    /* Close the accept() socket, set right state */

    if (inso->so_state & SS_FACCEPTONCE) {

        /* If we only accept once, close the accept() socket */

        closesocket(so->s);

        /* Don't select it yet, even though we have an FD */

        /* if it's not FACCEPTONCE, it's already NOFDREF */

        so->so_state = SS_NOFDREF;

    }

    so->s = s;

    so->so_state |= SS_INCOMING;

    so->so_iptos = tcp_tos(so);

    tp = sototcpcb(so);

    tcp_template(tp);

    tp->t_state = TCPS_SYN_SENT;

    tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;

    tp->iss = slirp->tcp_iss;

    slirp->tcp_iss += TCP_ISSINCR/2;

    tcp_sendseqinit(tp);

    tcp_output(tp);

}


static int vorbis_parse_setup_hdr_modes(vorbis_context *vc) {

    GetBitContext *gb=&vc->gb;

    uint_fast8_t i;

    vc->mode_count=get_bits(gb, 6)+1;

    vc->modes=(vorbis_mode *)av_mallocz(vc->mode_count * sizeof(vorbis_mode));

    AV_DEBUG(" There are %d modes.\n", vc->mode_count);

    for(i=0;i<vc->mode_count;++i) {

        vorbis_mode *mode_setup=&vc->modes[i];

        mode_setup->blockflag=get_bits1(gb);

        mode_setup->windowtype=get_bits(gb, 16); //FIXME check

        mode_setup->transformtype=get_bits(gb, 16); //FIXME check

        mode_setup->mapping=get_bits(gb, 8); //FIXME check

        AV_DEBUG(" %d mode: blockflag %d, windowtype %d, transformtype %d, mapping %d \n", i, mode_setup->blockflag, mode_setup->windowtype, mode_setup->transformtype, mode_setup->mapping);

    }

    return 0;

}


static void check_exception(sPAPREnvironment *spapr,

                            uint32_t token, uint32_t nargs,

                            target_ulong args,

                            uint32_t nret, target_ulong rets)

{

    uint32_t mask, buf, len;

    uint64_t xinfo;

    if ((nargs < 6) || (nargs > 7) || nret != 1) {

        rtas_st(rets, 0, -3);

        return;

    }

    xinfo = rtas_ld(args, 1);

    mask = rtas_ld(args, 2);

    buf = rtas_ld(args, 4);

    len = rtas_ld(args, 5);

    if (nargs == 7) {

        xinfo |= (uint64_t)rtas_ld(args, 6) << 32;

    }

    if ((mask & EVENT_MASK_EPOW) && pending_epow) {

        if (sizeof(*pending_epow) < len) {

            len = sizeof(*pending_epow);

        }

        cpu_physical_memory_write(buf, pending_epow, len);

        g_free(pending_epow);

        pending_epow = NULL;

        rtas_st(rets, 0, 0);

    } else {

        rtas_st(rets, 0, 1);

    }

}