static int transcode_init(void)

{

    int ret = 0, i, j, k;

    AVFormatContext *oc;

    OutputStream *ost;

    InputStream *ist;

    char error[1024] = {0};

    int want_sdp = 1;

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

        FilterGraph *fg = filtergraphs[i];

        for (j = 0; j < fg->nb_outputs; j++) {

            OutputFilter *ofilter = fg->outputs[j];

            if (!ofilter->ost || ofilter->ost->source_index >= 0)

                continue;

            if (fg->nb_inputs != 1)

                continue;

            for (k = nb_input_streams-1; k >= 0 ; k--)

                if (fg->inputs[0]->ist == input_streams[k])

                    break;

            ofilter->ost->source_index = k;

        }

    }

    /* init framerate emulation */

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

        InputFile *ifile = input_files[i];

        if (ifile->rate_emu)

            for (j = 0; j < ifile->nb_streams; j++)

                input_streams[j + ifile->ist_index]->start = av_gettime_relative();

    }

    /* output stream init */

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

        oc = output_files[i]->ctx;

        if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {

            av_dump_format(oc, i, oc->filename, 1);

            av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);

            return AVERROR(EINVAL);

        }

    }

    /* init complex filtergraphs */

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

        if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)

            return ret;

    /* for each output stream, we compute the right encoding parameters */

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

        AVCodecContext *enc_ctx;

        AVCodecContext *dec_ctx = NULL;

        ost = output_streams[i];

        oc  = output_files[ost->file_index]->ctx;

        ist = get_input_stream(ost);

        if (ost->attachment_filename)

            continue;

        enc_ctx = ost->stream_copy ? ost->st->codec : ost->enc_ctx;

        if (ist) {

            dec_ctx = ist->dec_ctx;

            ost->st->disposition          = ist->st->disposition;

            enc_ctx->bits_per_raw_sample    = dec_ctx->bits_per_raw_sample;

            enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;

        } else {

            for (j=0; j<oc->nb_streams; j++) {

                AVStream *st = oc->streams[j];

                if (st != ost->st && st->codec->codec_type == enc_ctx->codec_type)

                    break;

            }

            if (j == oc->nb_streams)

                if (enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO || enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)

                    ost->st->disposition = AV_DISPOSITION_DEFAULT;

        }

        if (ost->stream_copy) {

            AVRational sar;

            uint64_t extra_size;

            av_assert0(ist && !ost->filter);

            extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;

            if (extra_size > INT_MAX) {

                return AVERROR(EINVAL);

            }

            /* if stream_copy is selected, no need to decode or encode */

            enc_ctx->codec_id   = dec_ctx->codec_id;

            enc_ctx->codec_type = dec_ctx->codec_type;

            if (!enc_ctx->codec_tag) {

                unsigned int codec_tag;

                if (!oc->oformat->codec_tag ||

                     av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||

                     !av_codec_get_tag2(oc->oformat->codec_tag, dec_ctx->codec_id, &codec_tag))

                    enc_ctx->codec_tag = dec_ctx->codec_tag;

            }

            enc_ctx->bit_rate       = dec_ctx->bit_rate;

            enc_ctx->rc_max_rate    = dec_ctx->rc_max_rate;

            enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;

            enc_ctx->field_order    = dec_ctx->field_order;

            if (dec_ctx->extradata_size) {

                enc_ctx->extradata      = av_mallocz(extra_size);

                if (!enc_ctx->extradata) {

                    return AVERROR(ENOMEM);

                }

                memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);

            }

            enc_ctx->extradata_size= dec_ctx->extradata_size;

            enc_ctx->bits_per_coded_sample  = dec_ctx->bits_per_coded_sample;

            enc_ctx->time_base = ist->st->time_base;

            /*

             * Avi is a special case here because it supports variable fps but

             * having the fps and timebase differe significantly adds quite some

             * overhead

             */

            if(!strcmp(oc->oformat->name, "avi")) {

                if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)

                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)

                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base)

                               && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500

                     || copy_tb==2){

                    enc_ctx->time_base.num = ist->st->r_frame_rate.den;

                    enc_ctx->time_base.den = 2*ist->st->r_frame_rate.num;

                    enc_ctx->ticks_per_frame = 2;

                } else if (   copy_tb<0 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->st->time_base)

                                 && av_q2d(ist->st->time_base) < 1.0/500

                    || copy_tb==0){

                    enc_ctx->time_base = dec_ctx->time_base;

                    enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;

                    enc_ctx->time_base.den *= 2;

                    enc_ctx->ticks_per_frame = 2;

                }

            } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)

                      && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")

                      && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")

                      && strcmp(oc->oformat->name, "f4v")

            ) {

                if(   copy_tb<0 && dec_ctx->time_base.den

                                && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->st->time_base)

                                && av_q2d(ist->st->time_base) < 1.0/500

                   || copy_tb==0){

                    enc_ctx->time_base = dec_ctx->time_base;

                    enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;

                }

            }

            if (   enc_ctx->codec_tag == AV_RL32("tmcd")

                && dec_ctx->time_base.num < dec_ctx->time_base.den

                && dec_ctx->time_base.num > 0

                && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {

                enc_ctx->time_base = dec_ctx->time_base;

            }

            if (ist && !ost->frame_rate.num)

                ost->frame_rate = ist->framerate;

            if(ost->frame_rate.num)

                enc_ctx->time_base = av_inv_q(ost->frame_rate);

            av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,

                        enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);

            if (ist->st->nb_side_data) {

                ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,

                                                      sizeof(*ist->st->side_data));

                if (!ost->st->side_data)

                    return AVERROR(ENOMEM);

                for (j = 0; j < ist->st->nb_side_data; j++) {

                    const AVPacketSideData *sd_src = &ist->st->side_data[j];

                    AVPacketSideData *sd_dst = &ost->st->side_data[j];

                    sd_dst->data = av_malloc(sd_src->size);

                    if (!sd_dst->data)

                        return AVERROR(ENOMEM);

                    memcpy(sd_dst->data, sd_src->data, sd_src->size);

                    sd_dst->size = sd_src->size;

                    sd_dst->type = sd_src->type;

                    ost->st->nb_side_data++;

                }

            }

            ost->parser = av_parser_init(enc_ctx->codec_id);

            switch (enc_ctx->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                if (audio_volume != 256) {

                    av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");

                    exit_program(1);

                }

                enc_ctx->channel_layout     = dec_ctx->channel_layout;

                enc_ctx->sample_rate        = dec_ctx->sample_rate;

                enc_ctx->channels           = dec_ctx->channels;

                enc_ctx->frame_size         = dec_ctx->frame_size;

                enc_ctx->audio_service_type = dec_ctx->audio_service_type;

                enc_ctx->block_align        = dec_ctx->block_align;

                enc_ctx->initial_padding    = dec_ctx->delay;

#if FF_API_AUDIOENC_DELAY

                enc_ctx->delay              = dec_ctx->delay;

#endif

                if((enc_ctx->block_align == 1 || enc_ctx->block_align == 1152 || enc_ctx->block_align == 576) && enc_ctx->codec_id == AV_CODEC_ID_MP3)

                    enc_ctx->block_align= 0;

                if(enc_ctx->codec_id == AV_CODEC_ID_AC3)

                    enc_ctx->block_align= 0;

                break;

            case AVMEDIA_TYPE_VIDEO:

                enc_ctx->pix_fmt            = dec_ctx->pix_fmt;

                enc_ctx->width              = dec_ctx->width;

                enc_ctx->height             = dec_ctx->height;

                enc_ctx->has_b_frames       = dec_ctx->has_b_frames;

                if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option

                    sar =

                        av_mul_q(ost->frame_aspect_ratio,

                                 (AVRational){ enc_ctx->height, enc_ctx->width });

                    av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "

                           "with stream copy may produce invalid files\n");

                }

                else if (ist->st->sample_aspect_ratio.num)

                    sar = ist->st->sample_aspect_ratio;

                else

                    sar = dec_ctx->sample_aspect_ratio;

                ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;

                ost->st->avg_frame_rate = ist->st->avg_frame_rate;

                ost->st->r_frame_rate = ist->st->r_frame_rate;

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                enc_ctx->width  = dec_ctx->width;

                enc_ctx->height = dec_ctx->height;

                break;

            case AVMEDIA_TYPE_DATA:

            case AVMEDIA_TYPE_ATTACHMENT:

                break;

            default:

                abort();

            }

        } else {

            if (!ost->enc)

                ost->enc = avcodec_find_encoder(enc_ctx->codec_id);

            if (!ost->enc) {

                /* should only happen when a default codec is not present. */

                snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",

                         avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            if (ist)

                ist->decoding_needed |= DECODING_FOR_OST;

            ost->encoding_needed = 1;

            set_encoder_id(output_files[ost->file_index], ost);

            if (!ost->filter &&

                (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||

                 enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {

                    FilterGraph *fg;

                    fg = init_simple_filtergraph(ist, ost);

                    if (configure_filtergraph(fg)) {

                        av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");

                        exit_program(1);

                    }

            }

            if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {

                if (ost->filter && !ost->frame_rate.num)

                    ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);

                if (ist && !ost->frame_rate.num)

                    ost->frame_rate = ist->framerate;

                if (ist && !ost->frame_rate.num)

                    ost->frame_rate = ist->st->r_frame_rate;

                if (ist && !ost->frame_rate.num) {

                    ost->frame_rate = (AVRational){25, 1};

                    av_log(NULL, AV_LOG_WARNING,

                           "No information "

                           "about the input framerate is available. Falling "

                           "back to a default value of 25fps for output stream #%d:%d. Use the -r option "

                           "if you want a different framerate.\n",

                           ost->file_index, ost->index);

                }

//                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};

                if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {

                    int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);

                    ost->frame_rate = ost->enc->supported_framerates[idx];

                }

                // reduce frame rate for mpeg4 to be within the spec limits

                if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {

                    av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,

                              ost->frame_rate.num, ost->frame_rate.den, 65535);

                }

            }

            switch (enc_ctx->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                enc_ctx->sample_fmt     = ost->filter->filter->inputs[0]->format;

                enc_ctx->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;

                enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;

                enc_ctx->channels       = avfilter_link_get_channels(ost->filter->filter->inputs[0]);

                enc_ctx->time_base      = (AVRational){ 1, enc_ctx->sample_rate };

                break;

            case AVMEDIA_TYPE_VIDEO:

                enc_ctx->time_base = av_inv_q(ost->frame_rate);

                if (ost->filter && !(enc_ctx->time_base.num && enc_ctx->time_base.den))

                    enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;

                if (   av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH

                   && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){

                    av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"

                                               "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");

                }

                for (j = 0; j < ost->forced_kf_count; j++)

                    ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],

                                                         AV_TIME_BASE_Q,

                                                         enc_ctx->time_base);

                enc_ctx->width  = ost->filter->filter->inputs[0]->w;

                enc_ctx->height = ost->filter->filter->inputs[0]->h;

                enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =

                    ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option

                    av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :

                    ost->filter->filter->inputs[0]->sample_aspect_ratio;

                if (!strncmp(ost->enc->name, "libx264", 7) &&

                    enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&

                    ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)

                    av_log(NULL, AV_LOG_WARNING,

                           "No pixel format specified, %s for H.264 encoding chosen.\n"

                           "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",

                           av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));

                if (!strncmp(ost->enc->name, "mpeg2video", 10) &&

                    enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&

                    ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)

                    av_log(NULL, AV_LOG_WARNING,

                           "No pixel format specified, %s for MPEG-2 encoding chosen.\n"

                           "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",

                           av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));

                enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;

                ost->st->avg_frame_rate = ost->frame_rate;

                if (!dec_ctx ||

                    enc_ctx->width   != dec_ctx->width  ||

                    enc_ctx->height  != dec_ctx->height ||

                    enc_ctx->pix_fmt != dec_ctx->pix_fmt) {

                    enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;

                }

                if (ost->forced_keyframes) {

                    if (!strncmp(ost->forced_keyframes, "expr:", 5)) {

                        ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,

                                            forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);

                        if (ret < 0) {

                            av_log(NULL, AV_LOG_ERROR,

                                   "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);

                            return ret;

                        }

                        ost->forced_keyframes_expr_const_values[FKF_N] = 0;

                        ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;

                        ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;

                        ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;

                    } else {

                        parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);

                    }

                }

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                enc_ctx->time_base = (AVRational){1, 1000};

                if (!enc_ctx->width) {

                    enc_ctx->width     = input_streams[ost->source_index]->st->codec->width;

                    enc_ctx->height    = input_streams[ost->source_index]->st->codec->height;

                }

                break;

            case AVMEDIA_TYPE_DATA:

                break;

            default:

                abort();

                break;

            }

            /* two pass mode */

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

                char logfilename[1024];

                FILE *f;

                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",

                         ost->logfile_prefix ? ost->logfile_prefix :

                                               DEFAULT_PASS_LOGFILENAME_PREFIX,

                         i);

                if (!strcmp(ost->enc->name, "libx264")) {

                    av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);

                } else {

                    if (enc_ctx->flags & CODEC_FLAG_PASS2) {

                        char  *logbuffer;

                        size_t logbuffer_size;

                        if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {

                            av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",

                                   logfilename);

                            exit_program(1);

                        }

                        enc_ctx->stats_in = logbuffer;

                    }

                    if (enc_ctx->flags & CODEC_FLAG_PASS1) {

                        f = av_fopen_utf8(logfilename, "wb");

                        if (!f) {

                            av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",

                                logfilename, strerror(errno));

                            exit_program(1);

                        }

                        ost->logfile = f;

                    }

                }

            }

        }

        if (ost->disposition) {

            static const AVOption opts[] = {

                { "disposition"         , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },

                { "default"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT           },    .unit = "flags" },

                { "dub"                 , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB               },    .unit = "flags" },

                { "original"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL          },    .unit = "flags" },

                { "comment"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT           },    .unit = "flags" },

                { "lyrics"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS            },    .unit = "flags" },

                { "karaoke"             , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE           },    .unit = "flags" },

                { "forced"              , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED            },    .unit = "flags" },

                { "hearing_impaired"    , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED  },    .unit = "flags" },

                { "visual_impaired"     , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED   },    .unit = "flags" },

                { "clean_effects"       , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS     },    .unit = "flags" },

                { "captions"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS          },    .unit = "flags" },

                { "descriptions"        , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS      },    .unit = "flags" },

                { "metadata"            , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA          },    .unit = "flags" },

                { NULL },

            };

            static const AVClass class = {

                .class_name = "",

                .item_name  = av_default_item_name,

                .option     = opts,

                .version    = LIBAVUTIL_VERSION_INT,

            };

            const AVClass *pclass = &class;

            ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);

            if (ret < 0)

                goto dump_format;

        }

    }

    /* open each encoder */

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

        ost = output_streams[i];

        if (ost->encoding_needed) {

            AVCodec      *codec = ost->enc;

            AVCodecContext *dec = NULL;

            if ((ist = get_input_stream(ost)))

                dec = ist->dec_ctx;

            if (dec && dec->subtitle_header) {

                /* ASS code assumes this buffer is null terminated so add extra byte. */

                ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);

                if (!ost->enc_ctx->subtitle_header) {

                    ret = AVERROR(ENOMEM);

                    goto dump_format;

                }

                memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);

                ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;

            }

            if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))

                av_dict_set(&ost->encoder_opts, "threads", "auto", 0);

            av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);

            if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {

                if (ret == AVERROR_EXPERIMENTAL)

                    abort_codec_experimental(codec, 1);

                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",

                        ost->file_index, ost->index);

                goto dump_format;

            }

            if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&

                !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))

                av_buffersink_set_frame_size(ost->filter->filter,

                                             ost->enc_ctx->frame_size);

            assert_avoptions(ost->encoder_opts);

            if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)

                av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."

                                             " It takes bits/s as argument, not kbits/s\n");

            ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);

            if (ret < 0) {

                av_log(NULL, AV_LOG_FATAL,

                       "Error initializing the output stream codec context.\n");

                exit_program(1);

            }

            // copy timebase while removing common factors

            ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});

            ost->st->codec->codec= ost->enc_ctx->codec;

        } else {

            ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);

            if (ret < 0) {

                av_log(NULL, AV_LOG_FATAL,

                    "Error setting up codec context options.\n");

                return ret;

            }

            // copy timebase while removing common factors

            ost->st->time_base = av_add_q(ost->st->codec->time_base, (AVRational){0, 1});

        }

    }

    /* init input streams */

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

        if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {

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

                ost = output_streams[i];

                avcodec_close(ost->enc_ctx);

            }

            goto dump_format;

        }

    /* discard unused programs */

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

        InputFile *ifile = input_files[i];

        for (j = 0; j < ifile->ctx->nb_programs; j++) {

            AVProgram *p = ifile->ctx->programs[j];

            int discard  = AVDISCARD_ALL;

            for (k = 0; k < p->nb_stream_indexes; k++)

                if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {

                    discard = AVDISCARD_DEFAULT;

                    break;

                }

            p->discard = discard;

        }

    }

    /* open files and write file headers */

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

        oc = output_files[i]->ctx;

        oc->interrupt_callback = int_cb;

        if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {

            snprintf(error, sizeof(error),

                     "Could not write header for output file #%d "

                     "(incorrect codec parameters ?): %s",

                     i, av_err2str(ret));

            ret = AVERROR(EINVAL);

            goto dump_format;

        }

//         assert_avoptions(output_files[i]->opts);

        if (strcmp(oc->oformat->name, "rtp")) {

            want_sdp = 0;

        }

    }

 dump_format:

    /* dump the file output parameters - cannot be done before in case

       of stream copy */

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

        av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);

    }

    /* dump the stream mapping */

    av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");

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

        ist = input_streams[i];

        for (j = 0; j < ist->nb_filters; j++) {

            if (ist->filters[j]->graph->graph_desc) {

                av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",

                       ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",

                       ist->filters[j]->name);

                if (nb_filtergraphs > 1)

                    av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);

                av_log(NULL, AV_LOG_INFO, "\n");

            }

        }

    }

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

        ost = output_streams[i];

        if (ost->attachment_filename) {

            /* an attached file */

            av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",

                   ost->attachment_filename, ost->file_index, ost->index);

            continue;

        }

        if (ost->filter && ost->filter->graph->graph_desc) {

            /* output from a complex graph */

            av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);

            if (nb_filtergraphs > 1)

                av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);

            av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,

                   ost->index, ost->enc ? ost->enc->name : "?");

            continue;

        }

        av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",

               input_streams[ost->source_index]->file_index,

               input_streams[ost->source_index]->st->index,

               ost->file_index,

               ost->index);

        if (ost->sync_ist != input_streams[ost->source_index])

            av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",

                   ost->sync_ist->file_index,

                   ost->sync_ist->st->index);

        if (ost->stream_copy)

            av_log(NULL, AV_LOG_INFO, " (copy)");

        else {

            const AVCodec *in_codec    = input_streams[ost->source_index]->dec;

            const AVCodec *out_codec   = ost->enc;

            const char *decoder_name   = "?";

            const char *in_codec_name  = "?";

            const char *encoder_name   = "?";

            const char *out_codec_name = "?";

            const AVCodecDescriptor *desc;

            if (in_codec) {

                decoder_name  = in_codec->name;

                desc = avcodec_descriptor_get(in_codec->id);

                if (desc)

                    in_codec_name = desc->name;

                if (!strcmp(decoder_name, in_codec_name))

                    decoder_name = "native";

            }

            if (out_codec) {

                encoder_name   = out_codec->name;

                desc = avcodec_descriptor_get(out_codec->id);

                if (desc)

                    out_codec_name = desc->name;

                if (!strcmp(encoder_name, out_codec_name))

                    encoder_name = "native";

            }

            av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",

                   in_codec_name, decoder_name,

                   out_codec_name, encoder_name);

        }

        av_log(NULL, AV_LOG_INFO, "\n");

    }

    if (ret) {

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

        return ret;

    }

    if (sdp_filename || want_sdp) {

        print_sdp();

    }

    transcode_init_done = 1;

    return 0;

}


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

{

    int ret;

    ret = av_get_packet(s->pb, pkt, MP3_PACKET_SIZE);

    pkt->stream_index = 0;

    if (ret <= 0) {

        return AVERROR(EIO);

    }

    if (ret > ID3v1_TAG_SIZE &&

        memcmp(&pkt->data[ret - ID3v1_TAG_SIZE], "TAG", 3) == 0)

        ret -= ID3v1_TAG_SIZE;

    /* note: we need to modify the packet size here to handle the last

       packet */

    pkt->size = ret;

    return ret;

}


static void vdadec_flush(AVCodecContext *avctx)

{

    return ff_h264_decoder.flush(avctx);

}


static inline tcg_target_ulong cpu_tb_exec(CPUState *cpu, TranslationBlock *itb)

{

    CPUArchState *env = cpu->env_ptr;

    uintptr_t ret;

    TranslationBlock *last_tb;

    int tb_exit;

    uint8_t *tb_ptr = itb->tc_ptr;

    qemu_log_mask_and_addr(CPU_LOG_EXEC, itb->pc,

                           "Trace %p [" TARGET_FMT_lx "] %s\n",

                           itb->tc_ptr, itb->pc, lookup_symbol(itb->pc));

#if defined(DEBUG_DISAS)

    if (qemu_loglevel_mask(CPU_LOG_TB_CPU)

        && qemu_log_in_addr_range(itb->pc)) {

#if defined(TARGET_I386)

        log_cpu_state(cpu, CPU_DUMP_CCOP);

#elif defined(TARGET_M68K)

        /* ??? Should not modify env state for dumping.  */

        cpu_m68k_flush_flags(env, env->cc_op);

        env->cc_op = CC_OP_FLAGS;

        env->sr = (env->sr & 0xffe0) | env->cc_dest | (env->cc_x << 4);

        log_cpu_state(cpu, 0);

#else

        log_cpu_state(cpu, 0);

#endif

    }

#endif /* DEBUG_DISAS */

    cpu->can_do_io = !use_icount;

    ret = tcg_qemu_tb_exec(env, tb_ptr);

    cpu->can_do_io = 1;

    last_tb = (TranslationBlock *)(ret & ~TB_EXIT_MASK);

    tb_exit = ret & TB_EXIT_MASK;

    trace_exec_tb_exit(last_tb, tb_exit);

    if (tb_exit > TB_EXIT_IDX1) {

        /* We didn't start executing this TB (eg because the instruction

         * counter hit zero); we must restore the guest PC to the address

         * of the start of the TB.

         */

        CPUClass *cc = CPU_GET_CLASS(cpu);

        qemu_log_mask_and_addr(CPU_LOG_EXEC, last_tb->pc,

                               "Stopped execution of TB chain before %p ["

                               TARGET_FMT_lx "] %s\n",

                               last_tb->tc_ptr, last_tb->pc,

                               lookup_symbol(last_tb->pc));

        if (cc->synchronize_from_tb) {

            cc->synchronize_from_tb(cpu, last_tb);

        } else {

            assert(cc->set_pc);

            cc->set_pc(cpu, last_tb->pc);

        }

    }

    if (tb_exit == TB_EXIT_REQUESTED) {

        /* We were asked to stop executing TBs (probably a pending

         * interrupt. We've now stopped, so clear the flag.

         */

        cpu->tcg_exit_req = 0;

    }

    return ret;

}


static void ac97_class_init (ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS (klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS (klass);

    k->realize = ac97_realize;

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_82801AA_5;

    k->revision = 0x01;

    k->class_id = PCI_CLASS_MULTIMEDIA_AUDIO;

    set_bit(DEVICE_CATEGORY_SOUND, dc->categories);

    dc->desc = "Intel 82801AA AC97 Audio";

    dc->vmsd = &vmstate_ac97;

    dc->props = ac97_properties;

    dc->reset = ac97_on_reset;

}


static int adx_decode_init(AVCodecContext * avctx)

{

	ADXContext *c = avctx->priv_data;

//	printf("adx_decode_init\n"); fflush(stdout);

	c->prev[0].s1 = 0;

	c->prev[0].s2 = 0;

	c->prev[1].s1 = 0;

	c->prev[1].s2 = 0;

	c->header_parsed = 0;

	c->in_temp = 0;

	return 0;

}


static int xan_huffman_decode(unsigned char *dest, int dest_len,

                              const unsigned char *src, int src_len)

{

    unsigned char byte = *src++;

    unsigned char ival = byte + 0x16;

    const unsigned char * ptr = src + byte*2;

    int ptr_len = src_len - 1 - byte*2;

    unsigned char val = ival;

    unsigned char *dest_end = dest + dest_len;

    GetBitContext gb;

    if (ptr_len < 0)

        return AVERROR_INVALIDDATA;

    init_get_bits(&gb, ptr, ptr_len * 8);

    while ( val != 0x16 ) {

        val = src[val - 0x17 + get_bits1(&gb) * byte];

        if ( val < 0x16 ) {

            if (dest >= dest_end)

                return 0;

            *dest++ = val;

            val = ival;

        }

    }

    return 0;

}


static int init(AVCodecParserContext *s)

{

    H264Context *h = s->priv_data;

    h->thread_context[0] = h;

    return 0;

}


static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)

{

    int i, j, k;

    int coding_mode;

    int motion_x[6];

    int motion_y[6];

    int last_motion_x = 0;

    int last_motion_y = 0;

    int prior_last_motion_x = 0;

    int prior_last_motion_y = 0;

    int current_macroblock;

    int current_fragment;

    debug_vp3("  vp3: unpacking motion vectors\n");

    if (s->keyframe) {

        debug_vp3("    keyframe-- there are no motion vectors\n");

    } else {

        memset(motion_x, 0, 6 * sizeof(int));

        memset(motion_y, 0, 6 * sizeof(int));

        /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */

        coding_mode = get_bits1(gb);

        debug_vectors("    using %s scheme for unpacking motion vectors\n",

            (coding_mode == 0) ? "VLC" : "fixed-length");

        /* iterate through all of the macroblocks that contain 1 or more

         * coded fragments */

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

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

                current_macroblock = s->superblock_macroblocks[i * 4 + j];

                if ((current_macroblock == -1) ||

                    (s->macroblock_coding[current_macroblock] == MODE_COPY))

                    continue;

                if (current_macroblock >= s->macroblock_count) {

                    av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_vectors(): bad macroblock number (%d >= %d)\n",

                        current_macroblock, s->macroblock_count);

                    return 1;

                }

                current_fragment = s->macroblock_fragments[current_macroblock * 6];

                if (current_fragment >= s->fragment_count) {

                    av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_vectors(): bad fragment number (%d >= %d\n",

                        current_fragment, s->fragment_count);

                    return 1;

                }

                switch (s->macroblock_coding[current_macroblock]) {

                case MODE_INTER_PLUS_MV:

                case MODE_GOLDEN_MV:

                    /* all 6 fragments use the same motion vector */

                    if (coding_mode == 0) {

                        motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                        motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                    } else {

                        motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                        motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];

                    }

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* vector maintenance, only on MODE_INTER_PLUS_MV */

                    if (s->macroblock_coding[current_macroblock] ==

                        MODE_INTER_PLUS_MV) {

                        prior_last_motion_x = last_motion_x;

                        prior_last_motion_y = last_motion_y;

                        last_motion_x = motion_x[0];

                        last_motion_y = motion_y[0];

                    }

                    break;

                case MODE_INTER_FOURMV:

                    /* vector maintenance */

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    /* fetch 4 vectors from the bitstream, one for each

                     * Y fragment, then average for the C fragment vectors */

                    motion_x[4] = motion_y[4] = 0;

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

                        if (coding_mode == 0) {

                            motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                            motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];

                        } else {

                            motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                            motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];

                        }

                        last_motion_x = motion_x[k];

                        last_motion_y = motion_y[k];

                        motion_x[4] += motion_x[k];

                        motion_y[4] += motion_y[k];

                    }

                    motion_x[5]=

                    motion_x[4]= RSHIFT(motion_x[4], 2);

                    motion_y[5]=

                    motion_y[4]= RSHIFT(motion_y[4], 2);

                    break;

                case MODE_INTER_LAST_MV:

                    /* all 6 fragments use the last motion vector */

                    motion_x[0] = last_motion_x;

                    motion_y[0] = last_motion_y;

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* no vector maintenance (last vector remains the

                     * last vector) */

                    break;

                case MODE_INTER_PRIOR_LAST:

                    /* all 6 fragments use the motion vector prior to the

                     * last motion vector */

                    motion_x[0] = prior_last_motion_x;

                    motion_y[0] = prior_last_motion_y;

                    for (k = 1; k < 6; k++) {

                        motion_x[k] = motion_x[0];

                        motion_y[k] = motion_y[0];

                    }

                    /* vector maintenance */

                    prior_last_motion_x = last_motion_x;

                    prior_last_motion_y = last_motion_y;

                    last_motion_x = motion_x[0];

                    last_motion_y = motion_y[0];

                    break;

                default:

                    /* covers intra, inter without MV, golden without MV */

                    memset(motion_x, 0, 6 * sizeof(int));

                    memset(motion_y, 0, 6 * sizeof(int));

                    /* no vector maintenance */

                    break;

                }

                /* assign the motion vectors to the correct fragments */

                debug_vectors("    vectors for macroblock starting @ fragment %d (coding method %d):\n",

                    current_fragment,

                    s->macroblock_coding[current_macroblock]);

                for (k = 0; k < 6; k++) {

                    current_fragment =

                        s->macroblock_fragments[current_macroblock * 6 + k];

                    if (current_fragment == -1)

                        continue;

                    if (current_fragment >= s->fragment_count) {

                        av_log(s->avctx, AV_LOG_ERROR, "  vp3:unpack_vectors(): bad fragment number (%d >= %d)\n",

                            current_fragment, s->fragment_count);

                        return 1;

                    }

                    s->all_fragments[current_fragment].motion_x = motion_x[k];

                    s->all_fragments[current_fragment].motion_y = motion_y[k];

                    debug_vectors("    vector %d: fragment %d = (%d, %d)\n",

                        k, current_fragment, motion_x[k], motion_y[k]);

                }

            }

        }

    }

    return 0;

}


static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce)

{

    int start, i, j, w;

    if (sce->ics.clip_avoidance_factor < 1.0f) {

        for (w = 0; w < sce->ics.num_windows; w++) {

            start = 0;

            for (i = 0; i < sce->ics.max_sfb; i++) {

                float *swb_coeffs = sce->coeffs + start + w*128;

                for (j = 0; j < sce->ics.swb_sizes[i]; j++)

                    swb_coeffs[j] *= sce->ics.clip_avoidance_factor;

                start += sce->ics.swb_sizes[i];

            }

        }

    }

}


static void sdhci_end_transfer(SDHCIState *s)

{

    /* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */

    if ((s->trnmod & SDHC_TRNS_ACMD12) != 0) {

        SDRequest request;

        uint8_t response[16];

        request.cmd = 0x0C;

        request.arg = 0;

        DPRINT_L1("Automatically issue CMD%d %08x\n", request.cmd, request.arg);

        sdbus_do_command(&s->sdbus, &request, response);

        /* Auto CMD12 response goes to the upper Response register */

        s->rspreg[3] = (response[0] << 24) | (response[1] << 16) |

                (response[2] << 8) | response[3];

    }

    s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE |

            SDHC_DAT_LINE_ACTIVE | SDHC_DATA_INHIBIT |

            SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE);

    if (s->norintstsen & SDHC_NISEN_TRSCMP) {

        s->norintsts |= SDHC_NIS_TRSCMP;

    }

    sdhci_update_irq(s);

}


int ff_ps_read_data(AVCodecContext *avctx, GetBitContext *gb_host, PSContext *ps, int bits_left)

{

    int e;

    int bit_count_start = get_bits_count(gb_host);

    int header;

    int bits_consumed;

    GetBitContext gbc = *gb_host, *gb = &gbc;

    header = get_bits1(gb);

    if (header) {     //enable_ps_header

        ps->enable_iid = get_bits1(gb);

        if (ps->enable_iid) {

            int iid_mode = get_bits(gb, 3);

            if (iid_mode > 5) {

                av_log(avctx, AV_LOG_ERROR, "iid_mode %d is reserved.\n",

                       iid_mode);

                goto err;

            }

            ps->nr_iid_par    = nr_iidicc_par_tab[iid_mode];

            ps->iid_quant     = iid_mode > 2;

            ps->nr_ipdopd_par = nr_iidopd_par_tab[iid_mode];

        }

        ps->enable_icc = get_bits1(gb);

        if (ps->enable_icc) {

            ps->icc_mode = get_bits(gb, 3);

            if (ps->icc_mode > 5) {

                av_log(avctx, AV_LOG_ERROR, "icc_mode %d is reserved.\n",

                       ps->icc_mode);

                goto err;

            }

            ps->nr_icc_par = nr_iidicc_par_tab[ps->icc_mode];

        }

        ps->enable_ext = get_bits1(gb);

    }

    ps->frame_class = get_bits1(gb);

    ps->num_env_old = ps->num_env;

    ps->num_env     = num_env_tab[ps->frame_class][get_bits(gb, 2)];

    ps->border_position[0] = -1;

    if (ps->frame_class) {

        for (e = 1; e <= ps->num_env; e++)

            ps->border_position[e] = get_bits(gb, 5);

    } else

        for (e = 1; e <= ps->num_env; e++)

            ps->border_position[e] = (e * numQMFSlots >> ff_log2_tab[ps->num_env]) - 1;

    if (ps->enable_iid) {

        for (e = 0; e < ps->num_env; e++) {

            int dt = get_bits1(gb);

            if (read_iid_data(avctx, gb, ps, ps->iid_par, huff_iid[2*dt+ps->iid_quant], e, dt))

                goto err;

        }

    } else

    if (ps->enable_icc)

        for (e = 0; e < ps->num_env; e++) {

            int dt = get_bits1(gb);

            if (read_icc_data(avctx, gb, ps, ps->icc_par, dt ? huff_icc_dt : huff_icc_df, e, dt))

                goto err;

        }

    else

    if (ps->enable_ext) {

        int cnt = get_bits(gb, 4);

        if (cnt == 15) {

            cnt += get_bits(gb, 8);

        }

        cnt *= 8;

        while (cnt > 7) {

            int ps_extension_id = get_bits(gb, 2);

            cnt -= 2 + ps_read_extension_data(gb, ps, ps_extension_id);

        }

        if (cnt < 0) {

            av_log(avctx, AV_LOG_ERROR, "ps extension overflow %d\n", cnt);

            goto err;

        }

        skip_bits(gb, cnt);

    }

    ps->enable_ipdopd &= !PS_BASELINE;

    //Fix up envelopes

    if (!ps->num_env || ps->border_position[ps->num_env] < numQMFSlots - 1) {

        //Create a fake envelope

        int source = ps->num_env ? ps->num_env - 1 : ps->num_env_old - 1;

        if (source >= 0 && source != ps->num_env) {

            if (ps->enable_iid) {

                memcpy(ps->iid_par+ps->num_env, ps->iid_par+source, sizeof(ps->iid_par[0]));

            }

            if (ps->enable_icc) {

                memcpy(ps->icc_par+ps->num_env, ps->icc_par+source, sizeof(ps->icc_par[0]));

            }

            if (ps->enable_ipdopd) {

                memcpy(ps->ipd_par+ps->num_env, ps->ipd_par+source, sizeof(ps->ipd_par[0]));

                memcpy(ps->opd_par+ps->num_env, ps->opd_par+source, sizeof(ps->opd_par[0]));

            }

        }

        ps->num_env++;

        ps->border_position[ps->num_env] = numQMFSlots - 1;

    }

    ps->is34bands_old = ps->is34bands;

    if (!PS_BASELINE && (ps->enable_iid || ps->enable_icc))

        ps->is34bands = (ps->enable_iid && ps->nr_iid_par == 34) ||

                        (ps->enable_icc && ps->nr_icc_par == 34);

    //Baseline

    if (!ps->enable_ipdopd) {

    }

    if (header)

        ps->start = 1;

    bits_consumed = get_bits_count(gb) - bit_count_start;

    if (bits_consumed <= bits_left) {

        skip_bits_long(gb_host, bits_consumed);

        return bits_consumed;

    }

    av_log(avctx, AV_LOG_ERROR, "Expected to read %d PS bits actually read %d.\n", bits_left, bits_consumed);

err:

    ps->start = 0;

    skip_bits_long(gb_host, bits_left);

    return bits_left;

}


ff_vorbis_comment(AVFormatContext * as, AVDictionary **m, const uint8_t *buf, int size)

{

    const uint8_t *p = buf;

    const uint8_t *end = buf + size;

    unsigned n, j;

    int s;

    if (size < 8) /* must have vendor_length and user_comment_list_length */

        return -1;

    s = bytestream_get_le32(&p);

    if (end - p - 4 < s || s < 0)

        return -1;

    p += s;

    n = bytestream_get_le32(&p);

    while (end - p >= 4 && n > 0) {

        const char *t, *v;

        int tl, vl;

        s = bytestream_get_le32(&p);

        if (end - p < s || s < 0)

            break;

        t = p;

        p += s;

        n--;

        v = memchr(t, '=', s);

        if (!v)

            continue;

        tl = v - t;

        vl = s - tl - 1;

        v++;

        if (tl && vl) {

            char *tt, *ct;

            tt = av_malloc(tl + 1);

            ct = av_malloc(vl + 1);

            if (!tt || !ct) {

                av_freep(&tt);

                av_log(as, AV_LOG_WARNING, "out-of-memory error. skipping VorbisComment tag.\n");

                continue;

            }

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

                tt[j] = av_toupper(t[j]);

            tt[tl] = 0;

            memcpy(ct, v, vl);

            ct[vl] = 0;

            if (!strcmp(tt, "METADATA_BLOCK_PICTURE")) {

                int ret;

                char *pict = av_malloc(vl);

                if (!pict) {

                    av_log(as, AV_LOG_WARNING, "out-of-memory error. Skipping cover art block.\n");

                    continue;

                }

                if ((ret = av_base64_decode(pict, ct, vl)) > 0)

                    ret = ff_flac_parse_picture(as, pict, ret);

                av_freep(&pict);

                if (ret < 0) {

                    av_log(as, AV_LOG_WARNING, "Failed to parse cover art block.\n");

                    continue;

                }

            } else if (!ogm_chapter(as, tt, ct))

                av_dict_set(m, tt, ct,

                                   AV_DICT_DONT_STRDUP_KEY |

                                   AV_DICT_DONT_STRDUP_VAL);

        }

    }

    if (p != end)

        av_log(as, AV_LOG_INFO, "%ti bytes of comment header remain\n", end-p);

    if (n > 0)

        av_log(as, AV_LOG_INFO,

               "truncated comment header, %i comments not found\n", n);

    ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);

    return 0;

}


static void *do_touch_pages(void *arg)

{

    MemsetThread *memset_args = (MemsetThread *)arg;

    char *addr = memset_args->addr;

    uint64_t numpages = memset_args->numpages;

    uint64_t hpagesize = memset_args->hpagesize;

    sigset_t set, oldset;

    int i = 0;

    /* unblock SIGBUS */

    sigemptyset(&set);

    sigaddset(&set, SIGBUS);

    pthread_sigmask(SIG_UNBLOCK, &set, &oldset);

    if (sigsetjmp(memset_args->env, 1)) {

        memset_thread_failed = true;

    } else {

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

            memset(addr, 0, 1);

            addr += hpagesize;

        }

    }

    pthread_sigmask(SIG_SETMASK, &oldset, NULL);

    return NULL;

}


static int raw_decode(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    int linesize_align = 4;

    RawVideoContext *context = avctx->priv_data;

    AVFrame   *frame   = data;

    AVPicture *picture = data;

    frame->pict_type        = avctx->coded_frame->pict_type;

    frame->interlaced_frame = avctx->coded_frame->interlaced_frame;

    frame->top_field_first = avctx->coded_frame->top_field_first;

    frame->reordered_opaque = avctx->reordered_opaque;

    frame->pkt_pts          = avctx->pkt->pts;

    frame->pkt_pos          = avctx->pkt->pos;

    if(context->tff>=0){

        frame->interlaced_frame = 1;

        frame->top_field_first  = context->tff;

    }

    if(buf_size < context->length - (avctx->pix_fmt==PIX_FMT_PAL8 ? 256*4 : 0))

        return -1;

    if (avctx->width <= 0 || avctx->height <= 0) {

        av_log(avctx, AV_LOG_ERROR, "w/h is invalid\n");

        return AVERROR(EINVAL);

    }

    //2bpp and 4bpp raw in avi and mov (yes this is ugly ...)

    if (context->buffer) {

        int i;

        uint8_t *dst = context->buffer;

        buf_size = context->length - 256*4;

        if (avctx->bits_per_coded_sample == 4){

            for(i=0; 2*i+1 < buf_size && i<avpkt->size; i++){

                dst[2*i+0]= buf[i]>>4;

                dst[2*i+1]= buf[i]&15;

            }

            linesize_align = 8;

        } else {

            for(i=0; 4*i+3 < buf_size && i<avpkt->size; i++){

                dst[4*i+0]= buf[i]>>6;

                dst[4*i+1]= buf[i]>>4&3;

                dst[4*i+2]= buf[i]>>2&3;

                dst[4*i+3]= buf[i]   &3;

            }

            linesize_align = 16;

        }

        buf= dst;

    }

    if(avctx->codec_tag == MKTAG('A', 'V', '1', 'x') ||

       avctx->codec_tag == MKTAG('A', 'V', 'u', 'p'))

        buf += buf_size - context->length;

    avpicture_fill(picture, buf, avctx->pix_fmt, avctx->width, avctx->height);

    if((avctx->pix_fmt==PIX_FMT_PAL8 && buf_size < context->length) ||

       (av_pix_fmt_descriptors[avctx->pix_fmt].flags & PIX_FMT_PSEUDOPAL)) {

        frame->data[1]= context->palette;

    }

    if (avctx->pix_fmt == PIX_FMT_PAL8) {

        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, NULL);

        if (pal) {

            memcpy(frame->data[1], pal, AVPALETTE_SIZE);

            frame->palette_has_changed = 1;

        }

    }

    if((avctx->pix_fmt==PIX_FMT_BGR24    ||

        avctx->pix_fmt==PIX_FMT_GRAY8    ||

        avctx->pix_fmt==PIX_FMT_RGB555LE ||

        avctx->pix_fmt==PIX_FMT_RGB555BE ||

        avctx->pix_fmt==PIX_FMT_RGB565LE ||

        avctx->pix_fmt==PIX_FMT_MONOWHITE ||

        avctx->pix_fmt==PIX_FMT_PAL8) &&

        FFALIGN(frame->linesize[0], linesize_align)*avctx->height <= buf_size)

        frame->linesize[0] = FFALIGN(frame->linesize[0], linesize_align);

    if(context->flip)

        flip(avctx, picture);

    if (   avctx->codec_tag == MKTAG('Y', 'V', '1', '2')

        || avctx->codec_tag == MKTAG('Y', 'V', '1', '6')

        || avctx->codec_tag == MKTAG('Y', 'V', '2', '4')

        || avctx->codec_tag == MKTAG('Y', 'V', 'U', '9'))

        FFSWAP(uint8_t *, picture->data[1], picture->data[2]);

    if(avctx->codec_tag == AV_RL32("yuv2") &&

       avctx->pix_fmt   == PIX_FMT_YUYV422) {

        int x, y;

        uint8_t *line = picture->data[0];

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

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

                line[2*x + 1] ^= 0x80;

            line += picture->linesize[0];

        }

    }

    *data_size = sizeof(AVPicture);

    return buf_size;

}


static int oma_read_header(AVFormatContext *s)

{

    int     ret, framesize, jsflag, samplerate;

    uint32_t codec_params, channel_id;

    int16_t eid;

    uint8_t buf[EA3_HEADER_SIZE];

    uint8_t *edata;

    AVStream *st;

    ID3v2ExtraMeta *extra_meta = NULL;

    OMAContext *oc = s->priv_data;

    ff_id3v2_read(s, ID3v2_EA3_MAGIC, &extra_meta);

    ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);

    if (ret < EA3_HEADER_SIZE)

        return -1;

    if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}), 3) ||

        buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {

        av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");

        return AVERROR_INVALIDDATA;

    }

    oc->content_start = avio_tell(s->pb);

    /* encrypted file */

    eid = AV_RB16(&buf[6]);

    if (eid != -1 && eid != -128 && decrypt_init(s, extra_meta, buf) < 0) {

        ff_id3v2_free_extra_meta(&extra_meta);

        return -1;

    }

    ff_id3v2_free_extra_meta(&extra_meta);

    codec_params = AV_RB24(&buf[33]);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->start_time = 0;

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_tag  = buf[32];

    st->codec->codec_id   = ff_codec_get_id(ff_oma_codec_tags,

                                            st->codec->codec_tag);

    switch (buf[32]) {

    case OMA_CODECID_ATRAC3:

        samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;

        if (!samplerate) {

            av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");

            return AVERROR_INVALIDDATA;

        }

        if (samplerate != 44100)

            avpriv_request_sample(s, "Sample rate %d", samplerate);

        framesize = (codec_params & 0x3FF) * 8;

        /* get stereo coding mode, 1 for joint-stereo */

        jsflag = (codec_params >> 17) & 1;

        st->codec->channels    = 2;

        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

        st->codec->sample_rate = samplerate;

        st->codec->bit_rate    = st->codec->sample_rate * framesize * 8 / 1024;

        /* fake the ATRAC3 extradata

         * (wav format, makes stream copy to wav work) */

        if (ff_alloc_extradata(st->codec, 14))

            return AVERROR(ENOMEM);

        edata = st->codec->extradata;

        AV_WL16(&edata[0],  1);             // always 1

        AV_WL32(&edata[2],  samplerate);    // samples rate

        AV_WL16(&edata[6],  jsflag);        // coding mode

        AV_WL16(&edata[8],  jsflag);        // coding mode

        AV_WL16(&edata[10], 1);             // always 1

        // AV_WL16(&edata[12], 0);          // always 0

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

        break;

    case OMA_CODECID_ATRAC3P:

        channel_id = (codec_params >> 10) & 7;

        if (!channel_id) {

            av_log(s, AV_LOG_ERROR,

                   "Invalid ATRAC-X channel id: %"PRIu32"\n", channel_id);

            return AVERROR_INVALIDDATA;

        }

        st->codec->channel_layout = ff_oma_chid_to_native_layout[channel_id - 1];

        st->codec->channels       = ff_oma_chid_to_num_channels[channel_id - 1];

        framesize = ((codec_params & 0x3FF) * 8) + 8;

        samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;

        if (!samplerate) {

            av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");

            return AVERROR_INVALIDDATA;

        }

        st->codec->sample_rate = samplerate;

        st->codec->bit_rate    = samplerate * framesize * 8 / 2048;

        avpriv_set_pts_info(st, 64, 1, samplerate);

        break;

    case OMA_CODECID_MP3:

        st->need_parsing = AVSTREAM_PARSE_FULL_RAW;

        framesize = 1024;

        break;

    case OMA_CODECID_LPCM:

        /* PCM 44.1 kHz 16 bit stereo big-endian */

        st->codec->channels = 2;

        st->codec->channel_layout = AV_CH_LAYOUT_STEREO;

        st->codec->sample_rate = 44100;

        framesize = 1024;

        /* bit rate = sample rate x PCM block align (= 4) x 8 */

        st->codec->bit_rate = st->codec->sample_rate * 32;

        st->codec->bits_per_coded_sample =

            av_get_bits_per_sample(st->codec->codec_id);

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

        break;

    default:

        av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n", buf[32]);

        return AVERROR(ENOSYS);

    }

    st->codec->block_align = framesize;

    return 0;

}


void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,

                               int linesize_align[AV_NUM_DATA_POINTERS])

{

    int i;

    int w_align= 1;

    int h_align= 1;

    switch(s->pix_fmt){

    case PIX_FMT_YUV420P:

    case PIX_FMT_YUYV422:

    case PIX_FMT_UYVY422:

    case PIX_FMT_YUV422P:

    case PIX_FMT_YUV440P:

    case PIX_FMT_YUV444P:

    case PIX_FMT_GBRP:

    case PIX_FMT_GRAY8:

    case PIX_FMT_GRAY16BE:

    case PIX_FMT_GRAY16LE:

    case PIX_FMT_YUVJ420P:

    case PIX_FMT_YUVJ422P:

    case PIX_FMT_YUVJ440P:

    case PIX_FMT_YUVJ444P:

    case PIX_FMT_YUVA420P:

    case PIX_FMT_YUVA444P:

    case PIX_FMT_YUV420P9LE:

    case PIX_FMT_YUV420P9BE:

    case PIX_FMT_YUV420P10LE:

    case PIX_FMT_YUV420P10BE:

    case PIX_FMT_YUV422P9LE:

    case PIX_FMT_YUV422P9BE:

    case PIX_FMT_YUV422P10LE:

    case PIX_FMT_YUV422P10BE:

    case PIX_FMT_YUV444P9LE:

    case PIX_FMT_YUV444P9BE:

    case PIX_FMT_YUV444P10LE:

    case PIX_FMT_YUV444P10BE:

    case PIX_FMT_GBRP9LE:

    case PIX_FMT_GBRP9BE:

    case PIX_FMT_GBRP10LE:

    case PIX_FMT_GBRP10BE:

        w_align = 16; //FIXME assume 16 pixel per macroblock

        h_align = 16 * 2; // interlaced needs 2 macroblocks height

        break;

    case PIX_FMT_YUV411P:

    case PIX_FMT_UYYVYY411:

        w_align=32;

        h_align=8;

        break;

    case PIX_FMT_YUV410P:

        if(s->codec_id == CODEC_ID_SVQ1){

            w_align=64;

            h_align=64;

        }

    case PIX_FMT_RGB555:

        if(s->codec_id == CODEC_ID_RPZA){

            w_align=4;

            h_align=4;

        }

    case PIX_FMT_PAL8:

    case PIX_FMT_BGR8:

    case PIX_FMT_RGB8:

        if(s->codec_id == CODEC_ID_SMC){

            w_align=4;

            h_align=4;

        }

        break;

    case PIX_FMT_BGR24:

        if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){

            w_align=4;

            h_align=4;

        }

        break;

    default:

        w_align= 1;

        h_align= 1;

        break;

    }

    if(s->codec_id == CODEC_ID_IFF_ILBM || s->codec_id == CODEC_ID_IFF_BYTERUN1){

        w_align= FFMAX(w_align, 8);

    }

    *width = FFALIGN(*width , w_align);

    *height= FFALIGN(*height, h_align);

    if (s->codec_id == CODEC_ID_H264)

        *height+=2; // some of the optimized chroma MC reads one line too much

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

        linesize_align[i] = STRIDE_ALIGN;

}


static int decode_mb_i(AVSContext *h, int cbp_code)

{

    GetBitContext *gb = &h->gb;

    unsigned pred_mode_uv;

    int block;

    uint8_t top[18];

    uint8_t *left = NULL;

    uint8_t *d;

    ff_cavs_init_mb(h);

    /* get intra prediction modes from stream */

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

        int nA, nB, predpred;

        int pos = scan3x3[block];

        nA = h->pred_mode_Y[pos - 1];

        nB = h->pred_mode_Y[pos - 3];

        predpred = FFMIN(nA, nB);

        if (predpred == NOT_AVAIL) // if either is not available

            predpred = INTRA_L_LP;

        if (!get_bits1(gb)) {

            int rem_mode = get_bits(gb, 2);

            predpred     = rem_mode + (rem_mode >= predpred);

        }

        h->pred_mode_Y[pos] = predpred;

    }

    pred_mode_uv = get_ue_golomb(gb);

    if (pred_mode_uv > 6) {

        av_log(h->avctx, AV_LOG_ERROR, "illegal intra chroma pred mode\n");

        return AVERROR_INVALIDDATA;

    }

    ff_cavs_modify_mb_i(h, &pred_mode_uv);

    /* get coded block pattern */

    if (h->cur.f->pict_type == AV_PICTURE_TYPE_I)

        cbp_code = get_ue_golomb(gb);

    if (cbp_code > 63) {

        av_log(h->avctx, AV_LOG_ERROR, "illegal intra cbp\n");

        return AVERROR_INVALIDDATA;

    }

    h->cbp = cbp_tab[cbp_code][0];

    if (h->cbp && !h->qp_fixed)

        h->qp = (h->qp + get_se_golomb(gb)) & 63; //qp_delta

    /* luma intra prediction interleaved with residual decode/transform/add */

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

        d = h->cy + h->luma_scan[block];

        ff_cavs_load_intra_pred_luma(h, top, &left, block);

        h->intra_pred_l[h->pred_mode_Y[scan3x3[block]]]

            (d, top, left, h->l_stride);

        if (h->cbp & (1<<block))

            decode_residual_block(h, gb, intra_dec, 1, h->qp, d, h->l_stride);

    }

    /* chroma intra prediction */

    ff_cavs_load_intra_pred_chroma(h);

    h->intra_pred_c[pred_mode_uv](h->cu, &h->top_border_u[h->mbx * 10],

                                  h->left_border_u, h->c_stride);

    h->intra_pred_c[pred_mode_uv](h->cv, &h->top_border_v[h->mbx * 10],

                                  h->left_border_v, h->c_stride);

    decode_residual_chroma(h);

    ff_cavs_filter(h, I_8X8);

    set_mv_intra(h);

    return 0;

}


static int gif_read_image(GifState *s)

{

    int left, top, width, height, bits_per_pixel, code_size, flags;

    int is_interleaved, has_local_palette, y, pass, y1, linesize, n, i;

    uint8_t *ptr, *spal, *palette, *ptr1;

    left = bytestream_get_le16(&s->bytestream);

    top = bytestream_get_le16(&s->bytestream);

    width = bytestream_get_le16(&s->bytestream);

    height = bytestream_get_le16(&s->bytestream);

    flags = bytestream_get_byte(&s->bytestream);

    is_interleaved = flags & 0x40;

    has_local_palette = flags & 0x80;

    bits_per_pixel = (flags & 0x07) + 1;

    av_dlog(s->avctx, "gif: image x=%d y=%d w=%d h=%d\n", left, top, width, height);

    if (has_local_palette) {

        bytestream_get_buffer(&s->bytestream, s->local_palette, 3 * (1 << bits_per_pixel));

        palette = s->local_palette;

    } else {

        palette = s->global_palette;

        bits_per_pixel = s->bits_per_pixel;

    }

    /* verify that all the image is inside the screen dimensions */

    if (left + width > s->screen_width ||

        top + height > s->screen_height)

        return AVERROR(EINVAL);

    /* build the palette */

    n = (1 << bits_per_pixel);

    spal = palette;

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

        s->image_palette[i] = (0xff << 24) | AV_RB24(spal);

        spal += 3;

    }

    for(; i < 256; i++)

        s->image_palette[i] = (0xff << 24);

    /* handle transparency */

    if (s->transparent_color_index >= 0)

        s->image_palette[s->transparent_color_index] = 0;

    /* now get the image data */

    code_size = bytestream_get_byte(&s->bytestream);

    ff_lzw_decode_init(s->lzw, code_size, s->bytestream,

                       s->bytestream_end - s->bytestream, FF_LZW_GIF);

    /* read all the image */

    linesize = s->picture.linesize[0];

    ptr1 = s->picture.data[0] + top * linesize + left;

    ptr = ptr1;

    pass = 0;

    y1 = 0;

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

        ff_lzw_decode(s->lzw, ptr, width);

        if (is_interleaved) {

            switch(pass) {

            default:

            case 0:

            case 1:

                y1 += 8;

                ptr += linesize * 8;

                if (y1 >= height) {

                    y1 = pass ? 2 : 4;

                    ptr = ptr1 + linesize * y1;

                    pass++;

                }

                break;

            case 2:

                y1 += 4;

                ptr += linesize * 4;

                if (y1 >= height) {

                    y1 = 1;

                    ptr = ptr1 + linesize;

                    pass++;

                }

                break;

            case 3:

                y1 += 2;

                ptr += linesize * 2;

                break;

            }

        } else {

            ptr += linesize;

        }

    }

    /* read the garbage data until end marker is found */

    ff_lzw_decode_tail(s->lzw);

    s->bytestream = ff_lzw_cur_ptr(s->lzw);

    return 0;

}


static int mkv_write_tags(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    int i, ret;

    ff_metadata_conv_ctx(s, ff_mkv_metadata_conv, NULL);

    if (mkv_check_tag(s->metadata, 0)) {

        ret = mkv_write_tag(s, s->metadata, 0, 0, &mkv->tags);

        if (ret < 0) return ret;

    }

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

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

        if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)

            continue;

        if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID))

            continue;

        ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags);

        if (ret < 0) return ret;

    }

    if (s->pb->seekable && !mkv->is_live) {

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

            AVIOContext *pb;

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

            ebml_master tag_target;

            ebml_master tag;

            if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT)

                continue;

            mkv_write_tag_targets(s, MATROSKA_ID_TAGTARGETS_TRACKUID, i + 1, &mkv->tags, &tag_target);

            pb = mkv->tags_bc;

            tag = start_ebml_master(pb, MATROSKA_ID_SIMPLETAG, 0);

            put_ebml_string(pb, MATROSKA_ID_TAGNAME, "DURATION");

            mkv->stream_duration_offsets[i] = avio_tell(pb);

            // Reserve space to write duration as a 20-byte string.

            // 2 (ebml id) + 1 (data size) + 20 (data)

            put_ebml_void(pb, 23);

            end_ebml_master(pb, tag);

            end_ebml_master(pb, tag_target);

        }

    }

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

        AVChapter *ch = s->chapters[i];

        if (!mkv_check_tag(ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID))

            continue;

        ret = mkv_write_tag(s, ch->metadata, MATROSKA_ID_TAGTARGETS_CHAPTERUID, ch->id + mkv->chapter_id_offset, &mkv->tags);

        if (ret < 0) return ret;

    }

    if (mkv->have_attachments) {

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

            mkv_attachment *attachment = &mkv->attachments->entries[i];

            AVStream *st = s->streams[attachment->stream_idx];

            if (!mkv_check_tag(st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID))

                continue;

            ret = mkv_write_tag(s, st->metadata, MATROSKA_ID_TAGTARGETS_ATTACHUID, attachment->fileuid, &mkv->tags);

            if (ret < 0)

                return ret;

        }

    }

    if (mkv->tags.pos) {

        if (s->pb->seekable && !mkv->is_live)

            put_ebml_void(s->pb, avio_tell(mkv->tags_bc));

        else

            end_ebml_master_crc32(s->pb, &mkv->tags_bc, mkv, mkv->tags);

    }

    return 0;

}


static int hls_delete_old_segments(HLSContext *hls) {

    HLSSegment *segment, *previous_segment = NULL;

    float playlist_duration = 0.0f;

    int ret = 0, path_size, sub_path_size;

    char *dirname = NULL, *p, *sub_path;

    char *path = NULL;

    segment = hls->segments;

    while (segment) {

        playlist_duration += segment->duration;

        segment = segment->next;

    }

    segment = hls->old_segments;

    while (segment) {

        playlist_duration -= segment->duration;

        previous_segment = segment;

        segment = previous_segment->next;

        if (playlist_duration <= -previous_segment->duration) {

            previous_segment->next = NULL;

            break;

        }

    }

    if (segment && !hls->use_localtime_mkdir) {

        if (hls->segment_filename) {

            dirname = av_strdup(hls->segment_filename);

        } else {

            dirname = av_strdup(hls->avf->filename);

        }

        if (!dirname) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        p = (char *)av_basename(dirname);

        *p = '\0';

    }

    while (segment) {

        av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",

                                  segment->filename);

        path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;

        path = av_malloc(path_size);

        if (!path) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (hls->use_localtime_mkdir)

            av_strlcpy(path, segment->filename, path_size);

        else { // segment->filename contains basename only

            av_strlcpy(path, dirname, path_size);

            av_strlcat(path, segment->filename, path_size);

        }

        if (unlink(path) < 0) {

            av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",

                                     path, strerror(errno));

        }

        if (segment->sub_filename[0] != '\0') {

            sub_path_size = strlen(dirname) + strlen(segment->sub_filename) + 1;

            sub_path = av_malloc(sub_path_size);

            if (!sub_path) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            av_strlcpy(sub_path, dirname, sub_path_size);

            av_strlcat(sub_path, segment->sub_filename, sub_path_size);

            if (unlink(sub_path) < 0) {

                av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",

                                         sub_path, strerror(errno));

            }

            av_free(sub_path);

        }

        av_freep(&path);

        previous_segment = segment;

        segment = previous_segment->next;

        av_free(previous_segment);

    }

fail:

    av_free(path);

    av_free(dirname);

    return ret;

}


qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,

                           uint64_t bytes, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    QEMUIOVector hd_qiov;

    struct iovec iov;

    z_stream strm;

    int ret, out_len;

    uint8_t *buf, *out_buf;

    uint64_t cluster_offset;

    buf = qemu_blockalign(bs, s->cluster_size);

    if (bytes != s->cluster_size) {

        if (bytes > s->cluster_size ||

            offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)

        {

            qemu_vfree(buf);

            return -EINVAL;

        }

        /* Zero-pad last write if image size is not cluster aligned */

        memset(buf + bytes, 0, s->cluster_size - bytes);

    }

    qemu_iovec_to_buf(qiov, 0, buf, qiov->size);

    out_buf = g_malloc(s->cluster_size);

    /* best compression, small window, no zlib header */

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

    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,

                       Z_DEFLATED, -12,

                       9, Z_DEFAULT_STRATEGY);

    if (ret != 0) {

        ret = -EINVAL;

        goto fail;

    }

    strm.avail_in = s->cluster_size;

    strm.next_in = (uint8_t *)buf;

    strm.avail_out = s->cluster_size;

    strm.next_out = out_buf;

    ret = deflate(&strm, Z_FINISH);

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

        deflateEnd(&strm);

        ret = -EINVAL;

        goto fail;

    }

    out_len = strm.next_out - out_buf;

    deflateEnd(&strm);

    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {

        /* could not compress: write normal cluster */

        ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,

                             bytes >> BDRV_SECTOR_BITS, qiov);

        if (ret < 0) {

            goto fail;

        }

        goto success;

    }

    qemu_co_mutex_lock(&s->lock);

    cluster_offset = get_cluster_offset(bs, offset, 2, out_len, 0, 0);

    qemu_co_mutex_unlock(&s->lock);

    if (cluster_offset == 0) {

        ret = -EIO;

        goto fail;

    }

    cluster_offset &= s->cluster_offset_mask;

    iov = (struct iovec) {

        .iov_base   = out_buf,

        .iov_len    = out_len,

    };

    qemu_iovec_init_external(&hd_qiov, &iov, 1);

    ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);

    if (ret < 0) {

        goto fail;

    }

success:

    ret = 0;

fail:

    qemu_vfree(buf);

    g_free(out_buf);

    return ret;

}


static int fifo_put(SerialState *s, int fifo, uint8_t chr)

{

    SerialFIFO *f = (fifo) ? &s->recv_fifo : &s->xmit_fifo;

    f->data[f->head++] = chr;

    if (f->head == UART_FIFO_LENGTH)

        f->head = 0;

    f->count++;

    return 1;

}


static void rc4030_reset(DeviceState *dev)

{

    rc4030State *s = RC4030(dev);

    int i;

    s->config = 0x410; /* some boards seem to accept 0x104 too */

    s->revision = 1;

    s->invalid_address_register = 0;

    memset(s->dma_regs, 0, sizeof(s->dma_regs));

    rc4030_dma_tt_update(s, 0, 0);

    s->remote_failed_address = s->memory_failed_address = 0;

    s->cache_maint = 0;

    s->cache_ptag = s->cache_ltag = 0;

    s->cache_bmask = 0;

    s->memory_refresh_rate = 0x18186;

    s->nvram_protect = 7;

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

        s->rem_speed[i] = 7;

    s->imr_jazz = 0x10; /* XXX: required by firmware, but why? */

    s->isr_jazz = 0;

    s->itr = 0;

    qemu_irq_lower(s->timer_irq);

    qemu_irq_lower(s->jazz_bus_irq);

}


static void encode_refpass(Jpeg2000T1Context *t1, int width, int height, int *nmsedec, int bpno)

{

    int y0, x, y, mask = 1 << (bpno + NMSEDEC_FRACBITS);

    for (y0 = 0; y0 < height; y0 += 4)

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

            for (y = y0; y < height && y < y0+4; y++)

                if ((t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG){

                    int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y+1][x+1]);

                    *nmsedec += getnmsedec_ref(t1->data[y][x], bpno + NMSEDEC_FRACBITS);

                    ff_mqc_encode(&t1->mqc, t1->mqc.cx_states + ctxno, t1->data[y][x] & mask ? 1:0);

                    t1->flags[y+1][x+1] |= JPEG2000_T1_REF;

                }

}


void visit_optional(Visitor *v, bool *present, const char *name,

                    Error **errp)

{

    if (!error_is_set(errp) && v->optional) {

        v->optional(v, present, name, errp);

    }

}


static int ws_snd_decode_frame(AVCodecContext *avctx,

                void *data, int *data_size,

                AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

//    WSSNDContext *c = avctx->priv_data;

    int in_size, out_size;

    int sample = 128;

    int i;

    uint8_t *samples = data;

    if (!buf_size)

        return 0;

    out_size = AV_RL16(&buf[0]);

    in_size = AV_RL16(&buf[2]);

    buf += 4;

    if (out_size > *data_size) {

        av_log(avctx, AV_LOG_ERROR, "Frame is too large to fit in buffer\n");

        return -1;

    }

    if (in_size > buf_size) {

        av_log(avctx, AV_LOG_ERROR, "Frame data is larger than input buffer\n");

        return -1;

    }

    *data_size = out_size;

    if (in_size == out_size) {

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

            *samples++ = *buf++;

        return buf_size;

    }

    while (out_size > 0) {

        int code;

        uint8_t count;

        code = (*buf) >> 6;

        count = (*buf) & 0x3F;

        buf++;

        switch(code) {

        case 0: /* ADPCM 2-bit */

            for (count++; count > 0; count--) {

                code = *buf++;

                sample += ws_adpcm_2bit[code & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 2) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 4) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_2bit[(code >> 6) & 0x3];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                out_size -= 4;

            }

            break;

        case 1: /* ADPCM 4-bit */

            for (count++; count > 0; count--) {

                code = *buf++;

                sample += ws_adpcm_4bit[code & 0xF];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                sample += ws_adpcm_4bit[code >> 4];

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                out_size -= 2;

            }

            break;

        case 2: /* no compression */

            if (count & 0x20) { /* big delta */

                int8_t t;

                t = count;

                t <<= 3;

                sample += t >> 3;

                sample = av_clip_uint8(sample);

                *samples++ = sample;

                out_size--;

            } else { /* copy */

                for (count++; count > 0; count--) {

                    *samples++ = *buf++;

                    out_size--;

                }

                sample = buf[-1];

            }

            break;

        default: /* run */

            for(count++; count > 0; count--) {

                *samples++ = sample;

                out_size--;

            }

        }

    }

    return buf_size;

}


static int mb_var_thread(AVCodecContext *c, void *arg){

    MpegEncContext *s= *(void**)arg;

    int mb_x, mb_y;

    for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {

        for(mb_x=0; mb_x < s->mb_width; mb_x++) {

            int xx = mb_x * 16;

            int yy = mb_y * 16;

            uint8_t *pix = s->new_picture.f.data[0] + (yy * s->linesize) + xx;

            int varc;

            int sum = s->dsp.pix_sum(pix, s->linesize);

            varc = (s->dsp.pix_norm1(pix, s->linesize) - (((unsigned)sum*sum)>>8) + 500 + 128)>>8;

            s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;

            s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;

            s->me.mb_var_sum_temp    += varc;

        }

    }

    return 0;

}


int inet_listen_opts(QemuOpts *opts, int port_offset)

{

    struct addrinfo ai,*res,*e;

    const char *addr;

    char port[33];

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int slisten,rc,to,try_next;

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

    ai.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    if (qemu_opt_get(opts, "port") == NULL) {

        fprintf(stderr, "%s: host and/or port not specified\n", __FUNCTION__);

        return -1;

    }

    pstrcpy(port, sizeof(port), qemu_opt_get(opts, "port"));

    addr = qemu_opt_get(opts, "host");

    to = qemu_opt_get_number(opts, "to", 0);

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    /* lookup */

    if (port_offset)

        snprintf(port, sizeof(port), "%d", atoi(port) + port_offset);

    rc = getaddrinfo(strlen(addr) ? addr : NULL, port, &ai, &res);

    if (rc != 0) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

        return -1;

    }

    if (sockets_debug)

        inet_print_addrinfo(__FUNCTION__, res);

    /* create socket + bind */

    for (e = res; e != NULL; e = e->ai_next) {

        getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

		        uaddr,INET6_ADDRSTRLEN,uport,32,

		        NI_NUMERICHOST | NI_NUMERICSERV);

        slisten = socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (slisten < 0) {

            fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__,

                    inet_strfamily(e->ai_family), strerror(errno));

            continue;

        }

        setsockopt(slisten,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));

#ifdef IPV6_V6ONLY

        if (e->ai_family == PF_INET6) {

            /* listen on both ipv4 and ipv6 */

            setsockopt(slisten,IPPROTO_IPV6,IPV6_V6ONLY,(void*)&off,

                sizeof(off));

        }

#endif

        for (;;) {

            if (bind(slisten, e->ai_addr, e->ai_addrlen) == 0) {

                if (sockets_debug)

                    fprintf(stderr,"%s: bind(%s,%s,%d): OK\n", __FUNCTION__,

                        inet_strfamily(e->ai_family), uaddr, inet_getport(e));

                goto listen;

            }

            try_next = to && (inet_getport(e) <= to + port_offset);

            if (!try_next || sockets_debug)

                fprintf(stderr,"%s: bind(%s,%s,%d): %s\n", __FUNCTION__,

                        inet_strfamily(e->ai_family), uaddr, inet_getport(e),

                        strerror(errno));

            if (try_next) {

                inet_setport(e, inet_getport(e) + 1);

                continue;

            }

            break;

        }

        closesocket(slisten);

    }

    fprintf(stderr, "%s: FAILED\n", __FUNCTION__);

    freeaddrinfo(res);

    return -1;

listen:

    if (listen(slisten,1) != 0) {

        perror("listen");

        closesocket(slisten);

        freeaddrinfo(res);

        return -1;

    }

    snprintf(uport, sizeof(uport), "%d", inet_getport(e) - port_offset);

    qemu_opt_set(opts, "host", uaddr);

    qemu_opt_set(opts, "port", uport);

    qemu_opt_set(opts, "ipv6", (e->ai_family == PF_INET6) ? "on" : "off");

    qemu_opt_set(opts, "ipv4", (e->ai_family != PF_INET6) ? "on" : "off");

    freeaddrinfo(res);

    return slisten;

}


static int socket_open_listen(struct sockaddr_in *my_addr)

{

    int server_fd, tmp;

    server_fd = socket(AF_INET,SOCK_STREAM,0);

    if (server_fd < 0) {

        perror ("socket");

        return -1;

    }

    tmp = 1;

    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));

    if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {

        char bindmsg[32];

        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));

        perror (bindmsg);

        closesocket(server_fd);

        return -1;

    }

    if (listen (server_fd, 5) < 0) {

        perror ("listen");

        closesocket(server_fd);

        return -1;

    }

    ff_socket_nonblock(server_fd, 1);

    return server_fd;

}


static uint64_t pxa2xx_gpio_read(void *opaque, hwaddr offset,

                                 unsigned size)

{

    PXA2xxGPIOInfo *s = (PXA2xxGPIOInfo *) opaque;

    uint32_t ret;

    int bank;

    if (offset >= 0x200)

        return 0;

    bank = pxa2xx_gpio_regs[offset].bank;

    switch (pxa2xx_gpio_regs[offset].reg) {

    case GPDR:		/* GPIO Pin-Direction registers */

        return s->dir[bank];

    case GPSR:		/* GPIO Pin-Output Set registers */

        printf("%s: Read from a write-only register " REG_FMT "\n",

                        __FUNCTION__, offset);

        return s->gpsr[bank];	/* Return last written value.  */

    case GPCR:		/* GPIO Pin-Output Clear registers */

        printf("%s: Read from a write-only register " REG_FMT "\n",

                        __FUNCTION__, offset);

        return 31337;		/* Specified as unpredictable in the docs.  */

    case GRER:		/* GPIO Rising-Edge Detect Enable registers */

        return s->rising[bank];

    case GFER:		/* GPIO Falling-Edge Detect Enable registers */

        return s->falling[bank];

    case GAFR_L:	/* GPIO Alternate Function registers */

        return s->gafr[bank * 2];

    case GAFR_U:	/* GPIO Alternate Function registers */

        return s->gafr[bank * 2 + 1];

    case GPLR:		/* GPIO Pin-Level registers */

        ret = (s->olevel[bank] & s->dir[bank]) |

                (s->ilevel[bank] & ~s->dir[bank]);

        qemu_irq_raise(s->read_notify);

        return ret;

    case GEDR:		/* GPIO Edge Detect Status registers */

        return s->status[bank];

    default:

        hw_error("%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);

    }

    return 0;

}


static void aux_slave_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *k = DEVICE_CLASS(klass);

    set_bit(DEVICE_CATEGORY_MISC, k->categories);

    k->bus_type = TYPE_AUX_BUS;

}


static void vmdk_close(BlockDriverState *bs)

{

    BDRVVmdkState *s = bs->opaque;

    qemu_free(s->l1_table);

    qemu_free(s->l2_cache);

    bdrv_delete(s->hd);

    // try to close parent image, if exist

    vmdk_parent_close(s->hd);

}


static void *file_ram_alloc(RAMBlock *block,

                            ram_addr_t memory,

                            const char *path,

                            Error **errp)

{

    bool unlink_on_error = false;

    char *filename;

    char *sanitized_name;

    char *c;

    void *area = MAP_FAILED;

    int fd = -1;

    int64_t file_size;

    if (kvm_enabled() && !kvm_has_sync_mmu()) {

        error_setg(errp,

                   "host lacks kvm mmu notifiers, -mem-path unsupported");

        return NULL;

    }

    for (;;) {

        fd = open(path, O_RDWR);

        if (fd >= 0) {

            /* @path names an existing file, use it */

            break;

        }

        if (errno == ENOENT) {

            /* @path names a file that doesn't exist, create it */

            fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0644);

            if (fd >= 0) {

                unlink_on_error = true;

                break;

            }

        } else if (errno == EISDIR) {

            /* @path names a directory, create a file there */

            /* Make name safe to use with mkstemp by replacing '/' with '_'. */

            sanitized_name = g_strdup(memory_region_name(block->mr));

            for (c = sanitized_name; *c != '\0'; c++) {

                if (*c == '/') {

                    *c = '_';

                }

            }

            filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,

                                       sanitized_name);

            g_free(sanitized_name);

            fd = mkstemp(filename);

            if (fd >= 0) {

                unlink(filename);

                g_free(filename);

                break;

            }

            g_free(filename);

        }

        if (errno != EEXIST && errno != EINTR) {

            error_setg_errno(errp, errno,

                             "can't open backing store %s for guest RAM",

                             path);

            goto error;

        }

        /*

         * Try again on EINTR and EEXIST.  The latter happens when

         * something else creates the file between our two open().

         */

    }

    block->page_size = qemu_fd_getpagesize(fd);

    block->mr->align = block->page_size;

#if defined(__s390x__)

    if (kvm_enabled()) {

        block->mr->align = MAX(block->mr->align, QEMU_VMALLOC_ALIGN);

    }

#endif

    file_size = get_file_size(fd);

    if (memory < block->page_size) {

        error_setg(errp, "memory size 0x" RAM_ADDR_FMT " must be equal to "

                   "or larger than page size 0x%zx",

                   memory, block->page_size);

        goto error;

    }

    if (file_size > 0 && file_size < memory) {

        error_setg(errp, "backing store %s size 0x%" PRIx64

                   " does not match 'size' option 0x" RAM_ADDR_FMT,

                   path, file_size, memory);

        goto error;

    }

    memory = ROUND_UP(memory, block->page_size);

    /*

     * ftruncate is not supported by hugetlbfs in older

     * hosts, so don't bother bailing out on errors.

     * If anything goes wrong with it under other filesystems,

     * mmap will fail.

     *

     * Do not truncate the non-empty backend file to avoid corrupting

     * the existing data in the file. Disabling shrinking is not

     * enough. For example, the current vNVDIMM implementation stores

     * the guest NVDIMM labels at the end of the backend file. If the

     * backend file is later extended, QEMU will not be able to find

     * those labels. Therefore, extending the non-empty backend file

     * is disabled as well.

     */

    if (!file_size && ftruncate(fd, memory)) {

        perror("ftruncate");

    }

    area = qemu_ram_mmap(fd, memory, block->mr->align,

                         block->flags & RAM_SHARED);

    if (area == MAP_FAILED) {

        error_setg_errno(errp, errno,

                         "unable to map backing store for guest RAM");

        goto error;

    }

    if (mem_prealloc) {

        os_mem_prealloc(fd, area, memory, errp);

        if (errp && *errp) {

            goto error;

        }

    }

    block->fd = fd;

    return area;

error:

    if (area != MAP_FAILED) {

        qemu_ram_munmap(area, memory);

    }

    if (unlink_on_error) {

        unlink(path);

    }

    if (fd != -1) {

        close(fd);

    }

    return NULL;

}


static void qpeg_decode_inter(const uint8_t *src, uint8_t *dst, int size,

                            int stride, int width, int height,

                            int delta, const uint8_t *ctable, uint8_t *refdata)

{

    int i, j;

    int code;

    int filled = 0;

    int orig_height;

    if(!refdata)

        refdata= dst;

    /* copy prev frame */

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

        memcpy(dst + (i * stride), refdata + (i * stride), width);

    orig_height = height;

    height--;

    dst = dst + height * stride;

    while((size > 0) && (height >= 0)) {

        code = *src++;

        size--;

        if(delta) {

            /* motion compensation */

            while((code & 0xF0) == 0xF0) {

                if(delta == 1) {

                    int me_idx;

                    int me_w, me_h, me_x, me_y;

                    uint8_t *me_plane;

                    int corr, val;

                    /* get block size by index */

                    me_idx = code & 0xF;

                    me_w = qpeg_table_w[me_idx];

                    me_h = qpeg_table_h[me_idx];

                    /* extract motion vector */

                    corr = *src++;

                    size--;

                    val = corr >> 4;

                    if(val > 7)

                        val -= 16;

                    me_x = val;

                    val = corr & 0xF;

                    if(val > 7)

                        val -= 16;

                    me_y = val;

                    /* check motion vector */

                    if ((me_x + filled < 0) || (me_x + me_w + filled > width) ||

                       (height - me_y - me_h < 0) || (height - me_y > orig_height) ||

                       (filled + me_w > width) || (height - me_h < 0))

                        av_log(NULL, AV_LOG_ERROR, "Bogus motion vector (%i,%i), block size %ix%i at %i,%i\n",

                               me_x, me_y, me_w, me_h, filled, height);

                    else {

                        /* do motion compensation */

                        me_plane = refdata + (filled + me_x) + (height - me_y) * stride;

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

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

                                dst[filled + i - (j * stride)] = me_plane[i - (j * stride)];

                        }

                    }

                }

                code = *src++;

                size--;

            }

        }

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

            break;

        if(code > 0xE0) { /* run code: 0xE1..0xFF */

            int p;

            code &= 0x1F;

            p = *src++;

            size--;

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

                dst[filled++] = p;

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if(height < 0)

                        break;

                }

            }

        } else if(code >= 0xC0) { /* copy code: 0xC0..0xDF */

            code &= 0x1F;

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

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

                if(filled >= width) {

                    filled = 0;

                    dst -= stride;

                    height--;

                    if(height < 0)

                        break;

                }

            }

            size -= code + 1;

        } else if(code >= 0x80) { /* skip code: 0x80..0xBF */

            int skip;

            code &= 0x3F;

            /* codes 0x80 and 0x81 are actually escape codes,

               skip value minus constant is in the next byte */

            if(!code)

                skip = (*src++) + 64;

            else if(code == 1)

                skip = (*src++) + 320;

            else

                skip = code;

            filled += skip;

            while( filled >= width) {

                filled -= width;

                dst -= stride;

                height--;

                if(height < 0)

                    break;

            }

        } else {

            /* zero code treated as one-pixel skip */

            if(code)

                dst[filled++] = ctable[code & 0x7F];

            else

                filled++;

            if(filled >= width) {

                filled = 0;

                dst -= stride;

                height--;

            }

        }

    }

}


static void x86_cpu_apic_create(X86CPU *cpu, Error **errp)

{

    APICCommonState *apic;

    const char *apic_type = "apic";

    if (kvm_apic_in_kernel()) {

        apic_type = "kvm-apic";

    } else if (xen_enabled()) {

        apic_type = "xen-apic";

    }

    cpu->apic_state = DEVICE(object_new(apic_type));

    object_property_add_child(OBJECT(cpu), "lapic",

                              OBJECT(cpu->apic_state), &error_abort);

    qdev_prop_set_uint8(cpu->apic_state, "id", cpu->apic_id);

    /* TODO: convert to link<> */

    apic = APIC_COMMON(cpu->apic_state);

    apic->cpu = cpu;

    apic->apicbase = APIC_DEFAULT_ADDRESS | MSR_IA32_APICBASE_ENABLE;

}


bool migration_has_failed(MigrationState *s)

{

    return (s->state == MIG_STATE_CANCELLED ||

            s->state == MIG_STATE_ERROR);

}