static int ljpeg_decode_rgb_scan(MJpegDecodeContext *s, int nb_components, int predictor, int point_transform)
{
    int i, mb_x, mb_y;
    uint16_t (*buffer)[4];
    int left[4], top[4], topleft[4];
    const int linesize = s->linesize[0];
    const int mask     = (1 << s->bits) - 1;
    int resync_mb_y = 0;
    int resync_mb_x = 0;
    s->restart_count = s->restart_interval;
    av_fast_malloc(&s->ljpeg_buffer, &s->ljpeg_buffer_size,
                   (unsigned)s->mb_width * 4 * sizeof(s->ljpeg_buffer[0][0]));
    buffer = s->ljpeg_buffer;
    for (i = 0; i < 4; i++)
        buffer[0][i] = 1 << (s->bits - 1);
    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
        uint8_t *ptr = s->picture.data[0] + (linesize * mb_y);
        if (s->interlaced && s->bottom_field)
            ptr += linesize >> 1;
        for (i = 0; i < 4; i++)
            top[i] = left[i] = topleft[i] = buffer[0][i];
        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
            int modified_predictor = predictor;
            if (s->restart_interval && !s->restart_count){
                s->restart_count = s->restart_interval;
                resync_mb_x = mb_x;
                resync_mb_y = mb_y;
                for(i=0; i<4; i++)
                    top[i] = left[i]= topleft[i]= 1 << (s->bits - 1);
            }
            if (mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || !mb_x)
                modified_predictor = 1;
            for (i=0;i<nb_components;i++) {
                int pred, dc;
                topleft[i] = top[i];
                top[i]     = buffer[mb_x][i];
                PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
                dc = mjpeg_decode_dc(s, s->dc_index[i]);
                if(dc == 0xFFFF)
                    return -1;
                left[i] = buffer[mb_x][i] =
                    mask & (pred + (dc << point_transform));
            }
            if (s->restart_interval && !--s->restart_count) {
                align_get_bits(&s->gb);
                skip_bits(&s->gb, 16); /* skip RSTn */
            }
        }
        if (s->nb_components == 4) {
            for(i=0; i<nb_components; i++) {
                int c= s->comp_index[i];
                for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
                    ptr[4*mb_x+3-c] = buffer[mb_x][i];
                }
            }
        } else if (s->rct) {
            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
                ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2] - 0x200) >> 2);
                ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
                ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
            }
        } else if (s->pegasus_rct) {
            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {
                ptr[3*mb_x + 1] = buffer[mb_x][0] - ((buffer[mb_x][1] + buffer[mb_x][2]) >> 2);
                ptr[3*mb_x + 0] = buffer[mb_x][1] + ptr[3*mb_x + 1];
                ptr[3*mb_x + 2] = buffer[mb_x][2] + ptr[3*mb_x + 1];
            }
        } else {
            for(i=0; i<nb_components; i++) {
                int c= s->comp_index[i];
                for(mb_x = 0; mb_x < s->mb_width; mb_x++) {
                    ptr[3*mb_x+2-c] = buffer[mb_x][i];
                }
            }
        }
    }
    return 0;
}


static av_cold int vp8_init(AVCodecContext *avctx)

{

    VP8Context *ctx = avctx->priv_data;

    const struct vpx_codec_iface *iface = &vpx_codec_vp8_cx_algo;

    struct vpx_codec_enc_cfg enccfg;

    int res;

    av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());

    av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());

    if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",

               vpx_codec_err_to_string(res));

        return AVERROR(EINVAL);

    }

    dump_enc_cfg(avctx, &enccfg);

    enccfg.g_w            = avctx->width;

    enccfg.g_h            = avctx->height;

    enccfg.g_timebase.num = avctx->time_base.num;

    enccfg.g_timebase.den = avctx->time_base.den;

    enccfg.g_threads      = avctx->thread_count;

    enccfg.g_lag_in_frames= ctx->lag_in_frames;

    if (avctx->flags & CODEC_FLAG_PASS1)

        enccfg.g_pass = VPX_RC_FIRST_PASS;

    else if (avctx->flags & CODEC_FLAG_PASS2)

        enccfg.g_pass = VPX_RC_LAST_PASS;

    else

        enccfg.g_pass = VPX_RC_ONE_PASS;

    if (avctx->rc_min_rate == avctx->rc_max_rate &&

        avctx->rc_min_rate == avctx->bit_rate)

        enccfg.rc_end_usage = VPX_CBR;

    else if (ctx->crf)

        enccfg.rc_end_usage = VPX_CQ;

    enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,

                                              AV_ROUND_NEAR_INF);

    if (avctx->qmin > 0)

        enccfg.rc_min_quantizer = avctx->qmin;

    if (avctx->qmax > 0)

        enccfg.rc_max_quantizer = avctx->qmax;

    enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;

    //0-100 (0 => CBR, 100 => VBR)

    enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);

    enccfg.rc_2pass_vbr_minsection_pct     =

        avctx->rc_min_rate * 100LL / avctx->bit_rate;

    if (avctx->rc_max_rate)

        enccfg.rc_2pass_vbr_maxsection_pct =

            avctx->rc_max_rate * 100LL / avctx->bit_rate;

    if (avctx->rc_buffer_size)

        enccfg.rc_buf_sz         =

            avctx->rc_buffer_size * 1000LL / avctx->bit_rate;

    if (avctx->rc_initial_buffer_occupancy)

        enccfg.rc_buf_initial_sz =

            avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;

    enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;

    enccfg.rc_undershoot_pct     = round(avctx->rc_buffer_aggressivity * 100);

    //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO

    if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)

        enccfg.kf_min_dist = avctx->keyint_min;

    if (avctx->gop_size >= 0)

        enccfg.kf_max_dist = avctx->gop_size;

    if (enccfg.g_pass == VPX_RC_FIRST_PASS)

        enccfg.g_lag_in_frames = 0;

    else if (enccfg.g_pass == VPX_RC_LAST_PASS) {

        int decode_size;

        if (!avctx->stats_in) {

            av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");

            return AVERROR_INVALIDDATA;

        }

        ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;

        ctx->twopass_stats.buf = av_malloc(ctx->twopass_stats.sz);

        if (!ctx->twopass_stats.buf) {

            av_log(avctx, AV_LOG_ERROR,

                   "Stat buffer alloc (%zu bytes) failed\n",

                   ctx->twopass_stats.sz);

            return AVERROR(ENOMEM);

        }

        decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,

                                       ctx->twopass_stats.sz);

        if (decode_size < 0) {

            av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");

            return AVERROR_INVALIDDATA;

        }

        ctx->twopass_stats.sz      = decode_size;

        enccfg.rc_twopass_stats_in = ctx->twopass_stats;

    }

    /* 0-3: For non-zero values the encoder increasingly optimizes for reduced

       complexity playback on low powered devices at the expense of encode

       quality. */

   if (avctx->profile != FF_PROFILE_UNKNOWN)

       enccfg.g_profile = avctx->profile;

    enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;

    dump_enc_cfg(avctx, &enccfg);

    /* Construct Encoder Context */

    res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);

    if (res != VPX_CODEC_OK) {

        log_encoder_error(avctx, "Failed to initialize encoder");

        return AVERROR(EINVAL);

    }

    //codec control failures are currently treated only as warnings

    av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");

    if (ctx->cpu_used != INT_MIN)

        codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);

    if (ctx->flags & VP8F_AUTO_ALT_REF)

        ctx->auto_alt_ref = 1;

    if (ctx->auto_alt_ref >= 0)

        codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);

    if (ctx->arnr_max_frames >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);

    if (ctx->arnr_strength >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);

    if (ctx->arnr_type >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);

    codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);

    codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));

    codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  avctx->mb_threshold);

    codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);

    if (ctx->max_intra_rate >= 0)

        codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);

    av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);

    //provide dummy value to initialize wrapper, values will be updated each _encode()

    vpx_img_wrap(&ctx->rawimg, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,

                 (unsigned char*)1);

    avctx->coded_frame = avcodec_alloc_frame();

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");

        vp8_free(avctx);

        return AVERROR(ENOMEM);

    }

    return 0;

}


unsigned long virtio_load_direct(ulong rec_list1, ulong rec_list2,

                                 ulong subchan_id, void *load_addr)

{

    u8 status;

    int sec = rec_list1;

    int sec_num = ((rec_list2 >> 32) & 0xffff) + 1;

    int sec_len = rec_list2 >> 48;

    ulong addr = (ulong)load_addr;

    if (sec_len != virtio_get_block_size()) {

        return -1;

    }

    sclp_print(".");

    status = virtio_read_many(sec, (void *)addr, sec_num);

    if (status) {

        virtio_panic("I/O Error");

    }

    addr += sec_num * virtio_get_block_size();

    return addr;

}


void restore_boot_order(void *opaque)

{

    char *normal_boot_order = opaque;

    static int first = 1;

    /* Restore boot order and remove ourselves after the first boot */

    if (first) {

        first = 0;

        return;

    }

    qemu_boot_set(normal_boot_order, NULL);

    qemu_unregister_reset(restore_boot_order, normal_boot_order);

    g_free(normal_boot_order);

}


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

                                 int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    const uint8_t *buf_end;

    int buf_size = avpkt->size;

    VmdAudioContext *s = avctx->priv_data;

    int block_type, silent_chunks, audio_chunks;

    int ret;

    uint8_t *output_samples_u8;

    int16_t *output_samples_s16;

    if (buf_size < 16) {

        av_log(avctx, AV_LOG_WARNING, "skipping small junk packet\n");

        *got_frame_ptr = 0;

        return buf_size;

    }

    block_type = buf[6];

    if (block_type < BLOCK_TYPE_AUDIO || block_type > BLOCK_TYPE_SILENCE) {

        av_log(avctx, AV_LOG_ERROR, "unknown block type: %d\n", block_type);

        return AVERROR(EINVAL);

    }

    buf      += 16;

    buf_size -= 16;

    /* get number of silent chunks */

    silent_chunks = 0;

    if (block_type == BLOCK_TYPE_INITIAL) {

        uint32_t flags;

        if (buf_size < 4) {

            av_log(avctx, AV_LOG_ERROR, "packet is too small\n");

            return AVERROR(EINVAL);

        }

        flags         = AV_RB32(buf);

        silent_chunks = av_popcount(flags);

        buf      += 4;

        buf_size -= 4;

    } else if (block_type == BLOCK_TYPE_SILENCE) {

        silent_chunks = 1;

        buf_size = 0; // should already be zero but set it just to be sure

    }

    /* ensure output buffer is large enough */

    audio_chunks = buf_size / s->chunk_size;

    /* get output buffer */

    frame->nb_samples = ((silent_chunks + audio_chunks) * avctx->block_align) /

                        avctx->channels;

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    output_samples_u8  =            frame->data[0];

    output_samples_s16 = (int16_t *)frame->data[0];

    /* decode silent chunks */

    if (silent_chunks > 0) {

        int silent_size = avctx->block_align * silent_chunks;

        if (s->out_bps == 2) {

            memset(output_samples_s16, 0x00, silent_size * 2);

            output_samples_s16 += silent_size;

        } else {

            memset(output_samples_u8,  0x80, silent_size);

            output_samples_u8 += silent_size;

        }

    }

    /* decode audio chunks */

    if (audio_chunks > 0) {

        buf_end = buf + buf_size;

        while (buf < buf_end) {

            if (s->out_bps == 2) {

                decode_audio_s16(output_samples_s16, buf, s->chunk_size,

                                 avctx->channels);

                output_samples_s16 += avctx->block_align;

            } else {

                memcpy(output_samples_u8, buf, s->chunk_size);

                output_samples_u8  += avctx->block_align;

            }

            buf += s->chunk_size;

        }

    }

    *got_frame_ptr = 1;

    return avpkt->size;

}


static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)

{

    int i;

    AVBPrint buf;

    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);

    for (i = 0; i < sub->num_rects; i++) {

        char *final_dialog;

        const char *dialog;

        AVSubtitleRect *rect = sub->rects[i];

        int ts_start, ts_duration = -1;

        long int layer;

        if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue ", 10))

            continue;

        av_bprint_clear(&buf);

        /* skip ReadOrder */

        dialog = strchr(rect->ass, ',');

        if (!dialog)

            continue;

        dialog++;

        /* extract Layer or Marked */

        layer = strtol(dialog, (char**)&dialog, 10);

        if (*dialog != ',')

            continue;

        dialog++;

        /* rescale timing to ASS time base (ms) */

        ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));

        if (pkt->duration != -1)

            ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));

        sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);

        /* construct ASS (standalone file form with timestamps) string */

        av_bprintf(&buf, "Dialogue: %ld,", layer);

        insert_ts(&buf, ts_start);

        insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);

        av_bprintf(&buf, "%s\r\n", dialog);

        final_dialog = av_strdup(buf.str);

        if (!av_bprint_is_complete(&buf) || !final_dialog) {

            av_freep(&final_dialog);

            av_bprint_finalize(&buf, NULL);

            return AVERROR(ENOMEM);

        }

        av_freep(&rect->ass);

        rect->ass = final_dialog;

    }

    av_bprint_finalize(&buf, NULL);

    return 0;

}


static av_cold int bmp_encode_init(AVCodecContext *avctx){

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_BGR24:

        avctx->bits_per_coded_sample = 24;

        break;

    case AV_PIX_FMT_RGB555:

    case AV_PIX_FMT_RGB565:

    case AV_PIX_FMT_RGB444:

        avctx->bits_per_coded_sample = 16;

        break;

    case AV_PIX_FMT_RGB8:

    case AV_PIX_FMT_BGR8:

    case AV_PIX_FMT_RGB4_BYTE:

    case AV_PIX_FMT_BGR4_BYTE:

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_PAL8:

        avctx->bits_per_coded_sample = 8;

        break;

    case AV_PIX_FMT_MONOBLACK:

        avctx->bits_per_coded_sample = 1;

        break;

    default:

        av_log(avctx, AV_LOG_INFO, "unsupported pixel format\n");

        return -1;

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


static int ape_read_header(AVFormatContext * s)

{

    AVIOContext *pb = s->pb;

    APEContext *ape = s->priv_data;

    AVStream *st;

    uint32_t tag;

    int i;

    int total_blocks, final_size = 0;

    int64_t pts, file_size;

    /* Skip any leading junk such as id3v2 tags */

    ape->junklength = avio_tell(pb);

    tag = avio_rl32(pb);

    if (tag != MKTAG('M', 'A', 'C', ' '))

        return -1;

    ape->fileversion = avio_rl16(pb);

    if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {

        av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n",

               ape->fileversion / 1000, (ape->fileversion % 1000) / 10);

        return -1;

    }

    if (ape->fileversion >= 3980) {

        ape->padding1             = avio_rl16(pb);

        ape->descriptorlength     = avio_rl32(pb);

        ape->headerlength         = avio_rl32(pb);

        ape->seektablelength      = avio_rl32(pb);

        ape->wavheaderlength      = avio_rl32(pb);

        ape->audiodatalength      = avio_rl32(pb);

        ape->audiodatalength_high = avio_rl32(pb);

        ape->wavtaillength        = avio_rl32(pb);

        avio_read(pb, ape->md5, 16);

        /* Skip any unknown bytes at the end of the descriptor.

           This is for future compatibility */

        if (ape->descriptorlength > 52)

            avio_skip(pb, ape->descriptorlength - 52);

        /* Read header data */

        ape->compressiontype      = avio_rl16(pb);

        ape->formatflags          = avio_rl16(pb);

        ape->blocksperframe       = avio_rl32(pb);

        ape->finalframeblocks     = avio_rl32(pb);

        ape->totalframes          = avio_rl32(pb);

        ape->bps                  = avio_rl16(pb);

        ape->channels             = avio_rl16(pb);

        ape->samplerate           = avio_rl32(pb);

    } else {

        ape->descriptorlength = 0;

        ape->headerlength = 32;

        ape->compressiontype      = avio_rl16(pb);

        ape->formatflags          = avio_rl16(pb);

        ape->channels             = avio_rl16(pb);

        ape->samplerate           = avio_rl32(pb);

        ape->wavheaderlength      = avio_rl32(pb);

        ape->wavtaillength        = avio_rl32(pb);

        ape->totalframes          = avio_rl32(pb);

        ape->finalframeblocks     = avio_rl32(pb);

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {

            avio_skip(pb, 4); /* Skip the peak level */

            ape->headerlength += 4;

        }

        if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {

            ape->seektablelength = avio_rl32(pb);

            ape->headerlength += 4;

            ape->seektablelength *= sizeof(int32_t);

        } else

            ape->seektablelength = ape->totalframes * sizeof(int32_t);

        if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)

            ape->bps = 8;

        else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)

            ape->bps = 24;

        else

            ape->bps = 16;

        if (ape->fileversion >= 3950)

            ape->blocksperframe = 73728 * 4;

        else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800  && ape->compressiontype >= 4000))

            ape->blocksperframe = 73728;

        else

            ape->blocksperframe = 9216;

        /* Skip any stored wav header */

        if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))

            avio_skip(pb, ape->wavheaderlength);

    }

    if(!ape->totalframes){

        av_log(s, AV_LOG_ERROR, "No frames in the file!\n");

        return AVERROR(EINVAL);

    }

    if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){

        av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",

               ape->totalframes);

        return -1;

    }

    if (ape->seektablelength / sizeof(*ape->seektable) < ape->totalframes) {

        av_log(s, AV_LOG_ERROR,

               "Number of seek entries is less than number of frames: %zu vs. %"PRIu32"\n",

               ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);

        return AVERROR_INVALIDDATA;

    }

    ape->frames       = av_malloc(ape->totalframes * sizeof(APEFrame));

    if(!ape->frames)

        return AVERROR(ENOMEM);

    ape->firstframe   = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;

    if (ape->fileversion < 3810)

        ape->firstframe += ape->totalframes;

    ape->currentframe = 0;

    ape->totalsamples = ape->finalframeblocks;

    if (ape->totalframes > 1)

        ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);

    if (ape->seektablelength > 0) {

        ape->seektable = av_malloc(ape->seektablelength);

        if (!ape->seektable)

            return AVERROR(ENOMEM);

        for (i = 0; i < ape->seektablelength / sizeof(uint32_t) && !pb->eof_reached; i++)

            ape->seektable[i] = avio_rl32(pb);

        if (ape->fileversion < 3810) {

            ape->bittable = av_malloc(ape->totalframes);

            if (!ape->bittable)

                return AVERROR(ENOMEM);

            for (i = 0; i < ape->totalframes && !pb->eof_reached; i++)

                ape->bittable[i] = avio_r8(pb);

        }

    }

    ape->frames[0].pos     = ape->firstframe;

    ape->frames[0].nblocks = ape->blocksperframe;

    ape->frames[0].skip    = 0;

    for (i = 1; i < ape->totalframes; i++) {

        ape->frames[i].pos      = ape->seektable[i] + ape->junklength;

        ape->frames[i].nblocks  = ape->blocksperframe;

        ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;

        ape->frames[i].skip     = (ape->frames[i].pos - ape->frames[0].pos) & 3;

    }

    ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;

    /* calculate final packet size from total file size, if available */

    file_size = avio_size(pb);

    if (file_size > 0) {

        final_size = file_size - ape->frames[ape->totalframes - 1].pos -

                     ape->wavtaillength;

        final_size -= final_size & 3;

    }

    if (file_size <= 0 || final_size <= 0)

        final_size = ape->finalframeblocks * 8;

    ape->frames[ape->totalframes - 1].size = final_size;

    for (i = 0; i < ape->totalframes; i++) {

        if(ape->frames[i].skip){

            ape->frames[i].pos  -= ape->frames[i].skip;

            ape->frames[i].size += ape->frames[i].skip;

        }

        ape->frames[i].size = (ape->frames[i].size + 3) & ~3;

    }

    if (ape->fileversion < 3810) {

        for (i = 0; i < ape->totalframes; i++) {

            if (i < ape->totalframes - 1 && ape->bittable[i + 1])

                ape->frames[i].size += 4;

            ape->frames[i].skip <<= 3;

            ape->frames[i].skip  += ape->bittable[i];

        }

    }

    ape_dumpinfo(s, ape);

    av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",

           ape->fileversion / 1000, (ape->fileversion % 1000) / 10,

           ape->compressiontype);

    /* now we are ready: build format streams */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return -1;

    total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;

    st->codecpar->codec_type      = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_id        = AV_CODEC_ID_APE;

    st->codecpar->codec_tag       = MKTAG('A', 'P', 'E', ' ');

    st->codecpar->channels        = ape->channels;

    st->codecpar->sample_rate     = ape->samplerate;

    st->codecpar->bits_per_coded_sample = ape->bps;

    st->nb_frames = ape->totalframes;

    st->start_time = 0;

    st->duration  = total_blocks / MAC_SUBFRAME_SIZE;

    avpriv_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);

    st->codecpar->extradata = av_malloc(APE_EXTRADATA_SIZE);

    st->codecpar->extradata_size = APE_EXTRADATA_SIZE;

    AV_WL16(st->codecpar->extradata + 0, ape->fileversion);

    AV_WL16(st->codecpar->extradata + 2, ape->compressiontype);

    AV_WL16(st->codecpar->extradata + 4, ape->formatflags);

    pts = 0;

    for (i = 0; i < ape->totalframes; i++) {

        ape->frames[i].pts = pts;

        av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);

        pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;

    }

    /* try to read APE tags */

    if (pb->seekable) {

        ff_ape_parse_tag(s);

        avio_seek(pb, 0, SEEK_SET);

    }

    return 0;

}


static gboolean udp_chr_read(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    CharDriverState *chr = opaque;

    NetCharDriver *s = chr->opaque;

    gsize bytes_read = 0;

    GIOStatus status;

    if (s->max_size == 0) {

        return TRUE;

    }

    status = g_io_channel_read_chars(s->chan, (gchar *)s->buf, sizeof(s->buf),

                                     &bytes_read, NULL);

    s->bufcnt = bytes_read;

    s->bufptr = s->bufcnt;

    if (status != G_IO_STATUS_NORMAL) {

        if (s->tag) {

            g_source_remove(s->tag);

            s->tag = 0;

        }

        return FALSE;

    }

    s->bufptr = 0;

    while (s->max_size > 0 && s->bufptr < s->bufcnt) {

        qemu_chr_be_write(chr, &s->buf[s->bufptr], 1);

        s->bufptr++;

        s->max_size = qemu_chr_be_can_write(chr);

    }

    return TRUE;

}


static void pc_q35_init_1_4(QEMUMachineInitArgs *args)

{

    pc_sysfw_flash_vs_rom_bug_compatible = true;

    has_pvpanic = false;

    x86_cpu_compat_set_features("n270", FEAT_1_ECX, 0, CPUID_EXT_MOVBE);

    pc_q35_init(args);

}


void do_interrupt(CPUARMState *env)

{

    uint32_t addr;

    uint32_t mask;

    int new_mode;

    uint32_t offset;

    if (IS_M(env)) {

        do_interrupt_v7m(env);

        return;

    }

    /* TODO: Vectored interrupt controller.  */

    switch (env->exception_index) {

    case EXCP_UDEF:

        new_mode = ARM_CPU_MODE_UND;

        addr = 0x04;

        mask = CPSR_I;

        if (env->thumb)

            offset = 2;

        else

            offset = 4;

        break;

    case EXCP_SWI:

        if (semihosting_enabled) {

            /* Check for semihosting interrupt.  */

            if (env->thumb) {

                mask = lduw_code(env->regs[15] - 2) & 0xff;

            } else {

                mask = ldl_code(env->regs[15] - 4) & 0xffffff;

            }

            /* Only intercept calls from privileged modes, to provide some

               semblance of security.  */

            if (((mask == 0x123456 && !env->thumb)

                    || (mask == 0xab && env->thumb))

                  && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        new_mode = ARM_CPU_MODE_SVC;

        addr = 0x08;

        mask = CPSR_I;

        /* The PC already points to the next instruction.  */

        offset = 0;

        break;

    case EXCP_BKPT:

        /* See if this is a semihosting syscall.  */

        if (env->thumb && semihosting_enabled) {

            mask = lduw_code(env->regs[15]) & 0xff;

            if (mask == 0xab

                  && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {

                env->regs[15] += 2;

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        env->cp15.c5_insn = 2;

        /* Fall through to prefetch abort.  */

    case EXCP_PREFETCH_ABORT:

        new_mode = ARM_CPU_MODE_ABT;

        addr = 0x0c;

        mask = CPSR_A | CPSR_I;

        offset = 4;

        break;

    case EXCP_DATA_ABORT:

        new_mode = ARM_CPU_MODE_ABT;

        addr = 0x10;

        mask = CPSR_A | CPSR_I;

        offset = 8;

        break;

    case EXCP_IRQ:

        new_mode = ARM_CPU_MODE_IRQ;

        addr = 0x18;

        /* Disable IRQ and imprecise data aborts.  */

        mask = CPSR_A | CPSR_I;

        offset = 4;

        break;

    case EXCP_FIQ:

        new_mode = ARM_CPU_MODE_FIQ;

        addr = 0x1c;

        /* Disable FIQ, IRQ and imprecise data aborts.  */

        mask = CPSR_A | CPSR_I | CPSR_F;

        offset = 4;

        break;

    default:

        cpu_abort(env, "Unhandled exception 0x%x\n", env->exception_index);

        return; /* Never happens.  Keep compiler happy.  */

    }

    /* High vectors.  */

    if (env->cp15.c1_sys & (1 << 13)) {

        addr += 0xffff0000;

    }

    switch_mode (env, new_mode);

    env->spsr = cpsr_read(env);

    /* Clear IT bits.  */

    env->condexec_bits = 0;

    /* Switch to the new mode, and to the correct instruction set.  */

    env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;

    env->uncached_cpsr |= mask;

    /* this is a lie, as the was no c1_sys on V4T/V5, but who cares

     * and we should just guard the thumb mode on V4 */

    if (arm_feature(env, ARM_FEATURE_V4T)) {

        env->thumb = (env->cp15.c1_sys & (1 << 30)) != 0;

    }

    env->regs[14] = env->regs[15] + offset;

    env->regs[15] = addr;

    env->interrupt_request |= CPU_INTERRUPT_EXITTB;

}


static void ERROR(const char *str)

{

        fprintf(stderr, "%s\n", str);

        exit(1);

}


static void handle_control_message(VirtIOSerial *vser, void *buf, size_t len)

{

    struct VirtIOSerialPort *port;

    struct virtio_console_control cpkt, *gcpkt;

    uint8_t *buffer;

    size_t buffer_len;

    gcpkt = buf;

    if (len < sizeof(cpkt)) {

        /* The guest sent an invalid control packet */

        return;

    }

    cpkt.event = lduw_p(&gcpkt->event);

    cpkt.value = lduw_p(&gcpkt->value);

    port = find_port_by_id(vser, ldl_p(&gcpkt->id));

    if (!port && cpkt.event != VIRTIO_CONSOLE_DEVICE_READY)

        return;

    switch(cpkt.event) {

    case VIRTIO_CONSOLE_DEVICE_READY:

        if (!cpkt.value) {

            error_report("virtio-serial-bus: Guest failure in adding device %s\n",

                         vser->bus->qbus.name);

            break;

        }

        /*

         * The device is up, we can now tell the device about all the

         * ports we have here.

         */

        QTAILQ_FOREACH(port, &vser->ports, next) {

            send_control_event(port, VIRTIO_CONSOLE_PORT_ADD, 1);

        }

        break;

    case VIRTIO_CONSOLE_PORT_READY:

        if (!cpkt.value) {

            error_report("virtio-serial-bus: Guest failure in adding port %u for device %s\n",

                         port->id, vser->bus->qbus.name);

            break;

        }

        /*

         * Now that we know the guest asked for the port name, we're

         * sure the guest has initialised whatever state is necessary

         * for this port. Now's a good time to let the guest know if

         * this port is a console port so that the guest can hook it

         * up to hvc.

         */

        if (port->is_console) {

            send_control_event(port, VIRTIO_CONSOLE_CONSOLE_PORT, 1);

        }

        if (port->name) {

            stw_p(&cpkt.event, VIRTIO_CONSOLE_PORT_NAME);

            stw_p(&cpkt.value, 1);

            buffer_len = sizeof(cpkt) + strlen(port->name) + 1;

            buffer = qemu_malloc(buffer_len);

            memcpy(buffer, &cpkt, sizeof(cpkt));

            memcpy(buffer + sizeof(cpkt), port->name, strlen(port->name));

            buffer[buffer_len - 1] = 0;

            send_control_msg(port, buffer, buffer_len);

            qemu_free(buffer);

        }

        if (port->host_connected) {

            send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN, 1);

        }

        /*

         * When the guest has asked us for this information it means

         * the guest is all setup and has its virtqueues

         * initialised. If some app is interested in knowing about

         * this event, let it know.

         */

        if (port->info->guest_ready) {

            port->info->guest_ready(port);

        }

        break;

    case VIRTIO_CONSOLE_PORT_OPEN:

        port->guest_connected = cpkt.value;

        if (cpkt.value && port->info->guest_open) {

            /* Send the guest opened notification if an app is interested */

            port->info->guest_open(port);

        }

        if (!cpkt.value && port->info->guest_close) {

            /* Send the guest closed notification if an app is interested */

            port->info->guest_close(port);

        }

        break;

    }

}


static int asf_write_header1(AVFormatContext *s, int64_t file_size,

                             int64_t data_chunk_size)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    AVDictionaryEntry *tags[5];

    int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;

    int has_title, has_aspect_ratio = 0;

    int metadata_count;

    AVCodecContext *enc;

    int64_t header_offset, cur_pos, hpos;

    int bit_rate;

    int64_t duration;

    ff_metadata_conv(&s->metadata, ff_asf_metadata_conv, NULL);

    tags[0] = av_dict_get(s->metadata, "title", NULL, 0);

    tags[1] = av_dict_get(s->metadata, "author", NULL, 0);

    tags[2] = av_dict_get(s->metadata, "copyright", NULL, 0);

    tags[3] = av_dict_get(s->metadata, "comment", NULL, 0);

    tags[4] = av_dict_get(s->metadata, "rating", NULL, 0);

    duration       = asf->duration + PREROLL_TIME * 10000;

    has_title      = tags[0] || tags[1] || tags[2] || tags[3] || tags[4];

    metadata_count = av_dict_count(s->metadata);

    bit_rate = 0;

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

        enc = s->streams[n]->codec;

        avpriv_set_pts_info(s->streams[n], 32, 1, 1000); /* 32 bit pts in ms */

        bit_rate += enc->bit_rate;

        if (   enc->codec_type == AVMEDIA_TYPE_VIDEO

            && enc->sample_aspect_ratio.num > 0

            && enc->sample_aspect_ratio.den > 0)

            has_aspect_ratio++;

    }

    if (asf->is_streamed) {

        put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */

    }

    ff_put_guid(pb, &ff_asf_header);

    avio_wl64(pb, -1); /* header length, will be patched after */

    avio_wl32(pb, 3 + has_title + !!metadata_count + s->nb_streams); /* number of chunks in header */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 2); /* ??? */

    /* file header */

    header_offset = avio_tell(pb);

    hpos          = put_header(pb, &ff_asf_file_header);

    ff_put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, file_size);

    file_time = 0;

    avio_wl64(pb, unix_to_file_time(file_time));

    avio_wl64(pb, asf->nb_packets); /* number of packets */

    avio_wl64(pb, duration); /* end time stamp (in 100ns units) */

    avio_wl64(pb, asf->duration); /* duration (in 100ns units) */

    avio_wl64(pb, PREROLL_TIME); /* start time stamp */

    avio_wl32(pb, (asf->is_streamed || !pb->seekable) ? 3 : 2);  /* ??? */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, s->packet_size); /* packet size */

    avio_wl32(pb, bit_rate ? bit_rate : -1); /* Maximum data rate in bps */

    end_header(pb, hpos);

    /* unknown headers */

    hpos = put_header(pb, &ff_asf_head1_guid);

    ff_put_guid(pb, &ff_asf_head2_guid);

    avio_wl16(pb, 6);

    if (has_aspect_ratio) {

        int64_t hpos2;

        avio_wl32(pb, 26 + has_aspect_ratio * 84);

        hpos2 = put_header(pb, &ff_asf_metadata_header);

        avio_wl16(pb, 2 * has_aspect_ratio);

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

            enc = s->streams[n]->codec;

            if (   enc->codec_type == AVMEDIA_TYPE_VIDEO

                && enc->sample_aspect_ratio.num > 0

                && enc->sample_aspect_ratio.den > 0) {

                AVRational sar = enc->sample_aspect_ratio;

                avio_wl16(pb, 0);

                // the stream number is set like this below

                avio_wl16(pb, n + 1);

                avio_wl16(pb, 26); // name_len

                avio_wl16(pb,  3); // value_type

                avio_wl32(pb,  4); // value_len

                avio_put_str16le(pb, "AspectRatioX");

                avio_wl32(pb, sar.num);

                avio_wl16(pb, 0);

                // the stream number is set like this below

                avio_wl16(pb, n + 1);

                avio_wl16(pb, 26); // name_len

                avio_wl16(pb,  3); // value_type

                avio_wl32(pb,  4); // value_len

                avio_put_str16le(pb, "AspectRatioY");

                avio_wl32(pb, sar.den);

            }

        }

        end_header(pb, hpos2);

    } else {

        avio_wl32(pb, 0);

    }

    end_header(pb, hpos);

    /* title and other infos */

    if (has_title) {

        int len;

        uint8_t *buf;

        AVIOContext *dyn_buf;

        if (avio_open_dyn_buf(&dyn_buf) < 0)

            return AVERROR(ENOMEM);

        hpos = put_header(pb, &ff_asf_comment_header);

        for (n = 0; n < FF_ARRAY_ELEMS(tags); n++) {

            len = tags[n] ? avio_put_str16le(dyn_buf, tags[n]->value) : 0;

            avio_wl16(pb, len);

        }

        len = avio_close_dyn_buf(dyn_buf, &buf);

        avio_write(pb, buf, len);

        av_freep(&buf);

        end_header(pb, hpos);

    }

    if (metadata_count) {

        AVDictionaryEntry *tag = NULL;

        hpos = put_header(pb, &ff_asf_extended_content_header);

        avio_wl16(pb, metadata_count);

        while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {

            put_str16(pb, tag->key);

            avio_wl16(pb, 0);

            put_str16(pb, tag->value);

        }

        end_header(pb, hpos);

    }

    /* chapters using ASF markers */

    if (!asf->is_streamed && s->nb_chapters) {

        int ret;

        if (ret = asf_write_markers(s))

            return ret;

    }

    /* stream headers */

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

        int64_t es_pos;

        //        ASFStream *stream = &asf->streams[n];

        enc                 = s->streams[n]->codec;

        asf->streams[n].num = n + 1;

        asf->streams[n].seq = 1;

        switch (enc->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            wav_extra_size = 0;

            extra_size     = 18 + wav_extra_size;

            extra_size2    = 8;

            break;

        default:

        case AVMEDIA_TYPE_VIDEO:

            wav_extra_size = enc->extradata_size;

            extra_size     = 0x33 + wav_extra_size;

            extra_size2    = 0;

            break;

        }

        hpos = put_header(pb, &ff_asf_stream_header);

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            ff_put_guid(pb, &ff_asf_audio_stream);

            ff_put_guid(pb, &ff_asf_audio_conceal_spread);

        } else {

            ff_put_guid(pb, &ff_asf_video_stream);

            ff_put_guid(pb, &ff_asf_video_conceal_none);

        }

        avio_wl64(pb, 0); /* ??? */

        es_pos = avio_tell(pb);

        avio_wl32(pb, extra_size); /* wav header len */

        avio_wl32(pb, extra_size2); /* additional data len */

        avio_wl16(pb, n + 1); /* stream number */

        avio_wl32(pb, 0); /* ??? */

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            /* WAVEFORMATEX header */

            int wavsize = ff_put_wav_header(pb, enc, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX);

            if (wavsize < 0)

                return -1;

            if (wavsize != extra_size) {

                cur_pos = avio_tell(pb);

                avio_seek(pb, es_pos, SEEK_SET);

                avio_wl32(pb, wavsize); /* wav header len */

                avio_seek(pb, cur_pos, SEEK_SET);

            }

            /* ERROR Correction */

            avio_w8(pb, 0x01);

            if (enc->codec_id == AV_CODEC_ID_ADPCM_G726 || !enc->block_align) {

                avio_wl16(pb, 0x0190);

                avio_wl16(pb, 0x0190);

            } else {

                avio_wl16(pb, enc->block_align);

                avio_wl16(pb, enc->block_align);

            }

            avio_wl16(pb, 0x01);

            avio_w8(pb, 0x00);

        } else {

            avio_wl32(pb, enc->width);

            avio_wl32(pb, enc->height);

            avio_w8(pb, 2); /* ??? */

            avio_wl16(pb, 40 + enc->extradata_size); /* size */

            /* BITMAPINFOHEADER header */

            ff_put_bmp_header(pb, enc, ff_codec_bmp_tags, 1, 0);

        }

        end_header(pb, hpos);

    }

    /* media comments */

    hpos = put_header(pb, &ff_asf_codec_comment_header);

    ff_put_guid(pb, &ff_asf_codec_comment1_header);

    avio_wl32(pb, s->nb_streams);

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

        const AVCodecDescriptor *codec_desc;

        const char *desc;

        enc  = s->streams[n]->codec;

        codec_desc = avcodec_descriptor_get(enc->codec_id);

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO)

            avio_wl16(pb, 2);

        else if (enc->codec_type == AVMEDIA_TYPE_VIDEO)

            avio_wl16(pb, 1);

        else

            avio_wl16(pb, -1);

        if (enc->codec_id == AV_CODEC_ID_WMAV2)

            desc = "Windows Media Audio V8";

        else

            desc = codec_desc ? codec_desc->name : NULL;

        if (desc) {

            AVIOContext *dyn_buf;

            uint8_t *buf;

            int len;

            if (avio_open_dyn_buf(&dyn_buf) < 0)

                return AVERROR(ENOMEM);

            avio_put_str16le(dyn_buf, desc);

            len = avio_close_dyn_buf(dyn_buf, &buf);

            avio_wl16(pb, len / 2); // "number of characters" = length in bytes / 2

            avio_write(pb, buf, len);

            av_freep(&buf);

        } else

            avio_wl16(pb, 0);

        avio_wl16(pb, 0); /* no parameters */

        /* id */

        if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {

            avio_wl16(pb, 2);

            avio_wl16(pb, enc->codec_tag);

        } else {

            avio_wl16(pb, 4);

            avio_wl32(pb, enc->codec_tag);

        }

        if (!enc->codec_tag)

            return -1;

    }

    end_header(pb, hpos);

    /* patch the header size fields */

    cur_pos     = avio_tell(pb);

    header_size = cur_pos - header_offset;

    if (asf->is_streamed) {

        header_size += 8 + 30 + DATA_HEADER_SIZE;

        avio_seek(pb, header_offset - 10 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        avio_seek(pb, header_offset - 2 - 30, SEEK_SET);

        avio_wl16(pb, header_size);

        header_size -= 8 + 30 + DATA_HEADER_SIZE;

    }

    header_size += 24 + 6;

    avio_seek(pb, header_offset - 14, SEEK_SET);

    avio_wl64(pb, header_size);

    avio_seek(pb, cur_pos, SEEK_SET);

    /* movie chunk, followed by packets of packet_size */

    asf->data_offset = cur_pos;

    ff_put_guid(pb, &ff_asf_data_header);

    avio_wl64(pb, data_chunk_size);

    ff_put_guid(pb, &ff_asf_my_guid);

    avio_wl64(pb, asf->nb_packets); /* nb packets */

    avio_w8(pb, 1); /* ??? */

    avio_w8(pb, 1); /* ??? */

    return 0;

}


static unsigned int codec_get_asf_tag(const CodecTag *tags, unsigned int id)

{

    while (tags->id != 0) {

        if (!tags->invalid_asf && tags->id == id)

            return tags->tag;

        tags++;

    }

    return 0;

}


static int decode_cblk(J2kDecoderContext *s, J2kCodingStyle *codsty, J2kT1Context *t1, J2kCblk *cblk,

                       int width, int height, int bandpos)

{

    int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y, clnpass_cnt = 0;

    int bpass_csty_symbol = J2K_CBLK_BYPASS & codsty->cblk_style;

    int vert_causal_ctx_csty_symbol = J2K_CBLK_VSC & codsty->cblk_style;

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

        memset(t1->flags[y], 0, (width+2)*sizeof(int));

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

        memset(t1->data[y], 0, width*sizeof(int));

    ff_mqc_initdec(&t1->mqc, cblk->data);

    cblk->data[cblk->length] = 0xff;

    cblk->data[cblk->length+1] = 0xff;

    while(passno--){

        switch(pass_t){

            case 0: decode_sigpass(t1, width, height, bpno+1, bandpos,

                                  bpass_csty_symbol && (clnpass_cnt >= 4), vert_causal_ctx_csty_symbol);

                    break;

            case 1: decode_refpass(t1, width, height, bpno+1);

                    if (bpass_csty_symbol && clnpass_cnt >= 4)

                        ff_mqc_initdec(&t1->mqc, cblk->data);

                    break;

            case 2: decode_clnpass(s, t1, width, height, bpno+1, bandpos,

                                   codsty->cblk_style & J2K_CBLK_SEGSYM);

                    clnpass_cnt = clnpass_cnt + 1;

                    if (bpass_csty_symbol && clnpass_cnt >= 4)

                       ff_mqc_initdec(&t1->mqc, cblk->data);

                    break;

        }

        pass_t++;

        if (pass_t == 3){

            bpno--;

            pass_t = 0;

        }

    }

    return 0;

}


static int do_token_out(USBDevice *s, USBPacket *p)

{

    if (p->devep != 0)

        return s->info->handle_data(s, p);

    switch(s->setup_state) {

    case SETUP_STATE_ACK:

        if (s->setup_buf[0] & USB_DIR_IN) {

            s->setup_state = SETUP_STATE_IDLE;

            /* transfer OK */

        } else {

            /* ignore additional output */

        }

        return 0;

    case SETUP_STATE_DATA:

        if (!(s->setup_buf[0] & USB_DIR_IN)) {

            int len = s->setup_len - s->setup_index;

            if (len > p->len)

                len = p->len;

            memcpy(s->data_buf + s->setup_index, p->data, len);

            s->setup_index += len;

            if (s->setup_index >= s->setup_len)

                s->setup_state = SETUP_STATE_ACK;

            return len;

        }

        s->setup_state = SETUP_STATE_IDLE;

        return USB_RET_STALL;

    default:

        return USB_RET_STALL;

    }

}


static int coroutine_fn blkreplay_co_pwrite_zeroes(BlockDriverState *bs,

    int64_t offset, int count, BdrvRequestFlags flags)

{

    uint64_t reqid = request_id++;

    int ret = bdrv_co_pwrite_zeroes(bs->file, offset, count, flags);

    block_request_create(reqid, bs, qemu_coroutine_self());

    qemu_coroutine_yield();

    return ret;

}


int ff_eac3_parse_header(AC3DecodeContext *s)

{

    int i, blk, ch;

    int ac3_exponent_strategy, parse_aht_info, parse_spx_atten_data;

    int parse_transient_proc_info;

    int num_cpl_blocks;

    GetBitContext *gbc = &s->gbc;

    /* An E-AC-3 stream can have multiple independent streams which the

       application can select from. each independent stream can also contain

       dependent streams which are used to add or replace channels. */

    if (s->frame_type == EAC3_FRAME_TYPE_DEPENDENT) {

        avpriv_request_sample(s->avctx, "Dependent substream decoding");

        return AAC_AC3_PARSE_ERROR_FRAME_TYPE;

    } else if (s->frame_type == EAC3_FRAME_TYPE_RESERVED) {

        av_log(s->avctx, AV_LOG_ERROR, "Reserved frame type\n");

        return AAC_AC3_PARSE_ERROR_FRAME_TYPE;

    }

    /* The substream id indicates which substream this frame belongs to. each

       independent stream has its own substream id, and the dependent streams

       associated to an independent stream have matching substream id's. */

    if (s->substreamid) {

        /* only decode substream with id=0. skip any additional substreams. */

        avpriv_request_sample(s->avctx, "Additional substreams");

        return AAC_AC3_PARSE_ERROR_FRAME_TYPE;

    }

    if (s->bit_alloc_params.sr_code == EAC3_SR_CODE_REDUCED) {

        /* The E-AC-3 specification does not tell how to handle reduced sample

           rates in bit allocation.  The best assumption would be that it is

           handled like AC-3 DolbyNet, but we cannot be sure until we have a

           sample which utilizes this feature. */

        avpriv_request_sample(s->avctx, "Reduced sampling rate");

        return AVERROR_PATCHWELCOME;

    }

    skip_bits(gbc, 5); // skip bitstream id

    /* volume control params */

    for (i = 0; i < (s->channel_mode ? 1 : 2); i++) {

        skip_bits(gbc, 5); // skip dialog normalization

        if (get_bits1(gbc)) {

            skip_bits(gbc, 8); // skip compression gain word

        }

    }

    /* dependent stream channel map */

    if (s->frame_type == EAC3_FRAME_TYPE_DEPENDENT) {

        if (get_bits1(gbc)) {

            skip_bits(gbc, 16); // skip custom channel map

        }

    }

    /* mixing metadata */

    if (get_bits1(gbc)) {

        /* center and surround mix levels */

        if (s->channel_mode > AC3_CHMODE_STEREO) {

            s->preferred_downmix = get_bits(gbc, 2);

            if (s->channel_mode & 1) {

                /* if three front channels exist */

                s->center_mix_level_ltrt = get_bits(gbc, 3);

                s->center_mix_level      = get_bits(gbc, 3);

            }

            if (s->channel_mode & 4) {

                /* if a surround channel exists */

                s->surround_mix_level_ltrt = av_clip(get_bits(gbc, 3), 3, 7);

                s->surround_mix_level      = av_clip(get_bits(gbc, 3), 3, 7);

            }

        }

        /* lfe mix level */

        if (s->lfe_on && (s->lfe_mix_level_exists = get_bits1(gbc))) {

            s->lfe_mix_level = get_bits(gbc, 5);

        }

        /* info for mixing with other streams and substreams */

        if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {

            for (i = 0; i < (s->channel_mode ? 1 : 2); i++) {

                // TODO: apply program scale factor

                if (get_bits1(gbc)) {

                    skip_bits(gbc, 6);  // skip program scale factor

                }

            }

            if (get_bits1(gbc)) {

                skip_bits(gbc, 6);  // skip external program scale factor

            }

            /* skip mixing parameter data */

            switch(get_bits(gbc, 2)) {

                case 1: skip_bits(gbc, 5);  break;

                case 2: skip_bits(gbc, 12); break;

                case 3: {

                    int mix_data_size = (get_bits(gbc, 5) + 2) << 3;

                    skip_bits_long(gbc, mix_data_size);

                    break;

                }

            }

            /* skip pan information for mono or dual mono source */

            if (s->channel_mode < AC3_CHMODE_STEREO) {

                for (i = 0; i < (s->channel_mode ? 1 : 2); i++) {

                    if (get_bits1(gbc)) {

                        /* note: this is not in the ATSC A/52B specification

                           reference: ETSI TS 102 366 V1.1.1

                                      section: E.1.3.1.25 */

                        skip_bits(gbc, 8);  // skip pan mean direction index

                        skip_bits(gbc, 6);  // skip reserved paninfo bits

                    }

                }

            }

            /* skip mixing configuration information */

            if (get_bits1(gbc)) {

                for (blk = 0; blk < s->num_blocks; blk++) {

                    if (s->num_blocks == 1 || get_bits1(gbc)) {

                        skip_bits(gbc, 5);

                    }

                }

            }

        }

    }

    /* informational metadata */

    if (get_bits1(gbc)) {

        s->bitstream_mode = get_bits(gbc, 3);

        skip_bits(gbc, 2); // skip copyright bit and original bitstream bit

        if (s->channel_mode == AC3_CHMODE_STEREO) {

            s->dolby_surround_mode  = get_bits(gbc, 2);

            s->dolby_headphone_mode = get_bits(gbc, 2);

        }

        if (s->channel_mode >= AC3_CHMODE_2F2R) {

            s->dolby_surround_ex_mode = get_bits(gbc, 2);

        }

        for (i = 0; i < (s->channel_mode ? 1 : 2); i++) {

            if (get_bits1(gbc)) {

                skip_bits(gbc, 8); // skip mix level, room type, and A/D converter type

            }

        }

        if (s->bit_alloc_params.sr_code != EAC3_SR_CODE_REDUCED) {

            skip_bits1(gbc); // skip source sample rate code

        }

    }

    /* converter synchronization flag

       If frames are less than six blocks, this bit should be turned on

       once every 6 blocks to indicate the start of a frame set.

       reference: RFC 4598, Section 2.1.3  Frame Sets */

    if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT && s->num_blocks != 6) {

        skip_bits1(gbc); // skip converter synchronization flag

    }

    /* original frame size code if this stream was converted from AC-3 */

    if (s->frame_type == EAC3_FRAME_TYPE_AC3_CONVERT &&

            (s->num_blocks == 6 || get_bits1(gbc))) {

        skip_bits(gbc, 6); // skip frame size code

    }

    /* additional bitstream info */

    if (get_bits1(gbc)) {

        int addbsil = get_bits(gbc, 6);

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

            skip_bits(gbc, 8); // skip additional bit stream info

        }

    }

    /* audio frame syntax flags, strategy data, and per-frame data */

    if (s->num_blocks == 6) {

        ac3_exponent_strategy = get_bits1(gbc);

        parse_aht_info        = get_bits1(gbc);

    } else {

        /* less than 6 blocks, so use AC-3-style exponent strategy syntax, and

           do not use AHT */

        ac3_exponent_strategy = 1;

        parse_aht_info = 0;

    }

    s->snr_offset_strategy    = get_bits(gbc, 2);

    parse_transient_proc_info = get_bits1(gbc);

    s->block_switch_syntax = get_bits1(gbc);

    if (!s->block_switch_syntax)

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

    s->dither_flag_syntax = get_bits1(gbc);

    if (!s->dither_flag_syntax) {

        for (ch = 1; ch <= s->fbw_channels; ch++)

            s->dither_flag[ch] = 1;

    }

    s->dither_flag[CPL_CH] = s->dither_flag[s->lfe_ch] = 0;

    s->bit_allocation_syntax = get_bits1(gbc);

    if (!s->bit_allocation_syntax) {

        /* set default bit allocation parameters */

        s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[2];

        s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[1];

        s->bit_alloc_params.slow_gain  = ff_ac3_slow_gain_tab [1];

        s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[2];

        s->bit_alloc_params.floor      = ff_ac3_floor_tab     [7];

    }

    s->fast_gain_syntax  = get_bits1(gbc);

    s->dba_syntax        = get_bits1(gbc);

    s->skip_syntax       = get_bits1(gbc);

    parse_spx_atten_data = get_bits1(gbc);

    /* coupling strategy occurrence and coupling use per block */

    num_cpl_blocks = 0;

    if (s->channel_mode > 1) {

        for (blk = 0; blk < s->num_blocks; blk++) {

            s->cpl_strategy_exists[blk] = (!blk || get_bits1(gbc));

            if (s->cpl_strategy_exists[blk]) {

                s->cpl_in_use[blk] = get_bits1(gbc);

            } else {

                s->cpl_in_use[blk] = s->cpl_in_use[blk-1];

            }

            num_cpl_blocks += s->cpl_in_use[blk];

        }

    } else {

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

    }

    /* exponent strategy data */

    if (ac3_exponent_strategy) {

        /* AC-3-style exponent strategy syntax */

        for (blk = 0; blk < s->num_blocks; blk++) {

            for (ch = !s->cpl_in_use[blk]; ch <= s->fbw_channels; ch++) {

                s->exp_strategy[blk][ch] = get_bits(gbc, 2);

            }

        }

    } else {

        /* LUT-based exponent strategy syntax */

        for (ch = !((s->channel_mode > 1) && num_cpl_blocks); ch <= s->fbw_channels; ch++) {

            int frmchexpstr = get_bits(gbc, 5);

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

                s->exp_strategy[blk][ch] = ff_eac3_frm_expstr[frmchexpstr][blk];

            }

        }

    }

    /* LFE exponent strategy */

    if (s->lfe_on) {

        for (blk = 0; blk < s->num_blocks; blk++) {

            s->exp_strategy[blk][s->lfe_ch] = get_bits1(gbc);

        }

    }

    /* original exponent strategies if this stream was converted from AC-3 */

    if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT &&

            (s->num_blocks == 6 || get_bits1(gbc))) {

        skip_bits(gbc, 5 * s->fbw_channels); // skip converter channel exponent strategy

    }

    /* determine which channels use AHT */

    if (parse_aht_info) {

        /* For AHT to be used, all non-zero blocks must reuse exponents from

           the first block.  Furthermore, for AHT to be used in the coupling

           channel, all blocks must use coupling and use the same coupling

           strategy. */

        s->channel_uses_aht[CPL_CH]=0;

        for (ch = (num_cpl_blocks != 6); ch <= s->channels; ch++) {

            int use_aht = 1;

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

                if ((s->exp_strategy[blk][ch] != EXP_REUSE) ||

                        (!ch && s->cpl_strategy_exists[blk])) {

                    use_aht = 0;

                    break;

                }

            }

            s->channel_uses_aht[ch] = use_aht && get_bits1(gbc);

        }

    } else {

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

    }

    /* per-frame SNR offset */

    if (!s->snr_offset_strategy) {

        int csnroffst = (get_bits(gbc, 6) - 15) << 4;

        int snroffst = (csnroffst + get_bits(gbc, 4)) << 2;

        for (ch = 0; ch <= s->channels; ch++)

            s->snr_offset[ch] = snroffst;

    }

    /* transient pre-noise processing data */

    if (parse_transient_proc_info) {

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            if (get_bits1(gbc)) { // channel in transient processing

                skip_bits(gbc, 10); // skip transient processing location

                skip_bits(gbc, 8);  // skip transient processing length

            }

        }

    }

    /* spectral extension attenuation data */

    for (ch = 1; ch <= s->fbw_channels; ch++) {

        if (parse_spx_atten_data && get_bits1(gbc)) {

            s->spx_atten_code[ch] = get_bits(gbc, 5);

        } else {

            s->spx_atten_code[ch] = -1;

        }

    }

    /* block start information */

    if (s->num_blocks > 1 && get_bits1(gbc)) {

        /* reference: Section E2.3.2.27

           nblkstrtbits = (numblks - 1) * (4 + ceiling(log2(words_per_frame)))

           The spec does not say what this data is or what it's used for.

           It is likely the offset of each block within the frame. */

        int block_start_bits = (s->num_blocks-1) * (4 + av_log2(s->frame_size-2));

        skip_bits_long(gbc, block_start_bits);

        avpriv_request_sample(s->avctx, "Block start info");

    }

    /* syntax state initialization */

    for (ch = 1; ch <= s->fbw_channels; ch++) {

        s->first_spx_coords[ch] = 1;

        s->first_cpl_coords[ch] = 1;

    }

    s->first_cpl_leak = 1;

    return 0;

}


static void ipmi_init_sensors_from_sdrs(IPMIBmcSim *s)

{

    unsigned int i, pos;

    IPMISensor *sens;

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

        memset(s->sensors + i, 0, sizeof(*sens));

    }

    pos = 0;

    for (i = 0; !sdr_find_entry(&s->sdr, i, &pos, NULL); i++) {

        struct ipmi_sdr_compact *sdr =

            (struct ipmi_sdr_compact *) &s->sdr.sdr[pos];

        unsigned int len = sdr->header.rec_length;

        if (len < 20) {

            continue;

        }

        if (sdr->header.rec_type != IPMI_SDR_COMPACT_TYPE) {

            continue; /* Not a sensor SDR we set from */

        }

        if (sdr->sensor_owner_number > MAX_SENSORS) {

            continue;

        }

        sens = s->sensors + sdr->sensor_owner_number;

        IPMI_SENSOR_SET_PRESENT(sens, 1);

        IPMI_SENSOR_SET_SCAN_ON(sens, (sdr->sensor_init >> 6) & 1);

        IPMI_SENSOR_SET_EVENTS_ON(sens, (sdr->sensor_init >> 5) & 1);

        sens->assert_suppt = sdr->assert_mask[0] | (sdr->assert_mask[1] << 8);

        sens->deassert_suppt =

            sdr->deassert_mask[0] | (sdr->deassert_mask[1] << 8);

        sens->states_suppt =

            sdr->discrete_mask[0] | (sdr->discrete_mask[1] << 8);

        sens->sensor_type = sdr->sensor_type;

        sens->evt_reading_type_code = sdr->reading_type & 0x7f;

        /* Enable all the events that are supported. */

        sens->assert_enable = sens->assert_suppt;

        sens->deassert_enable = sens->deassert_suppt;

    }

}


static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,

                           int short_window)

{

    const float bitsave_slope  = short_window ? PSY_3GPP_SAVE_SLOPE_S  : PSY_3GPP_SAVE_SLOPE_L;

    const float bitsave_add    = short_window ? PSY_3GPP_SAVE_ADD_S    : PSY_3GPP_SAVE_ADD_L;

    const float bitspend_slope = short_window ? PSY_3GPP_SPEND_SLOPE_S : PSY_3GPP_SPEND_SLOPE_L;

    const float bitspend_add   = short_window ? PSY_3GPP_SPEND_ADD_S   : PSY_3GPP_SPEND_ADD_L;

    const float clip_low       = short_window ? PSY_3GPP_CLIP_LO_S     : PSY_3GPP_CLIP_LO_L;

    const float clip_high      = short_window ? PSY_3GPP_CLIP_HI_S     : PSY_3GPP_CLIP_HI_L;

    float clipped_pe, bit_save, bit_spend, bit_factor, fill_level;

    ctx->fill_level += ctx->frame_bits - bits;

    ctx->fill_level  = av_clip(ctx->fill_level, 0, size);

    fill_level = av_clipf((float)ctx->fill_level / size, clip_low, clip_high);

    clipped_pe = av_clipf(pe, ctx->pe.min, ctx->pe.max);

    bit_save   = (fill_level + bitsave_add) * bitsave_slope;

    assert(bit_save <= 0.3f && bit_save >= -0.05000001f);

    bit_spend  = (fill_level + bitspend_add) * bitspend_slope;

    assert(bit_spend <= 0.5f && bit_spend >= -0.1f);

    /* The bit factor graph in the spec is obviously incorrect.

     *      bit_spend + ((bit_spend - bit_spend))...

     * The reference encoder subtracts everything from 1, but also seems incorrect.

     *      1 - bit_save + ((bit_spend + bit_save))...

     * Hopefully below is correct.

     */

    bit_factor = 1.0f - bit_save + ((bit_spend - bit_save) / (ctx->pe.max - ctx->pe.min)) * (clipped_pe - ctx->pe.min);

    /* NOTE: The reference encoder attempts to center pe max/min around the current pe. */

    ctx->pe.max = FFMAX(pe, ctx->pe.max);

    ctx->pe.min = FFMIN(pe, ctx->pe.min);

    return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits);

}


static void RENAME(yuyvtoyuv420)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,

                                      long width, long height,

                                      long lumStride, long chromStride, long srcStride)

{

    long y;

    const long chromWidth= -((-width)>>1);

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

        RENAME(extract_even)(src, ydst, width);

        if(y&1) {

            RENAME(extract_odd2avg)(src-srcStride, src, udst, vdst, chromWidth);

            udst+= chromStride;

            vdst+= chromStride;

        }

        src += srcStride;

        ydst+= lumStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

#endif

}


static uint64_t log16(uint64_t a){

    int i;

    int out=0;

    assert(a >= (1<<16));

    a<<=16;

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

        if(a<(exp16_table[i]<<16)) continue;

        out |= 1<<i;

        a = ((a<<16) + exp16_table[i]/2)/exp16_table[i];

    }

    return out;

}


static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFTrack *track = arg;

    switch(tag) {

    case 0x4801:

        track->track_id = avio_rb32(pb);

        break;

    case 0x4804:

        avio_read(pb, track->track_number, 4);

        break;

    case 0x4B01:

        track->edit_rate.den = avio_rb32(pb);

        track->edit_rate.num = avio_rb32(pb);

        break;

    case 0x4803:

        avio_read(pb, track->sequence_ref, 16);

        break;

    }

    return 0;

}


void pl181_init(uint32_t base, BlockDriverState *bd,

                qemu_irq irq0, qemu_irq irq1)

{

    int iomemtype;

    pl181_state *s;

    s = (pl181_state *)qemu_mallocz(sizeof(pl181_state));

    iomemtype = cpu_register_io_memory(0, pl181_readfn,

                                       pl181_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    s->base = base;

    s->card = sd_init(bd);

    s->irq[0] = irq0;

    s->irq[1] = irq1;

    qemu_register_reset(pl181_reset, s);

    pl181_reset(s);

    /* ??? Save/restore.  */

}


static int dxva2_get_decoder_configuration(AVCodecContext *s, const GUID *device_guid,

                                           const DXVA2_VideoDesc *desc,

                                           DXVA2_ConfigPictureDecode *config)

{

    InputStream  *ist = s->opaque;

    int loglevel = (ist->hwaccel_id == HWACCEL_AUTO) ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    DXVA2Context *ctx = ist->hwaccel_ctx;

    unsigned cfg_count = 0, best_score = 0;

    DXVA2_ConfigPictureDecode *cfg_list = NULL;

    DXVA2_ConfigPictureDecode best_cfg = {{0}};

    HRESULT hr;

    int i;

    hr = IDirectXVideoDecoderService_GetDecoderConfigurations(ctx->decoder_service, device_guid, desc, NULL, &cfg_count, &cfg_list);

    if (FAILED(hr)) {

        av_log(NULL, loglevel, "Unable to retrieve decoder configurations\n");

        return AVERROR(EINVAL);

    }

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

        DXVA2_ConfigPictureDecode *cfg = &cfg_list[i];

        unsigned score;

        if (cfg->ConfigBitstreamRaw == 1)

            score = 1;

        else if (s->codec_id == AV_CODEC_ID_H264 && cfg->ConfigBitstreamRaw == 2)

            score = 2;

        else

            continue;

        if (IsEqualGUID(&cfg->guidConfigBitstreamEncryption, &DXVA2_NoEncrypt))

            score += 16;

        if (score > best_score) {

            best_score = score;

            best_cfg   = *cfg;

        }

    }

    CoTaskMemFree(cfg_list);

    if (!best_score) {

        av_log(NULL, loglevel, "No valid decoder configuration available\n");

        return AVERROR(EINVAL);

    }

    *config = best_cfg;

    return 0;

}


static inline int RENAME(yuv420_rgb15)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*2 > dstStride[0]) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

//printf("%X %X %X %X %X %X %X %X %X %X\n", (int)&c->redDither, (int)&b5Dither, (int)src[0], (int)src[1], (int)src[2], (int)dst[0],

//srcStride[0],srcStride[1],srcStride[2],dstStride[0]);

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

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	b5Dither= dither8[y&1];

	g6Dither= dither4[y&1];

	g5Dither= dither8[y&1];

	r5Dither= dither8[(y+1)&1];

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

YUV2RGB

#ifdef DITHER1XBPP

			"paddusb "MANGLE(b5Dither)", %%mm0	\n\t"

			"paddusb "MANGLE(g5Dither)", %%mm2	\n\t"

			"paddusb "MANGLE(r5Dither)", %%mm1	\n\t"

#endif

		     /* mask unneeded bits off */

		     "pand "MANGLE(mmx_redmask)", %%mm0;" /* b7b6b5b4 b3_0_0_0 b7b6b5b4 b3_0_0_0 */

		     "pand "MANGLE(mmx_redmask)", %%mm2;" /* g7g6g5g4 g3_0_0_0 g7g6g5g4 g3_0_0_0 */

		     "pand "MANGLE(mmx_redmask)", %%mm1;" /* r7r6r5r4 r3_0_0_0 r7r6r5r4 r3_0_0_0 */

		     "psrlw $3,%%mm0;" /* 0_0_0_b7 b6b5b4b3 0_0_0_b7 b6b5b4b3 */

		     "psrlw $1,%%mm1;"            /* 0_r7r6r5  r4r3_0_0 0_r7r6r5 r4r3_0_0 */

		     "pxor %%mm4, %%mm4;" /* zero mm4 */

		     "movq %%mm0, %%mm5;" /* Copy B7-B0 */

		     "movq %%mm2, %%mm7;" /* Copy G7-G0 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpcklbw %%mm4, %%mm2;" /* 0_0_0_0 0_0_0_0 g7g6g5g4 g3_0_0_0 */

		     "punpcklbw %%mm1, %%mm0;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $2, %%mm2;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */

		     "por %%mm2, %%mm0;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */

		     "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

		     MOVNTQ " %%mm0, (%1);" /* store pixel 0-3 */

		     /* convert rgb24 plane to rgb16 pack for pixel 0-3 */

		     "punpckhbw %%mm4, %%mm7;" /* 0_0_0_0 0_0_0_0 0_g7g6g5 g4g3_0_0 */

		     "punpckhbw %%mm1, %%mm5;" /* r7r6r5r4 r3_0_0_0 0_0_0_b7 b6b5b4b3 */

		     "psllw $2, %%mm7;" /* 0_0_0_0 0_0_g7g6 g5g4g3_0 0_0_0_0 */

		     "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "por %%mm7, %%mm5;" /* 0_r7r6r5 r4r3g7g6 g5g4g3b7 b6b5b4b3 */

		     "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     MOVNTQ " %%mm5, 8 (%1);" /* store pixel 4-7 */

		     "add $16, %1			\n\t"

		     "add $4, %0			\n\t"

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,

                           int letter, const char *buf)

{

    RTSPState *rt = s->priv_data;

    char buf1[64], st_type[64];

    const char *p;

    int codec_type, payload_type, i;

    AVStream *st;

    RTSPStream *rtsp_st;

    struct in_addr sdp_ip;

    int ttl;

#ifdef DEBUG

    printf("sdp: %c='%s'\n", letter, buf);

#endif

    p = buf;

    switch(letter) {

    case 'c':

        get_word(buf1, sizeof(buf1), &p);

        if (strcmp(buf1, "IN") != 0)

            return;

        get_word(buf1, sizeof(buf1), &p);

        if (strcmp(buf1, "IP4") != 0)

            return;

        get_word_sep(buf1, sizeof(buf1), "/", &p);

        if (inet_aton(buf1, &sdp_ip) == 0)

            return;

        ttl = 16;

        if (*p == '/') {

            p++;

            get_word_sep(buf1, sizeof(buf1), "/", &p);

            ttl = atoi(buf1);

        }

        if (s->nb_streams == 0) {

            s1->default_ip = sdp_ip;

            s1->default_ttl = ttl;

        } else {

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

            rtsp_st = st->priv_data;

            rtsp_st->sdp_ip = sdp_ip;

            rtsp_st->sdp_ttl = ttl;

        }

        break;

    case 's':

        pstrcpy(s->title, sizeof(s->title), p);

        break;

    case 'i':

        if (s->nb_streams == 0) {

            pstrcpy(s->comment, sizeof(s->comment), p);

            break;

        }

        break;

    case 'm':

        /* new stream */

        get_word(st_type, sizeof(st_type), &p);

        if (!strcmp(st_type, "audio")) {

            codec_type = CODEC_TYPE_AUDIO;

        } else if (!strcmp(st_type, "video")) {

            codec_type = CODEC_TYPE_VIDEO;

        } else {

            return;

        }

        rtsp_st = av_mallocz(sizeof(RTSPStream));

        if (!rtsp_st)

            return;

        rtsp_st->stream_index = -1;

        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);

        rtsp_st->sdp_ip = s1->default_ip;

        rtsp_st->sdp_ttl = s1->default_ttl;

        get_word(buf1, sizeof(buf1), &p); /* port */

        rtsp_st->sdp_port = atoi(buf1);

        get_word(buf1, sizeof(buf1), &p); /* protocol (ignored) */

        /* XXX: handle list of formats */

        get_word(buf1, sizeof(buf1), &p); /* format list */

        rtsp_st->sdp_payload_type = atoi(buf1);

        if (rtsp_st->sdp_payload_type == RTP_PT_MPEG2TS) {

            /* no corresponding stream */

        } else {

            st = av_new_stream(s, 0);

            if (!st)

                return;

            st->priv_data = rtsp_st;

            rtsp_st->stream_index = st->index;

            st->codec.codec_type = codec_type;

            if (rtsp_st->sdp_payload_type < 96) {

                /* if standard payload type, we can find the codec right now */

                rtp_get_codec_info(&st->codec, rtsp_st->sdp_payload_type);

            }

        }

        /* put a default control url */

        pstrcpy(rtsp_st->control_url, sizeof(rtsp_st->control_url), s->filename);

        break;

    case 'a':

        if (strstart(p, "control:", &p) && s->nb_streams > 0) {

            char proto[32];

            /* get the control url */

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

            rtsp_st = st->priv_data;

            /* XXX: may need to add full url resolution */

            url_split(proto, sizeof(proto), NULL, 0, NULL, NULL, 0, p);

            if (proto[0] == '\0') {

                /* relative control URL */

                pstrcat(rtsp_st->control_url, sizeof(rtsp_st->control_url), "/");

                pstrcat(rtsp_st->control_url, sizeof(rtsp_st->control_url), p);

            } else {

                pstrcpy(rtsp_st->control_url, sizeof(rtsp_st->control_url), p);

            }

        } else if (strstart(p, "rtpmap:", &p)) {

            /* NOTE: rtpmap is only supported AFTER the 'm=' tag */

            get_word(buf1, sizeof(buf1), &p);

            payload_type = atoi(buf1);

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

                st = s->streams[i];

                rtsp_st = st->priv_data;

                if (rtsp_st->sdp_payload_type == payload_type) {

                    sdp_parse_rtpmap(&st->codec, p);

                }

            }

        } else if (strstart(p, "fmtp:", &p)) {

            /* NOTE: fmtp is only supported AFTER the 'a=rtpmap:xxx' tag */

            get_word(buf1, sizeof(buf1), &p);

            payload_type = atoi(buf1);

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

                st = s->streams[i];

                rtsp_st = st->priv_data;

                if (rtsp_st->sdp_payload_type == payload_type) {

                    sdp_parse_fmtp(&st->codec, p);

                }

            }

        }

        break;

    }

}


static void vmsvga_init(struct vmsvga_state_s *s, int vga_ram_size)

{

    s->scratch_size = SVGA_SCRATCH_SIZE;

    s->scratch = qemu_malloc(s->scratch_size * 4);

    vmsvga_reset(s);

    s->fifo_size = SVGA_FIFO_SIZE;

    s->fifo_offset = qemu_ram_alloc(s->fifo_size);

    s->fifo_ptr = qemu_get_ram_ptr(s->fifo_offset);

    vga_common_init(&s->vga, vga_ram_size);

    vga_init(&s->vga);

    vmstate_register(0, &vmstate_vga_common, &s->vga);

    s->vga.ds = graphic_console_init(vmsvga_update_display,

                                     vmsvga_invalidate_display,

                                     vmsvga_screen_dump,

                                     vmsvga_text_update, s);

    vga_init_vbe(&s->vga);

    rom_add_vga(VGABIOS_FILENAME);

}


static uint32_t ehci_mem_readw(void *ptr, target_phys_addr_t addr)

{

    EHCIState *s = ptr;

    uint32_t val;

    val = s->mmio[addr] | (s->mmio[addr+1] << 8);

    return val;

}


static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,

                      Error **errp)

{

    BDRVQcowState *s = bs->opaque;

    int len, i, ret = 0;

    QCowHeader header;

    QemuOpts *opts;

    Error *local_err = NULL;

    uint64_t ext_end;

    uint64_t l1_vm_state_index;

    const char *opt_overlap_check;

    int overlap_check_template = 0;

    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read qcow2 header");

        goto fail;

    }

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC) {

        error_setg(errp, "Image is not in qcow2 format");

        ret = -EINVAL;

        goto fail;

    }

    if (header.version < 2 || header.version > 3) {

        report_unsupported(bs, errp, "QCOW version %d", header.version);

        ret = -ENOTSUP;

        goto fail;

    }

    s->qcow_version = header.version;

    /* Initialise version 3 header fields */

    if (header.version == 2) {

        header.incompatible_features    = 0;

        header.compatible_features      = 0;

        header.autoclear_features       = 0;

        header.refcount_order           = 4;

        header.header_length            = 72;

    } else {

        be64_to_cpus(&header.incompatible_features);

        be64_to_cpus(&header.compatible_features);

        be64_to_cpus(&header.autoclear_features);

        be32_to_cpus(&header.refcount_order);

        be32_to_cpus(&header.header_length);

    }

    if (header.header_length > sizeof(header)) {

        s->unknown_header_fields_size = header.header_length - sizeof(header);

        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);

        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,

                         s->unknown_header_fields_size);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "

                             "fields");

            goto fail;

        }

    }

    if (header.backing_file_offset) {

        ext_end = header.backing_file_offset;

    } else {

        ext_end = 1 << header.cluster_bits;

    }

    /* Handle feature bits */

    s->incompatible_features    = header.incompatible_features;

    s->compatible_features      = header.compatible_features;

    s->autoclear_features       = header.autoclear_features;

    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {

        void *feature_table = NULL;

        qcow2_read_extensions(bs, header.header_length, ext_end,

                              &feature_table, NULL);

        report_unsupported_feature(bs, errp, feature_table,

                                   s->incompatible_features &

                                   ~QCOW2_INCOMPAT_MASK);

        ret = -ENOTSUP;

        g_free(feature_table);

        goto fail;

    }

    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {

        /* Corrupt images may not be written to unless they are being repaired

         */

        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {

            error_setg(errp, "qcow2: Image is corrupt; cannot be opened "

                       "read/write");

            ret = -EACCES;

            goto fail;

        }

    }

    /* Check support for various header values */

    if (header.refcount_order != 4) {

        report_unsupported(bs, errp, "%d bit reference counts",

                           1 << header.refcount_order);

        ret = -ENOTSUP;

        goto fail;

    }

    s->refcount_order = header.refcount_order;

    if (header.cluster_bits < MIN_CLUSTER_BITS ||

        header.cluster_bits > MAX_CLUSTER_BITS) {

        error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);

        ret = -EINVAL;

        goto fail;

    }

    if (header.crypt_method > QCOW_CRYPT_AES) {

        error_setg(errp, "Unsupported encryption method: %i",

                   header.crypt_method);

        ret = -EINVAL;

        goto fail;

    }

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header) {

        bs->encrypted = 1;

    }

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    /* read the level 1 table */

    s->l1_size = header.l1_size;

    l1_vm_state_index = size_to_l1(s, header.size);

    if (l1_vm_state_index > INT_MAX) {

        error_setg(errp, "Image is too big");

        ret = -EFBIG;

        goto fail;

    }

    s->l1_vm_state_index = l1_vm_state_index;

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index) {

        error_setg(errp, "L1 table is too small");

        ret = -EINVAL;

        goto fail;

    }

    s->l1_table_offset = header.l1_table_offset;

    if (s->l1_size > 0) {

        s->l1_table = g_malloc0(

            align_offset(s->l1_size * sizeof(uint64_t), 512));

        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,

                         s->l1_size * sizeof(uint64_t));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read L1 table");

            goto fail;

        }

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

            be64_to_cpus(&s->l1_table[i]);

        }

    }

    /* alloc L2 table/refcount block cache */

    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);

    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);

    s->cluster_cache = g_malloc(s->cluster_size);

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size

                                  + 512);

    s->cluster_cache_offset = -1;

    s->flags = flags;

    ret = qcow2_refcount_init(bs);

    if (ret != 0) {

        error_setg_errno(errp, -ret, "Could not initialize refcount handling");

        goto fail;

    }

    QLIST_INIT(&s->cluster_allocs);

    QTAILQ_INIT(&s->discards);

    /* read qcow2 extensions */

    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,

        &local_err)) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > 1023) {

            len = 1023;

        }

        ret = bdrv_pread(bs->file, header.backing_file_offset,

                         bs->backing_file, len);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not read backing file name");

            goto fail;

        }

        bs->backing_file[len] = '\0';

    }

    ret = qcow2_read_snapshots(bs);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read snapshots");

        goto fail;

    }

    /* Clear unknown autoclear feature bits */

    if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {

        s->autoclear_features = 0;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not update qcow2 header");

            goto fail;

        }

    }

    /* Initialise locks */

    qemu_co_mutex_init(&s->lock);

    /* Repair image if dirty */

    if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&

        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {

        BdrvCheckResult result = {0};

        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not repair dirty image");

            goto fail;

        }

    }

    /* Enable lazy_refcounts according to image and command line options */

    opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,

        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));

    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;

    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;

    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,

                          flags & BDRV_O_UNMAP);

    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);

    s->discard_passthrough[QCOW2_DISCARD_OTHER] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);

    opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";

    if (!strcmp(opt_overlap_check, "none")) {

        overlap_check_template = 0;

    } else if (!strcmp(opt_overlap_check, "constant")) {

        overlap_check_template = QCOW2_OL_CONSTANT;

    } else if (!strcmp(opt_overlap_check, "cached")) {

        overlap_check_template = QCOW2_OL_CACHED;

    } else if (!strcmp(opt_overlap_check, "all")) {

        overlap_check_template = QCOW2_OL_ALL;

    } else {

        error_setg(errp, "Unsupported value '%s' for qcow2 option "

                   "'overlap-check'. Allowed are either of the following: "

                   "none, constant, cached, all", opt_overlap_check);

        qemu_opts_del(opts);

        ret = -EINVAL;

        goto fail;

    }

    s->overlap_check = 0;

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

        /* overlap-check defines a template bitmask, but every flag may be

         * overwritten through the associated boolean option */

        s->overlap_check |=

            qemu_opt_get_bool(opts, overlap_bool_option_names[i],

                              overlap_check_template & (1 << i)) << i;

    }

    qemu_opts_del(opts);

    if (s->use_lazy_refcounts && s->qcow_version < 3) {

        error_setg(errp, "Lazy refcounts require a qcow2 image with at least "

                   "qemu 1.1 compatibility level");

        ret = -EINVAL;

        goto fail;

    }

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return ret;

 fail:

    g_free(s->unknown_header_fields);

    cleanup_unknown_header_ext(bs);

    qcow2_free_snapshots(bs);

    qcow2_refcount_close(bs);

    g_free(s->l1_table);

    /* else pre-write overlap checks in cache_destroy may crash */

    s->l1_table = NULL;

    if (s->l2_table_cache) {

        qcow2_cache_destroy(bs, s->l2_table_cache);

    }

    if (s->refcount_block_cache) {

        qcow2_cache_destroy(bs, s->refcount_block_cache);

    }

    g_free(s->cluster_cache);

    qemu_vfree(s->cluster_data);

    return ret;

}


static void replay_save_event(Event *event, int checkpoint)

{

    if (replay_mode != REPLAY_MODE_PLAY) {

        /* put the event into the file */

        replay_put_event(EVENT_ASYNC);

        replay_put_byte(checkpoint);

        replay_put_byte(event->event_kind);

        /* save event-specific data */

        switch (event->event_kind) {

        case REPLAY_ASYNC_EVENT_BH:

            replay_put_qword(event->id);

            break;

        case REPLAY_ASYNC_EVENT_INPUT:

            replay_save_input_event(event->opaque);

            break;

        case REPLAY_ASYNC_EVENT_INPUT_SYNC:

            break;

        case REPLAY_ASYNC_EVENT_CHAR_READ:

            replay_event_char_read_save(event->opaque);

            break;

        default:

            error_report("Unknown ID %d of replay event", read_event_kind);

            exit(1);

        }

    }

}


int avformat_alloc_output_context2(AVFormatContext **avctx, AVOutputFormat *oformat,

                                   const char *format, const char *filename)

{

    AVFormatContext *s = avformat_alloc_context();

    int ret = 0;

    *avctx = NULL;

    if (!s)

        goto nomem;

    if (!oformat) {

        if (format) {

            oformat = av_guess_format(format, NULL, NULL);

            if (!oformat) {

                av_log(s, AV_LOG_ERROR, "Requested output format '%s' is not a suitable output format\n", format);

                ret = AVERROR(EINVAL);

                goto error;

            }

        } else {

            oformat = av_guess_format(NULL, filename, NULL);

            if (!oformat) {

                ret = AVERROR(EINVAL);

                av_log(s, AV_LOG_ERROR, "Unable to find a suitable output format for '%s'\n",

                       filename);

                goto error;

            }

        }

    }

    s->oformat = oformat;

    if (s->oformat->priv_data_size > 0) {

        s->priv_data = av_mallocz(s->oformat->priv_data_size);

        if (!s->priv_data)

            goto nomem;

        if (s->oformat->priv_class) {

            *(const AVClass**)s->priv_data= s->oformat->priv_class;

            av_opt_set_defaults(s->priv_data);

        }

    } else

        s->priv_data = NULL;

    if (filename)

        av_strlcpy(s->filename, filename, sizeof(s->filename));

    *avctx = s;

    return 0;

nomem:

    av_log(s, AV_LOG_ERROR, "Out of memory\n");

    ret = AVERROR(ENOMEM);

error:

    avformat_free_context(s);

    return ret;

}


static av_cold int gif_encode_init(AVCodecContext *avctx)

{

    GIFContext *s = avctx->priv_data;

    if (avctx->width > 65535 || avctx->height > 65535) {

        av_log(avctx, AV_LOG_ERROR, "GIF does not support resolutions above 65535x65535\n");

        return AVERROR(EINVAL);

    }

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    avctx->coded_frame->key_frame = 1;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    s->transparent_index = -1;

    s->lzw = av_mallocz(ff_lzw_encode_state_size);

    s->buf = av_malloc(avctx->width*avctx->height*2);

    s->tmpl = av_malloc(avctx->width);

    if (!s->tmpl || !s->buf || !s->lzw)

        return AVERROR(ENOMEM);

    if (avpriv_set_systematic_pal2(s->palette, avctx->pix_fmt) < 0)

        av_assert0(avctx->pix_fmt == AV_PIX_FMT_PAL8);

    return 0;

}