int vc1_decode_sequence_header(AVCodecContext *avctx, VC1Context *v, GetBitContext *gb)

{

    av_log(avctx, AV_LOG_DEBUG, "Header: %0X\n", show_bits(gb, 32));

    v->profile = get_bits(gb, 2);

    if (v->profile == PROFILE_COMPLEX)

    {

        av_log(avctx, AV_LOG_WARNING, "WMV3 Complex Profile is not fully supported\n");

    }

    if (v->profile == PROFILE_ADVANCED)

    {

        v->zz_8x4 = ff_vc1_adv_progressive_8x4_zz;

        v->zz_4x8 = ff_vc1_adv_progressive_4x8_zz;

        return decode_sequence_header_adv(v, gb);

    }

    else

    {

        v->zz_8x4 = wmv2_scantableA;

        v->zz_4x8 = wmv2_scantableB;

        v->res_y411   = get_bits1(gb);

        v->res_sprite = get_bits1(gb);

        if (v->res_y411)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Old interlaced mode is not supported\n");

            return -1;

        }

        if (v->res_sprite) {

            av_log(avctx, AV_LOG_ERROR, "WMVP is not fully supported\n");

        }

    }

    // (fps-2)/4 (->30)

    v->frmrtq_postproc = get_bits(gb, 3); //common

    // (bitrate-32kbps)/64kbps

    v->bitrtq_postproc = get_bits(gb, 5); //common

    v->s.loop_filter = get_bits1(gb); //common

    if(v->s.loop_filter == 1 && v->profile == PROFILE_SIMPLE)

    {

        av_log(avctx, AV_LOG_ERROR,

               "LOOPFILTER shall not be enabled in Simple Profile\n");

    }

    if(v->s.avctx->skip_loop_filter >= AVDISCARD_ALL)

        v->s.loop_filter = 0;

    v->res_x8 = get_bits1(gb); //reserved

    v->multires = get_bits1(gb);

    v->res_fasttx = get_bits1(gb);

    if (!v->res_fasttx)

    {

        v->vc1dsp.vc1_inv_trans_8x8 = ff_simple_idct;

        v->vc1dsp.vc1_inv_trans_8x4 = ff_simple_idct84_add;

        v->vc1dsp.vc1_inv_trans_4x8 = ff_simple_idct48_add;

        v->vc1dsp.vc1_inv_trans_4x4 = ff_simple_idct44_add;

        v->vc1dsp.vc1_inv_trans_8x8_dc = ff_simple_idct_add;

        v->vc1dsp.vc1_inv_trans_8x4_dc = ff_simple_idct84_add;

        v->vc1dsp.vc1_inv_trans_4x8_dc = ff_simple_idct48_add;

        v->vc1dsp.vc1_inv_trans_4x4_dc = ff_simple_idct44_add;

    }

    v->fastuvmc =  get_bits1(gb); //common

    if (!v->profile && !v->fastuvmc)

    {

        av_log(avctx, AV_LOG_ERROR,

               "FASTUVMC unavailable in Simple Profile\n");

        return -1;

    }

    v->extended_mv =  get_bits1(gb); //common

    if (!v->profile && v->extended_mv)

    {

        av_log(avctx, AV_LOG_ERROR,

               "Extended MVs unavailable in Simple Profile\n");

        return -1;

    }

    v->dquant =  get_bits(gb, 2); //common

    v->vstransform =  get_bits1(gb); //common

    v->res_transtab = get_bits1(gb);

    if (v->res_transtab)

    {

        av_log(avctx, AV_LOG_ERROR,

               "1 for reserved RES_TRANSTAB is forbidden\n");

        return -1;

    }

    v->overlap = get_bits1(gb); //common

    v->s.resync_marker = get_bits1(gb);

    v->rangered = get_bits1(gb);

    if (v->rangered && v->profile == PROFILE_SIMPLE)

    {

        av_log(avctx, AV_LOG_INFO,

               "RANGERED should be set to 0 in Simple Profile\n");

    }

    v->s.max_b_frames = avctx->max_b_frames = get_bits(gb, 3); //common

    v->quantizer_mode = get_bits(gb, 2); //common

    v->finterpflag = get_bits1(gb); //common

    if (v->res_sprite) {

        v->s.avctx->width  = v->s.avctx->coded_width  = get_bits(gb, 11);

        v->s.avctx->height = v->s.avctx->coded_height = get_bits(gb, 11);

        skip_bits(gb, 5); //frame rate

        v->res_x8 = get_bits1(gb);

        if (get_bits1(gb)) { // something to do with DC VLC selection

            av_log(avctx, AV_LOG_ERROR, "Unsupported sprite feature\n");

            return -1;

        }

        skip_bits(gb, 3); //slice code

        v->res_rtm_flag = 0;

    } else {

        v->res_rtm_flag = get_bits1(gb); //reserved

    }

    if (!v->res_rtm_flag)

    {

//            av_log(avctx, AV_LOG_ERROR,

//                   "0 for reserved RES_RTM_FLAG is forbidden\n");

        av_log(avctx, AV_LOG_ERROR,

               "Old WMV3 version detected, some frames may be decoded incorrectly\n");

        //return -1;

    }

    //TODO: figure out what they mean (always 0x402F)

    if(!v->res_fasttx) skip_bits(gb, 16);

    av_log(avctx, AV_LOG_DEBUG,

               "Profile %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"

               "LoopFilter=%i, MultiRes=%i, FastUVMC=%i, Extended MV=%i\n"

               "Rangered=%i, VSTransform=%i, Overlap=%i, SyncMarker=%i\n"

               "DQuant=%i, Quantizer mode=%i, Max B frames=%i\n",

               v->profile, v->frmrtq_postproc, v->bitrtq_postproc,

               v->s.loop_filter, v->multires, v->fastuvmc, v->extended_mv,

               v->rangered, v->vstransform, v->overlap, v->s.resync_marker,

               v->dquant, v->quantizer_mode, avctx->max_b_frames

               );

    return 0;

}


static int parse_ptl(HEVCContext *s, PTL *ptl, int max_num_sub_layers)

{

    int i;

    HEVCLocalContext *lc = s->HEVClc;

    GetBitContext *gb = &lc->gb;

    decode_profile_tier_level(s, &ptl->general_PTL);

    ptl->general_PTL.level_idc = get_bits(gb, 8);

    for (i = 0; i < max_num_sub_layers - 1; i++) {

        ptl->sub_layer_profile_present_flag[i] = get_bits1(gb);

        ptl->sub_layer_level_present_flag[i]   = get_bits1(gb);

    }

    if (max_num_sub_layers - 1> 0)

        for (i = max_num_sub_layers - 1; i < 8; i++)

            skip_bits(gb, 2); // reserved_zero_2bits[i]

    for (i = 0; i < max_num_sub_layers - 1; i++) {

        if (ptl->sub_layer_profile_present_flag[i])

            decode_profile_tier_level(s, &ptl->sub_layer_PTL[i]);

        if (ptl->sub_layer_level_present_flag[i])

            ptl->sub_layer_PTL[i].level_idc = get_bits(gb, 8);

    }

    return 0;

}


static inline int msmpeg4_decode_block(MpegEncContext * s, DCTELEM * block,

                              int n, int coded, const uint8_t *scan_table)

{

    int level, i, last, run, run_diff;

    int dc_pred_dir;

    RLTable *rl;

    RL_VLC_ELEM *rl_vlc;

    int qmul, qadd;

    if (s->mb_intra) {

        qmul=1;

        qadd=0;

	/* DC coef */

        set_stat(ST_DC);

        level = msmpeg4_decode_dc(s, n, &dc_pred_dir);

#ifdef PRINT_MB

{

    static int c;

    if(n==0) c=0;

    if(n==4) printf("%X", c);

    c+= c +dc_pred_dir;

}

#endif

        if (level < 0){

            fprintf(stderr, "dc overflow- block: %d qscale: %d//\n", n, s->qscale);

            if(s->inter_intra_pred) level=0;

            else                    return -1;

        }

        if (n < 4) {

            rl = &rl_table[s->rl_table_index];

            if(level > 256*s->y_dc_scale){

                fprintf(stderr, "dc overflow+ L qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        } else {

            rl = &rl_table[3 + s->rl_chroma_table_index];

            if(level > 256*s->c_dc_scale){

                fprintf(stderr, "dc overflow+ C qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        }

        block[0] = level;

        run_diff = 0;

        i = 0;

        if (!coded) {

            goto not_coded;

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        set_stat(ST_INTRA_AC);

        rl_vlc= rl->rl_vlc[0];

    } else {

        qmul = s->qscale << 1;

        qadd = (s->qscale - 1) | 1;

        i = -1;

        rl = &rl_table[3 + s->rl_table_index];

        if(s->msmpeg4_version==2)

            run_diff = 0;

        else

            run_diff = 1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        if(!scan_table)

            scan_table = s->inter_scantable.permutated;

        set_stat(ST_INTER_AC);

        rl_vlc= rl->rl_vlc[s->qscale];

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

        if (level==0) {

            int cache;

            cache= GET_CACHE(re, &s->gb);

            /* escape */

            if (s->msmpeg4_version==1 || (cache&0x80000000)==0) {

                if (s->msmpeg4_version==1 || (cache&0x40000000)==0) {

                    /* third escape */

                    if(s->msmpeg4_version!=1) LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

                    if(s->msmpeg4_version<=3){

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                        run=   SHOW_UBITS(re, &s->gb, 6); SKIP_CACHE(re, &s->gb, 6);

                        level= SHOW_SBITS(re, &s->gb, 8); LAST_SKIP_CACHE(re, &s->gb, 8);

                        SKIP_COUNTER(re, &s->gb, 1+6+8);

                    }else{

                        int sign;

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_BITS(re, &s->gb, 1);

                        if(!s->esc3_level_length){

                            int ll;

                            //printf("ESC-3 %X at %d %d\n", show_bits(&s->gb, 24), s->mb_x, s->mb_y);

                            if(s->qscale<8){

                                ll= SHOW_UBITS(re, &s->gb, 3); SKIP_BITS(re, &s->gb, 3);

                                if(ll==0){

                                    if(SHOW_UBITS(re, &s->gb, 1)) printf("cool a new vlc code ,contact the ffmpeg developers and upload the file\n");

                                    SKIP_BITS(re, &s->gb, 1);

                                    ll=8;

                                }

                            }else{

                                ll=2;

                                while(ll<8 && SHOW_UBITS(re, &s->gb, 1)==0){

                                    ll++;

                                    SKIP_BITS(re, &s->gb, 1);

                                }

                                if(ll<8) SKIP_BITS(re, &s->gb, 1);

                            }

                            s->esc3_level_length= ll;

                            s->esc3_run_length= SHOW_UBITS(re, &s->gb, 2) + 3; SKIP_BITS(re, &s->gb, 2);

//printf("level length:%d, run length: %d\n", ll, s->esc3_run_length);

                            UPDATE_CACHE(re, &s->gb);

                        }

                        run=   SHOW_UBITS(re, &s->gb, s->esc3_run_length);

                        SKIP_BITS(re, &s->gb, s->esc3_run_length);

                        sign=  SHOW_UBITS(re, &s->gb, 1);

                        SKIP_BITS(re, &s->gb, 1);

                        level= SHOW_UBITS(re, &s->gb, s->esc3_level_length);

                        SKIP_BITS(re, &s->gb, s->esc3_level_length);

                        if(sign) level= -level;

                    }

//printf("level: %d, run: %d at %d %d\n", level, run, s->mb_x, s->mb_y);

#if 0 // waste of time / this will detect very few errors

                    {

                        const int abs_level= ABS(level);

                        const int run1= run - rl->max_run[last][abs_level] - run_diff;

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            if(abs_level <= rl->max_level[last][run]){

                                fprintf(stderr, "illegal 3. esc, vlc encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(abs_level <= rl->max_level[last][run]*2){

                                fprintf(stderr, "illegal 3. esc, esc 1 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(run1>=0 && abs_level <= rl->max_level[last][run1]){

                                fprintf(stderr, "illegal 3. esc, esc 2 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                        }

                    }

#endif

		    //level = level * qmul + (level>0) * qadd - (level<=0) * qadd ;

		    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

#if 0 // waste of time too :(

                    if(level>2048 || level<-2048){

                        fprintf(stderr, "|level| overflow in 3. esc\n");

                        return DECODING_AC_LOST;

                    }

#endif

                    i+= run + 1;

                    if(last) i+=192;

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC3 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC3 i=%d run=%d level=%d\n", i, run, level);

#endif

                } else {

                    /* second escape */

#if MIN_CACHE_BITS < 23

                    LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

#else

                    SKIP_BITS(re, &s->gb, 2);

#endif

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                    i+= run + rl->max_run[run>>7][level/qmul] + run_diff; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC2 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC2 i=%d run=%d level=%d\n", i, run, level);

#endif

                }

            } else {

                /* first escape */

#if MIN_CACHE_BITS < 22

                LAST_SKIP_BITS(re, &s->gb, 1);

                UPDATE_CACHE(re, &s->gb);

#else

                SKIP_BITS(re, &s->gb, 1);

#endif

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code in ESC1 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow in ESC1 i=%d run=%d level=%d\n", i, run, level);

#endif

            }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    fprintf(stderr, "illegal vlc code level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    fprintf(stderr, "run overflow i=%d run=%d level=%d\n", i, run, level);

#endif

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                const int left= s->gb.size*8 - get_bits_count(&s->gb);

                if(((i+192 == 64 && level/qmul==-1) || s->error_resilience<=1) && left>=0){

                    fprintf(stderr, "ignoring overflow at %d %d\n", s->mb_x, s->mb_y);

                    break;

                }else{

                    fprintf(stderr, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                    return -1;

                }

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (s->mb_intra) {

        mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    if(s->msmpeg4_version>=4 && i>0) i=63; //FIXME/XXX optimize

    s->block_last_index[n] = i;

    return 0;

}


static void ff_h264_idct8_add4_mmx2(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){

    int i;

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

        int nnz = nnzc[ scan8[i] ];

        if(nnz){

            if(nnz==1 && block[i*16]) ff_h264_idct8_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);

            else                      ff_h264_idct8_add_mmx    (dst + block_offset[i], block + i*16, stride);

        }

    }

}


static void filter_channel(MLPDecodeContext *m, unsigned int substr,

                           unsigned int channel)

{

    SubStream *s = &m->substream[substr];

    int32_t firbuf[MAX_BLOCKSIZE + MAX_FIR_ORDER];

    int32_t iirbuf[MAX_BLOCKSIZE + MAX_IIR_ORDER];

    FilterParams *fir = &m->channel_params[channel].filter_params[FIR];

    FilterParams *iir = &m->channel_params[channel].filter_params[IIR];

    unsigned int filter_shift = fir->shift;

    int32_t mask = MSB_MASK(s->quant_step_size[channel]);

    int index = MAX_BLOCKSIZE;

    int i;

    memcpy(&firbuf[MAX_BLOCKSIZE], &fir->state[0],

            MAX_FIR_ORDER * sizeof(int32_t));

    memcpy(&iirbuf[MAX_BLOCKSIZE], &iir->state[0],

            MAX_IIR_ORDER * sizeof(int32_t));

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

        int32_t residual = m->sample_buffer[i + s->blockpos][channel];

        unsigned int order;

        int64_t accum = 0;

        int32_t result;

        /* TODO: Move this code to DSPContext? */

        for (order = 0; order < fir->order; order++)

            accum += (int64_t)firbuf[index + order] *

                                fir->coeff[order];

        for (order = 0; order < iir->order; order++)

            accum += (int64_t)iirbuf[index + order] *

                                iir->coeff[order];

        accum  = accum >> filter_shift;

        result = (accum + residual) & mask;

        --index;

        firbuf[index] = result;

        iirbuf[index] = result - accum;

        m->sample_buffer[i + s->blockpos][channel] = result;

    }

    memcpy(&fir->state[0], &firbuf[index],

            MAX_FIR_ORDER * sizeof(int32_t));

    memcpy(&iir->state[0], &iirbuf[index],

            MAX_IIR_ORDER * sizeof(int32_t));

}


static void update(Real288_internal *glob)

{

    float buffer1[40], temp1[37];

    float buffer2[8], temp2[11];

    memcpy(buffer1     , glob->output + 20, 20*sizeof(*buffer1));

    memcpy(buffer1 + 20, glob->output     , 20*sizeof(*buffer1));

    do_hybrid_window(36, 40, 35, buffer1, temp1, glob->st1a, glob->st1b,

                     syn_window);

    if (eval_lpc_coeffs(temp1, glob->st1, 36))

        colmult(glob->pr1, glob->st1, table1a, 36);

    memcpy(buffer2    , glob->history + 4, 4*sizeof(*buffer2));

    memcpy(buffer2 + 4, glob->history    , 4*sizeof(*buffer2));

    do_hybrid_window(10, 8, 20, buffer2, temp2, glob->st2a, glob->st2b,

                     gain_window);

    if (eval_lpc_coeffs(temp2, glob->st2, 10))

        colmult(glob->pr2, glob->st2, table2a, 10);

}


static void fw_cfg_data_mem_write(void *opaque, hwaddr addr,

                                  uint64_t value, unsigned size)

{

    FWCfgState *s = opaque;

    uint8_t buf[8];

    unsigned i;

    switch (size) {

    case 1:

        buf[0] = value;

        break;

    case 2:

        stw_he_p(buf, value);

        break;

    case 4:

        stl_he_p(buf, value);

        break;

    case 8:

        stq_he_p(buf, value);

        break;

    default:

        abort();

    }

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

        fw_cfg_write(s, buf[i]);

    }

}


static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,

                               const uint8_t *buf, int buf_size,

                               int first_field)

{

    static const uint8_t header_prefix[]    = { 0x00, 0x00, 0x02, 0x80, 0x01 };

    static const uint8_t header_prefix444[] = { 0x00, 0x00, 0x02, 0x80, 0x02 };

    static const uint8_t header_prefixhr1[] = { 0x00, 0x00, 0x02, 0x80, 0x03 };

    static const uint8_t header_prefixhr2[] = { 0x00, 0x00, 0x03, 0x8C, 0x03 };

    int i, cid, ret;

    int old_bit_depth = ctx->bit_depth, bitdepth;

    int old_mb_height = ctx->mb_height;

    if (buf_size < 0x280) {

        av_log(ctx->avctx, AV_LOG_ERROR,

               "buffer too small (%d < 640).\n", buf_size);

        return AVERROR_INVALIDDATA;

    }

    if (memcmp(buf, header_prefix, 5) && memcmp(buf, header_prefix444, 5) &&

        memcmp(buf, header_prefixhr1, 5) && memcmp(buf, header_prefixhr2, 5)) {

        av_log(ctx->avctx, AV_LOG_ERROR,

               "unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",

               buf[0], buf[1], buf[2], buf[3], buf[4]);

        return AVERROR_INVALIDDATA;

    }

    if (buf[5] & 2) { /* interlaced */

        ctx->cur_field = buf[5] & 1;

        frame->interlaced_frame = 1;

        frame->top_field_first  = first_field ^ ctx->cur_field;

        av_log(ctx->avctx, AV_LOG_DEBUG,

               "interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);

    } else {

        ctx->cur_field = 0;

    }

    ctx->mbaff = (buf[0x6] >> 5) & 1;

    ctx->height = AV_RB16(buf + 0x18);

    ctx->width  = AV_RB16(buf + 0x1a);

    switch(buf[0x21] >> 5) {

    case 1: bitdepth = 8; break;

    case 2: bitdepth = 10; break;

    case 3: bitdepth = 12; break;

    default:

        av_log(ctx->avctx, AV_LOG_ERROR,

               "Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);

        return AVERROR_INVALIDDATA;

    }

    cid = AV_RB32(buf + 0x28);

    if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)

        return ret;

    if (ctx->mbaff && ctx->cid_table->cid != 1260)

        av_log(ctx->avctx, AV_LOG_WARNING,

               "Adaptive MB interlace flag in an unsupported profile.\n");

    ctx->act = buf[0x2C] & 7;

    if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)

        av_log(ctx->avctx, AV_LOG_WARNING,

               "Adaptive color transform in an unsupported profile.\n");

    ctx->is_444 = (buf[0x2C] >> 6) & 1;

    if (ctx->is_444) {

        if (bitdepth == 8) {

            avpriv_request_sample(ctx->avctx, "4:4:4 8 bits\n");

            return AVERROR_INVALIDDATA;

        } else if (bitdepth == 10) {

            ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;

            ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10

                                    : AV_PIX_FMT_GBRP10;

        } else {

            ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;

            ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12

                                    : AV_PIX_FMT_GBRP12;

        }

    } else if (bitdepth == 12) {

        ctx->decode_dct_block = dnxhd_decode_dct_block_12;

        ctx->pix_fmt = AV_PIX_FMT_YUV422P12;

    } else if (bitdepth == 10) {

        ctx->decode_dct_block = dnxhd_decode_dct_block_10;

        ctx->pix_fmt = AV_PIX_FMT_YUV422P10;

    } else {

        ctx->decode_dct_block = dnxhd_decode_dct_block_8;

        ctx->pix_fmt = AV_PIX_FMT_YUV422P;

    }

    ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;

    if (ctx->bit_depth != old_bit_depth) {

        ff_blockdsp_init(&ctx->bdsp, ctx->avctx);

        ff_idctdsp_init(&ctx->idsp, ctx->avctx);

        ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,

                          ff_zigzag_direct);

    }

    // make sure profile size constraints are respected

    // DNx100 allows 1920->1440 and 1280->960 subsampling

    if (ctx->width != ctx->cid_table->width &&

        ctx->cid_table->width != DNXHD_VARIABLE) {

        av_reduce(&ctx->avctx->sample_aspect_ratio.num,

                  &ctx->avctx->sample_aspect_ratio.den,

                  ctx->width, ctx->cid_table->width, 255);

        ctx->width = ctx->cid_table->width;

    }

    if (buf_size < ctx->cid_table->coding_unit_size) {

        av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %d).\n",

               buf_size, ctx->cid_table->coding_unit_size);

        return AVERROR_INVALIDDATA;

    }

    ctx->mb_width  = (ctx->width + 15)>> 4;

    ctx->mb_height = buf[0x16d];

    if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)

        ctx->height <<= 1;

    av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",

           ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",

           ctx->bit_depth, ctx->mbaff, ctx->act);

    // Newer format supports variable mb_scan_index sizes

    if (!memcmp(buf, header_prefixhr2, 5)) {

        ctx->data_offset = 0x170 + (ctx->mb_height << 2);

    } else {

        if (ctx->mb_height > 68 ||

            (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {

            av_log(ctx->avctx, AV_LOG_ERROR,

                   "mb height too big: %d\n", ctx->mb_height);

            return AVERROR_INVALIDDATA;

        }

        ctx->data_offset = 0x280;

    }

    if (buf_size < ctx->data_offset) {

        av_log(ctx->avctx, AV_LOG_ERROR,

               "buffer too small (%d < %d).\n", buf_size, ctx->data_offset);

        return AVERROR_INVALIDDATA;

    }

    if (ctx->mb_height != old_mb_height) {

        av_freep(&ctx->mb_scan_index);

        ctx->mb_scan_index = av_mallocz_array(ctx->mb_height, sizeof(uint32_t));

        if (!ctx->mb_scan_index)

            return AVERROR(ENOMEM);

    }

    for (i = 0; i < ctx->mb_height; i++) {

        ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));

        ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %u\n", i, 0x170 + (i << 2), ctx->mb_scan_index[i]);

        if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {

            av_log(ctx->avctx, AV_LOG_ERROR,

                   "invalid mb scan index (%u vs %u).\n",

                   ctx->mb_scan_index[i], buf_size - ctx->data_offset);

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static void raw_aio_writev_scrubbed(void *opaque, int ret)

{

    RawScrubberBounce *b = opaque;

    if (ret < 0) {

        b->cb(b->opaque, ret);

    } else {

        b->cb(b->opaque, ret + 512);

    }

    qemu_iovec_destroy(&b->qiov);

    qemu_free(b);

}


static inline uint32_t mipsdsp_sat32_sub(int32_t a, int32_t b,

                                         CPUMIPSState *env)

{

    int32_t  temp;

    temp = a - b;

    if (MIPSDSP_OVERFLOW(a, -b, temp, 0x80000000)) {

        if (a > 0) {

            temp = 0x7FFFFFFF;

        } else {

            temp = 0x80000000;

        }

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return temp & 0xFFFFFFFFull;

}


int avconv_parse_options(int argc, char **argv)

{

    OptionParseContext octx;

    uint8_t error[128];

    int ret;

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

    /* split the commandline into an internal representation */

    ret = split_commandline(&octx, argc, argv, options, groups);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error splitting the argument list: ");

        goto fail;

    }

    /* apply global options */

    ret = parse_optgroup(NULL, &octx.global_opts);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error parsing global options: ");

        goto fail;

    }

    /* open input files */

    ret = open_files(&octx.groups[GROUP_INFILE], "input", open_input_file);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error opening input files: ");

        goto fail;

    }

    /* open output files */

    ret = open_files(&octx.groups[GROUP_OUTFILE], "output", open_output_file);

    if (ret < 0) {

        av_log(NULL, AV_LOG_FATAL, "Error opening output files: ");

        goto fail;

    }

fail:

    uninit_parse_context(&octx);

    if (ret < 0) {

        av_strerror(ret, error, sizeof(error));

        av_log(NULL, AV_LOG_FATAL, "%s\n", error);

    }

    return ret;

}


static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,

                                     const uint8_t *buf, int len)

{

    unsigned int ssrc, h;

    int payload_type, seq, ret, flags = 0;

    int ext;

    AVStream *st;

    uint32_t timestamp;

    int rv= 0;

    ext = buf[0] & 0x10;

    payload_type = buf[1] & 0x7f;

    if (buf[1] & 0x80)

        flags |= RTP_FLAG_MARKER;

    seq  = AV_RB16(buf + 2);

    timestamp = AV_RB32(buf + 4);

    ssrc = AV_RB32(buf + 8);

    /* store the ssrc in the RTPDemuxContext */

    s->ssrc = ssrc;

    /* NOTE: we can handle only one payload type */

    if (s->payload_type != payload_type)

        return -1;

    st = s->st;

    // only do something with this if all the rtp checks pass...

    if(!rtp_valid_packet_in_sequence(&s->statistics, seq))

    {

        av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",

               payload_type, seq, ((s->seq + 1) & 0xffff));

        return -1;

    }

    if (buf[0] & 0x20) {

        int padding = buf[len - 1];

        if (len >= 12 + padding)

            len -= padding;

    }

    s->seq = seq;

    len -= 12;

    buf += 12;

    /* RFC 3550 Section 5.3.1 RTP Header Extension handling */

    if (ext) {

        if (len < 4)

            return -1;

        /* calculate the header extension length (stored as number

         * of 32-bit words) */

        ext = (AV_RB16(buf + 2) + 1) << 2;

        if (len < ext)

            return -1;

        // skip past RTP header extension

        len -= ext;

        buf += ext;

    }

    if (!st) {

        /* specific MPEG2TS demux support */

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

        /* The only error that can be returned from ff_mpegts_parse_packet

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

         * AVERROR(EAGAIN) for all errors */

        if (ret < 0)

            return AVERROR(EAGAIN);

        if (ret < len) {

            s->read_buf_size = len - ret;

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

            s->read_buf_index = 0;

            return 1;

        }

        return 0;

    } else if (s->parse_packet) {

        rv = s->parse_packet(s->ic, s->dynamic_protocol_context,

                             s->st, pkt, &timestamp, buf, len, flags);

    } else {

        // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.

        switch(st->codec->codec_id) {

        case AV_CODEC_ID_MP2:

        case AV_CODEC_ID_MP3:

            /* better than nothing: skip mpeg audio RTP header */

            if (len <= 4)

                return -1;

            h = AV_RB32(buf);

            len -= 4;

            buf += 4;

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        case AV_CODEC_ID_MPEG1VIDEO:

        case AV_CODEC_ID_MPEG2VIDEO:

            /* better than nothing: skip mpeg video RTP header */

            if (len <= 4)

                return -1;

            h = AV_RB32(buf);

            buf += 4;

            len -= 4;

            if (h & (1 << 26)) {

                /* mpeg2 */

                if (len <= 4)

                    return -1;

                buf += 4;

                len -= 4;

            }

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        default:

            av_new_packet(pkt, len);

            memcpy(pkt->data, buf, len);

            break;

        }

        pkt->stream_index = st->index;

    }

    // now perform timestamp things....

    finalize_packet(s, pkt, timestamp);

    return rv;

}


static inline void scale_mv(AVSContext *h, int *d_x, int *d_y,

                            cavs_vector *src, int distp)

{

    int den = h->scale_den[FFMAX(src->ref, 0)];

    *d_x = (src->x * distp * den + 256 + FF_SIGNBIT(src->x)) >> 9;

    *d_y = (src->y * distp * den + 256 + FF_SIGNBIT(src->y)) >> 9;

}


static int kvm_get_xsave(CPUState *env)

{

#ifdef KVM_CAP_XSAVE

    struct kvm_xsave* xsave;

    int ret, i;

    uint16_t cwd, swd, twd, fop;

    if (!kvm_has_xsave()) {

        return kvm_get_fpu(env);

    }

    xsave = qemu_memalign(4096, sizeof(struct kvm_xsave));

    ret = kvm_vcpu_ioctl(env, KVM_GET_XSAVE, xsave);

    if (ret < 0) {

        qemu_free(xsave);

        return ret;

    }

    cwd = (uint16_t)xsave->region[0];

    swd = (uint16_t)(xsave->region[0] >> 16);

    twd = (uint16_t)xsave->region[1];

    fop = (uint16_t)(xsave->region[1] >> 16);

    env->fpstt = (swd >> 11) & 7;

    env->fpus = swd;

    env->fpuc = cwd;

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

        env->fptags[i] = !((twd >> i) & 1);

    }

    env->mxcsr = xsave->region[XSAVE_MXCSR];

    memcpy(env->fpregs, &xsave->region[XSAVE_ST_SPACE],

            sizeof env->fpregs);

    memcpy(env->xmm_regs, &xsave->region[XSAVE_XMM_SPACE],

            sizeof env->xmm_regs);

    env->xstate_bv = *(uint64_t *)&xsave->region[XSAVE_XSTATE_BV];

    memcpy(env->ymmh_regs, &xsave->region[XSAVE_YMMH_SPACE],

            sizeof env->ymmh_regs);

    qemu_free(xsave);

    return 0;

#else

    return kvm_get_fpu(env);

#endif

}


int qemu_acl_insert(qemu_acl *acl,

                    int deny,

                    const char *match,

                    int index)

{

    qemu_acl_entry *entry;

    qemu_acl_entry *tmp;

    int i = 0;

    if (index <= 0)

        return -1;

    if (index > acl->nentries) {

        return qemu_acl_append(acl, deny, match);

    }

    entry = g_malloc(sizeof(*entry));

    entry->match = g_strdup(match);

    entry->deny = deny;

    QTAILQ_FOREACH(tmp, &acl->entries, next) {

        i++;

        if (i == index) {

            QTAILQ_INSERT_BEFORE(tmp, entry, next);

            acl->nentries++;

            break;

        }

    }

    return i;

}


PPC_OP(subfc)

{

    T0 = T1 - T0;

    if (T0 <= T1) {

        xer_ca = 1;

    } else {

        xer_ca = 0;

    }

    RETURN();

}


static uint16_t nvme_rw(NvmeCtrl *n, NvmeNamespace *ns, NvmeCmd *cmd,

    NvmeRequest *req)

{

    NvmeRwCmd *rw = (NvmeRwCmd *)cmd;

    uint32_t nlb  = le32_to_cpu(rw->nlb) + 1;

    uint64_t slba = le64_to_cpu(rw->slba);

    uint64_t prp1 = le64_to_cpu(rw->prp1);

    uint64_t prp2 = le64_to_cpu(rw->prp2);

    uint8_t lba_index  = NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas);

    uint8_t data_shift = ns->id_ns.lbaf[lba_index].ds;

    uint64_t data_size = (uint64_t)nlb << data_shift;

    uint64_t aio_slba  = slba << (data_shift - BDRV_SECTOR_BITS);

    int is_write = rw->opcode == NVME_CMD_WRITE ? 1 : 0;

    if ((slba + nlb) > ns->id_ns.nsze) {

        return NVME_LBA_RANGE | NVME_DNR;

    }

    if (nvme_map_prp(&req->qsg, prp1, prp2, data_size, n)) {

        return NVME_INVALID_FIELD | NVME_DNR;

    }

    assert((nlb << data_shift) == req->qsg.size);

    req->has_sg = true;

    dma_acct_start(n->conf.blk, &req->acct, &req->qsg,

                   is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);

    req->aiocb = is_write ?

        dma_blk_write(n->conf.blk, &req->qsg, aio_slba, nvme_rw_cb, req) :

        dma_blk_read(n->conf.blk, &req->qsg, aio_slba, nvme_rw_cb, req);

    return NVME_NO_COMPLETE;

}


uint64_t HELPER(neon_sub_saturate_u64)(uint64_t src1, uint64_t src2)

{

    uint64_t res;

    if (src1 < src2) {

        env->QF = 1;

        res = 0;

    } else {

        res = src1 - src2;

    }

    return res;

}


void memory_global_sync_dirty_bitmap(MemoryRegion *address_space)

{

    AddressSpace *as = memory_region_to_address_space(address_space);

    FlatRange *fr;

    FOR_EACH_FLAT_RANGE(fr, &as->current_map) {

        MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);

    }

}


static int lvf_probe(AVProbeData *p)

{

    if (AV_RL32(p->buf) == MKTAG('L', 'V', 'F', 'F'))

        return AVPROBE_SCORE_EXTENSION;

    return 0;

}


static inline int decode_subframe(FLACContext *s, int channel)

{

    int32_t *decoded = s->decoded[channel];

    int type, wasted = 0;

    int bps = s->flac_stream_info.bps;

    int i, tmp, ret;

    if (channel == 0) {

        if (s->ch_mode == FLAC_CHMODE_RIGHT_SIDE)

            bps++;

    } else {

        if (s->ch_mode == FLAC_CHMODE_LEFT_SIDE || s->ch_mode == FLAC_CHMODE_MID_SIDE)

            bps++;

    }

    if (get_bits1(&s->gb)) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");

        return AVERROR_INVALIDDATA;

    }

    type = get_bits(&s->gb, 6);

    if (get_bits1(&s->gb)) {

        int left = get_bits_left(&s->gb);

        if ( left <= 0 ||

            (left < bps && !show_bits_long(&s->gb, left)) ||

                           !show_bits_long(&s->gb, bps)) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid number of wasted bits > available bits (%d) - left=%d\n",

                   bps, left);

            return AVERROR_INVALIDDATA;

        }

        wasted = 1 + get_unary(&s->gb, 1, get_bits_left(&s->gb));

        bps -= wasted;

    }

    if (bps > 32) {

        avpriv_report_missing_feature(s->avctx, "Decorrelated bit depth > 32");

        return AVERROR_PATCHWELCOME;

    }

//FIXME use av_log2 for types

    if (type == 0) {

        tmp = get_sbits_long(&s->gb, bps);

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

            decoded[i] = tmp;

    } else if (type == 1) {

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

            decoded[i] = get_sbits_long(&s->gb, bps);

    } else if ((type >= 8) && (type <= 12)) {

        if ((ret = decode_subframe_fixed(s, decoded, type & ~0x8, bps)) < 0)

            return ret;

    } else if (type >= 32) {

        if ((ret = decode_subframe_lpc(s, decoded, (type & ~0x20)+1, bps)) < 0)

            return ret;

    } else {

        av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");

        return AVERROR_INVALIDDATA;

    }

    if (wasted) {

        int i;

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

            decoded[i] <<= wasted;

    }

    return 0;

}


static void icp_set_cppr(struct icp_state *icp, int server, uint8_t cppr)

{

    struct icp_server_state *ss = icp->ss + server;

    uint8_t old_cppr;

    uint32_t old_xisr;

    old_cppr = CPPR(ss);

    ss->xirr = (ss->xirr & ~CPPR_MASK) | (cppr << 24);

    if (cppr < old_cppr) {

        if (XISR(ss) && (cppr <= ss->pending_priority)) {

            old_xisr = XISR(ss);

            ss->xirr &= ~XISR_MASK; /* Clear XISR */

            qemu_irq_lower(ss->output);

            ics_reject(icp->ics, old_xisr);

        }

    } else {

        if (!XISR(ss)) {

            icp_resend(icp, server);

        }

    }

}


static av_cold int opus_decode_init(AVCodecContext *avctx)

{

    OpusContext *c = avctx->priv_data;

    int ret, i, j;

    avctx->sample_fmt  = AV_SAMPLE_FMT_FLTP;

    avctx->sample_rate = 48000;

    c->fdsp = avpriv_float_dsp_alloc(0);

    if (!c->fdsp)

        return AVERROR(ENOMEM);

    /* find out the channel configuration */

    ret = ff_opus_parse_extradata(avctx, c);

    if (ret < 0)

        return ret;

    /* allocate and init each independent decoder */

    c->streams = av_mallocz_array(c->nb_streams, sizeof(*c->streams));

    c->out             = av_mallocz_array(c->nb_streams, 2 * sizeof(*c->out));

    c->out_size        = av_mallocz_array(c->nb_streams, sizeof(*c->out_size));

    c->sync_buffers    = av_mallocz_array(c->nb_streams, sizeof(*c->sync_buffers));

    c->decoded_samples = av_mallocz_array(c->nb_streams, sizeof(*c->decoded_samples));

    if (!c->streams || !c->sync_buffers || !c->decoded_samples || !c->out || !c->out_size) {

        c->nb_streams = 0;

        ret = AVERROR(ENOMEM);

        goto fail;

    }

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

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

        uint64_t layout;

        s->output_channels = (i < c->nb_stereo_streams) ? 2 : 1;

        s->avctx = avctx;

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

            s->silk_output[j]       = s->silk_buf[j];

            s->celt_output[j]       = s->celt_buf[j];

            s->redundancy_output[j] = s->redundancy_buf[j];

        }

        s->fdsp = c->fdsp;

        s->swr =swr_alloc();

        if (!s->swr)

            goto fail;

        layout = (s->output_channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;

        av_opt_set_int(s->swr, "in_sample_fmt",      avctx->sample_fmt,  0);

        av_opt_set_int(s->swr, "out_sample_fmt",     avctx->sample_fmt,  0);

        av_opt_set_int(s->swr, "in_channel_layout",  layout,             0);

        av_opt_set_int(s->swr, "out_channel_layout", layout,             0);

        av_opt_set_int(s->swr, "out_sample_rate",    avctx->sample_rate, 0);

        av_opt_set_int(s->swr, "filter_size",        16,                 0);

        ret = ff_silk_init(avctx, &s->silk, s->output_channels);

        if (ret < 0)

            goto fail;

        ret = ff_celt_init(avctx, &s->celt, s->output_channels);

        if (ret < 0)

            goto fail;

        s->celt_delay = av_audio_fifo_alloc(avctx->sample_fmt,

                                            s->output_channels, 1024);

        if (!s->celt_delay) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        c->sync_buffers[i] = av_audio_fifo_alloc(avctx->sample_fmt,

                                                 s->output_channels, 32);

        if (!c->sync_buffers[i]) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

    }

    return 0;

fail:

    opus_decode_close(avctx);

    return ret;

}


static void nvme_rw_cb(void *opaque, int ret)

{

    NvmeRequest *req = opaque;

    NvmeSQueue *sq = req->sq;

    NvmeCtrl *n = sq->ctrl;

    NvmeCQueue *cq = n->cq[sq->cqid];

    block_acct_done(blk_get_stats(n->conf.blk), &req->acct);

    if (!ret) {

        req->status = NVME_SUCCESS;

    } else {

        req->status = NVME_INTERNAL_DEV_ERROR;

    }

    if (req->has_sg) {

        qemu_sglist_destroy(&req->qsg);

    }

    nvme_enqueue_req_completion(cq, req);

}


int find_itlb_entry(CPUState * env, target_ulong address,

		    int use_asid, int update)

{

    int e, n;

    e = find_tlb_entry(env, address, env->itlb, ITLB_SIZE, use_asid);

    if (e == MMU_DTLB_MULTIPLE)

	e = MMU_ITLB_MULTIPLE;

    else if (e == MMU_DTLB_MISS && update) {

	e = find_tlb_entry(env, address, env->utlb, UTLB_SIZE, use_asid);

	if (e >= 0) {

	    n = itlb_replacement(env);

	    env->itlb[n] = env->utlb[e];

	    e = n;

	} else if (e == MMU_DTLB_MISS)

	    e = MMU_ITLB_MISS;

    } else if (e == MMU_DTLB_MISS)

	e = MMU_ITLB_MISS;

    if (e >= 0)

	update_itlb_use(env, e);

    return e;

}


static void s390_msi_ctrl_write(void *opaque, hwaddr addr, uint64_t data,

                                unsigned int size)

{

    S390PCIBusDevice *pbdev;

    uint32_t io_int_word;

    uint32_t fid = data >> ZPCI_MSI_VEC_BITS;

    uint32_t vec = data & ZPCI_MSI_VEC_MASK;

    uint64_t ind_bit;

    uint32_t sum_bit;

    uint32_t e = 0;

    DPRINTF("write_msix data 0x%" PRIx64 " fid %d vec 0x%x\n", data, fid, vec);

    pbdev = s390_pci_find_dev_by_fid(fid);

    if (!pbdev) {

        e |= (vec << ERR_EVENT_MVN_OFFSET);

        s390_pci_generate_error_event(ERR_EVENT_NOMSI, 0, fid, addr, e);

        return;

    }

    if (pbdev->state != ZPCI_FS_ENABLED) {

        return;

    }

    ind_bit = pbdev->routes.adapter.ind_offset;

    sum_bit = pbdev->routes.adapter.summary_offset;

    set_ind_atomic(pbdev->routes.adapter.ind_addr + (ind_bit + vec) / 8,

                   0x80 >> ((ind_bit + vec) % 8));

    if (!set_ind_atomic(pbdev->routes.adapter.summary_addr + sum_bit / 8,

                                       0x80 >> (sum_bit % 8))) {

        io_int_word = (pbdev->isc << 27) | IO_INT_WORD_AI;

        s390_io_interrupt(0, 0, 0, io_int_word);

    }

}


void net_slirp_redir(const char *redir_str)

{

    struct slirp_config_str *config;

    if (QTAILQ_EMPTY(&slirp_stacks)) {

        config = qemu_malloc(sizeof(*config));

        pstrcpy(config->str, sizeof(config->str), redir_str);

        config->flags = SLIRP_CFG_HOSTFWD | SLIRP_CFG_LEGACY;

        config->next = slirp_configs;

        slirp_configs = config;

        return;

    }

    slirp_hostfwd(QTAILQ_FIRST(&slirp_stacks), NULL, redir_str, 1);

}


static unsigned int get_video_format_idx(AVCodecContext *avctx)

{

    unsigned int ret_idx = 0;

    unsigned int idx;

    unsigned int num_formats = sizeof(ff_schro_video_format_info) /

                               sizeof(ff_schro_video_format_info[0]);

    for (idx = 1; idx < num_formats; ++idx) {

        const SchroVideoFormatInfo *vf = &ff_schro_video_format_info[idx];

        if (avctx->width  == vf->width &&

            avctx->height == vf->height) {

            ret_idx = idx;

            if (avctx->time_base.den == vf->frame_rate_num &&

                avctx->time_base.num == vf->frame_rate_denom)

                return idx;

        }

    }

    return ret_idx;

}


static void compute_pts_dts(AVStream *st, int64_t *ppts, int64_t *pdts,

                            int64_t timestamp)

{

    int frame_delay;

    int64_t pts, dts;

    if (st->codec.codec_type == CODEC_TYPE_VIDEO &&

        st->codec.max_b_frames != 0) {

        frame_delay = (st->codec.frame_rate_base * 90000LL) /

            st->codec.frame_rate;

        if (timestamp == 0) {

            /* specific case for first frame : DTS just before */

            pts = timestamp;

            dts = timestamp - frame_delay;

        } else {

            timestamp -= frame_delay;

            if (st->codec.coded_frame->pict_type == FF_B_TYPE) {

                /* B frames has identical pts/dts */

                pts = timestamp;

                dts = timestamp;

            } else {

                /* a reference frame has a pts equal to the dts of the

                   _next_ one */

                dts = timestamp;

                pts = timestamp + (st->codec.max_b_frames + 1) * frame_delay;

            }

        }

#if 1

        av_log(&st->codec, AV_LOG_DEBUG, "pts=%0.3f dts=%0.3f pict_type=%c\n",

               pts / 90000.0, dts / 90000.0,

               av_get_pict_type_char(st->codec.coded_frame->pict_type));

#endif

    } else {

        pts = timestamp;

        dts = timestamp;

    }

    *ppts = pts & ((1LL << 33) - 1);

    *pdts = dts & ((1LL << 33) - 1);

}


static void close_connection(HTTPContext *c)

{

    HTTPContext **cp, *c1;

    int i, nb_streams;

    AVFormatContext *ctx;

    URLContext *h;

    AVStream *st;

    /* remove connection from list */

    cp = &first_http_ctx;

    while ((*cp) != NULL) {

        c1 = *cp;

        if (c1 == c) {

            *cp = c->next;

        } else {

            cp = &c1->next;

        }

    }

    /* remove references, if any (XXX: do it faster) */

    for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {

        if (c1->rtsp_c == c)

            c1->rtsp_c = NULL;

    }

    /* remove connection associated resources */

    if (c->fd >= 0)

        close(c->fd);

    if (c->fmt_in) {

        /* close each frame parser */

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

            st = c->fmt_in->streams[i];

            if (st->codec->codec) {

                avcodec_close(st->codec);

            }

        }

        av_close_input_file(c->fmt_in);

    }

    /* free RTP output streams if any */

    nb_streams = 0;

    if (c->stream)

        nb_streams = c->stream->nb_streams;

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

        ctx = c->rtp_ctx[i];

        if (ctx) {

            av_write_trailer(ctx);

            av_free(ctx);

        }

        h = c->rtp_handles[i];

        if (h) {

            url_close(h);

        }

    }

    ctx = &c->fmt_ctx;

    if (!c->last_packet_sent) {

        if (ctx->oformat) {

            /* prepare header */

            if (url_open_dyn_buf(&ctx->pb) >= 0) {

                av_write_trailer(ctx);

                url_close_dyn_buf(&ctx->pb, &c->pb_buffer);

            }

        }

    }

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

        av_free(ctx->streams[i]) ;

    if (c->stream)

        current_bandwidth -= c->stream->bandwidth;

    av_freep(&c->pb_buffer);

    av_freep(&c->packet_buffer);

    av_free(c->buffer);

    av_free(c);

    nb_connections--;

}


static int rv10_decode_packet(AVCodecContext *avctx,
                             const uint8_t *buf, int buf_size, int buf_size2)
{
    MpegEncContext *s = avctx->priv_data;
    int mb_count, mb_pos, left, start_mb_x;
    init_get_bits(&s->gb, buf, buf_size*8);
    if(s->codec_id ==CODEC_ID_RV10)
        mb_count = rv10_decode_picture_header(s);
    else
        mb_count = rv20_decode_picture_header(s);
    if (mb_count < 0) {
        av_log(s->avctx, AV_LOG_ERROR, "HEADER ERROR\n");
    }
    if (s->mb_x >= s->mb_width ||
        s->mb_y >= s->mb_height) {
        av_log(s->avctx, AV_LOG_ERROR, "POS ERROR %d %d\n", s->mb_x, s->mb_y);
    }
    mb_pos = s->mb_y * s->mb_width + s->mb_x;
    left = s->mb_width * s->mb_height - mb_pos;
    if (mb_count > left) {
        av_log(s->avctx, AV_LOG_ERROR, "COUNT ERROR\n");
    }
    if ((s->mb_x == 0 && s->mb_y == 0) || s->current_picture_ptr==NULL) {
        if(s->current_picture_ptr){ //FIXME write parser so we always have complete frames?
            ff_er_frame_end(s);
            MPV_frame_end(s);
            s->mb_x= s->mb_y = s->resync_mb_x = s->resync_mb_y= 0;
        }
        if(MPV_frame_start(s, avctx) < 0)
        ff_er_frame_start(s);
    }
    av_dlog(avctx, "qscale=%d\n", s->qscale);
    /* default quantization values */
    if(s->codec_id== CODEC_ID_RV10){
        if(s->mb_y==0) s->first_slice_line=1;
    }else{
        s->first_slice_line=1;
        s->resync_mb_x= s->mb_x;
    }
    start_mb_x= s->mb_x;
    s->resync_mb_y= s->mb_y;
    if(s->h263_aic){
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_aic_dc_scale_table;
    }else{
        s->y_dc_scale_table=
        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;
    }
    if(s->modified_quant)
        s->chroma_qscale_table= ff_h263_chroma_qscale_table;
    ff_set_qscale(s, s->qscale);
    s->rv10_first_dc_coded[0] = 0;
    s->rv10_first_dc_coded[1] = 0;
    s->rv10_first_dc_coded[2] = 0;
    s->block_wrap[0]=
    s->block_wrap[1]=
    s->block_wrap[2]=
    s->block_wrap[3]= s->b8_stride;
    s->block_wrap[4]=
    s->block_wrap[5]= s->mb_stride;
    ff_init_block_index(s);
    /* decode each macroblock */
    for(s->mb_num_left= mb_count; s->mb_num_left>0; s->mb_num_left--) {
        int ret;
        ff_update_block_index(s);
        av_dlog(avctx, "**mb x=%d y=%d\n", s->mb_x, s->mb_y);
        s->mv_dir = MV_DIR_FORWARD;
        s->mv_type = MV_TYPE_16X16;
        ret=ff_h263_decode_mb(s, s->block);
        if (ret != SLICE_ERROR && s->gb.size_in_bits < get_bits_count(&s->gb) && 8*buf_size2 >= get_bits_count(&s->gb)){
            av_log(avctx, AV_LOG_DEBUG, "update size from %d to %d\n", s->gb.size_in_bits, 8*buf_size2);
            s->gb.size_in_bits= 8*buf_size2;
            ret= SLICE_OK;
        }
        if (ret == SLICE_ERROR || s->gb.size_in_bits < get_bits_count(&s->gb)) {
            av_log(s->avctx, AV_LOG_ERROR, "ERROR at MB %d %d\n", s->mb_x, s->mb_y);
        }
        if(s->pict_type != AV_PICTURE_TYPE_B)
            ff_h263_update_motion_val(s);
        MPV_decode_mb(s, s->block);
        if(s->loop_filter)
            ff_h263_loop_filter(s);
        if (++s->mb_x == s->mb_width) {
            s->mb_x = 0;
            s->mb_y++;
            ff_init_block_index(s);
        }
        if(s->mb_x == s->resync_mb_x)
            s->first_slice_line=0;
        if(ret == SLICE_END) break;
    }
    ff_er_add_slice(s, start_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, AC_END|DC_END|MV_END);
    return s->gb.size_in_bits;
}


static void video_encode_example(const char *filename, int codec_id)

{

    AVCodec *codec;

    AVCodecContext *c= NULL;

    int i, ret, x, y, got_output;

    FILE *f;

    AVFrame *picture;

    AVPacket pkt;

    uint8_t endcode[] = { 0, 0, 1, 0xb7 };

    printf("Encode video file %s\n", filename);

    /* find the mpeg1 video encoder */

    codec = avcodec_find_encoder(codec_id);

    if (!codec) {

        fprintf(stderr, "codec not found\n");

        exit(1);

    }

    c = avcodec_alloc_context3(codec);

    picture= avcodec_alloc_frame();

    /* put sample parameters */

    c->bit_rate = 400000;

    /* resolution must be a multiple of two */

    c->width = 352;

    c->height = 288;

    /* frames per second */

    c->time_base= (AVRational){1,25};

    c->gop_size = 10; /* emit one intra frame every ten frames */

    c->max_b_frames=1;

    c->pix_fmt = PIX_FMT_YUV420P;

    if(codec_id == AV_CODEC_ID_H264)

        av_opt_set(c->priv_data, "preset", "slow", 0);

    /* open it */

    if (avcodec_open2(c, codec, NULL) < 0) {

        fprintf(stderr, "could not open codec\n");

        exit(1);

    }

    f = fopen(filename, "wb");

    if (!f) {

        fprintf(stderr, "could not open %s\n", filename);

        exit(1);

    }

    /* the image can be allocated by any means and av_image_alloc() is

     * just the most convenient way if av_malloc() is to be used */

    ret = av_image_alloc(picture->data, picture->linesize, c->width, c->height,

                         c->pix_fmt, 32);

    if (ret < 0) {

        fprintf(stderr, "could not alloc raw picture buffer\n");

        exit(1);

    }

    picture->format = c->pix_fmt;

    picture->width  = c->width;

    picture->height = c->height;

    /* encode 1 second of video */

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

        av_init_packet(&pkt);

        pkt.data = NULL;    // packet data will be allocated by the encoder

        pkt.size = 0;

        fflush(stdout);

        /* prepare a dummy image */

        /* Y */

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

            for(x=0;x<c->width;x++) {

                picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;

            }

        }

        /* Cb and Cr */

        for(y=0;y<c->height/2;y++) {

            for(x=0;x<c->width/2;x++) {

                picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;

                picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;

            }

        }

        picture->pts = i;

        /* encode the image */

        ret = avcodec_encode_video2(c, &pkt, picture, &got_output);

        if (ret < 0) {

            fprintf(stderr, "error encoding frame\n");

            exit(1);

        }

        if (got_output) {

            printf("encoding frame %3d (size=%5d)\n", i, pkt.size);

            fwrite(pkt.data, 1, pkt.size, f);

            av_free_packet(&pkt);

        }

    }

    /* get the delayed frames */

    for (got_output = 1; got_output; i++) {

        fflush(stdout);

        ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);

        if (ret < 0) {

            fprintf(stderr, "error encoding frame\n");

            exit(1);

        }

        if (got_output) {

            printf("write frame %3d (size=%5d)\n", i, pkt.size);

            fwrite(pkt.data, 1, pkt.size, f);

            av_free_packet(&pkt);

        }

    }

    /* add sequence end code to have a real mpeg file */

    fwrite(endcode, 1, sizeof(endcode), f);

    fclose(f);

    avcodec_close(c);

    av_free(c);

    av_freep(&picture->data[0]);

    av_free(picture);

    printf("\n");

}


static void usb_host_handle_reset(USBDevice *udev)

{

    USBHostDevice *s = USB_HOST_DEVICE(udev);

    trace_usb_host_reset(s->bus_num, s->addr);

    if (udev->configuration == 0) {

        return;

    }

    usb_host_release_interfaces(s);

    libusb_reset_device(s->dh);

    usb_host_claim_interfaces(s, 0);

    usb_host_ep_update(s);

}


static int matroska_read_seek(AVFormatContext *s, int stream_index,

                              int64_t timestamp, int flags)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    MatroskaTrack *tracks = matroska->tracks.elem;

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

    int i, index, index_sub, index_min;

    /* Parse the CUES now since we need the index data to seek. */

    if (matroska->cues_parsing_deferred) {

        matroska_parse_cues(matroska);

        matroska->cues_parsing_deferred = 0;

    }

    if (!st->nb_index_entries)

        return 0;

    timestamp = FFMAX(timestamp, st->index_entries[0].timestamp);

    if ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {

        avio_seek(s->pb, st->index_entries[st->nb_index_entries-1].pos, SEEK_SET);

        matroska->current_id = 0;

        while ((index = av_index_search_timestamp(st, timestamp, flags)) < 0) {

            matroska_clear_queue(matroska);

            if (matroska_parse_cluster(matroska) < 0)

                break;

        }

    }

    matroska_clear_queue(matroska);

    if (index < 0)

        return 0;

    index_min = index;

    for (i=0; i < matroska->tracks.nb_elem; i++) {

        tracks[i].audio.pkt_cnt = 0;

        tracks[i].audio.sub_packet_cnt = 0;

        tracks[i].audio.buf_timecode = AV_NOPTS_VALUE;

        tracks[i].end_timecode = 0;

        if (tracks[i].type == MATROSKA_TRACK_TYPE_SUBTITLE

            && !tracks[i].stream->discard != AVDISCARD_ALL) {

            index_sub = av_index_search_timestamp(tracks[i].stream, st->index_entries[index].timestamp, AVSEEK_FLAG_BACKWARD);

            if (index_sub >= 0

                && st->index_entries[index_sub].pos < st->index_entries[index_min].pos

                && st->index_entries[index].timestamp - st->index_entries[index_sub].timestamp < 30000000000/matroska->time_scale)

                index_min = index_sub;

        }

    }

    avio_seek(s->pb, st->index_entries[index_min].pos, SEEK_SET);

    matroska->current_id = 0;

    matroska->skip_to_keyframe = !(flags & AVSEEK_FLAG_ANY);

    matroska->skip_to_timecode = st->index_entries[index].timestamp;

    matroska->done = 0;

    ff_update_cur_dts(s, st, st->index_entries[index].timestamp);

    return 0;

}


static int mp_pacl_setxattr(FsContext *ctx, const char *path, const char *name,

                            void *value, size_t size, int flags)

{

    char *buffer;

    int ret;

    buffer = rpath(ctx, path);

    ret = lsetxattr(buffer, MAP_ACL_ACCESS, value, size, flags);

    g_free(buffer);

    return ret;

}


static inline void qemu_assert(int cond, const char *msg)

{

    if (!cond) {

        fprintf (stderr, "badness: %s\n", msg);

        abort();

    }

}


static inline int pic_is_unused(MpegEncContext *s, Picture *pic)

{

    if (pic->f.buf[0] == NULL)

        return 1;

    if (pic->needs_realloc && !(pic->reference & DELAYED_PIC_REF))

        return 1;

    return 0;

}


static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    BdrvTrackedRequest req;

    /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */

    uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);

    uint8_t *head_buf = NULL;

    uint8_t *tail_buf = NULL;

    QEMUIOVector local_qiov;

    bool use_local_qiov = false;

    int ret;

    if (!bs->drv) {

        return -ENOMEDIUM;

    }

    if (bs->read_only) {

        return -EACCES;

    }

    if (bdrv_check_byte_request(bs, offset, bytes)) {

        return -EIO;

    }

    /* throttling disk I/O */

    if (bs->io_limits_enabled) {

        /* TODO Switch to byte granularity */

        bdrv_io_limits_intercept(bs, bytes >> BDRV_SECTOR_BITS, true);

    }

    /*

     * Align write if necessary by performing a read-modify-write cycle.

     * Pad qiov with the read parts and be sure to have a tracked request not

     * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.

     */

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

    if (offset & (align - 1)) {

        QEMUIOVector head_qiov;

        struct iovec head_iov;

        mark_request_serialising(&req, align);

        wait_serialising_requests(&req);

        head_buf = qemu_blockalign(bs, align);

        head_iov = (struct iovec) {

            .iov_base   = head_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&head_qiov, &head_iov, 1);

        ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,

                                  align, &head_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

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

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

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

        use_local_qiov = true;

        bytes += offset & (align - 1);

        offset = offset & ~(align - 1);

    }

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

        QEMUIOVector tail_qiov;

        struct iovec tail_iov;

        size_t tail_bytes;

        mark_request_serialising(&req, align);

        wait_serialising_requests(&req);

        tail_buf = qemu_blockalign(bs, align);

        tail_iov = (struct iovec) {

            .iov_base   = tail_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);

        ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,

                                  align, &tail_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        if (!use_local_qiov) {

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

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

            use_local_qiov = true;

        }

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

        qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);

        bytes = ROUND_UP(bytes, align);

    }

    ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,

                               use_local_qiov ? &local_qiov : qiov,

                               flags);

fail:

    tracked_request_end(&req);

    if (use_local_qiov) {

        qemu_iovec_destroy(&local_qiov);

        qemu_vfree(head_buf);

        qemu_vfree(tail_buf);

    }

    return ret;

}


static void vmd_decode(VmdVideoContext *s)

{

    int i;

    unsigned int *palette32;

    unsigned char r, g, b;

    /* point to the start of the encoded data */

    unsigned char *p = s->buf + 16;

    unsigned char *pb;

    unsigned char meth;

    unsigned char *dp;   /* pointer to current frame */

    unsigned char *pp;   /* pointer to previous frame */

    unsigned char len;

    int ofs;

    int frame_x, frame_y;

    int frame_width, frame_height;

    frame_x = LE_16(&s->buf[6]);

    frame_y = LE_16(&s->buf[8]);

    frame_width = LE_16(&s->buf[10]) - frame_x + 1;

    frame_height = LE_16(&s->buf[12]) - frame_y + 1;

    /* if only a certain region will be updated, copy the entire previous

     * frame before the decode */

    if (frame_x || frame_y || (frame_width != s->avctx->width) ||

        (frame_height != s->avctx->height)) {

        memcpy(s->frame.data[0], s->prev_frame.data[0],

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

    }

    /* check if there is a new palette */

    if (s->buf[15] & 0x02) {

        p += 2;

        palette32 = (unsigned int *)s->palette;

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

            r = *p++ * 4;

            g = *p++ * 4;

            b = *p++ * 4;

            palette32[i] = (r << 16) | (g << 8) | (b);

        }

        s->size -= (256 * 3 + 2);

    }

    if (s->size >= 0) {

        /* originally UnpackFrame in VAG's code */

        pb = p;

        meth = *pb++;

        if (meth & 0x80) {

            lz_unpack(pb, s->unpack_buffer);

            meth &= 0x7F;

            pb = s->unpack_buffer;

        }

        dp = &s->frame.data[0][frame_y * s->frame.linesize[0] + frame_x];

        pp = &s->prev_frame.data[0][frame_y * s->prev_frame.linesize[0] + frame_x];

        switch (meth) {

        case 1:

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

                ofs = 0;

                do {

                    len = *pb++;

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        memcpy(&dp[ofs], pb, len);

                        pb += len;

                        ofs += len;

                    } else {

                        /* interframe pixel copy */

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                    break;

                }

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

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 2:

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

                memcpy(dp, pb, frame_width);

                pb += frame_width;

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

                pp += s->prev_frame.linesize[0];

            }

            break;

        case 3:

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

                ofs = 0;

                do {

                    len = *pb++;

                    if (len & 0x80) {

                        len = (len & 0x7F) + 1;

                        if (*pb++ == 0xFF)

                            len = rle_unpack(pb, &dp[ofs], len);

                        else

                            memcpy(&dp[ofs], pb, len);

                        pb += len;

                        ofs += len;

                    } else {

                        /* interframe pixel copy */

                        memcpy(&dp[ofs], &pp[ofs], len + 1);

                        ofs += len + 1;

                    }

                } while (ofs < frame_width);

                if (ofs > frame_width) {

                    av_log(s->avctx, AV_LOG_ERROR, "VMD video: offset > width (%d > %d)\n",

                        ofs, frame_width);

                }

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

                pp += s->prev_frame.linesize[0];

            }

            break;

        }

    }

}


static int oss_ctl_in (HWVoiceIn *hw, int cmd, ...)

{

    OSSVoiceIn *oss = (OSSVoiceIn *) hw;

    switch (cmd) {

    case VOICE_ENABLE:

        {

            va_list ap;

            int poll_mode;

            va_start (ap, cmd);

            poll_mode = va_arg (ap, int);

            va_end (ap);

            if (poll_mode && oss_poll_in (hw)) {

                poll_mode = 0;

            }

            hw->poll_mode = poll_mode;

        }

        break;

    case VOICE_DISABLE:

        if (hw->poll_mode) {

            hw->poll_mode = 0;

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

        }

        break;

    }

    return 0;

}


static int parse_uint32(DeviceState *dev, Property *prop, const char *str)

{

    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);

    const char *fmt;

    /* accept both hex and decimal */

    fmt = strncasecmp(str, "0x",2) == 0 ? "%" PRIx32 : "%" PRIu32;

    if (sscanf(str, fmt, ptr) != 1)

        return -EINVAL;

    return 0;

}


void OPPROTO op_lmsw_T0(void)

{

    /* only 4 lower bits of CR0 are modified */

    T0 = (env->cr[0] & ~0xf) | (T0 & 0xf);

    helper_movl_crN_T0(0);

}


static int slirp_guestfwd(SlirpState *s, const char *config_str,

                          int legacy_format)

{

    struct in_addr server = { .s_addr = 0 };

    struct GuestFwd *fwd;

    const char *p;

    char buf[128];

    char *end;

    int port;

    p = config_str;

    if (legacy_format) {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

    } else {

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (strcmp(buf, "tcp") && buf[0] != '\0') {

            goto fail_syntax;

        }

        if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

            goto fail_syntax;

        }

        if (buf[0] != '\0' && !inet_aton(buf, &server)) {

            goto fail_syntax;

        }

        if (get_str_sep(buf, sizeof(buf), &p, '-') < 0) {

            goto fail_syntax;

        }

    }

    port = strtol(buf, &end, 10);

    if (*end != '\0' || port < 1 || port > 65535) {

        goto fail_syntax;

    }

    fwd = g_malloc(sizeof(struct GuestFwd));

    snprintf(buf, sizeof(buf), "guestfwd.tcp.%d", port);

    if ((strlen(p) > 4) && !strncmp(p, "cmd:", 4)) {

        if (slirp_add_exec(s->slirp, 0, &p[4], &server, port) < 0) {

            error_report("conflicting/invalid host:port in guest forwarding "

                         "rule '%s'", config_str);

            g_free(fwd);

            return -1;

        }

    } else {

        fwd->hd = qemu_chr_new(buf, p, NULL);

        if (!fwd->hd) {

            error_report("could not open guest forwarding device '%s'", buf);

            g_free(fwd);

            return -1;

        }

        if (slirp_add_exec(s->slirp, 3, fwd->hd, &server, port) < 0) {

            error_report("conflicting/invalid host:port in guest forwarding "

                         "rule '%s'", config_str);

            g_free(fwd);

            return -1;

        }

        fwd->server = server;

        fwd->port = port;

        fwd->slirp = s->slirp;

        qemu_chr_fe_claim_no_fail(fwd->hd);

        qemu_chr_add_handlers(fwd->hd, guestfwd_can_read, guestfwd_read,

                              NULL, fwd);

    }

    return 0;

 fail_syntax:

    error_report("invalid guest forwarding rule '%s'", config_str);

    return -1;

}


void visit_start_list(Visitor *v, const char *name, Error **errp)

{

    if (!error_is_set(errp)) {

        v->start_list(v, name, errp);

    }

}


static void av_always_inline filter_mb_edgev( uint8_t *pix, int stride, const int16_t bS[4], unsigned int qp, H264Context *h) {

    const int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    const unsigned int index_a = qp - qp_bd_offset + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[qp - qp_bd_offset + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]];

        tc[1] = tc0_table[index_a][bS[1]];

        tc[2] = tc0_table[index_a][bS[2]];

        tc[3] = tc0_table[index_a][bS[3]];

        h->h264dsp.h264_h_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

        h->h264dsp.h264_h_loop_filter_luma_intra(pix, stride, alpha, beta);

    }

}


static int decode_info_header(NUTContext *nut)

{

    AVFormatContext *s = nut->avf;

    AVIOContext *bc    = s->pb;

    uint64_t tmp, chapter_start, chapter_len;

    unsigned int stream_id_plus1, count;

    int chapter_id, i;

    int64_t value, end;

    char name[256], str_value[1024], type_str[256];

    const char *type;

    int *event_flags;

    AVChapter *chapter      = NULL;

    AVStream *st            = NULL;

    AVDictionary **metadata = NULL;

    int metadata_flag       = 0;

    end  = get_packetheader(nut, bc, 1, INFO_STARTCODE);

    end += avio_tell(bc);

    GET_V(stream_id_plus1, tmp <= s->nb_streams);

    chapter_id    = get_s(bc);

    chapter_start = ffio_read_varlen(bc);

    chapter_len   = ffio_read_varlen(bc);

    count         = ffio_read_varlen(bc);

    if (chapter_id && !stream_id_plus1) {

        int64_t start = chapter_start / nut->time_base_count;

        chapter = avpriv_new_chapter(s, chapter_id,

                                     nut->time_base[chapter_start %

                                                    nut->time_base_count],

                                     start, start + chapter_len, NULL);

        metadata = &chapter->metadata;

    } else if (stream_id_plus1) {

        st       = s->streams[stream_id_plus1 - 1];

        metadata = &st->metadata;

        event_flags = &st->event_flags;

        metadata_flag = AVSTREAM_EVENT_FLAG_METADATA_UPDATED;

    } else {

        metadata = &s->metadata;

        event_flags = &s->event_flags;

        metadata_flag = AVFMT_EVENT_FLAG_METADATA_UPDATED;

    }

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

        get_str(bc, name, sizeof(name));

        value = get_s(bc);

        if (value == -1) {

            type = "UTF-8";

            get_str(bc, str_value, sizeof(str_value));

        } else if (value == -2) {

            get_str(bc, type_str, sizeof(type_str));

            type = type_str;

            get_str(bc, str_value, sizeof(str_value));

        } else if (value == -3) {

            type  = "s";

            value = get_s(bc);

        } else if (value == -4) {

            type  = "t";

            value = ffio_read_varlen(bc);

        } else if (value < -4) {

            type = "r";

            get_s(bc);

        } else {

            type = "v";

        }

        if (stream_id_plus1 > s->nb_streams) {

            av_log(s, AV_LOG_ERROR, "invalid stream id for info packet\n");

            continue;

        }

        if (!strcmp(type, "UTF-8")) {

            if (chapter_id == 0 && !strcmp(name, "Disposition")) {

                set_disposition_bits(s, str_value, stream_id_plus1 - 1);

                continue;

            }

            if (stream_id_plus1 && !strcmp(name, "r_frame_rate")) {

                sscanf(str_value, "%d/%d", &st->r_frame_rate.num, &st->r_frame_rate.den);

                if (st->r_frame_rate.num >= 1000LL*st->r_frame_rate.den)

                    st->r_frame_rate.num = st->r_frame_rate.den = 0;

                continue;

            }

            if (metadata && av_strcasecmp(name, "Uses") &&

                av_strcasecmp(name, "Depends") && av_strcasecmp(name, "Replaces")) {

                *event_flags |= metadata_flag;

                av_dict_set(metadata, name, str_value, 0);

            }

        }

    }

    if (skip_reserved(bc, end) || ffio_get_checksum(bc)) {

        av_log(s, AV_LOG_ERROR, "info header checksum mismatch\n");

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void mp3_update_xing(AVFormatContext *s)

{

    MP3Context  *mp3 = s->priv_data;

    int i;

    /* replace "Xing" identification string with "Info" for CBR files. */

    if (!mp3->has_variable_bitrate) {

        avio_seek(s->pb, mp3->xing_offset, SEEK_SET);

        ffio_wfourcc(s->pb, "Info");

    }

    avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET);

    avio_wb32(s->pb, mp3->frames);

    avio_wb32(s->pb, mp3->size);

    avio_w8(s->pb, 0);  // first toc entry has to be zero.

    for (i = 1; i < XING_TOC_SIZE; ++i) {

        int j = i * mp3->pos / XING_TOC_SIZE;

        int seek_point = 256LL * mp3->bag[j] / mp3->size;

        avio_w8(s->pb, FFMIN(seek_point, 255));

    }

    avio_seek(s->pb, 0, SEEK_END);

}


static void sh7750_mem_writel(void *opaque, target_phys_addr_t addr,

			      uint32_t mem_value)

{

    SH7750State *s = opaque;

    uint16_t temp;

    switch (addr) {

	/* SDRAM controller */

    case SH7750_BCR1_A7:

    case SH7750_BCR4_A7:

    case SH7750_WCR1_A7:

    case SH7750_WCR2_A7:

    case SH7750_WCR3_A7:

    case SH7750_MCR_A7:

	ignore_access("long write", addr);

	return;

	/* IO ports */

    case SH7750_PCTRA_A7:

	temp = porta_lines(s);

	s->pctra = mem_value;

	s->portdira = portdir(mem_value);

	s->portpullupa = portpullup(mem_value);

	porta_changed(s, temp);

	return;

    case SH7750_PCTRB_A7:

	temp = portb_lines(s);

	s->pctrb = mem_value;

	s->portdirb = portdir(mem_value);

	s->portpullupb = portpullup(mem_value);

	portb_changed(s, temp);

	return;

    case SH7750_MMUCR_A7:

	s->cpu->mmucr = mem_value;

	return;

    case SH7750_PTEH_A7:

	s->cpu->pteh = mem_value;

	return;

    case SH7750_PTEL_A7:

	s->cpu->ptel = mem_value;

	return;

    case SH7750_PTEA_A7:

	s->cpu->ptea = mem_value & 0x0000000f;

	return;

    case SH7750_TTB_A7:

	s->cpu->ttb = mem_value;

	return;

    case SH7750_TEA_A7:

	s->cpu->tea = mem_value;

	return;

    case SH7750_TRA_A7:

	s->cpu->tra = mem_value & 0x000007ff;

	return;

    case SH7750_EXPEVT_A7:

	s->cpu->expevt = mem_value & 0x000007ff;

	return;

    case SH7750_INTEVT_A7:

	s->cpu->intevt = mem_value & 0x000007ff;

	return;

    case SH7750_CCR_A7:

	s->ccr = mem_value;

	return;

    default:

	error_access("long write", addr);

	assert(0);

    }

}


int nbd_receive_negotiate(QIOChannel *ioc, const char *name,

                          QCryptoTLSCreds *tlscreds, const char *hostname,

                          QIOChannel **outioc, NBDExportInfo *info,

                          Error **errp)

{

    char buf[256];

    uint64_t magic;

    int rc;

    bool zeroes = true;

    trace_nbd_receive_negotiate(tlscreds, hostname ? hostname : "<null>");

    rc = -EINVAL;

    if (outioc) {

        *outioc = NULL;

    }

    if (tlscreds && !outioc) {

        error_setg(errp, "Output I/O channel required for TLS");

        goto fail;

    }

    if (nbd_read(ioc, buf, 8, errp) < 0) {

        error_prepend(errp, "Failed to read data");

        goto fail;

    }

    buf[8] = '\0';

    if (strlen(buf) == 0) {

        error_setg(errp, "Server connection closed unexpectedly");

        goto fail;

    }

    magic = ldq_be_p(buf);

    trace_nbd_receive_negotiate_magic(magic);

    if (memcmp(buf, "NBDMAGIC", 8) != 0) {

        error_setg(errp, "Invalid magic received");

        goto fail;

    }

    if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {

        error_prepend(errp, "Failed to read magic");

        goto fail;

    }

    magic = be64_to_cpu(magic);

    trace_nbd_receive_negotiate_magic(magic);

    if (magic == NBD_OPTS_MAGIC) {

        uint32_t clientflags = 0;

        uint16_t globalflags;

        bool fixedNewStyle = false;

        if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {

            error_prepend(errp, "Failed to read server flags");

            goto fail;

        }

        globalflags = be16_to_cpu(globalflags);

        trace_nbd_receive_negotiate_server_flags(globalflags);

        if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {

            fixedNewStyle = true;

            clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;

        }

        if (globalflags & NBD_FLAG_NO_ZEROES) {

            zeroes = false;

            clientflags |= NBD_FLAG_C_NO_ZEROES;

        }

        /* client requested flags */

        clientflags = cpu_to_be32(clientflags);

        if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {

            error_prepend(errp, "Failed to send clientflags field");

            goto fail;

        }

        if (tlscreds) {

            if (fixedNewStyle) {

                *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);

                if (!*outioc) {

                    goto fail;

                }

                ioc = *outioc;

            } else {

                error_setg(errp, "Server does not support STARTTLS");

                goto fail;

            }

        }

        if (!name) {

            trace_nbd_receive_negotiate_default_name();

            name = "";

        }

        if (fixedNewStyle) {

            int result;

            if (structured_reply) {

                result = nbd_request_simple_option(ioc,

                                                   NBD_OPT_STRUCTURED_REPLY,

                                                   errp);

                if (result < 0) {

                    goto fail;

                }

                info->structured_reply = result == 1;

            }

            /* Try NBD_OPT_GO first - if it works, we are done (it

             * also gives us a good message if the server requires

             * TLS).  If it is not available, fall back to

             * NBD_OPT_LIST for nicer error messages about a missing

             * export, then use NBD_OPT_EXPORT_NAME.  */

            result = nbd_opt_go(ioc, name, info, errp);

            if (result < 0) {

                goto fail;

            }

            if (result > 0) {

                return 0;

            }

            /* Check our desired export is present in the

             * server export list. Since NBD_OPT_EXPORT_NAME

             * cannot return an error message, running this

             * query gives us better error reporting if the

             * export name is not available.

             */

            if (nbd_receive_query_exports(ioc, name, errp) < 0) {

                goto fail;

            }

        }

        /* write the export name request */

        if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,

                                    errp) < 0) {

            goto fail;

        }

        /* Read the response */

        if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {

            error_prepend(errp, "Failed to read export length");

            goto fail;

        }

        be64_to_cpus(&info->size);

        if (nbd_read(ioc, &info->flags, sizeof(info->flags), errp) < 0) {

            error_prepend(errp, "Failed to read export flags");

            goto fail;

        }

        be16_to_cpus(&info->flags);

    } else if (magic == NBD_CLIENT_MAGIC) {

        uint32_t oldflags;

        if (name) {

            error_setg(errp, "Server does not support export names");

            goto fail;

        }

        if (tlscreds) {

            error_setg(errp, "Server does not support STARTTLS");

            goto fail;

        }

        if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {

            error_prepend(errp, "Failed to read export length");

            goto fail;

        }

        be64_to_cpus(&info->size);

        if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {

            error_prepend(errp, "Failed to read export flags");

            goto fail;

        }

        be32_to_cpus(&oldflags);

        if (oldflags & ~0xffff) {

            error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);

            goto fail;

        }

        info->flags = oldflags;

    } else {

        error_setg(errp, "Bad magic received");

        goto fail;

    }

    trace_nbd_receive_negotiate_size_flags(info->size, info->flags);

    if (zeroes && nbd_drop(ioc, 124, errp) < 0) {

        error_prepend(errp, "Failed to read reserved block");

        goto fail;

    }

    rc = 0;

fail:

    return rc;

}


static int check_refcounts_l1(BlockDriverState *bs,
                              uint16_t *refcount_table,
                              int refcount_table_size,
                              int64_t l1_table_offset, int l1_size,
                              int check_copied)
{
    BDRVQcowState *s = bs->opaque;
    uint64_t *l1_table, l2_offset, l1_size2;
    int i, refcount, ret;
    int errors = 0;
    l1_size2 = l1_size * sizeof(uint64_t);
    /* Mark L1 table as used */
    errors += inc_refcounts(bs, refcount_table, refcount_table_size,
                  l1_table_offset, l1_size2);
    /* Read L1 table entries from disk */
    l1_table = qemu_malloc(l1_size2);
    if (bdrv_pread(s->hd, l1_table_offset,
                   l1_table, l1_size2) != l1_size2)
        goto fail;
    for(i = 0;i < l1_size; i++)
        be64_to_cpus(&l1_table[i]);
    /* Do the actual checks */
    for(i = 0; i < l1_size; i++) {
        l2_offset = l1_table[i];
        if (l2_offset) {
            /* QCOW_OFLAG_COPIED must be set iff refcount == 1 */
            if (check_copied) {
                refcount = get_refcount(bs, (l2_offset & ~QCOW_OFLAG_COPIED)
                    >> s->cluster_bits);
                if ((refcount == 1) != ((l2_offset & QCOW_OFLAG_COPIED) != 0)) {
                    fprintf(stderr, "ERROR OFLAG_COPIED: l2_offset=%" PRIx64
                        " refcount=%d\n", l2_offset, refcount);
            /* Mark L2 table as used */
            l2_offset &= ~QCOW_OFLAG_COPIED;
            errors += inc_refcounts(bs, refcount_table,
                          refcount_table_size,
                          l2_offset,
                          s->cluster_size);
            /* Process and check L2 entries */
            ret = check_refcounts_l2(bs, refcount_table, refcount_table_size,
                l2_offset, check_copied);
            if (ret < 0) {
                goto fail;
            errors += ret;
    qemu_free(l1_table);
    return errors;
fail:
    fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
    qemu_free(l1_table);
    return -EIO;


static void mpeg_decode_sequence_extension(MpegEncContext *s)

{

    int horiz_size_ext, vert_size_ext;

    int bit_rate_ext, vbv_buf_ext, low_delay;

    int frame_rate_ext_n, frame_rate_ext_d;

    skip_bits(&s->gb, 8); /* profil and level */

    skip_bits(&s->gb, 1); /* progressive_sequence */

    skip_bits(&s->gb, 2); /* chroma_format */

    horiz_size_ext = get_bits(&s->gb, 2);

    vert_size_ext = get_bits(&s->gb, 2);

    s->width |= (horiz_size_ext << 12);

    s->height |= (vert_size_ext << 12);

    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */

    s->bit_rate = ((s->bit_rate / 400) | (bit_rate_ext << 12)) * 400;

    skip_bits1(&s->gb); /* marker */

    vbv_buf_ext = get_bits(&s->gb, 8);

    low_delay = get_bits1(&s->gb);

    frame_rate_ext_n = get_bits(&s->gb, 2);

    frame_rate_ext_d = get_bits(&s->gb, 5);

    if (frame_rate_ext_d >= 1)

        s->frame_rate = (s->frame_rate * frame_rate_ext_n) / frame_rate_ext_d;

    dprintf("sequence extension\n");

    s->mpeg2 = 1;

}


static void do_audio_out(AVFormatContext *s, OutputStream *ost,

                         AVFrame *frame)

{

    AVCodecContext *enc = ost->enc_ctx;

    AVPacket pkt;

    int got_packet = 0;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (!check_recording_time(ost))

        return;

    if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)

        frame->pts = ost->sync_opts;

    ost->sync_opts = frame->pts + frame->nb_samples;

    ost->samples_encoded += frame->nb_samples;

    ost->frames_encoded++;

    av_assert0(pkt.size || !pkt.data);

    update_benchmark(NULL);

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "

               "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",

               av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),

               enc->time_base.num, enc->time_base.den);

    }

    if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {

        av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");

        exit_program(1);

    }

    update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);

    if (got_packet) {

        av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);

        if (debug_ts) {

            av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "

                   "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                   av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

                   av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

        }

        write_frame(s, &pkt, ost);

    }

}


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

{

    int16_t *v = pv;

    qemu_put_sbe16s(f, v);

}


static void rtas_set_tce_bypass(sPAPREnvironment *spapr, uint32_t token,

                                uint32_t nargs, target_ulong args,

                                uint32_t nret, target_ulong rets)

{

    VIOsPAPRBus *bus = spapr->vio_bus;

    VIOsPAPRDevice *dev;

    uint32_t unit, enable;

    if (nargs != 2) {

        rtas_st(rets, 0, -3);

        return;

    }

    unit = rtas_ld(args, 0);

    enable = rtas_ld(args, 1);

    dev = spapr_vio_find_by_reg(bus, unit);

    if (!dev) {

        rtas_st(rets, 0, -3);

        return;

    }

    if (enable) {

        dev->flags |= VIO_PAPR_FLAG_DMA_BYPASS;

    } else {

        dev->flags &= ~VIO_PAPR_FLAG_DMA_BYPASS;

    }

    rtas_st(rets, 0, 0);

}


static int vp3_decode_end(AVCodecContext *avctx)
{
    Vp3DecodeContext *s = avctx->priv_data;
    int i;
    av_free(s->superblock_coding);
    av_free(s->all_fragments);
    av_free(s->coeffs);
    av_free(s->coded_fragment_list);
    av_free(s->superblock_fragments);
    av_free(s->superblock_macroblocks);
    av_free(s->macroblock_fragments);
    av_free(s->macroblock_coding);
    /* release all frames */
    if (s->golden_frame.data[0] && s->golden_frame.data[0] != s->last_frame.data[0])
        avctx->release_buffer(avctx, &s->golden_frame);
    if (s->last_frame.data[0])
        avctx->release_buffer(avctx, &s->last_frame);
    /* no need to release the current_frame since it will always be pointing
     * to the same frame as either the golden or last frame */
    return 0;


static uint32_t timer_int_route(struct HPETTimer *timer)

{

    uint32_t route;

    route = (timer->config & HPET_TN_INT_ROUTE_MASK) >> HPET_TN_INT_ROUTE_SHIFT;

    return route;

}


static int virtio_net_load_device(VirtIODevice *vdev, QEMUFile *f,

                                  int version_id)

{

    VirtIONet *n = VIRTIO_NET(vdev);

    int i, link_down;

    qemu_get_buffer(f, n->mac, ETH_ALEN);

    n->vqs[0].tx_waiting = qemu_get_be32(f);

    virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f),

                               virtio_has_feature(vdev, VIRTIO_F_VERSION_1));

    if (version_id >= 3)

        n->status = qemu_get_be16(f);

    if (version_id >= 4) {

        if (version_id < 8) {

            n->promisc = qemu_get_be32(f);

            n->allmulti = qemu_get_be32(f);

        } else {

            n->promisc = qemu_get_byte(f);

            n->allmulti = qemu_get_byte(f);

        }

    }

    if (version_id >= 5) {

        n->mac_table.in_use = qemu_get_be32(f);

        /* MAC_TABLE_ENTRIES may be different from the saved image */

        if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {

            qemu_get_buffer(f, n->mac_table.macs,

                            n->mac_table.in_use * ETH_ALEN);

        } else {

            int64_t i;

            /* Overflow detected - can happen if source has a larger MAC table.

             * We simply set overflow flag so there's no need to maintain the

             * table of addresses, discard them all.

             * Note: 64 bit math to avoid integer overflow.

             */

            for (i = 0; i < (int64_t)n->mac_table.in_use * ETH_ALEN; ++i) {

                qemu_get_byte(f);

            }

            n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1;

            n->mac_table.in_use = 0;

        }

    }

    if (version_id >= 6)

        qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);

    if (version_id >= 7) {

        if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) {

            error_report("virtio-net: saved image requires vnet_hdr=on");

            return -1;

        }

    }

    if (version_id >= 9) {

        n->mac_table.multi_overflow = qemu_get_byte(f);

        n->mac_table.uni_overflow = qemu_get_byte(f);

    }

    if (version_id >= 10) {

        n->alluni = qemu_get_byte(f);

        n->nomulti = qemu_get_byte(f);

        n->nouni = qemu_get_byte(f);

        n->nobcast = qemu_get_byte(f);

    }

    if (version_id >= 11) {

        if (qemu_get_byte(f) && !peer_has_ufo(n)) {

            error_report("virtio-net: saved image requires TUN_F_UFO support");

            return -1;

        }

    }

    if (n->max_queues > 1) {

        if (n->max_queues != qemu_get_be16(f)) {

            error_report("virtio-net: different max_queues ");

            return -1;

        }

        n->curr_queues = qemu_get_be16(f);

        if (n->curr_queues > n->max_queues) {

            error_report("virtio-net: curr_queues %x > max_queues %x",

                         n->curr_queues, n->max_queues);

            return -1;

        }

        for (i = 1; i < n->curr_queues; i++) {

            n->vqs[i].tx_waiting = qemu_get_be32(f);

        }

    }

    if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {

        n->curr_guest_offloads = qemu_get_be64(f);

    } else {

        n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);

    }

    if (peer_has_vnet_hdr(n)) {

        virtio_net_apply_guest_offloads(n);

    }

    virtio_net_set_queues(n);

    /* Find the first multicast entry in the saved MAC filter */

    for (i = 0; i < n->mac_table.in_use; i++) {

        if (n->mac_table.macs[i * ETH_ALEN] & 1) {

            break;

        }

    }

    n->mac_table.first_multi = i;

    /* nc.link_down can't be migrated, so infer link_down according

     * to link status bit in n->status */

    link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;

    for (i = 0; i < n->max_queues; i++) {

        qemu_get_subqueue(n->nic, i)->link_down = link_down;

    }

    if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE) &&

        virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {

        n->announce_counter = SELF_ANNOUNCE_ROUNDS;

        timer_mod(n->announce_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL));

    }

    return 0;

}


static inline void t_gen_mov_preg_TN(DisasContext *dc, int r, TCGv tn)

{

	if (r < 0 || r > 15)

		fprintf(stderr, "wrong register write $p%d\n", r);

	if (r == PR_BZ || r == PR_WZ || r == PR_DZ)

		return;

	else if (r == PR_SRS)

		tcg_gen_andi_tl(cpu_PR[r], tn, 3);

	else {

		if (r == PR_PID)

			tcg_gen_helper_0_1(helper_tlb_flush_pid, tn);

		if (dc->tb_flags & S_FLAG && r == PR_SPC)

			tcg_gen_helper_0_1(helper_spc_write, tn);

		else if (r == PR_CCS)

			dc->cpustate_changed = 1;

		tcg_gen_mov_tl(cpu_PR[r], tn);

	}

}


void stl_phys_notdirty(AddressSpace *as, hwaddr addr, uint32_t val)

{

    uint8_t *ptr;

    MemoryRegion *mr;

    hwaddr l = 4;

    hwaddr addr1;

    mr = address_space_translate(as, addr, &addr1, &l,

                                 true);

    if (l < 4 || !memory_access_is_direct(mr, true)) {

        io_mem_write(mr, addr1, val, 4);

    } else {

        addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;

        ptr = qemu_get_ram_ptr(addr1);

        stl_p(ptr, val);

        if (unlikely(in_migration)) {

            if (cpu_physical_memory_is_clean(addr1)) {

                /* invalidate code */

                tb_invalidate_phys_page_range(addr1, addr1 + 4, 0);

                /* set dirty bit */

                cpu_physical_memory_set_dirty_flag(addr1,

                                                   DIRTY_MEMORY_MIGRATION);

                cpu_physical_memory_set_dirty_flag(addr1, DIRTY_MEMORY_VGA);

            }

        }

    }

}


static void tty_serial_init(int fd, int speed,

                            int parity, int data_bits, int stop_bits)

{

    struct termios tty;

    speed_t spd;

#if 0

    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",

           speed, parity, data_bits, stop_bits);

#endif

    tcgetattr (fd, &tty);

    oldtty = tty;

#define check_speed(val) if (speed <= val) { spd = B##val; break; }

    speed = speed * 10 / 11;

    do {

        check_speed(50);

        check_speed(75);

        check_speed(110);

        check_speed(134);

        check_speed(150);

        check_speed(200);

        check_speed(300);

        check_speed(600);

        check_speed(1200);

        check_speed(1800);

        check_speed(2400);

        check_speed(4800);

        check_speed(9600);

        check_speed(19200);

        check_speed(38400);

        /* Non-Posix values follow. They may be unsupported on some systems. */

        check_speed(57600);

        check_speed(115200);

#ifdef B230400

        check_speed(230400);

#endif

#ifdef B460800

        check_speed(460800);

#endif

#ifdef B500000

        check_speed(500000);

#endif

#ifdef B576000

        check_speed(576000);

#endif

#ifdef B921600

        check_speed(921600);

#endif

#ifdef B1000000

        check_speed(1000000);

#endif

#ifdef B1152000

        check_speed(1152000);

#endif

#ifdef B1500000

        check_speed(1500000);

#endif

#ifdef B2000000

        check_speed(2000000);

#endif

#ifdef B2500000

        check_speed(2500000);

#endif

#ifdef B3000000

        check_speed(3000000);

#endif

#ifdef B3500000

        check_speed(3500000);

#endif

#ifdef B4000000

        check_speed(4000000);

#endif

        spd = B115200;

    } while (0);

    cfsetispeed(&tty, spd);

    cfsetospeed(&tty, spd);

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP

                          |INLCR|IGNCR|ICRNL|IXON);

    tty.c_oflag |= OPOST;

    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);

    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);

    switch(data_bits) {

    default:

    case 8:

        tty.c_cflag |= CS8;

        break;

    case 7:

        tty.c_cflag |= CS7;

        break;

    case 6:

        tty.c_cflag |= CS6;

        break;

    case 5:

        tty.c_cflag |= CS5;

        break;

    }

    switch(parity) {

    default:

    case 'N':

        break;

    case 'E':

        tty.c_cflag |= PARENB;

        break;

    case 'O':

        tty.c_cflag |= PARENB | PARODD;

        break;

    }

    if (stop_bits == 2)

        tty.c_cflag |= CSTOPB;

    tcsetattr (fd, TCSANOW, &tty);

}


BlockBackend *blk_new_with_bs(Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    blk = blk_new(errp);

    if (!blk) {

        return NULL;

    }

    bs = bdrv_new_root();

    blk->root = bdrv_root_attach_child(bs, "root", &child_root);

    blk->root->opaque = blk;

    bs->blk = blk;

    return blk;

}