static int theora_decode_tables(AVCodecContext *avctx, GetBitContext gb)

{

    Vp3DecodeContext *s = avctx->priv_data;

    int i, n, matrices;

    if (s->theora >= 0x030200) {

        n = get_bits(&gb, 3);

        /* loop filter limit values table */

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

            s->filter_limit_values[i] = get_bits(&gb, n);

    }

    if (s->theora >= 0x030200)

        n = get_bits(&gb, 4) + 1;

    else

        n = 16;

    /* quality threshold table */

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

        s->coded_ac_scale_factor[i] = get_bits(&gb, n);

    if (s->theora >= 0x030200)

        n = get_bits(&gb, 4) + 1;

    else

        n = 16;

    /* dc scale factor table */

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

        s->coded_dc_scale_factor[i] = get_bits(&gb, n);

    if (s->theora >= 0x030200)

        matrices = get_bits(&gb, 9) + 1;

    else

        matrices = 3;

    if (matrices != 3) {

        av_log(avctx,AV_LOG_ERROR, "unsupported matrices: %d\n", matrices);

//        return -1;

    }

    /* y coeffs */

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

        s->coded_intra_y_dequant[i] = get_bits(&gb, 8);

    /* uv coeffs */

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

        s->coded_intra_c_dequant[i] = get_bits(&gb, 8);

    /* inter coeffs */

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

        s->coded_inter_dequant[i] = get_bits(&gb, 8);

    /* skip unknown matrices */

    n = matrices - 3;

    while(n--)

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

            skip_bits(&gb, 8);

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

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

            int newqr;

            if (i > 0 || n > 0)

                newqr = get_bits(&gb, 1);

            else

                newqr = 1;

            if (!newqr) {

                if (i > 0)

                    get_bits(&gb, 1);

            }

            else {

                int qi = 0;

                skip_bits(&gb, av_log2(matrices-1)+1);

                while (qi < 63) {

                    qi += get_bits(&gb, av_log2(63-qi)+1) + 1;

                    skip_bits(&gb, av_log2(matrices-1)+1);

                }

                if (qi > 63) {

                    av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);

                    return -1;

                }

            }

        }

    }

    /* Huffman tables */

    for (s->hti = 0; s->hti < 80; s->hti++) {

        s->entries = 0;

        s->huff_code_size = 1;

        if (!get_bits(&gb, 1)) {

            s->hbits = 0;

            read_huffman_tree(avctx, &gb);

            s->hbits = 1;

            read_huffman_tree(avctx, &gb);

        }

    }

    s->theora_tables = 1;

    return 0;

}


static int ac3_eac3_probe(AVProbeData *p, enum AVCodecID expected_codec_id)

{

    int max_frames, first_frames = 0, frames;

    const uint8_t *buf, *buf2, *end;

    enum AVCodecID codec_id = AV_CODEC_ID_AC3;

    max_frames = 0;

    buf = p->buf;

    end = buf + p->buf_size;

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

        if(buf > p->buf && !(buf[0] == 0x0B && buf[1] == 0x77)

                        && !(buf[0] == 0x77 && buf[1] == 0x0B) )

            continue;

        buf2 = buf;

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

            uint8_t buf3[4096];

            uint8_t bitstream_id;

            uint16_t frame_size;

            int i, ret;

            if(!memcmp(buf2, "\x1\x10\0\0\0\0\0\0", 8))

                buf2+=16;

            if (buf[0] == 0x77 && buf[1] == 0x0B) {

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

                    buf3[i  ] = buf2[i+1];

                    buf3[i+1] = buf2[i  ];

                }

                ret = av_ac3_parse_header(buf3, 8, &bitstream_id,

                                          &frame_size);

            }else

                ret = av_ac3_parse_header(buf2, end - buf2, &bitstream_id,

                                          &frame_size);

            if (ret < 0)

                break;

            if(buf2 + frame_size > end)

                break;

            if (buf[0] == 0x77 && buf[1] == 0x0B) {

                av_assert0(frame_size <= sizeof(buf3));

                for(i = 8; i < frame_size; i += 2) {

                    buf3[i  ] = buf2[i+1];

                    buf3[i+1] = buf2[i  ];

                }

                if (av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf3 + 2, frame_size - 2))

                    break;

            } else {

                if (av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf2 + 2, frame_size - 2))

                    break;

            }

            if (bitstream_id > 10)

                codec_id = AV_CODEC_ID_EAC3;

            buf2 += frame_size;

        }

        max_frames = FFMAX(max_frames, frames);

        if(buf == p->buf)

            first_frames = frames;

    }

    if(codec_id != expected_codec_id) return 0;

    // keep this in sync with mp3 probe, both need to avoid

    // issues with MPEG-files!

    if   (first_frames>=7) return AVPROBE_SCORE_EXTENSION + 1;

    else if(max_frames>200)return AVPROBE_SCORE_EXTENSION;

    else if(max_frames>=4) return AVPROBE_SCORE_EXTENSION/2;

    else if(max_frames>=1) return 1;

    else                   return 0;

}


static int segment_end(AVFormatContext *oc, int write_trailer)

{

    int ret = 0;

    av_write_frame(oc, NULL); /* Flush any buffered data (fragmented mp4) */

    if (write_trailer)

        av_write_trailer(oc);

    avio_close(oc->pb);

    return ret;

}


AVStream *avformat_new_stream(AVFormatContext *s, const AVCodec *c)

{

    AVStream *st;

    int i;

    if (av_reallocp_array(&s->streams, s->nb_streams + 1,

                          sizeof(*s->streams)) < 0) {

        s->nb_streams = 0;

        return NULL;

    }

    st = av_mallocz(sizeof(AVStream));

    if (!st)

        return NULL;

    if (!(st->info = av_mallocz(sizeof(*st->info)))) {

        av_free(st);

        return NULL;

    }

    st->codec = avcodec_alloc_context3(c);

    if (!st->codec) {

        av_free(st->info);

        av_free(st);

        return NULL;

    }

    if (s->iformat) {

        /* no default bitrate if decoding */

        st->codec->bit_rate = 0;

        /* default pts setting is MPEG-like */

        avpriv_set_pts_info(st, 33, 1, 90000);

    }

    st->index      = s->nb_streams;

    st->start_time = AV_NOPTS_VALUE;

    st->duration   = AV_NOPTS_VALUE;

    /* we set the current DTS to 0 so that formats without any timestamps

     * but durations get some timestamps, formats with some unknown

     * timestamps have their first few packets buffered and the

     * timestamps corrected before they are returned to the user */

    st->cur_dts       = 0;

    st->first_dts     = AV_NOPTS_VALUE;

    st->probe_packets = MAX_PROBE_PACKETS;

    st->last_IP_pts = AV_NOPTS_VALUE;

    for (i = 0; i < MAX_REORDER_DELAY + 1; i++)

        st->pts_buffer[i] = AV_NOPTS_VALUE;

    st->sample_aspect_ratio = (AVRational) { 0, 1 };

    st->info->fps_first_dts = AV_NOPTS_VALUE;

    st->info->fps_last_dts  = AV_NOPTS_VALUE;

    s->streams[s->nb_streams++] = st;

    return st;

}


static int cdxa_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf[0] == 'R' && p->buf[1] == 'I' &&

        p->buf[2] == 'F' && p->buf[3] == 'F' &&

        p->buf[8] == 'C' && p->buf[9] == 'D' &&

        p->buf[10] == 'X' && p->buf[11] == 'A')

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static int set_string_fmt(void *obj, const AVOption *o, const char *val, uint8_t *dst,

                          int fmt_nb, int ((*get_fmt)(const char *)), const char *desc)

{

    int fmt;

    if (!val || !strcmp(val, "none")) {

        fmt = -1;

    } else {

        fmt = get_fmt(val);

        if (fmt == -1) {

            char *tail;

            fmt = strtol(val, &tail, 0);

            if (*tail || (unsigned)fmt >= fmt_nb) {

                av_log(obj, AV_LOG_ERROR,

                       "Unable to parse option value \"%s\" as %s\n", val, desc);

                return AVERROR(EINVAL);

            }

        }

    }

    *(int *)dst = fmt;

    return 0;

}


static int ratecontrol_1pass(SnowContext *s, AVFrame *pict)

{

    /* estimate the frame's complexity as a sum of weighted dwt coefs.

     * FIXME we know exact mv bits at this point,

     * but ratecontrol isn't set up to include them. */

    uint32_t coef_sum= 0;

    int level, orientation, delta_qlog;

    for(level=0; level<s->spatial_decomposition_count; level++){

        for(orientation=level ? 1 : 0; orientation<4; orientation++){

            SubBand *b= &s->plane[0].band[level][orientation];

            DWTELEM *buf= b->buf;

            const int w= b->width;

            const int h= b->height;

            const int stride= b->stride;

            const int qlog= clip(2*QROOT + b->qlog, 0, QROOT*16);

            const int qmul= qexp[qlog&(QROOT-1)]<<(qlog>>QSHIFT);

            const int qdiv= (1<<16)/qmul;

            int x, y;

            if(orientation==0)

                decorrelate(s, b, buf, stride, 1, 0);

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

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

                    coef_sum+= abs(buf[x+y*stride]) * qdiv >> 16;

            if(orientation==0)

                correlate(s, b, buf, stride, 1, 0);

        }

    }

    /* ugly, ratecontrol just takes a sqrt again */

    coef_sum = (uint64_t)coef_sum * coef_sum >> 16;

    assert(coef_sum < INT_MAX);

    if(pict->pict_type == I_TYPE){

        s->m.current_picture.mb_var_sum= coef_sum;

        s->m.current_picture.mc_mb_var_sum= 0;

    }else{

        s->m.current_picture.mc_mb_var_sum= coef_sum;

        s->m.current_picture.mb_var_sum= 0;

    }

    pict->quality= ff_rate_estimate_qscale(&s->m, 1);

    if (pict->quality < 0)

        return -1;

    s->lambda= pict->quality * 3/2;

    delta_qlog= qscale2qlog(pict->quality) - s->qlog;

    s->qlog+= delta_qlog;

    return delta_qlog;

}


static void lsp2lpc(int16_t *lpc)

{

    int f1[LPC_ORDER / 2 + 1];

    int f2[LPC_ORDER / 2 + 1];

    int i, j;

    /* Calculate negative cosine */

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

        int index     = lpc[j] >> 7;

        int offset    = lpc[j] & 0x7f;

        int temp1     = cos_tab[index] << 16;

        int temp2     = (cos_tab[index + 1] - cos_tab[index]) *

                          ((offset << 8) + 0x80) << 1;

        lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);

    }

    /*

     * Compute sum and difference polynomial coefficients

     * (bitexact alternative to lsp2poly() in lsp.c)

     */

    /* Initialize with values in Q28 */

    f1[0] = 1 << 28;

    f1[1] = (lpc[0] << 14) + (lpc[2] << 14);

    f1[2] = lpc[0] * lpc[2] + (2 << 28);

    f2[0] = 1 << 28;

    f2[1] = (lpc[1] << 14) + (lpc[3] << 14);

    f2[2] = lpc[1] * lpc[3] + (2 << 28);

    /*

     * Calculate and scale the coefficients by 1/2 in

     * each iteration for a final scaling factor of Q25

     */

    for (i = 2; i < LPC_ORDER / 2; i++) {

        f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);

        f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);

        for (j = i; j >= 2; j--) {

            f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +

                    (f1[j] >> 1) + (f1[j - 2] >> 1);

            f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +

                    (f2[j] >> 1) + (f2[j - 2] >> 1);

        }

        f1[0] >>= 1;

        f2[0] >>= 1;

        f1[1] = ((lpc[2 * i]     << 16 >> i) + f1[1]) >> 1;

        f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;

    }

    /* Convert polynomial coefficients to LPC coefficients */

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

        int64_t ff1 = f1[i + 1] + f1[i];

        int64_t ff2 = f2[i + 1] - f2[i];

        lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;

        lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +

                                                (1 << 15)) >> 16;

    }

}


static inline void mix_3f_2r_to_dolby(AC3DecodeContext *ctx)

{

    int i;

    float (*output)[256] = ctx->audio_block.block_output;

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

        output[1][i] += (output[2][i] - output[4][i] - output[5][i]);

        output[2][i] += (output[3][i] + output[4][i] + output[5][i]);

    }

    memset(output[3], 0, sizeof(output[3]));

    memset(output[4], 0, sizeof(output[4]));

    memset(output[5], 0, sizeof(output[5]));

}


static int ffm_read_header(AVFormatContext *s)

{

    FFMContext *ffm = s->priv_data;

    AVStream *st;

    AVIOContext *pb = s->pb;

    AVCodecContext *codec;

    int i, nb_streams;

    uint32_t tag;

    /* header */

    tag = avio_rl32(pb);

    if (tag == MKTAG('F', 'F', 'M', '2'))

        return ffm2_read_header(s);

    if (tag != MKTAG('F', 'F', 'M', '1'))

        goto fail;

    ffm->packet_size = avio_rb32(pb);

    if (ffm->packet_size != FFM_PACKET_SIZE)

        goto fail;

    ffm->write_index = avio_rb64(pb);

    /* get also filesize */

    if (pb->seekable) {

        ffm->file_size = avio_size(pb);

        if (ffm->write_index && 0)

            adjust_write_index(s);

    } else {

        ffm->file_size = (UINT64_C(1) << 63) - 1;

    }

    nb_streams = avio_rb32(pb);

    avio_rb32(pb); /* total bitrate */

    /* read each stream */

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

        char rc_eq_buf[128];

        st = avformat_new_stream(s, NULL);

        if (!st)

            goto fail;

        avpriv_set_pts_info(st, 64, 1, 1000000);

        codec = st->codec;

        /* generic info */

        codec->codec_id = avio_rb32(pb);

        codec->codec_type = avio_r8(pb); /* codec_type */

        codec->bit_rate = avio_rb32(pb);

        codec->flags = avio_rb32(pb);

        codec->flags2 = avio_rb32(pb);

        codec->debug = avio_rb32(pb);

        /* specific info */

        switch(codec->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            codec->time_base.num = avio_rb32(pb);

            codec->time_base.den = avio_rb32(pb);

            codec->width = avio_rb16(pb);

            codec->height = avio_rb16(pb);

            codec->gop_size = avio_rb16(pb);

            codec->pix_fmt = avio_rb32(pb);

            codec->qmin = avio_r8(pb);

            codec->qmax = avio_r8(pb);

            codec->max_qdiff = avio_r8(pb);

            codec->qcompress = avio_rb16(pb) / 10000.0;

            codec->qblur = avio_rb16(pb) / 10000.0;

            codec->bit_rate_tolerance = avio_rb32(pb);

            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));

            codec->rc_eq = av_strdup(rc_eq_buf);

            codec->rc_max_rate = avio_rb32(pb);

            codec->rc_min_rate = avio_rb32(pb);

            codec->rc_buffer_size = avio_rb32(pb);

            codec->i_quant_factor = av_int2double(avio_rb64(pb));

            codec->b_quant_factor = av_int2double(avio_rb64(pb));

            codec->i_quant_offset = av_int2double(avio_rb64(pb));

            codec->b_quant_offset = av_int2double(avio_rb64(pb));

            codec->dct_algo = avio_rb32(pb);

            codec->strict_std_compliance = avio_rb32(pb);

            codec->max_b_frames = avio_rb32(pb);

            codec->mpeg_quant = avio_rb32(pb);

            codec->intra_dc_precision = avio_rb32(pb);

            codec->me_method = avio_rb32(pb);

            codec->mb_decision = avio_rb32(pb);

            codec->nsse_weight = avio_rb32(pb);

            codec->frame_skip_cmp = avio_rb32(pb);

            codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));

            codec->codec_tag = avio_rb32(pb);

            codec->thread_count = avio_r8(pb);

            codec->coder_type = avio_rb32(pb);

            codec->me_cmp = avio_rb32(pb);

            codec->me_subpel_quality = avio_rb32(pb);

            codec->me_range = avio_rb32(pb);

            codec->keyint_min = avio_rb32(pb);

            codec->scenechange_threshold = avio_rb32(pb);

            codec->b_frame_strategy = avio_rb32(pb);

            codec->qcompress = av_int2double(avio_rb64(pb));

            codec->qblur = av_int2double(avio_rb64(pb));

            codec->max_qdiff = avio_rb32(pb);

            codec->refs = avio_rb32(pb);

            break;

        case AVMEDIA_TYPE_AUDIO:

            codec->sample_rate = avio_rb32(pb);

            codec->channels = avio_rl16(pb);

            codec->frame_size = avio_rl16(pb);

            break;

        default:

            goto fail;

        }

        if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {

            if (ff_get_extradata(codec, pb, avio_rb32(pb)) < 0)

                return AVERROR(ENOMEM);

        }

    }

    /* get until end of block reached */

    while ((avio_tell(pb) % ffm->packet_size) != 0)

        avio_r8(pb);

    /* init packet demux */

    ffm->packet_ptr = ffm->packet;

    ffm->packet_end = ffm->packet;

    ffm->frame_offset = 0;

    ffm->dts = 0;

    ffm->read_state = READ_HEADER;

    ffm->first_packet = 1;

    return 0;

 fail:

    ffm_close(s);

    return -1;

}


static int svq3_decode_mb (H264Context *h, unsigned int mb_type) {

  int i, j, k, m, dir, mode;

  int cbp = 0;

  uint32_t vlc;

  int8_t *top, *left;

  MpegEncContext *const s = (MpegEncContext *) h;

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

  const int b_xy = 4*s->mb_x + 4*s->mb_y*h->b_stride;

  h->top_samples_available	= (s->mb_y == 0) ? 0x33FF : 0xFFFF;

  h->left_samples_available	= (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

  h->topright_samples_available	= 0xFFFF;

  if (mb_type == 0) {		/* SKIP */

    if (s->pict_type == P_TYPE || s->next_picture.mb_type[mb_xy] == -1) {

      svq3_mc_dir_part (s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 0, 0);

      if (s->pict_type == B_TYPE) {

	svq3_mc_dir_part (s, 16*s->mb_x, 16*s->mb_y, 16, 16, 0, 0, 0, 0, 1, 1);

      }

      mb_type = MB_TYPE_SKIP;

    } else {

      mb_type= FFMIN(s->next_picture.mb_type[mb_xy], 0);

      svq3_mc_dir (h, mb_type, PREDICT_MODE, 0, 0);

      svq3_mc_dir (h, mb_type, PREDICT_MODE, 1, 1);

      mb_type = MB_TYPE_16x16;

    }

  } else if (mb_type < 8) {	/* INTER */

    if (h->thirdpel_flag && h->halfpel_flag == !get_bits (&s->gb, 1)) {

      mode = THIRDPEL_MODE;

    } else if (h->halfpel_flag && h->thirdpel_flag == !get_bits (&s->gb, 1)) {

      mode = HALFPEL_MODE;

    } else {

      mode = FULLPEL_MODE;

    }

    /* fill caches */

    /* note ref_cache should contain here:

        ????????

        ???11111

        N??11111

        N??11111

        N??11111

        N

    */

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

      if (s->mb_x > 0 && h->intra4x4_pred_mode[mb_xy - 1][0] != -1) {

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

	  *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - 1 + i*h->b_stride];

	}

      } else {

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

	  *(uint32_t *) h->mv_cache[m][scan8[0] - 1 + i*8] = 0;

	}

      }

      if (s->mb_y > 0) {

	memcpy (h->mv_cache[m][scan8[0] - 1*8], s->current_picture.motion_val[m][b_xy - h->b_stride], 4*2*sizeof(int16_t));

	memset (&h->ref_cache[m][scan8[0] - 1*8], (h->intra4x4_pred_mode[mb_xy - s->mb_stride][4] == -1) ? PART_NOT_AVAILABLE : 1, 4);

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

	  *(uint32_t *) h->mv_cache[m][scan8[0] + 4 - 1*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - h->b_stride + 4];

	  h->ref_cache[m][scan8[0] + 4 - 1*8] =

		  (h->intra4x4_pred_mode[mb_xy - s->mb_stride + 1][0] == -1 ||

		   h->intra4x4_pred_mode[mb_xy - s->mb_stride][4] == -1) ? PART_NOT_AVAILABLE : 1;

	}else

	  h->ref_cache[m][scan8[0] + 4 - 1*8] = PART_NOT_AVAILABLE;

	if (s->mb_x > 0) {

	  *(uint32_t *) h->mv_cache[m][scan8[0] - 1 - 1*8] = *(uint32_t *) s->current_picture.motion_val[m][b_xy - h->b_stride - 1];

	  h->ref_cache[m][scan8[0] - 1 - 1*8] = (h->intra4x4_pred_mode[mb_xy - s->mb_stride - 1][3] == -1) ? PART_NOT_AVAILABLE : 1;

	}else

	  h->ref_cache[m][scan8[0] - 1 - 1*8] = PART_NOT_AVAILABLE;

      }else

	memset (&h->ref_cache[m][scan8[0] - 1*8 - 1], PART_NOT_AVAILABLE, 8);

      if (s->pict_type != B_TYPE)

	break;

    }

    /* decode motion vector(s) and form prediction(s) */

    if (s->pict_type == P_TYPE) {

      svq3_mc_dir (h, (mb_type - 1), mode, 0, 0);

    } else {	/* B_TYPE */

      if (mb_type != 2) {

	svq3_mc_dir (h, 0, mode, 0, 0);

      } else {

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

	  memset (s->current_picture.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

	}

      }

      if (mb_type != 1) {

	svq3_mc_dir (h, 0, mode, 1, (mb_type == 3));

      } else {

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

	  memset (s->current_picture.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

	}

      }

    }

    mb_type = MB_TYPE_16x16;

  } else if (mb_type == 8 || mb_type == 33) {	/* INTRA4x4 */

    memset (h->intra4x4_pred_mode_cache, -1, 8*5*sizeof(int8_t));

    if (mb_type == 8) {

      if (s->mb_x > 0) {

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

	  h->intra4x4_pred_mode_cache[scan8[0] - 1 + i*8] = h->intra4x4_pred_mode[mb_xy - 1][i];

	}

	if (h->intra4x4_pred_mode_cache[scan8[0] - 1] == -1) {

	  h->left_samples_available = 0x5F5F;

	}

      }

      if (s->mb_y > 0) {

	h->intra4x4_pred_mode_cache[4+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][4];

	h->intra4x4_pred_mode_cache[5+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][5];

	h->intra4x4_pred_mode_cache[6+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][6];

	h->intra4x4_pred_mode_cache[7+8*0] = h->intra4x4_pred_mode[mb_xy - s->mb_stride][3];

	if (h->intra4x4_pred_mode_cache[4+8*0] == -1) {

	  h->top_samples_available = 0x33FF;

	}

      }

      /* decode prediction codes for luma blocks */

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

	vlc = svq3_get_ue_golomb (&s->gb);

	if (vlc >= 25)

	  return -1;

	left	= &h->intra4x4_pred_mode_cache[scan8[i] - 1];

	top	= &h->intra4x4_pred_mode_cache[scan8[i] - 8];

	left[1]	= svq3_pred_1[top[0] + 1][left[0] + 1][svq3_pred_0[vlc][0]];

	left[2]	= svq3_pred_1[top[1] + 1][left[1] + 1][svq3_pred_0[vlc][1]];

	if (left[1] == -1 || left[2] == -1)

	  return -1;

      }

    } else {	/* mb_type == 33, DC_128_PRED block type */

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

	memset (&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_PRED, 4);

      }

    }

    write_back_intra_pred_mode (h);

    if (mb_type == 8) {

      check_intra4x4_pred_mode (h);

      h->top_samples_available  = (s->mb_y == 0) ? 0x33FF : 0xFFFF;

      h->left_samples_available = (s->mb_x == 0) ? 0x5F5F : 0xFFFF;

    } else {

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

        memset (&h->intra4x4_pred_mode_cache[scan8[0] + 8*i], DC_128_PRED, 4);

      }

      h->top_samples_available  = 0x33FF;

      h->left_samples_available = 0x5F5F;

    }

    mb_type = MB_TYPE_INTRA4x4;

  } else {			/* INTRA16x16 */

    dir = i_mb_type_info[mb_type - 8].pred_mode;

    dir = (dir >> 1) ^ 3*(dir & 1) ^ 1;

    if ((h->intra16x16_pred_mode = check_intra_pred_mode (h, dir)) == -1)

      return -1;

    cbp = i_mb_type_info[mb_type - 8].cbp;

    mb_type = MB_TYPE_INTRA16x16;

  }

  if (!IS_INTER(mb_type) && s->pict_type != I_TYPE) {

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

      memset (s->current_picture.motion_val[0][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

    }

    if (s->pict_type == B_TYPE) {

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

	memset (s->current_picture.motion_val[1][b_xy + i*h->b_stride], 0, 4*2*sizeof(int16_t));

      }

    }

  }

  if (!IS_INTRA4x4(mb_type)) {

    memset (h->intra4x4_pred_mode[mb_xy], DC_PRED, 8);

  }

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

    memset (h->non_zero_count_cache + 8, 0, 4*9*sizeof(uint8_t));

    s->dsp.clear_blocks(h->mb);

  }

  if (!IS_INTRA16x16(mb_type) && (!IS_SKIP(mb_type) || s->pict_type == B_TYPE)) {

    if ((vlc = svq3_get_ue_golomb (&s->gb)) >= 48)

      return -1;

    cbp = IS_INTRA(mb_type) ? golomb_to_intra4x4_cbp[vlc] : golomb_to_inter_cbp[vlc];

  }

  if (IS_INTRA16x16(mb_type) || (s->pict_type != I_TYPE && s->adaptive_quant && cbp)) {

    s->qscale += svq3_get_se_golomb (&s->gb);

    if (s->qscale > 31)

      return -1;

  }

  if (IS_INTRA16x16(mb_type)) {

    if (svq3_decode_block (&s->gb, h->mb, 0, 0))

      return -1;

  }

  if (cbp) {

    const int index = IS_INTRA16x16(mb_type) ? 1 : 0;

    const int type = ((s->qscale < 24 && IS_INTRA4x4(mb_type)) ? 2 : 1);

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

      if ((cbp & (1 << i))) {

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

	  k = index ? ((j&1) + 2*(i&1) + 2*(j&2) + 4*(i&2)) : (4*i + j);

	  h->non_zero_count_cache[ scan8[k] ] = 1;

	  if (svq3_decode_block (&s->gb, &h->mb[16*k], index, type))

	    return -1;

	}

      }

    }

    if ((cbp & 0x30)) {

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

	if (svq3_decode_block (&s->gb, &h->mb[16*(16 + 4*i)], 0, 3))

	  return -1;

      }

      if ((cbp & 0x20)) {

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

	  h->non_zero_count_cache[ scan8[16+i] ] = 1;

	  if (svq3_decode_block (&s->gb, &h->mb[16*(16 + i)], 1, 1))

	    return -1;

	}

      }

    }

  }

  s->current_picture.mb_type[mb_xy] = mb_type;

  if (IS_INTRA(mb_type)) {

    h->chroma_pred_mode = check_intra_pred_mode (h, DC_PRED8x8);

  }

  return 0;

}


static void rtsp_send_cmd (AVFormatContext *s,

                           const char *cmd, RTSPMessageHeader *reply,

                           unsigned char **content_ptr)

{

    rtsp_send_cmd_async(s, cmd, reply, content_ptr);

    rtsp_read_reply(s, reply, content_ptr, 0);

}


static int rtsp_read_header(AVFormatContext *s,

                            AVFormatParameters *ap)

{

    RTSPState *rt = s->priv_data;

    int ret;

    ret = ff_rtsp_connect(s);

    if (ret)

        return ret;

    rt->real_setup_cache = av_mallocz(2 * s->nb_streams * sizeof(*rt->real_setup_cache));

    if (!rt->real_setup_cache)

        return AVERROR(ENOMEM);

    rt->real_setup = rt->real_setup_cache + s->nb_streams * sizeof(*rt->real_setup);

    if (ap->initial_pause) {

         /* do not start immediately */

    } else {

         if (rtsp_read_play(s) < 0) {

            ff_rtsp_close_streams(s);

            ff_rtsp_close_connections(s);

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


static void xhci_event(XHCIState *xhci, XHCIEvent *event, int v)

{

    XHCIInterrupter *intr;

    dma_addr_t erdp;

    unsigned int dp_idx;

    if (v >= xhci->numintrs) {

        DPRINTF("intr nr out of range (%d >= %d)\n", v, xhci->numintrs);

        return;

    }

    intr = &xhci->intr[v];

    if (intr->er_full) {

        DPRINTF("xhci_event(): ER full, queueing\n");

        if (((intr->ev_buffer_put+1) % EV_QUEUE) == intr->ev_buffer_get) {

            DPRINTF("xhci: event queue full, dropping event!\n");

            return;

        }

        intr->ev_buffer[intr->ev_buffer_put++] = *event;

        if (intr->ev_buffer_put == EV_QUEUE) {

            intr->ev_buffer_put = 0;

        }

        return;

    }

    erdp = xhci_addr64(intr->erdp_low, intr->erdp_high);

    if (erdp < intr->er_start ||

        erdp >= (intr->er_start + TRB_SIZE*intr->er_size)) {

        DPRINTF("xhci: ERDP out of bounds: "DMA_ADDR_FMT"\n", erdp);

        DPRINTF("xhci: ER[%d] at "DMA_ADDR_FMT" len %d\n",

                v, intr->er_start, intr->er_size);

        xhci_die(xhci);

        return;

    }

    dp_idx = (erdp - intr->er_start) / TRB_SIZE;

    assert(dp_idx < intr->er_size);

    if ((intr->er_ep_idx+1) % intr->er_size == dp_idx) {

        DPRINTF("xhci_event(): ER full, queueing\n");

#ifndef ER_FULL_HACK

        XHCIEvent full = {ER_HOST_CONTROLLER, CC_EVENT_RING_FULL_ERROR};

        xhci_write_event(xhci, &full);

#endif

        intr->er_full = 1;

        if (((intr->ev_buffer_put+1) % EV_QUEUE) == intr->ev_buffer_get) {

            DPRINTF("xhci: event queue full, dropping event!\n");

            return;

        }

        intr->ev_buffer[intr->ev_buffer_put++] = *event;

        if (intr->ev_buffer_put == EV_QUEUE) {

            intr->ev_buffer_put = 0;

        }

    } else {

        xhci_write_event(xhci, event, v);

    }

    xhci_intr_raise(xhci, v);

}


static void ehci_advance_state(EHCIState *ehci, int async)

{

    EHCIQueue *q = NULL;

    int again;

    do {

        switch(ehci_get_state(ehci, async)) {

        case EST_WAITLISTHEAD:

            again = ehci_state_waitlisthead(ehci, async);

            break;

        case EST_FETCHENTRY:

            again = ehci_state_fetchentry(ehci, async);

            break;

        case EST_FETCHQH:

            q = ehci_state_fetchqh(ehci, async);

            if (q != NULL) {

                assert(q->async == async);

                again = 1;

            } else {

                again = 0;

            }

            break;

        case EST_FETCHITD:

            again = ehci_state_fetchitd(ehci, async);

            break;

        case EST_FETCHSITD:

            again = ehci_state_fetchsitd(ehci, async);

            break;

        case EST_ADVANCEQUEUE:

            assert(q != NULL);

            again = ehci_state_advqueue(q);

            break;

        case EST_FETCHQTD:

            assert(q != NULL);

            again = ehci_state_fetchqtd(q);

            break;

        case EST_HORIZONTALQH:

            assert(q != NULL);

            again = ehci_state_horizqh(q);

            break;

        case EST_EXECUTE:

            assert(q != NULL);

            again = ehci_state_execute(q);

            if (async) {

                ehci->async_stepdown = 0;

            }

            break;

        case EST_EXECUTING:

            assert(q != NULL);

            if (async) {

                ehci->async_stepdown = 0;

            }

            again = ehci_state_executing(q);

            break;

        case EST_WRITEBACK:

            assert(q != NULL);

            again = ehci_state_writeback(q);

            if (!async) {

                ehci->periodic_sched_active = PERIODIC_ACTIVE;

            }

            break;

        default:

            fprintf(stderr, "Bad state!\n");

            again = -1;

            g_assert_not_reached();

            break;

        }

        if (again < 0) {

            fprintf(stderr, "processing error - resetting ehci HC\n");

            ehci_reset(ehci);

            again = 0;

        }

    }

    while (again);

}


int ff_lpc_calc_coefs(LPCContext *s,
                      const int32_t *samples, int blocksize, int min_order,
                      int max_order, int precision,
                      int32_t coefs[][MAX_LPC_ORDER], int *shift,
                      enum FFLPCType lpc_type, int lpc_passes,
                      int omethod, int max_shift, int zero_shift)
{
    double autoc[MAX_LPC_ORDER+1];
    double ref[MAX_LPC_ORDER];
    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
    int i, j, pass;
    int opt_order;
    av_assert2(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER &&
           lpc_type > FF_LPC_TYPE_FIXED);
    /* reinit LPC context if parameters have changed */
    if (blocksize != s->blocksize || max_order != s->max_order ||
        lpc_type  != s->lpc_type) {
        ff_lpc_end(s);
        ff_lpc_init(s, blocksize, max_order, lpc_type);
    }
    if (lpc_type == FF_LPC_TYPE_LEVINSON) {
        double *windowed_samples = s->windowed_samples + max_order;
        s->lpc_apply_welch_window(samples, blocksize, windowed_samples);
        s->lpc_compute_autocorr(windowed_samples, blocksize, max_order, autoc);
        compute_lpc_coefs(autoc, max_order, &lpc[0][0], MAX_LPC_ORDER, 0, 1);
        for(i=0; i<max_order; i++)
            ref[i] = fabs(lpc[i][i]);
    } else if (lpc_type == FF_LPC_TYPE_CHOLESKY) {
        LLSModel m[2];
        double var[MAX_LPC_ORDER+1], av_uninit(weight);
        for(pass=0; pass<lpc_passes; pass++){
            av_init_lls(&m[pass&1], max_order);
            weight=0;
            for(i=max_order; i<blocksize; i++){
                for(j=0; j<=max_order; j++)
                    var[j]= samples[i-j];
                if(pass){
                    double eval, inv, rinv;
                    eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
                    eval= (512>>pass) + fabs(eval - var[0]);
                    inv = 1/eval;
                    rinv = sqrt(inv);
                    for(j=0; j<=max_order; j++)
                        var[j] *= rinv;
                    weight += inv;
                }else
                    weight++;
                av_update_lls(&m[pass&1], var, 1.0);
            }
            av_solve_lls(&m[pass&1], 0.001, 0);
        }
        for(i=0; i<max_order; i++){
            for(j=0; j<max_order; j++)
                lpc[i][j]=-m[(pass-1)&1].coeff[i][j];
            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
        }
        for(i=max_order-1; i>0; i--)
            ref[i] = ref[i-1] - ref[i];
    }
    opt_order = max_order;
    if(omethod == ORDER_METHOD_EST) {
        opt_order = estimate_best_order(ref, min_order, max_order);
        i = opt_order-1;
        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);
    } else {
        for(i=min_order-1; i<max_order; i++) {
            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i], max_shift, zero_shift);
        }
    }
    return opt_order;
}


void do_device_add(Monitor *mon, const QDict *qdict)

{

    QemuOpts *opts;

    opts = qemu_opts_parse(&qemu_device_opts,

                           qdict_get_str(qdict, "config"), "driver");

    if (opts && !qdev_device_help(opts))

        qdev_device_add(opts);

}


static void update_irq(struct xlx_pic *p)

{

    uint32_t i;

    /* level triggered interrupt */

    if (p->regs[R_MER] & 2) {

        p->regs[R_ISR] |= p->irq_pin_state & ~p->c_kind_of_intr;

    }

    /* Update the pending register.  */

    p->regs[R_IPR] = p->regs[R_ISR] & p->regs[R_IER];

    /* Update the vector register.  */

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

        if (p->regs[R_IPR] & (1 << i))

            break;

    }

    if (i == 32)

        i = ~0;

    p->regs[R_IVR] = i;

    qemu_set_irq(p->parent_irq, (p->regs[R_MER] & 1) && p->regs[R_IPR]);

}


static void init_proc_e500 (CPUPPCState *env, int version)

{

    uint32_t tlbncfg[2];

    uint64_t ivor_mask = 0x0000000F0000FFFFULL;

#if !defined(CONFIG_USER_ONLY)

    int i;

#endif

    /* Time base */

    gen_tbl(env);

    /*

     * XXX The e500 doesn't implement IVOR7 and IVOR9, but doesn't

     *     complain when accessing them.

     * gen_spr_BookE(env, 0x0000000F0000FD7FULL);

     */

    if (version == fsl_e500mc) {

        ivor_mask = 0x000003FE0000FFFFULL;

    }

    gen_spr_BookE(env, ivor_mask);

    /* Processor identification */

    spr_register(env, SPR_BOOKE_PIR, "PIR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_pir,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_SPEFSCR, "SPEFSCR",

                 &spr_read_spefscr, &spr_write_spefscr,

                 &spr_read_spefscr, &spr_write_spefscr,

                 0x00000000);

    /* Memory management */

#if !defined(CONFIG_USER_ONLY)

    env->nb_pids = 3;

    env->nb_ways = 2;

    env->id_tlbs = 0;

    switch (version) {

    case fsl_e500v1:

        /* e500v1 */

        tlbncfg[0] = gen_tlbncfg(2, 1, 1, 0, 256);

        tlbncfg[1] = gen_tlbncfg(16, 1, 9, TLBnCFG_AVAIL | TLBnCFG_IPROT, 16);

        env->dcache_line_size = 32;

        env->icache_line_size = 32;

        break;

    case fsl_e500v2:

        /* e500v2 */

        tlbncfg[0] = gen_tlbncfg(4, 1, 1, 0, 512);

        tlbncfg[1] = gen_tlbncfg(16, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 16);

        env->dcache_line_size = 32;

        env->icache_line_size = 32;

        break;

    case fsl_e500mc:

        /* e500mc */

        tlbncfg[0] = gen_tlbncfg(4, 1, 1, 0, 512);

        tlbncfg[1] = gen_tlbncfg(64, 1, 12, TLBnCFG_AVAIL | TLBnCFG_IPROT, 64);

        env->dcache_line_size = 64;

        env->icache_line_size = 64;

        break;

    default:

        cpu_abort(env, "Unknown CPU: " TARGET_FMT_lx "\n", env->spr[SPR_PVR]);

    }

#endif

    gen_spr_BookE206(env, 0x000000DF, tlbncfg);

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BBEAR, "BBEAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BBTAR, "BBTAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_MCAR, "MCAR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_BOOKE_MCSR, "MCSR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_NPIDR, "NPIDR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_BUCSR, "BUCSR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CFG0, "L1CFG0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CSR0, "L1CSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_e500_l1csr0,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_Exxx_L1CSR1, "L1CSR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_BOOKE_MCSRR0, "MCSRR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_BOOKE_MCSRR1, "MCSRR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_MMUCSR0, "MMUCSR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_booke206_mmucsr0,

                 0x00000000);

#if !defined(CONFIG_USER_ONLY)

    env->nb_tlb = 0;

    env->tlb_type = TLB_MAS;

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

        env->nb_tlb += booke206_tlb_size(env, i);

    }

#endif

    init_excp_e200(env);

    /* Allocate hardware IRQ controller */

    ppce500_irq_init(env);

}


static void interface_get_init_info(QXLInstance *sin, QXLDevInitInfo *info)

{

    SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);

    info->memslot_gen_bits = MEMSLOT_GENERATION_BITS;

    info->memslot_id_bits  = MEMSLOT_SLOT_BITS;

    info->num_memslots = NUM_MEMSLOTS;

    info->num_memslots_groups = NUM_MEMSLOTS_GROUPS;

    info->internal_groupslot_id = 0;

    info->qxl_ram_size = ssd->bufsize;

    info->n_surfaces = ssd->num_surfaces;

}


static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)

{

    MPCContext *c = s->priv_data;

    int tag;

    int64_t size, pos, ppos[2];

    uint8_t *buf;

    int i, t, seekd;

    GetBitContext gb;

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

    mpc8_get_chunk_header(s->pb, &tag, &size);

    if(tag != TAG_SEEKTABLE){

        av_log(s, AV_LOG_ERROR, "No seek table at given position\n");

    if(!(buf = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE)))

    avio_read(s->pb, buf, size);

    init_get_bits(&gb, buf, size * 8);

    size = gb_get_v(&gb);

    if(size > UINT_MAX/4 || size > c->samples/1152){

        av_log(s, AV_LOG_ERROR, "Seek table is too big\n");

    seekd = get_bits(&gb, 4);

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

        pos = gb_get_v(&gb) + c->header_pos;

        ppos[1 - i] = pos;

        av_add_index_entry(s->streams[0], pos, i, 0, 0, AVINDEX_KEYFRAME);

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

        t = get_unary(&gb, 1, 33) << 12;

        t += get_bits(&gb, 12);

        if(t & 1)

            t = -(t & ~1);

        pos = (t >> 1) + ppos[0]*2 - ppos[1];

        av_add_index_entry(s->streams[0], pos, i << seekd, 0, 0, AVINDEX_KEYFRAME);

        ppos[1] = ppos[0];

        ppos[0] = pos;

    av_free(buf);


static void esp_do_dma(ESPState *s)

{

    uint32_t len;

    int to_device;

    to_device = (s->ti_size < 0);

    len = s->dma_left;

    if (s->do_cmd) {

        DPRINTF("command len %d + %d\n", s->cmdlen, len);

        s->dma_memory_read(s->dma_opaque, &s->cmdbuf[s->cmdlen], len);

        s->ti_size = 0;

        s->cmdlen = 0;

        s->do_cmd = 0;

        do_cmd(s, s->cmdbuf);

        return;

    }

    if (s->async_len == 0) {

        /* Defer until data is available.  */

        return;

    }

    if (len > s->async_len) {

        len = s->async_len;

    }

    if (to_device) {

        s->dma_memory_read(s->dma_opaque, s->async_buf, len);

    } else {

        s->dma_memory_write(s->dma_opaque, s->async_buf, len);

    }

    s->dma_left -= len;

    s->async_buf += len;

    s->async_len -= len;

    if (to_device)

        s->ti_size += len;

    else

        s->ti_size -= len;

    if (s->async_len == 0) {

        if (to_device) {

            // ti_size is negative

            s->current_dev->info->write_data(s->current_dev, 0);

        } else {

            s->current_dev->info->read_data(s->current_dev, 0);

            /* If there is still data to be read from the device then

               complete the DMA operation immediately.  Otherwise defer

               until the scsi layer has completed.  */

            if (s->dma_left == 0 && s->ti_size > 0) {

                esp_dma_done(s);

            }

        }

    } else {

        /* Partially filled a scsi buffer. Complete immediately.  */

        esp_dma_done(s);

    }

}


void ide_sector_write(IDEState *s)
{
    int64_t sector_num;
    int n;
    s->status = READY_STAT | SEEK_STAT | BUSY_STAT;
    sector_num = ide_get_sector(s);
#if defined(DEBUG_IDE)
    printf("sector=%" PRId64 "\n", sector_num);
#endif
    n = s->nsector;
    if (n > s->req_nb_sectors) {
        n = s->req_nb_sectors;
    s->iov.iov_base = s->io_buffer;
    s->iov.iov_len  = n * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&s->qiov, &s->iov, 1);
    bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
    s->pio_aiocb = bdrv_aio_writev(s->bs, sector_num, &s->qiov, n,
                                   ide_sector_write_cb, s);


static void openrisc_sim_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    OpenRISCCPU *cpu = NULL;

    MemoryRegion *ram;

    int n;

    if (!cpu_model) {

        cpu_model = "or1200";

    }

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

        cpu = OPENRISC_CPU(cpu_generic_init(TYPE_OPENRISC_CPU, cpu_model));

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find CPU definition!\n");

            exit(1);

        }

        qemu_register_reset(main_cpu_reset, cpu);

        main_cpu_reset(cpu);

    }

    ram = g_malloc(sizeof(*ram));

    memory_region_init_ram(ram, NULL, "openrisc.ram", ram_size, &error_fatal);

    memory_region_add_subregion(get_system_memory(), 0, ram);

    cpu_openrisc_pic_init(cpu);

    cpu_openrisc_clock_init(cpu);

    serial_mm_init(get_system_memory(), 0x90000000, 0, cpu->env.irq[2],

                   115200, serial_hds[0], DEVICE_NATIVE_ENDIAN);

    if (nd_table[0].used) {

        openrisc_sim_net_init(get_system_memory(), 0x92000000,

                              0x92000400, cpu->env.irq[4], nd_table);

    }

    cpu_openrisc_load_kernel(ram_size, kernel_filename, cpu);

}


static int decode_block_coeffs_internal(VP56RangeCoder *c, DCTELEM block[16],

                                        uint8_t probs[16][3][NUM_DCT_TOKENS-1],

                                        int i, uint8_t *token_prob, int16_t qmul[2])

{

    goto skip_eob;

    do {

        int coeff;

        if (!vp56_rac_get_prob_branchy(c, token_prob[0]))   // DCT_EOB

            return i;

skip_eob:

        if (!vp56_rac_get_prob_branchy(c, token_prob[1])) { // DCT_0

            if (++i == 16)

                return i; // invalid input; blocks should end with EOB

            token_prob = probs[i][0];

            goto skip_eob;

        }

        if (!vp56_rac_get_prob_branchy(c, token_prob[2])) { // DCT_1

            coeff = 1;

            token_prob = probs[i+1][1];

        } else {

            if (!vp56_rac_get_prob_branchy(c, token_prob[3])) { // DCT 2,3,4

                coeff = vp56_rac_get_prob_branchy(c, token_prob[4]);

                if (coeff)

                    coeff += vp56_rac_get_prob(c, token_prob[5]);

                coeff += 2;

            } else {

                // DCT_CAT*

                if (!vp56_rac_get_prob_branchy(c, token_prob[6])) {

                    if (!vp56_rac_get_prob_branchy(c, token_prob[7])) { // DCT_CAT1

                        coeff  = 5 + vp56_rac_get_prob(c, vp8_dct_cat1_prob[0]);

                    } else {                                    // DCT_CAT2

                        coeff  = 7;

                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[0]) << 1;

                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[1]);

                    }

                } else {    // DCT_CAT3 and up

                    int a = vp56_rac_get_prob(c, token_prob[8]);

                    int b = vp56_rac_get_prob(c, token_prob[9+a]);

                    int cat = (a<<1) + b;

                    coeff  = 3 + (8<<cat);

                    coeff += vp8_rac_get_coeff(c, ff_vp8_dct_cat_prob[cat]);

                }

            }

            token_prob = probs[i+1][2];

        }

        block[zigzag_scan[i]] = (vp8_rac_get(c) ? -coeff : coeff) * qmul[!!i];

    } while (++i < 16);

    return i;

}


yuv2mono_X_c_template(SwsContext *c, const int16_t *lumFilter,

                      const int16_t **lumSrc, int lumFilterSize,

                      const int16_t *chrFilter, const int16_t **chrUSrc,

                      const int16_t **chrVSrc, int chrFilterSize,

                      const int16_t **alpSrc, uint8_t *dest, int dstW,

                      int y, enum AVPixelFormat target)

{

    const uint8_t * const d128=dither_8x8_220[y&7];

    int i;

    unsigned acc = 0;

    int err = 0;

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

        int j;

        int Y1 = 1 << 18;

        int Y2 = 1 << 18;

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

            Y1 += lumSrc[j][i]   * lumFilter[j];

            Y2 += lumSrc[j][i+1] * lumFilter[j];

        }

        Y1 >>= 19;

        Y2 >>= 19;

        if ((Y1 | Y2) & 0x100) {

            Y1 = av_clip_uint8(Y1);

            Y2 = av_clip_uint8(Y2);

        }

        if (c->flags & SWS_ERROR_DIFFUSION) {

            Y1 += (7*err + 1*c->dither_error[0][i] + 5*c->dither_error[0][i+1] + 3*c->dither_error[0][i+2] + 8 - 256)>>4;

            c->dither_error[0][i] = err;

            acc = 2*acc + (Y1 >= 128);

            Y1 -= 220*(acc&1);

            err = Y2 + ((7*Y1 + 1*c->dither_error[0][i+1] + 5*c->dither_error[0][i+2] + 3*c->dither_error[0][i+3] + 8 - 256)>>4);

            c->dither_error[0][i+1] = Y1;

            acc = 2*acc + (err >= 128);

            err -= 220*(acc&1);

        } else {

            accumulate_bit(acc, Y1 + d128[(i + 0) & 7]);

            accumulate_bit(acc, Y2 + d128[(i + 1) & 7]);

        }

        if ((i & 7) == 6) {

            output_pixel(*dest++, acc);

        }

    }

    c->dither_error[0][i] = err;

    if (i & 6) {

        output_pixel(*dest, acc);

    }

}


int ff_rate_control_init(MpegEncContext *s)

{

    RateControlContext *rcc= &s->rc_context;

    int i;

    char *error = NULL;

    static const char *const_names[]={

        "PI",

        "E",

        "iTex",

        "pTex",

        "tex",

        "mv",

        "fCode",

        "iCount",

        "mcVar",

        "var",

        "isI",

        "isP",

        "isB",

        "avgQP",

        "qComp",

/*        "lastIQP",

        "lastPQP",

        "lastBQP",

        "nextNonBQP",*/

        "avgIITex",

        "avgPITex",

        "avgPPTex",

        "avgBPTex",

        "avgTex",

        NULL

    };

    static double (*func1[])(void *, double)={

        (void *)bits2qp,

        (void *)qp2bits,

        NULL

    };

    static const char *func1_names[]={

        "bits2qp",

        "qp2bits",

        NULL

    };

    emms_c();

    rcc->rc_eq_eval = ff_parse(s->avctx->rc_eq, const_names, func1, func1_names, NULL, NULL, &error);

    if (!rcc->rc_eq_eval) {

        av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\": %s\n", s->avctx->rc_eq, error? error : "");

        return -1;

    }

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

        rcc->pred[i].coeff= FF_QP2LAMBDA * 7.0;

        rcc->pred[i].count= 1.0;

        rcc->pred[i].decay= 0.4;

        rcc->i_cplx_sum [i]=

        rcc->p_cplx_sum [i]=

        rcc->mv_bits_sum[i]=

        rcc->qscale_sum [i]=

        rcc->frame_count[i]= 1; // 1 is better cuz of 1/0 and such

        rcc->last_qscale_for[i]=FF_QP2LAMBDA * 5;

    }

    rcc->buffer_index= s->avctx->rc_initial_buffer_occupancy;

    if(s->flags&CODEC_FLAG_PASS2){

        int i;

        char *p;

        /* find number of pics */

        p= s->avctx->stats_in;

        for(i=-1; p; i++){

            p= strchr(p+1, ';');

        }

        i+= s->max_b_frames;

        if(i<=0 || i>=INT_MAX / sizeof(RateControlEntry))

            return -1;

        rcc->entry = (RateControlEntry*)av_mallocz(i*sizeof(RateControlEntry));

        rcc->num_entries= i;

        /* init all to skipped p frames (with b frames we might have a not encoded frame at the end FIXME) */

        for(i=0; i<rcc->num_entries; i++){

            RateControlEntry *rce= &rcc->entry[i];

            rce->pict_type= rce->new_pict_type=P_TYPE;

            rce->qscale= rce->new_qscale=FF_QP2LAMBDA * 2;

            rce->misc_bits= s->mb_num + 10;

            rce->mb_var_sum= s->mb_num*100;

        }

        /* read stats */

        p= s->avctx->stats_in;

        for(i=0; i<rcc->num_entries - s->max_b_frames; i++){

            RateControlEntry *rce;

            int picture_number;

            int e;

            char *next;

            next= strchr(p, ';');

            if(next){

                (*next)=0; //sscanf in unbelievably slow on looong strings //FIXME copy / do not write

                next++;

            }

            e= sscanf(p, " in:%d ", &picture_number);

            assert(picture_number >= 0);

            assert(picture_number < rcc->num_entries);

            rce= &rcc->entry[picture_number];

            e+=sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d",

                   &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits, &rce->mv_bits, &rce->misc_bits,

                   &rce->f_code, &rce->b_code, &rce->mc_mb_var_sum, &rce->mb_var_sum, &rce->i_count, &rce->skip_count, &rce->header_bits);

            if(e!=14){

                av_log(s->avctx, AV_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);

                return -1;

            }

            p= next;

        }

        if(init_pass2(s) < 0) return -1;

        //FIXME maybe move to end

        if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {

#ifdef CONFIG_LIBXVID

            return ff_xvid_rate_control_init(s);

#else

            av_log(s->avctx, AV_LOG_ERROR, "XviD ratecontrol requires libavcodec compiled with XviD support\n");

            return -1;

#endif

        }

    }

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

        rcc->short_term_qsum=0.001;

        rcc->short_term_qcount=0.001;

        rcc->pass1_rc_eq_output_sum= 0.001;

        rcc->pass1_wanted_bits=0.001;

        if(s->avctx->qblur > 1.0){

            av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");

            return -1;

        }

        /* init stuff with the user specified complexity */

        if(s->avctx->rc_initial_cplx){

            for(i=0; i<60*30; i++){

                double bits= s->avctx->rc_initial_cplx * (i/10000.0 + 1.0)*s->mb_num;

                RateControlEntry rce;

                double q;

                if     (i%((s->gop_size+3)/4)==0) rce.pict_type= I_TYPE;

                else if(i%(s->max_b_frames+1))    rce.pict_type= B_TYPE;

                else                              rce.pict_type= P_TYPE;

                rce.new_pict_type= rce.pict_type;

                rce.mc_mb_var_sum= bits*s->mb_num/100000;

                rce.mb_var_sum   = s->mb_num;

                rce.qscale   = FF_QP2LAMBDA * 2;

                rce.f_code   = 2;

                rce.b_code   = 1;

                rce.misc_bits= 1;

                if(s->pict_type== I_TYPE){

                    rce.i_count   = s->mb_num;

                    rce.i_tex_bits= bits;

                    rce.p_tex_bits= 0;

                    rce.mv_bits= 0;

                }else{

                    rce.i_count   = 0; //FIXME we do know this approx

                    rce.i_tex_bits= 0;

                    rce.p_tex_bits= bits*0.9;

                    rce.mv_bits= bits*0.1;

                }

                rcc->i_cplx_sum [rce.pict_type] += rce.i_tex_bits*rce.qscale;

                rcc->p_cplx_sum [rce.pict_type] += rce.p_tex_bits*rce.qscale;

                rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;

                rcc->frame_count[rce.pict_type] ++;

                bits= rce.i_tex_bits + rce.p_tex_bits;

                q= get_qscale(s, &rce, rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum, i);

                rcc->pass1_wanted_bits+= s->bit_rate/(1/av_q2d(s->avctx->time_base)); //FIXME misbehaves a little for variable fps

            }

        }

    }

    return 0;

}


bool sysbus_has_irq(SysBusDevice *dev, int n)
{
    char *prop = g_strdup_printf("%s[%d]", SYSBUS_DEVICE_GPIO_IRQ, n);
    ObjectProperty *r;
    r = object_property_find(OBJECT(dev), prop, NULL);
    return (r != NULL);
}


static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,

                                             bool want_zero,

                                             int64_t offset, int64_t bytes,

                                             int64_t *pnum, int64_t *map,

                                             BlockDriverState **file)

{

    int64_t total_size;

    int64_t n; /* bytes */

    int ret;

    int64_t local_map = 0;

    BlockDriverState *local_file = NULL;

    int64_t aligned_offset, aligned_bytes;

    uint32_t align;

    assert(pnum);

    *pnum = 0;

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        ret = total_size;

        goto early_out;

    }

    if (offset >= total_size) {

        ret = BDRV_BLOCK_EOF;

        goto early_out;

    }

    if (!bytes) {

        ret = 0;

        goto early_out;

    }

    n = total_size - offset;

    if (n < bytes) {

        bytes = n;

    }

    if (!bs->drv->bdrv_co_get_block_status) {

        *pnum = bytes;

        ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;

        if (offset + bytes == total_size) {

            ret |= BDRV_BLOCK_EOF;

        }

        if (bs->drv->protocol_name) {

            ret |= BDRV_BLOCK_OFFSET_VALID;

            local_map = offset;

            local_file = bs;

        }

        goto early_out;

    }

    bdrv_inc_in_flight(bs);

    /* Round out to request_alignment boundaries */

    /* TODO: until we have a byte-based driver callback, we also have to

     * round out to sectors, even if that is bigger than request_alignment */

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

    aligned_offset = QEMU_ALIGN_DOWN(offset, align);

    aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;

    {

        int count; /* sectors */

        int64_t longret;

        assert(QEMU_IS_ALIGNED(aligned_offset | aligned_bytes,

                               BDRV_SECTOR_SIZE));

        /*

         * The contract allows us to return pnum smaller than bytes, even

         * if the next query would see the same status; we truncate the

         * request to avoid overflowing the driver's 32-bit interface.

         */

        longret = bs->drv->bdrv_co_get_block_status(

            bs, aligned_offset >> BDRV_SECTOR_BITS,

            MIN(INT_MAX, aligned_bytes) >> BDRV_SECTOR_BITS, &count,

            &local_file);

        if (longret < 0) {

            assert(INT_MIN <= longret);

            ret = longret;

            goto out;

        }

        if (longret & BDRV_BLOCK_OFFSET_VALID) {

            local_map = longret & BDRV_BLOCK_OFFSET_MASK;

        }

        ret = longret & ~BDRV_BLOCK_OFFSET_MASK;

        *pnum = count * BDRV_SECTOR_SIZE;

    }

    /*

     * The driver's result must be a multiple of request_alignment.

     * Clamp pnum and adjust map to original request.

     */

    assert(QEMU_IS_ALIGNED(*pnum, align) && align > offset - aligned_offset);

    *pnum -= offset - aligned_offset;

    if (*pnum > bytes) {

        *pnum = bytes;

    }

    if (ret & BDRV_BLOCK_OFFSET_VALID) {

        local_map += offset - aligned_offset;

    }

    if (ret & BDRV_BLOCK_RAW) {

        assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);

        ret = bdrv_co_block_status(local_file, want_zero, local_map,

                                   *pnum, pnum, &local_map, &local_file);

        goto out;

    }

    if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {

        ret |= BDRV_BLOCK_ALLOCATED;

    } else if (want_zero) {

        if (bdrv_unallocated_blocks_are_zero(bs)) {

            ret |= BDRV_BLOCK_ZERO;

        } else if (bs->backing) {

            BlockDriverState *bs2 = bs->backing->bs;

            int64_t size2 = bdrv_getlength(bs2);

            if (size2 >= 0 && offset >= size2) {

                ret |= BDRV_BLOCK_ZERO;

            }

        }

    }

    if (want_zero && local_file && local_file != bs &&

        (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&

        (ret & BDRV_BLOCK_OFFSET_VALID)) {

        int64_t file_pnum;

        int ret2;

        ret2 = bdrv_co_block_status(local_file, want_zero, local_map,

                                    *pnum, &file_pnum, NULL, NULL);

        if (ret2 >= 0) {

            /* Ignore errors.  This is just providing extra information, it

             * is useful but not necessary.

             */

            if (ret2 & BDRV_BLOCK_EOF &&

                (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {

                /*

                 * It is valid for the format block driver to read

                 * beyond the end of the underlying file's current

                 * size; such areas read as zero.

                 */

                ret |= BDRV_BLOCK_ZERO;

            } else {

                /* Limit request to the range reported by the protocol driver */

                *pnum = file_pnum;

                ret |= (ret2 & BDRV_BLOCK_ZERO);

            }

        }

    }

out:

    bdrv_dec_in_flight(bs);

    if (ret >= 0 && offset + *pnum == total_size) {

        ret |= BDRV_BLOCK_EOF;

    }

early_out:

    if (file) {

        *file = local_file;

    }

    if (map) {

        *map = local_map;

    }

    return ret;

}


static void simple_string(void)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

    } test_cases[] = {

        { "\"hello world\"", "hello world" },

        { "\"the quick brown fox jumped over the fence\"",

          "the quick brown fox jumped over the fence" },

        {}

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded, NULL);

        str = qobject_to_qstring(obj);

        g_assert(str);

        g_assert(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        str = qobject_to_json(obj);

        g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

        qobject_decref(obj);

        QDECREF(str);

    }

}


static void spr_write_tbu(DisasContext *ctx, int sprn, int gprn)

{

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_store_tbu(cpu_env, cpu_gpr[gprn]);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static int decode_block(AVCodecContext *avctx, void *tdata,

                        int jobnr, int threadnr)

{

    EXRContext *s = avctx->priv_data;

    AVFrame *const p = s->picture;

    EXRThreadData *td = &s->thread_data[threadnr];

    const uint8_t *channel_buffer[4] = { 0 };

    const uint8_t *buf = s->buf;

    uint64_t line_offset, uncompressed_size;

    uint16_t *ptr_x;

    uint8_t *ptr;

    uint32_t data_size;

    uint64_t line, col = 0;

    uint64_t tile_x, tile_y, tile_level_x, tile_level_y;

    const uint8_t *src;

    int axmax = (avctx->width - (s->xmax + 1)) * 2 * s->desc->nb_components; /* nb pixel to add at the right of the datawindow */

    int bxmin = s->xmin * 2 * s->desc->nb_components; /* nb pixel to add at the left of the datawindow */

    int i, x, buf_size = s->buf_size;

    int c, rgb_channel_count;

    float one_gamma = 1.0f / s->gamma;

    avpriv_trc_function trc_func = avpriv_get_trc_function_from_trc(s->apply_trc_type);

    int ret;

    line_offset = AV_RL64(s->gb.buffer + jobnr * 8);

    if (s->is_tile) {

        if (line_offset > buf_size - 20)

            return AVERROR_INVALIDDATA;

        src  = buf + line_offset + 20;

        tile_x = AV_RL32(src - 20);

        tile_y = AV_RL32(src - 16);

        tile_level_x = AV_RL32(src - 12);

        tile_level_y = AV_RL32(src - 8);

        data_size = AV_RL32(src - 4);

        if (data_size <= 0 || data_size > buf_size)

            return AVERROR_INVALIDDATA;

        if (tile_level_x || tile_level_y) { /* tile level, is not the full res level */

            avpriv_report_missing_feature(s->avctx, "Subres tile before full res tile");

            return AVERROR_PATCHWELCOME;

        }

        if (s->xmin || s->ymin) {

            avpriv_report_missing_feature(s->avctx, "Tiles with xmin/ymin");

            return AVERROR_PATCHWELCOME;

        }

        line = s->tile_attr.ySize * tile_y;

        col = s->tile_attr.xSize * tile_x;

        if (line < s->ymin || line > s->ymax ||

            col  < s->xmin || col  > s->xmax)

            return AVERROR_INVALIDDATA;

        td->ysize = FFMIN(s->tile_attr.ySize, s->ydelta - tile_y * s->tile_attr.ySize);

        td->xsize = FFMIN(s->tile_attr.xSize, s->xdelta - tile_x * s->tile_attr.xSize);

        if (col) { /* not the first tile of the line */

            bxmin = 0; /* doesn't add pixel at the left of the datawindow */

        }

        if ((col + td->xsize) != s->xdelta)/* not the last tile of the line */

            axmax = 0; /* doesn't add pixel at the right of the datawindow */

        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */

        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */

    } else {

        if (line_offset > buf_size - 8)

            return AVERROR_INVALIDDATA;

        src  = buf + line_offset + 8;

        line = AV_RL32(src - 8);

        if (line < s->ymin || line > s->ymax)

            return AVERROR_INVALIDDATA;

        data_size = AV_RL32(src - 4);

        if (data_size <= 0 || data_size > buf_size)

            return AVERROR_INVALIDDATA;

        td->ysize          = FFMIN(s->scan_lines_per_block, s->ymax - line + 1); /* s->ydelta - line ?? */

        td->xsize          = s->xdelta;

        td->channel_line_size = td->xsize * s->current_channel_offset;/* uncompress size of one line */

        uncompressed_size = td->channel_line_size * (uint64_t)td->ysize;/* uncompress size of the block */

        if ((s->compression == EXR_RAW && (data_size != uncompressed_size ||

                                           line_offset > buf_size - uncompressed_size)) ||

            (s->compression != EXR_RAW && (data_size > uncompressed_size ||

                                           line_offset > buf_size - data_size))) {

            return AVERROR_INVALIDDATA;

        }

    }

    if (data_size < uncompressed_size || s->is_tile) { /* td->tmp is use for tile reorganization */

        av_fast_padded_malloc(&td->tmp, &td->tmp_size, uncompressed_size);

        if (!td->tmp)

            return AVERROR(ENOMEM);

    }

    if (data_size < uncompressed_size) {

        av_fast_padded_malloc(&td->uncompressed_data,

                              &td->uncompressed_size, uncompressed_size + 64);/* Force 64 padding for AVX2 reorder_pixels dst */

        if (!td->uncompressed_data)

            return AVERROR(ENOMEM);

        ret = AVERROR_INVALIDDATA;

        switch (s->compression) {

        case EXR_ZIP1:

        case EXR_ZIP16:

            ret = zip_uncompress(s, src, data_size, uncompressed_size, td);

            break;

        case EXR_PIZ:

            ret = piz_uncompress(s, src, data_size, uncompressed_size, td);

            break;

        case EXR_PXR24:

            ret = pxr24_uncompress(s, src, data_size, uncompressed_size, td);

            break;

        case EXR_RLE:

            ret = rle_uncompress(s, src, data_size, uncompressed_size, td);

            break;

        case EXR_B44:

        case EXR_B44A:

            ret = b44_uncompress(s, src, data_size, uncompressed_size, td);

            break;

        }

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "decode_block() failed.\n");

            return ret;

        }

        src = td->uncompressed_data;

    }

    if (!s->is_luma) {

        channel_buffer[0] = src + td->xsize * s->channel_offsets[0];

        channel_buffer[1] = src + td->xsize * s->channel_offsets[1];

        channel_buffer[2] = src + td->xsize * s->channel_offsets[2];

        rgb_channel_count = 3;

    } else { /* put y data in the first channel_buffer */

        channel_buffer[0] = src + td->xsize * s->channel_offsets[1];

        rgb_channel_count = 1;

    }

    if (s->channel_offsets[3] >= 0)

        channel_buffer[3] = src + td->xsize * s->channel_offsets[3];

    ptr = p->data[0] + line * p->linesize[0] + (col * s->desc->nb_components * 2);

    for (i = 0;

         i < td->ysize; i++, ptr += p->linesize[0]) {

        const uint8_t * a;

        const uint8_t *rgb[3];

        for (c = 0; c < rgb_channel_count; c++){

            rgb[c] = channel_buffer[c];

        }

        if (channel_buffer[3])

            a = channel_buffer[3];

        ptr_x = (uint16_t *) ptr;

        // Zero out the start if xmin is not 0

        memset(ptr_x, 0, bxmin);

        ptr_x += s->xmin * s->desc->nb_components;

        if (s->pixel_type == EXR_FLOAT) {

            // 32-bit

            if (trc_func) {

                for (x = 0; x < td->xsize; x++) {

                    union av_intfloat32 t;

                    for (c = 0; c < rgb_channel_count; c++) {

                        t.i = bytestream_get_le32(&rgb[c]);

                        t.f = trc_func(t.f);

                        *ptr_x++ = exr_flt2uint(t.i);

                    }

                    if (channel_buffer[3])

                        *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));

                }

            } else {

                for (x = 0; x < td->xsize; x++) {

                    union av_intfloat32 t;

                    int c;

                    for (c = 0; c < rgb_channel_count; c++) {

                        t.i = bytestream_get_le32(&rgb[c]);

                        if (t.f > 0.0f)  /* avoid negative values */

                            t.f = powf(t.f, one_gamma);

                        *ptr_x++ = exr_flt2uint(t.i);

                    }

                    if (channel_buffer[3])

                        *ptr_x++ = exr_flt2uint(bytestream_get_le32(&a));

                }

            }

        } else if (s->pixel_type == EXR_HALF) {

            // 16-bit

            for (x = 0; x < td->xsize; x++) {

                int c;

                for (c = 0; c < rgb_channel_count; c++) {

                    *ptr_x++ = s->gamma_table[bytestream_get_le16(&rgb[c])];

                }

                if (channel_buffer[3])

                    *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&a));

            }

        } else if (s->pixel_type == EXR_UINT) {

            for (x = 0; x < td->xsize; x++) {

                for (c = 0; c < rgb_channel_count; c++) {

                    *ptr_x++ = bytestream_get_le32(&rgb[c]) >> 16;

                }

                if (channel_buffer[3])

                    *ptr_x++ = bytestream_get_le32(&a) >> 16;

            }

        }

        // Zero out the end if xmax+1 is not w

        memset(ptr_x, 0, axmax);

        channel_buffer[0] += td->channel_line_size;

        channel_buffer[1] += td->channel_line_size;

        channel_buffer[2] += td->channel_line_size;

        if (channel_buffer[3])

            channel_buffer[3] += td->channel_line_size;

    }

    return 0;

}


void watchdog_pc_init(PCIBus *pci_bus)

{

    if (watchdog)

        watchdog->wdt_pc_init(pci_bus);

}


static void copy_bits(PutBitContext *pb,

                      const uint8_t *data, int size,

                      GetBitContext *gb, int nbits)

{

    int rmn_bytes, rmn_bits;

    rmn_bits = rmn_bytes = get_bits_left(gb);

    if (rmn_bits < nbits)

    rmn_bits &= 7; rmn_bytes >>= 3;

    if ((rmn_bits = FFMIN(rmn_bits, nbits)) > 0)

        put_bits(pb, rmn_bits, get_bits(gb, rmn_bits));

    ff_copy_bits(pb, data + size - rmn_bytes,

                 FFMIN(nbits - rmn_bits, rmn_bytes << 3));

}


int ff_asf_parse_packet(AVFormatContext *s, ByteIOContext *pb, AVPacket *pkt)

{

    ASFContext *asf = s->priv_data;

    ASFStream *asf_st = 0;

    for (;;) {

        if(url_feof(pb))

            return AVERROR_EOF;

        if (asf->packet_size_left < FRAME_HEADER_SIZE

            || asf->packet_segments < 1) {

            //asf->packet_size_left <= asf->packet_padsize) {

            int ret = asf->packet_size_left + asf->packet_padsize;

            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));

            assert(ret>=0);

            /* fail safe */

            url_fskip(pb, ret);

            asf->packet_pos= url_ftell(pb);

            if (asf->data_object_size != (uint64_t)-1 &&

                (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))

                return AVERROR(EIO); /* Do not exceed the size of the data object */

            return 1;

        }

        if (asf->packet_time_start == 0) {

            if(asf_read_frame_header(s, pb) < 0){

                asf->packet_segments= 0;

                continue;

            }

            if (asf->stream_index < 0

                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL

                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)

                ) {

                asf->packet_time_start = 0;

                /* unhandled packet (should not happen) */

                url_fskip(pb, asf->packet_frag_size);

                asf->packet_size_left -= asf->packet_frag_size;

                if(asf->stream_index < 0)

                    av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);

                continue;

            }

            asf->asf_st = s->streams[asf->stream_index]->priv_data;

        }

        asf_st = asf->asf_st;

        if (asf->packet_replic_size == 1) {

            // frag_offset is here used as the beginning timestamp

            asf->packet_frag_timestamp = asf->packet_time_start;

            asf->packet_time_start += asf->packet_time_delta;

            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);

            asf->packet_size_left--;

            asf->packet_multi_size--;

            if (asf->packet_multi_size < asf->packet_obj_size)

            {

                asf->packet_time_start = 0;

                url_fskip(pb, asf->packet_multi_size);

                asf->packet_size_left -= asf->packet_multi_size;

                continue;

            }

            asf->packet_multi_size -= asf->packet_obj_size;

            //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);

        }

        if(   /*asf->packet_frag_size == asf->packet_obj_size*/

              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size

           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){

            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",

                asf_st->frag_offset, asf->packet_frag_size,

                asf->packet_obj_size, asf_st->pkt.size);

            asf->packet_obj_size= asf_st->pkt.size;

        }

        if (   asf_st->pkt.size != asf->packet_obj_size

            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?

            if(asf_st->pkt.data){

                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);

                asf_st->frag_offset = 0;

                av_free_packet(&asf_st->pkt);

            }

            /* new packet */

            av_new_packet(&asf_st->pkt, asf->packet_obj_size);

            asf_st->seq = asf->packet_seq;

            asf_st->pkt.dts = asf->packet_frag_timestamp;

            asf_st->pkt.stream_index = asf->stream_index;

            asf_st->pkt.pos =

            asf_st->packet_pos= asf->packet_pos;

//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",

//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,

//s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);

            if (s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO)

                asf->packet_key_frame = 1;

            if (asf->packet_key_frame)

                asf_st->pkt.flags |= PKT_FLAG_KEY;

        }

        /* read data */

        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",

        //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,

        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);

        asf->packet_size_left -= asf->packet_frag_size;

        if (asf->packet_size_left < 0)

            continue;

        if(   asf->packet_frag_offset >= asf_st->pkt.size

           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){

            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",

                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);

            continue;

        }

        get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,

                   asf->packet_frag_size);

        if (s->key && s->keylen == 20)

            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,

                            asf->packet_frag_size);

        asf_st->frag_offset += asf->packet_frag_size;

        /* test if whole packet is read */

        if (asf_st->frag_offset == asf_st->pkt.size) {

            //workaround for macroshit radio DVR-MS files

            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO

               && asf_st->pkt.size > 100){

                int i;

                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);

                if(i == asf_st->pkt.size){

                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");

                    asf_st->frag_offset = 0;

                    av_free_packet(&asf_st->pkt);

                    continue;

                }

            }

            /* return packet */

            if (asf_st->ds_span > 1) {

              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){

                    av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);

              }else{

                /* packet descrambling */

                uint8_t *newdata = av_malloc(asf_st->pkt.size);

                if (newdata) {

                    int offset = 0;

                    while (offset < asf_st->pkt.size) {

                        int off = offset / asf_st->ds_chunk_size;

                        int row = off / asf_st->ds_span;

                        int col = off % asf_st->ds_span;

                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;

                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);

                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);

                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);

                        memcpy(newdata + offset,

                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,

                               asf_st->ds_chunk_size);

                        offset += asf_st->ds_chunk_size;

                    }

                    av_free(asf_st->pkt.data);

                    asf_st->pkt.data = newdata;

                }

              }

            }

            asf_st->frag_offset = 0;

            *pkt= asf_st->pkt;

            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);

            asf_st->pkt.size = 0;

            asf_st->pkt.data = 0;

            break; // packet completed

        }

    }

    return 0;

}


static int xmv_read_close(AVFormatContext *s)

{

    XMVDemuxContext *xmv = s->priv_data;

    av_free(xmv->audio);

    av_free(xmv->audio_tracks);

    return 0;

}


static void mpeg1_encode_sequence_header(MpegEncContext *s)

{

        unsigned int vbv_buffer_size;

        unsigned int fps, v;

        int i;

        uint64_t time_code;

        float best_aspect_error= 1E10;

        float aspect_ratio= av_q2d(s->avctx->sample_aspect_ratio);

        int constraint_parameter_flag;

        if(aspect_ratio==0.0) aspect_ratio= 1.0; //pixel aspect 1:1 (VGA)

        if (s->current_picture.key_frame) {

            AVRational framerate= frame_rate_tab[s->frame_rate_index];

            /* mpeg1 header repeated every gop */

            put_header(s, SEQ_START_CODE);

            put_bits(&s->pb, 12, s->width);

            put_bits(&s->pb, 12, s->height);

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

                float error= aspect_ratio;

                if(s->codec_id == CODEC_ID_MPEG1VIDEO || i <=1)

                    error-= 1.0/mpeg1_aspect[i];

                else

                    error-= av_q2d(mpeg2_aspect[i])*s->height/s->width;

                error= ABS(error);

                if(error < best_aspect_error){

                    best_aspect_error= error;

                    s->aspect_ratio_info= i;

                }

            }

            put_bits(&s->pb, 4, s->aspect_ratio_info);

            put_bits(&s->pb, 4, s->frame_rate_index);

            if(s->avctx->rc_max_rate){

                v = (s->avctx->rc_max_rate + 399) / 400;

                if (v > 0x3ffff && s->codec_id == CODEC_ID_MPEG1VIDEO)

                    v = 0x3ffff;

            }else{

                v= 0x3FFFF;

            }

            if(s->avctx->rc_buffer_size)

                vbv_buffer_size = s->avctx->rc_buffer_size;

            else

                /* VBV calculation: Scaled so that a VCD has the proper VBV size of 40 kilobytes */

                vbv_buffer_size = (( 20 * s->bit_rate) / (1151929 / 2)) * 8 * 1024;

            vbv_buffer_size= (vbv_buffer_size + 16383) / 16384;

            put_bits(&s->pb, 18, v & 0x3FFFF);

            put_bits(&s->pb, 1, 1); /* marker */

            put_bits(&s->pb, 10, vbv_buffer_size & 0x3FF);

            constraint_parameter_flag=

                s->width <= 768 && s->height <= 576 &&

                s->mb_width * s->mb_height <= 396 &&

                s->mb_width * s->mb_height * framerate.num <= framerate.den*396*25 &&

                framerate.num <= framerate.den*30 &&

                vbv_buffer_size <= 20 &&

                v <= 1856000/400 &&

                s->codec_id == CODEC_ID_MPEG1VIDEO;

            put_bits(&s->pb, 1, constraint_parameter_flag);

            ff_write_quant_matrix(&s->pb, s->avctx->intra_matrix);

            ff_write_quant_matrix(&s->pb, s->avctx->inter_matrix);

            if(s->codec_id == CODEC_ID_MPEG2VIDEO){

                put_header(s, EXT_START_CODE);

                put_bits(&s->pb, 4, 1); //seq ext

                put_bits(&s->pb, 1, 0); //esc

                put_bits(&s->pb, 3, 4); //profile

                put_bits(&s->pb, 4, 8); //level

                put_bits(&s->pb, 1, s->progressive_sequence);

                put_bits(&s->pb, 2, 1); //chroma format 4:2:0

                put_bits(&s->pb, 2, 0); //horizontal size ext

                put_bits(&s->pb, 2, 0); //vertical size ext

                put_bits(&s->pb, 12, v>>18); //bitrate ext

                put_bits(&s->pb, 1, 1); //marker

                put_bits(&s->pb, 8, vbv_buffer_size >>10); //vbv buffer ext

                put_bits(&s->pb, 1, s->low_delay);

                put_bits(&s->pb, 2, 0); // frame_rate_ext_n

                put_bits(&s->pb, 5, 0); // frame_rate_ext_d

            }

            put_header(s, GOP_START_CODE);

            put_bits(&s->pb, 1, 0); /* do drop frame */

            /* time code : we must convert from the real frame rate to a

               fake mpeg frame rate in case of low frame rate */

            fps = (framerate.num + framerate.den/2)/ framerate.den;

            time_code = s->current_picture_ptr->coded_picture_number;

            s->gop_picture_number = time_code;

            put_bits(&s->pb, 5, (uint32_t)((time_code / (fps * 3600)) % 24));

            put_bits(&s->pb, 6, (uint32_t)((time_code / (fps * 60)) % 60));

            put_bits(&s->pb, 1, 1);

            put_bits(&s->pb, 6, (uint32_t)((time_code / fps) % 60));

            put_bits(&s->pb, 6, (uint32_t)((time_code % fps)));

            put_bits(&s->pb, 1, !!(s->flags & CODEC_FLAG_CLOSED_GOP));

            put_bits(&s->pb, 1, 0); /* broken link */

        }

}


int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                         AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    VP56Context *s = avctx->priv_data;

    AVFrame *const p = s->frames[VP56_FRAME_CURRENT];

    int remaining_buf_size = avpkt->size;

    int av_uninit(alpha_offset);

    int i, res;

    if (s->has_alpha) {

        if (remaining_buf_size < 3)

            return -1;

        alpha_offset = bytestream_get_be24(&buf);

        remaining_buf_size -= 3;

        if (remaining_buf_size < alpha_offset)

            return -1;

    }

    res = s->parse_header(s, buf, remaining_buf_size);

    if (res < 0)

        return res;

    if (res == VP56_SIZE_CHANGE) {

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

            av_frame_unref(s->frames[i]);

            if (s->alpha_context)

                av_frame_unref(s->alpha_context->frames[i]);

        }

    }

    if (ff_get_buffer(avctx, p, AV_GET_BUFFER_FLAG_REF) < 0)

        return -1;

    if (s->has_alpha) {

        av_frame_unref(s->alpha_context->frames[VP56_FRAME_CURRENT]);

        av_frame_ref(s->alpha_context->frames[VP56_FRAME_CURRENT], p);

    }

    if (res == VP56_SIZE_CHANGE) {

        if (vp56_size_changed(s)) {

            av_frame_unref(p);

            return -1;

        }

    }

    if (s->has_alpha) {

        int bak_w = avctx->width;

        int bak_h = avctx->height;

        int bak_cw = avctx->coded_width;

        int bak_ch = avctx->coded_height;

        buf += alpha_offset;

        remaining_buf_size -= alpha_offset;

        res = s->alpha_context->parse_header(s->alpha_context, buf, remaining_buf_size);

        if (res != 0) {

            if(res==VP56_SIZE_CHANGE) {

                av_log(avctx, AV_LOG_ERROR, "Alpha reconfiguration\n");

                avctx->width  = bak_w;

                avctx->height = bak_h;

                avctx->coded_width  = bak_cw;

                avctx->coded_height = bak_ch;

            }

            av_frame_unref(p);

            return -1;

        }

    }

    avctx->execute2(avctx, ff_vp56_decode_mbs, 0, 0, s->has_alpha + 1);

    if ((res = av_frame_ref(data, p)) < 0)

        return res;

    *got_frame = 1;

    return avpkt->size;

}


static int vfio_get_device(VFIOGroup *group, const char *name,

                           VFIOPCIDevice *vdev)

{

    struct vfio_device_info dev_info = { .argsz = sizeof(dev_info) };

    struct vfio_region_info reg_info = { .argsz = sizeof(reg_info) };

    struct vfio_irq_info irq_info = { .argsz = sizeof(irq_info) };

    int ret, i;

    ret = ioctl(group->fd, VFIO_GROUP_GET_DEVICE_FD, name);

    if (ret < 0) {

        error_report("vfio: error getting device %s from group %d: %m",

                     name, group->groupid);

        error_printf("Verify all devices in group %d are bound to vfio-pci "

                     "or pci-stub and not already in use\n", group->groupid);

        return ret;

    }

    vdev->vbasedev.fd = ret;

    vdev->vbasedev.group = group;

    QLIST_INSERT_HEAD(&group->device_list, vdev, next);

    /* Sanity check device */

    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_INFO, &dev_info);

    if (ret) {

        error_report("vfio: error getting device info: %m");

        goto error;

    }

    trace_vfio_get_device_irq(name, dev_info.flags,

                              dev_info.num_regions, dev_info.num_irqs);

    if (!(dev_info.flags & VFIO_DEVICE_FLAGS_PCI)) {

        error_report("vfio: Um, this isn't a PCI device");

        goto error;

    }

    vdev->reset_works = !!(dev_info.flags & VFIO_DEVICE_FLAGS_RESET);

    if (dev_info.num_regions < VFIO_PCI_CONFIG_REGION_INDEX + 1) {

        error_report("vfio: unexpected number of io regions %u",

                     dev_info.num_regions);

        goto error;

    }

    if (dev_info.num_irqs < VFIO_PCI_MSIX_IRQ_INDEX + 1) {

        error_report("vfio: unexpected number of irqs %u", dev_info.num_irqs);

        goto error;

    }

    for (i = VFIO_PCI_BAR0_REGION_INDEX; i < VFIO_PCI_ROM_REGION_INDEX; i++) {

        reg_info.index = i;

        ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);

        if (ret) {

            error_report("vfio: Error getting region %d info: %m", i);

            goto error;

        }

        trace_vfio_get_device_region(name, i,

                                     (unsigned long)reg_info.size,

                                     (unsigned long)reg_info.offset,

                                     (unsigned long)reg_info.flags);

        vdev->bars[i].flags = reg_info.flags;

        vdev->bars[i].size = reg_info.size;

        vdev->bars[i].fd_offset = reg_info.offset;

        vdev->bars[i].fd = vdev->vbasedev.fd;

        vdev->bars[i].nr = i;

        QLIST_INIT(&vdev->bars[i].quirks);

    }

    reg_info.index = VFIO_PCI_CONFIG_REGION_INDEX;

    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &reg_info);

    if (ret) {

        error_report("vfio: Error getting config info: %m");

        goto error;

    }

    trace_vfio_get_device_config(name, (unsigned long)reg_info.size,

                                 (unsigned long)reg_info.offset,

                                 (unsigned long)reg_info.flags);

    vdev->config_size = reg_info.size;

    if (vdev->config_size == PCI_CONFIG_SPACE_SIZE) {

        vdev->pdev.cap_present &= ~QEMU_PCI_CAP_EXPRESS;

    }

    vdev->config_offset = reg_info.offset;

    if ((vdev->features & VFIO_FEATURE_ENABLE_VGA) &&

        dev_info.num_regions > VFIO_PCI_VGA_REGION_INDEX) {

        struct vfio_region_info vga_info = {

            .argsz = sizeof(vga_info),

            .index = VFIO_PCI_VGA_REGION_INDEX,

         };

        ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_REGION_INFO, &vga_info);

        if (ret) {

            error_report(

                "vfio: Device does not support requested feature x-vga");

            goto error;

        }

        if (!(vga_info.flags & VFIO_REGION_INFO_FLAG_READ) ||

            !(vga_info.flags & VFIO_REGION_INFO_FLAG_WRITE) ||

            vga_info.size < 0xbffff + 1) {

            error_report("vfio: Unexpected VGA info, flags 0x%lx, size 0x%lx",

                         (unsigned long)vga_info.flags,

                         (unsigned long)vga_info.size);

            goto error;

        }

        vdev->vga.fd_offset = vga_info.offset;

        vdev->vga.fd = vdev->vbasedev.fd;

        vdev->vga.region[QEMU_PCI_VGA_MEM].offset = QEMU_PCI_VGA_MEM_BASE;

        vdev->vga.region[QEMU_PCI_VGA_MEM].nr = QEMU_PCI_VGA_MEM;

        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_MEM].quirks);

        vdev->vga.region[QEMU_PCI_VGA_IO_LO].offset = QEMU_PCI_VGA_IO_LO_BASE;

        vdev->vga.region[QEMU_PCI_VGA_IO_LO].nr = QEMU_PCI_VGA_IO_LO;

        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_LO].quirks);

        vdev->vga.region[QEMU_PCI_VGA_IO_HI].offset = QEMU_PCI_VGA_IO_HI_BASE;

        vdev->vga.region[QEMU_PCI_VGA_IO_HI].nr = QEMU_PCI_VGA_IO_HI;

        QLIST_INIT(&vdev->vga.region[QEMU_PCI_VGA_IO_HI].quirks);

        vdev->has_vga = true;

    }

    irq_info.index = VFIO_PCI_ERR_IRQ_INDEX;

    ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info);

    if (ret) {

        /* This can fail for an old kernel or legacy PCI dev */

        trace_vfio_get_device_get_irq_info_failure();

        ret = 0;

    } else if (irq_info.count == 1) {

        vdev->pci_aer = true;

    } else {

        error_report("vfio: %04x:%02x:%02x.%x "

                     "Could not enable error recovery for the device",

                     vdev->host.domain, vdev->host.bus, vdev->host.slot,

                     vdev->host.function);

    }

error:

    if (ret) {

        QLIST_REMOVE(vdev, next);

        vdev->vbasedev.group = NULL;

        close(vdev->vbasedev.fd);

    }

    return ret;

}


static void css_inject_io_interrupt(SubchDev *sch)

{

    S390CPU *cpu = s390_cpu_addr2state(0);

    uint8_t isc = (sch->curr_status.pmcw.flags & PMCW_FLAGS_MASK_ISC) >> 11;

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

                           sch->curr_status.pmcw.intparm, isc, "");

    s390_io_interrupt(cpu,

                      css_build_subchannel_id(sch),

                      sch->schid,

                      sch->curr_status.pmcw.intparm,

                      isc << 27);

}


static int bonito_initfn(PCIDevice *dev)

{

    PCIBonitoState *s = DO_UPCAST(PCIBonitoState, dev, dev);

    /* Bonito North Bridge, built on FPGA, VENDOR_ID/DEVICE_ID are "undefined" */

    pci_config_set_vendor_id(dev->config, 0xdf53);

    pci_config_set_device_id(dev->config, 0x00d5);

    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_HOST);

    pci_config_set_prog_interface(dev->config, 0x00);

    pci_config_set_revision(dev->config, 0x01);

    /* set the north bridge register mapping */

    s->bonito_reg_handle = cpu_register_io_memory(bonito_read, bonito_write, s,

                                                  DEVICE_NATIVE_ENDIAN);

    s->bonito_reg_start = BONITO_INTERNAL_REG_BASE;

    s->bonito_reg_length = BONITO_INTERNAL_REG_SIZE;

    cpu_register_physical_memory(s->bonito_reg_start, s->bonito_reg_length,

                                 s->bonito_reg_handle);

    /* set the north bridge pci configure  mapping */

    s->bonito_pciconf_handle = cpu_register_io_memory(bonito_pciconf_read,

                                                      bonito_pciconf_write, s,

                                                      DEVICE_NATIVE_ENDIAN);

    s->bonito_pciconf_start = BONITO_PCICONFIG_BASE;

    s->bonito_pciconf_length = BONITO_PCICONFIG_SIZE;

    cpu_register_physical_memory(s->bonito_pciconf_start, s->bonito_pciconf_length,

                                 s->bonito_pciconf_handle);

    /* set the south bridge pci configure  mapping */

    s->bonito_spciconf_handle = cpu_register_io_memory(bonito_spciconf_read,

                                                       bonito_spciconf_write, s,

                                                       DEVICE_NATIVE_ENDIAN);

    s->bonito_spciconf_start = BONITO_SPCICONFIG_BASE;

    s->bonito_spciconf_length = BONITO_SPCICONFIG_SIZE;

    cpu_register_physical_memory(s->bonito_spciconf_start, s->bonito_spciconf_length,

                                 s->bonito_spciconf_handle);

    s->bonito_ldma_handle = cpu_register_io_memory(bonito_ldma_read,

                                                   bonito_ldma_write, s,

                                                   DEVICE_NATIVE_ENDIAN);

    s->bonito_ldma_start = 0xbfe00200;

    s->bonito_ldma_length = 0x100;

    cpu_register_physical_memory(s->bonito_ldma_start, s->bonito_ldma_length,

                                 s->bonito_ldma_handle);

    s->bonito_cop_handle = cpu_register_io_memory(bonito_cop_read,

                                                  bonito_cop_write, s,

                                                  DEVICE_NATIVE_ENDIAN);

    s->bonito_cop_start = 0xbfe00300;

    s->bonito_cop_length = 0x100;

    cpu_register_physical_memory(s->bonito_cop_start, s->bonito_cop_length,

                                 s->bonito_cop_handle);

    /* Map PCI IO Space  0x1fd0 0000 - 0x1fd1 0000 */

    s->bonito_pciio_start = BONITO_PCIIO_BASE;

    s->bonito_pciio_length = BONITO_PCIIO_SIZE;

    isa_mem_base = s->bonito_pciio_start;

    isa_mmio_init(s->bonito_pciio_start, s->bonito_pciio_length);

    /* add pci local io mapping */

    s->bonito_localio_start = BONITO_DEV_BASE;

    s->bonito_localio_length = BONITO_DEV_SIZE;

    isa_mmio_init(s->bonito_localio_start, s->bonito_localio_length);

    /* set the default value of north bridge pci config */

    pci_set_word(dev->config + PCI_COMMAND, 0x0000);

    pci_set_word(dev->config + PCI_STATUS, 0x0000);

    pci_set_word(dev->config + PCI_SUBSYSTEM_VENDOR_ID, 0x0000);

    pci_set_word(dev->config + PCI_SUBSYSTEM_ID, 0x0000);

    pci_set_byte(dev->config + PCI_INTERRUPT_LINE, 0x00);

    pci_set_byte(dev->config + PCI_INTERRUPT_PIN, 0x01);

    pci_set_byte(dev->config + PCI_MIN_GNT, 0x3c);

    pci_set_byte(dev->config + PCI_MAX_LAT, 0x00);

    qemu_register_reset(bonito_reset, s);

    return 0;

}