static int dirac_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *pkt)

{

    DiracContext *s     = avctx->priv_data;

    AVFrame *picture    = data;

    uint8_t *buf        = pkt->data;

    int buf_size        = pkt->size;

    int i, data_unit_size, buf_idx = 0;

    int ret;

    /* release unused frames */

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

        if (s->all_frames[i].avframe->data[0] && !s->all_frames[i].avframe->reference) {

            av_frame_unref(s->all_frames[i].avframe);

            memset(s->all_frames[i].interpolated, 0, sizeof(s->all_frames[i].interpolated));

        }

    s->current_picture = NULL;

    *got_frame = 0;

    /* end of stream, so flush delayed pics */

    if (buf_size == 0)

        return get_delayed_pic(s, (AVFrame *)data, got_frame);

    for (;;) {

        /*[DIRAC_STD] Here starts the code from parse_info() defined in 9.6

          [DIRAC_STD] PARSE_INFO_PREFIX = "BBCD" as defined in ISO/IEC 646

          BBCD start code search */

        for (; buf_idx + DATA_UNIT_HEADER_SIZE < buf_size; buf_idx++) {

            if (buf[buf_idx  ] == 'B' && buf[buf_idx+1] == 'B' &&

                buf[buf_idx+2] == 'C' && buf[buf_idx+3] == 'D')

                break;

        }

        /* BBCD found or end of data */

        if (buf_idx + DATA_UNIT_HEADER_SIZE >= buf_size)

            break;

        data_unit_size = AV_RB32(buf+buf_idx+5);

        if (data_unit_size > buf_size - buf_idx || !data_unit_size) {

            if(data_unit_size > buf_size - buf_idx)

            av_log(s->avctx, AV_LOG_ERROR,

                   "Data unit with size %d is larger than input buffer, discarding\n",

                   data_unit_size);

            buf_idx += 4;

            continue;

        }

        /* [DIRAC_STD] dirac_decode_data_unit makes reference to the while defined in 9.3 inside the function parse_sequence() */

        ret = dirac_decode_data_unit(avctx, buf+buf_idx, data_unit_size);

        if (ret < 0)

        {

            av_log(s->avctx, AV_LOG_ERROR,"Error in dirac_decode_data_unit\n");

            return ret;

        }

        buf_idx += data_unit_size;

    }

    if (!s->current_picture)

        return buf_size;

    if (s->current_picture->avframe->display_picture_number > s->frame_number) {

        DiracFrame *delayed_frame = remove_frame(s->delay_frames, s->frame_number);

        s->current_picture->avframe->reference |= DELAYED_PIC_REF;

        if (add_frame(s->delay_frames, MAX_DELAY, s->current_picture)) {

            int min_num = s->delay_frames[0]->avframe->display_picture_number;

            /* Too many delayed frames, so we display the frame with the lowest pts */

            av_log(avctx, AV_LOG_ERROR, "Delay frame overflow\n");

            for (i = 1; s->delay_frames[i]; i++)

                if (s->delay_frames[i]->avframe->display_picture_number < min_num)

                    min_num = s->delay_frames[i]->avframe->display_picture_number;

            delayed_frame = remove_frame(s->delay_frames, min_num);

            add_frame(s->delay_frames, MAX_DELAY, s->current_picture);

        }

        if (delayed_frame) {

            delayed_frame->avframe->reference ^= DELAYED_PIC_REF;

            if((ret=av_frame_ref(data, delayed_frame->avframe)) < 0)

                return ret;

            *got_frame = 1;

        }

    } else if (s->current_picture->avframe->display_picture_number == s->frame_number) {

        /* The right frame at the right time :-) */

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

            return ret;

        *got_frame = 1;

    }

    if (*got_frame)

        s->frame_number = picture->display_picture_number + 1;

    return buf_idx;

}


static int decode_svq1_block (bit_buffer_t *bitbuf, uint8_t *pixels, int pitch, int intra) {

  uint32_t    bit_cache;

  vlc_code_t *vlc;

  uint8_t    *list[63];

  uint32_t   *dst;

  uint32_t   *codebook;

  int	      entries[6];

  int	      i, j, m, n;

  int	      mean, stages;

  int	      x, y, width, height, level;

  uint32_t    n1, n2, n3, n4;

  /* initialize list for breadth first processing of vectors */

  list[0] = pixels;

  /* recursively process vector */

  for (i=0, m=1, n=1, level=5; i < n; i++) {

    for (; level > 0; i++) {

      /* process next depth */

      if (i == m) {

	m = n;

	if (--level == 0)

	  break;

      }

      /* divide block if next bit set */

      if (get_bits (bitbuf, 1) == 0)

	break;

      /* add child nodes */

      list[n++] = list[i];

      list[n++] = list[i] + (((level & 1) ? pitch : 1) << ((level / 2) + 1));

    }

    /* destination address and vector size */

    dst = (uint32_t *) list[i];

    width = 1 << ((4 + level) /2);

    height = 1 << ((3 + level) /2);

    /* get number of stages (-1 skips vector, 0 for mean only) */

    bit_cache = get_bit_cache (bitbuf);

    if (intra)

      vlc = &intra_vector_tables[level][bit_cache >> (32 - 7)];

    else

      vlc = &inter_vector_tables[level][bit_cache >> (32 - 6)];

    /* flush bits */

    stages	    = vlc->value;

    skip_bits(bitbuf,vlc->length);

    if (stages == -1) {

      if (intra) {

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

	  memset (&dst[y*(pitch / 4)], 0, width);

	}

      }

      continue;		/* skip vector */

    }

    if ((stages > 0) && (level >= 4)) {

#ifdef DEBUG_SVQ1

    printf("Error (decode_svq1_block): invalid vector: stages=%i level=%i\n",stages,level);

#endif

      return -1;	/* invalid vector */

    }

    /* get mean value for vector */

    bit_cache = get_bit_cache (bitbuf);

    if (intra) {

      if (bit_cache >= 0x25000000)

	vlc = &intra_mean_table_0[(bit_cache >> (32 - 8)) - 37];

      else if (bit_cache >= 0x03400000)

	vlc = &intra_mean_table_1[(bit_cache >> (32 - 10)) - 13];

      else if (bit_cache >= 0x00040000)

	vlc = &intra_mean_table_2[(bit_cache >> (32 - 14)) - 1];

      else

	vlc = &intra_mean_table_3[bit_cache >> (32 - 20)];

    } else {

      if (bit_cache >= 0x0B000000)

	vlc = &inter_mean_table_0[(bit_cache >> (32 - 8)) - 11];

      else if (bit_cache >= 0x01200000)

	vlc = &inter_mean_table_1[(bit_cache >> (32 - 12)) - 18];

      else if (bit_cache >= 0x002E0000)

	vlc = &inter_mean_table_2[(bit_cache >> (32 - 15)) - 23];

      else if (bit_cache >= 0x00094000)

	vlc = &inter_mean_table_3[(bit_cache >> (32 - 18)) - 37];

      else if (bit_cache >= 0x00049000)

	vlc = &inter_mean_table_4[(bit_cache >> (32 - 20)) - 73];

      else

	vlc = &inter_mean_table_5[bit_cache >> (32 - 22)];

    }

    /* flush bits */

    mean	    = vlc->value;

    skip_bits(bitbuf,vlc->length);

    if (intra && stages == 0) {

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

	memset (&dst[y*(pitch / 4)], mean, width);

      }

    } else {

      codebook = (uint32_t *) (intra ? intra_codebooks[level] : inter_codebooks[level]);

      bit_cache = get_bits (bitbuf, 4*stages);

      /* calculate codebook entries for this vector */

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

	entries[j] = (((bit_cache >> (4*(stages - j - 1))) & 0xF) + 16*j) << (level + 1);

      }

      mean -= (stages * 128);

      n4    = ((mean + (mean >> 31)) << 16) | (mean & 0xFFFF);

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

	for (x=0; x < (width / 4); x++, codebook++) {

	  if (intra) {

	    n1 = n4;

	    n2 = n4;

	  } else {

	    n3 = dst[x];

	    /* add mean value to vector */

	    n1 = ((n3 & 0xFF00FF00) >> 8) + n4;

	    n2 =  (n3 & 0x00FF00FF)	  + n4;

	  }

	  /* add codebook entries to vector */

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

	    n3  = codebook[entries[j]] ^ 0x80808080;

	    n1 += ((n3 & 0xFF00FF00) >> 8);

	    n2 +=  (n3 & 0x00FF00FF);

	  }

	  /* clip to [0..255] */

	  if (n1 & 0xFF00FF00) {

	    n3  = ((( n1 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;

	    n1 += 0x7F007F00;

	    n1 |= (((~n1 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;

	    n1 &= (n3 & 0x00FF00FF);

	  }

	  if (n2 & 0xFF00FF00) {

	    n3  = ((( n2 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;

	    n2 += 0x7F007F00;

	    n2 |= (((~n2 >> 15) & 0x00010001) | 0x01000100) - 0x00010001;

	    n2 &= (n3 & 0x00FF00FF);

	  }

	  /* store result */

	  dst[x] = (n1 << 8) | n2;

        }

        dst += (pitch / 4);

      }

    }

  }

  return 0;

}


static int mov_init(AVFormatContext *s)

{

    MOVMuxContext *mov = s->priv_data;

    AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);

    int i, ret;

    mov->fc = s;

    /* Default mode == MP4 */

    mov->mode = MODE_MP4;

    if (s->oformat) {

        if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;

        else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;

        else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;

        else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;

        else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;

        else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;

        else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;

    }

    if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)

        mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;

    /* Set the FRAGMENT flag if any of the fragmentation methods are

     * enabled. */

    if (mov->max_fragment_duration || mov->max_fragment_size ||

        mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |

                      FF_MOV_FLAG_FRAG_KEYFRAME |

                      FF_MOV_FLAG_FRAG_CUSTOM))

        mov->flags |= FF_MOV_FLAG_FRAGMENT;

    /* Set other implicit flags immediately */

    if (mov->mode == MODE_ISM)

        mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |

                      FF_MOV_FLAG_FRAGMENT;

    if (mov->flags & FF_MOV_FLAG_DASH)

        mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |

                      FF_MOV_FLAG_DEFAULT_BASE_MOOF;

    if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {

        av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");

        s->flags &= ~AVFMT_FLAG_AUTO_BSF;

    }

    if (mov->flags & FF_MOV_FLAG_FASTSTART) {

        mov->reserved_moov_size = -1;

    }

    if (mov->use_editlist < 0) {

        mov->use_editlist = 1;

        if (mov->flags & FF_MOV_FLAG_FRAGMENT &&

            !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {

            // If we can avoid needing an edit list by shifting the

            // tracks, prefer that over (trying to) write edit lists

            // in fragmented output.

            if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||

                s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)

                mov->use_editlist = 0;

        }

    }

    if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&

        !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)

        av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");

    if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)

        s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;

    /* Clear the omit_tfhd_offset flag if default_base_moof is set;

     * if the latter is set that's enough and omit_tfhd_offset doesn't

     * add anything extra on top of that. */

    if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&

        mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)

        mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;

    if (mov->frag_interleave &&

        mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {

        av_log(s, AV_LOG_ERROR,

               "Sample interleaving in fragments is mutually exclusive with "

               "omit_tfhd_offset and separate_moof\n");

        return AVERROR(EINVAL);

    }

    /* Non-seekable output is ok if using fragmentation. If ism_lookahead

     * is enabled, we don't support non-seekable output at all. */

    if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&

        (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {

        av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");

        return AVERROR(EINVAL);

    }

    mov->nb_streams = s->nb_streams;

    if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)

        mov->chapter_track = mov->nb_streams++;

    if (mov->flags & FF_MOV_FLAG_RTP_HINT) {

        /* Add hint tracks for each audio and video stream */

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

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

            if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||

                st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

                mov->nb_streams++;

            }

        }

    }

    if (   mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)

        || mov->write_tmcd == 1) {

        /* +1 tmcd track for each video stream with a timecode */

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

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

            AVDictionaryEntry *t = global_tcr;

            if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&

                (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {

                AVTimecode tc;

                ret = mov_check_timecode_track(s, &tc, i, t->value);

                if (ret >= 0)

                    mov->nb_meta_tmcd++;

            }

        }

        /* check if there is already a tmcd track to remux */

        if (mov->nb_meta_tmcd) {

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

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

                if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {

                    av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "

                           "so timecode metadata are now ignored\n");

                    mov->nb_meta_tmcd = 0;

                }

            }

        }

        mov->nb_streams += mov->nb_meta_tmcd;

    }

    // Reserve an extra stream for chapters for the case where chapters

    // are written in the trailer

    mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));

    if (!mov->tracks)

        return AVERROR(ENOMEM);

    if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {

        if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {

            mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;

            if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {

                av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",

                    mov->encryption_key_len, AES_CTR_KEY_SIZE);

                return AVERROR(EINVAL);

            }

            if (mov->encryption_kid_len != CENC_KID_SIZE) {

                av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",

                    mov->encryption_kid_len, CENC_KID_SIZE);

                return AVERROR(EINVAL);

            }

        } else {

            av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",

                mov->encryption_scheme_str);

            return AVERROR(EINVAL);

        }

    }

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

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

        MOVTrack *track= &mov->tracks[i];

        AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);

        track->st  = st;

        track->par = st->codecpar;

        track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);

        if (track->language < 0)

            track->language = 0;

        track->mode = mov->mode;

        track->tag  = mov_find_codec_tag(s, track);

        if (!track->tag) {

            av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "

                   "codec not currently supported in container\n",

                   avcodec_get_name(st->codecpar->codec_id), i);

            return AVERROR(EINVAL);

        }

        /* If hinting of this track is enabled by a later hint track,

         * this is updated. */

        track->hint_track = -1;

        track->start_dts  = AV_NOPTS_VALUE;

        track->start_cts  = AV_NOPTS_VALUE;

        track->end_pts    = AV_NOPTS_VALUE;

        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

            if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||

                track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||

                track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {

                if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {

                    av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");

                    return AVERROR(EINVAL);

                }

                track->height = track->tag >> 24 == 'n' ? 486 : 576;

            }

            if (mov->video_track_timescale) {

                track->timescale = mov->video_track_timescale;

            } else {

                track->timescale = st->time_base.den;

                while(track->timescale < 10000)

                    track->timescale *= 2;

            }

            if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {

                av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);

                return AVERROR(EINVAL);

            }

            if (track->mode == MODE_MOV && track->timescale > 100000)

                av_log(s, AV_LOG_WARNING,

                       "WARNING codec timebase is very high. If duration is too long,\n"

                       "file may not be playable by quicktime. Specify a shorter timebase\n"

                       "or choose different container.\n");

            if (track->mode == MODE_MOV &&

                track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&

                track->tag == MKTAG('r','a','w',' ')) {

                enum AVPixelFormat pix_fmt = track->par->format;

                if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)

                    pix_fmt = AV_PIX_FMT_MONOWHITE;

                track->is_unaligned_qt_rgb =

                        pix_fmt == AV_PIX_FMT_RGB24 ||

                        pix_fmt == AV_PIX_FMT_BGR24 ||

                        pix_fmt == AV_PIX_FMT_PAL8 ||

                        pix_fmt == AV_PIX_FMT_GRAY8 ||

                        pix_fmt == AV_PIX_FMT_MONOWHITE ||

                        pix_fmt == AV_PIX_FMT_MONOBLACK;

            }

            if (track->par->codec_id == AV_CODEC_ID_VP9) {

                if (track->mode != MODE_MP4) {

                    av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");

                    return AVERROR(EINVAL);

                }

                if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

                    av_log(s, AV_LOG_ERROR,

                           "VP9 in MP4 support is experimental, add "

                           "'-strict %d' if you want to use it.\n",

                           FF_COMPLIANCE_EXPERIMENTAL);

                    return AVERROR_EXPERIMENTAL;

                }

            }

        } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            track->timescale = st->codecpar->sample_rate;

            if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {

                av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);

                track->audio_vbr = 1;

            }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||

                     st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||

                     st->codecpar->codec_id == AV_CODEC_ID_ILBC){

                if (!st->codecpar->block_align) {

                    av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);

                    return AVERROR(EINVAL);

                }

                track->sample_size = st->codecpar->block_align;

            }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */

                track->audio_vbr = 1;

            }else{

                track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;

            }

            if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||

                st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {

                track->audio_vbr = 1;

            }

            if (track->mode != MODE_MOV &&

                track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {

                if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {

                    av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",

                        i, track->par->sample_rate);

                    return AVERROR(EINVAL);

                } else {

                    av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",

                           i, track->par->sample_rate);

                }

            }

            if (track->par->codec_id == AV_CODEC_ID_FLAC ||

                track->par->codec_id == AV_CODEC_ID_OPUS) {

                if (track->mode != MODE_MP4) {

                    av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));

                    return AVERROR(EINVAL);

                }

                if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

                    av_log(s, AV_LOG_ERROR,

                           "%s in MP4 support is experimental, add "

                           "'-strict %d' if you want to use it.\n",

                           avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);

                    return AVERROR_EXPERIMENTAL;

                }

            }

        } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {

            track->timescale = st->time_base.den;

        } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {

            track->timescale = st->time_base.den;

        } else {

            track->timescale = MOV_TIMESCALE;

        }

        if (!track->height)

            track->height = st->codecpar->height;

        /* The ism specific timescale isn't mandatory, but is assumed by

         * some tools, such as mp4split. */

        if (mov->mode == MODE_ISM)

            track->timescale = 10000000;

        avpriv_set_pts_info(st, 64, 1, track->timescale);

        if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {

            ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,

                track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);

            if (ret)

                return ret;

        }

    }

    enable_tracks(s);

    return 0;

}


static GThread *trace_thread_create(GThreadFunc fn)

{

    GThread *thread;

#ifndef _WIN32

    sigset_t set, oldset;

    sigfillset(&set);

    pthread_sigmask(SIG_SETMASK, &set, &oldset);

#endif

    thread = g_thread_create(writeout_thread, NULL, FALSE, NULL);

#ifndef _WIN32

    pthread_sigmask(SIG_SETMASK, &oldset, NULL);

#endif

    return thread;

}


static void visit_type_TestStruct(Visitor *v, TestStruct **obj,

                                  const char *name, Error **errp)

{

    Error *err = NULL;

    visit_start_struct(v, (void **)obj, "TestStruct", name, sizeof(TestStruct),

                       &err);

    if (err) {

        goto out;

    }

    visit_type_int(v, &(*obj)->integer, "integer", &err);

    visit_type_bool(v, &(*obj)->boolean, "boolean", &err);

    visit_type_str(v, &(*obj)->string, "string", &err);

    visit_end_struct(v, &err);

out:

    error_propagate(errp, err);

}


static float get_band_cost_ZERO_mips(struct AACEncContext *s,

                                     PutBitContext *pb, const float *in,

                                     const float *scaled, int size, int scale_idx,

                                     int cb, const float lambda, const float uplim,

                                     int *bits)

{

    int i;

    float cost = 0;

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

        cost += in[i  ] * in[i  ];

        cost += in[i+1] * in[i+1];

        cost += in[i+2] * in[i+2];

        cost += in[i+3] * in[i+3];

    }

    if (bits)

        *bits = 0;

    return cost * lambda;

}


static int decode_thread(void *arg)

{

    VideoState *is = arg;

    AVFormatContext *ic;

    int err, i, ret;

    int st_index[AVMEDIA_TYPE_NB];

    AVPacket pkt1, *pkt = &pkt1;

    AVFormatParameters params, *ap = &params;

    int eof=0;

    int pkt_in_play_range = 0;

    ic = avformat_alloc_context();

    memset(st_index, -1, sizeof(st_index));

    is->video_stream = -1;

    is->audio_stream = -1;

    is->subtitle_stream = -1;

    global_video_state = is;

    url_set_interrupt_cb(decode_interrupt_cb);

    memset(ap, 0, sizeof(*ap));

    ap->prealloced_context = 1;

    ap->width = frame_width;

    ap->height= frame_height;

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

    ap->pix_fmt = frame_pix_fmt;

    set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);

    err = av_open_input_file(&ic, is->filename, is->iformat, 0, ap);

    if (err < 0) {

        print_error(is->filename, err);

        ret = -1;

        goto fail;

    }

    is->ic = ic;

    if(genpts)

        ic->flags |= AVFMT_FLAG_GENPTS;

    err = av_find_stream_info(ic);

    if (err < 0) {

        fprintf(stderr, "%s: could not find codec parameters\n", is->filename);

        ret = -1;

        goto fail;

    }

    if(ic->pb)

        ic->pb->eof_reached= 0; //FIXME hack, ffplay maybe should not use url_feof() to test for the end

    if(seek_by_bytes<0)

        seek_by_bytes= !!(ic->iformat->flags & AVFMT_TS_DISCONT);

    /* if seeking requested, we execute it */

    if (start_time != AV_NOPTS_VALUE) {

        int64_t timestamp;

        timestamp = start_time;

        /* add the stream start time */

        if (ic->start_time != AV_NOPTS_VALUE)

            timestamp += ic->start_time;

        ret = avformat_seek_file(ic, -1, INT64_MIN, timestamp, INT64_MAX, 0);

        if (ret < 0) {

            fprintf(stderr, "%s: could not seek to position %0.3f\n",

                    is->filename, (double)timestamp / AV_TIME_BASE);

        }

    }

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

        ic->streams[i]->discard = AVDISCARD_ALL;

    if (!video_disable)

        st_index[AVMEDIA_TYPE_VIDEO] =

            av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO,

                                wanted_stream[AVMEDIA_TYPE_VIDEO], -1, NULL, 0);

    if (!audio_disable)

        st_index[AVMEDIA_TYPE_AUDIO] =

            av_find_best_stream(ic, AVMEDIA_TYPE_AUDIO,

                                wanted_stream[AVMEDIA_TYPE_AUDIO],

                                st_index[AVMEDIA_TYPE_VIDEO],

                                NULL, 0);

    if (!video_disable)

        st_index[AVMEDIA_TYPE_SUBTITLE] =

            av_find_best_stream(ic, AVMEDIA_TYPE_SUBTITLE,

                                wanted_stream[AVMEDIA_TYPE_SUBTITLE],

                                (st_index[AVMEDIA_TYPE_AUDIO] >= 0 ?

                                 st_index[AVMEDIA_TYPE_AUDIO] :

                                 st_index[AVMEDIA_TYPE_VIDEO]),

                                NULL, 0);

    if (show_status) {

        av_dump_format(ic, 0, is->filename, 0);

    }

    /* open the streams */

    if (st_index[AVMEDIA_TYPE_AUDIO] >= 0) {

        stream_component_open(is, st_index[AVMEDIA_TYPE_AUDIO]);

    }

    ret=-1;

    if (st_index[AVMEDIA_TYPE_VIDEO] >= 0) {

        ret= stream_component_open(is, st_index[AVMEDIA_TYPE_VIDEO]);

    }

    is->refresh_tid = SDL_CreateThread(refresh_thread, is);

    if(ret<0) {

        if (!display_disable)

            is->show_audio = 2;

    }

    if (st_index[AVMEDIA_TYPE_SUBTITLE] >= 0) {

        stream_component_open(is, st_index[AVMEDIA_TYPE_SUBTITLE]);

    }

    if (is->video_stream < 0 && is->audio_stream < 0) {

        fprintf(stderr, "%s: could not open codecs\n", is->filename);

        ret = -1;

        goto fail;

    }

    for(;;) {

        if (is->abort_request)

            break;

        if (is->paused != is->last_paused) {

            is->last_paused = is->paused;

            if (is->paused)

                is->read_pause_return= av_read_pause(ic);

            else

                av_read_play(ic);

        }

#if CONFIG_RTSP_DEMUXER

        if (is->paused && !strcmp(ic->iformat->name, "rtsp")) {

            /* wait 10 ms to avoid trying to get another packet */

            /* XXX: horrible */

            SDL_Delay(10);

            continue;

        }

#endif

        if (is->seek_req) {

            int64_t seek_target= is->seek_pos;

            int64_t seek_min= is->seek_rel > 0 ? seek_target - is->seek_rel + 2: INT64_MIN;

            int64_t seek_max= is->seek_rel < 0 ? seek_target - is->seek_rel - 2: INT64_MAX;

//FIXME the +-2 is due to rounding being not done in the correct direction in generation

//      of the seek_pos/seek_rel variables

            ret = avformat_seek_file(is->ic, -1, seek_min, seek_target, seek_max, is->seek_flags);

            if (ret < 0) {

                fprintf(stderr, "%s: error while seeking\n", is->ic->filename);

            }else{

                if (is->audio_stream >= 0) {

                    packet_queue_flush(&is->audioq);

                    packet_queue_put(&is->audioq, &flush_pkt);

                }

                if (is->subtitle_stream >= 0) {

                    packet_queue_flush(&is->subtitleq);

                    packet_queue_put(&is->subtitleq, &flush_pkt);

                }

                if (is->video_stream >= 0) {

                    packet_queue_flush(&is->videoq);

                    packet_queue_put(&is->videoq, &flush_pkt);

                }

            }

            is->seek_req = 0;

            eof= 0;

        }

        /* if the queue are full, no need to read more */

        if (   is->audioq.size + is->videoq.size + is->subtitleq.size > MAX_QUEUE_SIZE

            || (   (is->audioq   .size  > MIN_AUDIOQ_SIZE || is->audio_stream<0)

                && (is->videoq   .nb_packets > MIN_FRAMES || is->video_stream<0)

                && (is->subtitleq.nb_packets > MIN_FRAMES || is->subtitle_stream<0))) {

            /* wait 10 ms */

            SDL_Delay(10);

            continue;

        }

        if(eof) {

            if(is->video_stream >= 0){

                av_init_packet(pkt);

                pkt->data=NULL;

                pkt->size=0;

                pkt->stream_index= is->video_stream;

                packet_queue_put(&is->videoq, pkt);

            }

            SDL_Delay(10);

            if(is->audioq.size + is->videoq.size + is->subtitleq.size ==0){

                if(loop!=1 && (!loop || --loop)){

                    stream_seek(cur_stream, start_time != AV_NOPTS_VALUE ? start_time : 0, 0, 0);

                }else if(autoexit){

                    ret=AVERROR_EOF;

                    goto fail;

                }

            }

            continue;

        }

        ret = av_read_frame(ic, pkt);

        if (ret < 0) {

            if (ret == AVERROR_EOF || ic->pb->eof_reached)

                eof=1;

            if (ic->pb->error)

                break;

            SDL_Delay(100); /* wait for user event */

            continue;

        }

        /* check if packet is in play range specified by user, then queue, otherwise discard */

        pkt_in_play_range = duration == AV_NOPTS_VALUE ||

                (pkt->pts - ic->streams[pkt->stream_index]->start_time) *

                av_q2d(ic->streams[pkt->stream_index]->time_base) -

                (double)(start_time != AV_NOPTS_VALUE ? start_time : 0)/1000000

                <= ((double)duration/1000000);

        if (pkt->stream_index == is->audio_stream && pkt_in_play_range) {

            packet_queue_put(&is->audioq, pkt);

        } else if (pkt->stream_index == is->video_stream && pkt_in_play_range) {

            packet_queue_put(&is->videoq, pkt);

        } else if (pkt->stream_index == is->subtitle_stream && pkt_in_play_range) {

            packet_queue_put(&is->subtitleq, pkt);

        } else {

            av_free_packet(pkt);

        }

    }

    /* wait until the end */

    while (!is->abort_request) {

        SDL_Delay(100);

    }

    ret = 0;

 fail:

    /* disable interrupting */

    global_video_state = NULL;

    /* close each stream */

    if (is->audio_stream >= 0)

        stream_component_close(is, is->audio_stream);

    if (is->video_stream >= 0)

        stream_component_close(is, is->video_stream);

    if (is->subtitle_stream >= 0)

        stream_component_close(is, is->subtitle_stream);

    if (is->ic) {

        av_close_input_file(is->ic);

        is->ic = NULL; /* safety */

    }

    url_set_interrupt_cb(NULL);

    if (ret != 0) {

        SDL_Event event;

        event.type = FF_QUIT_EVENT;

        event.user.data1 = is;

        SDL_PushEvent(&event);

    }

    return 0;

}


static int restore_sigcontext(CPUSH4State *regs, struct target_sigcontext *sc,

                              target_ulong *r0_p)

{

    unsigned int err = 0;

    int i;

#define COPY(x)         __get_user(regs->x, &sc->sc_##x)

    COPY(gregs[1]);

    COPY(gregs[2]); COPY(gregs[3]);

    COPY(gregs[4]); COPY(gregs[5]);

    COPY(gregs[6]); COPY(gregs[7]);

    COPY(gregs[8]); COPY(gregs[9]);

    COPY(gregs[10]); COPY(gregs[11]);

    COPY(gregs[12]); COPY(gregs[13]);

    COPY(gregs[14]); COPY(gregs[15]);

    COPY(gbr); COPY(mach);

    COPY(macl); COPY(pr);

    COPY(sr); COPY(pc);

#undef COPY

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

        __get_user(regs->fregs[i], &sc->sc_fpregs[i]);

    }

    __get_user(regs->fpscr, &sc->sc_fpscr);

    __get_user(regs->fpul, &sc->sc_fpul);

    regs->tra = -1;         /* disable syscall checks */

    __get_user(*r0_p, &sc->sc_gregs[0]);

    return err;

}


void do_rfi (void)

{

    env->nip = env->spr[SPR_SRR0] & ~0x00000003;

    T0 = env->spr[SPR_SRR1] & ~0xFFFF0000UL;

    do_store_msr(env, T0);

#if defined (DEBUG_OP)

    dump_rfi();

#endif

    env->interrupt_request |= CPU_INTERRUPT_EXITTB;

}


restore_sigcontext(CPUX86State *env, struct target_sigcontext *sc, int *peax)

{

	unsigned int err = 0;

        abi_ulong fpstate_addr;

        unsigned int tmpflags;

        cpu_x86_load_seg(env, R_GS, tswap16(sc->gs));

        cpu_x86_load_seg(env, R_FS, tswap16(sc->fs));

        cpu_x86_load_seg(env, R_ES, tswap16(sc->es));

        cpu_x86_load_seg(env, R_DS, tswap16(sc->ds));

        env->regs[R_EDI] = tswapl(sc->edi);

        env->regs[R_ESI] = tswapl(sc->esi);

        env->regs[R_EBP] = tswapl(sc->ebp);

        env->regs[R_ESP] = tswapl(sc->esp);

        env->regs[R_EBX] = tswapl(sc->ebx);

        env->regs[R_EDX] = tswapl(sc->edx);

        env->regs[R_ECX] = tswapl(sc->ecx);

        env->eip = tswapl(sc->eip);

        cpu_x86_load_seg(env, R_CS, lduw(&sc->cs) | 3);

        cpu_x86_load_seg(env, R_SS, lduw(&sc->ss) | 3);

        tmpflags = tswapl(sc->eflags);

        env->eflags = (env->eflags & ~0x40DD5) | (tmpflags & 0x40DD5);

        //		regs->orig_eax = -1;		/* disable syscall checks */

        fpstate_addr = tswapl(sc->fpstate);

	if (fpstate_addr != 0) {

                if (!access_ok(VERIFY_READ, fpstate_addr,

                               sizeof(struct target_fpstate)))

                        goto badframe;

                cpu_x86_frstor(env, fpstate_addr, 1);

	}

        *peax = tswapl(sc->eax);

	return err;

badframe:

	return 1;

}


static ssize_t local_readlink(FsContext *fs_ctx, V9fsPath *fs_path,

                              char *buf, size_t bufsz)

{

    ssize_t tsize = -1;

    char *buffer;

    char *path = fs_path->data;

    if ((fs_ctx->export_flags & V9FS_SM_MAPPED) ||

        (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE)) {

        int fd;

        buffer = rpath(fs_ctx, path);

        fd = open(buffer, O_RDONLY | O_NOFOLLOW);

        g_free(buffer);

        if (fd == -1) {

            return -1;

        }

        do {

            tsize = read(fd, (void *)buf, bufsz);

        } while (tsize == -1 && errno == EINTR);

        close(fd);

    } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||

               (fs_ctx->export_flags & V9FS_SM_NONE)) {

        buffer = rpath(fs_ctx, path);

        tsize = readlink(buffer, buf, bufsz);

        g_free(buffer);

    }

    return tsize;

}


static void htab_save_first_pass(QEMUFile *f, sPAPRMachineState *spapr,

                                 int64_t max_ns)

{

    bool has_timeout = max_ns != -1;

    int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;

    int index = spapr->htab_save_index;

    int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    assert(spapr->htab_first_pass);

    do {

        int chunkstart;

        /* Consume invalid HPTEs */

        while ((index < htabslots)

               && !HPTE_VALID(HPTE(spapr->htab, index))) {

            index++;

            CLEAN_HPTE(HPTE(spapr->htab, index));

        }

        /* Consume valid HPTEs */

        chunkstart = index;

        while ((index < htabslots) && (index - chunkstart < USHRT_MAX)

               && HPTE_VALID(HPTE(spapr->htab, index))) {

            index++;

            CLEAN_HPTE(HPTE(spapr->htab, index));

        }

        if (index > chunkstart) {

            int n_valid = index - chunkstart;

            qemu_put_be32(f, chunkstart);

            qemu_put_be16(f, n_valid);

            qemu_put_be16(f, 0);

            qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),

                            HASH_PTE_SIZE_64 * n_valid);

            if (has_timeout &&

                (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {

                break;

            }

        }

    } while ((index < htabslots) && !qemu_file_rate_limit(f));

    if (index >= htabslots) {

        assert(index == htabslots);

        index = 0;

        spapr->htab_first_pass = false;

    }

    spapr->htab_save_index = index;

}


void OPPROTO op_check_addo_64 (void)

{

    if (likely(!(((uint64_t)T2 ^ (uint64_t)T1 ^ UINT64_MAX) &

                 ((uint64_t)T2 ^ (uint64_t)T0) & (1ULL << 63)))) {

        xer_ov = 0;

    } else {

        xer_so = 1;

        xer_ov = 1;

    }

    RETURN();

}


static void vnc_dpy_resize(DisplayChangeListener *dcl,

                           DisplayState *ds)

{

    VncDisplay *vd = ds->opaque;

    VncState *vs;

    vnc_abort_display_jobs(vd);

    /* server surface */

    qemu_pixman_image_unref(vd->server);

    vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,

                                          ds_get_width(ds),

                                          ds_get_height(ds),

                                          NULL, 0);

    /* guest surface */

#if 0 /* FIXME */

    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)

        console_color_init(ds);

#endif

    qemu_pixman_image_unref(vd->guest.fb);

    vd->guest.fb = pixman_image_ref(ds->surface->image);

    vd->guest.format = ds->surface->format;

    memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));

    QTAILQ_FOREACH(vs, &vd->clients, next) {

        vnc_colordepth(vs);

        vnc_desktop_resize(vs);

        if (vs->vd->cursor) {

            vnc_cursor_define(vs);

        }

        memset(vs->dirty, 0xFF, sizeof(vs->dirty));

    }

}


void hbitmap_iter_init(HBitmapIter *hbi, const HBitmap *hb, uint64_t first)

{

    unsigned i, bit;

    uint64_t pos;

    hbi->hb = hb;

    pos = first >> hb->granularity;

    hbi->pos = pos >> BITS_PER_LEVEL;

    hbi->granularity = hb->granularity;

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

        bit = pos & (BITS_PER_LONG - 1);

        pos >>= BITS_PER_LEVEL;

        /* Drop bits representing items before first.  */

        hbi->cur[i] = hb->levels[i][pos] & ~((1UL << bit) - 1);

        /* We have already added level i+1, so the lowest set bit has

         * been processed.  Clear it.

         */

        if (i != HBITMAP_LEVELS - 1) {

            hbi->cur[i] &= ~(1UL << bit);

        }

    }

}


print_ipc_cmd(int cmd)

{

#define output_cmd(val) \

if( cmd == val ) { \

    gemu_log(#val); \

    return; \

}

    cmd &= 0xff;

    /* General IPC commands */

    output_cmd( IPC_RMID );

    output_cmd( IPC_SET );

    output_cmd( IPC_STAT );

    output_cmd( IPC_INFO );

    /* msgctl() commands */

    #ifdef __USER_MISC

    output_cmd( MSG_STAT );

    output_cmd( MSG_INFO );

    #endif

    /* shmctl() commands */

    output_cmd( SHM_LOCK );

    output_cmd( SHM_UNLOCK );

    output_cmd( SHM_STAT );

    output_cmd( SHM_INFO );

    /* semctl() commands */

    output_cmd( GETPID );

    output_cmd( GETVAL );

    output_cmd( GETALL );

    output_cmd( GETNCNT );

    output_cmd( GETZCNT );

    output_cmd( SETVAL );

    output_cmd( SETALL );

    output_cmd( SEM_STAT );

    output_cmd( SEM_INFO );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    output_cmd( IPC_RMID );

    /* Some value we don't recognize */

    gemu_log("%d",cmd);

}


static void extract_mpeg4_header(AVFormatContext *infile)

{

    int mpeg4_count, i, size;

    AVPacket pkt;

    AVStream *st;

    const uint8_t *p;

    mpeg4_count = 0;

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

        st = infile->streams[i];

        if (st->codec.codec_id == CODEC_ID_MPEG4 &&

            st->codec.extradata_size == 0) {

            mpeg4_count++;

        }

    }

    if (!mpeg4_count)

        return;

    printf("MPEG4 without extra data: trying to find header\n");

    while (mpeg4_count > 0) {

        if (av_read_packet(infile, &pkt) < 0)

            break;

        st = infile->streams[pkt.stream_index];

        if (st->codec.codec_id == CODEC_ID_MPEG4 &&

            st->codec.extradata_size == 0) {

            av_freep(&st->codec.extradata);

            /* fill extradata with the header */

            /* XXX: we make hard suppositions here ! */

            p = pkt.data;

            while (p < pkt.data + pkt.size - 4) {

                /* stop when vop header is found */

                if (p[0] == 0x00 && p[1] == 0x00 &&

                    p[2] == 0x01 && p[3] == 0xb6) {

                    size = p - pkt.data;

                    //                    av_hex_dump(pkt.data, size);

                    st->codec.extradata = av_malloc(size);

                    st->codec.extradata_size = size;

                    memcpy(st->codec.extradata, pkt.data, size);

                    break;

                }

                p++;

            }

            mpeg4_count--;

        }

        av_free_packet(&pkt);

    }

}


void avfilter_unref_buffer(AVFilterBufferRef *ref)

{

    if (!ref)

        return;

    av_assert0(ref->buf->refcount > 0);

    if (!(--ref->buf->refcount)) {

        if (!ref->buf->free) {

            store_in_pool(ref);

            return;

        }

        ref->buf->free(ref->buf);

    }

    if (ref->extended_data != ref->data)

        av_freep(&ref->extended_data);

    if (ref->video)

        av_freep(&ref->video->qp_table);

    av_freep(&ref->video);

    av_freep(&ref->audio);

    av_free(ref);

}


QmpInputVisitor *qmp_input_visitor_new(QObject *obj, bool strict)

{

    QmpInputVisitor *v;

    v = g_malloc0(sizeof(*v));

    v->visitor.type = VISITOR_INPUT;

    v->visitor.start_struct = qmp_input_start_struct;

    v->visitor.end_struct = qmp_input_end_struct;

    v->visitor.start_list = qmp_input_start_list;

    v->visitor.next_list = qmp_input_next_list;

    v->visitor.end_list = qmp_input_end_list;

    v->visitor.start_alternate = qmp_input_start_alternate;

    v->visitor.type_int64 = qmp_input_type_int64;

    v->visitor.type_uint64 = qmp_input_type_uint64;

    v->visitor.type_bool = qmp_input_type_bool;

    v->visitor.type_str = qmp_input_type_str;

    v->visitor.type_number = qmp_input_type_number;

    v->visitor.type_any = qmp_input_type_any;

    v->visitor.type_null = qmp_input_type_null;

    v->visitor.optional = qmp_input_optional;

    v->strict = strict;

    v->root = obj;

    qobject_incref(obj);

    return v;

}


static void imx_eth_enable_rx(IMXFECState *s)

{

    IMXFECBufDesc bd;

    bool rx_ring_full;

    imx_fec_read_bd(&bd, s->rx_descriptor);

    rx_ring_full = !(bd.flags & ENET_BD_E);

    if (rx_ring_full) {

        FEC_PRINTF("RX buffer full\n");

    } else if (!s->regs[ENET_RDAR]) {

        qemu_flush_queued_packets(qemu_get_queue(s->nic));

    }

    s->regs[ENET_RDAR] = rx_ring_full ? 0 : ENET_RDAR_RDAR;

}


static inline void FUNC(idctSparseColAdd)(pixel *dest, int line_size,

                                          DCTELEM *col)

{

    int a0, a1, a2, a3, b0, b1, b2, b3;

    INIT_CLIP;

    IDCT_COLS;

    dest[0] = CLIP(dest[0] + ((a0 + b0) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a1 + b1) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a2 + b2) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a3 + b3) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a3 - b3) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a2 - b2) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a1 - b1) >> COL_SHIFT));

    dest += line_size;

    dest[0] = CLIP(dest[0] + ((a0 - b0) >> COL_SHIFT));

}


static int bfi_read_packet(AVFormatContext * s, AVPacket * pkt)

{

    BFIContext *bfi = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret, audio_offset, video_offset, chunk_size, audio_size = 0;

    if (bfi->nframes == 0 || pb->eof_reached) {

        return AVERROR(EIO);

    /* If all previous chunks were completely read, then find a new one... */

    if (!bfi->avflag) {

        uint32_t state = 0;

        while(state != MKTAG('S','A','V','I')){

            if (pb->eof_reached)

                return AVERROR(EIO);

            state = 256*state + avio_r8(pb);

        /* Now that the chunk's location is confirmed, we proceed... */

        chunk_size      = avio_rl32(pb);

        avio_rl32(pb);

        audio_offset    = avio_rl32(pb);

        avio_rl32(pb);

        video_offset    = avio_rl32(pb);

        audio_size      = video_offset - audio_offset;

        bfi->video_size = chunk_size - video_offset;

        //Tossing an audio packet at the audio decoder.

        ret = av_get_packet(pb, pkt, audio_size);

        if (ret < 0)

            return ret;

        pkt->pts          = bfi->audio_frame;

        bfi->audio_frame += ret;

    } else if (bfi->video_size > 0) {

        //Tossing a video packet at the video decoder.

        ret = av_get_packet(pb, pkt, bfi->video_size);

        if (ret < 0)

            return ret;

        pkt->pts          = bfi->video_frame;

        bfi->video_frame += ret / bfi->video_size;

        /* One less frame to read. A cursory decrement. */

        bfi->nframes--;

    } else {

        /* Empty video packet */

        ret = AVERROR(EAGAIN);

    bfi->avflag       = !bfi->avflag;

    pkt->stream_index = bfi->avflag;

    return ret;


static int mpc7_decode_frame(AVCodecContext * avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MPCContext *c = avctx->priv_data;

    GetBitContext gb;

    uint8_t *bits;

    int i, ch, t;

    int mb = -1;

    Band *bands = c->bands;

    int off;

    int bits_used, bits_avail;

    memset(bands, 0, sizeof(bands));

    if(buf_size <= 4){

        av_log(avctx, AV_LOG_ERROR, "Too small buffer passed (%i bytes)\n", buf_size);

    }

    bits = av_malloc(((buf_size - 1) & ~3) + FF_INPUT_BUFFER_PADDING_SIZE);

    c->dsp.bswap_buf((uint32_t*)bits, (const uint32_t*)(buf + 4), (buf_size - 4) >> 2);

    init_get_bits(&gb, bits, (buf_size - 4)* 8);

    skip_bits(&gb, buf[0]);

    /* read subband indexes */

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

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

            if(i) t = get_vlc2(&gb, hdr_vlc.table, MPC7_HDR_BITS, 1) - 5;

            if(!i || (t == 4)) bands[i].res[ch] = get_bits(&gb, 4);

            else bands[i].res[ch] = bands[i-1].res[ch] + t;

        }

        if(bands[i].res[0] || bands[i].res[1]){

            mb = i;

            if(c->MSS) bands[i].msf = get_bits1(&gb);

        }

    }

    /* get scale indexes coding method */

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

        for(ch = 0; ch < 2; ch++)

            if(bands[i].res[ch]) bands[i].scfi[ch] = get_vlc2(&gb, scfi_vlc.table, MPC7_SCFI_BITS, 1);

    /* get scale indexes */

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

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

            if(bands[i].res[ch]){

                bands[i].scf_idx[ch][2] = c->oldDSCF[ch][i];

                bands[i].scf_idx[ch][0] = get_scale_idx(&gb, bands[i].scf_idx[ch][2]);

                switch(bands[i].scfi[ch]){

                case 0:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 1:

                    bands[i].scf_idx[ch][1] = get_scale_idx(&gb, bands[i].scf_idx[ch][0]);

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1];

                    break;

                case 2:

                    bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    bands[i].scf_idx[ch][2] = get_scale_idx(&gb, bands[i].scf_idx[ch][1]);

                    break;

                case 3:

                    bands[i].scf_idx[ch][2] = bands[i].scf_idx[ch][1] = bands[i].scf_idx[ch][0];

                    break;

                }

                c->oldDSCF[ch][i] = bands[i].scf_idx[ch][2];

            }

        }

    }

    /* get quantizers */

    memset(c->Q, 0, sizeof(c->Q));

    off = 0;

    for(i = 0; i < BANDS; i++, off += SAMPLES_PER_BAND)

        for(ch = 0; ch < 2; ch++)

            idx_to_quant(c, &gb, bands[i].res[ch], c->Q[ch] + off);

    ff_mpc_dequantize_and_synth(c, mb, data);

    av_free(bits);

    bits_used = get_bits_count(&gb);

    bits_avail = (buf_size - 4) * 8;

    if(!buf[1] && ((bits_avail < bits_used) || (bits_used + 32 <= bits_avail))){

        av_log(NULL,0, "Error decoding frame: used %i of %i bits\n", bits_used, bits_avail);

        return -1;

    }

    if(c->frames_to_skip){

        c->frames_to_skip--;

        *data_size = 0;

        return buf_size;

    }

    *data_size = (buf[1] ? c->lastframelen : MPC_FRAME_SIZE) * 4;

    return buf_size;

}


static void qpeg_decode_intra(uint8_t *src, uint8_t *dst, int size,

			    int stride, int width, int height)

{

    int i;

    int code;

    int c0, c1;

    int run, copy;

    int filled = 0;

    height--;

    dst = dst + height * stride;

    while(size > 0) {

	code = *src++;

	size--;

	run = copy = 0;

	if(code == 0xFC) /* end-of-picture code */

	    break;

	if(code >= 0xF8) { /* very long run */

	    c0 = *src++;

	    c1 = *src++;

	    size -= 2;

	    run = ((code & 0x7) << 16) + (c0 << 8) + c1 + 2;

	} else if (code >= 0xF0) { /* long run */

	    c0 = *src++;

	    size--;

	    run = ((code & 0xF) << 8) + c0 + 2;

	} else if (code >= 0xE0) { /* short run */

	    run = (code & 0x1F) + 2;

	} else if (code >= 0xC0) { /* very long copy */

	    c0 = *src++;

	    c1 = *src++;

	    size -= 2;

	    copy = ((code & 0x3F) << 16) + (c0 << 8) + c1 + 1;

	} else if (code >= 0x80) { /* long copy */

	    c0 = *src++;

	    size--;

	    copy = ((code & 0x7F) << 8) + c0 + 1;

	} else { /* short copy */

	    copy = code + 1;

	}

	/* perform actual run or copy */

	if(run) {

	    int p;

	    p = *src++;

	    size--;

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

		dst[filled++] = p;

		if (filled >= width) {

		    filled = 0;

		    dst -= stride;

		}

	    }

	} else {

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

		dst[filled++] = *src++;

		if (filled >= width) {

		    filled = 0;

		    dst -= stride;

		}

	    }

	    size -= copy;

	}

    }

}


static void usb_mtp_handle_reset(USBDevice *dev)

{

    MTPState *s = USB_MTP(dev);

    trace_usb_mtp_reset(s->dev.addr);

#ifdef __linux__

    usb_mtp_inotify_cleanup(s);

#endif

    usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));

    s->session = 0;

    usb_mtp_data_free(s->data_in);

    s->data_in = NULL;

    usb_mtp_data_free(s->data_out);

    s->data_out = NULL;

    g_free(s->result);

    s->result = NULL;

}


int vfio_region_mmap(VFIORegion *region)

{

    int i, prot = 0;

    char *name;

    if (!region->mem) {

        return 0;

    }

    prot |= region->flags & VFIO_REGION_INFO_FLAG_READ ? PROT_READ : 0;

    prot |= region->flags & VFIO_REGION_INFO_FLAG_WRITE ? PROT_WRITE : 0;

    for (i = 0; i < region->nr_mmaps; i++) {

        region->mmaps[i].mmap = mmap(NULL, region->mmaps[i].size, prot,

                                     MAP_SHARED, region->vbasedev->fd,

                                     region->fd_offset +

                                     region->mmaps[i].offset);

        if (region->mmaps[i].mmap == MAP_FAILED) {

            int ret = -errno;

            trace_vfio_region_mmap_fault(memory_region_name(region->mem), i,

                                         region->fd_offset +

                                         region->mmaps[i].offset,

                                         region->fd_offset +

                                         region->mmaps[i].offset +

                                         region->mmaps[i].size - 1, ret);

            region->mmaps[i].mmap = NULL;

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

                memory_region_del_subregion(region->mem, &region->mmaps[i].mem);

                munmap(region->mmaps[i].mmap, region->mmaps[i].size);

                object_unparent(OBJECT(&region->mmaps[i].mem));

                region->mmaps[i].mmap = NULL;

            }

            return ret;

        }

        name = g_strdup_printf("%s mmaps[%d]",

                               memory_region_name(region->mem), i);

        memory_region_init_ram_ptr(&region->mmaps[i].mem,

                                   memory_region_owner(region->mem),

                                   name, region->mmaps[i].size,

                                   region->mmaps[i].mmap);

        g_free(name);

        memory_region_set_skip_dump(&region->mmaps[i].mem);

        memory_region_add_subregion(region->mem, region->mmaps[i].offset,

                                    &region->mmaps[i].mem);

        trace_vfio_region_mmap(memory_region_name(&region->mmaps[i].mem),

                               region->mmaps[i].offset,

                               region->mmaps[i].offset +

                               region->mmaps[i].size - 1);

    }

    return 0;

}


float64 HELPER(ucf64_subd)(float64 a, float64 b, CPUUniCore32State *env)

{

    return float64_sub(a, b, &env->ucf64.fp_status);

}


static void text_console_do_init(CharDriverState *chr, DisplayState *ds)

{

    TextConsole *s;

    static int color_inited;

    s = chr->opaque;

    chr->chr_write = console_puts;

    chr->chr_send_event = console_send_event;

    s->out_fifo.buf = s->out_fifo_buf;

    s->out_fifo.buf_size = sizeof(s->out_fifo_buf);

    s->kbd_timer = qemu_new_timer(rt_clock, kbd_send_chars, s);

    s->ds = ds;

    if (!color_inited) {

        color_inited = 1;

        console_color_init(s->ds);

    }

    s->y_displayed = 0;

    s->y_base = 0;

    s->total_height = DEFAULT_BACKSCROLL;

    s->x = 0;

    s->y = 0;

    if (s->console_type == TEXT_CONSOLE) {

        s->g_width = ds_get_width(s->ds);

        s->g_height = ds_get_height(s->ds);

    }

    s->hw_invalidate = text_console_invalidate;

    s->hw_text_update = text_console_update;

    s->hw = s;

    /* Set text attribute defaults */

    s->t_attrib_default.bold = 0;

    s->t_attrib_default.uline = 0;

    s->t_attrib_default.blink = 0;

    s->t_attrib_default.invers = 0;

    s->t_attrib_default.unvisible = 0;

    s->t_attrib_default.fgcol = COLOR_WHITE;

    s->t_attrib_default.bgcol = COLOR_BLACK;

    /* set current text attributes to default */

    s->t_attrib = s->t_attrib_default;

    text_console_resize(s);

    if (chr->label) {

        char msg[128];

        int len;

        s->t_attrib.bgcol = COLOR_BLUE;

        len = snprintf(msg, sizeof(msg), "%s console\r\n", chr->label);

        console_puts(chr, (uint8_t*)msg, len);

        s->t_attrib = s->t_attrib_default;

    }

    qemu_chr_generic_open(chr);

    if (chr->init)

        chr->init(chr);

}


BlockDriverState *bdrv_find_node(const char *node_name)

{

    BlockDriverState *bs;

    assert(node_name);

    QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {

        if (!strcmp(node_name, bs->node_name)) {

            return bs;

        }

    }

    return NULL;

}


static inline void load_seg_vm(int seg, int selector)

{

    selector &= 0xffff;

    cpu_x86_load_seg_cache(env, seg, selector,

                           (uint8_t *)(selector << 4), 0xffff, 0);

}


static int ehci_state_fetchqtd(EHCIQueue *q, int async)

{

    int again = 0;

    get_dwords(NLPTR_GET(q->qtdaddr),(uint32_t *) &q->qtd, sizeof(EHCIqtd) >> 2);

    ehci_trace_qtd(q, NLPTR_GET(q->qtdaddr), &q->qtd);

    if (q->qtd.token & QTD_TOKEN_ACTIVE) {

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

        again = 1;

    } else {

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

        again = 1;

    }

    return again;

}


av_cold void ff_dnxhdenc_init_x86(DNXHDEncContext *ctx)

{

#if HAVE_SSE2_INLINE

    if (av_get_cpu_flags() & AV_CPU_FLAG_SSE2) {

        if (ctx->cid_table->bit_depth == 8)

            ctx->get_pixels_8x4_sym = get_pixels_8x4_sym_sse2;

    }

#endif /* HAVE_SSE2_INLINE */

}


static int usb_bt_initfn(USBDevice *dev)

{

    struct USBBtState *s = DO_UPCAST(struct USBBtState, dev, dev);

    s->dev.speed = USB_SPEED_HIGH;

    return 0;

}


static void ppc_hash64_set_dsi(CPUState *cs, CPUPPCState *env, uint64_t dar,

                               uint64_t dsisr)

{

    bool vpm;

    if (msr_dr) {

        vpm = !!(env->spr[SPR_LPCR] & LPCR_VPM1);

    } else {

        vpm = !!(env->spr[SPR_LPCR] & LPCR_VPM0);

    }

    if (vpm && !msr_hv) {

        cs->exception_index = POWERPC_EXCP_HDSI;

        env->spr[SPR_HDAR] = dar;

        env->spr[SPR_HDSISR] = dsisr;

    } else {

        cs->exception_index = POWERPC_EXCP_DSI;

        env->spr[SPR_DAR] = dar;

        env->spr[SPR_DSISR] = dsisr;

   }

    env->error_code = 0;

}


static void cpu_ppc_decr_cb(void *opaque)

{

    PowerPCCPU *cpu = opaque;

    _cpu_ppc_store_decr(cpu, 0x00000000, 0xFFFFFFFF, 1);

}


static int vmdk_open_vmdk3(BlockDriverState *bs,

                           BlockDriverState *file,

                           int flags)

{

    int ret;

    uint32_t magic;

    VMDK3Header header;

    VmdkExtent *extent;

    ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));

    if (ret < 0) {

        return ret;

    }

    extent = vmdk_add_extent(bs,

                             bs->file, false,

                             le32_to_cpu(header.disk_sectors),

                             le32_to_cpu(header.l1dir_offset) << 9,

                             0, 1 << 6, 1 << 9,

                             le32_to_cpu(header.granularity));

    ret = vmdk_init_tables(bs, extent);

    if (ret) {

        /* free extent allocated by vmdk_add_extent */

        vmdk_free_last_extent(bs);

    }

    return ret;

}


static uint64_t mv88w8618_flashcfg_read(void *opaque,

                                        target_phys_addr_t offset,

                                        unsigned size)

{

    mv88w8618_flashcfg_state *s = opaque;

    switch (offset) {

    case MP_FLASHCFG_CFGR0:

        return s->cfgr0;

    default:

        return 0;

    }

}


static void qio_channel_socket_dgram_worker_free(gpointer opaque)

{

    struct QIOChannelSocketDGramWorkerData *data = opaque;

    qapi_free_SocketAddressLegacy(data->localAddr);

    qapi_free_SocketAddressLegacy(data->remoteAddr);

    g_free(data);

}


static QString *qstring_from_escaped_str(JSONParserContext *ctxt, QObject *token)

{

    const char *ptr = token_get_value(token);

    QString *str;

    int double_quote = 1;

    if (*ptr == '"') {

        double_quote = 1;

    } else {

        double_quote = 0;

    }

    ptr++;

    str = qstring_new();

    while (*ptr &&

           ((double_quote && *ptr != '"') || (!double_quote && *ptr != '\''))) {

        if (*ptr == '\\') {

            ptr++;

            switch (*ptr) {

            case '"':

                qstring_append(str, "\"");

                ptr++;

                break;

            case '\'':

                qstring_append(str, "'");

                ptr++;

                break;

            case '\\':

                qstring_append(str, "\\");

                ptr++;

                break;

            case '/':

                qstring_append(str, "/");

                ptr++;

                break;

            case 'b':

                qstring_append(str, "\b");

                ptr++;

                break;

            case 'f':

                qstring_append(str, "\f");

                ptr++;

                break;

            case 'n':

                qstring_append(str, "\n");

                ptr++;

                break;

            case 'r':

                qstring_append(str, "\r");

                ptr++;

                break;

            case 't':

                qstring_append(str, "\t");

                ptr++;

                break;

            case 'u': {

                uint16_t unicode_char = 0;

                char utf8_char[4];

                int i = 0;

                ptr++;

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

                    if (qemu_isxdigit(*ptr)) {

                        unicode_char |= hex2decimal(*ptr) << ((3 - i) * 4);

                    } else {

                        parse_error(ctxt, token,

                                    "invalid hex escape sequence in string");

                        goto out;

                    }

                    ptr++;

                }

                wchar_to_utf8(unicode_char, utf8_char, sizeof(utf8_char));

                qstring_append(str, utf8_char);

            }   break;

            default:

                parse_error(ctxt, token, "invalid escape sequence in string");

                goto out;

            }

        } else {

            char dummy[2];

            dummy[0] = *ptr++;

            dummy[1] = 0;

            qstring_append(str, dummy);

        }

    }

    return str;

out:

    QDECREF(str);

    return NULL;

}


static void init_types(void)

{

    static int inited;

    int i;

    if (inited) {

        return;

    }

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

        TAILQ_INIT(&init_type_list[i]);

    }

    inited = 1;

}


int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int n_start, int n_end, int *num, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret;

    uint64_t l2_offset, *l2_table;

    int64_t cluster_offset;

    unsigned int nb_clusters, i = 0;

    QCowL2Meta *old_alloc;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);

    if (ret < 0) {

        return ret;

    }

again:

    nb_clusters = size_to_clusters(s, n_end << 9);

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* We keep all QCOW_OFLAG_COPIED clusters */

    if (cluster_offset & QCOW_OFLAG_COPIED) {

        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0, 0);

        cluster_offset &= ~QCOW_OFLAG_COPIED;

        m->nb_clusters = 0;

        goto out;

    }

    /* for the moment, multiple compressed clusters are not managed */

    if (cluster_offset & QCOW_OFLAG_COMPRESSED)

        nb_clusters = 1;

    /* how many available clusters ? */

    while (i < nb_clusters) {

        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,

                &l2_table[l2_index], i, 0);

        if ((i >= nb_clusters) || be64_to_cpu(l2_table[l2_index + i])) {

            break;

        }

        i += count_contiguous_free_clusters(nb_clusters - i,

                &l2_table[l2_index + i]);

        if (i >= nb_clusters) {

            break;

        }

        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);

        if ((cluster_offset & QCOW_OFLAG_COPIED) ||

                (cluster_offset & QCOW_OFLAG_COMPRESSED))

            break;

    }

    assert(i <= nb_clusters);

    nb_clusters = i;

    /*

     * Check if there already is an AIO write request in flight which allocates

     * the same cluster. In this case we need to wait until the previous

     * request has completed and updated the L2 table accordingly.

     */

    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {

        uint64_t end_offset = offset + nb_clusters * s->cluster_size;

        uint64_t old_offset = old_alloc->offset;

        uint64_t old_end_offset = old_alloc->offset +

            old_alloc->nb_clusters * s->cluster_size;

        if (end_offset < old_offset || offset > old_end_offset) {

            /* No intersection */

        } else {

            if (offset < old_offset) {

                /* Stop at the start of a running allocation */

                nb_clusters = (old_offset - offset) >> s->cluster_bits;

            } else {

                nb_clusters = 0;

            }

            if (nb_clusters == 0) {

                /* Wait for the dependency to complete. We need to recheck

                 * the free/allocated clusters when we continue. */

                qemu_co_mutex_unlock(&s->lock);

                qemu_co_queue_wait(&old_alloc->dependent_requests);

                qemu_co_mutex_lock(&s->lock);

                goto again;

            }

        }

    }

    if (!nb_clusters) {

        abort();

    }

    QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);

    /* allocate a new cluster */

    cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);

    if (cluster_offset < 0) {

        ret = cluster_offset;

        goto fail;

    }

    /* save info needed for meta data update */

    m->offset = offset;

    m->n_start = n_start;

    m->nb_clusters = nb_clusters;

out:

    ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

    if (ret < 0) {

        goto fail_put;

    }

    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);

    m->cluster_offset = cluster_offset;

    *num = m->nb_available - n_start;

    return 0;

fail:

    qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

fail_put:

    QLIST_REMOVE(m, next_in_flight);

    return ret;

}


static void test_validate_union_native_list(TestInputVisitorData *data,

                                            const void *unused)

{

    UserDefNativeListUnion *tmp = NULL;

    Visitor *v;

    Error *err = NULL;

    v = validate_test_init(data, "{ 'type': 'integer', 'data' : [ 1, 2 ] }");

    visit_type_UserDefNativeListUnion(v, &tmp, NULL, &err);

    g_assert(!err);

    qapi_free_UserDefNativeListUnion(tmp);

}


static int delta_decode(uint8_t *dst, const uint8_t *src, int src_size,

                         unsigned val, const int8_t *table)

{

    uint8_t *dst0 = dst;

    while (src_size--) {

        uint8_t d = *src++;

        val = av_clip_uint8(val + table[d & 0xF]);

        *dst++ = val;

        val = av_clip_uint8(val + table[d >> 4]);

        *dst++ = val;

    }

    return dst-dst0;

}


int css_do_ssch(SubchDev *sch, ORB *orb)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    int ret;

    if (!(p->flags & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA))) {

        ret = -ENODEV;

        goto out;

    }

    if (s->ctrl & SCSW_STCTL_STATUS_PEND) {

        ret = -EINPROGRESS;

        goto out;

    }

    if (s->ctrl & (SCSW_FCTL_START_FUNC |

                   SCSW_FCTL_HALT_FUNC |

                   SCSW_FCTL_CLEAR_FUNC)) {

        ret = -EBUSY;

        goto out;

    }

    /* If monitoring is active, update counter. */

    if (channel_subsys.chnmon_active) {

        css_update_chnmon(sch);

    }

    sch->channel_prog = orb->cpa;

    /* Trigger the start function. */

    s->ctrl |= (SCSW_FCTL_START_FUNC | SCSW_ACTL_START_PEND);

    s->flags &= ~SCSW_FLAGS_MASK_PNO;

    do_subchannel_work(sch, orb);

    ret = 0;

out:

    return ret;

}


static void ehci_reset(void *opaque)

{

    EHCIState *s = opaque;

    int i;

    USBDevice *devs[NB_PORTS];

    trace_usb_ehci_reset();

    /*

     * Do the detach before touching portsc, so that it correctly gets send to

     * us or to our companion based on PORTSC_POWNER before the reset.

     */

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

        devs[i] = s->ports[i].dev;

        if (devs[i]) {

            usb_attach(&s->ports[i], NULL);

        }

    }

    memset(&s->mmio[OPREGBASE], 0x00, MMIO_SIZE - OPREGBASE);

    s->usbcmd = NB_MAXINTRATE << USBCMD_ITC_SH;

    s->usbsts = USBSTS_HALT;

    s->astate = EST_INACTIVE;

    s->pstate = EST_INACTIVE;

    s->isoch_pause = -1;

    s->attach_poll_counter = 0;

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

        if (s->companion_ports[i]) {

            s->portsc[i] = PORTSC_POWNER | PORTSC_PPOWER;

        } else {

            s->portsc[i] = PORTSC_PPOWER;

        }

        if (devs[i]) {

            usb_attach(&s->ports[i], devs[i]);

        }

    }

    ehci_queues_rip_all(s);

}


DISAS_INSN(divl)

{

    TCGv num;

    TCGv den;

    TCGv reg;

    uint16_t ext;

    ext = read_im16(env, s);

    if (ext & 0x87f8) {

        gen_exception(s, s->pc - 4, EXCP_UNSUPPORTED);

        return;

    }

    num = DREG(ext, 12);

    reg = DREG(ext, 0);

    tcg_gen_mov_i32(QREG_DIV1, num);

    SRC_EA(env, den, OS_LONG, 0, NULL);

    tcg_gen_mov_i32(QREG_DIV2, den);

    if (ext & 0x0800) {

        gen_helper_divs(cpu_env, tcg_const_i32(0));

    } else {

        gen_helper_divu(cpu_env, tcg_const_i32(0));

    }

    if ((ext & 7) == ((ext >> 12) & 7)) {

        /* div */

        tcg_gen_mov_i32 (reg, QREG_DIV1);

    } else {

        /* rem */

        tcg_gen_mov_i32 (reg, QREG_DIV2);

    }

    set_cc_op(s, CC_OP_FLAGS);

}


static void gen_dcbi(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    TCGv EA, val;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    EA = tcg_temp_new();

    gen_set_access_type(ctx, ACCESS_CACHE);

    gen_addr_reg_index(ctx, EA);

    val = tcg_temp_new();

    /* XXX: specification says this should be treated as a store by the MMU */

    gen_qemu_ld8u(ctx, val, EA);

    gen_qemu_st8(ctx, val, EA);

    tcg_temp_free(val);

    tcg_temp_free(EA);

#endif

}


static int setup_common(char *argv[], int argv_sz)

{

    memset(cur_ide, 0, sizeof(cur_ide));

    return append_arg(0, argv, argv_sz,

                      g_strdup("-nodefaults -display none"));

}


static int encode_init(AVCodecContext *avctx)

{

    HYuvContext *s = avctx->priv_data;

    int i, j, width, height;

    s->avctx= avctx;

    s->flags= avctx->flags;

    dsputil_init(&s->dsp, avctx);

    width= s->width= avctx->width;

    height= s->height= avctx->height;

    assert(width && height);

    avctx->extradata= av_mallocz(1024*30);

    avctx->stats_out= av_mallocz(1024*30);

    s->version=2;

    avctx->coded_frame= &s->picture;

    switch(avctx->pix_fmt){

    case PIX_FMT_YUV420P:

        s->bitstream_bpp= 12;

        break;

    case PIX_FMT_YUV422P:

        s->bitstream_bpp= 16;

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "format not supported\n");

        return -1;

    }

    avctx->bits_per_sample= s->bitstream_bpp;

    s->decorrelate= s->bitstream_bpp >= 24;

    s->predictor= avctx->prediction_method;

    s->interlaced= avctx->flags&CODEC_FLAG_INTERLACED_ME ? 1 : 0;

    if(avctx->context_model==1){

        s->context= avctx->context_model;

        if(s->flags & (CODEC_FLAG_PASS1|CODEC_FLAG_PASS2)){

            av_log(avctx, AV_LOG_ERROR, "context=1 is not compatible with 2 pass huffyuv encoding\n");

            return -1;

        }

    }else s->context= 0;

    if(avctx->codec->id==CODEC_ID_HUFFYUV){

        if(avctx->pix_fmt==PIX_FMT_YUV420P){

            av_log(avctx, AV_LOG_ERROR, "Error: YV12 is not supported by huffyuv; use vcodec=ffvhuff or format=422p\n");

            return -1;

        }

        if(avctx->context_model){

            av_log(avctx, AV_LOG_ERROR, "Error: per-frame huffman tables are not supported by huffyuv; use vcodec=ffvhuff\n");

            return -1;

        }

        if(s->interlaced != ( height > 288 ))

            av_log(avctx, AV_LOG_INFO, "using huffyuv 2.2.0 or newer interlacing flag\n");

    }else if(avctx->strict_std_compliance>=0){

        av_log(avctx, AV_LOG_ERROR, "This codec is under development; files encoded with it may not be decodeable with future versions!!! Set vstrict=-1 to use it anyway.\n");

        return -1;

    }

    ((uint8_t*)avctx->extradata)[0]= s->predictor;

    ((uint8_t*)avctx->extradata)[1]= s->bitstream_bpp;

    ((uint8_t*)avctx->extradata)[2]= s->interlaced ? 0x10 : 0x20;

    if(s->context)

        ((uint8_t*)avctx->extradata)[2]|= 0x40;

    ((uint8_t*)avctx->extradata)[3]= 0;

    s->avctx->extradata_size= 4;

    if(avctx->stats_in){

        char *p= avctx->stats_in;

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

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

                s->stats[i][j]= 1;

        for(;;){

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

                char *next;

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

                    s->stats[i][j]+= strtol(p, &next, 0);

                    if(next==p) return -1;

                    p=next;

                }

            }

            if(p[0]==0 || p[1]==0 || p[2]==0) break;

        }

    }else{

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

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

                int d= FFMIN(j, 256-j);

                s->stats[i][j]= 100000000/(d+1);

            }

    }

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

        generate_len_table(s->len[i], s->stats[i], 256);

        if(generate_bits_table(s->bits[i], s->len[i])<0){

            return -1;

        }

        s->avctx->extradata_size+=

        store_table(s, s->len[i], &((uint8_t*)s->avctx->extradata)[s->avctx->extradata_size]);

    }

    if(s->context){

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

            int pels = width*height / (i?40:10);

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

                int d= FFMIN(j, 256-j);

                s->stats[i][j]= pels/(d+1);

            }

        }

    }else{

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

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

                s->stats[i][j]= 0;

    }

//    printf("pred:%d bpp:%d hbpp:%d il:%d\n", s->predictor, s->bitstream_bpp, avctx->bits_per_sample, s->interlaced);

    s->picture_number=0;

    return 0;

}


size_t qemu_file_set_rate_limit(QEMUFile *f, size_t new_rate)

{

    if (f->set_rate_limit)

        return f->set_rate_limit(f->opaque, new_rate);

    return 0;

}


static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,

                                       ALSChannelData **cd, int *reverted,

                                       unsigned int offset, int c)

{

    ALSChannelData *ch = cd[c];

    unsigned int   dep = 0;

    unsigned int channels = ctx->avctx->channels;

    if (reverted[c])

        return 0;

    reverted[c] = 1;

    while (dep < channels && !ch[dep].stop_flag) {

        revert_channel_correlation(ctx, bd, cd, reverted, offset,

                                   ch[dep].master_channel);

        dep++;

    }

    if (dep == channels) {

        av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel correlation.\n");

        return AVERROR_INVALIDDATA;

    }

    bd->const_block = ctx->const_block + c;

    bd->shift_lsbs  = ctx->shift_lsbs + c;

    bd->opt_order   = ctx->opt_order + c;

    bd->store_prev_samples = ctx->store_prev_samples + c;

    bd->use_ltp     = ctx->use_ltp + c;

    bd->ltp_lag     = ctx->ltp_lag + c;

    bd->ltp_gain    = ctx->ltp_gain[c];

    bd->lpc_cof     = ctx->lpc_cof[c];

    bd->quant_cof   = ctx->quant_cof[c];

    bd->raw_samples = ctx->raw_samples[c] + offset;

    dep = 0;

    while (!ch[dep].stop_flag) {

        unsigned int smp;

        unsigned int begin = 1;

        unsigned int end   = bd->block_length - 1;

        int64_t y;

        int32_t *master = ctx->raw_samples[ch[dep].master_channel] + offset;

        if (ch[dep].time_diff_flag) {

            int t = ch[dep].time_diff_index;

            if (ch[dep].time_diff_sign) {

                t      = -t;

                begin -= t;

            } else {

                end   -= t;

            }

            for (smp = begin; smp < end; smp++) {

                y  = (1 << 6) +

                     MUL64(ch[dep].weighting[0], master[smp - 1    ]) +

                     MUL64(ch[dep].weighting[1], master[smp        ]) +

                     MUL64(ch[dep].weighting[2], master[smp + 1    ]) +

                     MUL64(ch[dep].weighting[3], master[smp - 1 + t]) +

                     MUL64(ch[dep].weighting[4], master[smp     + t]) +

                     MUL64(ch[dep].weighting[5], master[smp + 1 + t]);

                bd->raw_samples[smp] += y >> 7;

            }

        } else {

            for (smp = begin; smp < end; smp++) {

                y  = (1 << 6) +

                     MUL64(ch[dep].weighting[0], master[smp - 1]) +

                     MUL64(ch[dep].weighting[1], master[smp    ]) +

                     MUL64(ch[dep].weighting[2], master[smp + 1]);

                bd->raw_samples[smp] += y >> 7;

            }

        }

        dep++;

    }

    return 0;

}


const char *cpu_parse_cpu_model(const char *typename, const char *cpu_model)

{

    ObjectClass *oc;

    CPUClass *cc;

    Error *err = NULL;

    gchar **model_pieces;

    const char *cpu_type;

    model_pieces = g_strsplit(cpu_model, ",", 2);

    oc = cpu_class_by_name(typename, model_pieces[0]);

    if (oc == NULL) {

        g_strfreev(model_pieces);

        return NULL;

    }

    cpu_type = object_class_get_name(oc);

    cc = CPU_CLASS(oc);

    cc->parse_features(cpu_type, model_pieces[1], &err);

    g_strfreev(model_pieces);

    if (err != NULL) {

        error_report_err(err);

        return NULL;

    }

    return cpu_type;

}


static void find_peaks(DCAEncContext *c)

{

    int band, ch;

    for (band = 0; band < 32; band++)

        for (ch = 0; ch < c->fullband_channels; ch++) {

            int sample;

            int32_t m = 0;

            for (sample = 0; sample < SUBBAND_SAMPLES; sample++) {

                int32_t s = abs(c->subband[sample][band][ch]);

                if (m < s)

                    m = s;

            }

            c->peak_cb[band][ch] = get_cb(m);

        }

    if (c->lfe_channel) {

        int sample;

        int32_t m = 0;

        for (sample = 0; sample < DCA_LFE_SAMPLES; sample++)

            if (m < abs(c->downsampled_lfe[sample]))

                m = abs(c->downsampled_lfe[sample]);

        c->lfe_peak_cb = get_cb(m);

    }

}


void av_free(void *ptr)

{

#if CONFIG_MEMALIGN_HACK

    if (ptr)

        free((char *)ptr - ((char *)ptr)[-1]);

#elif HAVE_ALIGNED_MALLOC

    _aligned_free(ptr);

#else

    free(ptr);

#endif

}


static TCGv_i64 gen_mulu_i64_i32(TCGv a, TCGv b)

{

    TCGv_i64 tmp1 = tcg_temp_new_i64();

    TCGv_i64 tmp2 = tcg_temp_new_i64();

    tcg_gen_extu_i32_i64(tmp1, a);

    dead_tmp(a);

    tcg_gen_extu_i32_i64(tmp2, b);

    dead_tmp(b);

    tcg_gen_mul_i64(tmp1, tmp1, tmp2);

    tcg_temp_free_i64(tmp2);

    return tmp1;

}


static int tta_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    TTAContext *c = s->priv_data;

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

    int index = av_index_search_timestamp(st, timestamp, flags);

    if (index < 0)

        return -1;

    c->currentframe = index;

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

    return 0;

}


static void quantize_and_encode_band_cost_UQUAD_mips(struct AACEncContext *s,

                                                     PutBitContext *pb, const float *in, float *out,

                                                     const float *scaled, int size, int scale_idx,

                                                     int cb, const float lambda, const float uplim,

                                                     int *bits, const float ROUNDING)

{

    const float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    int i;

    int qc1, qc2, qc3, qc4;

    uint8_t  *p_bits  = (uint8_t  *)ff_aac_spectral_bits[cb-1];

    uint16_t *p_codes = (uint16_t *)ff_aac_spectral_codes[cb-1];

    float    *p_vec   = (float    *)ff_aac_codebook_vectors[cb-1];

    abs_pow34_v(s->scoefs, in, size);

    scaled = s->scoefs;

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

        int curidx, sign, count;

        int *in_int = (int *)&in[i];

        uint8_t v_bits;

        unsigned int v_codes;

        int t0, t1, t2, t3, t4;

        const float *vec;

        qc1 = scaled[i  ] * Q34 + ROUND_STANDARD;

        qc2 = scaled[i+1] * Q34 + ROUND_STANDARD;

        qc3 = scaled[i+2] * Q34 + ROUND_STANDARD;

        qc4 = scaled[i+3] * Q34 + ROUND_STANDARD;

        __asm__ volatile (

            ".set push                              \n\t"

            ".set noreorder                         \n\t"

            "ori    %[t4],      $zero,      2       \n\t"

            "ori    %[sign],    $zero,      0       \n\t"

            "slt    %[t0],      %[t4],      %[qc1]  \n\t"

            "slt    %[t1],      %[t4],      %[qc2]  \n\t"

            "slt    %[t2],      %[t4],      %[qc3]  \n\t"

            "slt    %[t3],      %[t4],      %[qc4]  \n\t"

            "movn   %[qc1],     %[t4],      %[t0]   \n\t"

            "movn   %[qc2],     %[t4],      %[t1]   \n\t"

            "movn   %[qc3],     %[t4],      %[t2]   \n\t"

            "movn   %[qc4],     %[t4],      %[t3]   \n\t"

            "lw     %[t0],      0(%[in_int])        \n\t"

            "lw     %[t1],      4(%[in_int])        \n\t"

            "lw     %[t2],      8(%[in_int])        \n\t"

            "lw     %[t3],      12(%[in_int])       \n\t"

            "slt    %[t0],      %[t0],      $zero   \n\t"

            "movn   %[sign],    %[t0],      %[qc1]  \n\t"

            "slt    %[t1],      %[t1],      $zero   \n\t"

            "slt    %[t2],      %[t2],      $zero   \n\t"

            "slt    %[t3],      %[t3],      $zero   \n\t"

            "sll    %[t0],      %[sign],    1       \n\t"

            "or     %[t0],      %[t0],      %[t1]   \n\t"

            "movn   %[sign],    %[t0],      %[qc2]  \n\t"

            "slt    %[t4],      $zero,      %[qc1]  \n\t"

            "slt    %[t1],      $zero,      %[qc2]  \n\t"

            "slt    %[count],   $zero,      %[qc3]  \n\t"

            "sll    %[t0],      %[sign],    1       \n\t"

            "or     %[t0],      %[t0],      %[t2]   \n\t"

            "movn   %[sign],    %[t0],      %[qc3]  \n\t"

            "slt    %[t2],      $zero,      %[qc4]  \n\t"

            "addu   %[count],   %[count],   %[t4]   \n\t"

            "addu   %[count],   %[count],   %[t1]   \n\t"

            "sll    %[t0],      %[sign],    1       \n\t"

            "or     %[t0],      %[t0],      %[t3]   \n\t"

            "movn   %[sign],    %[t0],      %[qc4]  \n\t"

            "addu   %[count],   %[count],   %[t2]   \n\t"

            ".set pop                               \n\t"

            : [qc1]"+r"(qc1), [qc2]"+r"(qc2),

              [qc3]"+r"(qc3), [qc4]"+r"(qc4),

              [sign]"=&r"(sign), [count]"=&r"(count),

              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),

              [t4]"=&r"(t4)

            : [in_int]"r"(in_int)

            : "memory"

        );

        curidx = qc1;

        curidx *= 3;

        curidx += qc2;

        curidx *= 3;

        curidx += qc3;

        curidx *= 3;

        curidx += qc4;

        v_codes = (p_codes[curidx] << count) | (sign & ((1 << count) - 1));

        v_bits  = p_bits[curidx] + count;

        put_bits(pb, v_bits, v_codes);

        if (out) {

           vec = &p_vec[curidx*4];

           out[i+0] = copysignf(vec[0] * IQ, in[i+0]);

           out[i+1] = copysignf(vec[1] * IQ, in[i+1]);

           out[i+2] = copysignf(vec[2] * IQ, in[i+2]);

           out[i+3] = copysignf(vec[3] * IQ, in[i+3]);

        }

    }

}


void ff_aac_update_ltp(AACEncContext *s, SingleChannelElement *sce)

{

    int i, j, lag;

    float corr, s0, s1, max_corr = 0.0f;

    float *samples = &s->planar_samples[s->cur_channel][1024];

    float *pred_signal = &sce->ltp_state[0];

    int samples_num = 2048;

    if (s->profile != FF_PROFILE_AAC_LTP)

        return;

    /* Calculate lag */

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

        s0 = s1 = 0.0f;

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

            if (j + 1024 < i)

                continue;

            s0 += samples[j]*pred_signal[j-i+1024];

            s1 += pred_signal[j-i+1024]*pred_signal[j-i+1024];

        }

        corr = s1 > 0.0f ? s0/sqrt(s1) : 0.0f;

        if (corr > max_corr) {

            max_corr = corr;

            lag = i;

        }

    }

    lag = av_clip(lag, 0, 2048); /* 11 bits => 2^11 = 2048 */

    if (!lag) {

        sce->ics.ltp.lag = lag;

        return;

    }

    s0 = s1 = 0.0f;

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

        s0 += samples[i];

        s1 += pred_signal[i-lag+1024];

    }

    sce->ics.ltp.coef_idx = quant_array_idx(s0/s1, ltp_coef, 8);

    sce->ics.ltp.coef     = ltp_coef[sce->ics.ltp.coef_idx];

    /* Predict the new samples */

    if (lag < 1024)

        samples_num = lag + 1024;

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

        pred_signal[i+1024] = sce->ics.ltp.coef*pred_signal[i-lag+1024];

    memset(&pred_signal[samples_num], 0, (2048 - samples_num)*sizeof(float));

    sce->ics.ltp.lag = lag;

}


static void z2_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    MemoryRegion *address_space_mem = get_system_memory();

    uint32_t sector_len = 0x10000;

    PXA2xxState *mpu;

    DriveInfo *dinfo;

    int be;

    void *z2_lcd;

    I2CBus *bus;

    DeviceState *wm;

    if (!cpu_model) {

        cpu_model = "pxa270-c5";

    }

    /* Setup CPU & memory */

    mpu = pxa270_init(address_space_mem, z2_binfo.ram_size, cpu_model);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    dinfo = drive_get(IF_PFLASH, 0, 0);

    if (!dinfo && !qtest_enabled()) {

        fprintf(stderr, "Flash image must be given with the "

                "'pflash' parameter\n");

        exit(1);

    }

    if (!pflash_cfi01_register(Z2_FLASH_BASE,

                               NULL, "z2.flash0", Z2_FLASH_SIZE,

                               dinfo ? dinfo->bdrv : NULL, sector_len,

                               Z2_FLASH_SIZE / sector_len, 4, 0, 0, 0, 0,

                               be)) {

        fprintf(stderr, "qemu: Error registering flash memory.\n");

        exit(1);

    }

    /* setup keypad */

    pxa27x_register_keypad(mpu->kp, map, 0x100);

    /* MMC/SD host */

    pxa2xx_mmci_handlers(mpu->mmc,

        NULL,

        qdev_get_gpio_in(mpu->gpio, Z2_GPIO_SD_DETECT));

    type_register_static(&zipit_lcd_info);

    type_register_static(&aer915_info);

    z2_lcd = ssi_create_slave(mpu->ssp[1], "zipit-lcd");

    bus = pxa2xx_i2c_bus(mpu->i2c[0]);

    i2c_create_slave(bus, TYPE_AER915, 0x55);

    wm = i2c_create_slave(bus, "wm8750", 0x1b);

    mpu->i2s->opaque = wm;

    mpu->i2s->codec_out = wm8750_dac_dat;

    mpu->i2s->codec_in = wm8750_adc_dat;

    wm8750_data_req_set(wm, mpu->i2s->data_req, mpu->i2s);

    qdev_connect_gpio_out(mpu->gpio, Z2_GPIO_LCD_CS,

        qemu_allocate_irqs(z2_lcd_cs, z2_lcd, 1)[0]);

    z2_binfo.kernel_filename = kernel_filename;

    z2_binfo.kernel_cmdline = kernel_cmdline;

    z2_binfo.initrd_filename = initrd_filename;

    z2_binfo.board_id = 0x6dd;

    arm_load_kernel(mpu->cpu, &z2_binfo);

}


void ff_put_h264_qpel16_mc20_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_hz_16w_msa(src - 2, stride, dst, stride, 16);

}


void avformat_free_context(AVFormatContext *s)

{

    int i;

    AVStream *st;

    av_opt_free(s);

    if (s->iformat && s->iformat->priv_class && s->priv_data)

        av_opt_free(s->priv_data);

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

        /* free all data in a stream component */

        st = s->streams[i];

        if (st->parser) {

            av_parser_close(st->parser);

            av_free_packet(&st->cur_pkt);

        }

        if (st->attached_pic.data)

            av_free_packet(&st->attached_pic);

        av_dict_free(&st->metadata);

        av_free(st->index_entries);

        av_free(st->codec->extradata);

        av_free(st->codec->subtitle_header);

        av_free(st->codec);

        av_free(st->priv_data);

        av_free(st->info);

        av_free(st);

    }

    for(i=s->nb_programs-1; i>=0; i--) {

        av_dict_free(&s->programs[i]->metadata);

        av_freep(&s->programs[i]->stream_index);

        av_freep(&s->programs[i]);

    }

    av_freep(&s->programs);

    av_freep(&s->priv_data);

    while(s->nb_chapters--) {

        av_dict_free(&s->chapters[s->nb_chapters]->metadata);

        av_free(s->chapters[s->nb_chapters]);

    }

    av_freep(&s->chapters);

    av_dict_free(&s->metadata);

    av_freep(&s->streams);

    av_free(s);

}


static int encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])

{

    int x, y, p, i;

    const int ring_size = s->avctx->context_model ? 3 : 2;

    int16_t *sample[4][3];

    int lbd    = s->bits_per_raw_sample <= 8;

    int bits   = s->bits_per_raw_sample > 0 ? s->bits_per_raw_sample : 8;

    int offset = 1 << bits;

    s->run_index = 0;

    memset(s->sample_buffer, 0, ring_size * MAX_PLANES *

                                (w + 6) * sizeof(*s->sample_buffer));

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

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

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

                sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;

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

            int b, g, r, av_uninit(a);

            if (lbd) {

                unsigned v = *((uint32_t*)(src[0] + x*4 + stride[0]*y));

                b =  v        & 0xFF;

                g = (v >>  8) & 0xFF;

                r = (v >> 16) & 0xFF;

                a =  v >> 24;

            } else {

                b = *((uint16_t*)(src[0] + x*2 + stride[0]*y));

                g = *((uint16_t*)(src[1] + x*2 + stride[1]*y));

                r = *((uint16_t*)(src[2] + x*2 + stride[2]*y));

            }

            b -= g;

            r -= g;

            g += (b + r) >> 2;

            b += offset;

            r += offset;

            sample[0][0][x] = g;

            sample[1][0][x] = b;

            sample[2][0][x] = r;

            sample[3][0][x] = a;

        }

        for (p = 0; p < 3 + s->transparency; p++) {

            int ret;

            sample[p][0][-1] = sample[p][1][0  ];

            sample[p][1][ w] = sample[p][1][w-1];

            if (lbd)

                ret = encode_line(s, w, sample[p], (p + 1) / 2, 9);

            else

                ret = encode_line(s, w, sample[p], (p + 1) / 2, bits + 1);

            if (ret < 0)

                return ret;

        }

    }

    return 0;

}