static int mjpeg_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              UINT8 *buf, int buf_size)

{

    MJpegDecodeContext *s = avctx->priv_data;

    UINT8 *buf_end, *buf_ptr, *buf_start;

    int len, code, input_size, i;

    AVPicture *picture = data;

    unsigned int start_code;

    *data_size = 0;

    /* no supplementary picture */

    if (buf_size == 0)

        return 0;

    buf_ptr = buf;

    buf_end = buf + buf_size;

    while (buf_ptr < buf_end) {

        buf_start = buf_ptr;

        /* find start next marker */

        code = find_marker(&buf_ptr, buf_end, &s->header_state);

        /* copy to buffer */

        len = buf_ptr - buf_start;

        if (len + (s->buf_ptr - s->buffer) > s->buffer_size) {

            /* data too big : flush */

            s->buf_ptr = s->buffer;

            if (code > 0)

                s->start_code = code;

        } else {

            memcpy(s->buf_ptr, buf_start, len);

            s->buf_ptr += len;

            /* if we got FF 00, we copy FF to the stream to unescape FF 00 */

	    /* valid marker code is between 00 and ff - alex */

            if (code == 0 || code == 0xff) {

                s->buf_ptr--;

            } else if (code > 0) {

                /* prepare data for next start code */

                input_size = s->buf_ptr - s->buffer;

                start_code = s->start_code;

                s->buf_ptr = s->buffer;

                s->start_code = code;

                dprintf("marker=%x\n", start_code);

                switch(start_code) {

                case SOI:

                    /* nothing to do on SOI */

                    break;

                case DQT:

                    mjpeg_decode_dqt(s, s->buffer, input_size);

                    break;

                case DHT:

                    mjpeg_decode_dht(s, s->buffer, input_size);

                    break;

                case SOF0:

                    mjpeg_decode_sof0(s, s->buffer, input_size);

                    break;

                case SOS:

                    mjpeg_decode_sos(s, s->buffer, input_size);

                    if (s->start_code == EOI) {

                        int l;

                        if (s->interlaced) {

                            s->bottom_field ^= 1;

                            /* if not bottom field, do not output image yet */

                            if (s->bottom_field)

                                goto the_end;

                        }

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

                            picture->data[i] = s->current_picture[i];

                            l = s->linesize[i];

                            if (s->interlaced)

                                l >>= 1;

                            picture->linesize[i] = l;

                        }

                        *data_size = sizeof(AVPicture);

                        avctx->height = s->height;

                        if (s->interlaced)

                            avctx->height *= 2;

                        avctx->width = s->width;

                        /* XXX: not complete test ! */

                        switch((s->h_count[0] << 4) | s->v_count[0]) {

                        case 0x11:

                            avctx->pix_fmt = PIX_FMT_YUV444P;

                            break;

                        case 0x21:

                            avctx->pix_fmt = PIX_FMT_YUV422P;

                            break;

                        default:

                        case 0x22:

                            avctx->pix_fmt = PIX_FMT_YUV420P;

                            break;

                        }

                        /* dummy quality */

                        /* XXX: infer it with matrix */

                        avctx->quality = 3;

                        goto the_end;

                    }

                    break;

                }

            }

        }

    }

 the_end:

    return buf_ptr - buf;

}


static struct pxa2xx_dma_state_s *pxa2xx_dma_init(target_phys_addr_t base,

                qemu_irq irq, int channels)

{

    int i, iomemtype;

    struct pxa2xx_dma_state_s *s;

    s = (struct pxa2xx_dma_state_s *)

            qemu_mallocz(sizeof(struct pxa2xx_dma_state_s));

    s->channels = channels;

    s->chan = qemu_mallocz(sizeof(struct pxa2xx_dma_channel_s) * s->channels);

    s->base = base;

    s->irq = irq;

    s->handler = (pxa2xx_dma_handler_t) pxa2xx_dma_request;

    s->req = qemu_mallocz(sizeof(uint8_t) * PXA2XX_DMA_NUM_REQUESTS);

    memset(s->chan, 0, sizeof(struct pxa2xx_dma_channel_s) * s->channels);

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

        s->chan[i].state = DCSR_STOPINTR;

    memset(s->req, 0, sizeof(uint8_t) * PXA2XX_DMA_NUM_REQUESTS);

    iomemtype = cpu_register_io_memory(0, pxa2xx_dma_readfn,

                    pxa2xx_dma_writefn, s);

    cpu_register_physical_memory(base, 0x0000ffff, iomemtype);

    register_savevm("pxa2xx_dma", 0, 0, pxa2xx_dma_save, pxa2xx_dma_load, s);

    return s;

}


static void halfpel_interpol(SnowContext *s, uint8_t *halfpel[4][4], AVFrame *frame){

    int p,x,y;

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

        int is_chroma= !!p;

        int w= is_chroma ? s->avctx->width >>s->chroma_h_shift : s->avctx->width;

        int h= is_chroma ? s->avctx->height>>s->chroma_v_shift : s->avctx->height;

        int ls= frame->linesize[p];

        uint8_t *src= frame->data[p];

        halfpel[1][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);

        halfpel[2][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);

        halfpel[3][p] = (uint8_t*) av_malloc(ls * (h + 2 * EDGE_WIDTH)) + EDGE_WIDTH * (1 + ls);

        halfpel[0][p]= src;

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

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

                int i= y*ls + x;

                halfpel[1][p][i]= (20*(src[i] + src[i+1]) - 5*(src[i-1] + src[i+2]) + (src[i-2] + src[i+3]) + 16 )>>5;

            }

        }

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

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

                int i= y*ls + x;

                halfpel[2][p][i]= (20*(src[i] + src[i+ls]) - 5*(src[i-ls] + src[i+2*ls]) + (src[i-2*ls] + src[i+3*ls]) + 16 )>>5;

            }

        }

        src= halfpel[1][p];

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

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

                int i= y*ls + x;

                halfpel[3][p][i]= (20*(src[i] + src[i+ls]) - 5*(src[i-ls] + src[i+2*ls]) + (src[i-2*ls] + src[i+3*ls]) + 16 )>>5;

            }

        }

//FIXME border!

    }

}


static int decompress_p(AVCodecContext *avctx,

                        uint32_t *dst, int linesize,

                        uint32_t *prev, int plinesize)

{

    SCPRContext *s = avctx->priv_data;

    GetByteContext *gb = &s->gb;

    int ret, temp, min, max, x, y, cx = 0, cx1 = 0;

    int backstep = linesize - avctx->width;

    const int cxshift = s->cxshift;

    if (bytestream2_get_byte(gb) == 0)

        return 0;

    bytestream2_skip(gb, 1);

    init_rangecoder(&s->rc, gb);

    ret  = decode_value(s, s->range_model, 256, 1, &min);

    ret |= decode_value(s, s->range_model, 256, 1, &temp);

    min += temp << 8;

    ret |= decode_value(s, s->range_model, 256, 1, &max);

    ret |= decode_value(s, s->range_model, 256, 1, &temp);

    if (ret < 0)

        return ret;

    max += temp << 8;

    memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount);

    while (min <= max) {

        int fill, count;

        ret  = decode_value(s, s->fill_model,  5,   10, &fill);

        ret |= decode_value(s, s->count_model, 256, 20, &count);

        if (ret < 0)

            return ret;

        while (min < s->nbcount && count-- > 0) {

            s->blocks[min++] = fill;

        }

    }

    for (y = 0; y < s->nby; y++) {

        for (x = 0; x < s->nbx; x++) {

            int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16;

            if (s->blocks[y * s->nbx + x] == 0)

                continue;

            if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) {

                ret  = decode_value(s, s->sxy_model[0], 16, 100, &sx1);

                ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1);

                ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2);

                ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2);

                if (ret < 0)

                    return ret;

                sx2++;

                sy2++;

            }

            if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) {

                int i, j, by = y * 16, bx = x * 16;

                int mvx, mvy;

                ret  = decode_value(s, s->mv_model[0], 512, 100, &mvx);

                ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy);

                if (ret < 0)

                    return ret;

                mvx -= 256;

                mvy -= 256;

                if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0 ||

                    by + mvy + sy1 >= avctx->height || bx + mvx + sx1 >= avctx->width)

                    return AVERROR_INVALIDDATA;

                for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height && (by + mvy + sy1 + i) < avctx->height; i++) {

                    for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width && (bx + mvx + sx1 + j) < avctx->width; j++) {

                        dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j];

                    }

                }

            } else {

                int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1;

                unsigned clr, ptype = 0;

                for (; by < y * 16 + sy2 && by < avctx->height;) {

                    ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);

                    if (ptype == 0) {

                        ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);

                        if (ret < 0)

                            return ret;

                        cx1 = (cx << 6) & 0xFC0;

                        cx = r >> cxshift;

                        ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);

                        if (ret < 0)

                            return ret;

                        cx1 = (cx << 6) & 0xFC0;

                        cx = g >> cxshift;

                        ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);

                        if (ret < 0)

                            return ret;

                        clr = (b << 16) + (g << 8) + r;

                    }

                    if (ptype > 5)

                        return AVERROR_INVALIDDATA;

                    ret = decode_value(s, s->run_model[ptype], 256, 400, &run);

                    if (ret < 0)

                        return ret;

                    switch (ptype) {

                    case 0:

                        while (run-- > 0) {

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 1:

                        while (run-- > 0) {

                            if (bx == 0) {

                                if (by < 1)

                                    return AVERROR_INVALIDDATA;

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = dst[by * linesize + bx - 1 - z];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 2:

                        while (run-- > 0) {

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = dst[(by - 1) * linesize + bx];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 3:

                        while (run-- > 0) {

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = prev[by * plinesize + bx];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 4:

                        while (run-- > 0) {

                            uint8_t *odst = (uint8_t *)dst;

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            if (bx == 0) {

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            r = odst[((by - 1) * linesize + bx) * 4] +

                                odst[(by * linesize + bx - 1 - z) * 4] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4];

                            g = odst[((by - 1) * linesize + bx) * 4 + 1] +

                                odst[(by * linesize + bx - 1 - z) * 4 + 1] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1];

                            b = odst[((by - 1) * linesize + bx) * 4 + 2] +

                                odst[(by * linesize + bx - 1 - z) * 4 + 2] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2];

                            clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 5:

                        while (run-- > 0) {

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            if (bx == 0) {

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            clr = dst[(by - 1) * linesize + bx - 1 - z];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    }

                    if (avctx->bits_per_coded_sample == 16) {

                        cx1 = (clr & 0x3F00) >> 2;

                        cx = (clr & 0xFFFFFF) >> 16;

                    } else {

                        cx1 = (clr & 0xFC00) >> 4;

                        cx = (clr & 0xFFFFFF) >> 18;

                    }

                }

            }

        }

    }

    return 0;

}


static ResampleContext *resample_init(ResampleContext *c, int out_rate, int in_rate, int filter_size, int phase_shift, int linear,

                                    double cutoff0, enum AVSampleFormat format, enum SwrFilterType filter_type, int kaiser_beta,

                                    double precision, int cheby){

    double cutoff = cutoff0? cutoff0 : 0.97;

    double factor= FFMIN(out_rate * cutoff / in_rate, 1.0);

    int phase_count= 1<<phase_shift;

    if (!c || c->phase_shift != phase_shift || c->linear!=linear || c->factor != factor

           || c->filter_length != FFMAX((int)ceil(filter_size/factor), 1) || c->format != format

           || c->filter_type != filter_type || c->kaiser_beta != kaiser_beta) {

        c = av_mallocz(sizeof(*c));

        if (!c)

            return NULL;

        c->format= format;

        c->felem_size= av_get_bytes_per_sample(c->format);

        switch(c->format){

        case AV_SAMPLE_FMT_S16P:

            c->filter_shift = 15;

            break;

        case AV_SAMPLE_FMT_S32P:

            c->filter_shift = 30;

            break;

        case AV_SAMPLE_FMT_FLTP:

        case AV_SAMPLE_FMT_DBLP:

            c->filter_shift = 0;

            break;

        default:

            av_log(NULL, AV_LOG_ERROR, "Unsupported sample format\n");

            av_assert0(0);

        }

        c->phase_shift   = phase_shift;

        c->phase_mask    = phase_count - 1;

        c->linear        = linear;

        c->factor        = factor;

        c->filter_length = FFMAX((int)ceil(filter_size/factor), 1);

        c->filter_alloc  = FFALIGN(c->filter_length, 8);

        c->filter_bank   = av_mallocz(c->filter_alloc*(phase_count+1)*c->felem_size);

        c->filter_type   = filter_type;

        c->kaiser_beta   = kaiser_beta;

        if (!c->filter_bank)

            goto error;

        if (build_filter(c, (void*)c->filter_bank, factor, c->filter_length, c->filter_alloc, phase_count, 1<<c->filter_shift, filter_type, kaiser_beta))

            goto error;

        memcpy(c->filter_bank + (c->filter_alloc*phase_count+1)*c->felem_size, c->filter_bank, (c->filter_alloc-1)*c->felem_size);

        memcpy(c->filter_bank + (c->filter_alloc*phase_count  )*c->felem_size, c->filter_bank + (c->filter_alloc - 1)*c->felem_size, c->felem_size);

    }

    c->compensation_distance= 0;

    if(!av_reduce(&c->src_incr, &c->dst_incr, out_rate, in_rate * (int64_t)phase_count, INT32_MAX/2))

        goto error;

    c->ideal_dst_incr= c->dst_incr;

    c->index= -phase_count*((c->filter_length-1)/2);

    c->frac= 0;

    return c;

error:

    av_free(c->filter_bank);

    av_free(c);

    return NULL;

}


int ff_h264_decode_ref_pic_marking(H264Context *h, GetBitContext *gb){

    MpegEncContext * const s = &h->s;

    int i;

    h->mmco_index= 0;

    if(h->nal_unit_type == NAL_IDR_SLICE){ //FIXME fields

        s->broken_link= get_bits1(gb) -1;

        if(get_bits1(gb)){

            h->mmco[0].opcode= MMCO_LONG;

            h->mmco[0].long_arg= 0;

            h->mmco_index= 1;

        }

    }else{

        if(get_bits1(gb)){ // adaptive_ref_pic_marking_mode_flag

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

                MMCOOpcode opcode= get_ue_golomb_31(gb);

                h->mmco[i].opcode= opcode;

                if(opcode==MMCO_SHORT2UNUSED || opcode==MMCO_SHORT2LONG){

                    h->mmco[i].short_pic_num= (h->curr_pic_num - get_ue_golomb(gb) - 1) & (h->max_pic_num - 1);

/*                    if(h->mmco[i].short_pic_num >= h->short_ref_count || h->short_ref[ h->mmco[i].short_pic_num ] == NULL){

                        av_log(s->avctx, AV_LOG_ERROR, "illegal short ref in memory management control operation %d\n", mmco);

                        return -1;

                    }*/

                }

                if(opcode==MMCO_SHORT2LONG || opcode==MMCO_LONG2UNUSED || opcode==MMCO_LONG || opcode==MMCO_SET_MAX_LONG){

                    unsigned int long_arg= get_ue_golomb_31(gb);

                    if(long_arg >= 32 || (long_arg >= 16 && !(opcode == MMCO_LONG2UNUSED && FIELD_PICTURE))){

                        av_log(h->s.avctx, AV_LOG_ERROR, "illegal long ref in memory management control operation %d\n", opcode);

                        return -1;

                    }

                    h->mmco[i].long_arg= long_arg;

                }

                if(opcode > (unsigned)MMCO_LONG){

                    av_log(h->s.avctx, AV_LOG_ERROR, "illegal memory management control operation %d\n", opcode);

                    return -1;

                }

                if(opcode == MMCO_END)

                    break;

            }

            h->mmco_index= i;

        }else{

            ff_generate_sliding_window_mmcos(h);

        }

    }

    return 0;

}


static void listener_add_address_space(MemoryListener *listener,

                                       AddressSpace *as)

{

    FlatRange *fr;

    if (listener->address_space_filter

        && listener->address_space_filter != as->root) {

        return;

    }

    if (global_dirty_log) {

        listener->log_global_start(listener);

    }

    FOR_EACH_FLAT_RANGE(fr, &as->current_map) {

        MemoryRegionSection section = {

            .mr = fr->mr,

            .address_space = as->root,

            .offset_within_region = fr->offset_in_region,

            .size = int128_get64(fr->addr.size),

            .offset_within_address_space = int128_get64(fr->addr.start),

            .readonly = fr->readonly,

        };

        listener->region_add(listener, &section);

    }

}


BlockDriverAIOCB *laio_submit(BlockDriverState *bs, void *aio_ctx, int fd,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque, int type)

{

    struct qemu_laio_state *s = aio_ctx;

    struct qemu_laiocb *laiocb;

    struct iocb *iocbs;

    off_t offset = sector_num * 512;

    laiocb = qemu_aio_get(&laio_pool, bs, cb, opaque);

    if (!laiocb)

        return NULL;

    laiocb->nbytes = nb_sectors * 512;

    laiocb->ctx = s;

    laiocb->ret = -EINPROGRESS;

    iocbs = &laiocb->iocb;

    switch (type) {

    case QEMU_AIO_WRITE:

        io_prep_pwritev(iocbs, fd, qiov->iov, qiov->niov, offset);

	break;

    case QEMU_AIO_READ:

        io_prep_preadv(iocbs, fd, qiov->iov, qiov->niov, offset);

	break;

    /* Currently Linux kernel does not support other operations */

    default:

        fprintf(stderr, "%s: invalid AIO request type 0x%x.\n",

                        __func__, type);

        goto out_free_aiocb;

    }

    io_set_eventfd(&laiocb->iocb, s->efd);

    s->count++;

    if (io_submit(s->ctx, 1, &iocbs) < 0)

        goto out_dec_count;

    return &laiocb->common;

out_free_aiocb:

    qemu_aio_release(laiocb);

out_dec_count:

    s->count--;

    return NULL;

}


static int dx2_decode_slice_5x5(GetBitContext *gb, AVFrame *frame,

                                int line, int left, uint8_t lru[3][8],

                                int is_565)

{

    int x, y;

    int r, g, b;

    int width    = frame->width;

    int stride   = frame->linesize[0];

    uint8_t *dst = frame->data[0] + stride * line;

    for (y = 0; y < left && get_bits_left(gb) > 16; y++) {

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

            b = decode_sym_565(gb, lru[0], 5);

            g = decode_sym_565(gb, lru[1], is_565 ? 6 : 5);

            r = decode_sym_565(gb, lru[2], 5);

            dst[x * 3 + 0] = (r << 3) | (r >> 2);

            dst[x * 3 + 1] = is_565 ? (g << 2) | (g >> 4) : (g << 3) | (g >> 2);

            dst[x * 3 + 2] = (b << 3) | (b >> 2);

        }

        dst += stride;

    }

    return y;

}


static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)

{

    int i, re, im, n, n2, n4;

    int16_t *rot = mdct->rot_tmp;

    IComplex *x  = mdct->cplx_tmp;

    n  = 1 << mdct->nbits;

    n2 = n >> 1;

    n4 = n >> 2;

    /* shift to simplify computations */

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

        rot[i] = -in[i + 3*n4];

    memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in));

    /* pre rotation */

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

        re =  ((int)rot[   2*i] - (int)rot[ n-1-2*i]) >> 1;

        im = -((int)rot[n2+2*i] - (int)rot[n2-1-2*i]) >> 1;

        CMUL(x[i].re, x[i].im, re, im, -mdct->xcos1[i], mdct->xsin1[i], 15);

    }

    fft(mdct, x, mdct->nbits - 2);

    /* post rotation */

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

        re = x[i].re;

        im = x[i].im;

        CMUL(out[n2-1-2*i], out[2*i], re, im, mdct->xsin1[i], mdct->xcos1[i], 0);

    }

}


static int spapr_post_load(void *opaque, int version_id)
{
    sPAPRMachineState *spapr = (sPAPRMachineState *)opaque;
    int err = 0;
    if (!object_dynamic_cast(OBJECT(spapr->ics), TYPE_ICS_KVM)) {
        CPUState *cs;
        CPU_FOREACH(cs) {
            PowerPCCPU *cpu = POWERPC_CPU(cs);
            icp_resend(ICP(cpu->intc));
    /* In earlier versions, there was no separate qdev for the PAPR
     * RTC, so the RTC offset was stored directly in sPAPREnvironment.
     * So when migrating from those versions, poke the incoming offset
     * value into the RTC device */
    if (version_id < 3) {
        err = spapr_rtc_import_offset(&spapr->rtc, spapr->rtc_offset);
    if (kvm_enabled() && spapr->patb_entry) {
        PowerPCCPU *cpu = POWERPC_CPU(first_cpu);
        bool radix = !!(spapr->patb_entry & PATBE1_GR);
        bool gtse = !!(cpu->env.spr[SPR_LPCR] & LPCR_GTSE);
        err = kvmppc_configure_v3_mmu(cpu, radix, gtse, spapr->patb_entry);
            error_report("Process table config unsupported by the host");
            return -EINVAL;


static int encode_dvd_subtitles(AVCodecContext *avctx,

                                uint8_t *outbuf, int outbuf_size,

                                const AVSubtitle *h)

{

    DVDSubtitleContext *dvdc = avctx->priv_data;

    uint8_t *q, *qq;

    int offset1, offset2;

    int i, rects = h->num_rects, ret;

    unsigned global_palette_hits[33] = { 0 };

    int cmap[256];

    int out_palette[4];

    int out_alpha[4];

    AVSubtitleRect vrect;

    uint8_t *vrect_data = NULL;

    int x2, y2;

    if (rects == 0 || h->rects == NULL)

    vrect = *h->rects[0];

    if (rects > 1) {

        /* DVD subtitles can have only one rectangle: build a virtual

           rectangle containing all actual rectangles.

           The data of the rectangles will be copied later, when the palette

           is decided, because the rectangles may have different palettes. */

        int xmin = h->rects[0]->x, xmax = xmin + h->rects[0]->w;

        int ymin = h->rects[0]->y, ymax = ymin + h->rects[0]->h;

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

            xmin = FFMIN(xmin, h->rects[i]->x);

            ymin = FFMIN(ymin, h->rects[i]->y);

            xmax = FFMAX(xmax, h->rects[i]->x + h->rects[i]->w);

            ymax = FFMAX(ymax, h->rects[i]->y + h->rects[i]->h);

        vrect.x = xmin;

        vrect.y = ymin;

        vrect.w = xmax - xmin;

        vrect.h = ymax - ymin;

        if ((ret = av_image_check_size(vrect.w, vrect.h, 0, avctx)) < 0)

            return ret;

        /* Count pixels outside the virtual rectangle as transparent */

        global_palette_hits[0] = vrect.w * vrect.h;

            global_palette_hits[0] -= h->rects[i]->w * h->rects[i]->h;

        count_colors(avctx, global_palette_hits, h->rects[i]);

    select_palette(avctx, out_palette, out_alpha, global_palette_hits);

    if (rects > 1) {

        if (!(vrect_data = av_calloc(vrect.w, vrect.h)))

            return AVERROR(ENOMEM);

        vrect.pict.data    [0] = vrect_data;

        vrect.pict.linesize[0] = vrect.w;

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

            build_color_map(avctx, cmap, (uint32_t *)h->rects[i]->pict.data[1],

                            out_palette, out_alpha);

            copy_rectangle(&vrect, h->rects[i], cmap);

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

            cmap[i] = i;

    } else {

        build_color_map(avctx, cmap, (uint32_t *)h->rects[0]->pict.data[1],

                        out_palette, out_alpha);

    av_log(avctx, AV_LOG_DEBUG, "Selected palette:");

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

        av_log(avctx, AV_LOG_DEBUG, " 0x%06x@@%02x (0x%x,0x%x)",

               dvdc->global_palette[out_palette[i]], out_alpha[i],

               out_palette[i], out_alpha[i] >> 4);

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

    // encode data block

    q = outbuf + 4;

    offset1 = q - outbuf;

    // worst case memory requirement: 1 nibble per pixel..

    if ((q - outbuf) + vrect.w * vrect.h / 2 + 17 + 21 > outbuf_size) {

        av_log(NULL, AV_LOG_ERROR, "dvd_subtitle too big\n");

        ret = AVERROR_BUFFER_TOO_SMALL;

        goto fail;

    dvd_encode_rle(&q, vrect.pict.data[0], vrect.w * 2,

                   vrect.w, (vrect.h + 1) >> 1, cmap);

    offset2 = q - outbuf;

    dvd_encode_rle(&q, vrect.pict.data[0] + vrect.w, vrect.w * 2,

                   vrect.w, vrect.h >> 1, cmap);

    // set data packet size

    qq = outbuf + 2;

    bytestream_put_be16(&qq, q - outbuf);

    // send start display command

    bytestream_put_be16(&q, (h->start_display_time*90) >> 10);

    bytestream_put_be16(&q, (q - outbuf) /*- 2 */ + 8 + 12 + 2);

    *q++ = 0x03; // palette - 4 nibbles

    *q++ = (out_palette[3] << 4) | out_palette[2];

    *q++ = (out_palette[1] << 4) | out_palette[0];

    *q++ = 0x04; // alpha - 4 nibbles

    *q++ = (out_alpha[3] & 0xF0) | (out_alpha[2] >> 4);

    *q++ = (out_alpha[1] & 0xF0) | (out_alpha[0] >> 4);

    // 12 bytes per rect

    x2 = vrect.x + vrect.w - 1;

    y2 = vrect.y + vrect.h - 1;

    *q++ = 0x05;

    // x1 x2 -> 6 nibbles

    *q++ = vrect.x >> 4;

    *q++ = (vrect.x << 4) | ((x2 >> 8) & 0xf);

    *q++ = x2;

    // y1 y2 -> 6 nibbles

    *q++ = vrect.y >> 4;

    *q++ = (vrect.y << 4) | ((y2 >> 8) & 0xf);

    *q++ = y2;

    *q++ = 0x06;

    // offset1, offset2

    bytestream_put_be16(&q, offset1);

    bytestream_put_be16(&q, offset2);

    *q++ = 0x01; // start command

    *q++ = 0xff; // terminating command

    // send stop display command last

    bytestream_put_be16(&q, (h->end_display_time*90) >> 10);

    bytestream_put_be16(&q, (q - outbuf) - 2 /*+ 4*/);

    *q++ = 0x02; // set end

    *q++ = 0xff; // terminating command

    qq = outbuf;

    bytestream_put_be16(&qq, q - outbuf);

    av_log(NULL, AV_LOG_DEBUG, "subtitle_packet size=%td\n", q - outbuf);

    ret = q - outbuf;

fail:

    av_free(vrect_data);

    return ret;


static int coroutine_enter_func(void *arg)

{

    Coroutine *co = arg;

    qemu_coroutine_enter(co, NULL);

    return 0;

}


int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,

                           const uint8_t *name, uint8_t *dst, int dst_size)

{

    int namelen = strlen(name);

    int len;

    while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {

        len = ff_amf_tag_size(data, data_end);

        if (len < 0)

            len = data_end - data;

        data += len;

    }

    if (data_end - data < 3)

        return -1;

    data++;

    for (;;) {

        int size = bytestream_get_be16(&data);

        if (!size)

            break;

        if (data + size >= data_end || data + size < data)

            return -1;

        data += size;

        if (size == namelen && !memcmp(data-size, name, namelen)) {

            switch (*data++) {

            case AMF_DATA_TYPE_NUMBER:

                snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));

                break;

            case AMF_DATA_TYPE_BOOL:

                snprintf(dst, dst_size, "%s", *data ? "true" : "false");

                break;

            case AMF_DATA_TYPE_STRING:

                len = bytestream_get_be16(&data);

                av_strlcpy(dst, data, FFMIN(len+1, dst_size));

                break;

            default:

                return -1;

            }

            return 0;

        }

        len = ff_amf_tag_size(data, data_end);

        if (len < 0 || data + len >= data_end || data + len < data)

            return -1;

        data += len;

    }

    return -1;

}


static int decode_fctl_chunk(AVCodecContext *avctx, PNGDecContext *s,

                             uint32_t length)

{

    uint32_t sequence_number;

    int cur_w, cur_h, x_offset, y_offset, dispose_op, blend_op;

    if (length != 26)

        return AVERROR_INVALIDDATA;

    if (!(s->state & PNG_IHDR)) {

        av_log(avctx, AV_LOG_ERROR, "fctl before IHDR\n");

        return AVERROR_INVALIDDATA;

    }

    s->last_w = s->cur_w;

    s->last_h = s->cur_h;

    s->last_x_offset = s->x_offset;

    s->last_y_offset = s->y_offset;

    s->last_dispose_op = s->dispose_op;

    sequence_number = bytestream2_get_be32(&s->gb);

    cur_w           = bytestream2_get_be32(&s->gb);

    cur_h           = bytestream2_get_be32(&s->gb);

    x_offset        = bytestream2_get_be32(&s->gb);

    y_offset        = bytestream2_get_be32(&s->gb);

    bytestream2_skip(&s->gb, 4); /* delay_num (2), delay_den (2) */

    dispose_op      = bytestream2_get_byte(&s->gb);

    blend_op        = bytestream2_get_byte(&s->gb);

    bytestream2_skip(&s->gb, 4); /* crc */

    if (sequence_number == 0 &&

        (cur_w != s->width ||

         cur_h != s->height ||

         x_offset != 0 ||

         y_offset != 0) ||

        cur_w <= 0 || cur_h <= 0 ||

        x_offset < 0 || y_offset < 0 ||

        cur_w > s->width - x_offset|| cur_h > s->height - y_offset)

            return AVERROR_INVALIDDATA;

    if (blend_op != APNG_BLEND_OP_OVER && blend_op != APNG_BLEND_OP_SOURCE) {

        av_log(avctx, AV_LOG_ERROR, "Invalid blend_op %d\n", blend_op);

        return AVERROR_INVALIDDATA;

    }

    if ((sequence_number == 0 || !s->previous_picture.f->data[0]) &&

        dispose_op == APNG_DISPOSE_OP_PREVIOUS) {

        // No previous frame to revert to for the first frame

        // Spec says to just treat it as a APNG_DISPOSE_OP_BACKGROUND

        dispose_op = APNG_DISPOSE_OP_BACKGROUND;

    }

    if (blend_op == APNG_BLEND_OP_OVER && !s->has_trns && (

            avctx->pix_fmt == AV_PIX_FMT_RGB24 ||

            avctx->pix_fmt == AV_PIX_FMT_RGB48BE ||

            avctx->pix_fmt == AV_PIX_FMT_PAL8 ||

            avctx->pix_fmt == AV_PIX_FMT_GRAY8 ||

            avctx->pix_fmt == AV_PIX_FMT_GRAY16BE ||

            avctx->pix_fmt == AV_PIX_FMT_MONOBLACK

        )) {

        // APNG_BLEND_OP_OVER is the same as APNG_BLEND_OP_SOURCE when there is no alpha channel

        blend_op = APNG_BLEND_OP_SOURCE;

    }

    s->cur_w      = cur_w;

    s->cur_h      = cur_h;

    s->x_offset   = x_offset;

    s->y_offset   = y_offset;

    s->dispose_op = dispose_op;

    s->blend_op   = blend_op;

    return 0;

}


static void detach(sPAPRDRConnector *drc, DeviceState *d,

                   spapr_drc_detach_cb *detach_cb,

                   void *detach_cb_opaque, Error **errp)

{

    trace_spapr_drc_detach(get_index(drc));

    drc->detach_cb = detach_cb;

    drc->detach_cb_opaque = detach_cb_opaque;

    /* if we've signalled device presence to the guest, or if the guest

     * has gone ahead and configured the device (via manually-executed

     * device add via drmgr in guest, namely), we need to wait

     * for the guest to quiesce the device before completing detach.

     * Otherwise, we can assume the guest hasn't seen it and complete the

     * detach immediately. Note that there is a small race window

     * just before, or during, configuration, which is this context

     * refers mainly to fetching the device tree via RTAS.

     * During this window the device access will be arbitrated by

     * associated DRC, which will simply fail the RTAS calls as invalid.

     * This is recoverable within guest and current implementations of

     * drmgr should be able to cope.

     */

    if (!drc->signalled && !drc->configured) {

        /* if the guest hasn't seen the device we can't rely on it to

         * set it back to an isolated state via RTAS, so do it here manually

         */

        drc->isolation_state = SPAPR_DR_ISOLATION_STATE_ISOLATED;

    }

    if (drc->isolation_state != SPAPR_DR_ISOLATION_STATE_ISOLATED) {

        trace_spapr_drc_awaiting_isolated(get_index(drc));

        drc->awaiting_release = true;

        return;

    }

    if (drc->type != SPAPR_DR_CONNECTOR_TYPE_PCI &&

        drc->allocation_state != SPAPR_DR_ALLOCATION_STATE_UNUSABLE) {

        trace_spapr_drc_awaiting_unusable(get_index(drc));

        drc->awaiting_release = true;

        return;

    }

    if (drc->awaiting_allocation) {

        drc->awaiting_release = true;

        trace_spapr_drc_awaiting_allocation(get_index(drc));

        return;

    }

    drc->indicator_state = SPAPR_DR_INDICATOR_STATE_INACTIVE;

    if (drc->detach_cb) {

        drc->detach_cb(drc->dev, drc->detach_cb_opaque);

    }

    drc->awaiting_release = false;

    g_free(drc->fdt);

    drc->fdt = NULL;

    drc->fdt_start_offset = 0;

    object_property_del(OBJECT(drc), "device", NULL);

    drc->dev = NULL;

    drc->detach_cb = NULL;

    drc->detach_cb_opaque = NULL;

}


static int fraps2_decode_plane(FrapsContext *s, uint8_t *dst, int stride, int w,

                               int h, const uint8_t *src, int size, int Uoff,

                               const int step)

{

    int i, j;

    GetBitContext gb;

    VLC vlc;

    Node nodes[512];

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

        nodes[i].count = bytestream_get_le32(&src);

    size -= 1024;

    if (ff_huff_build_tree(s->avctx, &vlc, 256, nodes, huff_cmp,

                           FF_HUFFMAN_FLAG_ZERO_COUNT) < 0)

        return -1;

    /* we have built Huffman table and are ready to decode plane */

    /* convert bits so they may be used by standard bitreader */

    s->dsp.bswap_buf((uint32_t *)s->tmpbuf, (const uint32_t *)src, size >> 2);

    init_get_bits(&gb, s->tmpbuf, size * 8);

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

        for(i = 0; i < w*step; i += step){

            dst[i] = get_vlc2(&gb, vlc.table, 9, 3);

            /* lines are stored as deltas between previous lines

             * and we need to add 0x80 to the first lines of chroma planes

             */

            if(j) dst[i] += dst[i - stride];

            else if(Uoff) dst[i] += 0x80;

        }

        dst += stride;

        if(get_bits_left(&gb) < 0){

            free_vlc(&vlc);

            return -1;

        }

    }

    free_vlc(&vlc);

    return 0;

}


yuv2gray16_X_c_template(SwsContext *c, const int16_t *lumFilter,

                        const int32_t **lumSrc, int lumFilterSize,

                        const int16_t *chrFilter, const int32_t **chrUSrc,

                        const int32_t **chrVSrc, int chrFilterSize,

                        const int32_t **alpSrc, uint16_t *dest, int dstW,

                        int y, enum PixelFormat target)

{

    int i;

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

        int j;

        int Y1 = 1 << 14;

        int Y2 = 1 << 14;

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

            Y1 += lumSrc[j][i * 2]     * lumFilter[j];

            Y2 += lumSrc[j][i * 2 + 1] * lumFilter[j];

        }

        Y1 >>= 15;

        Y2 >>= 15;

        if ((Y1 | Y2) & 0x10000) {

            Y1 = av_clip_uint16(Y1);

            Y2 = av_clip_uint16(Y2);

        }

        output_pixel(&dest[i * 2 + 0], Y1);

        output_pixel(&dest[i * 2 + 1], Y2);

    }

}


static void ehci_mem_writeb(void *ptr, target_phys_addr_t addr, uint32_t val)

{

    fprintf(stderr, "EHCI doesn't handle byte writes to MMIO\n");

    exit(1);

}


static int cmp(const void *key, const void *node)

{

    return (*(const int64_t *) key) - ((const CacheEntry *) node)->logical_pos;

}


static void spapr_machine_reset(void)
{
    MachineState *machine = MACHINE(qdev_get_machine());
    sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
    PowerPCCPU *first_ppc_cpu;
    uint32_t rtas_limit;
    hwaddr rtas_addr, fdt_addr;
    void *fdt;
    int rc;
    /* Check for unknown sysbus devices */
    foreach_dynamic_sysbus_device(find_unknown_sysbus_device, NULL);
    first_ppc_cpu = POWERPC_CPU(first_cpu);
    if (kvm_enabled() && kvmppc_has_cap_mmu_radix() &&
        ppc_check_compat(first_ppc_cpu, CPU_POWERPC_LOGICAL_3_00, 0,
                         spapr->max_compat_pvr)) {
        /* If using KVM with radix mode available, VCPUs can be started
         * without a HPT because KVM will start them in radix mode.
         * Set the GR bit in PATB so that we know there is no HPT. */
        spapr->patb_entry = PATBE1_GR;
    } else {
        spapr_setup_hpt_and_vrma(spapr);
    }
    qemu_devices_reset();
    /* DRC reset may cause a device to be unplugged. This will cause troubles
     * if this device is used by another device (eg, a running vhost backend
     * will crash QEMU if the DIMM holding the vring goes away). To avoid such
     * situations, we reset DRCs after all devices have been reset.
     */
    object_child_foreach_recursive(object_get_root(), spapr_reset_drcs, NULL);
    spapr_clear_pending_events(spapr);
    /*
     * We place the device tree and RTAS just below either the top of the RMA,
     * or just below 2GB, whichever is lowere, so that it can be
     * processed with 32-bit real mode code if necessary
     */
    rtas_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR);
    rtas_addr = rtas_limit - RTAS_MAX_SIZE;
    fdt_addr = rtas_addr - FDT_MAX_SIZE;
    /* if this reset wasn't generated by CAS, we should reset our
     * negotiated options and start from scratch */
    if (!spapr->cas_reboot) {
        spapr_ovec_cleanup(spapr->ov5_cas);
        spapr->ov5_cas = spapr_ovec_new();
        ppc_set_compat(first_ppc_cpu, spapr->max_compat_pvr, &error_fatal);
    }
    fdt = spapr_build_fdt(spapr, rtas_addr, spapr->rtas_size);
    spapr_load_rtas(spapr, fdt, rtas_addr);
    rc = fdt_pack(fdt);
    /* Should only fail if we've built a corrupted tree */
    assert(rc == 0);
    if (fdt_totalsize(fdt) > FDT_MAX_SIZE) {
        error_report("FDT too big ! 0x%x bytes (max is 0x%x)",
                     fdt_totalsize(fdt), FDT_MAX_SIZE);
        exit(1);
    }
    /* Load the fdt */
    qemu_fdt_dumpdtb(fdt, fdt_totalsize(fdt));
    cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt));
    g_free(fdt);
    /* Set up the entry state */
    first_ppc_cpu->env.gpr[3] = fdt_addr;
    first_ppc_cpu->env.gpr[5] = 0;
    first_cpu->halted = 0;
    first_ppc_cpu->env.nip = SPAPR_ENTRY_POINT;
    spapr->cas_reboot = false;
}


static void compute_chapters_end(AVFormatContext *s)

{

    unsigned int i, j;

    int64_t max_time = s->duration +

                       ((s->start_time == AV_NOPTS_VALUE) ? 0 : s->start_time);

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

        if (s->chapters[i]->end == AV_NOPTS_VALUE) {

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

            int64_t end = max_time ? av_rescale_q(max_time, AV_TIME_BASE_Q,

                                                  ch->time_base)

                                   : INT64_MAX;

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

                AVChapter *ch1     = s->chapters[j];

                int64_t next_start = av_rescale_q(ch1->start, ch1->time_base,

                                                  ch->time_base);

                if (j != i && next_start > ch->start && next_start < end)

                    end = next_start;

            }

            ch->end = (end == INT64_MAX) ? ch->start : end;

        }

}


static coroutine_fn void nbd_read_reply_entry(void *opaque)

{

    NBDClientSession *s = opaque;

    uint64_t i;

    int ret = 0;

    Error *local_err = NULL;

    while (!s->quit) {

        assert(s->reply.handle == 0);

        ret = nbd_receive_reply(s->ioc, &s->reply, &local_err);

        if (ret < 0) {

            error_report_err(local_err);

        }

        if (ret <= 0) {

            break;

        }

        /* There's no need for a mutex on the receive side, because the

         * handler acts as a synchronization point and ensures that only

         * one coroutine is called until the reply finishes.

         */

        i = HANDLE_TO_INDEX(s, s->reply.handle);

        if (i >= MAX_NBD_REQUESTS ||

            !s->requests[i].coroutine ||

            !s->requests[i].receiving ||

            (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))

        {

            break;

        }

        /* We're woken up again by the request itself.  Note that there

         * is no race between yielding and reentering read_reply_co.  This

         * is because:

         *

         * - if the request runs on the same AioContext, it is only

         *   entered after we yield

         *

         * - if the request runs on a different AioContext, reentering

         *   read_reply_co happens through a bottom half, which can only

         *   run after we yield.

         */

        aio_co_wake(s->requests[i].coroutine);

        qemu_coroutine_yield();

    }

    s->quit = true;

    nbd_recv_coroutines_wake_all(s);

    s->read_reply_co = NULL;

}


void esp_reg_write(ESPState *s, uint32_t saddr, uint64_t val)

{

    trace_esp_mem_writeb(saddr, s->wregs[saddr], val);

    switch (saddr) {

    case ESP_TCHI:

        s->tchi_written = true;

        /* fall through */

    case ESP_TCLO:

    case ESP_TCMID:

        s->rregs[ESP_RSTAT] &= ~STAT_TC;

        break;

    case ESP_FIFO:

        if (s->do_cmd) {

            s->cmdbuf[s->cmdlen++] = val & 0xff;

        } else if (s->ti_size == TI_BUFSZ - 1) {

            trace_esp_error_fifo_overrun();

        } else {

            s->ti_size++;

            s->ti_buf[s->ti_wptr++] = val & 0xff;

        }

        break;

    case ESP_CMD:

        s->rregs[saddr] = val;

        if (val & CMD_DMA) {

            s->dma = 1;

            /* Reload DMA counter.  */

            s->rregs[ESP_TCLO] = s->wregs[ESP_TCLO];

            s->rregs[ESP_TCMID] = s->wregs[ESP_TCMID];

            s->rregs[ESP_TCHI] = s->wregs[ESP_TCHI];

        } else {

            s->dma = 0;

        }

        switch(val & CMD_CMD) {

        case CMD_NOP:

            trace_esp_mem_writeb_cmd_nop(val);

            break;

        case CMD_FLUSH:

            trace_esp_mem_writeb_cmd_flush(val);

            //s->ti_size = 0;

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSEQ] = 0;

            s->rregs[ESP_RFLAGS] = 0;

            break;

        case CMD_RESET:

            trace_esp_mem_writeb_cmd_reset(val);

            esp_soft_reset(s);

            break;

        case CMD_BUSRESET:

            trace_esp_mem_writeb_cmd_bus_reset(val);

            s->rregs[ESP_RINTR] = INTR_RST;

            if (!(s->wregs[ESP_CFG1] & CFG1_RESREPT)) {

                esp_raise_irq(s);

            }

            break;

        case CMD_TI:

            handle_ti(s);

            break;

        case CMD_ICCS:

            trace_esp_mem_writeb_cmd_iccs(val);

            write_response(s);

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSTAT] |= STAT_MI;

            break;

        case CMD_MSGACC:

            trace_esp_mem_writeb_cmd_msgacc(val);

            s->rregs[ESP_RINTR] = INTR_DC;

            s->rregs[ESP_RSEQ] = 0;

            s->rregs[ESP_RFLAGS] = 0;

            esp_raise_irq(s);

            break;

        case CMD_PAD:

            trace_esp_mem_writeb_cmd_pad(val);

            s->rregs[ESP_RSTAT] = STAT_TC;

            s->rregs[ESP_RINTR] = INTR_FC;

            s->rregs[ESP_RSEQ] = 0;

            break;

        case CMD_SATN:

            trace_esp_mem_writeb_cmd_satn(val);

            break;

        case CMD_RSTATN:

            trace_esp_mem_writeb_cmd_rstatn(val);

            break;

        case CMD_SEL:

            trace_esp_mem_writeb_cmd_sel(val);

            handle_s_without_atn(s);

            break;

        case CMD_SELATN:

            trace_esp_mem_writeb_cmd_selatn(val);

            handle_satn(s);

            break;

        case CMD_SELATNS:

            trace_esp_mem_writeb_cmd_selatns(val);

            handle_satn_stop(s);

            break;

        case CMD_ENSEL:

            trace_esp_mem_writeb_cmd_ensel(val);

            s->rregs[ESP_RINTR] = 0;

            break;

        case CMD_DISSEL:

            trace_esp_mem_writeb_cmd_dissel(val);

            s->rregs[ESP_RINTR] = 0;

            esp_raise_irq(s);

            break;

        default:

            trace_esp_error_unhandled_command(val);

            break;

        }

        break;

    case ESP_WBUSID ... ESP_WSYNO:

        break;

    case ESP_CFG1:

    case ESP_CFG2: case ESP_CFG3:

    case ESP_RES3: case ESP_RES4:

        s->rregs[saddr] = val;

        break;

    case ESP_WCCF ... ESP_WTEST:

        break;

    default:

        trace_esp_error_invalid_write(val, saddr);

        return;

    }

    s->wregs[saddr] = val;

}


static int coroutine_fn blkreplay_co_pdiscard(BlockDriverState *bs,

                                              int64_t offset, int count)

{

    uint64_t reqid = request_id++;

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

    block_request_create(reqid, bs, qemu_coroutine_self());

    qemu_coroutine_yield();

    return ret;

}


static void init_proc_750 (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* Time base */

    gen_tbl(env);

    /* Thermal management */

    gen_spr_thrm(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

    gen_low_BATs(env);

    /* XXX: high BATs are also present but are known to be bugged on

     *      die version 1.x

     */

    init_excp_7x0(env);

    env->dcache_line_size = 32;

    env->icache_line_size = 32;

    /* Allocate hardware IRQ controller */

    ppc6xx_irq_init(env);

}


static USBDevice *usb_serial_init(const char *filename)

{

    USBDevice *dev;

    CharDriverState *cdrv;

    uint32_t vendorid = 0, productid = 0;

    char label[32];

    static int index;

    while (*filename && *filename != ':') {

        const char *p;

        char *e;

        if (strstart(filename, "vendorid=", &p)) {

            vendorid = strtol(p, &e, 16);

            if (e == p || (*e && *e != ',' && *e != ':')) {

                qemu_error("bogus vendor ID %s\n", p);

            filename = e;

        } else if (strstart(filename, "productid=", &p)) {

            productid = strtol(p, &e, 16);

            if (e == p || (*e && *e != ',' && *e != ':')) {

                qemu_error("bogus product ID %s\n", p);

            filename = e;

        } else {

            qemu_error("unrecognized serial USB option %s\n", filename);

        while(*filename == ',')

            filename++;

    if (!*filename) {

        qemu_error("character device specification needed\n");

    filename++;

    snprintf(label, sizeof(label), "usbserial%d", index++);

    cdrv = qemu_chr_open(label, filename, NULL);

    if (!cdrv)

    dev = usb_create(NULL /* FIXME */, "usb-serial");

    qdev_prop_set_chr(&dev->qdev, "chardev", cdrv);

    if (vendorid)

        qdev_prop_set_uint16(&dev->qdev, "vendorid", vendorid);

    if (productid)

        qdev_prop_set_uint16(&dev->qdev, "productid", productid);

    qdev_init_nofail(&dev->qdev);

    return dev;


static int gen_neon_zip(int rd, int rm, int size, int q)

{

    TCGv tmp, tmp2;

    if (size == 3 || (!q && size == 2)) {

        return 1;

    }

    tmp = tcg_const_i32(rd);

    tmp2 = tcg_const_i32(rm);

    if (q) {

        switch (size) {

        case 0:

            gen_helper_neon_qzip8(tmp, tmp2);

            break;

        case 1:

            gen_helper_neon_qzip16(tmp, tmp2);

            break;

        case 2:

            gen_helper_neon_qzip32(tmp, tmp2);

            break;

        default:

            abort();

        }

    } else {

        switch (size) {

        case 0:

            gen_helper_neon_zip8(tmp, tmp2);

            break;

        case 1:

            gen_helper_neon_zip16(tmp, tmp2);

            break;

        default:

            abort();

        }

    }

    tcg_temp_free_i32(tmp);

    tcg_temp_free_i32(tmp2);

    return 0;

}


target_ulong helper_dmt(target_ulong arg1)

{

    // TODO

    arg1 = 0;

    // rt = arg1

    return arg1;

}


static int send_dma_request(int cmd, uint64_t sector, int nb_sectors,
                            PrdtEntry *prdt, int prdt_entries)
{
    QPCIDevice *dev;
    uint16_t bmdma_base;
    uintptr_t guest_prdt;
    size_t len;
    bool from_dev;
    uint8_t status;
    int flags;
    dev = get_pci_device(&bmdma_base);
    flags = cmd & ~0xff;
    cmd &= 0xff;
    switch (cmd) {
    case CMD_READ_DMA:
        from_dev = true;
        break;
    case CMD_WRITE_DMA:
        from_dev = false;
        break;
    default:
        g_assert_not_reached();
    /* Select device 0 */
    outb(IDE_BASE + reg_device, 0 | LBA);
    /* Stop any running transfer, clear any pending interrupt */
    outb(bmdma_base + bmreg_cmd, 0);
    outb(bmdma_base + bmreg_status, BM_STS_INTR);
    /* Setup PRDT */
    len = sizeof(*prdt) * prdt_entries;
    guest_prdt = guest_alloc(guest_malloc, len);
    memwrite(guest_prdt, prdt, len);
    outl(bmdma_base + bmreg_prdt, guest_prdt);
    /* ATA DMA command */
    outb(IDE_BASE + reg_nsectors, nb_sectors);
    outb(IDE_BASE + reg_lba_low,    sector & 0xff);
    outb(IDE_BASE + reg_lba_middle, (sector >> 8) & 0xff);
    outb(IDE_BASE + reg_lba_high,   (sector >> 16) & 0xff);
    outb(IDE_BASE + reg_command, cmd);
    /* Start DMA transfer */
    outb(bmdma_base + bmreg_cmd, BM_CMD_START | (from_dev ? BM_CMD_WRITE : 0));
    if (flags & CMDF_ABORT) {
        outb(bmdma_base + bmreg_cmd, 0);
    /* Wait for the DMA transfer to complete */
    do {
        status = inb(bmdma_base + bmreg_status);
    } while ((status & (BM_STS_ACTIVE | BM_STS_INTR)) == BM_STS_ACTIVE);
    g_assert_cmpint(get_irq(IDE_PRIMARY_IRQ), ==, !!(status & BM_STS_INTR));
    /* Check IDE status code */
    assert_bit_set(inb(IDE_BASE + reg_status), DRDY);
    assert_bit_clear(inb(IDE_BASE + reg_status), BSY | DRQ);
    /* Reading the status register clears the IRQ */
    g_assert(!get_irq(IDE_PRIMARY_IRQ));
    /* Stop DMA transfer if still active */
    if (status & BM_STS_ACTIVE) {
        outb(bmdma_base + bmreg_cmd, 0);
    free_pci_device(dev);
    return status;


static int qemu_rdma_block_for_wrid(RDMAContext *rdma, int wrid_requested,

                                    uint32_t *byte_len)

{

    int num_cq_events = 0, ret = 0;

    struct ibv_cq *cq;

    void *cq_ctx;

    uint64_t wr_id = RDMA_WRID_NONE, wr_id_in;

    if (ibv_req_notify_cq(rdma->cq, 0)) {

        return -1;

    }

    /* poll cq first */

    while (wr_id != wrid_requested) {

        ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);

        if (ret < 0) {

            return ret;

        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {

            break;

        }

        if (wr_id != wrid_requested) {

            DDDPRINTF("A Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",

                print_wrid(wrid_requested),

                wrid_requested, print_wrid(wr_id), wr_id);

        }

    }

    if (wr_id == wrid_requested) {

        return 0;

    }

    while (1) {

        /*

         * Coroutine doesn't start until process_incoming_migration()

         * so don't yield unless we know we're running inside of a coroutine.

         */

        if (rdma->migration_started_on_destination) {

            yield_until_fd_readable(rdma->comp_channel->fd);

        }

        if (ibv_get_cq_event(rdma->comp_channel, &cq, &cq_ctx)) {

            perror("ibv_get_cq_event");

            goto err_block_for_wrid;

        }

        num_cq_events++;

        if (ibv_req_notify_cq(cq, 0)) {

            goto err_block_for_wrid;

        }

        while (wr_id != wrid_requested) {

            ret = qemu_rdma_poll(rdma, &wr_id_in, byte_len);

            if (ret < 0) {

                goto err_block_for_wrid;

            }

            wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

            if (wr_id == RDMA_WRID_NONE) {

                break;

            }

            if (wr_id != wrid_requested) {

                DDDPRINTF("B Wanted wrid %s (%d) but got %s (%" PRIu64 ")\n",

                    print_wrid(wrid_requested), wrid_requested,

                    print_wrid(wr_id), wr_id);

            }

        }

        if (wr_id == wrid_requested) {

            goto success_block_for_wrid;

        }

    }

success_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    return 0;

err_block_for_wrid:

    if (num_cq_events) {

        ibv_ack_cq_events(cq, num_cq_events);

    }

    return ret;

}


static int svq1_decode_delta_block(AVCodecContext *avctx, DSPContext *dsp,

                                   GetBitContext *bitbuf,

                                   uint8_t *current, uint8_t *previous,

                                   int pitch, svq1_pmv *motion, int x, int y)

{

    uint32_t block_type;

    int result = 0;

    /* get block type */

    block_type = get_vlc2(bitbuf, svq1_block_type.table, 2, 2);

    /* reset motion vectors */

    if (block_type == SVQ1_BLOCK_SKIP || block_type == SVQ1_BLOCK_INTRA) {

        motion[0].x         =

        motion[0].y         =

        motion[x / 8 + 2].x =

        motion[x / 8 + 2].y =

        motion[x / 8 + 3].x =

        motion[x / 8 + 3].y = 0;

    }

    switch (block_type) {

    case SVQ1_BLOCK_SKIP:

        svq1_skip_block(current, previous, pitch, x, y);

        break;

    case SVQ1_BLOCK_INTER:

        result = svq1_motion_inter_block(dsp, bitbuf, current, previous,

                                         pitch, motion, x, y);

        if (result != 0) {

            av_dlog(avctx, "Error in svq1_motion_inter_block %i\n", result);

            break;

        }

        result = svq1_decode_block_non_intra(bitbuf, current, pitch);

        break;

    case SVQ1_BLOCK_INTER_4V:

        result = svq1_motion_inter_4v_block(dsp, bitbuf, current, previous,

                                            pitch, motion, x, y);

        if (result != 0) {

            av_dlog(avctx, "Error in svq1_motion_inter_4v_block %i\n", result);

            break;

        }

        result = svq1_decode_block_non_intra(bitbuf, current, pitch);

        break;

    case SVQ1_BLOCK_INTRA:

        result = svq1_decode_block_intra(bitbuf, current, pitch);

        break;

    }

    return result;

}


static int decode_styl(const uint8_t *tsmb, MovTextContext *m, AVPacket *avpkt)

{

    int i;

    m->style_entries = AV_RB16(tsmb);

    tsmb += 2;

    // A single style record is of length 12 bytes.

    if (m->tracksize + m->size_var + 2 + m->style_entries * 12 > avpkt->size)

        return -1;

    m->box_flags |= STYL_BOX;

    for(i = 0; i < m->style_entries; i++) {

        m->s_temp = av_malloc(sizeof(*m->s_temp));

        if (!m->s_temp) {

            mov_text_cleanup(m);

            return AVERROR(ENOMEM);

        }

        m->s_temp->style_start = AV_RB16(tsmb);

        tsmb += 2;

        m->s_temp->style_end = AV_RB16(tsmb);

        tsmb += 2;

        m->s_temp->style_fontID = AV_RB16(tsmb);

        tsmb += 2;

        m->s_temp->style_flag = AV_RB8(tsmb);

        tsmb++;

        m->s_temp->fontsize = AV_RB8(tsmb);

        av_dynarray_add(&m->s, &m->count_s, m->s_temp);

        if(!m->s) {

            mov_text_cleanup(m);

            return AVERROR(ENOMEM);

        }

        tsmb++;

        // text-color-rgba

        tsmb += 4;

    }

    return 0;

}


static void opt_pass(const char *pass_str)

{

    int pass;

    pass = atoi(pass_str);

    if (pass != 1 && pass != 2) {

        fprintf(stderr, "pass number can be only 1 or 2\n");

        ffmpeg_exit(1);

    }

    do_pass = pass;

}


static int opt_deinterlace(void *optctx, const char *opt, const char *arg)

{

    av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);

    do_deinterlace = 1;

    return 0;

}


int ff_get_schro_frame_format (SchroChromaFormat schro_pix_fmt,

                               SchroFrameFormat  *schro_frame_fmt)

{

    unsigned int num_formats = sizeof(schro_pixel_format_map) /

                               sizeof(schro_pixel_format_map[0]);

    int idx;

    for (idx = 0; idx < num_formats; ++idx) {

        if (schro_pixel_format_map[idx].schro_pix_fmt == schro_pix_fmt) {

            *schro_frame_fmt = schro_pixel_format_map[idx].schro_frame_fmt;

            return 0;

        }

    }

    return -1;

}


static int read_mv_component(VP56RangeCoder *c, const uint8_t *p)

{

    int bit, x = 0;

    if (vp56_rac_get_prob_branchy(c, p[0])) {

        int i;

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

            x += vp56_rac_get_prob(c, p[9 + i]) << i;

        for (i = 9; i > 3; i--)

            x += vp56_rac_get_prob(c, p[9 + i]) << i;

        if (!(x & 0xFFF0) || vp56_rac_get_prob(c, p[12]))

            x += 8;

    } else {

        // small_mvtree

        const uint8_t *ps = p + 2;

        bit = vp56_rac_get_prob(c, *ps);

        ps += 1 + 3 * bit;

        x  += 4 * bit;

        bit = vp56_rac_get_prob(c, *ps);

        ps += 1 + bit;

        x  += 2 * bit;

        x  += vp56_rac_get_prob(c, *ps);

    }

    return (x && vp56_rac_get_prob(c, p[1])) ? -x : x;

}


yuv2mono_2_c_template(SwsContext *c, const int16_t *buf[2],

                      const int16_t *ubuf[2], const int16_t *vbuf[2],

                      const int16_t *abuf[2], uint8_t *dest, int dstW,

                      int yalpha, int uvalpha, int y,

                      enum PixelFormat target)

{

    const int16_t *buf0  = buf[0],  *buf1  = buf[1];

    const uint8_t * const d128 = dither_8x8_220[y & 7];

    int  yalpha1 = 4095 - yalpha;

    int i;

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

        int Y, acc = 0;

        Y = (buf0[i + 0] * yalpha1 + buf1[i + 0] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[0]);

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

        accumulate_bit(acc, Y + d128[1]);

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

        accumulate_bit(acc, Y + d128[2]);

        Y = (buf0[i + 3] * yalpha1 + buf1[i + 3] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[3]);

        Y = (buf0[i + 4] * yalpha1 + buf1[i + 4] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[4]);

        Y = (buf0[i + 5] * yalpha1 + buf1[i + 5] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[5]);

        Y = (buf0[i + 6] * yalpha1 + buf1[i + 6] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[6]);

        Y = (buf0[i + 7] * yalpha1 + buf1[i + 7] * yalpha) >> 19;

        accumulate_bit(acc, Y + d128[7]);

        output_pixel(*dest++, acc);

    }

}


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

{

    int64_t size, av_uninit(data_size);

    uint32_t dpds_table_size = 0;

    uint32_t *dpds_table = 0;

    unsigned int tag;

    AVIOContext *pb = s->pb;

    AVStream *st;

    XWMAContext *xwma = s->priv_data;

    int i;

    /* The following code is mostly copied from wav.c, with some

     * minor alterations.

     */

    /* check RIFF header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('R', 'I', 'F', 'F'))

        return -1;

    avio_rl32(pb); /* file size */

    tag = avio_rl32(pb);

    if (tag != MKTAG('X', 'W', 'M', 'A'))

        return -1;

    /* parse fmt header */

    tag = avio_rl32(pb);

    if (tag != MKTAG('f', 'm', 't', ' '))

        return -1;

    size = avio_rl32(pb);

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    ff_get_wav_header(pb, st->codec, size);

    st->need_parsing = AVSTREAM_PARSE_NONE;

    /* All xWMA files I have seen contained WMAv2 data. If there are files

     * using WMA Pro or some other codec, then we need to figure out the right

     * extradata for that. Thus, ask the user for feedback, but try to go on

     * anyway.

     */

    if (st->codec->codec_id != CODEC_ID_WMAV2) {

        av_log(s, AV_LOG_WARNING, "unexpected codec (tag 0x04%x; id %d)\n",

                              st->codec->codec_tag, st->codec->codec_id);

        av_log_ask_for_sample(s, NULL);

    } else {

        /* In all xWMA files I have seen, there is no extradata. But the WMA

         * codecs require extradata, so we provide our own fake extradata.

         *

         * First, check that there really was no extradata in the header. If

         * there was, then try to use, after asking the the user to provide a

         * sample of this unusual file.

         */

        if (st->codec->extradata_size != 0) {

            /* Surprise, surprise: We *did* get some extradata. No idea

             * if it will work, but just go on and try it, after asking

             * the user for a sample.

             */

            av_log(s, AV_LOG_WARNING, "unexpected extradata (%d bytes)\n",

                                  st->codec->extradata_size);

            av_log_ask_for_sample(s, NULL);

        } else {

            st->codec->extradata_size = 6;

            st->codec->extradata      = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

            /* setup extradata with our experimentally obtained value */

            st->codec->extradata[4] = 31;

        }

    }

    /* set the sample rate */

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

    /* parse the remaining RIFF chunks */

    for (;;) {

        if (pb->eof_reached)

            return -1;

        /* read next chunk tag */

        tag = avio_rl32(pb);

        size = avio_rl32(pb);

        if (tag == MKTAG('d', 'a', 't', 'a')) {

            /* We assume that the data chunk comes last. */

            break;

        } else if (tag == MKTAG('d','p','d','s')) {

            /* Quoting the MSDN xWMA docs on the dpds chunk: "Contains the

             * decoded packet cumulative data size array, each element is the

             * number of bytes accumulated after the corresponding xWMA packet

             * is decoded in order"

             *

             * Each packet has size equal to st->codec->block_align, which in

             * all cases I saw so far was always 2230. Thus, we can use the

             * dpds data to compute a seeking index.

             */

            /* Error out if there is more than one dpds chunk. */

            if (dpds_table) {

                av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");

                return -1;

            }

            /* Compute the number of entries in the dpds chunk. */

            if (size & 3) {  /* Size should be divisible by four */

                av_log(s, AV_LOG_WARNING, "dpds chunk size "PRId64" not divisible by 4\n", size);

            }

            dpds_table_size = size / 4;

            if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {

                av_log(s, AV_LOG_ERROR, "dpds chunk size "PRId64" invalid\n", size);

                return -1;

            }

            /* Allocate some temporary storage to keep the dpds data around.

             * for processing later on.

             */

            dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));

            if (!dpds_table) {

                return AVERROR(ENOMEM);

            }

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

                dpds_table[i] = avio_rl32(pb);

                size -= 4;

            }

        }

        avio_skip(pb, size);

    }

    /* Determine overall data length */

    if (size < 0)

        return -1;

    if (!size) {

        xwma->data_end = INT64_MAX;

    } else

        xwma->data_end = avio_tell(pb) + size;

    if (dpds_table && dpds_table_size) {

        int64_t cur_pos;

        const uint32_t bytes_per_sample

                = (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;

        /* Estimate the duration from the total number of output bytes. */

        const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];

        st->duration = total_decoded_bytes / bytes_per_sample;

        /* Use the dpds data to build a seek table.  We can only do this after

         * we know the offset to the data chunk, as we need that to determine

         * the actual offset to each input block.

         * Note: If we allowed ourselves to assume that the data chunk always

         * follows immediately after the dpds block, we could of course guess

         * the data block's start offset already while reading the dpds chunk.

         * I decided against that, just in case other chunks ever are

         * discovered.

         */

        cur_pos = avio_tell(pb);

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

            /* From the number of output bytes that would accumulate in the

             * output buffer after decoding the first (i+1) packets, we compute

             * an offset / timestamp pair.

             */

            av_add_index_entry(st,

                               cur_pos + (i+1) * st->codec->block_align, /* pos */

                               dpds_table[i] / bytes_per_sample,         /* timestamp */

                               st->codec->block_align,                   /* size */

                               0,                                        /* duration */

                               AVINDEX_KEYFRAME);

        }

    } else if (st->codec->bit_rate) {

        /* No dpds chunk was present (or only an empty one), so estimate

         * the total duration using the average bits per sample and the

         * total data length.

         */

        st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;

    }

    av_free(dpds_table);

    return 0;

}


void qmp_migrate_set_parameters(bool has_compress_level,

                                int64_t compress_level,

                                bool has_compress_threads,

                                int64_t compress_threads,

                                bool has_decompress_threads,

                                int64_t decompress_threads,

                                bool has_cpu_throttle_initial,

                                int64_t cpu_throttle_initial,

                                bool has_cpu_throttle_increment,

                                int64_t cpu_throttle_increment,

                                Error **errp)

{

    MigrationState *s = migrate_get_current();

    if (has_compress_level && (compress_level < 0 || compress_level > 9)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",

                   "is invalid, it should be in the range of 0 to 9");

        return;

    }

    if (has_compress_threads &&

            (compress_threads < 1 || compress_threads > 255)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "compress_threads",

                   "is invalid, it should be in the range of 1 to 255");

        return;

    }

    if (has_decompress_threads &&

            (decompress_threads < 1 || decompress_threads > 255)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "decompress_threads",

                   "is invalid, it should be in the range of 1 to 255");

        return;

    }

    if (has_cpu_throttle_initial &&

            (cpu_throttle_initial < 1 || cpu_throttle_initial > 99)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "cpu_throttle_initial",

                   "an integer in the range of 1 to 99");

    }

    if (has_cpu_throttle_increment &&

            (cpu_throttle_increment < 1 || cpu_throttle_increment > 99)) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                   "cpu_throttle_increment",

                   "an integer in the range of 1 to 99");

    }

    if (has_compress_level) {

        s->parameters.compress_level = compress_level;

    }

    if (has_compress_threads) {

        s->parameters.compress_threads = compress_threads;

    }

    if (has_decompress_threads) {

        s->parameters.decompress_threads = decompress_threads;

    }

    if (has_cpu_throttle_initial) {

        s->parameters.cpu_throttle_initial = cpu_throttle_initial;

    }

    if (has_cpu_throttle_increment) {

        s->parameters.cpu_throttle_increment = cpu_throttle_increment;

    }

    if (has_tls_creds) {

        g_free(s->parameters.tls_creds);

        s->parameters.tls_creds = g_strdup(tls_creds);

    }

    if (has_tls_hostname) {

        g_free(s->parameters.tls_hostname);

        s->parameters.tls_hostname = g_strdup(tls_hostname);

    }

}


static int swf_write_packet(AVFormatContext *s, int stream_index,

                           const uint8_t *buf, int size, int64_t pts)

{

    AVCodecContext *codec = &s->streams[stream_index]->codec;

    if (codec->codec_type == CODEC_TYPE_AUDIO)

        return swf_write_audio(s, buf, size);

    else

        return swf_write_video(s, codec, buf, size);

}


static void hScale16To15_c(SwsContext *c, int16_t *dst, int dstW, const uint8_t *_src,

                           const int16_t *filter,

                           const int16_t *filterPos, int filterSize)

{

    int i;

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

    int sh = av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;

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

        int j;

        int srcPos = filterPos[i];

        int val = 0;

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

            val += src[srcPos + j] * filter[filterSize * i + j];

        }

        // filter=14 bit, input=16 bit, output=30 bit, >> 15 makes 15 bit

        dst[i] = FFMIN(val >> sh, (1 << 15) - 1);

    }

}


static int __qemu_rdma_delete_block(RDMAContext *rdma, ram_addr_t block_offset)

{

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMALocalBlock *block = g_hash_table_lookup(rdma->blockmap,

        (void *) block_offset);

    RDMALocalBlock *old = local->block;

    int x;

    assert(block);

    if (block->pmr) {

        int j;

        for (j = 0; j < block->nb_chunks; j++) {

            if (!block->pmr[j]) {

                continue;

            }

            ibv_dereg_mr(block->pmr[j]);

            rdma->total_registrations--;

        }

        g_free(block->pmr);

        block->pmr = NULL;

    }

    if (block->mr) {

        ibv_dereg_mr(block->mr);

        rdma->total_registrations--;

        block->mr = NULL;

    }

    g_free(block->transit_bitmap);

    block->transit_bitmap = NULL;

    g_free(block->unregister_bitmap);

    block->unregister_bitmap = NULL;

    g_free(block->remote_keys);

    block->remote_keys = NULL;

    for (x = 0; x < local->nb_blocks; x++) {

        g_hash_table_remove(rdma->blockmap, (void *)old[x].offset);

    }

    if (local->nb_blocks > 1) {

        local->block = g_malloc0(sizeof(RDMALocalBlock) *

                                    (local->nb_blocks - 1));

        if (block->index) {

            memcpy(local->block, old, sizeof(RDMALocalBlock) * block->index);

        }

        if (block->index < (local->nb_blocks - 1)) {

            memcpy(local->block + block->index, old + (block->index + 1),

                sizeof(RDMALocalBlock) *

                    (local->nb_blocks - (block->index + 1)));

        }

    } else {

        assert(block == local->block);

        local->block = NULL;

    }

    DDPRINTF("Deleted Block: %d, addr: %" PRIu64 ", offset: %" PRIu64

           " length: %" PRIu64 " end: %" PRIu64 " bits %" PRIu64 " chunks %d\n",

            local->nb_blocks, (uint64_t) block->local_host_addr, block->offset,

            block->length, (uint64_t) (block->local_host_addr + block->length),

                BITS_TO_LONGS(block->nb_chunks) *

                    sizeof(unsigned long) * 8, block->nb_chunks);

    g_free(old);

    local->nb_blocks--;

    if (local->nb_blocks) {

        for (x = 0; x < local->nb_blocks; x++) {

            g_hash_table_insert(rdma->blockmap, (void *)local->block[x].offset,

                                                &local->block[x]);

        }

    }

    return 0;

}


static int decode_extradata(ADTSContext *adts, uint8_t *buf, int size)

{

    GetBitContext gb;

    init_get_bits(&gb, buf, size * 8);

    adts->objecttype = get_bits(&gb, 5) - 1;

    adts->sample_rate_index = get_bits(&gb, 4);

    adts->channel_conf = get_bits(&gb, 4);

    adts->write_adts = 1;

    return 0;

}


static void tcg_out_st (TCGContext *s, TCGType type, int arg, int arg1,

                        tcg_target_long arg2)

{

    if (type == TCG_TYPE_I32)

        tcg_out_ldst (s, arg, arg1, arg2, STW, STWX);

    else

        tcg_out_ldst (s, arg, arg1, arg2, STD, STDX);

}


static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    char *buf;

    /* For /dev/sg devices the alignment is not really used.

       With buffered I/O, we don't have any restrictions. */

    if (bs->sg || !s->needs_alignment) {

        bs->request_alignment = 1;

        s->buf_align = 1;

        return;

    }

    bs->request_alignment = 0;

    s->buf_align = 0;

    /* Let's try to use the logical blocksize for the alignment. */

    if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {

        bs->request_alignment = 0;

    }

#ifdef CONFIG_XFS

    if (s->is_xfs) {

        struct dioattr da;

        if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {

            bs->request_alignment = da.d_miniosz;

            /* The kernel returns wrong information for d_mem */

            /* s->buf_align = da.d_mem; */

        }

    }

#endif

    /* If we could not get the sizes so far, we can only guess them */

    if (!s->buf_align) {

        size_t align;

        buf = qemu_memalign(MAX_BLOCKSIZE, 2 * MAX_BLOCKSIZE);

        for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {

            if (pread(fd, buf + align, MAX_BLOCKSIZE, 0) >= 0) {

                s->buf_align = align;

                break;

            }

        }

        qemu_vfree(buf);

    }

    if (!bs->request_alignment) {

        size_t align;

        buf = qemu_memalign(s->buf_align, MAX_BLOCKSIZE);

        for (align = 512; align <= MAX_BLOCKSIZE; align <<= 1) {

            if (pread(fd, buf, align, 0) >= 0) {

                bs->request_alignment = align;

                break;

            }

        }

        qemu_vfree(buf);

    }

    if (!s->buf_align || !bs->request_alignment) {

        error_setg(errp, "Could not find working O_DIRECT alignment. "

                         "Try cache.direct=off.");

    }

}


static void alpha_cpu_realizefn(DeviceState *dev, Error **errp)
{
    AlphaCPUClass *acc = ALPHA_CPU_GET_CLASS(dev);
    acc->parent_realize(dev, errp);
}


static void add_pixels_clamped_mmx(const DCTELEM *block, UINT8 *pixels, int line_size)

{

    const DCTELEM *p;

    UINT8 *pix;

    int i;

    /* read the pixels */

    p = block;

    pix = pixels;

    MOVQ_ZERO(mm7);

    i = 4;

    while (i) {

	__asm __volatile(

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

		"movq	8%2, %%mm1\n\t"

		"movq	16%2, %%mm2\n\t"

		"movq	24%2, %%mm3\n\t"

		"movq	%0, %%mm4\n\t"

		"movq	%1, %%mm6\n\t"

		"movq	%%mm4, %%mm5\n\t"

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

		"punpckhbw %%mm7, %%mm5\n\t"

		"paddsw	%%mm4, %%mm0\n\t"

		"paddsw	%%mm5, %%mm1\n\t"

		"movq	%%mm6, %%mm5\n\t"

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

		"punpckhbw %%mm7, %%mm5\n\t"

		"paddsw	%%mm6, %%mm2\n\t"

		"paddsw	%%mm5, %%mm3\n\t"

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

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

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

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

		:"+m"(*pix), "+m"(*(pix+line_size))

		:"m"(*p)

		:"memory");

        pix += line_size*2;

        p += 16;

        i--;

    };

}


struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory,

                unsigned long sdram_size,

                const char *core)

{

    int i;

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *)

            g_malloc0(sizeof(struct omap_mpu_state_s));

    qemu_irq dma_irqs[6];

    DriveInfo *dinfo;

    SysBusDevice *busdev;

    if (!core)

        core = "ti925t";

    /* Core */

    s->mpu_model = omap310;

    s->cpu = cpu_arm_init(core);

    if (s->cpu == NULL) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    s->sdram_size = sdram_size;

    s->sram_size = OMAP15XX_SRAM_SIZE;

    s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0);

    /* Clocks */

    omap_clk_init(s);

    /* Memory-mapped stuff */

    memory_region_allocate_system_memory(&s->emiff_ram, NULL, "omap1.dram",

                                         s->sdram_size);

    memory_region_add_subregion(system_memory, OMAP_EMIFF_BASE, &s->emiff_ram);

    memory_region_init_ram(&s->imif_ram, NULL, "omap1.sram", s->sram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->imif_ram);

    memory_region_add_subregion(system_memory, OMAP_IMIF_BASE, &s->imif_ram);

    omap_clkm_init(system_memory, 0xfffece00, 0xe1008000, s);

    s->ih[0] = qdev_create(NULL, "omap-intc");

    qdev_prop_set_uint32(s->ih[0], "size", 0x100);

    qdev_prop_set_ptr(s->ih[0], "clk", omap_findclk(s, "arminth_ck"));

    qdev_init_nofail(s->ih[0]);

    busdev = SYS_BUS_DEVICE(s->ih[0]);

    sysbus_connect_irq(busdev, 0,

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

    sysbus_connect_irq(busdev, 1,

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

    sysbus_mmio_map(busdev, 0, 0xfffecb00);

    s->ih[1] = qdev_create(NULL, "omap-intc");

    qdev_prop_set_uint32(s->ih[1], "size", 0x800);

    qdev_prop_set_ptr(s->ih[1], "clk", omap_findclk(s, "arminth_ck"));

    qdev_init_nofail(s->ih[1]);

    busdev = SYS_BUS_DEVICE(s->ih[1]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_15XX_IH2_IRQ));

    /* The second interrupt controller's FIQ output is not wired up */

    sysbus_mmio_map(busdev, 0, 0xfffe0000);

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

        dma_irqs[i] = qdev_get_gpio_in(s->ih[omap1_dma_irq_map[i].ih],

                                       omap1_dma_irq_map[i].intr);

    }

    s->dma = omap_dma_init(0xfffed800, dma_irqs, system_memory,

                           qdev_get_gpio_in(s->ih[0], OMAP_INT_DMA_LCD),

                           s, omap_findclk(s, "dma_ck"), omap_dma_3_1);

    s->port[emiff    ].addr_valid = omap_validate_emiff_addr;

    s->port[emifs    ].addr_valid = omap_validate_emifs_addr;

    s->port[imif     ].addr_valid = omap_validate_imif_addr;

    s->port[tipb     ].addr_valid = omap_validate_tipb_addr;

    s->port[local    ].addr_valid = omap_validate_local_addr;

    s->port[tipb_mpui].addr_valid = omap_validate_tipb_mpui_addr;

    /* Register SDRAM and SRAM DMA ports for fast transfers.  */

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->emiff_ram),

                         OMAP_EMIFF_BASE, s->sdram_size);

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->imif_ram),

                         OMAP_IMIF_BASE, s->sram_size);

    s->timer[0] = omap_mpu_timer_init(system_memory, 0xfffec500,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER1),

                    omap_findclk(s, "mputim_ck"));

    s->timer[1] = omap_mpu_timer_init(system_memory, 0xfffec600,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER2),

                    omap_findclk(s, "mputim_ck"));

    s->timer[2] = omap_mpu_timer_init(system_memory, 0xfffec700,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER3),

                    omap_findclk(s, "mputim_ck"));

    s->wdt = omap_wd_timer_init(system_memory, 0xfffec800,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_WD_TIMER),

                    omap_findclk(s, "armwdt_ck"));

    s->os_timer = omap_os_timer_init(system_memory, 0xfffb9000,

                    qdev_get_gpio_in(s->ih[1], OMAP_INT_OS_TIMER),

                    omap_findclk(s, "clk32-kHz"));

    s->lcd = omap_lcdc_init(system_memory, 0xfffec000,

                            qdev_get_gpio_in(s->ih[0], OMAP_INT_LCD_CTRL),

                            omap_dma_get_lcdch(s->dma),

                            omap_findclk(s, "lcd_ck"));

    omap_ulpd_pm_init(system_memory, 0xfffe0800, s);

    omap_pin_cfg_init(system_memory, 0xfffe1000, s);

    omap_id_init(system_memory, s);

    omap_mpui_init(system_memory, 0xfffec900, s);

    s->private_tipb = omap_tipb_bridge_init(system_memory, 0xfffeca00,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_BRIDGE_PRIV),

                    omap_findclk(s, "tipb_ck"));

    s->public_tipb = omap_tipb_bridge_init(system_memory, 0xfffed300,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_BRIDGE_PUB),

                    omap_findclk(s, "tipb_ck"));

    omap_tcmi_init(system_memory, 0xfffecc00, s);

    s->uart[0] = omap_uart_init(0xfffb0000,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_UART1),

                    omap_findclk(s, "uart1_ck"),

                    omap_findclk(s, "uart1_ck"),

                    s->drq[OMAP_DMA_UART1_TX], s->drq[OMAP_DMA_UART1_RX],

                    "uart1",

                    serial_hds[0]);

    s->uart[1] = omap_uart_init(0xfffb0800,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_UART2),

                    omap_findclk(s, "uart2_ck"),

                    omap_findclk(s, "uart2_ck"),

                    s->drq[OMAP_DMA_UART2_TX], s->drq[OMAP_DMA_UART2_RX],

                    "uart2",

                    serial_hds[0] ? serial_hds[1] : NULL);

    s->uart[2] = omap_uart_init(0xfffb9800,

                                qdev_get_gpio_in(s->ih[0], OMAP_INT_UART3),

                    omap_findclk(s, "uart3_ck"),

                    omap_findclk(s, "uart3_ck"),

                    s->drq[OMAP_DMA_UART3_TX], s->drq[OMAP_DMA_UART3_RX],

                    "uart3",

                    serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);

    s->dpll[0] = omap_dpll_init(system_memory, 0xfffecf00,

                                omap_findclk(s, "dpll1"));

    s->dpll[1] = omap_dpll_init(system_memory, 0xfffed000,

                                omap_findclk(s, "dpll2"));

    s->dpll[2] = omap_dpll_init(system_memory, 0xfffed100,

                                omap_findclk(s, "dpll3"));

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = omap_mmc_init(0xfffb7800, system_memory,

                           blk_by_legacy_dinfo(dinfo),

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_OQN),

                           &s->drq[OMAP_DMA_MMC_TX],

                    omap_findclk(s, "mmc_ck"));

    s->mpuio = omap_mpuio_init(system_memory, 0xfffb5000,

                               qdev_get_gpio_in(s->ih[1], OMAP_INT_KEYBOARD),

                               qdev_get_gpio_in(s->ih[1], OMAP_INT_MPUIO),

                               s->wakeup, omap_findclk(s, "clk32-kHz"));

    s->gpio = qdev_create(NULL, "omap-gpio");

    qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);

    qdev_prop_set_ptr(s->gpio, "clk", omap_findclk(s, "arm_gpio_ck"));

    qdev_init_nofail(s->gpio);

    sysbus_connect_irq(SYS_BUS_DEVICE(s->gpio), 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_GPIO_BANK1));

    sysbus_mmio_map(SYS_BUS_DEVICE(s->gpio), 0, 0xfffce000);

    s->microwire = omap_uwire_init(system_memory, 0xfffb3000,

                                   qdev_get_gpio_in(s->ih[1], OMAP_INT_uWireTX),

                                   qdev_get_gpio_in(s->ih[1], OMAP_INT_uWireRX),

                    s->drq[OMAP_DMA_UWIRE_TX], omap_findclk(s, "mpuper_ck"));

    s->pwl = omap_pwl_init(system_memory, 0xfffb5800,

                           omap_findclk(s, "armxor_ck"));

    s->pwt = omap_pwt_init(system_memory, 0xfffb6000,

                           omap_findclk(s, "armxor_ck"));

    s->i2c[0] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[0], "revision", 0x11);

    qdev_prop_set_ptr(s->i2c[0], "fclk", omap_findclk(s, "mpuper_ck"));

    qdev_init_nofail(s->i2c[0]);

    busdev = SYS_BUS_DEVICE(s->i2c[0]);

    sysbus_connect_irq(busdev, 0, qdev_get_gpio_in(s->ih[1], OMAP_INT_I2C));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP_DMA_I2C_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP_DMA_I2C_RX]);

    sysbus_mmio_map(busdev, 0, 0xfffb3800);

    s->rtc = omap_rtc_init(system_memory, 0xfffb4800,

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_RTC_TIMER),

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_RTC_ALARM),

                    omap_findclk(s, "clk32-kHz"));

    s->mcbsp1 = omap_mcbsp_init(system_memory, 0xfffb1800,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP1TX),

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP1RX),

                    &s->drq[OMAP_DMA_MCBSP1_TX], omap_findclk(s, "dspxor_ck"));

    s->mcbsp2 = omap_mcbsp_init(system_memory, 0xfffb1000,

                                qdev_get_gpio_in(s->ih[0],

                                                 OMAP_INT_310_McBSP2_TX),

                                qdev_get_gpio_in(s->ih[0],

                                                 OMAP_INT_310_McBSP2_RX),

                    &s->drq[OMAP_DMA_MCBSP2_TX], omap_findclk(s, "mpuper_ck"));

    s->mcbsp3 = omap_mcbsp_init(system_memory, 0xfffb7000,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP3TX),

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP3RX),

                    &s->drq[OMAP_DMA_MCBSP3_TX], omap_findclk(s, "dspxor_ck"));

    s->led[0] = omap_lpg_init(system_memory,

                              0xfffbd000, omap_findclk(s, "clk32-kHz"));

    s->led[1] = omap_lpg_init(system_memory,

                              0xfffbd800, omap_findclk(s, "clk32-kHz"));

    /* Register mappings not currenlty implemented:

     * MCSI2 Comm	fffb2000 - fffb27ff (not mapped on OMAP310)

     * MCSI1 Bluetooth	fffb2800 - fffb2fff (not mapped on OMAP310)

     * USB W2FC		fffb4000 - fffb47ff

     * Camera Interface	fffb6800 - fffb6fff

     * USB Host		fffba000 - fffba7ff

     * FAC		fffba800 - fffbafff

     * HDQ/1-Wire	fffbc000 - fffbc7ff

     * TIPB switches	fffbc800 - fffbcfff

     * Mailbox		fffcf000 - fffcf7ff

     * Local bus IF	fffec100 - fffec1ff

     * Local bus MMU	fffec200 - fffec2ff

     * DSP MMU		fffed200 - fffed2ff

     */

    omap_setup_dsp_mapping(system_memory, omap15xx_dsp_mm);

    omap_setup_mpui_io(system_memory, s);

    qemu_register_reset(omap1_mpu_reset, s);

    return s;

}


static void decode_scaling_list(GetBitContext *gb, uint8_t *factors, int size,

                                const uint8_t *jvt_list,

                                const uint8_t *fallback_list)

{

    int i, last = 8, next = 8;

    const uint8_t *scan = size == 16 ? ff_zigzag_scan : ff_zigzag_direct;

    if (!get_bits1(gb)) /* matrix not written, we use the predicted one */

        memcpy(factors, fallback_list, size * sizeof(uint8_t));

    else

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

            if (next)

                next = (last + get_se_golomb(gb)) & 0xff;

            if (!i && !next) { /* matrix not written, we use the preset one */

                memcpy(factors, jvt_list, size * sizeof(uint8_t));

                break;

            }

            last = factors[scan[i]] = next ? next : last;

        }

}


PCIDevice *virtio_net_init(PCIBus *bus, NICInfo *nd, int devfn)

{

    VirtIONet *n;

    static int virtio_net_id;

    n = (VirtIONet *)virtio_init_pci(bus, "virtio-net", 6900, 0x1000,

                                     0, VIRTIO_ID_NET,

                                     0x02, 0x00, 0x00,

                                     6, sizeof(VirtIONet));

    if (!n)

        return NULL;

    n->vdev.get_config = virtio_net_update_config;

    n->vdev.get_features = virtio_net_get_features;

    n->vdev.set_features = virtio_net_set_features;

    n->rx_vq = virtio_add_queue(&n->vdev, 256, virtio_net_handle_rx);

    n->tx_vq = virtio_add_queue(&n->vdev, 256, virtio_net_handle_tx);

    memcpy(n->mac, nd->macaddr, 6);

    n->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                 virtio_net_receive, virtio_net_can_receive, n);

    qemu_format_nic_info_str(n->vc, n->mac);

    n->tx_timer = qemu_new_timer(vm_clock, virtio_net_tx_timer, n);

    n->tx_timer_active = 0;

    n->mergeable_rx_bufs = 0;

    register_savevm("virtio-net", virtio_net_id++, 2,

                    virtio_net_save, virtio_net_load, n);

    return (PCIDevice *)n;

}


CharDriverState *chr_baum_init(void)

{

    BaumDriverState *baum;

    CharDriverState *chr;

    brlapi_handle_t *handle;

#ifdef CONFIG_SDL

    SDL_SysWMinfo info;

#endif

    int tty;

    baum = g_malloc0(sizeof(BaumDriverState));

    baum->chr = chr = g_malloc0(sizeof(CharDriverState));

    chr->opaque = baum;

    chr->chr_write = baum_write;

    chr->chr_accept_input = baum_accept_input;

    chr->chr_close = baum_close;

    handle = g_malloc0(brlapi_getHandleSize());

    baum->brlapi = handle;

    baum->brlapi_fd = brlapi__openConnection(handle, NULL, NULL);

    if (baum->brlapi_fd == -1) {

        brlapi_perror("baum_init: brlapi_openConnection");

        goto fail_handle;

    }

    baum->cellCount_timer = qemu_new_timer_ns(vm_clock, baum_cellCount_timer_cb, baum);

    if (brlapi__getDisplaySize(handle, &baum->x, &baum->y) == -1) {

        brlapi_perror("baum_init: brlapi_getDisplaySize");

        goto fail;

    }

#ifdef CONFIG_SDL

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

    SDL_VERSION(&info.version);

    if (SDL_GetWMInfo(&info))

        tty = info.info.x11.wmwindow;

    else

#endif

        tty = BRLAPI_TTY_DEFAULT;

    if (brlapi__enterTtyMode(handle, tty, NULL) == -1) {

        brlapi_perror("baum_init: brlapi_enterTtyMode");

        goto fail;

    }

    qemu_set_fd_handler(baum->brlapi_fd, baum_chr_read, NULL, baum);

    qemu_chr_be_generic_open(chr);

    return chr;

fail:

    qemu_free_timer(baum->cellCount_timer);

    brlapi__closeConnection(handle);

fail_handle:

    g_free(handle);

    g_free(chr);

    g_free(baum);

    return NULL;

}


static int all_vcpus_paused(void)

{

    CPUState *penv = first_cpu;

    while (penv) {

        if (!penv->stopped)

            return 0;

        penv = (CPUState *)penv->next_cpu;

    }

    return 1;

}


uint32_t lm4549_read(lm4549_state *s, target_phys_addr_t offset)

{

    uint16_t *regfile = s->regfile;

    uint32_t value = 0;

    /* Read the stored value */

    assert(offset < 128);

    value = regfile[offset];

    DPRINTF("read [0x%02x] = 0x%04x\n", offset, value);

    return value;

}


static void kvm_log_stop(MemoryListener *listener,

                          MemoryRegionSection *section)

{

    int r;

    r = kvm_dirty_pages_log_change(section->offset_within_address_space,

                                   int128_get64(section->size), false);

    if (r < 0) {

        abort();

    }

}