matroska_read_header (AVFormatContext    *s,

                      AVFormatParameters *ap)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    char *doctype;

    int version, last_level, res = 0;

    uint32_t id;

    matroska->ctx = s;

    /* First read the EBML header. */

    doctype = NULL;

    if ((res = ebml_read_header(matroska, &doctype, &version)) < 0)

        return res;

    if ((doctype == NULL) || strcmp(doctype, "matroska")) {

        av_log(matroska->ctx, AV_LOG_ERROR,

               "Wrong EBML doctype ('%s' != 'matroska').\n",

               doctype ? doctype : "(none)");

        if (doctype)

            av_free(doctype);

        return AVERROR_NOFMT;

    }

    av_free(doctype);

    if (version > 2) {

        av_log(matroska->ctx, AV_LOG_ERROR,

               "Matroska demuxer version 2 too old for file version %d\n",

               version);

        return AVERROR_NOFMT;

    }

    /* The next thing is a segment. */

    while (1) {

        if (!(id = ebml_peek_id(matroska, &last_level)))

            return AVERROR(EIO);

        if (id == MATROSKA_ID_SEGMENT)

            break;

        /* oi! */

        av_log(matroska->ctx, AV_LOG_INFO,

               "Expected a Segment ID (0x%x), but received 0x%x!\n",

               MATROSKA_ID_SEGMENT, id);

        if ((res = ebml_read_skip(matroska)) < 0)

            return res;

    }

    /* We now have a Matroska segment.

     * Seeks are from the beginning of the segment,

     * after the segment ID/length. */

    if ((res = ebml_read_master(matroska, &id)) < 0)

        return res;

    matroska->segment_start = url_ftell(s->pb);

    matroska->time_scale = 1000000;

    /* we've found our segment, start reading the different contents in here */

    while (res == 0) {

        if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {

            res = AVERROR(EIO);

            break;

        } else if (matroska->level_up) {

            matroska->level_up--;

            break;

        }

        switch (id) {

            /* stream info */

            case MATROSKA_ID_INFO: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_info(matroska);

                break;

            }

            /* track info headers */

            case MATROSKA_ID_TRACKS: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_tracks(matroska);

                break;

            }

            /* stream index */

            case MATROSKA_ID_CUES: {

                if (!matroska->index_parsed) {

                    if ((res = ebml_read_master(matroska, &id)) < 0)

                        break;

                    res = matroska_parse_index(matroska);

                } else

                    res = ebml_read_skip(matroska);

                break;

            }

            /* metadata */

            case MATROSKA_ID_TAGS: {

                if (!matroska->metadata_parsed) {

                    if ((res = ebml_read_master(matroska, &id)) < 0)

                        break;

                    res = matroska_parse_metadata(matroska);

                } else

                    res = ebml_read_skip(matroska);

                break;

            }

            /* file index (if seekable, seek to Cues/Tags to parse it) */

            case MATROSKA_ID_SEEKHEAD: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_seekhead(matroska);

                break;

            }

            case MATROSKA_ID_ATTACHMENTS: {

                if ((res = ebml_read_master(matroska, &id)) < 0)

                    break;

                res = matroska_parse_attachments(s);

                break;

            }

            case MATROSKA_ID_CLUSTER: {

                /* Do not read the master - this will be done in the next

                 * call to matroska_read_packet. */

                res = 1;

                break;

            }

            default:

                av_log(matroska->ctx, AV_LOG_INFO,

                       "Unknown matroska file header ID 0x%x\n", id);

            /* fall-through */

            case EBML_ID_VOID:

                res = ebml_read_skip(matroska);

                break;

        }

        if (matroska->level_up) {

            matroska->level_up--;

            break;

        }

    }

    /* Have we found a cluster? */

    if (ebml_peek_id(matroska, NULL) == MATROSKA_ID_CLUSTER) {

        int i, j;

        MatroskaTrack *track;

        AVStream *st;

        for (i = 0; i < matroska->num_tracks; i++) {

            enum CodecID codec_id = CODEC_ID_NONE;

            uint8_t *extradata = NULL;

            int extradata_size = 0;

            int extradata_offset = 0;

            track = matroska->tracks[i];

            track->stream_index = -1;

            /* Apply some sanity checks. */

            if (track->codec_id == NULL)

                continue;

            for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){

                if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,

                            strlen(ff_mkv_codec_tags[j].str))){

                    codec_id= ff_mkv_codec_tags[j].id;

                    break;

                }

            }

            /* Set the FourCC from the CodecID. */

            /* This is the MS compatibility mode which stores a

             * BITMAPINFOHEADER in the CodecPrivate. */

            if (!strcmp(track->codec_id,

                        MATROSKA_CODEC_ID_VIDEO_VFW_FOURCC) &&

                (track->codec_priv_size >= 40) &&

                (track->codec_priv != NULL)) {

                MatroskaVideoTrack *vtrack = (MatroskaVideoTrack *) track;

                /* Offset of biCompression. Stored in LE. */

                vtrack->fourcc = AV_RL32(track->codec_priv + 16);

                codec_id = codec_get_id(codec_bmp_tags, vtrack->fourcc);

            }

            /* This is the MS compatibility mode which stores a

             * WAVEFORMATEX in the CodecPrivate. */

            else if (!strcmp(track->codec_id,

                             MATROSKA_CODEC_ID_AUDIO_ACM) &&

                (track->codec_priv_size >= 18) &&

                (track->codec_priv != NULL)) {

                uint16_t tag;

                /* Offset of wFormatTag. Stored in LE. */

                tag = AV_RL16(track->codec_priv);

                codec_id = codec_get_id(codec_wav_tags, tag);

            }

            else if (codec_id == CODEC_ID_AAC && !track->codec_priv_size) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;

                int profile = matroska_aac_profile(track->codec_id);

                int sri = matroska_aac_sri(audiotrack->internal_samplerate);

                extradata = av_malloc(5);

                if (extradata == NULL)

                    return AVERROR(ENOMEM);

                extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);

                extradata[1] = ((sri&0x01) << 7) | (audiotrack->channels<<3);

                if (strstr(track->codec_id, "SBR")) {

                    sri = matroska_aac_sri(audiotrack->samplerate);

                    extradata[2] = 0x56;

                    extradata[3] = 0xE5;

                    extradata[4] = 0x80 | (sri<<3);

                    extradata_size = 5;

                } else {

                    extradata_size = 2;

                }

            }

            else if (codec_id == CODEC_ID_TTA) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *) track;

                ByteIOContext b;

                extradata_size = 30;

                extradata = av_mallocz(extradata_size);

                if (extradata == NULL)

                    return AVERROR(ENOMEM);

                init_put_byte(&b, extradata, extradata_size, 1,

                              NULL, NULL, NULL, NULL);

                put_buffer(&b, "TTA1", 4);

                put_le16(&b, 1);

                put_le16(&b, audiotrack->channels);

                put_le16(&b, audiotrack->bitdepth);

                put_le32(&b, audiotrack->samplerate);

                put_le32(&b, matroska->ctx->duration * audiotrack->samplerate);

            }

            else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||

                     codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {

                extradata_offset = 26;

                track->codec_priv_size -= extradata_offset;

            }

            else if (codec_id == CODEC_ID_RA_144) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;

                audiotrack->samplerate = 8000;

                audiotrack->channels = 1;

            }

            else if (codec_id == CODEC_ID_RA_288 ||

                     codec_id == CODEC_ID_COOK ||

                     codec_id == CODEC_ID_ATRAC3) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;

                ByteIOContext b;

                init_put_byte(&b, track->codec_priv, track->codec_priv_size, 0,

                              NULL, NULL, NULL, NULL);

                url_fskip(&b, 24);

                audiotrack->coded_framesize = get_be32(&b);

                url_fskip(&b, 12);

                audiotrack->sub_packet_h    = get_be16(&b);

                audiotrack->frame_size      = get_be16(&b);

                audiotrack->sub_packet_size = get_be16(&b);

                audiotrack->buf = av_malloc(audiotrack->frame_size * audiotrack->sub_packet_h);

                if (codec_id == CODEC_ID_RA_288) {

                    audiotrack->block_align = audiotrack->coded_framesize;

                    track->codec_priv_size = 0;

                } else {

                    audiotrack->block_align = audiotrack->sub_packet_size;

                    extradata_offset = 78;

                    track->codec_priv_size -= extradata_offset;

                }

            }

            if (codec_id == CODEC_ID_NONE) {

                av_log(matroska->ctx, AV_LOG_INFO,

                       "Unknown/unsupported CodecID %s.\n",

                       track->codec_id);

            }

            track->stream_index = matroska->num_streams;

            matroska->num_streams++;

            st = av_new_stream(s, track->stream_index);

            if (st == NULL)

                return AVERROR(ENOMEM);

            av_set_pts_info(st, 64, matroska->time_scale, 1000*1000*1000); /* 64 bit pts in ns */

            st->codec->codec_id = codec_id;

            st->start_time = 0;

            if (strcmp(track->language, "und"))

                strcpy(st->language, track->language);

            if (track->flags & MATROSKA_TRACK_DEFAULT)

                st->disposition |= AV_DISPOSITION_DEFAULT;

            if (track->default_duration)

                av_reduce(&st->codec->time_base.num, &st->codec->time_base.den,

                          track->default_duration, 1000000000, 30000);

            if(extradata){

                st->codec->extradata = extradata;

                st->codec->extradata_size = extradata_size;

            } else if(track->codec_priv && track->codec_priv_size > 0){

                st->codec->extradata = av_malloc(track->codec_priv_size);

                if(st->codec->extradata == NULL)

                    return AVERROR(ENOMEM);

                st->codec->extradata_size = track->codec_priv_size;

                memcpy(st->codec->extradata,track->codec_priv+extradata_offset,

                       track->codec_priv_size);

            }

            if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {

                MatroskaVideoTrack *videotrack = (MatroskaVideoTrack *)track;

                st->codec->codec_type = CODEC_TYPE_VIDEO;

                st->codec->codec_tag = videotrack->fourcc;

                st->codec->width = videotrack->pixel_width;

                st->codec->height = videotrack->pixel_height;

                if (videotrack->display_width == 0)

                    videotrack->display_width= videotrack->pixel_width;

                if (videotrack->display_height == 0)

                    videotrack->display_height= videotrack->pixel_height;

                av_reduce(&st->codec->sample_aspect_ratio.num,

                          &st->codec->sample_aspect_ratio.den,

                          st->codec->height * videotrack->display_width,

                          st->codec-> width * videotrack->display_height,

                          255);

                st->need_parsing = AVSTREAM_PARSE_HEADERS;

            } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {

                MatroskaAudioTrack *audiotrack = (MatroskaAudioTrack *)track;

                st->codec->codec_type = CODEC_TYPE_AUDIO;

                st->codec->sample_rate = audiotrack->samplerate;

                st->codec->channels = audiotrack->channels;

                st->codec->block_align = audiotrack->block_align;

            } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {

                st->codec->codec_type = CODEC_TYPE_SUBTITLE;

            }

            /* What do we do with private data? E.g. for Vorbis. */

        }

        res = 0;

    }

    if (matroska->index_parsed) {

        int i, track, stream;

        for (i=0; i<matroska->num_indexes; i++) {

            MatroskaDemuxIndex *idx = &matroska->index[i];

            track = matroska_find_track_by_num(matroska, idx->track);

            stream = matroska->tracks[track]->stream_index;

            if (stream >= 0)

                av_add_index_entry(matroska->ctx->streams[stream],

                                   idx->pos, idx->time/matroska->time_scale,

                                   0, 0, AVINDEX_KEYFRAME);

        }

    }

    return res;

}


static void test_enabled(void)

{

    int i;

    throttle_config_init(&cfg);

    g_assert(!throttle_enabled(&cfg));

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

        throttle_config_init(&cfg);

        set_cfg_value(false, i, 150);

        g_assert(throttle_enabled(&cfg));

    }

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

        throttle_config_init(&cfg);

        set_cfg_value(false, i, -150);

        g_assert(!throttle_enabled(&cfg));

    }

}


static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,

                           unsigned int width, unsigned int height,

                           uint8_t *line[4], int pixel_step[4], uint8_t color[4],

                           int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])

{

    int i, j, alpha;

    if (color[3] != 0xFF) {

        if (is_rgba_packed) {

            uint8_t *p;

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

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

                    SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],

                                  rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);

        } else {

            unsigned int luma_pos, chroma_pos1, chroma_pos2;

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

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

                    SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);

        }

    } else {

        ff_draw_rectangle(picref->data, picref->linesize,

                          line, pixel_step, hsub, vsub,

                          x, y, width, height);

    }

}


static void create_vorbis_context(venc_context_t * venc, AVCodecContext * avccontext) {

    codebook_t * cb;

    floor_t * fc;

    residue_t * rc;

    mapping_t * mc;

    int i, book;

    venc->channels = avccontext->channels;

    venc->sample_rate = avccontext->sample_rate;

    venc->blocksize[0] = venc->blocksize[1] = 8;

    venc->ncodebooks = 10;

    venc->codebooks = av_malloc(sizeof(codebook_t) * venc->ncodebooks);

    // codebook 1 - floor1 book, values 0..255

    cb = &venc->codebooks[0];

    cb->nentries = 256;

    cb->entries = av_malloc(sizeof(cb_entry_t) * cb->nentries);

    for (i = 0; i < cb->nentries; i++) cb->entries[i].len = 8;

    cb->ndimentions = 0;

    cb->min = 0.;

    cb->delta = 0.;

    cb->seq_p = 0;

    cb->lookup = 0;

    cb->quantlist = NULL;

    ready_codebook(cb);

    // codebook 2 - residue classbook, values 0..1, dimentions 200

    cb = &venc->codebooks[1];

    cb->nentries = 2;

    cb->entries = av_malloc(sizeof(cb_entry_t) * cb->nentries);

    for (i = 0; i < cb->nentries; i++) cb->entries[i].len = 1;

    cb->ndimentions = 200;

    cb->min = 0.;

    cb->delta = 0.;

    cb->seq_p = 0;

    cb->lookup = 0;

    cb->quantlist = NULL;

    ready_codebook(cb);

    // codebook 3..10 - vector, for the residue, values -32767..32767, dimentions 1

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

        cb = &venc->codebooks[2 + book];

        cb->nentries = 5;

        cb->entries = av_malloc(sizeof(cb_entry_t) * cb->nentries);

        for (i = 0; i < cb->nentries; i++) cb->entries[i].len = i == 2 ? 1 : 3;

        cb->ndimentions = 1;

        cb->delta = 1 << ((7 - book) * 2);

        cb->min = -cb->delta*2;

        cb->seq_p = 0;

        cb->lookup = 2;

        cb->quantlist = av_malloc(sizeof(int) * cb_lookup_vals(cb->lookup, cb->ndimentions, cb->nentries));

        for (i = 0; i < cb->nentries; i++) cb->quantlist[i] = i;

        ready_codebook(cb);

    }

    venc->nfloors = 1;

    venc->floors = av_malloc(sizeof(floor_t) * venc->nfloors);

    // just 1 floor

    fc = &venc->floors[0];

    fc->partitions = 1;

    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);

    for (i = 0; i < fc->partitions; i++) fc->partition_to_class = 0;

    fc->nclasses = 1;

    fc->classes = av_malloc(sizeof(floor_class_t) * fc->nclasses);

    for (i = 0; i < fc->nclasses; i++) {

        floor_class_t * c = &fc->classes[i];

        int j, books;

        c->dim = 1;

        c->subclass = 0;

        c->masterbook = 0;

        books = (1 << c->subclass);

        c->books = av_malloc(sizeof(int) * books);

        for (j = 0; j < books; j++) c->books[j] = 0;

    }

    fc->multiplier = 1;

    fc->rangebits = venc->blocksize[0];

    fc->values = 2;

    for (i = 0; i < fc->partitions; i++)

        fc->values += fc->classes[fc->partition_to_class[i]].dim;

    fc->list = av_malloc(sizeof(*fc->list) * fc->values);

    fc->list[0].x = 0;

    fc->list[1].x = 1 << fc->rangebits;

    for (i = 2; i < fc->values; i++) fc->list[i].x = i * 5;

    venc->nresidues = 1;

    venc->residues = av_malloc(sizeof(residue_t) * venc->nresidues);

    // single residue

    rc = &venc->residues[0];

    rc->type = 0;

    rc->begin = 0;

    rc->end = 1 << venc->blocksize[0];

    rc->partition_size = 64;

    rc->classifications = 1;

    rc->classbook = 1;

    rc->books = av_malloc(sizeof(int[8]) * rc->classifications);

    for (i = 0; i < 8; i++) rc->books[0][i] = 2 + i;

    venc->nmappings = 1;

    venc->mappings = av_malloc(sizeof(mapping_t) * venc->nmappings);

    // single mapping

    mc = &venc->mappings[0];

    mc->submaps = 1;

    mc->mux = av_malloc(sizeof(int) * venc->channels);

    for (i = 0; i < venc->channels; i++) mc->mux[i] = 0;

    mc->floor = av_malloc(sizeof(int) * mc->submaps);

    mc->residue = av_malloc(sizeof(int) * mc->submaps);

    for (i = 0; i < mc->submaps; i++) {

        mc->floor[i] = 0;

        mc->residue[i] = 0;

    }

    venc->nmodes = 1;

    venc->modes = av_malloc(sizeof(vorbis_mode_t) * venc->nmodes);

    // single mode

    venc->modes[0].blockflag = 0;

    venc->modes[0].mapping = 0;

}


static int iscsi_readcapacity_sync(IscsiLun *iscsilun)

{

    struct scsi_task *task = NULL;

    struct scsi_readcapacity10 *rc10 = NULL;

    struct scsi_readcapacity16 *rc16 = NULL;

    int ret = 0;

    int retries = ISCSI_CMD_RETRIES;

    do {

        if (task != NULL) {

            scsi_free_scsi_task(task);

            task = NULL;

        }

        switch (iscsilun->type) {

        case TYPE_DISK:

            task = iscsi_readcapacity16_sync(iscsilun->iscsi, iscsilun->lun);

            if (task != NULL && task->status == SCSI_STATUS_GOOD) {

                rc16 = scsi_datain_unmarshall(task);

                if (rc16 == NULL) {

                    error_report("iSCSI: Failed to unmarshall readcapacity16 data.");

                    ret = -EINVAL;

                } else {

                    iscsilun->block_size = rc16->block_length;

                    iscsilun->num_blocks = rc16->returned_lba + 1;

                    iscsilun->lbpme = rc16->lbpme;

                    iscsilun->lbprz = rc16->lbprz;

                }

            }

            break;

        case TYPE_ROM:

            task = iscsi_readcapacity10_sync(iscsilun->iscsi, iscsilun->lun, 0, 0);

            if (task != NULL && task->status == SCSI_STATUS_GOOD) {

                rc10 = scsi_datain_unmarshall(task);

                if (rc10 == NULL) {

                    error_report("iSCSI: Failed to unmarshall readcapacity10 data.");

                    ret = -EINVAL;

                } else {

                    iscsilun->block_size = rc10->block_size;

                    if (rc10->lba == 0) {

                        /* blank disk loaded */

                        iscsilun->num_blocks = 0;

                    } else {

                        iscsilun->num_blocks = rc10->lba + 1;

                    }

                }

            }

            break;

        default:

            return 0;

        }

    } while (task != NULL && task->status == SCSI_STATUS_CHECK_CONDITION

             && task->sense.key == SCSI_SENSE_UNIT_ATTENTION

             && retries-- > 0);

    if (task == NULL || task->status != SCSI_STATUS_GOOD) {

        error_report("iSCSI: failed to send readcapacity10 command.");

        ret = -EINVAL;

    }

    if (task) {

        scsi_free_scsi_task(task);

    }

    return ret;

}


int kvm_arch_process_async_events(CPUState *env)
{
    if (kvm_irqchip_in_kernel()) {
    if (env->interrupt_request & (CPU_INTERRUPT_HARD | CPU_INTERRUPT_NMI)) {
    if (env->interrupt_request & CPU_INTERRUPT_INIT) {
        do_cpu_init(env);
    if (env->interrupt_request & CPU_INTERRUPT_SIPI) {
        do_cpu_sipi(env);
    return env->halted;


static void gen_slbmte(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    gen_helper_store_slb(cpu_env, cpu_gpr[rB(ctx->opcode)],

                         cpu_gpr[rS(ctx->opcode)]);

#endif

}


static void shifter_out_im(TCGv var, int shift)

{

    TCGv tmp = new_tmp();

    if (shift == 0) {

        tcg_gen_andi_i32(tmp, var, 1);

    } else {

        tcg_gen_shri_i32(tmp, var, shift);

        if (shift != 31)

            tcg_gen_andi_i32(tmp, tmp, 1);

    }

    gen_set_CF(tmp);

    dead_tmp(tmp);

}


static kbd_layout_t *parse_keyboard_layout(const name2keysym_t *table,

                                           const char *language,

                                           kbd_layout_t *k)

{

    FILE *f;

    char * filename;

    char line[1024];

    int len;

    filename = qemu_find_file(QEMU_FILE_TYPE_KEYMAP, language);

    f = filename ? fopen(filename, "r") : NULL;

    g_free(filename);

    if (!f) {

        fprintf(stderr, "Could not read keymap file: '%s'\n", language);

        return NULL;

    }

    if (!k) {

        k = g_malloc0(sizeof(kbd_layout_t));

    }

    for(;;) {

        if (fgets(line, 1024, f) == NULL) {

            break;

        }

        len = strlen(line);

        if (len > 0 && line[len - 1] == '\n') {

            line[len - 1] = '\0';

        }

        if (line[0] == '#') {

            continue;

        }

        if (!strncmp(line, "map ", 4)) {

            continue;

        }

        if (!strncmp(line, "include ", 8)) {

            parse_keyboard_layout(table, line + 8, k);

        } else {

            char *end_of_keysym = line;

            while (*end_of_keysym != 0 && *end_of_keysym != ' ') {

                end_of_keysym++;

            }

            if (*end_of_keysym) {

                int keysym;

                *end_of_keysym = 0;

                keysym = get_keysym(table, line);

                if (keysym == 0) {

                    /* fprintf(stderr, "Warning: unknown keysym %s\n", line);*/

                } else {

                    const char *rest = end_of_keysym + 1;

                    int keycode = strtol(rest, NULL, 0);

                    if (strstr(rest, "numlock")) {

                        add_to_key_range(&k->keypad_range, keycode);

                        add_to_key_range(&k->numlock_range, keysym);

                        /* fprintf(stderr, "keypad keysym %04x keycode %d\n",

                                   keysym, keycode); */

                    }

                    if (strstr(rest, "shift")) {

                        keycode |= SCANCODE_SHIFT;

                    }

                    if (strstr(rest, "altgr")) {

                        keycode |= SCANCODE_ALTGR;

                    }

                    if (strstr(rest, "ctrl")) {

                        keycode |= SCANCODE_CTRL;

                    }

                    add_keysym(line, keysym, keycode, k);

                    if (strstr(rest, "addupper")) {

                        char *c;

                        for (c = line; *c; c++) {

                            *c = qemu_toupper(*c);

                        }

                        keysym = get_keysym(table, line);

                        if (keysym) {

                            add_keysym(line, keysym,

                                       keycode | SCANCODE_SHIFT, k);

                        }

                    }

                }

            }

        }

    }

    fclose(f);

    return k;

}


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

    int i;

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

        if(nnzc[ scan8[i] ] || block[i*16])

            ff_h264_idct_add_mmx    (dest[(i&4)>>2] + block_offset[i], block + i*16, stride);

    }

}


static void vmxnet3_deactivate_device(VMXNET3State *s)

{

    VMW_CBPRN("Deactivating vmxnet3...");

    s->device_active = false;

}


e1000e_set_pbaclr(E1000ECore *core, int index, uint32_t val)

{

    int i;

    core->mac[PBACLR] = val & E1000_PBACLR_VALID_MASK;

    if (msix_enabled(core->owner)) {

        return;

    }

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

        if (core->mac[PBACLR] & BIT(i)) {

            msix_clr_pending(core->owner, i);

        }

    }

}


void qemu_spice_vm_change_state_handler(void *opaque, int running, int reason)

{

    SimpleSpiceDisplay *ssd = opaque;

    if (running) {

        ssd->worker->start(ssd->worker);

    } else {

        qemu_mutex_unlock_iothread();

        ssd->worker->stop(ssd->worker);

        qemu_mutex_lock_iothread();

    }

    ssd->running = running;

}


static void do_audio_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         unsigned char *buf, int size)

{

    uint8_t *buftmp;

    uint8_t audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */

    uint8_t audio_out[4*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it - yep really WMA */

    int size_out, frame_bytes, ret;

    AVCodecContext *enc;

    enc = &ost->st->codec;

    if (ost->audio_resample) {

        buftmp = audio_buf;

        size_out = audio_resample(ost->resample,

                                  (short *)buftmp, (short *)buf,

                                  size / (ist->st->codec.channels * 2));

        size_out = size_out * enc->channels * 2;

    } else {

        buftmp = buf;

        size_out = size;

    }

    /* now encode as many frames as possible */

    if (enc->frame_size > 1) {

        /* output resampled raw samples */

        fifo_write(&ost->fifo, buftmp, size_out,

                   &ost->fifo.wptr);

        frame_bytes = enc->frame_size * 2 * enc->channels;

        while (fifo_read(&ost->fifo, audio_buf, frame_bytes,

                     &ost->fifo.rptr) == 0) {

            ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),

                                       (short *)audio_buf);

            av_write_frame(s, ost->index, audio_out, ret);

        }

    } else {

        /* output a pcm frame */

        /* XXX: change encoding codec API to avoid this ? */

        switch(enc->codec->id) {

        case CODEC_ID_PCM_S16LE:

        case CODEC_ID_PCM_S16BE:

        case CODEC_ID_PCM_U16LE:

        case CODEC_ID_PCM_U16BE:

            break;

        default:

            size_out = size_out >> 1;

            break;

        }

        ret = avcodec_encode_audio(enc, audio_out, size_out,

				   (short *)buftmp);

        av_write_frame(s, ost->index, audio_out, ret);

    }

}


static int ehci_state_waitlisthead(EHCIState *ehci,  int async)

{

    EHCIqh qh;

    int i = 0;

    int again = 0;

    uint32_t entry = ehci->asynclistaddr;

    /* set reclamation flag at start event (4.8.6) */

    if (async) {

        ehci_set_usbsts(ehci, USBSTS_REC);

    }

    ehci_queues_rip_unused(ehci, async);

    /*  Find the head of the list (4.9.1.1) */

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

        get_dwords(ehci, NLPTR_GET(entry), (uint32_t *) &qh,

                   sizeof(EHCIqh) >> 2);

        ehci_trace_qh(NULL, NLPTR_GET(entry), &qh);

        if (qh.epchar & QH_EPCHAR_H) {

            if (async) {

                entry |= (NLPTR_TYPE_QH << 1);

            }

            ehci_set_fetch_addr(ehci, async, entry);

            ehci_set_state(ehci, async, EST_FETCHENTRY);

            again = 1;

            goto out;

        }

        entry = qh.next;

        if (entry == ehci->asynclistaddr) {

            break;

        }

    }

    /* no head found for list. */

    ehci_set_state(ehci, async, EST_ACTIVE);

out:

    return again;

}


static void aux_bus_map_device(AUXBus *bus, AUXSlave *dev, hwaddr addr)

{

    memory_region_add_subregion(bus->aux_io, addr, dev->mmio);

}


static int verify_md5(HEVCContext *s, AVFrame *frame)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

    int pixel_shift = desc->comp[0].depth_minus1 > 7;

    int i, j;

    if (!desc)

        return AVERROR(EINVAL);

    av_log(s->avctx, AV_LOG_DEBUG, "Verifying checksum for frame with POC %d: ",

           s->poc);

    /* the checksums are LE, so we have to byteswap for >8bpp formats

     * on BE arches */

#if HAVE_BIGENDIAN

    if (pixel_shift && !s->checksum_buf) {

        av_fast_malloc(&s->checksum_buf, &s->checksum_buf_size,

                       FFMAX3(frame->linesize[0], frame->linesize[1],

                              frame->linesize[2]));

        if (!s->checksum_buf)

            return AVERROR(ENOMEM);

    }

#endif

    for (i = 0; frame->data[i]; i++) {

        int width  = s->avctx->coded_width;

        int height = s->avctx->coded_height;

        int w = (i == 1 || i == 2) ? (width  >> desc->log2_chroma_w) : width;

        int h = (i == 1 || i == 2) ? (height >> desc->log2_chroma_h) : height;

        uint8_t md5[16];

        av_md5_init(s->md5_ctx);

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

            const uint8_t *src = frame->data[i] + j * frame->linesize[i];

#if HAVE_BIGENDIAN

            if (pixel_shift) {

                s->dsp.bswap16_buf((uint16_t*)s->checksum_buf,

                                   (const uint16_t*)src, w);

                src = s->checksum_buf;

            }

#endif

            av_md5_update(s->md5_ctx, src, w << pixel_shift);

        }

        av_md5_final(s->md5_ctx, md5);

        if (!memcmp(md5, s->md5[i], 16)) {

            av_log   (s->avctx, AV_LOG_DEBUG, "plane %d - correct ", i);

            print_md5(s->avctx, AV_LOG_DEBUG, md5);

            av_log   (s->avctx, AV_LOG_DEBUG, "; ");

        } else {

            av_log   (s->avctx, AV_LOG_ERROR, "mismatching checksum of plane %d - ", i);

            print_md5(s->avctx, AV_LOG_ERROR, md5);

            av_log   (s->avctx, AV_LOG_ERROR, " != ");

            print_md5(s->avctx, AV_LOG_ERROR, s->md5[i]);

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

            return AVERROR_INVALIDDATA;

        }

    }

    av_log(s->avctx, AV_LOG_DEBUG, "\n");

    return 0;

}


static int dxva2_vc1_start_frame(AVCodecContext *avctx,

                                 av_unused const uint8_t *buffer,

                                 av_unused uint32_t size)

{

    const VC1Context *v = avctx->priv_data;

    AVDXVAContext *ctx = avctx->hwaccel_context;

    struct dxva2_picture_context *ctx_pic = v->s.current_picture_ptr->hwaccel_picture_private;

    if (!DXVA_CONTEXT_VALID(avctx, ctx))

        return -1;

    assert(ctx_pic);

    fill_picture_parameters(avctx, ctx, v, &ctx_pic->pp);

    ctx_pic->bitstream_size = 0;

    ctx_pic->bitstream      = NULL;

    return 0;

}


static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){

    while(bsfc){

        AVPacket new_pkt= *pkt;

        int a= av_bitstream_filter_filter(bsfc, avctx, NULL,

                                          &new_pkt.data, &new_pkt.size,

                                          pkt->data, pkt->size,

                                          pkt->flags & PKT_FLAG_KEY);

        if(a){

            av_free_packet(pkt);

            new_pkt.destruct= av_destruct_packet;

        }

        *pkt= new_pkt;

        bsfc= bsfc->next;

    }

    av_interleaved_write_frame(s, pkt);

}


static inline void h264_loop_filter_luma_c(uint8_t *pix, int xstride, int ystride, int alpha, int beta, int *tc0)

{

    int i, d;

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

        if( tc0[i] < 0 ) {

            pix += 4*ystride;

            continue;

        }

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

            const int p0 = pix[-1*xstride];

            const int p1 = pix[-2*xstride];

            const int p2 = pix[-3*xstride];

            const int q0 = pix[0];

            const int q1 = pix[1*xstride];

            const int q2 = pix[2*xstride];

            if( ABS( p0 - q0 ) < alpha &&

                ABS( p1 - p0 ) < beta &&

                ABS( q1 - q0 ) < beta ) {

                int tc = tc0[i];

                int i_delta;

                if( ABS( p2 - p0 ) < beta ) {

                    pix[-2*xstride] = p1 + clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0[i], tc0[i] );

                    tc++;

                }

                if( ABS( q2 - q0 ) < beta ) {

                    pix[xstride] = q1 + clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0[i], tc0[i] );

                    tc++;

                }

                i_delta = clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-xstride] = clip_uint8( p0 + i_delta );    /* p0' */

                pix[0]        = clip_uint8( q0 - i_delta );    /* q0' */

            }

            pix += ystride;

        }

    }

}


int64_t av_gettime_relative(void)

{

#if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)

    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;

#else

    return av_gettime() + 42 * 60 * 60 * INT64_C(1000000);

#endif

}


static void update_odml_entry(AVFormatContext *s, int stream_index, int64_t ix)

{

    AVIOContext *pb = s->pb;

    AVIContext *avi = s->priv_data;

    AVIStream *avist = s->streams[stream_index]->priv_data;

    int64_t pos;

    int au_byterate, au_ssize, au_scale;

    avio_flush(pb);

    pos = avio_tell(pb);

    /* Updating one entry in the AVI OpenDML master index */

    avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);

    ffio_wfourcc(pb, "indx");             /* enabling this entry */

    avio_skip(pb, 8);

    avio_wl32(pb, avi->riff_id);          /* nEntriesInUse */

    avio_skip(pb, 16 * avi->riff_id);

    avio_wl64(pb, ix);                    /* qwOffset */

    avio_wl32(pb, pos - ix);              /* dwSize */

    ff_parse_specific_params(s->streams[stream_index], &au_byterate, &au_ssize, &au_scale);

    if (s->streams[stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {

        uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);

        if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {

            avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");

            avist->sample_requested = 1;

        }

        avio_wl32(pb, audio_segm_size / au_ssize);  /* dwDuration (sample count) */

    } else

        avio_wl32(pb, avist->indexes.entry);  /* dwDuration (packet count) */

    avio_seek(pb, pos, SEEK_SET);

}


av_cold void ff_msmpeg4_encode_init(MpegEncContext *s)

{

    static int init_done=0;

    int i;

    ff_msmpeg4_common_init(s);

    if(s->msmpeg4_version>=4){

        s->min_qcoeff= -255;

        s->max_qcoeff=  255;

    }

    if (!init_done) {

        /* init various encoding tables */

        init_done = 1;

        init_mv_table(&ff_mv_tables[0]);

        init_mv_table(&ff_mv_tables[1]);

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

            ff_init_rl(&ff_rl_table[i], ff_static_rl_table_store[i]);

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

            int level;

            for (level = 1; level <= MAX_LEVEL; level++) {

                int run;

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

                    int last;

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

                        rl_length[i][level][run][last]= get_size_of_code(s, &ff_rl_table[  i], last, run, level, 0);

                    }

                }

            }

        }

    }

}


int check_stream_specifier(AVFormatContext *s, AVStream *st, const char *spec)

{

    if (*spec <= '9' && *spec >= '0') /* opt:index */

        return strtol(spec, NULL, 0) == st->index;

    else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||

             *spec == 't') { /* opt:[vasdt] */

        enum AVMediaType type;

        switch (*spec++) {

        case 'v': type = AVMEDIA_TYPE_VIDEO;      break;

        case 'a': type = AVMEDIA_TYPE_AUDIO;      break;

        case 's': type = AVMEDIA_TYPE_SUBTITLE;   break;

        case 'd': type = AVMEDIA_TYPE_DATA;       break;

        case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;

        default:  av_assert0(0);

        }

        if (type != st->codec->codec_type)

            return 0;

        if (*spec++ == ':') { /* possibly followed by :index */

            int i, index = strtol(spec, NULL, 0);

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

                if (s->streams[i]->codec->codec_type == type && index-- == 0)

                   return i == st->index;

            return 0;

        }

        return 1;

    } else if (*spec == 'p' && *(spec + 1) == ':') {

        int prog_id, i, j;

        char *endptr;

        spec += 2;

        prog_id = strtol(spec, &endptr, 0);

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

            if (s->programs[i]->id != prog_id)

                continue;

            if (*endptr++ == ':') {

                int stream_idx = strtol(endptr, NULL, 0);

                return stream_idx >= 0 &&

                    stream_idx < s->programs[i]->nb_stream_indexes &&

                    st->index == s->programs[i]->stream_index[stream_idx];

            }

            for (j = 0; j < s->programs[i]->nb_stream_indexes; j++)

                if (st->index == s->programs[i]->stream_index[j])

                    return 1;

        }

        return 0;

    } else if (*spec == '#') {

        int sid;

        char *endptr;

        sid = strtol(spec + 1, &endptr, 0);

        if (!*endptr)

            return st->id == sid;

    } else if (!*spec) /* empty specifier, matches everything */

        return 1;

    av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);

    return AVERROR(EINVAL);

}


static void filter_mb_edgecv( H264Context *h, uint8_t *pix, int stride, int16_t bS[4], int qp ) {

    const int index_a = qp + h->slice_alpha_c0_offset;

    const int alpha = (alpha_table+52)[index_a];

    const int beta  = (beta_table+52)[qp + h->slice_beta_offset];

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

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = (tc0_table+52)[index_a][bS[0]]+1;

        tc[1] = (tc0_table+52)[index_a][bS[1]]+1;

        tc[2] = (tc0_table+52)[index_a][bS[2]]+1;

        tc[3] = (tc0_table+52)[index_a][bS[3]]+1;

        h->s.dsp.h264_h_loop_filter_chroma(pix, stride, alpha, beta, tc);

    } else {

        h->s.dsp.h264_h_loop_filter_chroma_intra(pix, stride, alpha, beta);

    }

}


int x86_cpu_handle_mmu_fault(CPUState *cs, vaddr addr,

                             int is_write1, int mmu_idx)

{

    X86CPU *cpu = X86_CPU(cs);

    CPUX86State *env = &cpu->env;

    uint64_t ptep, pte;

    target_ulong pde_addr, pte_addr;

    int error_code = 0;

    int is_dirty, prot, page_size, is_write, is_user;

    hwaddr paddr;

    uint64_t rsvd_mask = PG_HI_RSVD_MASK;

    uint32_t page_offset;

    target_ulong vaddr;

    is_user = mmu_idx == MMU_USER_IDX;

#if defined(DEBUG_MMU)

    printf("MMU fault: addr=%" VADDR_PRIx " w=%d u=%d eip=" TARGET_FMT_lx "\n",

           addr, is_write1, is_user, env->eip);

#endif

    is_write = is_write1 & 1;

    if (!(env->cr[0] & CR0_PG_MASK)) {

        pte = addr;

#ifdef TARGET_X86_64

        if (!(env->hflags & HF_LMA_MASK)) {

            /* Without long mode we can only address 32bits in real mode */

            pte = (uint32_t)pte;

        }

#endif

        prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

        page_size = 4096;

        goto do_mapping;

    }

    if (!(env->efer & MSR_EFER_NXE)) {

        rsvd_mask |= PG_NX_MASK;

    }

    if (env->cr[4] & CR4_PAE_MASK) {

        uint64_t pde, pdpe;

        target_ulong pdpe_addr;

#ifdef TARGET_X86_64

        if (env->hflags & HF_LMA_MASK) {

            uint64_t pml4e_addr, pml4e;

            int32_t sext;

            /* test virtual address sign extension */

            sext = (int64_t)addr >> 47;

            if (sext != 0 && sext != -1) {

                env->error_code = 0;

                cs->exception_index = EXCP0D_GPF;

                return 1;

            }

            pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) &

                env->a20_mask;

            pml4e = ldq_phys(cs->as, pml4e_addr);

            if (!(pml4e & PG_PRESENT_MASK)) {

                goto do_fault;

            }

            if (pml4e & (rsvd_mask | PG_PSE_MASK)) {

                goto do_fault_rsvd;

            }

            if (!(pml4e & PG_ACCESSED_MASK)) {

                pml4e |= PG_ACCESSED_MASK;

                stl_phys_notdirty(cs->as, pml4e_addr, pml4e);

            }

            ptep = pml4e ^ PG_NX_MASK;

            pdpe_addr = ((pml4e & PG_ADDRESS_MASK) + (((addr >> 30) & 0x1ff) << 3)) &

                env->a20_mask;

            pdpe = ldq_phys(cs->as, pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK)) {

                goto do_fault;

            }

            if (pdpe & rsvd_mask) {

                goto do_fault_rsvd;

            }

            ptep &= pdpe ^ PG_NX_MASK;

            if (!(pdpe & PG_ACCESSED_MASK)) {

                pdpe |= PG_ACCESSED_MASK;

                stl_phys_notdirty(cs->as, pdpe_addr, pdpe);

            }

            if (pdpe & PG_PSE_MASK) {

                /* 1 GB page */

                page_size = 1024 * 1024 * 1024;

                pte_addr = pdpe_addr;

                pte = pdpe;

                goto do_check_protect;

            }

        } else

#endif

        {

            /* XXX: load them when cr3 is loaded ? */

            pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) &

                env->a20_mask;

            pdpe = ldq_phys(cs->as, pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK)) {

                goto do_fault;

            }

            rsvd_mask |= PG_HI_USER_MASK | PG_NX_MASK;

            if (pdpe & rsvd_mask) {

                goto do_fault_rsvd;

            }

            ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;

        }

        pde_addr = ((pdpe & PG_ADDRESS_MASK) + (((addr >> 21) & 0x1ff) << 3)) &

            env->a20_mask;

        pde = ldq_phys(cs->as, pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            goto do_fault;

        }

        if (pde & rsvd_mask) {

            goto do_fault_rsvd;

        }

        ptep &= pde ^ PG_NX_MASK;

        if (pde & PG_PSE_MASK) {

            /* 2 MB page */

            page_size = 2048 * 1024;

            pte_addr = pde_addr;

            pte = pde;

            goto do_check_protect;

        }

        /* 4 KB page */

        if (!(pde & PG_ACCESSED_MASK)) {

            pde |= PG_ACCESSED_MASK;

            stl_phys_notdirty(cs->as, pde_addr, pde);

        }

        pte_addr = ((pde & PG_ADDRESS_MASK) + (((addr >> 12) & 0x1ff) << 3)) &

            env->a20_mask;

        pte = ldq_phys(cs->as, pte_addr);

        if (!(pte & PG_PRESENT_MASK)) {

            goto do_fault;

        }

        if (pte & rsvd_mask) {

            goto do_fault_rsvd;

        }

        /* combine pde and pte nx, user and rw protections */

        ptep &= pte ^ PG_NX_MASK;

        page_size = 4096;

    } else {

        uint32_t pde;

        /* page directory entry */

        pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) &

            env->a20_mask;

        pde = ldl_phys(cs->as, pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            goto do_fault;

        }

        ptep = pde | PG_NX_MASK;

        /* if PSE bit is set, then we use a 4MB page */

        if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

            page_size = 4096 * 1024;

            pte_addr = pde_addr;

            /* Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved.

             * Leave bits 20-13 in place for setting accessed/dirty bits below.

             */

            pte = pde | ((pde & 0x1fe000) << (32 - 13));

            rsvd_mask = 0x200000;

            goto do_check_protect_pse36;

        }

        if (!(pde & PG_ACCESSED_MASK)) {

            pde |= PG_ACCESSED_MASK;

            stl_phys_notdirty(cs->as, pde_addr, pde);

        }

        /* page directory entry */

        pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) &

            env->a20_mask;

        pte = ldl_phys(cs->as, pte_addr);

        if (!(pte & PG_PRESENT_MASK)) {

            goto do_fault;

        }

        /* combine pde and pte user and rw protections */

        ptep &= pte | PG_NX_MASK;

        page_size = 4096;

        rsvd_mask = 0;

    }

do_check_protect:

    rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK;

do_check_protect_pse36:

    if (pte & rsvd_mask) {

        goto do_fault_rsvd;

    }

    ptep ^= PG_NX_MASK;

    if ((ptep & PG_NX_MASK) && is_write1 == 2) {

        goto do_fault_protect;

    }

    switch (mmu_idx) {

    case MMU_USER_IDX:

        if (!(ptep & PG_USER_MASK)) {

            goto do_fault_protect;

        }

        if (is_write && !(ptep & PG_RW_MASK)) {

            goto do_fault_protect;

        }

        break;

    case MMU_KSMAP_IDX:

        if (is_write1 != 2 && (ptep & PG_USER_MASK)) {

            goto do_fault_protect;

        }

        /* fall through */

    case MMU_KNOSMAP_IDX:

        if (is_write1 == 2 && (env->cr[4] & CR4_SMEP_MASK) &&

            (ptep & PG_USER_MASK)) {

            goto do_fault_protect;

        }

        if ((env->cr[0] & CR0_WP_MASK) &&

            is_write && !(ptep & PG_RW_MASK)) {

            goto do_fault_protect;

        }

        break;

    default: /* cannot happen */

        break;

    }

    is_dirty = is_write && !(pte & PG_DIRTY_MASK);

    if (!(pte & PG_ACCESSED_MASK) || is_dirty) {

        pte |= PG_ACCESSED_MASK;

        if (is_dirty) {

            pte |= PG_DIRTY_MASK;

        }

        stl_phys_notdirty(cs->as, pte_addr, pte);

    }

    /* the page can be put in the TLB */

    prot = PAGE_READ;

    if (!(ptep & PG_NX_MASK))

        prot |= PAGE_EXEC;

    if (pte & PG_DIRTY_MASK) {

        /* only set write access if already dirty... otherwise wait

           for dirty access */

        if (is_user) {

            if (ptep & PG_RW_MASK)

                prot |= PAGE_WRITE;

        } else {

            if (!(env->cr[0] & CR0_WP_MASK) ||

                (ptep & PG_RW_MASK))

                prot |= PAGE_WRITE;

        }

    }

 do_mapping:

    pte = pte & env->a20_mask;

    /* align to page_size */

    pte &= PG_ADDRESS_MASK & ~(page_size - 1);

    /* Even if 4MB pages, we map only one 4KB page in the cache to

       avoid filling it too fast */

    vaddr = addr & TARGET_PAGE_MASK;

    page_offset = vaddr & (page_size - 1);

    paddr = pte + page_offset;

    tlb_set_page(cs, vaddr, paddr, prot, mmu_idx, page_size);

    return 0;

 do_fault_rsvd:

    error_code |= PG_ERROR_RSVD_MASK;

 do_fault_protect:

    error_code |= PG_ERROR_P_MASK;

 do_fault:

    error_code |= (is_write << PG_ERROR_W_BIT);

    if (is_user)

        error_code |= PG_ERROR_U_MASK;

    if (is_write1 == 2 &&

        (((env->efer & MSR_EFER_NXE) &&

          (env->cr[4] & CR4_PAE_MASK)) ||

         (env->cr[4] & CR4_SMEP_MASK)))

        error_code |= PG_ERROR_I_D_MASK;

    if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) {

        /* cr2 is not modified in case of exceptions */

        stq_phys(cs->as,

                 env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),

                 addr);

    } else {

        env->cr[2] = addr;

    }

    env->error_code = error_code;

    cs->exception_index = EXCP0E_PAGE;

    return 1;

}


uint32_t virtio_config_readb(VirtIODevice *vdev, uint32_t addr)

{

    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);

    uint8_t val;

    k->get_config(vdev, vdev->config);

    if (addr > (vdev->config_len - sizeof(val)))

        return (uint32_t)-1;

    val = ldub_p(vdev->config + addr);

    return val;

}


av_cold int ff_rdft_init(RDFTContext *s, int nbits, enum RDFTransformType trans)

{

    int n = 1 << nbits;

    int ret;

    s->nbits           = nbits;

    s->inverse         = trans == IDFT_C2R || trans == DFT_C2R;

    s->sign_convention = trans == IDFT_R2C || trans == DFT_C2R ? 1 : -1;

    if (nbits < 4 || nbits > 16)

        return AVERROR(EINVAL);

    if ((ret = ff_fft_init(&s->fft, nbits-1, trans == IDFT_C2R || trans == IDFT_R2C)) < 0)

        return ret;

    ff_init_ff_cos_tabs(nbits);

    s->tcos = ff_cos_tabs[nbits];

    s->tsin = ff_sin_tabs[nbits]+(trans == DFT_R2C || trans == DFT_C2R)*(n>>2);

#if !CONFIG_HARDCODED_TABLES

    {

        int i;

        const double theta = (trans == DFT_R2C || trans == DFT_C2R ? -1 : 1) * 2 * M_PI / n;

        for (i = 0; i < (n >> 2); i++)

            s->tsin[i] = sin(i * theta);

    }

#endif

    s->rdft_calc   = rdft_calc_c;

    if (ARCH_ARM) ff_rdft_init_arm(s);

    return 0;

}


static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)

{

    UHCIAsync *async;

    int len = 0, max_len;

    uint8_t pid;

    USBDevice *dev;

    USBEndpoint *ep;

    /* Is active ? */

    if (!(td->ctrl & TD_CTRL_ACTIVE))

        return TD_RESULT_NEXT_QH;

    async = uhci_async_find_td(s, addr, td);

    if (async) {

        /* Already submitted */

        async->queue->valid = 32;

        if (!async->done)

            return TD_RESULT_ASYNC_CONT;

        uhci_async_unlink(async);

        goto done;

    }

    /* Allocate new packet */

    async = uhci_async_alloc(uhci_queue_get(s, td), addr);

    if (!async)

        return TD_RESULT_NEXT_QH;

    /* valid needs to be large enough to handle 10 frame delay

     * for initial isochronous requests

     */

    async->queue->valid = 32;

    async->isoc  = td->ctrl & TD_CTRL_IOS;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    dev = uhci_find_device(s, (td->token >> 8) & 0x7f);

    ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);

    usb_packet_setup(&async->packet, pid, ep);

    qemu_sglist_add(&async->sgl, td->buffer, max_len);

    usb_packet_map(&async->packet, &async->sgl);

    switch(pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

        len = usb_handle_packet(dev, &async->packet);

        if (len >= 0)

            len = max_len;

        break;

    case USB_TOKEN_IN:

        len = usb_handle_packet(dev, &async->packet);

        break;

    default:

        /* invalid pid : frame interrupted */

        uhci_async_free(async);

        s->status |= UHCI_STS_HCPERR;

        uhci_update_irq(s);

        return TD_RESULT_STOP_FRAME;

    }

    if (len == USB_RET_ASYNC) {

        uhci_async_link(async);

        return TD_RESULT_ASYNC_START;

    }

    async->packet.result = len;

done:

    len = uhci_complete_td(s, td, async, int_mask);

    usb_packet_unmap(&async->packet);

    uhci_async_free(async);

    return len;

}


static int update_wrap_reference(AVFormatContext *s, AVStream *st, int stream_index)

{

    if (s->correct_ts_overflow && st->pts_wrap_bits != 64 &&

        st->pts_wrap_reference == AV_NOPTS_VALUE && st->first_dts != AV_NOPTS_VALUE) {

        int i;

        // reference time stamp should be 60 s before first time stamp

        int64_t pts_wrap_reference = st->first_dts - av_rescale(60, st->time_base.den, st->time_base.num);

        // if first time stamp is not more than 1/8 and 60s before the wrap point, subtract rather than add wrap offset

        int pts_wrap_behavior = (st->first_dts < (1LL<<st->pts_wrap_bits) - (1LL<<st->pts_wrap_bits-3)) ||

            (st->first_dts < (1LL<<st->pts_wrap_bits) - av_rescale(60, st->time_base.den, st->time_base.num)) ?

            AV_PTS_WRAP_ADD_OFFSET : AV_PTS_WRAP_SUB_OFFSET;

        AVProgram *first_program = av_find_program_from_stream(s, NULL, stream_index);

        if (!first_program) {

            int default_stream_index = av_find_default_stream_index(s);

            if (s->streams[default_stream_index]->pts_wrap_reference == AV_NOPTS_VALUE) {

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

                    s->streams[i]->pts_wrap_reference = pts_wrap_reference;

                    s->streams[i]->pts_wrap_behavior = pts_wrap_behavior;

                }

            }

            else {

                st->pts_wrap_reference = s->streams[default_stream_index]->pts_wrap_reference;

                st->pts_wrap_behavior = s->streams[default_stream_index]->pts_wrap_behavior;

            }

        }

        else {

            AVProgram *program = first_program;

            while (program) {

                if (program->pts_wrap_reference != AV_NOPTS_VALUE) {

                    pts_wrap_reference = program->pts_wrap_reference;

                    pts_wrap_behavior = program->pts_wrap_behavior;

                    break;

                }

                program = av_find_program_from_stream(s, program, stream_index);

            }

            // update every program with differing pts_wrap_reference

            program = first_program;

            while(program) {

                if (program->pts_wrap_reference != pts_wrap_reference) {

                    for (i=0; i<program->nb_stream_indexes; i++) {

                        s->streams[program->stream_index[i]]->pts_wrap_reference = pts_wrap_reference;

                        s->streams[program->stream_index[i]]->pts_wrap_behavior = pts_wrap_behavior;

                    }

                    program->pts_wrap_reference = pts_wrap_reference;

                    program->pts_wrap_behavior = pts_wrap_behavior;

                }

                program = av_find_program_from_stream(s, program, stream_index);

            }

        }

        return 1;

    }

    return 0;

}


static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)

{

    PtyCharDriver *s = chr->opaque;

    if (!s->connected) {

        /* guest sends data, check for (re-)connect */

        pty_chr_update_read_handler_locked(chr);

        return 0;

    }

    return io_channel_send(s->fd, buf, len);

}


int vnc_client_io_error(VncState *vs, int ret, int last_errno)

{

    if (ret == 0 || ret == -1) {

        if (ret == -1) {

            switch (last_errno) {

                case EINTR:

                case EAGAIN:

#ifdef _WIN32

                case WSAEWOULDBLOCK:

#endif

                    return 0;

                default:

                    break;

            }

        }

        VNC_DEBUG("Closing down client sock %d %d\n", ret, ret < 0 ? last_errno : 0);

        qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);

        closesocket(vs->csock);

        qemu_del_timer(vs->timer);

        qemu_free_timer(vs->timer);

        if (vs->input.buffer) qemu_free(vs->input.buffer);

        if (vs->output.buffer) qemu_free(vs->output.buffer);

#ifdef CONFIG_VNC_TLS

        vnc_tls_client_cleanup(vs);

#endif /* CONFIG_VNC_TLS */

#ifdef CONFIG_VNC_SASL

        vnc_sasl_client_cleanup(vs);

#endif /* CONFIG_VNC_SASL */

        audio_del(vs);

        VncState *p, *parent = NULL;

        for (p = vs->vd->clients; p != NULL; p = p->next) {

            if (p == vs) {

                if (parent)

                    parent->next = p->next;

                else

                    vs->vd->clients = p->next;

                break;

            }

            parent = p;

        }

        if (!vs->vd->clients)

            dcl->idle = 1;

        qemu_free(vs->server.ds->data);

        qemu_free(vs->server.ds);

        qemu_free(vs->guest.ds);

        qemu_free(vs);

        return 0;

    }

    return ret;

}


static int get_nb_samples(AVCodecContext *avctx, const uint8_t *buf,
                          int buf_size, int *coded_samples)
{
    ADPCMDecodeContext *s = avctx->priv_data;
    int nb_samples        = 0;
    int ch                = avctx->channels;
    int has_coded_samples = 0;
    int header_size;
    *coded_samples = 0;
    switch (avctx->codec->id) {
    /* constant, only check buf_size */
    case CODEC_ID_ADPCM_EA_XAS:
        if (buf_size < 76 * ch)
        nb_samples = 128;
        break;
    case CODEC_ID_ADPCM_IMA_QT:
        if (buf_size < 34 * ch)
        nb_samples = 64;
        break;
    /* simple 4-bit adpcm */
    case CODEC_ID_ADPCM_CT:
    case CODEC_ID_ADPCM_IMA_EA_SEAD:
    case CODEC_ID_ADPCM_IMA_WS:
    case CODEC_ID_ADPCM_YAMAHA:
        nb_samples = buf_size * 2 / ch;
        break;
    }
    if (nb_samples)
        return nb_samples;
    /* simple 4-bit adpcm, with header */
    header_size = 0;
    switch (avctx->codec->id) {
        case CODEC_ID_ADPCM_4XM:
        case CODEC_ID_ADPCM_IMA_ISS:     header_size = 4 * ch;      break;
        case CODEC_ID_ADPCM_IMA_AMV:     header_size = 8;           break;
        case CODEC_ID_ADPCM_IMA_SMJPEG:  header_size = 4;           break;
    }
    if (header_size > 0)
        return (buf_size - header_size) * 2 / ch;
    /* more complex formats */
    switch (avctx->codec->id) {
    case CODEC_ID_ADPCM_EA:
        has_coded_samples = 1;
        if (buf_size < 4)
        *coded_samples  = AV_RL32(buf);
        *coded_samples -= *coded_samples % 28;
        nb_samples      = (buf_size - 12) / 30 * 28;
        break;
    case CODEC_ID_ADPCM_IMA_EA_EACS:
        has_coded_samples = 1;
        if (buf_size < 4)
        *coded_samples = AV_RL32(buf);
        nb_samples     = (buf_size - (4 + 8 * ch)) * 2 / ch;
        break;
    case CODEC_ID_ADPCM_EA_MAXIS_XA:
        nb_samples = ((buf_size - ch) / (2 * ch)) * 2 * ch;
        break;
    case CODEC_ID_ADPCM_EA_R1:
    case CODEC_ID_ADPCM_EA_R2:
    case CODEC_ID_ADPCM_EA_R3:
        /* maximum number of samples */
        /* has internal offsets and a per-frame switch to signal raw 16-bit */
        has_coded_samples = 1;
        if (buf_size < 4)
        switch (avctx->codec->id) {
        case CODEC_ID_ADPCM_EA_R1:
            header_size    = 4 + 9 * ch;
            *coded_samples = AV_RL32(buf);
            break;
        case CODEC_ID_ADPCM_EA_R2:
            header_size    = 4 + 5 * ch;
            *coded_samples = AV_RL32(buf);
            break;
        case CODEC_ID_ADPCM_EA_R3:
            header_size    = 4 + 5 * ch;
            *coded_samples = AV_RB32(buf);
            break;
        }
        *coded_samples -= *coded_samples % 28;
        nb_samples      = (buf_size - header_size) * 2 / ch;
        nb_samples     -= nb_samples % 28;
        break;
    case CODEC_ID_ADPCM_IMA_DK3:
        if (avctx->block_align > 0)
            buf_size = FFMIN(buf_size, avctx->block_align);
        nb_samples = ((buf_size - 16) * 8 / 3) / ch;
        break;
    case CODEC_ID_ADPCM_IMA_DK4:
        nb_samples = 1 + (buf_size - 4 * ch) * 2 / ch;
        break;
    case CODEC_ID_ADPCM_IMA_WAV:
        if (avctx->block_align > 0)
            buf_size = FFMIN(buf_size, avctx->block_align);
        nb_samples = 1 + (buf_size - 4 * ch) / (4 * ch) * 8;
        break;
    case CODEC_ID_ADPCM_MS:
        if (avctx->block_align > 0)
            buf_size = FFMIN(buf_size, avctx->block_align);
        nb_samples = 2 + (buf_size - 7 * ch) * 2 / ch;
        break;
    case CODEC_ID_ADPCM_SBPRO_2:
    case CODEC_ID_ADPCM_SBPRO_3:
    case CODEC_ID_ADPCM_SBPRO_4:
    {
        int samples_per_byte;
        switch (avctx->codec->id) {
        case CODEC_ID_ADPCM_SBPRO_2: samples_per_byte = 4; break;
        case CODEC_ID_ADPCM_SBPRO_3: samples_per_byte = 3; break;
        case CODEC_ID_ADPCM_SBPRO_4: samples_per_byte = 2; break;
        }
        if (!s->status[0].step_index) {
            nb_samples++;
            buf_size -= ch;
        }
        nb_samples += buf_size * samples_per_byte / ch;
        break;
    }
    case CODEC_ID_ADPCM_SWF:
    {
        int buf_bits       = buf_size * 8 - 2;
        int nbits          = (buf[0] >> 6) + 2;
        int block_hdr_size = 22 * ch;
        int block_size     = block_hdr_size + nbits * ch * 4095;
        int nblocks        = buf_bits / block_size;
        int bits_left      = buf_bits - nblocks * block_size;
        nb_samples         = nblocks * 4096;
        if (bits_left >= block_hdr_size)
            nb_samples += 1 + (bits_left - block_hdr_size) / (nbits * ch);
        break;
    }
    case CODEC_ID_ADPCM_THP:
        has_coded_samples = 1;
        if (buf_size < 8)
        *coded_samples  = AV_RB32(&buf[4]);
        *coded_samples -= *coded_samples % 14;
        nb_samples      = (buf_size - 80) / (8 * ch) * 14;
        break;
    case CODEC_ID_ADPCM_XA:
        nb_samples = (buf_size / 128) * 224 / ch;
        break;
    }
    /* validate coded sample count */
    if (has_coded_samples && (*coded_samples <= 0 || *coded_samples > nb_samples))
        return AVERROR_INVALIDDATA;
    return nb_samples;
}


static int64_t calculate_mode_score(CinepakEncContext *s, CinepakMode mode, int h, int v1_size, int v4_size, int v4, strip_info *info)

{

    //score = FF_LAMBDA_SCALE * error + lambda * bits

    int x;

    int entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4;

    int mb_count = s->w * h / MB_AREA;

    mb_info *mb;

    int64_t score1, score2, score3;

    int64_t ret = s->lambda * ((v1_size ? CHUNK_HEADER_SIZE + v1_size * entry_size : 0) +

                   (v4_size ? CHUNK_HEADER_SIZE + v4_size * entry_size : 0) +

                   CHUNK_HEADER_SIZE) << 3;

    //av_log(s->avctx, AV_LOG_INFO, "sizes %3i %3i -> %9li score mb_count %i", v1_size, v4_size, ret, mb_count);

    switch(mode) {

    case MODE_V1_ONLY:

        //one byte per MB

        ret += s->lambda * 8 * mb_count;

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

            mb = &s->mb[x];

            ret += FF_LAMBDA_SCALE * mb->v1_error;

            mb->best_encoding = ENC_V1;

        }

        break;

    case MODE_V1_V4:

        //9 or 33 bits per MB

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

            mb = &s->mb[x];

            score1 = s->lambda * 9  + FF_LAMBDA_SCALE * mb->v1_error;

            score2 = s->lambda * 33 + FF_LAMBDA_SCALE * mb->v4_error[v4];

            if(score1 <= score2) {

                ret += score1;

                mb->best_encoding = ENC_V1;

            } else {

                ret += score2;

                mb->best_encoding = ENC_V4;

            }

        }

        break;

    case MODE_MC:

        //1, 10 or 34 bits per MB

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

            mb = &s->mb[x];

            score1 = s->lambda * 1  + FF_LAMBDA_SCALE * mb->skip_error;

            score2 = s->lambda * 10 + FF_LAMBDA_SCALE * mb->v1_error;

            score3 = s->lambda * 34 + FF_LAMBDA_SCALE * mb->v4_error[v4];

            if(score1 <= score2 && score1 <= score3) {

                ret += score1;

                mb->best_encoding = ENC_SKIP;

            } else if(score2 <= score1 && score2 <= score3) {

                ret += score2;

                mb->best_encoding = ENC_V1;

            } else {

                ret += score3;

                mb->best_encoding = ENC_V4;

            }

        }

        break;

    }

    return ret;

}


static inline int GET_TOK(TM2Context *ctx,int type) {

    if(ctx->tok_ptrs[type] >= ctx->tok_lens[type]) {

        av_log(ctx->avctx, AV_LOG_ERROR, "Read token from stream %i out of bounds (%i>=%i)\n", type, ctx->tok_ptrs[type], ctx->tok_lens[type]);

        return 0;

    }

    if(type <= TM2_MOT)

        return ctx->deltas[type][ctx->tokens[type][ctx->tok_ptrs[type]++]];

    return ctx->tokens[type][ctx->tok_ptrs[type]++];

}


int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)

{

    RTSPState *rt = s->priv_data;

    AVStream *st = NULL;

    int reordering_queue_size = rt->reordering_queue_size;

    if (reordering_queue_size < 0) {

        if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)

            reordering_queue_size = 0;

        else

            reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;

    }

    /* open the RTP context */

    if (rtsp_st->stream_index >= 0)

        st = s->streams[rtsp_st->stream_index];

    if (!st)

        s->ctx_flags |= AVFMTCTX_NOHEADER;

    if (CONFIG_RTSP_MUXER && s->oformat) {

        int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv,

                                        s, st, rtsp_st->rtp_handle,

                                        RTSP_TCP_MAX_PACKET_SIZE,

                                        rtsp_st->stream_index);

        /* Ownership of rtp_handle is passed to the rtp mux context */

        rtsp_st->rtp_handle = NULL;

        if (ret < 0)

            return ret;

        st->time_base = ((AVFormatContext*)rtsp_st->transport_priv)->streams[0]->time_base;

    } else if (rt->transport == RTSP_TRANSPORT_RAW) {

        return 0; // Don't need to open any parser here

    } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)

        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,

                                            rtsp_st->dynamic_protocol_context,

                                            rtsp_st->dynamic_handler);

    else if (CONFIG_RTPDEC)

        rtsp_st->transport_priv = ff_rtp_parse_open(s, st,

                                         rtsp_st->sdp_payload_type,

                                         reordering_queue_size);

    if (!rtsp_st->transport_priv) {

         return AVERROR(ENOMEM);

    } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP) {

        RTPDemuxContext *rtpctx = rtsp_st->transport_priv;

        rtpctx->ssrc = rtsp_st->ssrc;

        if (rtsp_st->dynamic_handler) {

            ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,

                                              rtsp_st->dynamic_protocol_context,

                                              rtsp_st->dynamic_handler);

        }

        if (rtsp_st->crypto_suite[0])

            ff_rtp_parse_set_crypto(rtsp_st->transport_priv,

                                    rtsp_st->crypto_suite,

                                    rtsp_st->crypto_params);

    }

    return 0;

}


static void chassis_control(IPMIBmcSim *ibs,

                            uint8_t *cmd, unsigned int cmd_len,

                            uint8_t *rsp, unsigned int *rsp_len,

                            unsigned int max_rsp_len)

{

    IPMIInterface *s = ibs->parent.intf;

    IPMIInterfaceClass *k = IPMI_INTERFACE_GET_CLASS(s);

    IPMI_CHECK_CMD_LEN(3);

    switch (cmd[2] & 0xf) {

    case 0: /* power down */

        rsp[2] = k->do_hw_op(s, IPMI_POWEROFF_CHASSIS, 0);

        break;

    case 1: /* power up */

        rsp[2] = k->do_hw_op(s, IPMI_POWERON_CHASSIS, 0);

        break;

    case 2: /* power cycle */

        rsp[2] = k->do_hw_op(s, IPMI_POWERCYCLE_CHASSIS, 0);

        break;

    case 3: /* hard reset */

        rsp[2] = k->do_hw_op(s, IPMI_RESET_CHASSIS, 0);

        break;

    case 4: /* pulse diagnostic interrupt */

        rsp[2] = k->do_hw_op(s, IPMI_PULSE_DIAG_IRQ, 0);

        break;

    case 5: /* soft shutdown via ACPI by overtemp emulation */

        rsp[2] = k->do_hw_op(s,

                             IPMI_SHUTDOWN_VIA_ACPI_OVERTEMP, 0);

        break;

    default:

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

}


static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,

                                       const float *la, int channel, int prev_type)

{

    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;

    AacPsyChannel *pch  = &pctx->ch[channel];

    int grouping     = 0;

    int uselongblock = 1;

    int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };

    float clippings[AAC_NUM_BLOCKS_SHORT];

    int i;

    FFPsyWindowInfo wi = { { 0 } };

    if (la) {

        float hpfsmpl[AAC_BLOCK_SIZE_LONG];

        float const *pf = hpfsmpl;

        float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];

        float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];

        float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };

        const float *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN);

        int att_sum = 0;

        /* LAME comment: apply high pass filter of fs/4 */

        psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);

        /* Calculate the energies of each sub-shortblock */

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

            energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];

            assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);

            attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];

            energy_short[0] += energy_subshort[i];

        }

        for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {

            float const *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);

            float p = 1.0f;

            for (; pf < pfe; pf++)

                p = FFMAX(p, fabsf(*pf));

            pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;

            energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;

            /* NOTE: The indexes below are [i + 3 - 2] in the LAME source.

             *       Obviously the 3 and 2 have some significance, or this would be just [i + 1]

             *       (which is what we use here). What the 3 stands for is ambiguous, as it is both

             *       number of short blocks, and the number of sub-short blocks.

             *       It seems that LAME is comparing each sub-block to sub-block + 1 in the

             *       previous block.

             */

            if (p > energy_subshort[i + 1])

                p = p / energy_subshort[i + 1];

            else if (energy_subshort[i + 1] > p * 10.0f)

                p = energy_subshort[i + 1] / (p * 10.0f);

            else

                p = 0.0;

            attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;

        }

        /* compare energy between sub-short blocks */

        for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)

            if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])

                if (attack_intensity[i] > pch->attack_threshold)

                    attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;

        /* should have energy change between short blocks, in order to avoid periodic signals */

        /* Good samples to show the effect are Trumpet test songs */

        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */

        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */

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

            float const u = energy_short[i - 1];

            float const v = energy_short[i];

            float const m = FFMAX(u, v);

            if (m < 40000) {                          /* (2) */

                if (u < 1.7f * v && v < 1.7f * u) {   /* (1) */

                    if (i == 1 && attacks[0] < attacks[i])

                        attacks[0] = 0;

                    attacks[i] = 0;

                }

            }

            att_sum += attacks[i];

        }

        if (attacks[0] <= pch->prev_attack)

            attacks[0] = 0;

        att_sum += attacks[0];

        /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */

        if (pch->prev_attack == 3 || att_sum) {

            uselongblock = 0;

            for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)

                if (attacks[i] && attacks[i-1])

                    attacks[i] = 0;

        }

    } else {

        /* We have no lookahead info, so just use same type as the previous sequence. */

        uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);

    }

    lame_apply_block_type(pch, &wi, uselongblock);

    /* Calculate input sample maximums and evaluate clipping risk */

    if (audio) {

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

            const float *wbuf = audio + i * AAC_BLOCK_SIZE_SHORT;

            float max = 0;

            int j;

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

                max = FFMAX(max, fabsf(wbuf[j]));

            clippings[i] = max;

        }

    } else {

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

            clippings[i] = 0;

    }

    wi.window_type[1] = prev_type;

    if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {

        float clipping = 0.0f;

        wi.num_windows  = 1;

        wi.grouping[0]  = 1;

        if (wi.window_type[0] == LONG_START_SEQUENCE)

            wi.window_shape = 0;

        else

            wi.window_shape = 1;

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

            clipping = FFMAX(clipping, clippings[i]);

        wi.clipping[0] = clipping;

    } else {

        int lastgrp = 0;

        wi.num_windows = 8;

        wi.window_shape = 0;

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

            if (!((pch->next_grouping >> i) & 1))

                lastgrp = i;

            wi.grouping[lastgrp]++;

        }

        for (i = 0; i < 8; i += wi.grouping[i]) {

            int w;

            float clipping = 0.0f;

            for (w = 0; w < wi.grouping[i] && !clipping; w++)

                clipping = FFMAX(clipping, clippings[i+w]);

            wi.clipping[i] = clipping;

        }

    }

    /* Determine grouping, based on the location of the first attack, and save for

     * the next frame.

     * FIXME: Move this to analysis.

     * TODO: Tune groupings depending on attack location

     * TODO: Handle more than one attack in a group

     */

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

        if (attacks[i]) {

            grouping = i;

            break;

        }

    }

    pch->next_grouping = window_grouping[grouping];

    pch->prev_attack = attacks[8];

    return wi;

}


static int dca_decode_frame(AVCodecContext * avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    int lfe_samples;

    int num_core_channels = 0;

    int i;

    int xch_present = 0;

    int16_t *samples = data;

    DCAContext *s = avctx->priv_data;

    int channels;

    s->dca_buffer_size = dca_convert_bitstream(buf, buf_size, s->dca_buffer, DCA_MAX_FRAME_SIZE);

    if (s->dca_buffer_size == -1) {

        av_log(avctx, AV_LOG_ERROR, "Not a valid DCA frame\n");

        return -1;

    }

    init_get_bits(&s->gb, s->dca_buffer, s->dca_buffer_size * 8);

    if (dca_parse_frame_header(s) < 0) {

        //seems like the frame is corrupt, try with the next one

        *data_size=0;

        return buf_size;

    }

    //set AVCodec values with parsed data

    avctx->sample_rate = s->sample_rate;

    avctx->bit_rate = s->bit_rate;

    for (i = 0; i < (s->sample_blocks / 8); i++) {

        dca_decode_block(s, 0, i);

    }

    /* record number of core channels incase less than max channels are requested */

    num_core_channels = s->prim_channels;

    /* extensions start at 32-bit boundaries into bitstream */

    skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

    while(get_bits_left(&s->gb) >= 32) {

        uint32_t bits = get_bits_long(&s->gb, 32);

        switch(bits) {

        case 0x5a5a5a5a: {

            int ext_base_ch = s->prim_channels;

            int ext_amode;

            /* skip length-to-end-of-frame field for the moment */

            skip_bits(&s->gb, 10);

            /* extension amode should == 1, number of channels in extension */

            /* AFAIK XCh is not used for more channels */

            if ((ext_amode = get_bits(&s->gb, 4)) != 1) {

                av_log(avctx, AV_LOG_ERROR, "XCh extension amode %d not"

                       " supported!\n",ext_amode);

                continue;

            }

            /* much like core primary audio coding header */

            dca_parse_audio_coding_header(s, ext_base_ch);

            for (i = 0; i < (s->sample_blocks / 8); i++) {

                dca_decode_block(s, ext_base_ch, i);

            }

            xch_present = 1;

            break;

        }

        case 0x1d95f262:

            av_log(avctx, AV_LOG_DEBUG, "Possible X96 extension found at %d bits\n", get_bits_count(&s->gb));

            av_log(avctx, AV_LOG_DEBUG, "FSIZE96 = %d bytes\n", get_bits(&s->gb, 12)+1);

            av_log(avctx, AV_LOG_DEBUG, "REVNO = %d\n", get_bits(&s->gb, 4));

            break;

        }

        skip_bits_long(&s->gb, (-get_bits_count(&s->gb)) & 31);

    }

    channels = s->prim_channels + !!s->lfe;

    if (s->amode<16) {

        avctx->channel_layout = dca_core_channel_layout[s->amode];

        if (xch_present && (!avctx->request_channels ||

                            avctx->request_channels > num_core_channels)) {

            avctx->channel_layout |= CH_BACK_CENTER;

            if (s->lfe) {

                avctx->channel_layout |= CH_LOW_FREQUENCY;

                s->channel_order_tab = dca_channel_reorder_lfe_xch[s->amode];

            } else {

                s->channel_order_tab = dca_channel_reorder_nolfe_xch[s->amode];

            }

        } else {

            if (s->lfe) {

                avctx->channel_layout |= CH_LOW_FREQUENCY;

                s->channel_order_tab = dca_channel_reorder_lfe[s->amode];

            } else

                s->channel_order_tab = dca_channel_reorder_nolfe[s->amode];

        }

        if (s->prim_channels > 0 &&

            s->channel_order_tab[s->prim_channels - 1] < 0)

            return -1;

        if (avctx->request_channels == 2 && s->prim_channels > 2) {

            channels = 2;

            s->output = DCA_STEREO;

            avctx->channel_layout = CH_LAYOUT_STEREO;

        }

    } else {

        av_log(avctx, AV_LOG_ERROR, "Non standard configuration %d !\n",s->amode);

        return -1;

    }

    /* There is nothing that prevents a dts frame to change channel configuration

       but FFmpeg doesn't support that so only set the channels if it is previously

       unset. Ideally during the first probe for channels the crc should be checked

       and only set avctx->channels when the crc is ok. Right now the decoder could

       set the channels based on a broken first frame.*/

    if (!avctx->channels)

        avctx->channels = channels;

    if (*data_size < (s->sample_blocks / 8) * 256 * sizeof(int16_t) * channels)

        return -1;

    *data_size = 256 / 8 * s->sample_blocks * sizeof(int16_t) * channels;

    /* filter to get final output */

    for (i = 0; i < (s->sample_blocks / 8); i++) {

        dca_filter_channels(s, i);

        s->dsp.float_to_int16_interleave(samples, s->samples_chanptr, 256, channels);

        samples += 256 * channels;

    }

    /* update lfe history */

    lfe_samples = 2 * s->lfe * (s->sample_blocks / 8);

    for (i = 0; i < 2 * s->lfe * 4; i++) {

        s->lfe_data[i] = s->lfe_data[i + lfe_samples];

    }

    return buf_size;

}


static int rtl8139_can_receive(VLANClientState *nc)

{

    RTL8139State *s = DO_UPCAST(NICState, nc, nc)->opaque;

    int avail;

    /* Receive (drop) packets if card is disabled.  */

    if (!s->clock_enabled)

      return 1;

    if (!rtl8139_receiver_enabled(s))

      return 1;

    if (rtl8139_cp_receiver_enabled(s)) {

        /* ??? Flow control not implemented in c+ mode.

           This is a hack to work around slirp deficiencies anyway.  */

        return 1;

    } else {

        avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr,

                     s->RxBufferSize);

        return (avail == 0 || avail >= 1514);

    }

}


unsigned int qemu_get_be16(QEMUFile *f)

{

    unsigned int v;

    v = qemu_get_byte(f) << 8;

    v |= qemu_get_byte(f);

    return v;

}


void migration_fd_process_incoming(QEMUFile *f)

{

    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);

    migrate_decompress_threads_create();

    qemu_file_set_blocking(f, false);

    qemu_coroutine_enter(co, f);

}


void ff_xvmc_decode_mb(MpegEncContext *s)

{

    XvMCMacroBlock *mv_block;

    struct xvmc_pix_fmt *render;

    int i, cbp, blocks_per_mb;

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

    if (s->encoding) {

        av_log(s->avctx, AV_LOG_ERROR, "XVMC doesn't support encoding!!!\n");

        return;

    }

    // from MPV_decode_mb(), update DC predictors for P macroblocks

    if (!s->mb_intra) {

        s->last_dc[0] =

        s->last_dc[1] =

        s->last_dc[2] =  128 << s->intra_dc_precision;

    }

    // MC doesn't skip blocks

    s->mb_skipped = 0;

    // Do I need to export quant when I could not perform postprocessing?

    // Anyway, it doesn't hurt.

    s->current_picture.qscale_table[mb_xy] = s->qscale;

    // start of XVMC-specific code

    render = (struct xvmc_pix_fmt*)s->current_picture.f.data[2];

    assert(render);

    assert(render->xvmc_id == AV_XVMC_ID);

    assert(render->mv_blocks);

    // take the next free macroblock

    mv_block = &render->mv_blocks[render->start_mv_blocks_num +

                                  render->filled_mv_blocks_num];

    mv_block->x        = s->mb_x;

    mv_block->y        = s->mb_y;

    mv_block->dct_type = s->interlaced_dct; // XVMC_DCT_TYPE_FRAME/FIELD;

    if (s->mb_intra) {

        mv_block->macroblock_type = XVMC_MB_TYPE_INTRA; // no MC, all done

    } else {

        mv_block->macroblock_type = XVMC_MB_TYPE_PATTERN;

        if (s->mv_dir & MV_DIR_FORWARD) {

            mv_block->macroblock_type |= XVMC_MB_TYPE_MOTION_FORWARD;

            // PMV[n][dir][xy] = mv[dir][n][xy]

            mv_block->PMV[0][0][0] = s->mv[0][0][0];

            mv_block->PMV[0][0][1] = s->mv[0][0][1];

            mv_block->PMV[1][0][0] = s->mv[0][1][0];

            mv_block->PMV[1][0][1] = s->mv[0][1][1];

        }

        if (s->mv_dir & MV_DIR_BACKWARD) {

            mv_block->macroblock_type |= XVMC_MB_TYPE_MOTION_BACKWARD;

            mv_block->PMV[0][1][0] = s->mv[1][0][0];

            mv_block->PMV[0][1][1] = s->mv[1][0][1];

            mv_block->PMV[1][1][0] = s->mv[1][1][0];

            mv_block->PMV[1][1][1] = s->mv[1][1][1];

        }

        switch(s->mv_type) {

            case  MV_TYPE_16X16:

                mv_block->motion_type = XVMC_PREDICTION_FRAME;

                break;

            case  MV_TYPE_16X8:

                mv_block->motion_type = XVMC_PREDICTION_16x8;

                break;

            case  MV_TYPE_FIELD:

                mv_block->motion_type = XVMC_PREDICTION_FIELD;

                if (s->picture_structure == PICT_FRAME) {

                    mv_block->PMV[0][0][1] <<= 1;

                    mv_block->PMV[1][0][1] <<= 1;

                    mv_block->PMV[0][1][1] <<= 1;

                    mv_block->PMV[1][1][1] <<= 1;

                }

                break;

            case  MV_TYPE_DMV:

                mv_block->motion_type = XVMC_PREDICTION_DUAL_PRIME;

                if (s->picture_structure == PICT_FRAME) {

                    mv_block->PMV[0][0][0] = s->mv[0][0][0];      // top from top

                    mv_block->PMV[0][0][1] = s->mv[0][0][1] << 1;

                    mv_block->PMV[0][1][0] = s->mv[0][0][0];      // bottom from bottom

                    mv_block->PMV[0][1][1] = s->mv[0][0][1] << 1;

                    mv_block->PMV[1][0][0] = s->mv[0][2][0];      // dmv00, top from bottom

                    mv_block->PMV[1][0][1] = s->mv[0][2][1] << 1; // dmv01

                    mv_block->PMV[1][1][0] = s->mv[0][3][0];      // dmv10, bottom from top

                    mv_block->PMV[1][1][1] = s->mv[0][3][1] << 1; // dmv11

                } else {

                    mv_block->PMV[0][1][0] = s->mv[0][2][0];      // dmv00

                    mv_block->PMV[0][1][1] = s->mv[0][2][1];      // dmv01

                }

                break;

            default:

                assert(0);

        }

        mv_block->motion_vertical_field_select = 0;

        // set correct field references

        if (s->mv_type == MV_TYPE_FIELD || s->mv_type == MV_TYPE_16X8) {

            mv_block->motion_vertical_field_select |= s->field_select[0][0];

            mv_block->motion_vertical_field_select |= s->field_select[1][0] << 1;

            mv_block->motion_vertical_field_select |= s->field_select[0][1] << 2;

            mv_block->motion_vertical_field_select |= s->field_select[1][1] << 3;

        }

    } // !intra

    // time to handle data blocks

    mv_block->index = render->next_free_data_block_num;

    blocks_per_mb = 6;

    if (s->chroma_format >= 2) {

        blocks_per_mb = 4 + (1 << s->chroma_format);

    }

    // calculate cbp

    cbp = 0;

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

        cbp += cbp;

        if (s->block_last_index[i] >= 0)

            cbp++;

    }

    if (s->flags & CODEC_FLAG_GRAY) {

        if (s->mb_intra) {                                   // intra frames are always full chroma blocks

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

                memset(s->pblocks[i], 0, sizeof(*s->pblocks[i]));  // so we need to clear them

                if (!render->unsigned_intra)

                    *s->pblocks[i][0] = 1 << 10;

            }

        } else {

            cbp &= 0xf << (blocks_per_mb - 4);

            blocks_per_mb = 4;                               // luminance blocks only

        }

    }

    mv_block->coded_block_pattern = cbp;

    if (cbp == 0)

        mv_block->macroblock_type &= ~XVMC_MB_TYPE_PATTERN;

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

        if (s->block_last_index[i] >= 0) {

            // I do not have unsigned_intra MOCO to test, hope it is OK.

            if (s->mb_intra && (render->idct || !render->unsigned_intra))

                *s->pblocks[i][0] -= 1 << 10;

            if (!render->idct) {

                s->dsp.idct(*s->pblocks[i]);

                /* It is unclear if MC hardware requires pixel diff values to be

                 * in the range [-255;255]. TODO: Clipping if such hardware is

                 * ever found. As of now it would only be an unnecessary

                 * slowdown. */

            }

            // copy blocks only if the codec doesn't support pblocks reordering

            if (s->avctx->xvmc_acceleration == 1) {

                memcpy(&render->data_blocks[render->next_free_data_block_num*64],

                       s->pblocks[i], sizeof(*s->pblocks[i]));

            }

            render->next_free_data_block_num++;

        }

    }

    render->filled_mv_blocks_num++;

    assert(render->filled_mv_blocks_num     <= render->allocated_mv_blocks);

    assert(render->next_free_data_block_num <= render->allocated_data_blocks);

    /* The above conditions should not be able to fail as long as this function

     * is used and the following 'if ()' automatically calls a callback to free

     * blocks. */

    if (render->filled_mv_blocks_num == render->allocated_mv_blocks)

        ff_mpeg_draw_horiz_band(s, 0, 0);

}


static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,

                                                    int16_t *block, int n)

{

    int level, i, j, run;

    RLTable *rl = &ff_rl_mpeg1;

    uint8_t * const scantable = s->intra_scantable.permutated;

    const int qscale          = s->qscale;

    OPEN_READER(re, &s->gb);

    i = -1;

    // special case for first coefficient, no need to add second VLC table

    UPDATE_CACHE(re, &s->gb);

    if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {

        level = (3 * qscale) >> 1;

        if (GET_CACHE(re, &s->gb) & 0x40000000)

            level = -level;

        block[0] = level;

        i++;

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

        if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

            goto end;

    }

    /* now quantify & encode AC coefficients */

    for (;;) {

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

        if (level != 0) {

            i += run;

            check_scantable_index(s, i);

            j  = scantable[i];

            level = ((level * 2 + 1) * qscale) >> 1;

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

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

        } else {

            /* escape */

            run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);

            UPDATE_CACHE(re, &s->gb);

            level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);

            i += run;

            check_scantable_index(s, i);

            j  = scantable[i];

            if (level < 0) {

                level = ((-level * 2 + 1) * qscale) >> 1;

                level = -level;

            } else {

                level = ((level * 2 + 1) * qscale) >> 1;

            }

        }

        block[j] = level;

        if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

            break;

        UPDATE_CACHE(re, &s->gb);

    }

end:

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

    CLOSE_READER(re, &s->gb);

    s->block_last_index[n] = i;

    return 0;

}


int ffio_close_null_buf(AVIOContext *s)

{

    DynBuffer *d = s->opaque;

    int size;

    avio_flush(s);

    size = d->size;

    av_free(d);

    av_free(s);

    return size;

}