void smbios_entry_add(QemuOpts *opts)

{

    Error *local_err = NULL;

    const char *val;

    assert(!smbios_immutable);

    val = qemu_opt_get(opts, "file");

    if (val) {

        struct smbios_structure_header *header;

        struct smbios_table *table;

        int size;

        qemu_opts_validate(opts, qemu_smbios_file_opts, &local_err);

        if (local_err) {

            error_report("%s", error_get_pretty(local_err));

            exit(1);

        }

        size = get_image_size(val);

        if (size == -1 || size < sizeof(struct smbios_structure_header)) {

            error_report("Cannot read SMBIOS file %s", val);

            exit(1);

        }

        if (!smbios_entries) {

            smbios_entries_len = sizeof(uint16_t);

            smbios_entries = g_malloc0(smbios_entries_len);

        }

        smbios_entries = g_realloc(smbios_entries, smbios_entries_len +

                                                      sizeof(*table) + size);

        table = (struct smbios_table *)(smbios_entries + smbios_entries_len);

        table->header.type = SMBIOS_TABLE_ENTRY;

        table->header.length = cpu_to_le16(sizeof(*table) + size);

        if (load_image(val, table->data) != size) {

            error_report("Failed to load SMBIOS file %s", val);

            exit(1);

        }

        header = (struct smbios_structure_header *)(table->data);

        if (test_bit(header->type, have_fields_bitmap)) {

            error_report("can't load type %d struct, fields already specified!",

                         header->type);

            exit(1);

        }

        set_bit(header->type, have_binfile_bitmap);

        if (header->type == 4) {

            smbios_type4_count++;

        }

        smbios_entries_len += sizeof(*table) + size;

        (*(uint16_t *)smbios_entries) =

                cpu_to_le16(le16_to_cpu(*(uint16_t *)smbios_entries) + 1);

        return;

    }

    val = qemu_opt_get(opts, "type");

    if (val) {

        unsigned long type = strtoul(val, NULL, 0);

        if (type > SMBIOS_MAX_TYPE) {

            error_report("out of range!");

            exit(1);

        }

        if (test_bit(type, have_binfile_bitmap)) {

            error_report("can't add fields, binary file already loaded!");

            exit(1);

        }

        set_bit(type, have_fields_bitmap);

        switch (type) {

        case 0:

            qemu_opts_validate(opts, qemu_smbios_type0_opts, &local_err);

            if (local_err) {

                error_report("%s", error_get_pretty(local_err));

                exit(1);

            }

            save_opt(&type0.vendor, opts, "vendor");

            save_opt(&type0.version, opts, "version");

            save_opt(&type0.date, opts, "date");

            val = qemu_opt_get(opts, "release");

            if (val) {

                if (sscanf(val, "%hhu.%hhu", &type0.major, &type0.minor) != 2) {

                    error_report("Invalid release");

                    exit(1);

                }

                type0.have_major_minor = true;

            }

            return;

        case 1:

            qemu_opts_validate(opts, qemu_smbios_type1_opts, &local_err);

            if (local_err) {

                error_report("%s", error_get_pretty(local_err));

                exit(1);

            }

            save_opt(&type1.manufacturer, opts, "manufacturer");

            save_opt(&type1.product, opts, "product");

            save_opt(&type1.version, opts, "version");

            save_opt(&type1.serial, opts, "serial");

            save_opt(&type1.sku, opts, "sku");

            save_opt(&type1.family, opts, "family");

            val = qemu_opt_get(opts, "uuid");

            if (val) {

                if (qemu_uuid_parse(val, qemu_uuid) != 0) {

                    error_report("Invalid UUID");

                    exit(1);

                }

                qemu_uuid_set = true;

            }

            return;

        default:

            error_report("Don't know how to build fields for SMBIOS type %ld",

                         type);

            exit(1);

        }

    }

    error_report("Must specify type= or file=");

    exit(1);

}


static void guest_fsfreeze_cleanup(void)

{

    int64_t ret;

    Error *err = NULL;

    if (guest_fsfreeze_state.status == GUEST_FSFREEZE_STATUS_FROZEN) {

        ret = qmp_guest_fsfreeze_thaw(&err);

        if (ret < 0 || err) {

            slog("failed to clean up frozen filesystems");

        }

    }

}


static int qesd_init_in (HWVoiceIn *hw, audsettings_t *as)

{

    ESDVoiceIn *esd = (ESDVoiceIn *) hw;

    audsettings_t obt_as = *as;

    int esdfmt = ESD_STREAM | ESD_RECORD;

    int err;

    sigset_t set, old_set;

    sigfillset (&set);

    esdfmt |= (as->nchannels == 2) ? ESD_STEREO : ESD_MONO;

    switch (as->fmt) {

    case AUD_FMT_S8:

    case AUD_FMT_U8:

        esdfmt |= ESD_BITS8;

        obt_as.fmt = AUD_FMT_U8;

        break;

    case AUD_FMT_S16:

    case AUD_FMT_U16:

        esdfmt |= ESD_BITS16;

        obt_as.fmt = AUD_FMT_S16;

        break;

    case AUD_FMT_S32:

    case AUD_FMT_U32:

        dolog ("Will use 16 instead of 32 bit samples\n");

        esdfmt |= ESD_BITS16;

        obt_as.fmt = AUD_FMT_S16;

        break;

    }

    obt_as.endianness = AUDIO_HOST_ENDIANNESS;

    audio_pcm_init_info (&hw->info, &obt_as);

    hw->samples = conf.samples;

    esd->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!esd->pcm_buf) {

        dolog ("Could not allocate buffer (%d bytes)\n",

               hw->samples << hw->info.shift);

        return -1;

    }

    esd->fd = -1;

    err = pthread_sigmask (SIG_BLOCK, &set, &old_set);

    if (err) {

        qesd_logerr (err, "pthread_sigmask failed\n");

        goto fail1;

    }

    esd->fd = esd_record_stream (esdfmt, as->freq, conf.adc_host, NULL);

    if (esd->fd < 0) {

        qesd_logerr (errno, "esd_record_stream failed\n");

        goto fail2;

    }

    if (audio_pt_init (&esd->pt, qesd_thread_in, esd, AUDIO_CAP, AUDIO_FUNC)) {

        goto fail3;

    }

    err = pthread_sigmask (SIG_SETMASK, &old_set, NULL);

    if (err) {

        qesd_logerr (err, "pthread_sigmask(restore) failed\n");

    }

    return 0;

 fail3:

    if (close (esd->fd)) {

        qesd_logerr (errno, "%s: close on esd socket(%d) failed\n",

                     AUDIO_FUNC, esd->fd);

    }

    esd->fd = -1;

 fail2:

    err = pthread_sigmask (SIG_SETMASK, &old_set, NULL);

    if (err) {

        qesd_logerr (err, "pthread_sigmask(restore) failed\n");

    }

 fail1:

    qemu_free (esd->pcm_buf);

    esd->pcm_buf = NULL;

    return -1;

}


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

{

    LATMContext *ctx = s->priv_data;

    AVIOContext *pb = s->pb;

    PutBitContext bs;

    int i, len;

    uint8_t loas_header[] = "\x56\xe0\x00";

    if (s->streams[0]->codecpar->codec_id == AV_CODEC_ID_AAC_LATM)

        return ff_raw_write_packet(s, pkt);

    if (!s->streams[0]->codecpar->extradata) {

        if(pkt->size > 2 && pkt->data[0] == 0x56 && (pkt->data[1] >> 4) == 0xe &&

            (AV_RB16(pkt->data + 1) & 0x1FFF) + 3 == pkt->size)

            return ff_raw_write_packet(s, pkt);

        else

            return AVERROR_INVALIDDATA;

    }

    if (pkt->size > 0x1fff)

        goto too_large;

    init_put_bits(&bs, ctx->buffer, pkt->size+1024+MAX_EXTRADATA_SIZE);

    latm_write_frame_header(s, &bs);

    /* PayloadLengthInfo() */

    for (i = 0; i <= pkt->size-255; i+=255)

        put_bits(&bs, 8, 255);

    put_bits(&bs, 8, pkt->size-i);

    /* The LATM payload is written unaligned */

    /* PayloadMux() */

    if (pkt->size && (pkt->data[0] & 0xe1) == 0x81) {

        // Convert byte-aligned DSE to non-aligned.

        // Due to the input format encoding we know that

        // it is naturally byte-aligned in the input stream,

        // so there are no padding bits to account for.

        // To avoid having to add padding bits and rearrange

        // the whole stream we just remove the byte-align flag.

        // This allows us to remux our FATE AAC samples into latm

        // files that are still playable with minimal effort.

        put_bits(&bs, 8, pkt->data[0] & 0xfe);

        avpriv_copy_bits(&bs, pkt->data + 1, 8*pkt->size - 8);

    } else

        avpriv_copy_bits(&bs, pkt->data, 8*pkt->size);

    avpriv_align_put_bits(&bs);

    flush_put_bits(&bs);

    len = put_bits_count(&bs) >> 3;

    if (len > 0x1fff)

        goto too_large;

    loas_header[1] |= (len >> 8) & 0x1f;

    loas_header[2] |= len & 0xff;

    avio_write(pb, loas_header, 3);

    avio_write(pb, ctx->buffer, len);

    return 0;

too_large:

    av_log(s, AV_LOG_ERROR, "LATM packet size larger than maximum size 0x1fff\n");

    return AVERROR_INVALIDDATA;

}


static void end_ebml_master_crc32(AVIOContext *pb, AVIOContext **dyn_cp, MatroskaMuxContext *mkv,

                                  ebml_master master)

{

    uint8_t *buf, crc[4];

    int size;

    if (pb->seekable) {

        size = avio_close_dyn_buf(*dyn_cp, &buf);

        if (mkv->write_crc && mkv->mode != MODE_WEBM) {

            AV_WL32(crc, av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), UINT32_MAX, buf, size) ^ UINT32_MAX);

            put_ebml_binary(pb, EBML_ID_CRC32, crc, sizeof(crc));

        }

        avio_write(pb, buf, size);

        end_ebml_master(pb, master);

    } else {

        end_ebml_master(*dyn_cp, master);

        size = avio_close_dyn_buf(*dyn_cp, &buf);

        avio_write(pb, buf, size);

    }

    av_free(buf);

    *dyn_cp = NULL;

}


void ff_h264_direct_ref_list_init(const H264Context *const h, H264SliceContext *sl)

{

    H264Ref *const ref1 = &sl->ref_list[1][0];

    H264Picture *const cur = h->cur_pic_ptr;

    int list, j, field;

    int sidx     = (h->picture_structure & 1) ^ 1;

    int ref1sidx = (ref1->reference      & 1) ^ 1;

    for (list = 0; list < sl->list_count; list++) {

        cur->ref_count[sidx][list] = sl->ref_count[list];

        for (j = 0; j < sl->ref_count[list]; j++)

            cur->ref_poc[sidx][list][j] = 4 * sl->ref_list[list][j].parent->frame_num +

                                          (sl->ref_list[list][j].reference & 3);

    }

    if (h->picture_structure == PICT_FRAME) {

        memcpy(cur->ref_count[1], cur->ref_count[0], sizeof(cur->ref_count[0]));

        memcpy(cur->ref_poc[1],   cur->ref_poc[0],   sizeof(cur->ref_poc[0]));

    }

    cur->mbaff = FRAME_MBAFF(h);

    sl->col_fieldoff = 0;

    if (sl->list_count != 2 || !sl->ref_count[1])

        return;

    if (h->picture_structure == PICT_FRAME) {

        int cur_poc  = h->cur_pic_ptr->poc;

        int *col_poc = sl->ref_list[1][0].parent->field_poc;

        if (col_poc[0] == INT_MAX && col_poc[1] == INT_MAX) {

            av_log(h->avctx, AV_LOG_ERROR, "co located POCs unavailable\n");

            sl->col_parity = 1;

        } else

        sl->col_parity = (FFABS(col_poc[0] - cur_poc) >=

                          FFABS(col_poc[1] - cur_poc));

        ref1sidx =

        sidx     = sl->col_parity;

    // FL -> FL & differ parity

    } else if (!(h->picture_structure & sl->ref_list[1][0].reference) &&

               !sl->ref_list[1][0].parent->mbaff) {

        sl->col_fieldoff = 2 * sl->ref_list[1][0].reference - 3;

    }

    if (sl->slice_type_nos != AV_PICTURE_TYPE_B || sl->direct_spatial_mv_pred)

        return;

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

        fill_colmap(h, sl, sl->map_col_to_list0, list, sidx, ref1sidx, 0);

        if (FRAME_MBAFF(h))

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

                fill_colmap(h, sl, sl->map_col_to_list0_field[field], list, field,

                            field, 1);

    }

}


static av_cold int xvid_encode_init(AVCodecContext *avctx)

{

    int xerr, i;

    int xvid_flags = avctx->flags;

    struct xvid_context *x = avctx->priv_data;

    uint16_t *intra, *inter;

    int fd;

    xvid_plugin_single_t single         = { 0 };

    struct xvid_ff_pass1 rc2pass1       = { 0 };

    xvid_plugin_2pass2_t rc2pass2       = { 0 };

    xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */

    xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */

    xvid_plugin_ssim_t ssim             = { 0 };

    xvid_gbl_init_t xvid_gbl_init       = { 0 };

    xvid_enc_create_t xvid_enc_create   = { 0 };

    xvid_enc_plugin_t plugins[7];

    /* Bring in VOP flags from avconv command-line */

    x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */

    if (xvid_flags & CODEC_FLAG_4MV)

        x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */

    if (avctx->trellis)

        x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */

    if (xvid_flags & CODEC_FLAG_AC_PRED)

        x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */

    if (xvid_flags & CODEC_FLAG_GRAY)

        x->vop_flags |= XVID_VOP_GREYSCALE;

    /* Decide which ME quality setting to use */

    x->me_flags = 0;

    switch (avctx->me_method) {

    case ME_FULL:   /* Quality 6 */

        x->me_flags |= XVID_ME_EXTSEARCH16 |

                       XVID_ME_EXTSEARCH8;

    case ME_EPZS:   /* Quality 4 */

        x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |

                       XVID_ME_HALFPELREFINE8   |

                       XVID_ME_CHROMA_PVOP      |

                       XVID_ME_CHROMA_BVOP;

    case ME_LOG:    /* Quality 2 */

    case ME_PHODS:

    case ME_X1:

        x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |

                       XVID_ME_HALFPELREFINE16;

    case ME_ZERO:   /* Quality 0 */

    default:

        break;

    }

    /* Decide how we should decide blocks */

    switch (avctx->mb_decision) {

    case 2:

        x->vop_flags |=  XVID_VOP_MODEDECISION_RD;

        x->me_flags  |=  XVID_ME_HALFPELREFINE8_RD    |

                         XVID_ME_QUARTERPELREFINE8_RD |

                         XVID_ME_EXTSEARCH_RD         |

                         XVID_ME_CHECKPREDICTION_RD;

    case 1:

        if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))

            x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;

        x->me_flags |= XVID_ME_HALFPELREFINE16_RD |

                       XVID_ME_QUARTERPELREFINE16_RD;

    default:

        break;

    }

    /* Bring in VOL flags from avconv command-line */

#if FF_API_GMC

    if (avctx->flags & CODEC_FLAG_GMC)

        x->gmc = 1;

#endif

    x->vol_flags = 0;

    if (x->gmc) {

        x->vol_flags |= XVID_VOL_GMC;

        x->me_flags  |= XVID_ME_GME_REFINE;

    }

    if (xvid_flags & CODEC_FLAG_QPEL) {

        x->vol_flags |= XVID_VOL_QUARTERPEL;

        x->me_flags  |= XVID_ME_QUARTERPELREFINE16;

        if (x->vop_flags & XVID_VOP_INTER4V)

            x->me_flags |= XVID_ME_QUARTERPELREFINE8;

    }

    xvid_gbl_init.version   = XVID_VERSION;

    xvid_gbl_init.debug     = 0;

    xvid_gbl_init.cpu_flags = 0;

    /* Initialize */

    xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);

    /* Create the encoder reference */

    xvid_enc_create.version = XVID_VERSION;

    /* Store the desired frame size */

    xvid_enc_create.width  =

    x->xsize               = avctx->width;

    xvid_enc_create.height =

    x->ysize               = avctx->height;

    /* Xvid can determine the proper profile to use */

    /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */

    /* We don't use zones */

    xvid_enc_create.zones     = NULL;

    xvid_enc_create.num_zones = 0;

    xvid_enc_create.num_threads = avctx->thread_count;

    xvid_enc_create.plugins     = plugins;

    xvid_enc_create.num_plugins = 0;

    /* Initialize Buffers */

    x->twopassbuffer     = NULL;

    x->old_twopassbuffer = NULL;

    x->twopassfile       = NULL;

    if (xvid_flags & CODEC_FLAG_PASS1) {

        rc2pass1.version     = XVID_VERSION;

        rc2pass1.context     = x;

        x->twopassbuffer     = av_malloc(BUFFER_SIZE);

        x->old_twopassbuffer = av_malloc(BUFFER_SIZE);

        if (!x->twopassbuffer || !x->old_twopassbuffer) {

            av_log(avctx, AV_LOG_ERROR,

                   "Xvid: Cannot allocate 2-pass log buffers\n");

            return AVERROR(ENOMEM);

        }

        x->twopassbuffer[0]     =

        x->old_twopassbuffer[0] = 0;

        plugins[xvid_enc_create.num_plugins].func  = xvid_ff_2pass;

        plugins[xvid_enc_create.num_plugins].param = &rc2pass1;

        xvid_enc_create.num_plugins++;

    } else if (xvid_flags & CODEC_FLAG_PASS2) {

        rc2pass2.version = XVID_VERSION;

        rc2pass2.bitrate = avctx->bit_rate;

        fd = ff_tempfile("xvidff.", &x->twopassfile);

        if (fd < 0) {

            av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");

            return fd;

        }

        if (!avctx->stats_in) {

            av_log(avctx, AV_LOG_ERROR,

                   "Xvid: No 2-pass information loaded for second pass\n");

            return AVERROR_INVALIDDATA;

        }

        if (strlen(avctx->stats_in) >

            write(fd, avctx->stats_in, strlen(avctx->stats_in))) {

            close(fd);

            av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");

            return AVERROR(EIO);

        }

        close(fd);

        rc2pass2.filename                          = x->twopassfile;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_2pass2;

        plugins[xvid_enc_create.num_plugins].param = &rc2pass2;

        xvid_enc_create.num_plugins++;

    } else if (!(xvid_flags & CODEC_FLAG_QSCALE)) {

        /* Single Pass Bitrate Control! */

        single.version = XVID_VERSION;

        single.bitrate = avctx->bit_rate;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_single;

        plugins[xvid_enc_create.num_plugins].param = &single;

        xvid_enc_create.num_plugins++;

    }

    if (avctx->lumi_masking != 0.0)

        x->lumi_aq = 1;

    if (x->lumi_aq && x->variance_aq) {

        x->variance_aq = 0;

        av_log(avctx, AV_LOG_WARNING,

               "variance_aq is ignored when lumi_aq is set.\n");

    }

    /* Luminance Masking */

    if (x->lumi_aq) {

        masking_l.method                          = 0;

        plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;

        /* The old behavior is that when avctx->lumi_masking is specified,

         * plugins[...].param = NULL. Trying to keep the old behavior here. */

        plugins[xvid_enc_create.num_plugins].param =

            avctx->lumi_masking ? NULL : &masking_l;

        xvid_enc_create.num_plugins++;

    }

    /* Variance AQ */

    if (x->variance_aq) {

        masking_v.method                           = 1;

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_lumimasking;

        plugins[xvid_enc_create.num_plugins].param = &masking_v;

        xvid_enc_create.num_plugins++;

    }

    /* SSIM */

    if (x->ssim) {

        plugins[xvid_enc_create.num_plugins].func  = xvid_plugin_ssim;

        ssim.b_printstat                           = x->ssim == 2;

        ssim.acc                                   = x->ssim_acc;

        ssim.cpu_flags                             = xvid_gbl_init.cpu_flags;

        ssim.b_visualize                           = 0;

        plugins[xvid_enc_create.num_plugins].param = &ssim;

        xvid_enc_create.num_plugins++;

    }

    /* Frame Rate and Key Frames */

    xvid_correct_framerate(avctx);

    xvid_enc_create.fincr = avctx->time_base.num;

    xvid_enc_create.fbase = avctx->time_base.den;

    if (avctx->gop_size > 0)

        xvid_enc_create.max_key_interval = avctx->gop_size;

    else

        xvid_enc_create.max_key_interval = 240; /* Xvid's best default */

    /* Quants */

    if (xvid_flags & CODEC_FLAG_QSCALE)

        x->qscale = 1;

    else

        x->qscale = 0;

    xvid_enc_create.min_quant[0] = avctx->qmin;

    xvid_enc_create.min_quant[1] = avctx->qmin;

    xvid_enc_create.min_quant[2] = avctx->qmin;

    xvid_enc_create.max_quant[0] = avctx->qmax;

    xvid_enc_create.max_quant[1] = avctx->qmax;

    xvid_enc_create.max_quant[2] = avctx->qmax;

    /* Quant Matrices */

    x->intra_matrix =

    x->inter_matrix = NULL;

    if (avctx->mpeg_quant)

        x->vol_flags |= XVID_VOL_MPEGQUANT;

    if ((avctx->intra_matrix || avctx->inter_matrix)) {

        x->vol_flags |= XVID_VOL_MPEGQUANT;

        if (avctx->intra_matrix) {

            intra           = avctx->intra_matrix;

            x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);

            if (!x->intra_matrix)

                return AVERROR(ENOMEM);

        } else

            intra = NULL;

        if (avctx->inter_matrix) {

            inter           = avctx->inter_matrix;

            x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);

            if (!x->inter_matrix)

                return AVERROR(ENOMEM);

        } else

            inter = NULL;

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

            if (intra)

                x->intra_matrix[i] = (unsigned char) intra[i];

            if (inter)

                x->inter_matrix[i] = (unsigned char) inter[i];

        }

    }

    /* Misc Settings */

    xvid_enc_create.frame_drop_ratio = 0;

    xvid_enc_create.global           = 0;

    if (xvid_flags & CODEC_FLAG_CLOSED_GOP)

        xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;

    /* Determines which codec mode we are operating in */

    avctx->extradata      = NULL;

    avctx->extradata_size = 0;

    if (xvid_flags & CODEC_FLAG_GLOBAL_HEADER) {

        /* In this case, we are claiming to be MPEG4 */

        x->quicktime_format = 1;

        avctx->codec_id     = AV_CODEC_ID_MPEG4;

    } else {

        /* We are claiming to be Xvid */

        x->quicktime_format = 0;

        if (!avctx->codec_tag)

            avctx->codec_tag = AV_RL32("xvid");

    }

    /* Bframes */

    xvid_enc_create.max_bframes   = avctx->max_b_frames;

    xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;

    xvid_enc_create.bquant_ratio  = 100 * avctx->b_quant_factor;

    if (avctx->max_b_frames > 0 && !x->quicktime_format)

        xvid_enc_create.global |= XVID_GLOBAL_PACKED;

    /* Create encoder context */

    xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);

    if (xerr) {

        av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");

        return -1;

    }

    x->encoder_handle  = xvid_enc_create.handle;

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,

                                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,

                                       const int16_t **alpSrc, uint8_t *dest, long dstW, long dstY)

{

#if COMPILE_TEMPLATE_MMX

    x86_reg dummy=0;

    x86_reg dstW_reg = dstW;

    if(!(c->flags & SWS_BITEXACT)) {

        if (c->flags & SWS_ACCURATE_RND) {

            switch(c->dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    YSCALEYUV2PACKEDX_ACCURATE

                    YSCALEYUV2RGBX

                    "movq                      %%mm2, "U_TEMP"(%0)  \n\t"

                    "movq                      %%mm4, "V_TEMP"(%0)  \n\t"

                    "movq                      %%mm5, "Y_TEMP"(%0)  \n\t"

                    YSCALEYUV2PACKEDX_ACCURATE_YA(ALP_MMX_FILTER_OFFSET)

                    "movq               "Y_TEMP"(%0), %%mm5         \n\t"

                    "psraw                        $3, %%mm1         \n\t"

                    "psraw                        $3, %%mm7         \n\t"

                    "packuswb                  %%mm7, %%mm1         \n\t"

                    WRITEBGR32(%4, %5, %%REGa, %%mm3, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm2, %%mm6)

                    YSCALEYUV2PACKEDX_END

                } else {

                    YSCALEYUV2PACKEDX_ACCURATE

                    YSCALEYUV2RGBX

                    "pcmpeqd %%mm7, %%mm7 \n\t"

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                }

                return;

            case PIX_FMT_BGR24:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"\n\t" //FIXME optimize

                "add %4, %%"REG_c"                        \n\t"

                WRITEBGR24(%%REGc, %5, %%REGa)

                :: "r" (&c->redDither),

                "m" (dummy), "m" (dummy), "m" (dummy),

                "r" (dest), "m" (dstW_reg)

                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S

                );

                return;

            case PIX_FMT_RGB555:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"

                "paddusb "RED_DITHER"(%0), %%mm5\n\t"

#endif

                WRITERGB15(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_RGB565:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"

                "paddusb "RED_DITHER"(%0), %%mm5\n\t"

#endif

                WRITERGB16(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_YUYV422:

                YSCALEYUV2PACKEDX_ACCURATE

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

                "psraw $3, %%mm3    \n\t"

                "psraw $3, %%mm4    \n\t"

                "psraw $3, %%mm1    \n\t"

                "psraw $3, %%mm7    \n\t"

                WRITEYUY2(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            }

        } else {

            switch(c->dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    YSCALEYUV2PACKEDX

                    YSCALEYUV2RGBX

                    YSCALEYUV2PACKEDX_YA(ALP_MMX_FILTER_OFFSET, %%mm0, %%mm3, %%mm6, %%mm1, %%mm7)

                    "psraw                        $3, %%mm1         \n\t"

                    "psraw                        $3, %%mm7         \n\t"

                    "packuswb                  %%mm7, %%mm1         \n\t"

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                } else {

                    YSCALEYUV2PACKEDX

                    YSCALEYUV2RGBX

                    "pcmpeqd %%mm7, %%mm7 \n\t"

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                }

                return;

            case PIX_FMT_BGR24:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor                    %%mm7, %%mm7       \n\t"

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"   \n\t" //FIXME optimize

                "add                        %4, %%"REG_c"   \n\t"

                WRITEBGR24(%%REGc, %5, %%REGa)

                :: "r" (&c->redDither),

                "m" (dummy), "m" (dummy), "m" (dummy),

                "r" (dest),  "m" (dstW_reg)

                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S

                );

                return;

            case PIX_FMT_RGB555:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"

                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"

#endif

                WRITERGB15(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_RGB565:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"

                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"

#endif

                WRITERGB16(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_YUYV422:

                YSCALEYUV2PACKEDX

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

                "psraw $3, %%mm3    \n\t"

                "psraw $3, %%mm4    \n\t"

                "psraw $3, %%mm1    \n\t"

                "psraw $3, %%mm7    \n\t"

                WRITEYUY2(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            }

        }

    }

#endif /* COMPILE_TEMPLATE_MMX */

#if COMPILE_TEMPLATE_ALTIVEC

    /* The following list of supported dstFormat values should

       match what's found in the body of ff_yuv2packedX_altivec() */

    if (!(c->flags & SWS_BITEXACT) && !c->alpPixBuf &&

         (c->dstFormat==PIX_FMT_ABGR  || c->dstFormat==PIX_FMT_BGRA  ||

          c->dstFormat==PIX_FMT_BGR24 || c->dstFormat==PIX_FMT_RGB24 ||

          c->dstFormat==PIX_FMT_RGBA  || c->dstFormat==PIX_FMT_ARGB))

            ff_yuv2packedX_altivec(c, lumFilter, lumSrc, lumFilterSize,

                                   chrFilter, chrSrc, chrFilterSize,

                                   dest, dstW, dstY);

    else

#endif

        yuv2packedXinC(c, lumFilter, lumSrc, lumFilterSize,

                       chrFilter, chrSrc, chrFilterSize,

                       alpSrc, dest, dstW, dstY);

}


static inline int media_present(IDEState *s)

{

    return (s->nb_sectors > 0);

}


static void do_audio_out(AVFormatContext *s,

                         AVOutputStream *ost,

                         AVInputStream *ist,

                         unsigned char *buf, int size)

{

    uint8_t *buftmp;

    static uint8_t *audio_buf = NULL;

    static uint8_t *audio_out = NULL;

    const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;

    int size_out, frame_bytes, ret;

    AVCodecContext *enc= ost->st->codec;

    AVCodecContext *dec= ist->st->codec;

    /* SC: dynamic allocation of buffers */

    if (!audio_buf)

        audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);

    if (!audio_out)

        audio_out = av_malloc(audio_out_size);

    if (!audio_buf || !audio_out)

        return;               /* Should signal an error ! */

    if (enc->channels != dec->channels)

        ost->audio_resample = 1;

    if (ost->audio_resample && !ost->resample) {

        ost->resample = audio_resample_init(enc->channels,    dec->channels,

                                            enc->sample_rate, dec->sample_rate);

        if (!ost->resample) {

            fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",

                    dec->channels, dec->sample_rate,

                    enc->channels, enc->sample_rate);

            av_exit(1);

        }

    }

    if(audio_sync_method){

        double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts

                - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2);

        double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;

        int byte_delta= ((int)idelta)*2*ist->st->codec->channels;

        //FIXME resample delay

        if(fabs(delta) > 50){

            if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){

                if(byte_delta < 0){

                    byte_delta= FFMAX(byte_delta, -size);

                    size += byte_delta;

                    buf  -= byte_delta;

                    if(verbose > 2)

                        fprintf(stderr, "discarding %d audio samples\n", (int)-delta);

                    if(!size)

                        return;

                    ist->is_start=0;

                }else{

                    static uint8_t *input_tmp= NULL;

                    input_tmp= av_realloc(input_tmp, byte_delta + size);

                    if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)

                        ist->is_start=0;

                    else

                        byte_delta= MAX_AUDIO_PACKET_SIZE - size;

                    memset(input_tmp, 0, byte_delta);

                    memcpy(input_tmp + byte_delta, buf, size);

                    buf= input_tmp;

                    size += byte_delta;

                    if(verbose > 2)

                        fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);

                }

            }else if(audio_sync_method>1){

                int comp= av_clip(delta, -audio_sync_method, audio_sync_method);

                assert(ost->audio_resample);

                if(verbose > 2)

                    fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);

//                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2));

                av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);

            }

        }

    }else

        ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)

                        - av_fifo_size(&ost->fifo)/(ost->st->codec->channels * 2); //FIXME wrong

    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 */

        av_fifo_realloc(&ost->fifo, av_fifo_size(&ost->fifo) + size_out + 1);

        av_fifo_write(&ost->fifo, buftmp, size_out);

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

        while (av_fifo_read(&ost->fifo, audio_buf, frame_bytes) == 0) {

            AVPacket pkt;

            av_init_packet(&pkt);

            //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()

            ret = avcodec_encode_audio(enc, audio_out, audio_out_size,

                                       (short *)audio_buf);

            audio_size += ret;

            pkt.stream_index= ost->index;

            pkt.data= audio_out;

            pkt.size= ret;

            if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)

                pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

            pkt.flags |= PKT_FLAG_KEY;

            write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

            ost->sync_opts += enc->frame_size;

        }

    } else {

        AVPacket pkt;

        av_init_packet(&pkt);

        ost->sync_opts += size_out / (2 * enc->channels);

        /* output a pcm frame */

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

        switch(enc->codec->id) {

        case CODEC_ID_PCM_S32LE:

        case CODEC_ID_PCM_S32BE:

        case CODEC_ID_PCM_U32LE:

        case CODEC_ID_PCM_U32BE:

            size_out = size_out << 1;

            break;

        case CODEC_ID_PCM_S24LE:

        case CODEC_ID_PCM_S24BE:

        case CODEC_ID_PCM_U24LE:

        case CODEC_ID_PCM_U24BE:

        case CODEC_ID_PCM_S24DAUD:

            size_out = size_out / 2 * 3;

            break;

        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;

        }

        //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()

        ret = avcodec_encode_audio(enc, audio_out, size_out,

                                   (short *)buftmp);

        audio_size += ret;

        pkt.stream_index= ost->index;

        pkt.data= audio_out;

        pkt.size= ret;

        if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)

            pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= PKT_FLAG_KEY;

        write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);

    }

}


int qemu_thread_is_self(QemuThread *thread)

{

    QemuThread *this_thread = TlsGetValue(qemu_thread_tls_index);

    return this_thread->thread == thread->thread;

}


static void tcx_realizefn(DeviceState *dev, Error **errp)

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    TCXState *s = TCX(dev);

    ram_addr_t vram_offset = 0;

    int size, ret;

    uint8_t *vram_base;

    char *fcode_filename;

    memory_region_init_ram(&s->vram_mem, OBJECT(s), "tcx.vram",

                           s->vram_size * (1 + 4 + 4), &error_abort);

    vmstate_register_ram_global(&s->vram_mem);

    memory_region_set_log(&s->vram_mem, true, DIRTY_MEMORY_VGA);

    vram_base = memory_region_get_ram_ptr(&s->vram_mem);

    /* 10/ROM : FCode ROM */

    vmstate_register_ram_global(&s->rom);

    fcode_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, TCX_ROM_FILE);

    if (fcode_filename) {

        ret = load_image_targphys(fcode_filename, s->prom_addr,

                                  FCODE_MAX_ROM_SIZE);

        g_free(fcode_filename);

        if (ret < 0 || ret > FCODE_MAX_ROM_SIZE) {

            error_report("tcx: could not load prom '%s'", TCX_ROM_FILE);

        }

    }

    /* 0/DFB8 : 8-bit plane */

    s->vram = vram_base;

    size = s->vram_size;

    memory_region_init_alias(&s->vram_8bit, OBJECT(s), "tcx.vram.8bit",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_8bit);

    vram_offset += size;

    vram_base += size;

    /* 1/DFB24 : 24bit plane */

    size = s->vram_size * 4;

    s->vram24 = (uint32_t *)vram_base;

    s->vram24_offset = vram_offset;

    memory_region_init_alias(&s->vram_24bit, OBJECT(s), "tcx.vram.24bit",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_24bit);

    vram_offset += size;

    vram_base += size;

    /* 4/RDFB32 : Raw Framebuffer */

    size = s->vram_size * 4;

    s->cplane = (uint32_t *)vram_base;

    s->cplane_offset = vram_offset;

    memory_region_init_alias(&s->vram_cplane, OBJECT(s), "tcx.vram.cplane",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_cplane);

    /* 9/THC24bits : NetBSD writes here even with 8-bit display: dummy */

    if (s->depth == 8) {

        memory_region_init_io(&s->thc24, OBJECT(s), &tcx_dummy_ops, s,

                              "tcx.thc24", TCX_THC_NREGS);

        sysbus_init_mmio(sbd, &s->thc24);

    }

    sysbus_init_irq(sbd, &s->irq);

    if (s->depth == 8) {

        s->con = graphic_console_init(DEVICE(dev), 0, &tcx_ops, s);

    } else {

        s->con = graphic_console_init(DEVICE(dev), 0, &tcx24_ops, s);

    }

    s->thcmisc = 0;

    qemu_console_resize(s->con, s->width, s->height);

}


static int mace3_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              const uint8_t *buf, int buf_size)

{

    int16_t *samples = data;

    MACEContext *ctx = avctx->priv_data;

    int i, j, k;

    for(i = 0; i < avctx->channels; i++) {

        int16_t *output = samples + i;

        for (j=0; j < buf_size / 2 / avctx->channels; j++)

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

                uint8_t pkt = buf[i*2 + j*2*avctx->channels + k];

                chomp3(&ctx->chd[i], output, pkt       &7, MACEtab1, MACEtab2,

                       8, avctx->channels);

                output += avctx->channels;

                chomp3(&ctx->chd[i], output,(pkt >> 3) &3, MACEtab3, MACEtab4,

                       4, avctx->channels);

                output += avctx->channels;

                chomp3(&ctx->chd[i], output, pkt >> 5    , MACEtab1, MACEtab2,

                       8, avctx->channels);

                output += avctx->channels;

            }

    }

    *data_size = 2 * 3 * buf_size;

    return buf_size;

}


static void query_facilities(void)

{

    struct sigaction sa_old, sa_new;

    register int r0 __asm__("0");

    register void *r1 __asm__("1");

    int fail;

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

    sa_new.sa_handler = sigill_handler;

    sigaction(SIGILL, &sa_new, &sa_old);

    /* First, try STORE FACILITY LIST EXTENDED.  If this is present, then

       we need not do any more probing.  Unfortunately, this itself is an

       extension and the original STORE FACILITY LIST instruction is

       kernel-only, storing its results at absolute address 200.  */

    /* stfle 0(%r1) */

    r1 = &facilities;

    asm volatile(".word 0xb2b0,0x1000"

                 : "=r"(r0) : "0"(0), "r"(r1) : "memory", "cc");

    if (got_sigill) {

        /* STORE FACILITY EXTENDED is not available.  Probe for one of each

           kind of instruction that we're interested in.  */

        /* ??? Possibly some of these are in practice never present unless

           the store-facility-extended facility is also present.  But since

           that isn't documented it's just better to probe for each.  */

        /* Test for z/Architecture.  Required even in 31-bit mode.  */

        got_sigill = 0;

        /* agr %r0,%r0 */

        asm volatile(".word 0xb908,0x0000" : "=r"(r0) : : "cc");

        if (!got_sigill) {

            facilities |= FACILITY_ZARCH_ACTIVE;

        }

        /* Test for long displacement.  */

        got_sigill = 0;

        /* ly %r0,0(%r1) */

        r1 = &facilities;

        asm volatile(".word 0xe300,0x1000,0x0058"

                     : "=r"(r0) : "r"(r1) : "cc");

        if (!got_sigill) {

            facilities |= FACILITY_LONG_DISP;

        }

        /* Test for extended immediates.  */

        got_sigill = 0;

        /* afi %r0,0 */

        asm volatile(".word 0xc209,0x0000,0x0000" : : : "cc");

        if (!got_sigill) {

            facilities |= FACILITY_EXT_IMM;

        }

        /* Test for general-instructions-extension.  */

        got_sigill = 0;

        /* msfi %r0,1 */

        asm volatile(".word 0xc201,0x0000,0x0001");

        if (!got_sigill) {

            facilities |= FACILITY_GEN_INST_EXT;

        }

    }

    sigaction(SIGILL, &sa_old, NULL);

    /* The translator currently uses these extensions unconditionally.

       Pruning this back to the base ESA/390 architecture doesn't seem

       worthwhile, since even the KVM target requires z/Arch.  */

    fail = 0;

    if ((facilities & FACILITY_ZARCH_ACTIVE) == 0) {

        fprintf(stderr, "TCG: z/Arch facility is required.\n");

        fprintf(stderr, "TCG: Boot with a 64-bit enabled kernel.\n");

        fail = 1;

    }

    if ((facilities & FACILITY_LONG_DISP) == 0) {

        fprintf(stderr, "TCG: long-displacement facility is required.\n");

        fail = 1;

    }

    /* So far there's just enough support for 31-bit mode to let the

       compile succeed.  This is good enough to run QEMU with KVM.  */

    if (sizeof(void *) != 8) {

        fprintf(stderr, "TCG: 31-bit mode is not supported.\n");

        fail = 1;

    }

    if (fail) {

        exit(-1);

    }

}


static int nut_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    NUTContext *nut = s->priv_data;

    ByteIOContext *bc = &s->pb;

    int64_t pos;

    int inited_stream_count;

    nut->avf= s;

    /* main header */

    pos=0;

    for(;;){

        pos= find_startcode(bc, MAIN_STARTCODE, pos)+1;

        if (pos<0){

            av_log(s, AV_LOG_ERROR, "no main startcode found\n");

            return -1;

        }

        if(decode_main_header(nut) >= 0)

            break;

    }

    s->bit_rate = 0;

    nut->stream = av_malloc(sizeof(StreamContext)*nut->stream_count);

    /* stream headers */

    pos=0;

    for(inited_stream_count=0; inited_stream_count < nut->stream_count;){

        pos= find_startcode(bc, STREAM_STARTCODE, pos)+1;

        if (pos<0){

            av_log(s, AV_LOG_ERROR, "not all stream headers found\n");

            return -1;

        }

        if(decode_stream_header(nut) >= 0)

            inited_stream_count++;

    }

    /* info headers */

    pos=0;

    for(;;){

        uint64_t startcode= find_any_startcode(bc, pos);

        pos= url_ftell(bc);

        if(startcode==0){

            av_log(s, AV_LOG_ERROR, "EOF before video frames\n");

            return -1;

        }else if(startcode == KEYFRAME_STARTCODE){

            nut->next_startcode= startcode;

            break;

        }else if(startcode != INFO_STARTCODE){

            continue;

        }

        decode_info_header(nut);

    }

    return 0;

}


int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)

{

    int ret, flush = 0;

    ret = check_packet(s, pkt);

    if (ret < 0)

        goto fail;

    if (pkt) {

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

        //FIXME/XXX/HACK drop zero sized packets

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0) {

            ret = 0;

            goto fail;

        }

        av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",

                pkt->size, pkt->dts, pkt->pts);

        if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))

            goto fail;

        if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {

            ret = AVERROR(EINVAL);

            goto fail;

        }

    } else {

        av_dlog(s, "av_interleaved_write_frame FLUSH\n");

        flush = 1;

    }

    for (;; ) {

        AVPacket opkt;

        int ret = interleave_packet(s, &opkt, pkt, flush);

        if (pkt) {

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

            av_init_packet(pkt);

            pkt = NULL;

        }

        if (ret <= 0) //FIXME cleanup needed for ret<0 ?

            return ret;

        ret = write_packet(s, &opkt);

        if (ret >= 0)

            s->streams[opkt.stream_index]->nb_frames++;

        av_free_packet(&opkt);

        if (ret < 0)

            return ret;

    }

fail:

    av_packet_unref(pkt);

    return ret;

}


static av_noinline void FUNC(hl_decode_mb_444)(H264Context *h, H264SliceContext *sl)

{

    const int mb_x    = h->mb_x;

    const int mb_y    = h->mb_y;

    const int mb_xy   = h->mb_xy;

    const int mb_type = h->cur_pic.mb_type[mb_xy];

    uint8_t *dest[3];

    int linesize;

    int i, j, p;

    int *block_offset = &h->block_offset[0];

    const int transform_bypass = !SIMPLE && (sl->qscale == 0 && h->sps.transform_bypass);

    const int plane_count      = (SIMPLE || !CONFIG_GRAY || !(h->flags & CODEC_FLAG_GRAY)) ? 3 : 1;

    for (p = 0; p < plane_count; p++) {

        dest[p] = h->cur_pic.f.data[p] +

                  ((mb_x << PIXEL_SHIFT) + mb_y * h->linesize) * 16;

        h->vdsp.prefetch(dest[p] + (h->mb_x & 3) * 4 * h->linesize + (64 << PIXEL_SHIFT),

                         h->linesize, 4);

    }

    h->list_counts[mb_xy] = sl->list_count;

    if (!SIMPLE && MB_FIELD(h)) {

        linesize     = sl->mb_linesize = sl->mb_uvlinesize = h->linesize * 2;

        block_offset = &h->block_offset[48];

        if (mb_y & 1) // FIXME move out of this function?

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

                dest[p] -= h->linesize * 15;

        if (FRAME_MBAFF(h)) {

            int list;

            for (list = 0; list < sl->list_count; list++) {

                if (!USES_LIST(mb_type, list))

                    continue;

                if (IS_16X16(mb_type)) {

                    int8_t *ref = &sl->ref_cache[list][scan8[0]];

                    fill_rectangle(ref, 4, 4, 8, (16 + *ref) ^ (h->mb_y & 1), 1);

                } else {

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

                        int ref = sl->ref_cache[list][scan8[i]];

                        if (ref >= 0)

                            fill_rectangle(&sl->ref_cache[list][scan8[i]], 2, 2,

                                           8, (16 + ref) ^ (h->mb_y & 1), 1);

                    }

                }

            }

        }

    } else {

        linesize = sl->mb_linesize = sl->mb_uvlinesize = h->linesize;

    }

    if (!SIMPLE && IS_INTRA_PCM(mb_type)) {

        if (PIXEL_SHIFT) {

            const int bit_depth = h->sps.bit_depth_luma;

            GetBitContext gb;

            init_get_bits(&gb, sl->intra_pcm_ptr, 768 * bit_depth);

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

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

                    uint16_t *tmp = (uint16_t *)(dest[p] + i * linesize);

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

                        tmp[j] = get_bits(&gb, bit_depth);

                }

        } else {

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

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

                    memcpy(dest[p] + i * linesize,

                           sl->intra_pcm_ptr + p * 256 + i * 16, 16);

        }

    } else {

        if (IS_INTRA(mb_type)) {

            if (h->deblocking_filter)

                xchg_mb_border(h, sl, dest[0], dest[1], dest[2], linesize,

                               linesize, 1, 1, SIMPLE, PIXEL_SHIFT);

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

                hl_decode_mb_predict_luma(h, sl, mb_type, 1, SIMPLE,

                                          transform_bypass, PIXEL_SHIFT,

                                          block_offset, linesize, dest[p], p);

            if (h->deblocking_filter)

                xchg_mb_border(h, sl, dest[0], dest[1], dest[2], linesize,

                               linesize, 0, 1, SIMPLE, PIXEL_SHIFT);

        } else {

            FUNC(hl_motion_444)(h, sl, dest[0], dest[1], dest[2],

                      h->qpel_put, h->h264chroma.put_h264_chroma_pixels_tab,

                      h->qpel_avg, h->h264chroma.avg_h264_chroma_pixels_tab,

                      h->h264dsp.weight_h264_pixels_tab,

                      h->h264dsp.biweight_h264_pixels_tab);

        }

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

            hl_decode_mb_idct_luma(h, sl, mb_type, 1, SIMPLE, transform_bypass,

                                   PIXEL_SHIFT, block_offset, linesize,

                                   dest[p], p);

    }

}


static int synthfilt_build_sb_samples(QDM2Context *q, GetBitContext *gb,

                                       int length, int sb_min, int sb_max)

{

    int sb, j, k, n, ch, run, channels;

    int joined_stereo, zero_encoding;

    int type34_first;

    float type34_div = 0;

    float type34_predictor;

    float samples[10];

    int sign_bits[16];

    if (length == 0) {

        // If no data use noise

        for (sb=sb_min; sb < sb_max; sb++)

            build_sb_samples_from_noise (q, sb);

        return 0;

    }

    for (sb = sb_min; sb < sb_max; sb++) {

        channels = q->nb_channels;

        if (q->nb_channels <= 1 || sb < 12)

            joined_stereo = 0;

        else if (sb >= 24)

            joined_stereo = 1;

        else

            joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1 (gb) : 0;

        if (joined_stereo) {

            if (get_bits_left(gb) >= 16)

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

                    sign_bits[j] = get_bits1 (gb);

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

                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])

                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];

            if (fix_coding_method_array(sb, q->nb_channels,

                                            q->coding_method)) {

                av_log(NULL, AV_LOG_ERROR, "coding method invalid\n");

                build_sb_samples_from_noise(q, sb);

                continue;

            }

            channels = 1;

        }

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

            FIX_NOISE_IDX(q->noise_idx);

            zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;

            type34_predictor = 0.0;

            type34_first = 1;

            for (j = 0; j < 128; ) {

                switch (q->coding_method[ch][sb][j / 2]) {

                    case 8:

                        if (get_bits_left(gb) >= 10) {

                            if (zero_encoding) {

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

                                    if ((j + 2 * k) >= 128)

                                        break;

                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;

                                }

                            } else {

                                n = get_bits(gb, 8);

                                if (n >= 243) {

                                    av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");

                                    return AVERROR_INVALIDDATA;

                                }

                                for (k = 0; k < 5; k++)

                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                            for (k = 0; k < 5; k++)

                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else {

                            for (k = 0; k < 10; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 10;

                        break;

                    case 10:

                        if (get_bits_left(gb) >= 1) {

                            float f = 0.81;

                            if (get_bits1(gb))

                                f = -f;

                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;

                            samples[0] = f;

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    case 16:

                        if (get_bits_left(gb) >= 10) {

                            if (zero_encoding) {

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

                                    if ((j + k) >= 128)

                                        break;

                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];

                                }

                            } else {

                                n = get_bits (gb, 8);

                                if (n >= 243) {

                                    av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");

                                    return AVERROR_INVALIDDATA;

                                }

                                for (k = 0; k < 5; k++)

                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                        } else {

                            for (k = 0; k < 5; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 5;

                        break;

                    case 24:

                        if (get_bits_left(gb) >= 7) {

                            n = get_bits(gb, 7);

                            if (n >= 125) {

                                av_log(NULL, AV_LOG_ERROR, "Invalid 7bit codeword\n");

                                return AVERROR_INVALIDDATA;

                            }

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

                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;

                        } else {

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

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 3;

                        break;

                    case 30:

                        if (get_bits_left(gb) >= 4) {

                            unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);

                            if (index >= FF_ARRAY_ELEMS(type30_dequant)) {

                                av_log(NULL, AV_LOG_ERROR, "index %d out of type30_dequant array\n", index);

                                return AVERROR_INVALIDDATA;

                            }

                            samples[0] = type30_dequant[index];

                        } else

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                    case 34:

                        if (get_bits_left(gb) >= 7) {

                            if (type34_first) {

                                type34_div = (float)(1 << get_bits(gb, 2));

                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;

                                type34_predictor = samples[0];

                                type34_first = 0;

                            } else {

                                unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);

                                if (index >= FF_ARRAY_ELEMS(type34_delta)) {

                                    av_log(NULL, AV_LOG_ERROR, "index %d out of type34_delta array\n", index);

                                    return AVERROR_INVALIDDATA;

                                }

                                samples[0] = type34_delta[index] / type34_div + type34_predictor;

                                type34_predictor = samples[0];

                            }

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    default:

                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                }

                if (joined_stereo) {

                    for (k = 0; k < run && j + k < 128; k++) {

                        q->sb_samples[0][j + k][sb] =

                            q->tone_level[0][sb][(j + k) / 2] * samples[k];

                        if (q->nb_channels == 2) {

                            if (sign_bits[(j + k) / 8])

                                q->sb_samples[1][j + k][sb] =

                                    q->tone_level[1][sb][(j + k) / 2] * -samples[k];

                            else

                                q->sb_samples[1][j + k][sb] =

                                    q->tone_level[1][sb][(j + k) / 2] * samples[k];

                        }

                    }

                } else {

                    for (k = 0; k < run; k++)

                        if ((j + k) < 128)

                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];

                }

                j += run;

            } // j loop

        } // channel loop

    } // subband loop

    return 0;

}


static IsoBcSection *find_iso_bc_entry(void)

{

    IsoBcEntry *e = (IsoBcEntry *)sec;

    uint32_t offset = find_iso_bc();

    int i;

    if (!offset) {

        return NULL;

    }

    read_iso_sector(offset, sec, "Failed to read El Torito boot catalog");

    if (!is_iso_bc_valid(e)) {

        /* The validation entry is mandatory */

        virtio_panic("No valid boot catalog found!\n");

        return NULL;

    }

    /*

     * Each entry has 32 bytes size, so one sector cannot contain > 64 entries.

     * We consider only boot catalogs with no more than 64 entries.

     */

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

        if (e[i].id == ISO_BC_BOOTABLE_SECTION) {

            if (is_iso_bc_entry_compatible(&e[i].body.sect)) {

                return &e[i].body.sect;

            }

        }

    }

    virtio_panic("No suitable boot entry found on ISO-9660 media!\n");

    return NULL;

}


static int ogg_new_stream(AVFormatContext *s, uint32_t serial, int new_avstream)

{

    struct ogg *ogg = s->priv_data;

    int idx = ogg->nstreams++;

    AVStream *st;

    struct ogg_stream *os;

    ogg->streams = av_realloc (ogg->streams,

                               ogg->nstreams * sizeof (*ogg->streams));

    memset (ogg->streams + idx, 0, sizeof (*ogg->streams));

    os = ogg->streams + idx;

    os->serial = serial;

    os->bufsize = DECODER_BUFFER_SIZE;

    os->buf = av_malloc(os->bufsize);

    os->header = -1;

    if (new_avstream) {

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        st->id = idx;

        avpriv_set_pts_info(st, 64, 1, 1000000);

    }

    return idx;

}


void gdb_exit(CPUArchState *env, int code)

{

  GDBState *s;

  char buf[4];

  s = gdbserver_state;

  if (!s) {

      return;

  }

#ifdef CONFIG_USER_ONLY

  if (gdbserver_fd < 0 || s->fd < 0) {

      return;

  }

#endif

  snprintf(buf, sizeof(buf), "W%02x", (uint8_t)code);

  put_packet(s, buf);

#ifndef CONFIG_USER_ONLY

  if (s->chr) {

      qemu_chr_delete(s->chr);

  }

#endif

}


SCSIRequest *scsi_req_alloc(size_t size, SCSIDevice *d, uint32_t tag, uint32_t lun)

{

    SCSIRequest *req;

    req = qemu_mallocz(size);

    /* Two references: one is passed back to the HBA, one is in d->requests.  */

    req->refcount = 2;

    req->bus = scsi_bus_from_device(d);

    req->dev = d;

    req->tag = tag;

    req->lun = lun;

    req->status = -1;

    req->enqueued = true;

    trace_scsi_req_alloc(req->dev->id, req->lun, req->tag);

    QTAILQ_INSERT_TAIL(&d->requests, req, next);

    return req;

}


static void detach(sPAPRDRConnector *drc, DeviceState *d,
                   spapr_drc_detach_cb *detach_cb,
                   void *detach_cb_opaque, Error **errp)
{
    DPRINTFN("drc: %x, detach", get_index(drc));
    drc->detach_cb = detach_cb;
    drc->detach_cb_opaque = detach_cb_opaque;
    /* if we've signalled device presence to the guest, or if the guest
     * has gone ahead and configured the device (via manually-executed
     * device add via drmgr in guest, namely), we need to wait
     * for the guest to quiesce the device before completing detach.
     * Otherwise, we can assume the guest hasn't seen it and complete the
     * detach immediately. Note that there is a small race window
     * just before, or during, configuration, which is this context
     * refers mainly to fetching the device tree via RTAS.
     * During this window the device access will be arbitrated by
     * associated DRC, which will simply fail the RTAS calls as invalid.
     * This is recoverable within guest and current implementations of
     * drmgr should be able to cope.
     */
    if (!drc->signalled && !drc->configured) {
        /* if the guest hasn't seen the device we can't rely on it to
         * set it back to an isolated state via RTAS, so do it here manually
         */
        drc->isolation_state = SPAPR_DR_ISOLATION_STATE_ISOLATED;
    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {
        DPRINTFN("awaiting transition to isolated state before removal");
    if (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI &&
        drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {
        DPRINTFN("awaiting transition to unusable state before removal");
    drc->indicator_state = SPAPR_DR_INDICATOR_STATE_INACTIVE;
    if (drc->detach_cb) {
        drc->detach_cb(drc->dev, drc->detach_cb_opaque);
    drc->awaiting_release = false;
    g_free(drc->fdt);
    drc->fdt = NULL;
    drc->fdt_start_offset = 0;
    object_property_del(OBJECT(drc), "device", NULL);
    drc->dev = NULL;
    drc->detach_cb = NULL;
    drc->detach_cb_opaque = NULL;


void xen_invalidate_map_cache_entry(uint8_t *buffer)

{

    MapCacheEntry *entry = NULL, *pentry = NULL;

    MapCacheRev *reventry;

    target_phys_addr_t paddr_index;

    target_phys_addr_t size;

    int found = 0;

    if (mapcache->last_address_vaddr == buffer) {

        mapcache->last_address_index = -1;

    }

    QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {

        if (reventry->vaddr_req == buffer) {

            paddr_index = reventry->paddr_index;

            size = reventry->size;

            found = 1;

            break;

        }

    }

    if (!found) {

        DPRINTF("%s, could not find %p\n", __func__, buffer);

        QTAILQ_FOREACH(reventry, &mapcache->locked_entries, next) {

            DPRINTF("   "TARGET_FMT_plx" -> %p is present\n", reventry->paddr_index, reventry->vaddr_req);

        }

        return;

    }

    QTAILQ_REMOVE(&mapcache->locked_entries, reventry, next);

    g_free(reventry);

    entry = &mapcache->entry[paddr_index % mapcache->nr_buckets];

    while (entry && (entry->paddr_index != paddr_index || entry->size != size)) {

        pentry = entry;

        entry = entry->next;

    }

    if (!entry) {

        DPRINTF("Trying to unmap address %p that is not in the mapcache!\n", buffer);

        return;

    }

    entry->lock--;

    if (entry->lock > 0 || pentry == NULL) {

        return;

    }

    pentry->next = entry->next;

    if (munmap(entry->vaddr_base, entry->size) != 0) {

        perror("unmap fails");

        exit(-1);

    }

    g_free(entry->valid_mapping);

    g_free(entry);

}


static void adx_decode_stereo(short *out,const unsigned char *in,PREV *prev)

{

	short tmp[32*2];

	int i;

	adx_decode(tmp   ,in   ,prev);

	adx_decode(tmp+32,in+18,prev+1);

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

		out[i*2]   = tmp[i];

		out[i*2+1] = tmp[i+32];

	}

}


void unregister_savevm(DeviceState *dev, const char *idstr, void *opaque)

{

    SaveStateEntry *se, *new_se;

    char id[256] = "";

    if (dev && dev->parent_bus && dev->parent_bus->info->get_dev_path) {

        char *path = dev->parent_bus->info->get_dev_path(dev);

        if (path) {

            pstrcpy(id, sizeof(id), path);

            pstrcat(id, sizeof(id), "/");

            qemu_free(path);

    pstrcat(id, sizeof(id), idstr);

    QTAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {

        if (strcmp(se->idstr, id) == 0 && se->opaque == opaque) {

            QTAILQ_REMOVE(&savevm_handlers, se, entry);

            qemu_free(se);


static void fsl_imx25_realize(DeviceState *dev, Error **errp)

{

    FslIMX25State *s = FSL_IMX25(dev);

    uint8_t i;

    Error *err = NULL;

    object_property_set_bool(OBJECT(&s->cpu), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    object_property_set_bool(OBJECT(&s->avic), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    sysbus_mmio_map(SYS_BUS_DEVICE(&s->avic), 0, FSL_IMX25_AVIC_ADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(&s->avic), 0,

                       qdev_get_gpio_in(DEVICE(&s->cpu), ARM_CPU_IRQ));

    sysbus_connect_irq(SYS_BUS_DEVICE(&s->avic), 1,

                       qdev_get_gpio_in(DEVICE(&s->cpu), ARM_CPU_FIQ));

    object_property_set_bool(OBJECT(&s->ccm), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    sysbus_mmio_map(SYS_BUS_DEVICE(&s->ccm), 0, FSL_IMX25_CCM_ADDR);

    /* Initialize all UARTs */

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

        static const struct {

            hwaddr addr;

            unsigned int irq;

        } serial_table[FSL_IMX25_NUM_UARTS] = {

            { FSL_IMX25_UART1_ADDR, FSL_IMX25_UART1_IRQ },

            { FSL_IMX25_UART2_ADDR, FSL_IMX25_UART2_IRQ },

            { FSL_IMX25_UART3_ADDR, FSL_IMX25_UART3_IRQ },

            { FSL_IMX25_UART4_ADDR, FSL_IMX25_UART4_IRQ },

            { FSL_IMX25_UART5_ADDR, FSL_IMX25_UART5_IRQ }

        };

        if (i < MAX_SERIAL_PORTS) {

            Chardev *chr;

            chr = serial_hds[i];

            if (!chr) {

                char label[20];

                snprintf(label, sizeof(label), "imx31.uart%d", i);

                chr = qemu_chr_new(label, "null");

            }

            qdev_prop_set_chr(DEVICE(&s->uart[i]), "chardev", chr);

        }

        object_property_set_bool(OBJECT(&s->uart[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->uart[i]), 0, serial_table[i].addr);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->uart[i]), 0,

                           qdev_get_gpio_in(DEVICE(&s->avic),

                                            serial_table[i].irq));

    }

    /* Initialize all GPT timers */

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

        static const struct {

            hwaddr addr;

            unsigned int irq;

        } gpt_table[FSL_IMX25_NUM_GPTS] = {

            { FSL_IMX25_GPT1_ADDR, FSL_IMX25_GPT1_IRQ },

            { FSL_IMX25_GPT2_ADDR, FSL_IMX25_GPT2_IRQ },

            { FSL_IMX25_GPT3_ADDR, FSL_IMX25_GPT3_IRQ },

            { FSL_IMX25_GPT4_ADDR, FSL_IMX25_GPT4_IRQ }

        };

        s->gpt[i].ccm = IMX_CCM(&s->ccm);

        object_property_set_bool(OBJECT(&s->gpt[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->gpt[i]), 0, gpt_table[i].addr);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->gpt[i]), 0,

                           qdev_get_gpio_in(DEVICE(&s->avic),

                                            gpt_table[i].irq));

    }

    /* Initialize all EPIT timers */

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

        static const struct {

            hwaddr addr;

            unsigned int irq;

        } epit_table[FSL_IMX25_NUM_EPITS] = {

            { FSL_IMX25_EPIT1_ADDR, FSL_IMX25_EPIT1_IRQ },

            { FSL_IMX25_EPIT2_ADDR, FSL_IMX25_EPIT2_IRQ }

        };

        s->epit[i].ccm = IMX_CCM(&s->ccm);

        object_property_set_bool(OBJECT(&s->epit[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->epit[i]), 0, epit_table[i].addr);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->epit[i]), 0,

                           qdev_get_gpio_in(DEVICE(&s->avic),

                                            epit_table[i].irq));

    }

    qdev_set_nic_properties(DEVICE(&s->fec), &nd_table[0]);

    object_property_set_bool(OBJECT(&s->fec), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    sysbus_mmio_map(SYS_BUS_DEVICE(&s->fec), 0, FSL_IMX25_FEC_ADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(&s->fec), 0,

                       qdev_get_gpio_in(DEVICE(&s->avic), FSL_IMX25_FEC_IRQ));

    /* Initialize all I2C */

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

        static const struct {

            hwaddr addr;

            unsigned int irq;

        } i2c_table[FSL_IMX25_NUM_I2CS] = {

            { FSL_IMX25_I2C1_ADDR, FSL_IMX25_I2C1_IRQ },

            { FSL_IMX25_I2C2_ADDR, FSL_IMX25_I2C2_IRQ },

            { FSL_IMX25_I2C3_ADDR, FSL_IMX25_I2C3_IRQ }

        };

        object_property_set_bool(OBJECT(&s->i2c[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->i2c[i]), 0, i2c_table[i].addr);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->i2c[i]), 0,

                           qdev_get_gpio_in(DEVICE(&s->avic),

                                            i2c_table[i].irq));

    }

    /* Initialize all GPIOs */

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

        static const struct {

            hwaddr addr;

            unsigned int irq;

        } gpio_table[FSL_IMX25_NUM_GPIOS] = {

            { FSL_IMX25_GPIO1_ADDR, FSL_IMX25_GPIO1_IRQ },

            { FSL_IMX25_GPIO2_ADDR, FSL_IMX25_GPIO2_IRQ },

            { FSL_IMX25_GPIO3_ADDR, FSL_IMX25_GPIO3_IRQ },

            { FSL_IMX25_GPIO4_ADDR, FSL_IMX25_GPIO4_IRQ }

        };

        object_property_set_bool(OBJECT(&s->gpio[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->gpio[i]), 0, gpio_table[i].addr);

        /* Connect GPIO IRQ to PIC */

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->gpio[i]), 0,

                           qdev_get_gpio_in(DEVICE(&s->avic),

                                            gpio_table[i].irq));

    }

    /* initialize 2 x 16 KB ROM */

    memory_region_init_rom_nomigrate(&s->rom[0], NULL,

                           "imx25.rom0", FSL_IMX25_ROM0_SIZE, &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(get_system_memory(), FSL_IMX25_ROM0_ADDR,

                                &s->rom[0]);

    memory_region_init_rom_nomigrate(&s->rom[1], NULL,

                           "imx25.rom1", FSL_IMX25_ROM1_SIZE, &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(get_system_memory(), FSL_IMX25_ROM1_ADDR,

                                &s->rom[1]);

    /* initialize internal RAM (128 KB) */

    memory_region_init_ram(&s->iram, NULL, "imx25.iram", FSL_IMX25_IRAM_SIZE,

                           &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(get_system_memory(), FSL_IMX25_IRAM_ADDR,

                                &s->iram);

    /* internal RAM (128 KB) is aliased over 128 MB - 128 KB */

    memory_region_init_alias(&s->iram_alias, NULL, "imx25.iram_alias",

                             &s->iram, 0, FSL_IMX25_IRAM_ALIAS_SIZE);

    memory_region_add_subregion(get_system_memory(), FSL_IMX25_IRAM_ALIAS_ADDR,

                                &s->iram_alias);

}


int add_av_stream(FFStream *feed,

                  AVStream *st)

{

    AVStream *fst;

    AVCodecContext *av, *av1;

    int i;

    av = &st->codec;

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

        st = feed->streams[i];

        av1 = &st->codec;

        if (av1->codec_id == av->codec_id &&

            av1->codec_type == av->codec_type &&

            av1->bit_rate == av->bit_rate) {

            switch(av->codec_type) {

            case CODEC_TYPE_AUDIO:

                if (av1->channels == av->channels &&

                    av1->sample_rate == av->sample_rate)

                    goto found;

                break;

            case CODEC_TYPE_VIDEO:

                if (av1->width == av->width &&

                    av1->height == av->height &&

                    av1->frame_rate == av->frame_rate &&

                    av1->gop_size == av->gop_size)

                    goto found;

                break;

            default:

                abort();

            }

        }

    }

    fst = av_mallocz(sizeof(AVStream));

    if (!fst)

        return -1;

    fst->priv_data = av_mallocz(sizeof(FeedData));

    memcpy(&fst->codec, av, sizeof(AVCodecContext));

    feed->streams[feed->nb_streams++] = fst;

    return feed->nb_streams - 1;

 found:

    return i;

}


static void mov_text_new_line_cb(void *priv, int forced)

{

    MovTextContext *s = priv;

    av_strlcpy(s->ptr, "\n", FFMIN(s->end - s->ptr, 2));

    s->ptr++;

}


static void pulse_get_output_timestamp(AVFormatContext *h, int stream, int64_t *dts, int64_t *wall)

{

    PulseData *s = h->priv_data;

    pa_usec_t latency;

    int neg;

    pa_threaded_mainloop_lock(s->mainloop);

    pa_stream_get_latency(s->stream, &latency, &neg);

    pa_threaded_mainloop_unlock(s->mainloop);

    *wall = av_gettime();

    *dts = s->timestamp - (neg ? -latency : latency);

}


static int update_packetheader(NUTContext *nut, ByteIOContext *bc, int additional_size){

    int64_t start= nut->packet_start;

    int64_t cur= url_ftell(bc);

    int size= cur - start + additional_size;

    if(size != nut->written_packet_size){

        int i;

        assert( size <= nut->written_packet_size );

        url_fseek(bc, nut->packet_size_pos, SEEK_SET);

        for(i=get_length(size); i < get_length(nut->written_packet_size); i+=7)

            put_byte(bc, 0x80);

        put_v(bc, size);

        url_fseek(bc, cur, SEEK_SET);

        nut->written_packet_size= size; //FIXME may fail if multiple updates with differing sizes, as get_length may differ

    }

    return 0;

}


static int build_huff(const uint8_t *src, VLC *vlc)

{

    int i;

    HuffEntry he[256];

    int last;

    uint32_t codes[256];

    uint8_t bits[256];

    uint8_t syms[256];

    uint32_t code;

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

        he[i].sym = i;

        he[i].len = *src++;

    }

    qsort(he, 256, sizeof(*he), huff_cmp);

    if (!he[0].len || he[0].len > 32)

        return -1;

    last = 255;

    while (he[last].len == 255 && last)

        last--;

    code = 1;

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

        codes[i] = code >> (32 - he[i].len);

        bits[i]  = he[i].len;

        syms[i]  = he[i].sym;

        code += 0x80000000u >> (he[i].len - 1);

    }

    return init_vlc_sparse(vlc, FFMIN(he[last].len, 9), last + 1,

                           bits,  sizeof(*bits),  sizeof(*bits),

                           codes, sizeof(*codes), sizeof(*codes),

                           syms,  sizeof(*syms),  sizeof(*syms), 0);

}


static void qemu_thread_set_name(QemuThread *thread, const char *name)

{

#ifdef CONFIG_PTHREAD_SETNAME_NP

    pthread_setname_np(thread->thread, name);

#endif

}


int ff_jpeg2000_init_component(Jpeg2000Component *comp,

                               Jpeg2000CodingStyle *codsty,

                               Jpeg2000QuantStyle *qntsty,

                               int cbps, int dx, int dy,

                               AVCodecContext *avctx)

{

    uint8_t log2_band_prec_width, log2_band_prec_height;

    int reslevelno, bandno, gbandno = 0, ret, i, j;

    uint32_t csize = 1;

    if (!codsty->nreslevels2decode) {

        av_log(avctx, AV_LOG_ERROR, "nreslevels2decode uninitialized\n");

        return AVERROR_INVALIDDATA;

    }

    if (ret = ff_jpeg2000_dwt_init(&comp->dwt, comp->coord,

                                   codsty->nreslevels2decode - 1,

                                   codsty->transform))

        return ret;

    // component size comp->coord is uint16_t so ir cannot overflow

    csize = (comp->coord[0][1] - comp->coord[0][0]) *

            (comp->coord[1][1] - comp->coord[1][0]);

    comp->data = av_malloc_array(csize, sizeof(*comp->data));

    if (!comp->data)

        return AVERROR(ENOMEM);

    comp->reslevel = av_malloc_array(codsty->nreslevels, sizeof(*comp->reslevel));

    if (!comp->reslevel)

        return AVERROR(ENOMEM);

    /* LOOP on resolution levels */

    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {

        int declvl = codsty->nreslevels - reslevelno;    // N_L -r see  ISO/IEC 15444-1:2002 B.5

        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

        /* Compute borders for each resolution level.

         * Computation of trx_0, trx_1, try_0 and try_1.

         * see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */

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

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

                reslevel->coord[i][j] =

                    ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1);

        // update precincts size: 2^n value

        reslevel->log2_prec_width  = codsty->log2_prec_widths[reslevelno];

        reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno];

        /* Number of bands for each resolution level */

        if (reslevelno == 0)

            reslevel->nbands = 1;

        else

            reslevel->nbands = 3;

        /* Number of precincts wich span the tile for resolution level reslevelno

         * see B.6 in ISO/IEC 15444-1:2002 eq. B-16

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width)

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width)

         * for Dcinema profiles in JPEG 2000

         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -|

         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */

        if (reslevel->coord[0][1] == reslevel->coord[0][0])

            reslevel->num_precincts_x = 0;

        else

            reslevel->num_precincts_x =

                ff_jpeg2000_ceildivpow2(reslevel->coord[0][1],

                                        reslevel->log2_prec_width) -

                (reslevel->coord[0][0] >> reslevel->log2_prec_width);

        if (reslevel->coord[1][1] == reslevel->coord[1][0])

            reslevel->num_precincts_y = 0;

        else

            reslevel->num_precincts_y =

                ff_jpeg2000_ceildivpow2(reslevel->coord[1][1],

                                        reslevel->log2_prec_height) -

                (reslevel->coord[1][0] >> reslevel->log2_prec_height);

        reslevel->band = av_malloc_array(reslevel->nbands, sizeof(*reslevel->band));

        if (!reslevel->band)

            return AVERROR(ENOMEM);

        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {

            Jpeg2000Band *band = reslevel->band + bandno;

            int cblkno, precno;

            int nb_precincts;

            /* TODO: Implementation of quantization step not finished,

             * see ISO/IEC 15444-1:2002 E.1 and A.6.4. */

            switch (qntsty->quantsty) {

                uint8_t gain;

                int numbps;

            case JPEG2000_QSTY_NONE:

                /* TODO: to verify. No quantization in this case */

                numbps = cbps +

                         lut_gain[codsty->transform][bandno + reslevelno > 0];

                band->stepsize = (float)SHL(2048 + qntsty->mant[gbandno],

                                            2 + numbps - qntsty->expn[gbandno]);

                break;

            case JPEG2000_QSTY_SI:

                /*TODO: Compute formula to implement. */

                band->stepsize = (float) (1 << 13);

                break;

            case JPEG2000_QSTY_SE:

                /* Exponent quantization step.

                 * Formula:

                 * delta_b = 2 ^ (R_b - expn_b) * (1 + (mant_b / 2 ^ 11))

                 * R_b = R_I + log2 (gain_b )

                 * see ISO/IEC 15444-1:2002 E.1.1 eqn. E-3 and E-4 */

                /* TODO/WARN: value of log2 (gain_b ) not taken into account

                 * but it works (compared to OpenJPEG). Why?

                 * Further investigation needed. */

                gain            = cbps;

                band->stepsize  = pow(2.0, gain - qntsty->expn[gbandno]);

                band->stepsize *= (float)qntsty->mant[gbandno] / 2048.0 + 1.0;

                /* FIXME: In openjepg code stespize = stepsize * 0.5. Why?

                 * If not set output of entropic decoder is not correct. */

                band->stepsize *= 0.5;

                break;

            default:

                band->stepsize = 0;

                av_log(avctx, AV_LOG_ERROR, "Unknown quantization format\n");

                break;

            }

            /* BITEXACT computing case --> convert to int */

            if (avctx->flags & CODEC_FLAG_BITEXACT)

                band->stepsize = (int32_t)(band->stepsize * (1 << 16));

            /* computation of tbx_0, tbx_1, tby_0, tby_1

             * see ISO/IEC 15444-1:2002 B.5 eq. B-15 and tbl B.1

             * codeblock width and height is computed for

             * DCI JPEG 2000 codeblock_width = codeblock_width = 32 = 2 ^ 5 */

            if (reslevelno == 0) {

                /* for reslevelno = 0, only one band, x0_b = y0_b = 0 */

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

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

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j],

                                                    declvl - 1);

                log2_band_prec_width  = reslevel->log2_prec_width;

                log2_band_prec_height = reslevel->log2_prec_height;

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height);

            } else {

                /* 3 bands x0_b = 1 y0_b = 0; x0_b = 0 y0_b = 1; x0_b = y0_b = 1 */

                /* x0_b and y0_b are computed with ((bandno + 1 >> i) & 1) */

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

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

                        /* Formula example for tbx_0 = ceildiv((tcx_0 - 2 ^ (declvl - 1) * x0_b) / declvl) */

                        band->coord[i][j] =

                            ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] -

                                                    (((bandno + 1 >> i) & 1) << declvl - 1),

                                                    declvl);

                /* TODO: Manage case of 3 band offsets here or

                 * in coding/decoding function? */

                /* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */

                band->log2_cblk_width  = FFMIN(codsty->log2_cblk_width,

                                               reslevel->log2_prec_width - 1);

                band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,

                                               reslevel->log2_prec_height - 1);

                log2_band_prec_width  = reslevel->log2_prec_width  - 1;

                log2_band_prec_height = reslevel->log2_prec_height - 1;

            }

            band->prec = av_malloc_array(reslevel->num_precincts_x *

                                         reslevel->num_precincts_y,

                                         sizeof(*band->prec));

            if (!band->prec)

                return AVERROR(ENOMEM);

            nb_precincts = reslevel->num_precincts_x * reslevel->num_precincts_y;

            for (precno = 0; precno < nb_precincts; precno++) {

                Jpeg2000Prec *prec = band->prec + precno;

                /* TODO: Explain formula for JPEG200 DCINEMA. */

                /* TODO: Verify with previous count of codeblocks per band */

                /* Compute P_x0 */

                prec->coord[0][0] = (precno % reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_width);

                prec->coord[0][0] = FFMAX(prec->coord[0][0], band->coord[0][0]);

                /* Compute P_y0 */

                prec->coord[1][0] = (precno / reslevel->num_precincts_x) *

                                    (1 << log2_band_prec_height);

                prec->coord[1][0] = FFMAX(prec->coord[1][0], band->coord[1][0]);

                /* Compute P_x1 */

                prec->coord[0][1] = prec->coord[0][0] +

                                    (1 << log2_band_prec_width);

                prec->coord[0][1] = FFMIN(prec->coord[0][1], band->coord[0][1]);

                /* Compute P_y1 */

                prec->coord[1][1] = prec->coord[1][0] +

                                    (1 << log2_band_prec_height);

                prec->coord[1][1] = FFMIN(prec->coord[1][1], band->coord[1][1]);

                prec->nb_codeblocks_width =

                    ff_jpeg2000_ceildivpow2(prec->coord[0][1] -

                                            prec->coord[0][0],

                                            band->log2_cblk_width);

                prec->nb_codeblocks_height =

                    ff_jpeg2000_ceildivpow2(prec->coord[1][1] -

                                            prec->coord[1][0],

                                            band->log2_cblk_height);

                /* Tag trees initialization */

                prec->cblkincl =

                    ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->cblkincl)

                    return AVERROR(ENOMEM);

                prec->zerobits =

                    ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,

                                              prec->nb_codeblocks_height);

                if (!prec->zerobits)

                    return AVERROR(ENOMEM);

                prec->cblk = av_malloc_array(prec->nb_codeblocks_width *

                                             prec->nb_codeblocks_height,

                                             sizeof(*prec->cblk));

                if (!prec->cblk)

                    return AVERROR(ENOMEM);

                for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                    Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                    uint16_t Cx0, Cy0;

                    /* Compute coordinates of codeblocks */

                    /* Compute Cx0*/

                    Cx0 = (prec->coord[0][0] >> band->log2_cblk_width) << band->log2_cblk_width;

                    Cx0 = Cx0 + ((cblkno % prec->nb_codeblocks_width)  << band->log2_cblk_width);

                    cblk->coord[0][0] = FFMAX(Cx0, prec->coord[0][0]);

                    /* Compute Cy0*/

                    Cy0 = (prec->coord[1][0] >> band->log2_cblk_height) << band->log2_cblk_height;

                    Cy0 = Cy0 + ((cblkno / prec->nb_codeblocks_width)   << band->log2_cblk_height);

                    cblk->coord[1][0] = FFMAX(Cy0, prec->coord[1][0]);

                    /* Compute Cx1 */

                    cblk->coord[0][1] = FFMIN(Cx0 + (1 << band->log2_cblk_width),

                                              prec->coord[0][1]);

                    /* Compute Cy1 */

                    cblk->coord[1][1] = FFMIN(Cy0 + (1 << band->log2_cblk_height),

                                              prec->coord[1][1]);

                    cblk->zero      = 0;

                    cblk->lblock    = 3;

                    cblk->length    = 0;

                    cblk->lengthinc = 0;

                    cblk->npasses   = 0;

                }

            }

        }

    }

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->vmsd = &vmstate_icp_server;

    dc->realize = icp_realize;

}


static void balloon_stats_poll_cb(void *opaque)

{

    VirtIOBalloon *s = opaque;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    if (!balloon_stats_supported(s)) {

        /* re-schedule */

        balloon_stats_change_timer(s, s->stats_poll_interval);

        return;

    }

    virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);

    virtio_notify(vdev, s->svq);

    g_free(s->stats_vq_elem);

    s->stats_vq_elem = NULL;

}


void virtio_setup_block(struct subchannel_id schid)

{

    struct vq_info_block info;

    struct vq_config_block config = {};

    blk_cfg.blk_size = 0; /* mark "illegal" - setup started... */

    guessed_disk_nature = false;

    virtio_reset(schid);

    /*

     * Skipping CCW_CMD_READ_FEAT. We're not doing anything fancy, and

     * we'll just stop dead anyway if anything does not work like we

     * expect it.

     */

    config.index = 0;

    if (run_ccw(schid, CCW_CMD_READ_VQ_CONF, &config, sizeof(config))) {

        virtio_panic("Could not get block device VQ configuration\n");

    }

    if (run_ccw(schid, CCW_CMD_READ_CONF, &blk_cfg, sizeof(blk_cfg))) {

        virtio_panic("Could not get block device configuration\n");

    }

    vring_init(&block, config.num, ring_area,

               KVM_S390_VIRTIO_RING_ALIGN);

    info.queue = (unsigned long long) ring_area;

    info.align = KVM_S390_VIRTIO_RING_ALIGN;

    info.index = 0;

    info.num = config.num;

    block.schid = schid;

    if (!run_ccw(schid, CCW_CMD_SET_VQ, &info, sizeof(info))) {

        virtio_set_status(schid, VIRTIO_CONFIG_S_DRIVER_OK);

    }

    if (!virtio_ipl_disk_is_valid()) {

        /* make sure all getters but blocksize return 0 for invalid IPL disk */

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

        virtio_assume_scsi();

    }

}


static void test_tco1_control_bits(void)

{

    TestData d;

    uint16_t val;

    d.args = NULL;

    d.noreboot = true;

    test_init(&d);

    val = TCO_LOCK;

    qpci_io_writew(d.dev, d.tco_io_base + TCO1_CNT, val);

    val &= ~TCO_LOCK;

    qpci_io_writew(d.dev, d.tco_io_base + TCO1_CNT, val);

    g_assert_cmpint(qpci_io_readw(d.dev, d.tco_io_base + TCO1_CNT), ==,

                    TCO_LOCK);

    qtest_end();

}


static void update_pam(PCII440FXState *d, uint32_t start, uint32_t end, int r,

                       PAMMemoryRegion *mem)

{

    if (mem->initialized) {

        memory_region_del_subregion(d->system_memory, &mem->mem);

        memory_region_destroy(&mem->mem);

    }

    //    printf("ISA mapping %08x-0x%08x: %d\n", start, end, r);

    switch(r) {

    case 3:

        /* RAM */

        memory_region_init_alias(&mem->mem, "pam-ram", d->ram_memory,

                                 start, end - start);

        break;

    case 1:

        /* ROM (XXX: not quite correct) */

        memory_region_init_alias(&mem->mem, "pam-rom", d->ram_memory,

                                 start, end - start);

        memory_region_set_readonly(&mem->mem, true);

        break;

    case 2:

    case 0:

        /* XXX: should distinguish read/write cases */

        memory_region_init_alias(&mem->mem, "pam-pci", d->pci_address_space,

                                 start, end - start);

        break;

    }

    memory_region_add_subregion_overlap(d->system_memory,

                                        start, &mem->mem, 1);

    mem->initialized = true;

}


static int copy_cell(Indeo3DecodeContext *ctx, Plane *plane, Cell *cell)

{

    int     h, w, mv_x, mv_y, offset, offset_dst;

    uint8_t *src, *dst;

    /* setup output and reference pointers */

    offset_dst  = (cell->ypos << 2) * plane->pitch + (cell->xpos << 2);

    dst         = plane->pixels[ctx->buf_sel] + offset_dst;

    mv_y        = cell->mv_ptr[0];

    mv_x        = cell->mv_ptr[1];

    /* -1 because there is an extra line on top for prediction */

    if ((cell->ypos << 2) + mv_y < -1 || (cell->xpos << 2) + mv_x < 0 ||

        ((cell->ypos + cell->height) << 2) + mv_y > plane->height     ||

        ((cell->xpos + cell->width)  << 2) + mv_x > plane->width) {

        av_log(ctx->avctx, AV_LOG_ERROR,

               "Motion vectors point out of the frame.\n");

        return AVERROR_INVALIDDATA;

    }

    offset      = offset_dst + mv_y * plane->pitch + mv_x;

    src         = plane->pixels[ctx->buf_sel ^ 1] + offset;

    h = cell->height << 2;

    for (w = cell->width; w > 0;) {

        /* copy using 16xH blocks */

        if (!((cell->xpos << 2) & 15) && w >= 4) {

            for (; w >= 4; src += 16, dst += 16, w -= 4)

                ctx->hdsp.put_pixels_tab[0][0](dst, src, plane->pitch, h);

        }

        /* copy using 8xH blocks */

        if (!((cell->xpos << 2) & 7) && w >= 2) {

            ctx->hdsp.put_pixels_tab[1][0](dst, src, plane->pitch, h);

            w -= 2;

            src += 8;

            dst += 8;

        }

        if (w >= 1) {

            ctx->hdsp.put_pixels_tab[2][0](dst, src, plane->pitch, h);

            w--;

            src += 4;

            dst += 4;

        }

    }

    return 0;

}


int av_expr_parse(AVExpr **expr, const char *s,

                  const char * const *const_names,

                  const char * const *func1_names, double (* const *funcs1)(void *, double),

                  const char * const *func2_names, double (* const *funcs2)(void *, double, double),

                  int log_offset, void *log_ctx)

{

    Parser p;

    AVExpr *e = NULL;

    char *w = av_malloc(strlen(s) + 1);

    char *wp = w;

    const char *s0 = s;

    int ret = 0;

    if (!w)

        return AVERROR(ENOMEM);

    while (*s)

        if (!isspace(*s++)) *wp++ = s[-1];

    *wp++ = 0;

    p.class      = &class;

    p.stack_index=100;

    p.s= w;

    p.const_names = const_names;

    p.funcs1      = funcs1;

    p.func1_names = func1_names;

    p.funcs2      = funcs2;

    p.func2_names = func2_names;

    p.log_offset = log_offset;

    p.log_ctx    = log_ctx;

    if ((ret = parse_expr(&e, &p)) < 0)

        goto end;

    if (*p.s) {

        av_log(&p, AV_LOG_ERROR, "Invalid chars '%s' at the end of expression '%s'\n", p.s, s0);

        ret = AVERROR(EINVAL);

        goto end;

    }

    if (!verify_expr(e)) {

        av_expr_free(e);

        ret = AVERROR(EINVAL);

        goto end;

    }

    *expr = e;

end:

    av_free(w);

    return ret;

}