void ff_id3v1_read(AVFormatContext *s)

{

    int ret;

    uint8_t buf[ID3v1_TAG_SIZE];

    int64_t filesize, position = avio_tell(s->pb);

    if (s->pb->seekable) {

        /* XXX: change that */

        filesize = avio_size(s->pb);

        if (filesize > 128) {

            avio_seek(s->pb, filesize - 128, SEEK_SET);

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

            if (ret == ID3v1_TAG_SIZE) {

                parse_tag(s, buf);

            }

            avio_seek(s->pb, position, SEEK_SET);

        }

    }

}


static av_cold int dvvideo_encode_init(AVCodecContext *avctx)

{

    DVVideoContext *s = avctx->priv_data;

    FDCTDSPContext fdsp;

    MECmpContext mecc;

    PixblockDSPContext pdsp;

    int ret;

    s->sys = av_dv_codec_profile(avctx->width, avctx->height, avctx->pix_fmt);

    if (!s->sys) {

        av_log(avctx, AV_LOG_ERROR, "Found no DV profile for %ix%i %s video. "

                                    "Valid DV profiles are:\n",

               avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));

        ff_dv_print_profiles(avctx, AV_LOG_ERROR);

        return AVERROR(EINVAL);

    }

    ret = ff_dv_init_dynamic_tables(s, s->sys);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing work tables.\n");

        return ret;

    }

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    dv_vlc_map_tableinit();

    ff_fdctdsp_init(&fdsp, avctx);

    ff_me_cmp_init(&mecc, avctx);

    ff_pixblockdsp_init(&pdsp, avctx);

    ff_set_cmp(&mecc, mecc.ildct_cmp, avctx->ildct_cmp);

    s->get_pixels = pdsp.get_pixels;

    s->ildct_cmp  = mecc.ildct_cmp[5];

    s->fdct[0]    = fdsp.fdct;

    s->fdct[1]    = fdsp.fdct248;

    return ff_dvvideo_init(avctx);

}


yuv2rgb48_2_c_template(SwsContext *c, const uint16_t *buf0,

                       const uint16_t *buf1, const uint16_t *ubuf0,

                       const uint16_t *ubuf1, const uint16_t *vbuf0,

                       const uint16_t *vbuf1, const uint16_t *abuf0,

                       const uint16_t *abuf1, uint8_t *dest, int dstW,

                       int yalpha, int uvalpha, int y,

                       enum PixelFormat target)

{

    int  yalpha1 = 4095 - yalpha;

    int uvalpha1 = 4095 - uvalpha;

    int i;

    for (i = 0; i < (dstW >> 1); i++) {

        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha)  >> 19;

        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha)  >> 19;

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha) >> 19;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha) >> 19;

        const uint8_t *r = (const uint8_t *) c->table_rV[V],

                      *g = (const uint8_t *)(c->table_gU[U] + c->table_gV[V]),

                      *b = (const uint8_t *) c->table_bU[U];

        dest[ 0] = dest[ 1] = r_b[Y1];

        dest[ 2] = dest[ 3] =   g[Y1];

        dest[ 4] = dest[ 5] = b_r[Y1];

        dest[ 6] = dest[ 7] = r_b[Y2];

        dest[ 8] = dest[ 9] =   g[Y2];

        dest[10] = dest[11] = b_r[Y2];

        dest += 12;

    }

}


void *kvmppc_create_spapr_tce(uint32_t liobn, uint32_t window_size, int *pfd)

{

    struct kvm_create_spapr_tce args = {

        .liobn = liobn,

        .window_size = window_size,

    };

    long len;

    int fd;

    void *table;

    /* Must set fd to -1 so we don't try to munmap when called for

     * destroying the table, which the upper layers -will- do

     */

    *pfd = -1;

    if (!cap_spapr_tce) {

        return NULL;

    }

    fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_SPAPR_TCE, &args);

    if (fd < 0) {

        fprintf(stderr, "KVM: Failed to create TCE table for liobn 0x%x\n",

                liobn);

        return NULL;

    }

    len = (window_size / SPAPR_TCE_PAGE_SIZE) * sizeof(sPAPRTCE);

    /* FIXME: round this up to page size */

    table = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    if (table == MAP_FAILED) {

        fprintf(stderr, "KVM: Failed to map TCE table for liobn 0x%x\n",

                liobn);

        close(fd);

        return NULL;

    }

    *pfd = fd;

    return table;

}


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

    int i;

    int index_a = qp + h->slice_alpha_c0_offset;

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

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

    for( i = 0; i < 4; i++, pix += stride) {

        const int bS_index = i*bsi;

        if( bS[bS_index] == 0 ) {

            continue;

        }

        if( bS[bS_index] < 4 ) {

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

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int q0 = pix[0];

            const int q1 = pix[1];

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

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

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

                pix[-1] = av_clip_uint8( p0 + i_delta );    /* p0' */

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

                tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d, qp:%d, indexA:%d, alpha:%d, beta:%d, tc:%d\n# bS:%d -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x]\n", i, qp[qp_index], index_a, alpha, beta, tc, bS[bS_index], pix[-3], p1, p0, q0, q1, pix[2], p1, pix[-1], pix[0], q1);

            }

        }else{

            const int p0 = pix[-1];

            const int p1 = pix[-2];

            const int q0 = pix[0];

            const int q1 = pix[1];

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

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;   /* p0' */

                pix[0]  = ( 2*q1 + q0 + p1 + 2 ) >> 2;   /* q0' */

                tprintf(h->s.avctx, "filter_mb_mbaff_edgecv i:%d\n# bS:4 -> [%02x, %02x, %02x, %02x, %02x, %02x] =>[%02x, %02x, %02x, %02x, %02x, %02x]\n", i, pix[-3], p1, p0, q0, q1, pix[2], pix[-3], pix[-2], pix[-1], pix[0], pix[1], pix[2]);

            }

        }

    }

}


static void bdrv_qed_invalidate_cache(BlockDriverState *bs, Error **errp)

{

    BDRVQEDState *s = bs->opaque;

    Error *local_err = NULL;

    int ret;

    bdrv_qed_close(bs);

    memset(s, 0, sizeof(BDRVQEDState));

    ret = bdrv_qed_do_open(bs, NULL, bs->open_flags, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        error_prepend(errp, "Could not reopen qed layer: ");

        return;

    } else if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not reopen qed layer");

        return;

    }

}


void spapr_register_hypercall(target_ulong opcode, spapr_hcall_fn fn)

{

    spapr_hcall_fn *slot;

    if (opcode <= MAX_HCALL_OPCODE) {

        assert((opcode & 0x3) == 0);

        slot = &papr_hypercall_table[opcode / 4];

    } else {

        assert((opcode >= KVMPPC_HCALL_BASE) && (opcode <= KVMPPC_HCALL_MAX));

        slot = &kvmppc_hypercall_table[opcode - KVMPPC_HCALL_BASE];

    }

    assert(!(*slot) || (fn == *slot));

    *slot = fn;

}


static int usb_host_open(USBHostDevice *dev, int bus_num,

                         int addr, const char *port,

                         const char *prod_name, int speed)

{

    int fd = -1, ret;

    trace_usb_host_open_started(bus_num, addr);

    if (dev->fd != -1) {

        goto fail;

    }

    fd = usb_host_open_device(bus_num, addr);

    if (fd < 0) {

        goto fail;

    }

    DPRINTF("husb: opened %s\n", buf);

    dev->bus_num = bus_num;

    dev->addr = addr;

    strcpy(dev->port, port);

    dev->fd = fd;

    /* read the device description */

    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));

    if (dev->descr_len <= 0) {

        perror("husb: reading device data failed");

        goto fail;

    }

#ifdef DEBUG

    {

        int x;

        printf("=== begin dumping device descriptor data ===\n");

        for (x = 0; x < dev->descr_len; x++) {

            printf("%02x ", dev->descr[x]);

        }

        printf("\n=== end dumping device descriptor data ===\n");

    }

#endif

    /* start unconfigured -- we'll wait for the guest to set a configuration */

    if (!usb_host_claim_interfaces(dev, 0)) {

        goto fail;

    }

    usb_ep_init(&dev->dev);

    ret = usb_linux_update_endp_table(dev);

    if (ret) {

        goto fail;

    }

    if (speed == -1) {

        struct usbdevfs_connectinfo ci;

        ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);

        if (ret < 0) {

            perror("usb_host_device_open: USBDEVFS_CONNECTINFO");

            goto fail;

        }

        if (ci.slow) {

            speed = USB_SPEED_LOW;

        } else {

            speed = USB_SPEED_HIGH;

        }

    }

    dev->dev.speed = speed;

    dev->dev.speedmask = (1 << speed);

    if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {

        dev->dev.speedmask |= USB_SPEED_MASK_FULL;

    }

    trace_usb_host_open_success(bus_num, addr);

    if (!prod_name || prod_name[0] == '\0') {

        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),

                 "host:%d.%d", bus_num, addr);

    } else {

        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),

                prod_name);

    }

    ret = usb_device_attach(&dev->dev);

    if (ret) {

        goto fail;

    }

    /* USB devio uses 'write' flag to check for async completions */

    qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);

    return 0;

fail:

    trace_usb_host_open_failure(bus_num, addr);

    if (dev->fd != -1) {

        close(dev->fd);

        dev->fd = -1;

    }

    return -1;

}


static void ide_init2(IDEState *ide_state,

                      BlockDriverState *hd0, BlockDriverState *hd1,

                      qemu_irq irq)

{

    IDEState *s;

    static int drive_serial = 1;

    int i, cylinders, heads, secs;

    uint64_t nb_sectors;

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

        s = ide_state + i;

        s->io_buffer = qemu_memalign(512, IDE_DMA_BUF_SECTORS*512 + 4);

        if (i == 0)

            s->bs = hd0;

        else

            s->bs = hd1;

        if (s->bs) {

            bdrv_get_geometry(s->bs, &nb_sectors);

            bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);

            s->cylinders = cylinders;

            s->heads = heads;

            s->sectors = secs;

            s->nb_sectors = nb_sectors;

            if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {

                s->is_cdrom = 1;

		bdrv_set_change_cb(s->bs, cdrom_change_cb, s);

            }

        }

        s->drive_serial = drive_serial++;

        strncpy(s->drive_serial_str, drive_get_serial(s->bs),

                sizeof(s->drive_serial_str));

        if (strlen(s->drive_serial_str) == 0)

            snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),

                    "QM%05d", s->drive_serial);

        s->irq = irq;

        s->sector_write_timer = qemu_new_timer(vm_clock,

                                               ide_sector_write_timer_cb, s);

        ide_reset(s);

    }

}


static ssize_t nbd_send_reply(QIOChannel *ioc, NBDReply *reply)

{

    uint8_t buf[NBD_REPLY_SIZE];

    reply->error = system_errno_to_nbd_errno(reply->error);

    TRACE("Sending response to client: { .error = %" PRId32

          ", handle = %" PRIu64 " }",

          reply->error, reply->handle);

    /* Reply

       [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)

       [ 4 ..  7]    error   (0 == no error)

       [ 7 .. 15]    handle

     */

    stl_be_p(buf, NBD_REPLY_MAGIC);

    stl_be_p(buf + 4, reply->error);

    stq_be_p(buf + 8, reply->handle);

    return write_sync(ioc, buf, sizeof(buf), NULL);

}


static void q35_host_get_pci_hole64_end(Object *obj, Visitor *v,

                                        const char *name, void *opaque,

                                        Error **errp)

{

    PCIHostState *h = PCI_HOST_BRIDGE(obj);

    Range w64;

    pci_bus_get_w64_range(h->bus, &w64);

    visit_type_uint64(v, name, &w64.end, errp);

}


static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,

                                         int64_t sector_num,

                                         QEMUIOVector *qiov,

                                         int nb_sectors,

                                         BdrvRequestFlags flags,

                                         BlockCompletionFunc *cb,

                                         void *opaque,

                                         bool is_write)

{

    Coroutine *co;

    BlockAIOCBCoroutine *acb;

    acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);

    acb->need_bh = true;

    acb->req.error = -EINPROGRESS;

    acb->req.sector = sector_num;

    acb->req.nb_sectors = nb_sectors;

    acb->req.qiov = qiov;

    acb->req.flags = flags;

    acb->is_write = is_write;

    co = qemu_coroutine_create(bdrv_co_do_rw);

    qemu_coroutine_enter(co, acb);

    bdrv_co_maybe_schedule_bh(acb);

    return &acb->common;

}


static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,

                                            int64_t sector_num,

                                            int nb_sectors, int *pnum)

{

    *pnum = nb_sectors;

    return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID | BDRV_BLOCK_DATA |

           (sector_num << BDRV_SECTOR_BITS);

}


static inline int check_fit_tl(tcg_target_long val, unsigned int bits)

{

    return (val << ((sizeof(tcg_target_long) * 8 - bits))

            >> (sizeof(tcg_target_long) * 8 - bits)) == val;

}


int av_cold ff_celt_pvq_init(CeltPVQ **pvq, int encode)

{

    CeltPVQ *s = av_malloc(sizeof(CeltPVQ));

    if (!s)

        return AVERROR(ENOMEM);

    s->pvq_search = ppp_pvq_search_c;

    s->quant_band = encode ? pvq_encode_band : pvq_decode_band;

    s->band_cost  = pvq_band_cost;

    if (ARCH_X86)

        ff_opus_dsp_init_x86(s);

    *pvq = s;

    return 0;

}


static off_t v9fs_synth_telldir(FsContext *ctx, V9fsFidOpenState *fs)

{

    V9fsSynthOpenState *synth_open = fs->private;

    return synth_open->offset;

}


bool gs_allowed(void)

{

    if (kvm_enabled()) {

        MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());

        if (object_class_dynamic_cast(OBJECT_CLASS(mc),

                                      TYPE_S390_CCW_MACHINE)) {

            S390CcwMachineClass *s390mc = S390_MACHINE_CLASS(mc);

            return s390mc->gs_allowed;

        }

        /* Make sure the "none" machine can have gs */

        return true;

    }

    return false;

}


tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h)

{

    uint32_t *buf32;

    uint32_t pix32;

    int shift[3];

    int *prev;

    int here[3], upper[3], left[3], upperleft[3];

    int prediction;

    int x, y, c;

    buf32 = (uint32_t *)buf;

    memset(vs->tight_gradient.buffer, 0, w * 3 * sizeof(int));

    if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) ==

        (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) {

        shift[0] = vs->clientds.pf.rshift;

        shift[1] = vs->clientds.pf.gshift;

        shift[2] = vs->clientds.pf.bshift;

    } else {

        shift[0] = 24 - vs->clientds.pf.rshift;

        shift[1] = 24 - vs->clientds.pf.gshift;

        shift[2] = 24 - vs->clientds.pf.bshift;

    }

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

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

            upper[c] = 0;

            here[c] = 0;

        }

        prev = (int *)vs->tight_gradient.buffer;

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

            pix32 = *buf32++;

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

                upperleft[c] = upper[c];

                left[c] = here[c];

                upper[c] = *prev;

                here[c] = (int)(pix32 >> shift[c] & 0xFF);

                *prev++ = here[c];

                prediction = left[c] + upper[c] - upperleft[c];

                if (prediction < 0) {

                    prediction = 0;

                } else if (prediction > 0xFF) {

                    prediction = 0xFF;

                }

                *buf++ = (char)(here[c] - prediction);

            }

        }

    }

}


static void qmp_output_type_uint64(Visitor *v, const char *name, uint64_t *obj,

                                   Error **errp)

{

    /* FIXME values larger than INT64_MAX become negative */

    QmpOutputVisitor *qov = to_qov(v);

    qmp_output_add(qov, name, qint_from_int(*obj));

}


static void bh_run_aio_completions(void *opaque)

{

    QEMUBH **bh = opaque;

    qemu_bh_delete(*bh);

    qemu_free(bh);

    qemu_aio_process_queue();

}


long do_rt_sigreturn(CPUARMState *env)

{

    struct target_rt_sigframe *frame = NULL;

    abi_ulong frame_addr = env->xregs[31];

    trace_user_do_rt_sigreturn(env, frame_addr);

    if (frame_addr & 15) {

        goto badframe;

    }

    if  (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    if (target_restore_sigframe(env, frame)) {

        goto badframe;

    }

    if (do_sigaltstack(frame_addr +

            offsetof(struct target_rt_sigframe, uc.tuc_stack),

            0, get_sp_from_cpustate(env)) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->xregs[0];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static void update(NUTContext *nut, int stream_index, int64_t frame_start, int frame_type, int frame_code, int key_frame, int size, int64_t pts){

    StreamContext *stream= &nut->stream[stream_index];

    stream->last_key_frame= key_frame;

    nut->last_frame_start[ frame_type ]= frame_start;

    update_lru(stream->lru_pts_delta, pts - stream->last_pts, 3);

    update_lru(stream->lru_size     ,                   size, 2);

    stream->last_pts= pts;

    if(    nut->frame_code[frame_code].flags & FLAG_PTS

        && nut->frame_code[frame_code].flags & FLAG_FULL_PTS)

        stream->last_full_pts= pts;

}


void ff_rv34dsp_init_neon(RV34DSPContext *c, DSPContext* dsp)

{

    c->rv34_inv_transform    = ff_rv34_inv_transform_noround_neon;

    c->rv34_inv_transform_dc = ff_rv34_inv_transform_noround_dc_neon;

    c->rv34_idct_add    = ff_rv34_idct_add_neon;

    c->rv34_idct_dc_add = ff_rv34_idct_dc_add_neon;

}


static int request_samples(AVFilterContext *ctx, int min_samples)

{

    MixContext *s = ctx->priv;

    int i, ret;

    av_assert0(s->nb_inputs > 1);

    for (i = 1; i < s->nb_inputs; i++) {

        ret = 0;

        if (!(s->input_state[i] & INPUT_ON))

            continue;

        if (av_audio_fifo_size(s->fifos[i]) >= min_samples)

            continue;

        ret = ff_request_frame(ctx->inputs[i]);

        if (ret == AVERROR_EOF) {

            s->input_state[i] |= INPUT_EOF;

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

                s->input_state[i] = 0;

                continue;

            }

        } else if (ret < 0)

            return ret;

    }

    return output_frame(ctx->outputs[0], 1);

}


void ff_vp3_idct_dc_add_c(uint8_t *dest/*align 8*/, int line_size, const DCTELEM *block/*align 16*/){

    int i, dc = (block[0] + 15) >> 5;

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

        dest[0] = av_clip_uint8(dest[0] + dc);

        dest[1] = av_clip_uint8(dest[1] + dc);

        dest[2] = av_clip_uint8(dest[2] + dc);

        dest[3] = av_clip_uint8(dest[3] + dc);

        dest[4] = av_clip_uint8(dest[4] + dc);

        dest[5] = av_clip_uint8(dest[5] + dc);

        dest[6] = av_clip_uint8(dest[6] + dc);

        dest[7] = av_clip_uint8(dest[7] + dc);

        dest += line_size;

    }

}


static enum AVPixelFormat mpeg_get_pixelformat(AVCodecContext *avctx)

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    const enum AVPixelFormat *pix_fmts;

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->xvmc_acceleration)

        return ff_get_format(avctx, pixfmt_xvmc_mpg2_420);

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    if (s->chroma_format < 2)

        pix_fmts = mpeg12_hwaccel_pixfmt_list_420;

    else if (s->chroma_format == 2)

        pix_fmts = mpeg12_pixfmt_list_422;

    else

        pix_fmts = mpeg12_pixfmt_list_444;

    return ff_get_format(avctx, pix_fmts);

}


static int init_tiles(Jpeg2000EncoderContext *s)

{

    int tileno, tilex, tiley, compno;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    Jpeg2000QuantStyle  *qntsty = &s->qntsty;

    s->numXtiles = ff_jpeg2000_ceildiv(s->width, s->tile_width);

    s->numYtiles = ff_jpeg2000_ceildiv(s->height, s->tile_height);

    s->tile = av_malloc_array(s->numXtiles, s->numYtiles * sizeof(Jpeg2000Tile));

    if (!s->tile)

        return AVERROR(ENOMEM);

    for (tileno = 0, tiley = 0; tiley < s->numYtiles; tiley++)

        for (tilex = 0; tilex < s->numXtiles; tilex++, tileno++){

            Jpeg2000Tile *tile = s->tile + tileno;

            tile->comp = av_mallocz_array(s->ncomponents, sizeof(Jpeg2000Component));

            if (!tile->comp)

                return AVERROR(ENOMEM);

            for (compno = 0; compno < s->ncomponents; compno++){

                Jpeg2000Component *comp = tile->comp + compno;

                int ret, i, j;

                comp->coord[0][0] = comp->coord_o[0][0] = tilex * s->tile_width;

                comp->coord[0][1] = comp->coord_o[0][1] = FFMIN((tilex+1)*s->tile_width, s->width);

                comp->coord[1][0] = comp->coord_o[1][0] = tiley * s->tile_height;

                comp->coord[1][1] = comp->coord_o[1][1] = FFMIN((tiley+1)*s->tile_height, s->height);

                if (compno > 0)

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

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

                            comp->coord[i][j] = comp->coord_o[i][j] = ff_jpeg2000_ceildivpow2(comp->coord[i][j], s->chroma_shift[i]);

                if (ret = ff_jpeg2000_init_component(comp,

                                                codsty,

                                                qntsty,

                                                s->cbps[compno],

                                                compno?1<<s->chroma_shift[0]:1,

                                                compno?1<<s->chroma_shift[1]:1,

                                                s->avctx

                                               ))

                    return ret;

            }

        }

    return 0;

}


static TCGv neon_load_reg(int reg, int pass)

{

    TCGv tmp = new_tmp();

    tcg_gen_ld_i32(tmp, cpu_env, neon_reg_offset(reg, pass));

    return tmp;

}


int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)

{

    int i, count, ret = 0, j;

    int64_t read_size;

    AVStream *st;

    AVPacket pkt1, *pkt;

    int64_t old_offset = avio_tell(ic->pb);

    int orig_nb_streams = ic->nb_streams;        // new streams might appear, no options for those

    int flush_codecs = ic->probesize > 0;

    if(ic->pb)

        av_log(ic, AV_LOG_DEBUG, "File position before avformat_find_stream_info() is %"PRId64"\n", avio_tell(ic->pb));

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

        const AVCodec *codec;

        AVDictionary *thread_opt = NULL;

        st = ic->streams[i];

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

            st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {

/*            if(!st->time_base.num)

                st->time_base= */

            if(!st->codec->time_base.num)

                st->codec->time_base= st->time_base;

        }

        //only for the split stuff

        if (!st->parser && !(ic->flags & AVFMT_FLAG_NOPARSE)) {

            st->parser = av_parser_init(st->codec->codec_id);

            if(st->parser){

                if(st->need_parsing == AVSTREAM_PARSE_HEADERS){

                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;

                } else if(st->need_parsing == AVSTREAM_PARSE_FULL_RAW) {

                    st->parser->flags |= PARSER_FLAG_USE_CODEC_TS;

                }

            } else if (st->need_parsing) {

                av_log(ic, AV_LOG_VERBOSE, "parser not found for codec "

                       "%s, packets or times may be invalid.\n",

                       avcodec_get_name(st->codec->codec_id));

            }

        }

        codec = st->codec->codec ? st->codec->codec :

                                   avcodec_find_decoder(st->codec->codec_id);

        /* force thread count to 1 since the h264 decoder will not extract SPS

         *  and PPS to extradata during multi-threaded decoding */

        av_dict_set(options ? &options[i] : &thread_opt, "threads", "1", 0);

        /* Ensure that subtitle_header is properly set. */

        if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE

            && codec && !st->codec->codec)

            avcodec_open2(st->codec, codec, options ? &options[i]

                              : &thread_opt);

        //try to just open decoders, in case this is enough to get parameters

        if (!has_codec_parameters(st, NULL) && st->request_probe <= 0) {

            if (codec && !st->codec->codec)

                avcodec_open2(st->codec, codec, options ? &options[i]

                              : &thread_opt);

        }

        if (!options)

            av_dict_free(&thread_opt);

    }

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

#if FF_API_R_FRAME_RATE

        ic->streams[i]->info->last_dts = AV_NOPTS_VALUE;

#endif

        ic->streams[i]->info->fps_first_dts = AV_NOPTS_VALUE;

        ic->streams[i]->info->fps_last_dts  = AV_NOPTS_VALUE;

    }

    count = 0;

    read_size = 0;

    for(;;) {

        if (ff_check_interrupt(&ic->interrupt_callback)){

            ret= AVERROR_EXIT;

            av_log(ic, AV_LOG_DEBUG, "interrupted\n");

            break;

        }

        /* check if one codec still needs to be handled */

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

            int fps_analyze_framecount = 20;

            st = ic->streams[i];

            if (!has_codec_parameters(st, NULL))

                break;

            /* if the timebase is coarse (like the usual millisecond precision

               of mkv), we need to analyze more frames to reliably arrive at

               the correct fps */

            if (av_q2d(st->time_base) > 0.0005)

                fps_analyze_framecount *= 2;

            if (ic->fps_probe_size >= 0)

                fps_analyze_framecount = ic->fps_probe_size;

            if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)

                fps_analyze_framecount = 0;

            /* variable fps and no guess at the real fps */

            if(   tb_unreliable(st->codec) && !(st->r_frame_rate.num && st->avg_frame_rate.num)

               && st->info->duration_count < fps_analyze_framecount

               && st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

                break;

            if(st->parser && st->parser->parser->split && !st->codec->extradata)

                break;

            if (st->first_dts == AV_NOPTS_VALUE &&

                (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||

                 st->codec->codec_type == AVMEDIA_TYPE_AUDIO))

                break;

        }

        if (i == ic->nb_streams) {

            /* NOTE: if the format has no header, then we need to read

               some packets to get most of the streams, so we cannot

               stop here */

            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {

                /* if we found the info for all the codecs, we can stop */

                ret = count;

                av_log(ic, AV_LOG_DEBUG, "All info found\n");

                flush_codecs = 0;

                break;

            }

        }

        /* we did not get all the codec info, but we read too much data */

        if (read_size >= ic->probesize) {

            ret = count;

            av_log(ic, AV_LOG_DEBUG, "Probe buffer size limit of %d bytes reached\n", ic->probesize);

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

                if (!ic->streams[i]->r_frame_rate.num &&

                    ic->streams[i]->info->duration_count <= 1)

                    av_log(ic, AV_LOG_WARNING,

                           "Stream #%d: not enough frames to estimate rate; "

                           "consider increasing probesize\n", i);

            break;

        }

        /* NOTE: a new stream can be added there if no header in file

           (AVFMTCTX_NOHEADER) */

        ret = read_frame_internal(ic, &pkt1);

        if (ret == AVERROR(EAGAIN))

            continue;

        if (ret < 0) {

            /* EOF or error*/

            break;

        }

        if (ic->flags & AVFMT_FLAG_NOBUFFER) {

            pkt = &pkt1;

        } else {

            pkt = add_to_pktbuf(&ic->packet_buffer, &pkt1,

                                &ic->packet_buffer_end);

            if ((ret = av_dup_packet(pkt)) < 0)

                goto find_stream_info_err;

        }

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if (pkt->dts != AV_NOPTS_VALUE && st->codec_info_nb_frames > 1) {

            /* check for non-increasing dts */

            if (st->info->fps_last_dts != AV_NOPTS_VALUE &&

                st->info->fps_last_dts >= pkt->dts) {

                av_log(ic, AV_LOG_DEBUG, "Non-increasing DTS in stream %d: "

                       "packet %d with DTS %"PRId64", packet %d with DTS "

                       "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,

                       st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);

                st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;

            }

            /* check for a discontinuity in dts - if the difference in dts

             * is more than 1000 times the average packet duration in the sequence,

             * we treat it as a discontinuity */

            if (st->info->fps_last_dts != AV_NOPTS_VALUE &&

                st->info->fps_last_dts_idx > st->info->fps_first_dts_idx &&

                (pkt->dts - st->info->fps_last_dts) / 1000 >

                (st->info->fps_last_dts - st->info->fps_first_dts) / (st->info->fps_last_dts_idx - st->info->fps_first_dts_idx)) {

                av_log(ic, AV_LOG_WARNING, "DTS discontinuity in stream %d: "

                       "packet %d with DTS %"PRId64", packet %d with DTS "

                       "%"PRId64"\n", st->index, st->info->fps_last_dts_idx,

                       st->info->fps_last_dts, st->codec_info_nb_frames, pkt->dts);

                st->info->fps_first_dts = st->info->fps_last_dts = AV_NOPTS_VALUE;

            }

            /* update stored dts values */

            if (st->info->fps_first_dts == AV_NOPTS_VALUE) {

                st->info->fps_first_dts     = pkt->dts;

                st->info->fps_first_dts_idx = st->codec_info_nb_frames;

            }

            st->info->fps_last_dts = pkt->dts;

            st->info->fps_last_dts_idx = st->codec_info_nb_frames;

        }

        if (st->codec_info_nb_frames>1) {

            int64_t t=0;

            if (st->time_base.den > 0)

                t = av_rescale_q(st->info->codec_info_duration, st->time_base, AV_TIME_BASE_Q);

            if (st->avg_frame_rate.num > 0)

                t = FFMAX(t, av_rescale_q(st->codec_info_nb_frames, av_inv_q(st->avg_frame_rate), AV_TIME_BASE_Q));

            if (   t==0

                && st->codec_info_nb_frames>15

                && st->codec->codec_type == AVMEDIA_TYPE_VIDEO

                && (   !strcmp(ic->iformat->name, "mpeg") // this breaks some flvs thus use only for mpegps/ts for now (for ts we have a sample that needs it)

                    || !strcmp(ic->iformat->name, "mpegts"))

                && st->info->fps_first_dts != AV_NOPTS_VALUE

                && st->info->fps_last_dts  != AV_NOPTS_VALUE)

                t = FFMAX(t, av_rescale_q(st->info->fps_last_dts - st->info->fps_first_dts, st->time_base, AV_TIME_BASE_Q));

            if (t >= ic->max_analyze_duration) {

                av_log(ic, AV_LOG_VERBOSE, "max_analyze_duration %d reached at %"PRId64" microseconds\n", ic->max_analyze_duration, t);

                break;

            }

            if (pkt->duration) {

                st->info->codec_info_duration        += pkt->duration;

                st->info->codec_info_duration_fields += st->parser && st->codec->ticks_per_frame==2 ? st->parser->repeat_pict + 1 : 2;

            }

        }

#if FF_API_R_FRAME_RATE

        {

            int64_t last = st->info->last_dts;

            if(   pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && pkt->dts > last

               && pkt->dts - (uint64_t)last < INT64_MAX){

                double dts= (is_relative(pkt->dts) ?  pkt->dts - RELATIVE_TS_BASE : pkt->dts) * av_q2d(st->time_base);

                int64_t duration= pkt->dts - last;

                if (!st->info->duration_error)

                    st->info->duration_error = av_mallocz(sizeof(st->info->duration_error[0])*2);

//                 if(st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

//                     av_log(NULL, AV_LOG_ERROR, "%f\n", dts);

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

                    int framerate= get_std_framerate(i);

                    double sdts= dts*framerate/(1001*12);

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

                        int64_t ticks= llrint(sdts+j*0.5);

                        double error= sdts - ticks + j*0.5;

                        st->info->duration_error[j][0][i] += error;

                        st->info->duration_error[j][1][i] += error*error;

                    }

                }

                st->info->duration_count++;

                // ignore the first 4 values, they might have some random jitter

                if (st->info->duration_count > 3 && is_relative(pkt->dts) == is_relative(last))

                    st->info->duration_gcd = av_gcd(st->info->duration_gcd, duration);

            }

            if (pkt->dts != AV_NOPTS_VALUE)

                st->info->last_dts = pkt->dts;

        }

#endif

        if(st->parser && st->parser->parser->split && !st->codec->extradata){

            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);

            if (i > 0 && i < FF_MAX_EXTRADATA_SIZE) {

                st->codec->extradata_size= i;

                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!st->codec->extradata)

                    return AVERROR(ENOMEM);

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

                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);

            }

        }

        /* if still no information, we try to open the codec and to

           decompress the frame. We try to avoid that in most cases as

           it takes longer and uses more memory. For MPEG-4, we need to

           decompress for QuickTime.

           If CODEC_CAP_CHANNEL_CONF is set this will force decoding of at

           least one frame of codec data, this makes sure the codec initializes

           the channel configuration and does not only trust the values from the container.

        */

        try_decode_frame(st, pkt, (options && i < orig_nb_streams ) ? &options[i] : NULL);

        st->codec_info_nb_frames++;

        count++;

    }

    if (flush_codecs) {

        AVPacket empty_pkt = { 0 };

        int err = 0;

        av_init_packet(&empty_pkt);

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

            st = ic->streams[i];

            /* flush the decoders */

            if (st->info->found_decoder == 1) {

                do {

                    err = try_decode_frame(st, &empty_pkt,

                                            (options && i < orig_nb_streams) ?

                                            &options[i] : NULL);

                } while (err > 0 && !has_codec_parameters(st, NULL));

                if (err < 0) {

                    av_log(ic, AV_LOG_INFO,

                        "decoding for stream %d failed\n", st->index);

                }

            }

        }

    }

    // close codecs which were opened in try_decode_frame()

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

        st = ic->streams[i];

        avcodec_close(st->codec);

    }

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

        st = ic->streams[i];

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

            if(st->codec->codec_id == AV_CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_coded_sample){

                uint32_t tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);

                if (avpriv_find_pix_fmt(ff_raw_pix_fmt_tags, tag) == st->codec->pix_fmt)

                    st->codec->codec_tag= tag;

            }

            /* estimate average framerate if not set by demuxer */

            if (st->info->codec_info_duration_fields && !st->avg_frame_rate.num && st->info->codec_info_duration) {

                int      best_fps = 0;

                double best_error = 0.01;

                av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,

                          st->info->codec_info_duration_fields*(int64_t)st->time_base.den,

                          st->info->codec_info_duration*2*(int64_t)st->time_base.num, 60000);

                /* round guessed framerate to a "standard" framerate if it's

                 * within 1% of the original estimate*/

                for (j = 1; j < MAX_STD_TIMEBASES; j++) {

                    AVRational std_fps = { get_std_framerate(j), 12*1001 };

                    double error = fabs(av_q2d(st->avg_frame_rate) / av_q2d(std_fps) - 1);

                    if (error < best_error) {

                        best_error = error;

                        best_fps   = std_fps.num;

                    }

                }

                if (best_fps) {

                    av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den,

                              best_fps, 12*1001, INT_MAX);

                }

            }

            // the check for tb_unreliable() is not completely correct, since this is not about handling

            // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.

            // ipmovie.c produces.

            if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)

                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);

            if (st->info->duration_count>1 && !st->r_frame_rate.num

                && tb_unreliable(st->codec)) {

                int num = 0;

                double best_error= 0.01;

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

                    int k;

                    if(st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))

                        continue;

                    if(!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))

                        continue;

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

                        int n= st->info->duration_count;

                        double a= st->info->duration_error[k][0][j] / n;

                        double error= st->info->duration_error[k][1][j]/n - a*a;

                        if(error < best_error && best_error> 0.000000001){

                            best_error= error;

                            num = get_std_framerate(j);

                        }

                        if(error < 0.02)

                            av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);

                    }

                }

                // do not increase frame rate by more than 1 % in order to match a standard rate.

                if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))

                    av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);

            }

            if (!st->r_frame_rate.num){

                if(    st->codec->time_base.den * (int64_t)st->time_base.num

                    <= st->codec->time_base.num * st->codec->ticks_per_frame * (int64_t)st->time_base.den){

                    st->r_frame_rate.num = st->codec->time_base.den;

                    st->r_frame_rate.den = st->codec->time_base.num * st->codec->ticks_per_frame;

                }else{

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

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

                }

            }

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

            if(!st->codec->bits_per_coded_sample)

                st->codec->bits_per_coded_sample= av_get_bits_per_sample(st->codec->codec_id);

            // set stream disposition based on audio service type

            switch (st->codec->audio_service_type) {

            case AV_AUDIO_SERVICE_TYPE_EFFECTS:

                st->disposition = AV_DISPOSITION_CLEAN_EFFECTS;    break;

            case AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED:

                st->disposition = AV_DISPOSITION_VISUAL_IMPAIRED;  break;

            case AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED:

                st->disposition = AV_DISPOSITION_HEARING_IMPAIRED; break;

            case AV_AUDIO_SERVICE_TYPE_COMMENTARY:

                st->disposition = AV_DISPOSITION_COMMENT;          break;

            case AV_AUDIO_SERVICE_TYPE_KARAOKE:

                st->disposition = AV_DISPOSITION_KARAOKE;          break;

            }

        }

    }

    if(ic->probesize)

    estimate_timings(ic, old_offset);

    if (ret >= 0 && ic->nb_streams)

        ret = -1; /* we could not have all the codec parameters before EOF */

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

        const char *errmsg;

        st = ic->streams[i];

        if (!has_codec_parameters(st, &errmsg)) {

            char buf[256];

            avcodec_string(buf, sizeof(buf), st->codec, 0);

            av_log(ic, AV_LOG_WARNING,

                   "Could not find codec parameters for stream %d (%s): %s\n"

                   "Consider increasing the value for the 'analyzeduration' and 'probesize' options\n",

                   i, buf, errmsg);

        } else {

            ret = 0;

        }

    }

    compute_chapters_end(ic);

 find_stream_info_err:

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

        st = ic->streams[i];

        if (ic->streams[i]->codec && ic->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)

            ic->streams[i]->codec->thread_count = 0;

        if (st->info)

            av_freep(&st->info->duration_error);

        av_freep(&ic->streams[i]->info);

    }

    if(ic->pb)

        av_log(ic, AV_LOG_DEBUG, "File position after avformat_find_stream_info() is %"PRId64"\n", avio_tell(ic->pb));

    return ret;

}


static void tcg_handle_interrupt(CPUState *cpu, int mask)

{

    int old_mask;

    old_mask = cpu->interrupt_request;

    cpu->interrupt_request |= mask;

    /*

     * If called from iothread context, wake the target cpu in

     * case its halted.

     */

    if (!qemu_cpu_is_self(cpu)) {

        qemu_cpu_kick(cpu);

        return;

    }

    if (use_icount) {

        cpu->icount_decr.u16.high = 0xffff;

        if (!cpu->can_do_io

            && (mask & ~old_mask) != 0) {

            cpu_abort(cpu, "Raised interrupt while not in I/O function");

        }

    } else {

        cpu->tcg_exit_req = 1;

    }

}


void qemu_cond_broadcast(QemuCond *cond)

{

    BOOLEAN result;

    /*

     * As in pthread_cond_signal, access to cond->waiters and

     * cond->target is locked via the external mutex.

     */

    if (cond->waiters == 0) {

        return;

    }

    cond->target = 0;

    result = ReleaseSemaphore(cond->sema, cond->waiters, NULL);

    if (!result) {

        error_exit(GetLastError(), __func__);

    }

    /*

     * At this point all waiters continue. Each one takes its

     * slice of the semaphore. Now it's our turn to wait: Since

     * the external mutex is held, no thread can leave cond_wait,

     * yet. For this reason, we can be sure that no thread gets

     * a chance to eat *more* than one slice. OTOH, it means

     * that the last waiter must send us a wake-up.

     */

    WaitForSingleObject(cond->continue_event, INFINITE);

}


static uint16_t qvirtio_pci_config_readw(QVirtioDevice *d, uint64_t off)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    uint16_t value;

    value = qpci_io_readw(dev->pdev, CONFIG_BASE(dev) + off);

    if (qvirtio_is_big_endian(d)) {

        value = bswap16(value);

    }

    return value;

}


static int advanced_decode_picture_secondary_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    int index, status = 0;

    switch(v->s.pict_type)

    {

    case P_TYPE: status = decode_p_picture_secondary_header(v); break;

    case B_TYPE: status = decode_b_picture_secondary_header(v); break;

    case BI_TYPE:

    case I_TYPE: status = decode_i_picture_secondary_header(v); break;

    }

    if (status<0) return FRAME_SKIPED;

    /* AC Syntax */

    v->ac_table_level = decode012(gb);

    if (v->s.pict_type == I_TYPE || v->s.pict_type == BI_TYPE)

    {

        v->ac2_table_level = decode012(gb);

    }

    /* DC Syntax */

    index = decode012(gb);

    v->luma_dc_vlc = &ff_msmp4_dc_luma_vlc[index];

    v->chroma_dc_vlc = &ff_msmp4_dc_chroma_vlc[index];

    return 0;

}


struct omap_mmc_s *omap2_mmc_init(struct omap_target_agent_s *ta,

                BlockBackend *blk, qemu_irq irq, qemu_irq dma[],

                omap_clk fclk, omap_clk iclk)

{

    struct omap_mmc_s *s = (struct omap_mmc_s *)

            g_malloc0(sizeof(struct omap_mmc_s));

    s->irq = irq;

    s->dma = dma;

    s->clk = fclk;

    s->lines = 4;

    s->rev = 2;

    omap_mmc_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_mmc_ops, s, "omap.mmc",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    /* Instantiate the storage */

    s->card = sd_init(blk, false);

    if (s->card == NULL) {

        exit(1);

    }

    s->cdet = qemu_allocate_irq(omap_mmc_cover_cb, s, 0);

    sd_set_cb(s->card, NULL, s->cdet);

    return s;

}


static void dec_store(DisasContext *dc)
{
    TCGv t, *addr;
    unsigned int size;
    size = 1 << (dc->opcode & 3);
    LOG_DIS("s%d%s\n", size, dc->type_b ? "i" : "");
    t_sync_flags(dc);
    /* If we get a fault on a dslot, the jmpstate better be in sync.  */
    sync_jmpstate(dc);
    addr = compute_ldst_addr(dc, &t);
    /* Verify alignment if needed.  */
    if ((dc->env->pvr.regs[2] & PVR2_UNALIGNED_EXC_MASK) && size > 1) {
        gen_helper_memalign(*addr, tcg_const_tl(dc->rd),
                            tcg_const_tl(1), tcg_const_tl(size - 1));
    gen_store(dc, *addr, cpu_R[dc->rd], size);
    if (addr == &t)
        tcg_temp_free(t);


static inline void range_dec_normalize(APEContext *ctx)

{

    while (ctx->rc.range <= BOTTOM_VALUE) {

        ctx->rc.buffer <<= 8;

        if(ctx->ptr < ctx->data_end)

            ctx->rc.buffer += *ctx->ptr;

        ctx->ptr++;

        ctx->rc.low    = (ctx->rc.low << 8)    | ((ctx->rc.buffer >> 1) & 0xFF);

        ctx->rc.range  <<= 8;

    }

}


static int theora_header(AVFormatContext *s, int idx)
{
    struct ogg *ogg       = s->priv_data;
    struct ogg_stream *os = ogg->streams + idx;
    AVStream *st          = s->streams[idx];
    TheoraParams *thp     = os->private;
    int cds               = st->codec->extradata_size + os->psize + 2;
    int err;
    uint8_t *cdp;
    if (!(os->buf[os->pstart] & 0x80))
        return 0;
    if (!thp) {
        thp = av_mallocz(sizeof(*thp));
        if (!thp)
            return AVERROR(ENOMEM);
        os->private = thp;
    }
    switch (os->buf[os->pstart]) {
    case 0x80: {
        GetBitContext gb;
        AVRational timebase;
        init_get_bits(&gb, os->buf + os->pstart, os->psize * 8);
        /* 0x80"theora" */
        skip_bits_long(&gb, 7 * 8);
        thp->version = get_bits_long(&gb, 24);
        if (thp->version < 0x030100) {
            av_log(s, AV_LOG_ERROR,
                   "Too old or unsupported Theora (%x)\n", thp->version);
            return AVERROR(ENOSYS);
        }
        st->codec->width  = get_bits(&gb, 16) << 4;
        st->codec->height = get_bits(&gb, 16) << 4;
        if (thp->version >= 0x030400)
            skip_bits(&gb, 100);
        if (thp->version >= 0x030200) {
            int width  = get_bits_long(&gb, 24);
            int height = get_bits_long(&gb, 24);
            if (width  <= st->codec->width  && width  > st->codec->width  - 16 &&
                height <= st->codec->height && height > st->codec->height - 16) {
                st->codec->width  = width;
                st->codec->height = height;
            }
            skip_bits(&gb, 16);
        }
        timebase.den = get_bits_long(&gb, 32);
        timebase.num = get_bits_long(&gb, 32);
        if (!(timebase.num > 0 && timebase.den > 0)) {
            av_log(s, AV_LOG_WARNING, "Invalid time base in theora stream, assuming 25 FPS\n");
            timebase.num = 1;
            timebase.den = 25;
        }
        avpriv_set_pts_info(st, 64, timebase.num, timebase.den);
        st->sample_aspect_ratio.num = get_bits_long(&gb, 24);
        st->sample_aspect_ratio.den = get_bits_long(&gb, 24);
        if (thp->version >= 0x030200)
            skip_bits_long(&gb, 38);
        if (thp->version >= 0x304000)
            skip_bits(&gb, 2);
        thp->gpshift = get_bits(&gb, 5);
        thp->gpmask  = (1 << thp->gpshift) - 1;
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
        st->codec->codec_id   = AV_CODEC_ID_THEORA;
        st->need_parsing      = AVSTREAM_PARSE_HEADERS;
    }
    break;
    case 0x81:
        ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7, os->psize - 7);
    case 0x82:
        if (!thp->version)
            return AVERROR_INVALIDDATA;
        break;
    default:
        av_log(s, AV_LOG_ERROR, "Unknown header type %X\n", os->buf[os->pstart]);
        return AVERROR_INVALIDDATA;
    }
    if ((err = av_reallocp(&st->codec->extradata,
                           cds + FF_INPUT_BUFFER_PADDING_SIZE)) < 0) {
        st->codec->extradata_size = 0;
        return err;
    }
    cdp    = st->codec->extradata + st->codec->extradata_size;
    *cdp++ = os->psize >> 8;
    *cdp++ = os->psize & 0xff;
    memcpy(cdp, os->buf + os->pstart, os->psize);
    st->codec->extradata_size = cds;
    return 1;
}


static int buffer_needs_copy(PadContext *s, AVFrame *frame, AVBufferRef *buf)

{

    int planes[4] = { -1, -1, -1, -1}, *p = planes;

    int i, j;

    /* get all planes in this buffer */

    for (i = 0; i < FF_ARRAY_ELEMS(planes) && frame->data[i]; i++) {

        if (av_frame_get_plane_buffer(frame, i) == buf)

            *p++ = i;

    }

    /* for each plane in this buffer, check that it can be padded without

     * going over buffer bounds or other planes */

    for (i = 0; i < FF_ARRAY_ELEMS(planes) && planes[i] >= 0; i++) {

        int hsub = (planes[i] == 1 || planes[i] == 2) ? s->hsub : 0;

        int vsub = (planes[i] == 1 || planes[i] == 2) ? s->vsub : 0;

        uint8_t *start = frame->data[planes[i]];

        uint8_t *end   = start + (frame->height >> hsub) *

                                 frame->linesize[planes[i]];

        /* amount of free space needed before the start and after the end

         * of the plane */

        ptrdiff_t req_start = (s->x >> hsub) * s->line_step[planes[i]] +

                              (s->y >> vsub) * frame->linesize[planes[i]];

        ptrdiff_t req_end   = ((s->w - s->x - frame->width) >> hsub) *

                              s->line_step[planes[i]] +

                              (s->y >> vsub) * frame->linesize[planes[i]];

        if (frame->linesize[planes[i]] < (s->w >> hsub) * s->line_step[planes[i]])

            return 1;

        if (start - buf->data < req_start ||

            (buf->data + buf->size) - end < req_end)

            return 1;

#define SIGN(x) ((x) > 0 ? 1 : -1)

        for (j = 0; j < FF_ARRAY_ELEMS(planes) & planes[j] >= 0; j++) {

            int hsub1 = (planes[j] == 1 || planes[j] == 2) ? s->hsub : 0;

            uint8_t *start1 = frame->data[planes[j]];

            uint8_t *end1   = start1 + (frame->height >> hsub1) *

                                       frame->linesize[planes[j]];

            if (i == j)

                continue;

            if (SIGN(start - end1) != SIGN(start - end1 - req_start) ||

                SIGN(end - start1) != SIGN(end - start1 + req_end))

                return 1;

        }

    }

    return 0;

}


static void adb_kbd_initfn(Object *obj)

{

    ADBDevice *d = ADB_DEVICE(obj);

    d->devaddr = ADB_DEVID_KEYBOARD;

}


static void initMMX2HScaler(int dstW, int xInc, uint8_t *funnyCode)

{

	uint8_t *fragment;

	int imm8OfPShufW1;

	int imm8OfPShufW2;

	int fragmentLength;

	int xpos, i;

	// create an optimized horizontal scaling routine

	//code fragment

	asm volatile(

		"jmp 9f				\n\t"

	// Begin

		"0:				\n\t"

		"movq (%%esi), %%mm0		\n\t" //FIXME Alignment

		"movq %%mm0, %%mm1		\n\t"

		"psrlq $8, %%mm0		\n\t"

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

		"movq %%mm2, %%mm3		\n\t"

		"punpcklbw %%mm7, %%mm0	\n\t"

		"addw %%bx, %%cx		\n\t" //2*xalpha += (4*lumXInc)&0xFFFF

		"pshufw $0xFF, %%mm1, %%mm1	\n\t"

		"1:				\n\t"

		"adcl %%edx, %%esi		\n\t" //xx+= (4*lumXInc)>>16 + carry

		"pshufw $0xFF, %%mm0, %%mm0	\n\t"

		"2:				\n\t"

		"psrlw $9, %%mm3		\n\t"

		"psubw %%mm1, %%mm0		\n\t"

		"pmullw %%mm3, %%mm0		\n\t"

		"paddw %%mm6, %%mm2		\n\t" // 2*alpha += xpos&0xFFFF

		"psllw $7, %%mm1		\n\t"

		"paddw %%mm1, %%mm0		\n\t"

		"movq %%mm0, (%%edi, %%eax)	\n\t"

		"addl $8, %%eax			\n\t"

	// End

		"9:				\n\t"

//		"int $3\n\t"

		"leal 0b, %0			\n\t"

		"leal 1b, %1			\n\t"

		"leal 2b, %2			\n\t"

		"decl %1			\n\t"

		"decl %2			\n\t"

		"subl %0, %1			\n\t"

		"subl %0, %2			\n\t"

		"leal 9b, %3			\n\t"

		"subl %0, %3			\n\t"

		:"=r" (fragment), "=r" (imm8OfPShufW1), "=r" (imm8OfPShufW2),

		"=r" (fragmentLength)

	);

	xpos= 0; //lumXInc/2 - 0x8000; // difference between pixel centers

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

	{

		int xx=xpos>>16;

		if((i&3) == 0)

		{

			int a=0;

			int b=((xpos+xInc)>>16) - xx;

			int c=((xpos+xInc*2)>>16) - xx;

			int d=((xpos+xInc*3)>>16) - xx;

			memcpy(funnyCode + fragmentLength*i/4, fragment, fragmentLength);

			funnyCode[fragmentLength*i/4 + imm8OfPShufW1]=

			funnyCode[fragmentLength*i/4 + imm8OfPShufW2]=

				a | (b<<2) | (c<<4) | (d<<6);

			// if we dont need to read 8 bytes than dont :), reduces the chance of

			// crossing a cache line

			if(d<3) funnyCode[fragmentLength*i/4 + 1]= 0x6E;

			funnyCode[fragmentLength*(i+4)/4]= RET;

		}

		xpos+=xInc;

	}

}


static void *acpi_add_rom_blob(AcpiBuildState *build_state, GArray *blob,

                               const char *name)

{

    return rom_add_blob(name, blob->data, acpi_data_len(blob), -1, name,

                        acpi_build_update, build_state);

}


static void reclaim_ramblock(RAMBlock *block)

{

    if (block->flags & RAM_PREALLOC) {

        ;

    } else if (xen_enabled()) {

        xen_invalidate_map_cache_entry(block->host);

#ifndef _WIN32

    } else if (block->fd >= 0) {

        munmap(block->host, block->max_length);

        close(block->fd);

#endif

    } else {

        qemu_anon_ram_free(block->host, block->max_length);

    }

    g_free(block);

}


static int encode_picture_ls(AVCodecContext *avctx, AVPacket *pkt,

                             const AVFrame *pict, int *got_packet)

{

    const AVFrame *const p = pict;

    const int near         = avctx->prediction_method;

    PutBitContext pb, pb2;

    GetBitContext gb;

    uint8_t *buf2, *zero, *cur, *last;

    JLSState *state;

    int i, size, ret;

    int comps;

    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||

        avctx->pix_fmt == AV_PIX_FMT_GRAY16)

        comps = 1;

    else

        comps = 3;

    if ((ret = ff_alloc_packet(pkt, avctx->width * avctx->height * comps * 4 +

                               FF_MIN_BUFFER_SIZE)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    }

    buf2 = av_malloc(pkt->size);

    init_put_bits(&pb, pkt->data, pkt->size);

    init_put_bits(&pb2, buf2, pkt->size);

    /* write our own JPEG header, can't use mjpeg_picture_header */

    put_marker(&pb, SOI);

    put_marker(&pb, SOF48);

    put_bits(&pb, 16, 8 + comps * 3); // header size depends on components

    put_bits(&pb, 8, (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8);  // bpp

    put_bits(&pb, 16, avctx->height);

    put_bits(&pb, 16, avctx->width);

    put_bits(&pb, 8, comps);          // components

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

        put_bits(&pb, 8, i);     // component ID

        put_bits(&pb, 8, 0x11);  // subsampling: none

        put_bits(&pb, 8, 0);     // Tiq, used by JPEG-LS ext

    }

    put_marker(&pb, SOS);

    put_bits(&pb, 16, 6 + comps * 2);

    put_bits(&pb, 8, comps);

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

        put_bits(&pb, 8, i);   // component ID

        put_bits(&pb, 8, 0);   // mapping index: none

    }

    put_bits(&pb, 8, near);

    put_bits(&pb, 8, (comps > 1) ? 1 : 0);  // interleaving: 0 - plane, 1 - line

    put_bits(&pb, 8, 0);  // point transform: none

    state = av_mallocz(sizeof(JLSState));

    /* initialize JPEG-LS state from JPEG parameters */

    state->near = near;

    state->bpp  = (avctx->pix_fmt == AV_PIX_FMT_GRAY16) ? 16 : 8;

    ff_jpegls_reset_coding_parameters(state, 0);

    ff_jpegls_init_state(state);

    ls_store_lse(state, &pb);

    zero = av_mallocz(p->linesize[0]);

    last = zero;

    cur  = p->data[0];

    if (avctx->pix_fmt == AV_PIX_FMT_GRAY8) {

        int t = 0;

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

            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 8);

            t    = last[0];

            last = cur;

            cur += p->linesize[0];

        }

    } else if (avctx->pix_fmt == AV_PIX_FMT_GRAY16) {

        int t = 0;

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

            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);

            t    = *((uint16_t *)last);

            last = cur;

            cur += p->linesize[0];

        }

    } else if (avctx->pix_fmt == AV_PIX_FMT_RGB24) {

        int j, width;

        int Rc[3] = { 0, 0, 0 };

        width = avctx->width * 3;

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

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

                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],

                               width, 3, j, 8);

                Rc[j] = last[j];

            }

            last = cur;

            cur += p->linesize[0];

        }

    } else if (avctx->pix_fmt == AV_PIX_FMT_BGR24) {

        int j, width;

        int Rc[3] = { 0, 0, 0 };

        width = avctx->width * 3;

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

            for (j = 2; j >= 0; j--) {

                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j],

                               width, 3, j, 8);

                Rc[j] = last[j];

            }

            last = cur;

            cur += p->linesize[0];

        }

    }

    av_free(zero);

    av_free(state);

    /* the specification says that after doing 0xff escaping unused bits in

     * the last byte must be set to 0, so just append 7 "optional" zero-bits

     * to avoid special-casing. */

    put_bits(&pb2, 7, 0);

    size = put_bits_count(&pb2);

    flush_put_bits(&pb2);

    /* do escape coding */

    init_get_bits(&gb, buf2, size);

    size -= 7;

    while (get_bits_count(&gb) < size) {

        int v;

        v = get_bits(&gb, 8);

        put_bits(&pb, 8, v);

        if (v == 0xFF) {

            v = get_bits(&gb, 7);

            put_bits(&pb, 8, v);

        }

    }

    avpriv_align_put_bits(&pb);

    av_free(buf2);

    /* End of image */

    put_marker(&pb, EOI);

    flush_put_bits(&pb);

    emms_c();

    pkt->size   = put_bits_count(&pb) >> 3;

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static int bmp_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    BMPContext *s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame *p = &s->picture;

    unsigned int fsize, hsize;

    int width, height;

    unsigned int depth;

    BiCompression comp;

    unsigned int ihsize;

    int i, j, n, linesize;

    uint32_t rgb[3];

    uint32_t alpha = 0;

    uint8_t *ptr;

    int dsize;

    const uint8_t *buf0 = buf;

    GetByteContext gb;

    if(buf_size < 14){

        av_log(avctx, AV_LOG_ERROR, "buf size too small (%d)\n", buf_size);

        return -1;

    }

    if(bytestream_get_byte(&buf) != 'B' ||

       bytestream_get_byte(&buf) != 'M') {

        av_log(avctx, AV_LOG_ERROR, "bad magic number\n");

        return -1;

    }

    fsize = bytestream_get_le32(&buf);

    if(buf_size < fsize){

        av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d), trying to decode anyway\n",

               buf_size, fsize);

        fsize = buf_size;

    }

    buf += 2; /* reserved1 */

    buf += 2; /* reserved2 */

    hsize = bytestream_get_le32(&buf); /* header size */

    ihsize = bytestream_get_le32(&buf);       /* more header size */

    if(ihsize + 14 > hsize){

        av_log(avctx, AV_LOG_ERROR, "invalid header size %d\n", hsize);

        return -1;

    }

    /* sometimes file size is set to some headers size, set a real size in that case */

    if(fsize == 14 || fsize == ihsize + 14)

        fsize = buf_size - 2;

    if(fsize <= hsize){

        av_log(avctx, AV_LOG_ERROR, "declared file size is less than header size (%d < %d)\n",

               fsize, hsize);

        return -1;

    }

    switch(ihsize){

    case  40: // windib

    case  56: // windib v3

    case  64: // OS/2 v2

    case 108: // windib v4

    case 124: // windib v5

        width = bytestream_get_le32(&buf);

        height = bytestream_get_le32(&buf);

        break;

    case  12: // OS/2 v1

        width  = bytestream_get_le16(&buf);

        height = bytestream_get_le16(&buf);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "unsupported BMP file, patch welcome\n");

        return -1;

    }

    if(bytestream_get_le16(&buf) != 1){ /* planes */

        av_log(avctx, AV_LOG_ERROR, "invalid BMP header\n");

        return -1;

    }

    depth = bytestream_get_le16(&buf);

    if (ihsize >= 40)

        comp = bytestream_get_le32(&buf);

    else

        comp = BMP_RGB;

    if(comp != BMP_RGB && comp != BMP_BITFIELDS && comp != BMP_RLE4 && comp != BMP_RLE8){

        av_log(avctx, AV_LOG_ERROR, "BMP coding %d not supported\n", comp);

        return -1;

    }

    if(comp == BMP_BITFIELDS){

        buf += 20;

        rgb[0] = bytestream_get_le32(&buf);

        rgb[1] = bytestream_get_le32(&buf);

        rgb[2] = bytestream_get_le32(&buf);

        alpha = bytestream_get_le32(&buf);

    }

    avctx->width = width;

    avctx->height = height > 0? height: -height;

    avctx->pix_fmt = AV_PIX_FMT_NONE;

    switch(depth){

    case 32:

        if(comp == BMP_BITFIELDS){

            if (rgb[0] == 0xFF000000 && rgb[1] == 0x00FF0000 && rgb[2] == 0x0000FF00)

                avctx->pix_fmt = alpha ? AV_PIX_FMT_ABGR : AV_PIX_FMT_0BGR;

            else if (rgb[0] == 0x00FF0000 && rgb[1] == 0x0000FF00 && rgb[2] == 0x000000FF)

                avctx->pix_fmt = alpha ? AV_PIX_FMT_BGRA : AV_PIX_FMT_BGR0;

            else if (rgb[0] == 0x0000FF00 && rgb[1] == 0x00FF0000 && rgb[2] == 0xFF000000)

                avctx->pix_fmt = alpha ? AV_PIX_FMT_ARGB : AV_PIX_FMT_0RGB;

            else if (rgb[0] == 0x000000FF && rgb[1] == 0x0000FF00 && rgb[2] == 0x00FF0000)

                avctx->pix_fmt = alpha ? AV_PIX_FMT_RGBA : AV_PIX_FMT_RGB0;

            else {

                av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]);

                return AVERROR(EINVAL);

            }

        } else {

            avctx->pix_fmt = AV_PIX_FMT_BGRA;

        }

        break;

    case 24:

        avctx->pix_fmt = AV_PIX_FMT_BGR24;

        break;

    case 16:

        if(comp == BMP_RGB)

            avctx->pix_fmt = AV_PIX_FMT_RGB555;

        else if (comp == BMP_BITFIELDS) {

            if (rgb[0] == 0xF800 && rgb[1] == 0x07E0 && rgb[2] == 0x001F)

               avctx->pix_fmt = AV_PIX_FMT_RGB565;

            else if (rgb[0] == 0x7C00 && rgb[1] == 0x03E0 && rgb[2] == 0x001F)

               avctx->pix_fmt = AV_PIX_FMT_RGB555;

            else if (rgb[0] == 0x0F00 && rgb[1] == 0x00F0 && rgb[2] == 0x000F)

               avctx->pix_fmt = AV_PIX_FMT_RGB444;

            else {

               av_log(avctx, AV_LOG_ERROR, "Unknown bitfields %0X %0X %0X\n", rgb[0], rgb[1], rgb[2]);

               return AVERROR(EINVAL);

            }

        }

        break;

    case 8:

        if(hsize - ihsize - 14 > 0)

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

        else

            avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        break;

    case 1:

    case 4:

        if(hsize - ihsize - 14 > 0){

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

        }else{

            av_log(avctx, AV_LOG_ERROR, "Unknown palette for %d-colour BMP\n", 1<<depth);

            return -1;

        }

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "depth %d not supported\n", depth);

        return -1;

    }

    if(avctx->pix_fmt == AV_PIX_FMT_NONE){

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

        return -1;

    }

    if(p->data[0])

        avctx->release_buffer(avctx, p);

    p->reference = 0;

    if(avctx->get_buffer(avctx, p) < 0){

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

        return -1;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    p->key_frame = 1;

    buf = buf0 + hsize;

    dsize = buf_size - hsize;

    /* Line size in file multiple of 4 */

    n = ((avctx->width * depth + 31) / 8) & ~3;

    if(n * avctx->height > dsize && comp != BMP_RLE4 && comp != BMP_RLE8){

        av_log(avctx, AV_LOG_ERROR, "not enough data (%d < %d)\n",

               dsize, n * avctx->height);

        return -1;

    }

    // RLE may skip decoding some picture areas, so blank picture before decoding

    if(comp == BMP_RLE4 || comp == BMP_RLE8)

        memset(p->data[0], 0, avctx->height * p->linesize[0]);

    if(height > 0){

        ptr = p->data[0] + (avctx->height - 1) * p->linesize[0];

        linesize = -p->linesize[0];

    } else {

        ptr = p->data[0];

        linesize = p->linesize[0];

    }

    if(avctx->pix_fmt == AV_PIX_FMT_PAL8){

        int colors = 1 << depth;

        memset(p->data[1], 0, 1024);

        if(ihsize >= 36){

            int t;

            buf = buf0 + 46;

            t = bytestream_get_le32(&buf);

            if(t < 0 || t > (1 << depth)){

                av_log(avctx, AV_LOG_ERROR, "Incorrect number of colors - %X for bitdepth %d\n", t, depth);

            }else if(t){

                colors = t;

            }

        }

        buf = buf0 + 14 + ihsize; //palette location

        if((hsize-ihsize-14) < (colors << 2)){ // OS/2 bitmap, 3 bytes per palette entry

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

                ((uint32_t*)p->data[1])[i] = (0xff<<24) | bytestream_get_le24(&buf);

        }else{

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

                ((uint32_t*)p->data[1])[i] = 0xFFU << 24 | bytestream_get_le32(&buf);

        }

        buf = buf0 + hsize;

    }

    if(comp == BMP_RLE4 || comp == BMP_RLE8){

        if(height < 0){

            p->data[0] += p->linesize[0] * (avctx->height - 1);

            p->linesize[0] = -p->linesize[0];

        }

        bytestream2_init(&gb, buf, dsize);

        ff_msrle_decode(avctx, (AVPicture*)p, depth, &gb);

        if(height < 0){

            p->data[0] += p->linesize[0] * (avctx->height - 1);

            p->linesize[0] = -p->linesize[0];

        }

    }else{

        switch(depth){

        case 1:

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

                int j;

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

                    ptr[j*8+0] =  buf[j] >> 7;

                    ptr[j*8+1] = (buf[j] >> 6) & 1;

                    ptr[j*8+2] = (buf[j] >> 5) & 1;

                    ptr[j*8+3] = (buf[j] >> 4) & 1;

                    ptr[j*8+4] = (buf[j] >> 3) & 1;

                    ptr[j*8+5] = (buf[j] >> 2) & 1;

                    ptr[j*8+6] = (buf[j] >> 1) & 1;

                    ptr[j*8+7] =  buf[j]       & 1;

                }

                buf += n;

                ptr += linesize;

            }

            break;

        case 8:

        case 24:

        case 32:

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

                memcpy(ptr, buf, n);

                buf += n;

                ptr += linesize;

            }

            break;

        case 4:

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

                int j;

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

                    ptr[j*2+0] = (buf[j] >> 4) & 0xF;

                    ptr[j*2+1] = buf[j] & 0xF;

                }

                buf += n;

                ptr += linesize;

            }

            break;

        case 16:

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

                const uint16_t *src = (const uint16_t *) buf;

                uint16_t *dst = (uint16_t *) ptr;

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

                    *dst++ = av_le2ne16(*src++);

                buf += n;

                ptr += linesize;

            }

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "BMP decoder is broken\n");

            return -1;

        }

    }

    *picture = s->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


static void raven_realize(PCIDevice *d, Error **errp)

{

    RavenPCIState *s = RAVEN_PCI_DEVICE(d);

    char *filename;

    int bios_size = -1;

    d->config[0x0C] = 0x08; // cache_line_size

    d->config[0x0D] = 0x10; // latency_timer

    d->config[0x34] = 0x00; // capabilities_pointer

    memory_region_init_ram(&s->bios, OBJECT(s), "bios", BIOS_SIZE,

                           &error_abort);

    memory_region_set_readonly(&s->bios, true);

    memory_region_add_subregion(get_system_memory(), (uint32_t)(-BIOS_SIZE),

                                &s->bios);

    vmstate_register_ram_global(&s->bios);

    if (s->bios_name) {

        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, s->bios_name);

        if (filename) {

            if (s->elf_machine != EM_NONE) {

                bios_size = load_elf(filename, NULL, NULL, NULL,

                                     NULL, NULL, 1, s->elf_machine, 0);

            }

            if (bios_size < 0) {

                bios_size = get_image_size(filename);

                if (bios_size > 0 && bios_size <= BIOS_SIZE) {

                    hwaddr bios_addr;

                    bios_size = (bios_size + 0xfff) & ~0xfff;

                    bios_addr = (uint32_t)(-BIOS_SIZE);

                    bios_size = load_image_targphys(filename, bios_addr,

                                                    bios_size);

                }

            }

        }

        if (bios_size < 0 || bios_size > BIOS_SIZE) {

            hw_error("qemu: could not load bios image '%s'\n", s->bios_name);

        }

        g_free(filename);

    }

}


minimac2_write(void *opaque, target_phys_addr_t addr, uint64_t value,

               unsigned size)

{

    MilkymistMinimac2State *s = opaque;

    trace_milkymist_minimac2_memory_read(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_MDIO:

    {

        /* MDIO_DI is read only */

        int mdio_di = (s->regs[R_MDIO] & MDIO_DI);

        s->regs[R_MDIO] = value;

        if (mdio_di) {

            s->regs[R_MDIO] |= mdio_di;

        } else {

            s->regs[R_MDIO] &= ~mdio_di;

        }

        minimac2_update_mdio(s);

    } break;

    case R_TXCOUNT:

        s->regs[addr] = value;

        if (value > 0) {

            minimac2_tx(s);

        }

        break;

    case R_STATE0:

    case R_STATE1:

        s->regs[addr] = value;

        update_rx_interrupt(s);

        break;

    case R_SETUP:

    case R_COUNT0:

    case R_COUNT1:

        s->regs[addr] = value;

        break;

    default:

        error_report("milkymist_minimac2: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

}


int bdrv_in_use(BlockDriverState *bs)

{

    return bs->in_use;

}


static void vhost_log_start(MemoryListener *listener,

                            MemoryRegionSection *section)

{

    /* FIXME: implement */

}


static inline void tcg_out_addi(TCGContext *s, int reg, tcg_target_long val)

{

    if (val != 0) {

        if (val == (val & 0xfff))

            tcg_out_arithi(s, reg, reg, val, ARITH_ADD);

        else

            fprintf(stderr, "unimplemented addi %ld\n", (long)val);

    }

}


static void pl110_update_display(void *opaque)

{

    PL110State *s = (PL110State *)opaque;

    SysBusDevice *sbd;

    DisplaySurface *surface = qemu_console_surface(s->con);

    drawfn* fntable;

    drawfn fn;

    int dest_width;

    int src_width;

    int bpp_offset;

    int first;

    int last;

    if (!pl110_enabled(s)) {

        return;

    }

    sbd = SYS_BUS_DEVICE(s);

    switch (surface_bits_per_pixel(surface)) {

    case 0:

        return;

    case 8:

        fntable = pl110_draw_fn_8;

        dest_width = 1;

        break;

    case 15:

        fntable = pl110_draw_fn_15;

        dest_width = 2;

        break;

    case 16:

        fntable = pl110_draw_fn_16;

        dest_width = 2;

        break;

    case 24:

        fntable = pl110_draw_fn_24;

        dest_width = 3;

        break;

    case 32:

        fntable = pl110_draw_fn_32;

        dest_width = 4;

        break;

    default:

        fprintf(stderr, "pl110: Bad color depth\n");

        exit(1);

    }

    if (s->cr & PL110_CR_BGR)

        bpp_offset = 0;

    else

        bpp_offset = 24;

    if ((s->version != PL111) && (s->bpp == BPP_16)) {

        /* The PL110's native 16 bit mode is 5551; however

         * most boards with a PL110 implement an external

         * mux which allows bits to be reshuffled to give

         * 565 format. The mux is typically controlled by

         * an external system register.

         * This is controlled by a GPIO input pin

         * so boards can wire it up to their register.

         *

         * The PL111 straightforwardly implements both

         * 5551 and 565 under control of the bpp field

         * in the LCDControl register.

         */

        switch (s->mux_ctrl) {

        case 3: /* 565 BGR */

            bpp_offset = (BPP_16_565 - BPP_16);

            break;

        case 1: /* 5551 */

            break;

        case 0: /* 888; also if we have loaded vmstate from an old version */

        case 2: /* 565 RGB */

        default:

            /* treat as 565 but honour BGR bit */

            bpp_offset += (BPP_16_565 - BPP_16);

            break;

        }

    }

    if (s->cr & PL110_CR_BEBO)

        fn = fntable[s->bpp + 8 + bpp_offset];

    else if (s->cr & PL110_CR_BEPO)

        fn = fntable[s->bpp + 16 + bpp_offset];

    else

        fn = fntable[s->bpp + bpp_offset];

    src_width = s->cols;

    switch (s->bpp) {

    case BPP_1:

        src_width >>= 3;

        break;

    case BPP_2:

        src_width >>= 2;

        break;

    case BPP_4:

        src_width >>= 1;

        break;

    case BPP_8:

        break;

    case BPP_16:

    case BPP_16_565:

    case BPP_12:

        src_width <<= 1;

        break;

    case BPP_32:

        src_width <<= 2;

        break;

    }

    dest_width *= s->cols;

    first = 0;

    framebuffer_update_display(surface, sysbus_address_space(sbd),

                               s->upbase, s->cols, s->rows,

                               src_width, dest_width, 0,

                               s->invalidate,

                               fn, s->palette,

                               &first, &last);

    if (first >= 0) {

        dpy_gfx_update(s->con, 0, first, s->cols, last - first + 1);

    }

    s->invalidate = 0;

}


static void nvdimm_build_nvdimm_devices(GSList *device_list, Aml *root_dev)

{

    for (; device_list; device_list = device_list->next) {

        DeviceState *dev = device_list->data;

        int slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP,

                                           NULL);

        uint32_t handle = nvdimm_slot_to_handle(slot);

        Aml *nvdimm_dev;

        nvdimm_dev = aml_device("NV%02X", slot);

        /*

         * ACPI 6.0: 9.20 NVDIMM Devices:

         *

         * _ADR object that is used to supply OSPM with unique address

         * of the NVDIMM device. This is done by returning the NFIT Device

         * handle that is used to identify the associated entries in ACPI

         * table NFIT or _FIT.

         */

        aml_append(nvdimm_dev, aml_name_decl("_ADR", aml_int(handle)));

        nvdimm_build_device_dsm(nvdimm_dev);

        aml_append(root_dev, nvdimm_dev);

    }

}


int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,

    int nb_sectors, QEMUIOVector *qiov)

{

    trace_bdrv_co_readv(bs, sector_num, nb_sectors);

    return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);

}


static void test_qemu_strtosz_float(void)

{

    const char *str = "12.345M";

    char *endptr = NULL;

    int64_t res;

    res = qemu_strtosz(str, &endptr);

    g_assert_cmpint(res, ==, 12.345 * M_BYTE);

    g_assert(endptr == str + 7);

}


int i2c_start_transfer(I2CBus *bus, uint8_t address, int recv)

{

    BusChild *kid;

    I2CSlaveClass *sc;

    I2CNode *node;

    if (address == I2C_BROADCAST) {

        /*

         * This is a broadcast, the current_devs will be all the devices of the

         * bus.

         */

        bus->broadcast = true;

    }

    QTAILQ_FOREACH(kid, &bus->qbus.children, sibling) {

        DeviceState *qdev = kid->child;

        I2CSlave *candidate = I2C_SLAVE(qdev);

        if ((candidate->address == address) || (bus->broadcast)) {

            node = g_malloc(sizeof(struct I2CNode));

            node->elt = candidate;

            QLIST_INSERT_HEAD(&bus->current_devs, node, next);

            if (!bus->broadcast) {

                break;

            }

        }

    }

    if (QLIST_EMPTY(&bus->current_devs)) {

        return 1;

    }

    QLIST_FOREACH(node, &bus->current_devs, next) {

        sc = I2C_SLAVE_GET_CLASS(node->elt);

        /* If the bus is already busy, assume this is a repeated

           start condition.  */

        if (sc->event) {

            sc->event(node->elt, recv ? I2C_START_RECV : I2C_START_SEND);

        }

    }

    return 0;

}


static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque, int type)

{

    BDRVRawState *s = bs->opaque;

    if (fd_open(bs) < 0)

        return NULL;

    /*

     * Check if the underlying device requires requests to be aligned,

     * and if the request we are trying to submit is aligned or not.

     * If this is the case tell the low-level driver that it needs

     * to copy the buffer.

     */

    if (s->needs_alignment) {

        if (!bdrv_qiov_is_aligned(bs, qiov)) {

            type |= QEMU_AIO_MISALIGNED;

#ifdef CONFIG_LINUX_AIO

        } else if (s->use_aio) {

            return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,

                               nb_sectors, cb, opaque, type);

#endif

        }

    }

    return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,

                       cb, opaque, type);

}


static int v4l2_set_parameters(AVFormatContext *s1)

{

    struct video_data *s = s1->priv_data;

    struct v4l2_standard standard = { 0 };

    struct v4l2_streamparm streamparm = { 0 };

    struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;

    AVRational framerate_q = { 0 };

    int i, ret;

    streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (s->framerate &&

        (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {

        av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",

               s->framerate);

        return ret;

    }

    if (s->standard) {

        av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",

               s->standard);

        /* set tv standard */

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

            standard.index = i;

            ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);

            if (ret < 0 || !av_strcasecmp(standard.name, s->standard))

                break;

        }

        if (ret < 0) {

            av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);

            return ret;

        }

        av_log(s1, AV_LOG_DEBUG,

               "The V4L2 driver set standard: %s, id: %"PRIu64"\n",

               s->standard, (uint64_t)standard.id);

        if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {

            av_log(s1, AV_LOG_ERROR,

                   "The V4L2 driver ioctl set standard(%s) failed\n",

                   s->standard);

            return AVERROR(EIO);

        }

    }

    if (framerate_q.num && framerate_q.den) {

        av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",

               framerate_q.den, framerate_q.num);

        tpf->numerator   = framerate_q.den;

        tpf->denominator = framerate_q.num;

        if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {

            av_log(s1, AV_LOG_ERROR,

                   "ioctl set time per frame(%d/%d) failed\n",

                   framerate_q.den, framerate_q.num);

            return AVERROR(EIO);

        }

        if (framerate_q.num != tpf->denominator ||

            framerate_q.den != tpf->numerator) {

            av_log(s1, AV_LOG_INFO,

                   "The driver changed the time per frame from "

                   "%d/%d to %d/%d\n",

                   framerate_q.den, framerate_q.num,

                   tpf->numerator, tpf->denominator);

        }

    } else {

        if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {

            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",

                   strerror(errno));

            return AVERROR(errno);

        }

    }

    s1->streams[0]->avg_frame_rate.num = tpf->denominator;

    s1->streams[0]->avg_frame_rate.den = tpf->numerator;

    return 0;

}


static int vpc_create(const char *filename, QEMUOptionParameter *options)

{

    uint8_t buf[1024];

    struct vhd_footer *footer = (struct vhd_footer *) buf;

    QEMUOptionParameter *disk_type_param;

    int fd, i;

    uint16_t cyls = 0;

    uint8_t heads = 0;

    uint8_t secs_per_cyl = 0;

    int64_t total_sectors;

    int64_t total_size;

    int disk_type;

    int ret = -EIO;

    /* Read out options */

    total_size = get_option_parameter(options, BLOCK_OPT_SIZE)->value.n;

    disk_type_param = get_option_parameter(options, BLOCK_OPT_SUBFMT);

    if (disk_type_param && disk_type_param->value.s) {

        if (!strcmp(disk_type_param->value.s, "dynamic")) {

            disk_type = VHD_DYNAMIC;

        } else if (!strcmp(disk_type_param->value.s, "fixed")) {

            disk_type = VHD_FIXED;

        } else {

            return -EINVAL;

        }

    } else {

        disk_type = VHD_DYNAMIC;

    }

    /* Create the file */

    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);

    if (fd < 0) {

        return -EIO;

    }

    /*

     * Calculate matching total_size and geometry. Increase the number of

     * sectors requested until we get enough (or fail). This ensures that

     * qemu-img convert doesn't truncate images, but rather rounds up.

     */

    total_sectors = total_size / BDRV_SECTOR_SIZE;

    for (i = 0; total_sectors > (int64_t)cyls * heads * secs_per_cyl; i++) {

        if (calculate_geometry(total_sectors + i, &cyls, &heads,

                               &secs_per_cyl))

        {

            ret = -EFBIG;

            goto fail;

        }

    }

    total_sectors = (int64_t) cyls * heads * secs_per_cyl;

    /* Prepare the Hard Disk Footer */

    memset(buf, 0, 1024);

    memcpy(footer->creator, "conectix", 8);

    /* TODO Check if "qemu" creator_app is ok for VPC */

    memcpy(footer->creator_app, "qemu", 4);

    memcpy(footer->creator_os, "Wi2k", 4);

    footer->features = be32_to_cpu(0x02);

    footer->version = be32_to_cpu(0x00010000);

    if (disk_type == VHD_DYNAMIC) {

        footer->data_offset = be64_to_cpu(HEADER_SIZE);

    } else {

        footer->data_offset = be64_to_cpu(0xFFFFFFFFFFFFFFFFULL);

    }

    footer->timestamp = be32_to_cpu(time(NULL) - VHD_TIMESTAMP_BASE);

    /* Version of Virtual PC 2007 */

    footer->major = be16_to_cpu(0x0005);

    footer->minor = be16_to_cpu(0x0003);

    if (disk_type == VHD_DYNAMIC) {

        footer->orig_size = be64_to_cpu(total_sectors * 512);

        footer->size = be64_to_cpu(total_sectors * 512);

    } else {

        footer->orig_size = be64_to_cpu(total_size);

        footer->size = be64_to_cpu(total_size);

    }

    footer->cyls = be16_to_cpu(cyls);

    footer->heads = heads;

    footer->secs_per_cyl = secs_per_cyl;

    footer->type = be32_to_cpu(disk_type);

    /* TODO uuid is missing */

    footer->checksum = be32_to_cpu(vpc_checksum(buf, HEADER_SIZE));

    if (disk_type == VHD_DYNAMIC) {

        ret = create_dynamic_disk(fd, buf, total_sectors);

    } else {

        ret = create_fixed_disk(fd, buf, total_size);

    }

 fail:

    qemu_close(fd);

    return ret;

}


void kvm_s390_interrupt_internal(S390CPU *cpu, int type, uint32_t parm,

                                 uint64_t parm64, int vm)

{

    CPUState *cs = CPU(cpu);

    struct kvm_s390_interrupt kvmint;

    int r;

    if (!cs->kvm_state) {

        return;

    }

    kvmint.type = type;

    kvmint.parm = parm;

    kvmint.parm64 = parm64;

    if (vm) {

        r = kvm_vm_ioctl(cs->kvm_state, KVM_S390_INTERRUPT, &kvmint);

    } else {

        r = kvm_vcpu_ioctl(cs, KVM_S390_INTERRUPT, &kvmint);

    }

    if (r < 0) {

        fprintf(stderr, "KVM failed to inject interrupt\n");

        exit(1);

    }

}


static void *build_pci_bus_begin(PCIBus *bus, void *parent_state)

{

    AcpiBuildPciBusHotplugState *parent = parent_state;

    AcpiBuildPciBusHotplugState *child = g_malloc(sizeof *child);

    build_pci_bus_state_init(child, parent, parent->pcihp_bridge_en);

    return child;

}


static unsigned long copy_strings(int argc,char ** argv,unsigned long *page,

                unsigned long p)

{

    char *tmp, *tmp1, *pag = NULL;

    int len, offset = 0;

    if (!p) {

	return 0;       /* bullet-proofing */

    }

    while (argc-- > 0) {

	if (!(tmp1 = tmp = get_user(argv+argc))) {

	    fprintf(stderr, "VFS: argc is wrong");

	    exit(-1);

	}

	while (get_user(tmp++));

	len = tmp - tmp1;

	if (p < len) {  /* this shouldn't happen - 128kB */

		return 0;

	}

	while (len) {

	    --p; --tmp; --len;

	    if (--offset < 0) {

		offset = p % TARGET_PAGE_SIZE;

                pag = (char *) page[p/TARGET_PAGE_SIZE];

                if (!pag) {

                    pag = (char *)get_free_page();

                    page[p/TARGET_PAGE_SIZE] = (unsigned long)pag;

                    if (!pag)

                        return 0;

		}

	    }

	    if (len == 0 || offset == 0) {

	        *(pag + offset) = get_user(tmp);

	    }

	    else {

	      int bytes_to_copy = (len > offset) ? offset : len;

	      tmp -= bytes_to_copy;

	      p -= bytes_to_copy;

	      offset -= bytes_to_copy;

	      len -= bytes_to_copy;

	      memcpy_fromfs(pag + offset, tmp, bytes_to_copy + 1);

	    }

	}

    }

    return p;

}


void tb_set_jmp_target1(uintptr_t jmp_addr, uintptr_t addr)

{

    uint32_t *ptr = (uint32_t *)jmp_addr;

    uintptr_t disp = addr - jmp_addr;

    /* We can reach the entire address space for 32-bit.  For 64-bit

       the code_gen_buffer can't be larger than 2GB.  */

    assert(disp == (int32_t)disp);

    *ptr = CALL | (uint32_t)disp >> 2;

    flush_icache_range(jmp_addr, jmp_addr + 4);

}


void mmio_ide_init (target_phys_addr_t membase, target_phys_addr_t membase2,

                    MemoryRegion *address_space,

                    qemu_irq irq, int shift,

                    DriveInfo *hd0, DriveInfo *hd1)

{

    MMIOState *s = g_malloc0(sizeof(MMIOState));

    ide_init2_with_non_qdev_drives(&s->bus, hd0, hd1, irq);

    s->shift = shift;

    memory_region_init_io(&s->iomem1, &mmio_ide_ops, s,

                          "ide-mmio.1", 16 << shift);

    memory_region_init_io(&s->iomem2, &mmio_ide_cs_ops, s,

                          "ide-mmio.2", 2 << shift);

    memory_region_add_subregion(address_space, membase, &s->iomem1);

    memory_region_add_subregion(address_space, membase2, &s->iomem2);

    vmstate_register(NULL, 0, &vmstate_ide_mmio, s);

    qemu_register_reset(mmio_ide_reset, s);

}


void ff_mpc_dequantize_and_synth(MPCContext * c, int maxband, void *data, int channels)

{

    int i, j, ch;

    Band *bands = c->bands;

    int off;

    float mul;

    /* dequantize */

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

    off = 0;

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

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

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

                j = 0;

                mul = mpc_CC[bands[i].res[ch]] * mpc_SCF[bands[i].scf_idx[ch][0] & 0xFF];

                for(; j < 12; j++)

                    c->sb_samples[ch][j][i] = mul * c->Q[ch][j + off];

                mul = mpc_CC[bands[i].res[ch]] * mpc_SCF[bands[i].scf_idx[ch][1] & 0xFF];

                for(; j < 24; j++)

                    c->sb_samples[ch][j][i] = mul * c->Q[ch][j + off];

                mul = mpc_CC[bands[i].res[ch]] * mpc_SCF[bands[i].scf_idx[ch][2] & 0xFF];

                for(; j < 36; j++)

                    c->sb_samples[ch][j][i] = mul * c->Q[ch][j + off];

            }

        }

        if(bands[i].msf){

            int t1, t2;

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

                t1 = c->sb_samples[0][j][i];

                t2 = c->sb_samples[1][j][i];

                c->sb_samples[0][j][i] = t1 + t2;

                c->sb_samples[1][j][i] = t1 - t2;

            }

        }

    }

    mpc_synth(c, data, channels);

}


static int raw_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)

{

    BDRVRawState *s = bs->opaque;

    int ret;

    ret = bdrv_probe_blocksizes(bs->file->bs, bsz);

    if (ret < 0) {

        return ret;

    }

    if (!QEMU_IS_ALIGNED(s->offset, MAX(bsz->log, bsz->phys))) {

        return -ENOTSUP;

    }

    return 0;

}


BlockJobInfo *block_job_query(BlockJob *job)

{

    BlockJobInfo *info = g_new0(BlockJobInfo, 1);

    info->type      = g_strdup(BlockJobType_lookup[job->driver->job_type]);

    info->device    = g_strdup(bdrv_get_device_name(job->bs));

    info->len       = job->len;

    info->busy      = job->busy;

    info->paused    = job->paused;

    info->offset    = job->offset;

    info->speed     = job->speed;

    info->io_status = job->iostatus;

    info->ready     = job->ready;

    return info;

}


vcard_emul_options(const char *args)

{

    int reader_count = 0;

    VCardEmulOptions *opts;

    /* Allow the future use of allocating the options structure on the fly */

    memcpy(&options, &default_options, sizeof(options));

    opts = &options;

    do {

        args = strip(args); /* strip off the leading spaces */

        if (*args == ',') {

            continue;

        }

        /* soft=(slot_name,virt_name,emul_type,emul_flags,cert_1, (no eol)

         *       cert_2,cert_3...) */

        if (strncmp(args, "soft=", 5) == 0) {

            const char *name;

            size_t name_length;

            const char *vname;

            size_t vname_length;

            const char *type_params;

            size_t type_params_length;

            char type_str[100];

            VCardEmulType type;

            int count, i;

            VirtualReaderOptions *vreaderOpt = NULL;

            args = strip(args + 5);

            if (*args != '(') {

                continue;

            }

            args = strip(args+1);

            NEXT_TOKEN(name)

            NEXT_TOKEN(vname)

            NEXT_TOKEN(type_params)

            type_params_length = MIN(type_params_length, sizeof(type_str)-1);

            memcpy(type_str, type_params, type_params_length);

            type_str[type_params_length] = '\0';

            type = vcard_emul_type_from_string(type_str);

            NEXT_TOKEN(type_params)

            if (*args == 0) {

                break;

            }

            if (opts->vreader_count >= reader_count) {

                reader_count += READER_STEP;

                vreaderOpt = g_renew(VirtualReaderOptions, opts->vreader,

                                     reader_count);

            }

            opts->vreader = vreaderOpt;

            vreaderOpt = &vreaderOpt[opts->vreader_count];

            vreaderOpt->name = g_strndup(name, name_length);

            vreaderOpt->vname = g_strndup(vname, vname_length);

            vreaderOpt->card_type = type;

            vreaderOpt->type_params =

                g_strndup(type_params, type_params_length);

            count = count_tokens(args, ',', ')') + 1;

            vreaderOpt->cert_count = count;

            vreaderOpt->cert_name = g_new(char *, count);

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

                const char *cert = args;

                args = strpbrk(args, ",)");

                vreaderOpt->cert_name[i] = g_strndup(cert, args - cert);

                args = strip(args+1);

            }

            if (*args == ')') {

                args++;

            }

            opts->vreader_count++;

        /* use_hw= */

        } else if (strncmp(args, "use_hw=", 7) == 0) {

            args = strip(args+7);

            if (*args == '0' || *args == 'N' || *args == 'n' || *args == 'F') {

                opts->use_hw = PR_FALSE;

            } else {

                opts->use_hw = PR_TRUE;

            }

            args = find_blank(args);

        /* hw_type= */

        } else if (strncmp(args, "hw_type=", 8) == 0) {

            args = strip(args+8);

            opts->hw_card_type = vcard_emul_type_from_string(args);

            args = find_blank(args);

        /* hw_params= */

        } else if (strncmp(args, "hw_params=", 10) == 0) {

            const char *params;

            args = strip(args+10);

            params = args;

            args = find_blank(args);

            opts->hw_type_params = g_strndup(params, args-params);

        /* db="/data/base/path" */

        } else if (strncmp(args, "db=", 3) == 0) {

            const char *db;

            args = strip(args+3);

            if (*args != '"') {

                continue;

            }

            args++;

            db = args;

            args = strpbrk(args, "\"\n");

            opts->nss_db = g_strndup(db, args-db);

            if (*args != 0) {

                args++;

            }

        } else {

            args = find_blank(args);

        }

    } while (*args != 0);

    return opts;

}


static int pci_qdev_init(DeviceState *qdev)

{

    PCIDevice *pci_dev = (PCIDevice *)qdev;

    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);

    PCIBus *bus;

    int rc;

    bool is_default_rom;

    /* initialize cap_present for pci_is_express() and pci_config_size() */

    if (pc->is_express) {

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

    }

    bus = PCI_BUS(qdev_get_parent_bus(qdev));

    pci_dev = do_pci_register_device(pci_dev, bus,

                                     object_get_typename(OBJECT(qdev)),

                                     pci_dev->devfn);

    if (pci_dev == NULL)

        return -1;

    if (pc->init) {

        rc = pc->init(pci_dev);

        if (rc != 0) {

            do_pci_unregister_device(pci_dev);

            return rc;

        }

    }

    /* rom loading */

    is_default_rom = false;

    if (pci_dev->romfile == NULL && pc->romfile != NULL) {

        pci_dev->romfile = g_strdup(pc->romfile);

        is_default_rom = true;

    }

    pci_add_option_rom(pci_dev, is_default_rom);

    return 0;

}


static void report_unavailable_features(FeatureWord w, uint32_t mask)

{

    FeatureWordInfo *f = &feature_word_info[w];

    int i;

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

        if (1 << i & mask) {

            const char *reg = get_register_name_32(f->cpuid_reg);

            assert(reg);

            fprintf(stderr, "warning: %s doesn't support requested feature: "

                "CPUID.%02XH:%s%s%s [bit %d]\n",

                kvm_enabled() ? "host" : "TCG",

                f->cpuid_eax, reg,

                f->feat_names[i] ? "." : "",

                f->feat_names[i] ? f->feat_names[i] : "", i);

        }

    }

}


ISADevice *isa_create(ISABus *bus, const char *name)

{

    DeviceState *dev;

    if (!bus) {

        hw_error("Tried to create isa device %s with no isa bus present.",

                 name);

    }

    dev = qdev_create(BUS(bus), name);

    return ISA_DEVICE(dev);

}