static inline void unpack_coeffs(SnowContext *s, SubBand *b, SubBand * parent, int orientation){

    const int w= b->width;

    const int h= b->height;

    int x,y;

    if(1){

        int run;

        x_and_coeff *xc= b->x_coeff;

        x_and_coeff *prev_xc= NULL;

        x_and_coeff *prev2_xc= xc;

        x_and_coeff *parent_xc= parent ? parent->x_coeff : NULL;

        x_and_coeff *prev_parent_xc= parent_xc;

        run= get_symbol2(&s->c, b->state[1], 3);

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

            int v=0;

            int lt=0, t=0, rt=0;

            if(y && prev_xc->x == 0){

                rt= prev_xc->coeff;

            }

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

                int p=0;

                const int l= v;

                lt= t; t= rt;

                if(y){

                    if(prev_xc->x <= x)

                        prev_xc++;

                    if(prev_xc->x == x + 1)

                        rt= prev_xc->coeff;

                    else

                        rt=0;

                }

                if(parent_xc){

                    if(x>>1 > parent_xc->x){

                        parent_xc++;

                    }

                    if(x>>1 == parent_xc->x){

                        p= parent_xc->coeff;

                    }

                }

                if(/*ll|*/l|lt|t|rt|p){

                    int context= av_log2(/*ABS(ll) + */3*(l>>1) + (lt>>1) + (t&~1) + (rt>>1) + (p>>1));

                    v=get_rac(&s->c, &b->state[0][context]);

                    if(v){

                        v= 2*(get_symbol2(&s->c, b->state[context + 2], context-4) + 1);

                        v+=get_rac(&s->c, &b->state[0][16 + 1 + 3 + quant3bA[l&0xFF] + 3*quant3bA[t&0xFF]]);

                        xc->x=x;

                        (xc++)->coeff= v;

                    }

                }else{

                    if(!run){

                        run= get_symbol2(&s->c, b->state[1], 3);

                        v= 2*(get_symbol2(&s->c, b->state[0 + 2], 0-4) + 1);

                        v+=get_rac(&s->c, &b->state[0][16 + 1 + 3]);

                        xc->x=x;

                        (xc++)->coeff= v;

                    }else{

                        int max_run;

                        run--;

                        v=0;

                        if(y) max_run= FFMIN(run, prev_xc->x - x - 2);

                        else  max_run= FFMIN(run, w-x-1);

                        if(parent_xc)

                            max_run= FFMIN(max_run, 2*parent_xc->x - x - 1);

                        x+= max_run;

                        run-= max_run;

                    }

                }

            }

            (xc++)->x= w+1; //end marker

            prev_xc= prev2_xc;

            prev2_xc= xc;

            if(parent_xc){

                if(y&1){

                    while(parent_xc->x != parent->width+1)

                        parent_xc++;

                    parent_xc++;

                    prev_parent_xc= parent_xc;

                }else{

                    parent_xc= prev_parent_xc;

                }

            }

        }

        (xc++)->x= w+1; //end marker

    }

}


static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    VmncContext * const c = avctx->priv_data;

    GetByteContext *gb = &c->gb;

    uint8_t *outptr;

    int dx, dy, w, h, depth, enc, chunks, res, size_left, ret;

    if ((ret = ff_reget_buffer(avctx, c->pic)) < 0) {

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

        return ret;

    }

    bytestream2_init(gb, buf, buf_size);

    c->pic->key_frame = 0;

    c->pic->pict_type = AV_PICTURE_TYPE_P;

    // restore screen after cursor

    if (c->screendta) {

        int i;

        w = c->cur_w;

        if (c->width < c->cur_x + w)

            w = c->width - c->cur_x;

        h = c->cur_h;

        if (c->height < c->cur_y + h)

            h = c->height - c->cur_y;

        dx = c->cur_x;

        if (dx < 0) {

            w += dx;

            dx = 0;

        }

        dy = c->cur_y;

        if (dy < 0) {

            h += dy;

            dy = 0;

        }

        if ((w > 0) && (h > 0)) {

            outptr = c->pic->data[0] + dx * c->bpp2 + dy * c->pic->linesize[0];

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

                memcpy(outptr, c->screendta + i * c->cur_w * c->bpp2,

                       w * c->bpp2);

                outptr += c->pic->linesize[0];

            }

        }

    }

    bytestream2_skip(gb, 2);

    chunks = bytestream2_get_be16(gb);

    while (chunks--) {

        dx  = bytestream2_get_be16(gb);

        dy  = bytestream2_get_be16(gb);

        w   = bytestream2_get_be16(gb);

        h   = bytestream2_get_be16(gb);

        enc = bytestream2_get_be32(gb);

        outptr = c->pic->data[0] + dx * c->bpp2 + dy * c->pic->linesize[0];

        size_left = bytestream2_get_bytes_left(gb);

        switch (enc) {

        case MAGIC_WMVd: // cursor

            if (size_left < 2 + w * h * c->bpp2 * 2) {

                av_log(avctx, AV_LOG_ERROR,

                       "Premature end of data! (need %i got %i)\n",

                       2 + w * h * c->bpp2 * 2, size_left);

                return AVERROR_INVALIDDATA;

            }

            bytestream2_skip(gb, 2);

            c->cur_w  = w;

            c->cur_h  = h;

            c->cur_hx = dx;

            c->cur_hy = dy;

            if ((c->cur_hx > c->cur_w) || (c->cur_hy > c->cur_h)) {

                av_log(avctx, AV_LOG_ERROR,

                       "Cursor hot spot is not in image: "

                       "%ix%i of %ix%i cursor size\n",

                       c->cur_hx, c->cur_hy, c->cur_w, c->cur_h);

                c->cur_hx = c->cur_hy = 0;

            }

            if (c->cur_w * c->cur_h >= INT_MAX / c->bpp2) {

                reset_buffers(c);

                return AVERROR(EINVAL);

            } else {

                int screen_size = c->cur_w * c->cur_h * c->bpp2;

                if ((ret = av_reallocp(&c->curbits, screen_size)) < 0 ||

                    (ret = av_reallocp(&c->curmask, screen_size)) < 0 ||

                    (ret = av_reallocp(&c->screendta, screen_size)) < 0) {

                    reset_buffers(c);

                    return ret;

                }

            }

            load_cursor(c);

            break;

        case MAGIC_WMVe: // unknown

            bytestream2_skip(gb, 2);

            break;

        case MAGIC_WMVf: // update cursor position

            c->cur_x = dx - c->cur_hx;

            c->cur_y = dy - c->cur_hy;

            break;

        case MAGIC_WMVg: // unknown

            bytestream2_skip(gb, 10);

            break;

        case MAGIC_WMVh: // unknown

            bytestream2_skip(gb, 4);

            break;

        case MAGIC_WMVi: // ServerInitialization struct

            c->pic->key_frame = 1;

            c->pic->pict_type = AV_PICTURE_TYPE_I;

            depth = bytestream2_get_byte(gb);

            if (depth != c->bpp) {

                av_log(avctx, AV_LOG_INFO,

                       "Depth mismatch. Container %i bpp, "

                       "Frame data: %i bpp\n",

                       c->bpp, depth);

            }

            bytestream2_skip(gb, 1);

            c->bigendian = bytestream2_get_byte(gb);

            if (c->bigendian & (~1)) {

                av_log(avctx, AV_LOG_INFO,

                       "Invalid header: bigendian flag = %i\n", c->bigendian);

                return AVERROR_INVALIDDATA;

            }

            //skip the rest of pixel format data

            bytestream2_skip(gb, 13);

            break;

        case MAGIC_WMVj: // unknown

            bytestream2_skip(gb, 2);

            break;

        case 0x00000000: // raw rectangle data

            if ((dx + w > c->width) || (dy + h > c->height)) {

                av_log(avctx, AV_LOG_ERROR,

                       "Incorrect frame size: %ix%i+%ix%i of %ix%i\n",

                       w, h, dx, dy, c->width, c->height);

                return AVERROR_INVALIDDATA;

            }

            if (size_left < w * h * c->bpp2) {

                av_log(avctx, AV_LOG_ERROR,

                       "Premature end of data! (need %i got %i)\n",

                       w * h * c->bpp2, size_left);

                return AVERROR_INVALIDDATA;

            }

            paint_raw(outptr, w, h, gb, c->bpp2, c->bigendian,

                      c->pic->linesize[0]);

            break;

        case 0x00000005: // HexTile encoded rectangle

            if ((dx + w > c->width) || (dy + h > c->height)) {

                av_log(avctx, AV_LOG_ERROR,

                       "Incorrect frame size: %ix%i+%ix%i of %ix%i\n",

                       w, h, dx, dy, c->width, c->height);

                return AVERROR_INVALIDDATA;

            }

            res = decode_hextile(c, outptr, gb, w, h, c->pic->linesize[0]);

            if (res < 0)

                return res;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported block type 0x%08X\n", enc);

            chunks = 0; // leave chunks decoding loop

        }

    }

    if (c->screendta) {

        int i;

        // save screen data before painting cursor

        w = c->cur_w;

        if (c->width < c->cur_x + w)

            w = c->width - c->cur_x;

        h = c->cur_h;

        if (c->height < c->cur_y + h)

            h = c->height - c->cur_y;

        dx = c->cur_x;

        if (dx < 0) {

            w += dx;

            dx = 0;

        }

        dy = c->cur_y;

        if (dy < 0) {

            h += dy;

            dy = 0;

        }

        if ((w > 0) && (h > 0)) {

            outptr = c->pic->data[0] + dx * c->bpp2 + dy * c->pic->linesize[0];

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

                memcpy(c->screendta + i * c->cur_w * c->bpp2, outptr,

                       w * c->bpp2);

                outptr += c->pic->linesize[0];

            }

            outptr = c->pic->data[0];

            put_cursor(outptr, c->pic->linesize[0], c, c->cur_x, c->cur_y);

        }

    }

    *got_frame = 1;

    if ((ret = av_frame_ref(data, c->pic)) < 0)

        return ret;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


void ff_fft_calc_sse(FFTContext *s, FFTComplex *z)

{

    int ln = s->nbits;

    long i, j;

    long nblocks, nloops;

    FFTComplex *p, *cptr;

    asm volatile(

        "movaps %0, %%xmm4 \n\t"

        "movaps %1, %%xmm5 \n\t"

        ::"m"(*p1p1m1m1),

          "m"(*(s->inverse ? p1p1m1p1 : p1p1p1m1))

    );

    i = 8 << ln;

    asm volatile(

        "1: \n\t"

        "sub $32, %0 \n\t"

        /* do the pass 0 butterfly */

        "movaps   (%0,%1), %%xmm0 \n\t"

        "movaps    %%xmm0, %%xmm1 \n\t"

        "shufps     $0x4E, %%xmm0, %%xmm0 \n\t"

        "xorps     %%xmm4, %%xmm1 \n\t"

        "addps     %%xmm1, %%xmm0 \n\t"

        "movaps 16(%0,%1), %%xmm2 \n\t"

        "movaps    %%xmm2, %%xmm3 \n\t"

        "shufps     $0x4E, %%xmm2, %%xmm2 \n\t"

        "xorps     %%xmm4, %%xmm3 \n\t"

        "addps     %%xmm3, %%xmm2 \n\t"

        /* multiply third by -i */

        /* by toggling the sign bit */

        "shufps     $0xB4, %%xmm2, %%xmm2 \n\t"

        "xorps     %%xmm5, %%xmm2 \n\t"

        /* do the pass 1 butterfly */

        "movaps    %%xmm0, %%xmm1 \n\t"

        "addps     %%xmm2, %%xmm0 \n\t"

        "subps     %%xmm2, %%xmm1 \n\t"

        "movaps    %%xmm0,   (%0,%1) \n\t"

        "movaps    %%xmm1, 16(%0,%1) \n\t"

        "jg 1b \n\t"

        :"+r"(i)

        :"r"(z)

    );

    /* pass 2 .. ln-1 */

    nblocks = 1 << (ln-3);

    nloops = 1 << 2;

    cptr = s->exptab1;

    do {

        p = z;

        j = nblocks;

        do {

            i = nloops*8;

            asm volatile(

                "1: \n\t"

                "sub $16, %0 \n\t"

                "movaps    (%2,%0), %%xmm1 \n\t"

                "movaps    (%1,%0), %%xmm0 \n\t"

                "movaps     %%xmm1, %%xmm2 \n\t"

                "shufps      $0xA0, %%xmm1, %%xmm1 \n\t"

                "shufps      $0xF5, %%xmm2, %%xmm2 \n\t"

                "mulps   (%3,%0,2), %%xmm1 \n\t" //  cre*re cim*re

                "mulps 16(%3,%0,2), %%xmm2 \n\t" // -cim*im cre*im

                "addps      %%xmm2, %%xmm1 \n\t"

                "movaps     %%xmm0, %%xmm3 \n\t"

                "addps      %%xmm1, %%xmm0 \n\t"

                "subps      %%xmm1, %%xmm3 \n\t"

                "movaps     %%xmm0, (%1,%0) \n\t"

                "movaps     %%xmm3, (%2,%0) \n\t"

                "jg 1b \n\t"

                :"+r"(i)

                :"r"(p), "r"(p + nloops), "r"(cptr)

            );

            p += nloops*2;

        } while (--j);

        cptr += nloops*2;

        nblocks >>= 1;

        nloops <<= 1;

    } while (nblocks != 0);

}


static av_cold int cfhd_decode_init(AVCodecContext *avctx)

{

    CFHDContext *s = avctx->priv_data;

    avctx->bits_per_raw_sample = 10;

    s->avctx                   = avctx;

    avctx->width               = 0;

    avctx->height              = 0;

    return ff_cfhd_init_vlcs(s);

}


static int dump_init(DumpState *s, int fd, bool paging, bool has_filter,

                     int64_t begin, int64_t length, Error **errp)

{

    CPUState *cpu;

    int nr_cpus;

    Error *err = NULL;

    int ret;

    if (runstate_is_running()) {

        vm_stop(RUN_STATE_SAVE_VM);

        s->resume = true;

    } else {

        s->resume = false;

    }

    /* If we use KVM, we should synchronize the registers before we get dump

     * info or physmap info.

     */

    cpu_synchronize_all_states();

    nr_cpus = 0;

    for (cpu = first_cpu; cpu != NULL; cpu = cpu->next_cpu) {

        nr_cpus++;

    }

    s->errp = errp;

    s->fd = fd;

    s->has_filter = has_filter;

    s->begin = begin;

    s->length = length;

    guest_phys_blocks_init(&s->guest_phys_blocks);

    /* FILL LIST */

    s->start = get_start_block(s);

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

        error_set(errp, QERR_INVALID_PARAMETER, "begin");

        goto cleanup;

    }

    /* get dump info: endian, class and architecture.

     * If the target architecture is not supported, cpu_get_dump_info() will

     * return -1.

     */

    ret = cpu_get_dump_info(&s->dump_info);

    if (ret < 0) {

        error_set(errp, QERR_UNSUPPORTED);

        goto cleanup;

    }

    s->note_size = cpu_get_note_size(s->dump_info.d_class,

                                     s->dump_info.d_machine, nr_cpus);

    if (ret < 0) {

        error_set(errp, QERR_UNSUPPORTED);

        goto cleanup;

    }

    /* get memory mapping */

    memory_mapping_list_init(&s->list);

    if (paging) {

        qemu_get_guest_memory_mapping(&s->list, &err);

        if (err != NULL) {

            error_propagate(errp, err);

            goto cleanup;

        }

    } else {

        qemu_get_guest_simple_memory_mapping(&s->list);

    }

    if (s->has_filter) {

        memory_mapping_filter(&s->list, s->begin, s->length);

    }

    /*

     * calculate phdr_num

     *

     * the type of ehdr->e_phnum is uint16_t, so we should avoid overflow

     */

    s->phdr_num = 1; /* PT_NOTE */

    if (s->list.num < UINT16_MAX - 2) {

        s->phdr_num += s->list.num;

        s->have_section = false;

    } else {

        s->have_section = true;

        s->phdr_num = PN_XNUM;

        s->sh_info = 1; /* PT_NOTE */

        /* the type of shdr->sh_info is uint32_t, so we should avoid overflow */

        if (s->list.num <= UINT32_MAX - 1) {

            s->sh_info += s->list.num;

        } else {

            s->sh_info = UINT32_MAX;

        }

    }

    if (s->dump_info.d_class == ELFCLASS64) {

        if (s->have_section) {

            s->memory_offset = sizeof(Elf64_Ehdr) +

                               sizeof(Elf64_Phdr) * s->sh_info +

                               sizeof(Elf64_Shdr) + s->note_size;

        } else {

            s->memory_offset = sizeof(Elf64_Ehdr) +

                               sizeof(Elf64_Phdr) * s->phdr_num + s->note_size;

        }

    } else {

        if (s->have_section) {

            s->memory_offset = sizeof(Elf32_Ehdr) +

                               sizeof(Elf32_Phdr) * s->sh_info +

                               sizeof(Elf32_Shdr) + s->note_size;

        } else {

            s->memory_offset = sizeof(Elf32_Ehdr) +

                               sizeof(Elf32_Phdr) * s->phdr_num + s->note_size;

        }

    }

    return 0;

cleanup:

    guest_phys_blocks_free(&s->guest_phys_blocks);

    if (s->resume) {

        vm_start();

    }

    return -1;

}


qemu_irq xics_assign_irq(struct icp_state *icp, int irq,

                         enum xics_irq_type type)

{

    if ((irq < icp->ics->offset)

        || (irq >= (icp->ics->offset + icp->ics->nr_irqs))) {

        return NULL;

    }

    assert((type == XICS_MSI) || (type == XICS_LSI));

    icp->ics->irqs[irq - icp->ics->offset].type = type;

    return icp->ics->qirqs[irq - icp->ics->offset];

}


int load_aout(const char *filename, target_phys_addr_t addr, int max_sz,

              int bswap_needed, target_phys_addr_t target_page_size)

{

    int fd, size, ret;

    struct exec e;

    uint32_t magic;

    fd = open(filename, O_RDONLY | O_BINARY);

    if (fd < 0)

        return -1;

    size = read(fd, &e, sizeof(e));

    if (size < 0)

        goto fail;

    if (bswap_needed) {

        bswap_ahdr(&e);

    }

    magic = N_MAGIC(e);

    switch (magic) {

    case ZMAGIC:

    case QMAGIC:

    case OMAGIC:

        if (e.a_text + e.a_data > max_sz)

            goto fail;

	lseek(fd, N_TXTOFF(e), SEEK_SET);

	size = read_targphys(fd, addr, e.a_text + e.a_data);

	if (size < 0)

	    goto fail;

	break;

    case NMAGIC:

        if (N_DATADDR(e, target_page_size) + e.a_data > max_sz)

            goto fail;

	lseek(fd, N_TXTOFF(e), SEEK_SET);

	size = read_targphys(fd, addr, e.a_text);

	if (size < 0)

	    goto fail;

        ret = read_targphys(fd, addr + N_DATADDR(e, target_page_size),

                            e.a_data);

	if (ret < 0)

	    goto fail;

	size += ret;

	break;

    default:

	goto fail;

    }

    close(fd);

    return size;

 fail:

    close(fd);

    return -1;

}


SH7750State *sh7750_init(CPUSH4State * cpu)

{

    SH7750State *s;

    int sh7750_io_memory;

    int cpu_model = SH_CPU_SH7751R; /* for now */

    s = qemu_mallocz(sizeof(SH7750State));

    s->cpu = cpu;

    s->periph_freq = 60000000;	/* 60MHz */

    sh7750_io_memory = cpu_register_io_memory(0,

					      sh7750_mem_read,

					      sh7750_mem_write, s);

    cpu_register_physical_memory(0x1c000000, 0x04000000, sh7750_io_memory);

    sh_intc_init(&s->intc, NR_SOURCES,

		 _INTC_ARRAY(mask_registers),

		 _INTC_ARRAY(prio_registers));

    sh_intc_register_sources(&s->intc,

			     _INTC_ARRAY(vectors),

			     _INTC_ARRAY(groups));

    sh_serial_init(0x1fe00000, 0, s->periph_freq, serial_hds[0]);

    sh_serial_init(0x1fe80000, SH_SERIAL_FEAT_SCIF,

		   s->periph_freq, serial_hds[1]);

    tmu012_init(0x1fd80000,

		TMU012_FEAT_TOCR | TMU012_FEAT_3CHAN | TMU012_FEAT_EXTCLK,

		s->periph_freq);

    if (cpu_model & (SH_CPU_SH7750 | SH_CPU_SH7750S | SH_CPU_SH7751)) {

        sh_intc_register_sources(&s->intc,

				 _INTC_ARRAY(vectors_dma4),

				 _INTC_ARRAY(groups_dma4));

    }

    if (cpu_model & (SH_CPU_SH7750R | SH_CPU_SH7751R)) {

        sh_intc_register_sources(&s->intc,

				 _INTC_ARRAY(vectors_dma8),

				 _INTC_ARRAY(groups_dma8));

    }

    if (cpu_model & (SH_CPU_SH7750R | SH_CPU_SH7751 | SH_CPU_SH7751R)) {

        sh_intc_register_sources(&s->intc,

				 _INTC_ARRAY(vectors_tmu34),

				 _INTC_ARRAY(NULL));

        tmu012_init(0x1e100000, 0, s->periph_freq);

    }

    if (cpu_model & (SH_CPU_SH7751_ALL)) {

        sh_intc_register_sources(&s->intc,

				 _INTC_ARRAY(vectors_pci),

				 _INTC_ARRAY(groups_pci));

    }

    if (cpu_model & (SH_CPU_SH7750S | SH_CPU_SH7750R | SH_CPU_SH7751_ALL)) {

        sh_intc_register_sources(&s->intc,

				 _INTC_ARRAY(vectors_irlm),

				 _INTC_ARRAY(NULL));

    }

    return s;

}


static void *buffered_file_thread(void *opaque)

{

    MigrationState *s = opaque;

    int64_t initial_time = qemu_get_clock_ms(rt_clock);

    int64_t sleep_time = 0;

    int64_t max_size = 0;

    bool last_round = false;

    int ret;

    qemu_mutex_lock_iothread();

    DPRINTF("beginning savevm\n");

    ret = qemu_savevm_state_begin(s->file, &s->params);

    qemu_mutex_unlock_iothread();

    while (ret >= 0) {

        int64_t current_time;

        uint64_t pending_size;

        qemu_mutex_lock_iothread();

        if (s->state != MIG_STATE_ACTIVE) {

            DPRINTF("put_ready returning because of non-active state\n");

            qemu_mutex_unlock_iothread();

            break;

        }

        if (s->complete) {

            qemu_mutex_unlock_iothread();

            break;

        }

        if (s->bytes_xfer < s->xfer_limit) {

            DPRINTF("iterate\n");

            pending_size = qemu_savevm_state_pending(s->file, max_size);

            DPRINTF("pending size %lu max %lu\n", pending_size, max_size);

            if (pending_size && pending_size >= max_size) {

                ret = qemu_savevm_state_iterate(s->file);

                if (ret < 0) {

                    qemu_mutex_unlock_iothread();

                    break;

                }

            } else {

                int old_vm_running = runstate_is_running();

                int64_t start_time, end_time;

                DPRINTF("done iterating\n");

                start_time = qemu_get_clock_ms(rt_clock);

                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);

                vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);

                ret = qemu_savevm_state_complete(s->file);

                if (ret < 0) {

                    qemu_mutex_unlock_iothread();

                    break;

                } else {

                    migrate_fd_completed(s);

                }

                end_time = qemu_get_clock_ms(rt_clock);

                s->total_time = end_time - s->total_time;

                s->downtime = end_time - start_time;

                if (s->state != MIG_STATE_COMPLETED) {

                    if (old_vm_running) {

                        vm_start();

                    }

                }

                last_round = true;

            }

        }

        qemu_mutex_unlock_iothread();

        current_time = qemu_get_clock_ms(rt_clock);

        if (current_time >= initial_time + BUFFER_DELAY) {

            uint64_t transferred_bytes = s->bytes_xfer;

            uint64_t time_spent = current_time - initial_time - sleep_time;

            double bandwidth = transferred_bytes / time_spent;

            max_size = bandwidth * migrate_max_downtime() / 1000000;

            DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64

                    " bandwidth %g max_size %" PRId64 "\n",

                    transferred_bytes, time_spent, bandwidth, max_size);

            /* if we haven't sent anything, we don't want to recalculate

               10000 is a small enough number for our purposes */

            if (s->dirty_bytes_rate && transferred_bytes > 10000) {

                s->expected_downtime = s->dirty_bytes_rate / bandwidth;

            }

            s->bytes_xfer = 0;

            sleep_time = 0;

            initial_time = current_time;

        }

        if (!last_round && (s->bytes_xfer >= s->xfer_limit)) {

            /* usleep expects microseconds */

            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);

            sleep_time += qemu_get_clock_ms(rt_clock) - current_time;

        }

        buffered_flush(s);

        ret = qemu_file_get_error(s->file);

    }

    if (ret < 0) {

        migrate_fd_error(s);

    }

    g_free(s->buffer);

    return NULL;

}


static void test_qemu_strtoul_trailing(void)

{

    const char *str = "123xxx";

    char f = 'X';

    const char *endptr = &f;

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + 3);

}


static inline void downmix_3f_2r_to_stereo(float *samples)

{

    int i;

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

        samples[i] += (samples[i + 256] + samples[i + 768]);

        samples[i + 256] = (samples[i + 512] + samples[i + 1024]);

        samples[i + 512] = samples[i + 768] = samples[i + 1024] = 0;

    }

}


static void mirror_write_complete(void *opaque, int ret)

{

    MirrorOp *op = opaque;

    MirrorBlockJob *s = op->s;

    aio_context_acquire(blk_get_aio_context(s->common.blk));

    if (ret < 0) {

        BlockErrorAction action;

        bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);

        action = mirror_error_action(s, false, -ret);

        if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {

            s->ret = ret;

        }

    }

    mirror_iteration_done(op, ret);

    aio_context_release(blk_get_aio_context(s->common.blk));

}


static void qemu_remap_bucket(MapCacheEntry *entry,

                              target_phys_addr_t size,

                              target_phys_addr_t address_index)

{

    uint8_t *vaddr_base;

    xen_pfn_t *pfns;

    int *err;

    unsigned int i, j;

    target_phys_addr_t nb_pfn = size >> XC_PAGE_SHIFT;

    trace_qemu_remap_bucket(address_index);

    pfns = qemu_mallocz(nb_pfn * sizeof (xen_pfn_t));

    err = qemu_mallocz(nb_pfn * sizeof (int));

    if (entry->vaddr_base != NULL) {

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

            perror("unmap fails");

            exit(-1);

        }

    }

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

        pfns[i] = (address_index << (MCACHE_BUCKET_SHIFT-XC_PAGE_SHIFT)) + i;

    }

    vaddr_base = xc_map_foreign_bulk(xen_xc, xen_domid, PROT_READ|PROT_WRITE,

                                     pfns, err, nb_pfn);

    if (vaddr_base == NULL) {

        perror("xc_map_foreign_bulk");

        exit(-1);

    }

    entry->vaddr_base = vaddr_base;

    entry->paddr_index = address_index;

    for (i = 0; i < nb_pfn; i += BITS_PER_LONG) {

        unsigned long word = 0;

        if ((i + BITS_PER_LONG) > nb_pfn) {

            j = nb_pfn % BITS_PER_LONG;

        } else {

            j = BITS_PER_LONG;

        }

        while (j > 0) {

            word = (word << 1) | !err[i + --j];

        }

        entry->valid_mapping[i / BITS_PER_LONG] = word;

    }

    qemu_free(pfns);

    qemu_free(err);

}


uint64_t kvmppc_hash64_read_pteg(PowerPCCPU *cpu, target_ulong pte_index)

{

    int htab_fd;

    struct kvm_get_htab_fd ghf;

    struct kvm_get_htab_buf  *hpte_buf;

    ghf.flags = 0;

    ghf.start_index = pte_index;

    htab_fd = kvm_vm_ioctl(kvm_state, KVM_PPC_GET_HTAB_FD, &ghf);

    if (htab_fd < 0) {

        goto error_out;

    }

    hpte_buf = g_malloc0(sizeof(*hpte_buf));

    /*

     * Read the hpte group

     */

    if (read(htab_fd, hpte_buf, sizeof(*hpte_buf)) < 0) {

        goto out_close;

    }

    close(htab_fd);

    return (uint64_t)(uintptr_t) hpte_buf->hpte;

out_close:

    g_free(hpte_buf);

    close(htab_fd);

error_out:

    return 0;

}


static void xenfb_guest_copy(struct XenFB *xenfb, int x, int y, int w, int h)

{

    DisplaySurface *surface = qemu_console_surface(xenfb->c.con);

    int line, oops = 0;

    int bpp = surface_bits_per_pixel(surface);

    int linesize = surface_stride(surface);

    uint8_t *data = surface_data(surface);

    if (!is_buffer_shared(surface)) {

        switch (xenfb->depth) {

        case 8:

            if (bpp == 16) {

                BLT(uint8_t, uint16_t,   3, 3, 2,   5, 6, 5);

            } else if (bpp == 32) {

                BLT(uint8_t, uint32_t,   3, 3, 2,   8, 8, 8);

            } else {

                oops = 1;

            }

            break;

        case 24:

            if (bpp == 16) {

                BLT(uint32_t, uint16_t,  8, 8, 8,   5, 6, 5);

            } else if (bpp == 32) {

                BLT(uint32_t, uint32_t,  8, 8, 8,   8, 8, 8);

            } else {

                oops = 1;

            }

            break;

        default:

            oops = 1;

	}

    }

    if (oops) /* should not happen */

        xen_pv_printf(&xenfb->c.xendev, 0, "%s: oops: convert %d -> %d bpp?\n",

                      __FUNCTION__, xenfb->depth, bpp);

    dpy_gfx_update(xenfb->c.con, x, y, w, h);

}


DISAS_INSN(fbcc)

{

    uint32_t offset;

    uint32_t addr;

    TCGv flag;

    int l1;

    addr = s->pc;

    offset = cpu_ldsw_code(env, s->pc);

    s->pc += 2;

    if (insn & (1 << 6)) {

        offset = (offset << 16) | cpu_lduw_code(env, s->pc);

        s->pc += 2;

    }

    l1 = gen_new_label();

    /* TODO: Raise BSUN exception.  */

    flag = tcg_temp_new();

    gen_helper_compare_f64(flag, cpu_env, QREG_FP_RESULT);

    /* Jump to l1 if condition is true.  */

    switch (insn & 0xf) {

    case 0: /* f */

        break;

    case 1: /* eq (=0) */

        tcg_gen_brcond_i32(TCG_COND_EQ, flag, tcg_const_i32(0), l1);

        break;

    case 2: /* ogt (=1) */

        tcg_gen_brcond_i32(TCG_COND_EQ, flag, tcg_const_i32(1), l1);

        break;

    case 3: /* oge (=0 or =1) */

        tcg_gen_brcond_i32(TCG_COND_LEU, flag, tcg_const_i32(1), l1);

        break;

    case 4: /* olt (=-1) */

        tcg_gen_brcond_i32(TCG_COND_LT, flag, tcg_const_i32(0), l1);

        break;

    case 5: /* ole (=-1 or =0) */

        tcg_gen_brcond_i32(TCG_COND_LE, flag, tcg_const_i32(0), l1);

        break;

    case 6: /* ogl (=-1 or =1) */

        tcg_gen_andi_i32(flag, flag, 1);

        tcg_gen_brcond_i32(TCG_COND_NE, flag, tcg_const_i32(0), l1);

        break;

    case 7: /* or (=2) */

        tcg_gen_brcond_i32(TCG_COND_EQ, flag, tcg_const_i32(2), l1);

        break;

    case 8: /* un (<2) */

        tcg_gen_brcond_i32(TCG_COND_LT, flag, tcg_const_i32(2), l1);

        break;

    case 9: /* ueq (=0 or =2) */

        tcg_gen_andi_i32(flag, flag, 1);

        tcg_gen_brcond_i32(TCG_COND_EQ, flag, tcg_const_i32(0), l1);

        break;

    case 10: /* ugt (>0) */

        tcg_gen_brcond_i32(TCG_COND_GT, flag, tcg_const_i32(0), l1);

        break;

    case 11: /* uge (>=0) */

        tcg_gen_brcond_i32(TCG_COND_GE, flag, tcg_const_i32(0), l1);

        break;

    case 12: /* ult (=-1 or =2) */

        tcg_gen_brcond_i32(TCG_COND_GEU, flag, tcg_const_i32(2), l1);

        break;

    case 13: /* ule (!=1) */

        tcg_gen_brcond_i32(TCG_COND_NE, flag, tcg_const_i32(1), l1);

        break;

    case 14: /* ne (!=0) */

        tcg_gen_brcond_i32(TCG_COND_NE, flag, tcg_const_i32(0), l1);

        break;

    case 15: /* t */

        tcg_gen_br(l1);

        break;

    }

    gen_jmp_tb(s, 0, s->pc);

    gen_set_label(l1);

    gen_jmp_tb(s, 1, addr + offset);

}


int omap_validate_local_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return addr >= OMAP_LOCALBUS_BASE && addr < OMAP_LOCALBUS_BASE + 0x1000000;

}


static void build_pci_bus_state_init(AcpiBuildPciBusHotplugState *state,

                                     AcpiBuildPciBusHotplugState *parent,

                                     bool pcihp_bridge_en)

{

    state->parent = parent;

    state->device_table = build_alloc_array();

    state->notify_table = build_alloc_array();

    state->pcihp_bridge_en = pcihp_bridge_en;

}


int ff_MPV_encode_picture(AVCodecContext *avctx, AVPacket *pkt,

                          const AVFrame *pic_arg, int *got_packet)

{

    MpegEncContext *s = avctx->priv_data;

    int i, stuffing_count, ret;

    int context_count = s->slice_context_count;

    s->picture_in_gop_number++;

    if (load_input_picture(s, pic_arg) < 0)

        return -1;

    if (select_input_picture(s) < 0) {

        return -1;

    }

    /* output? */

    if (s->new_picture.f->data[0]) {

        if (!pkt->data &&

            (ret = ff_alloc_packet(pkt, s->mb_width*s->mb_height*MAX_MB_BYTES)) < 0)

            return ret;

        if (s->mb_info) {

            s->mb_info_ptr = av_packet_new_side_data(pkt,

                                 AV_PKT_DATA_H263_MB_INFO,

                                 s->mb_width*s->mb_height*12);

            s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;

        }

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

            int start_y = s->thread_context[i]->start_mb_y;

            int   end_y = s->thread_context[i]->  end_mb_y;

            int h       = s->mb_height;

            uint8_t *start = pkt->data + (size_t)(((int64_t) pkt->size) * start_y / h);

            uint8_t *end   = pkt->data + (size_t)(((int64_t) pkt->size) *   end_y / h);

            init_put_bits(&s->thread_context[i]->pb, start, end - start);

        }

        s->pict_type = s->new_picture.f->pict_type;

        //emms_c();

        ret = frame_start(s);

        if (ret < 0)

            return ret;

vbv_retry:

        if (encode_picture(s, s->picture_number) < 0)

            return -1;

        avctx->header_bits = s->header_bits;

        avctx->mv_bits     = s->mv_bits;

        avctx->misc_bits   = s->misc_bits;

        avctx->i_tex_bits  = s->i_tex_bits;

        avctx->p_tex_bits  = s->p_tex_bits;

        avctx->i_count     = s->i_count;

        // FIXME f/b_count in avctx

        avctx->p_count     = s->mb_num - s->i_count - s->skip_count;

        avctx->skip_count  = s->skip_count;

        frame_end(s);

        if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)

            ff_mjpeg_encode_picture_trailer(&s->pb, s->header_bits);

        if (avctx->rc_buffer_size) {

            RateControlContext *rcc = &s->rc_context;

            int max_size = rcc->buffer_index * avctx->rc_max_available_vbv_use;

            if (put_bits_count(&s->pb) > max_size &&

                s->lambda < s->avctx->lmax) {

                s->next_lambda = FFMAX(s->lambda + 1, s->lambda *

                                       (s->qscale + 1) / s->qscale);

                if (s->adaptive_quant) {

                    int i;

                    for (i = 0; i < s->mb_height * s->mb_stride; i++)

                        s->lambda_table[i] =

                            FFMAX(s->lambda_table[i] + 1,

                                  s->lambda_table[i] * (s->qscale + 1) /

                                  s->qscale);

                }

                s->mb_skipped = 0;        // done in frame_start()

                // done in encode_picture() so we must undo it

                if (s->pict_type == AV_PICTURE_TYPE_P) {

                    if (s->flipflop_rounding          ||

                        s->codec_id == AV_CODEC_ID_H263P ||

                        s->codec_id == AV_CODEC_ID_MPEG4)

                        s->no_rounding ^= 1;

                }

                if (s->pict_type != AV_PICTURE_TYPE_B) {

                    s->time_base       = s->last_time_base;

                    s->last_non_b_time = s->time - s->pp_time;

                }

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

                    PutBitContext *pb = &s->thread_context[i]->pb;

                    init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);

                }

                goto vbv_retry;

            }

            assert(s->avctx->rc_max_rate);

        }

        if (s->flags & CODEC_FLAG_PASS1)

            ff_write_pass1_stats(s);

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

            s->current_picture_ptr->f->error[i] = s->current_picture.f->error[i];

            avctx->error[i] += s->current_picture_ptr->f->error[i];

        }

        if (s->flags & CODEC_FLAG_PASS1)

            assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits +

                   avctx->i_tex_bits + avctx->p_tex_bits ==

                       put_bits_count(&s->pb));

        flush_put_bits(&s->pb);

        s->frame_bits  = put_bits_count(&s->pb);

        stuffing_count = ff_vbv_update(s, s->frame_bits);

        if (stuffing_count) {

            if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <

                    stuffing_count + 50) {

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

                return -1;

            }

            switch (s->codec_id) {

            case AV_CODEC_ID_MPEG1VIDEO:

            case AV_CODEC_ID_MPEG2VIDEO:

                while (stuffing_count--) {

                    put_bits(&s->pb, 8, 0);

                }

            break;

            case AV_CODEC_ID_MPEG4:

                put_bits(&s->pb, 16, 0);

                put_bits(&s->pb, 16, 0x1C3);

                stuffing_count -= 4;

                while (stuffing_count--) {

                    put_bits(&s->pb, 8, 0xFF);

                }

            break;

            default:

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

            }

            flush_put_bits(&s->pb);

            s->frame_bits  = put_bits_count(&s->pb);

        }

        /* update mpeg1/2 vbv_delay for CBR */

        if (s->avctx->rc_max_rate                          &&

            s->avctx->rc_min_rate == s->avctx->rc_max_rate &&

            s->out_format == FMT_MPEG1                     &&

            90000LL * (avctx->rc_buffer_size - 1) <=

                s->avctx->rc_max_rate * 0xFFFFLL) {

            int vbv_delay, min_delay;

            double inbits  = s->avctx->rc_max_rate *

                             av_q2d(s->avctx->time_base);

            int    minbits = s->frame_bits - 8 *

                             (s->vbv_delay_ptr - s->pb.buf - 1);

            double bits    = s->rc_context.buffer_index + minbits - inbits;

            if (bits < 0)

                av_log(s->avctx, AV_LOG_ERROR,

                       "Internal error, negative bits\n");

            assert(s->repeat_first_field == 0);

            vbv_delay = bits * 90000 / s->avctx->rc_max_rate;

            min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /

                        s->avctx->rc_max_rate;

            vbv_delay = FFMAX(vbv_delay, min_delay);

            assert(vbv_delay < 0xFFFF);

            s->vbv_delay_ptr[0] &= 0xF8;

            s->vbv_delay_ptr[0] |= vbv_delay >> 13;

            s->vbv_delay_ptr[1]  = vbv_delay >> 5;

            s->vbv_delay_ptr[2] &= 0x07;

            s->vbv_delay_ptr[2] |= vbv_delay << 3;

            avctx->vbv_delay     = vbv_delay * 300;

        }

        s->total_bits     += s->frame_bits;

        avctx->frame_bits  = s->frame_bits;

        pkt->pts = s->current_picture.f->pts;

        if (!s->low_delay) {

            if (!s->current_picture.f->coded_picture_number)

                pkt->dts = pkt->pts - s->dts_delta;

            else

                pkt->dts = s->reordered_pts;

            s->reordered_pts = s->input_picture[0]->f->pts;

        } else

            pkt->dts = pkt->pts;

        if (s->current_picture.f->key_frame)

            pkt->flags |= AV_PKT_FLAG_KEY;

        if (s->mb_info)

            av_packet_shrink_side_data(pkt, AV_PKT_DATA_H263_MB_INFO, s->mb_info_size);

    } else {

        s->frame_bits = 0;

    }

    assert((s->frame_bits & 7) == 0);

    pkt->size = s->frame_bits / 8;

    *got_packet = !!pkt->size;

    return 0;

}


void s390x_cpu_debug_excp_handler(CPUState *cs)

{

    S390CPU *cpu = S390_CPU(cs);

    CPUS390XState *env = &cpu->env;

    CPUWatchpoint *wp_hit = cs->watchpoint_hit;

    if (wp_hit && wp_hit->flags & BP_CPU) {

        /* FIXME: When the storage-alteration-space control bit is set,

           the exception should only be triggered if the memory access

           is done using an address space with the storage-alteration-event

           bit set.  We have no way to detect that with the current

           watchpoint code.  */

        cs->watchpoint_hit = NULL;

        env->per_address = env->psw.addr;

        env->per_perc_atmid |= PER_CODE_EVENT_STORE | get_per_atmid(env);

        /* FIXME: We currently no way to detect the address space used

           to trigger the watchpoint.  For now just consider it is the

           current default ASC. This turn to be true except when MVCP

           and MVCS instrutions are not used.  */

        env->per_perc_atmid |= env->psw.mask & (PSW_MASK_ASC) >> 46;

        /* Remove all watchpoints to re-execute the code.  A PER exception

           will be triggered, it will call load_psw which will recompute

           the watchpoints.  */

        cpu_watchpoint_remove_all(cs, BP_CPU);

        cpu_resume_from_signal(cs, NULL);

    }

}


static AVIOContext * wtvfile_open_sector(int first_sector, uint64_t length, int depth, AVFormatContext *s)

{

    AVIOContext *pb;

    WtvFile *wf;

    uint8_t *buffer;

    if (seek_by_sector(s->pb, first_sector, 0) < 0)

        return NULL;

    wf = av_mallocz(sizeof(WtvFile));

    if (!wf)

        return NULL;

    if (depth == 0) {

        wf->sectors = av_malloc(sizeof(uint32_t));

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->sectors[0]  = first_sector;

        wf->nb_sectors  = 1;

    } else if (depth == 1) {

        wf->sectors = av_malloc(WTV_SECTOR_SIZE);

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->nb_sectors  = read_ints(s->pb, wf->sectors, WTV_SECTOR_SIZE / 4);

    } else if (depth == 2) {

        uint32_t sectors1[WTV_SECTOR_SIZE / 4];

        int nb_sectors1 = read_ints(s->pb, sectors1, WTV_SECTOR_SIZE / 4);

        int i;

        wf->sectors = av_malloc_array(nb_sectors1, 1 << WTV_SECTOR_BITS);

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->nb_sectors = 0;

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

            if (seek_by_sector(s->pb, sectors1[i], 0) < 0)

                break;

            wf->nb_sectors += read_ints(s->pb, wf->sectors + i * WTV_SECTOR_SIZE / 4, WTV_SECTOR_SIZE / 4);

        }

    } else {

        av_log(s, AV_LOG_ERROR, "unsupported file allocation table depth (0x%x)\n", depth);

        av_free(wf);

        return NULL;

    }

    wf->sector_bits = length & (1ULL<<63) ? WTV_SECTOR_BITS : WTV_BIGSECTOR_BITS;

    if (!wf->nb_sectors) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    if ((int64_t)wf->sectors[wf->nb_sectors - 1] << WTV_SECTOR_BITS > avio_tell(s->pb))

        av_log(s, AV_LOG_WARNING, "truncated file\n");

    /* check length */

    length &= 0xFFFFFFFFFFFF;

    if (length > ((int64_t)wf->nb_sectors << wf->sector_bits)) {

        av_log(s, AV_LOG_WARNING, "reported file length (0x%"PRIx64") exceeds number of available sectors (0x%"PRIx64")\n", length, (int64_t)wf->nb_sectors << wf->sector_bits);

        length = (int64_t)wf->nb_sectors <<  wf->sector_bits;

    }

    wf->length = length;

    /* seek to initial sector */

    wf->position = 0;

    if (seek_by_sector(s->pb, wf->sectors[0], 0) < 0) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    wf->pb_filesystem = s->pb;

    buffer = av_malloc(1 << wf->sector_bits);

    if (!buffer) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    pb = avio_alloc_context(buffer, 1 << wf->sector_bits, 0, wf,

                           wtvfile_read_packet, NULL, wtvfile_seek);

    if (!pb) {

        av_free(buffer);

        av_free(wf->sectors);

        av_free(wf);

    }

    return pb;

}


static int smacker_probe(AVProbeData *p)

{

    if (p->buf_size < 4)

        return 0;

    if(p->buf[0] == 'S' && p->buf[1] == 'M' && p->buf[2] == 'K'

        && (p->buf[3] == '2' || p->buf[3] == '4'))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


int avfilter_init_filter(AVFilterContext *filter, const char *args, void *opaque)

#endif

{

    AVDictionary *options = NULL;

    AVDictionaryEntry *e;

    int ret=0;

    if (args && *args) {

        if (!filter->filter->priv_class) {

            av_log(filter, AV_LOG_ERROR, "This filter does not take any "

                   "options, but options were provided: %s.\n", args);

            return AVERROR(EINVAL);

        }

#if FF_API_OLD_FILTER_OPTS

        if (!strcmp(filter->filter->name, "scale") &&

            strchr(args, ':') < strchr(args, '=')) {

            /* old w:h:flags=<flags> syntax */

            char *copy = av_strdup(args);

            char *p;

            av_log(filter, AV_LOG_WARNING, "The <w>:<h>:flags=<flags> option "

                   "syntax is deprecated. Use either <w>:<h>:<flags> or "

                   "w=<w>:h=<h>:flags=<flags>.\n");

            if (!copy) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            p = strrchr(copy, ':');

            if (p) {

                *p++ = 0;

                ret = av_dict_parse_string(&options, p, "=", ":", 0);

            }

            if (ret >= 0)

                ret = process_options(filter, &options, copy);

            av_freep(&copy);

            if (ret < 0)

                goto fail;

        } else if (!strcmp(filter->filter->name, "format")     ||

                   !strcmp(filter->filter->name, "noformat")   ||

                   !strcmp(filter->filter->name, "frei0r")     ||

                   !strcmp(filter->filter->name, "frei0r_src") ||

                   !strcmp(filter->filter->name, "ocv")        ||

                   !strcmp(filter->filter->name, "pan")        ||

                   !strcmp(filter->filter->name, "pp")         ||

                   !strcmp(filter->filter->name, "aevalsrc")) {

            /* a hack for compatibility with the old syntax

             * replace colons with |s */

            char *copy = av_strdup(args);

            char *p    = copy;

            int nb_leading = 0; // number of leading colons to skip

            int deprecated = 0;

            if (!copy) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            if (!strcmp(filter->filter->name, "frei0r") ||

                !strcmp(filter->filter->name, "ocv"))

                nb_leading = 1;

            else if (!strcmp(filter->filter->name, "frei0r_src"))

                nb_leading = 3;

            while (nb_leading--) {

                p = strchr(p, ':');

                if (!p) {

                    p = copy + strlen(copy);

                    break;

                }

                p++;

            }

            deprecated = strchr(p, ':') != NULL;

            if (!strcmp(filter->filter->name, "aevalsrc")) {

                deprecated = 0;

                while ((p = strchr(p, ':')) && p[1] != ':') {

                    const char *epos = strchr(p + 1, '=');

                    const char *spos = strchr(p + 1, ':');

                    const int next_token_is_opt = epos && (!spos || epos < spos);

                    if (next_token_is_opt) {

                        p++;

                        break;

                    }

                    /* next token does not contain a '=', assume a channel expression */

                    deprecated = 1;

                    *p++ = '|';

                }

                if (p && *p == ':') { // double sep '::' found

                    deprecated = 1;

                    memmove(p, p + 1, strlen(p));

                }

            } else

            while ((p = strchr(p, ':')))

                *p++ = '|';

            if (deprecated)

                av_log(filter, AV_LOG_WARNING, "This syntax is deprecated. Use "

                       "'|' to separate the list items.\n");

            av_log(filter, AV_LOG_DEBUG, "compat: called with args=[%s]\n", copy);

            ret = process_options(filter, &options, copy);

            av_freep(&copy);

            if (ret < 0)

                goto fail;

#endif

        } else {

#if CONFIG_MP_FILTER

            if (!strcmp(filter->filter->name, "mp")) {

                char *escaped;

                if (!strncmp(args, "filter=", 7))

                    args += 7;

                ret = av_escape(&escaped, args, ":=", AV_ESCAPE_MODE_BACKSLASH, 0);

                if (ret < 0) {

                    av_log(filter, AV_LOG_ERROR, "Unable to escape MPlayer filters arg '%s'\n", args);

                    goto fail;

                }

                ret = process_options(filter, &options, escaped);

                av_free(escaped);

            } else

#endif

            ret = process_options(filter, &options, args);

            if (ret < 0)

                goto fail;

        }

    }

    if (filter->filter->priv_class) {

        ret = av_opt_set_dict(filter->priv, &options);

        if (ret < 0) {

            av_log(filter, AV_LOG_ERROR, "Error applying options to the filter.\n");

            goto fail;

        }

    }

    if (filter->filter->init_opaque)

        ret = filter->filter->init_opaque(filter, opaque);

    else if (filter->filter->init)

        ret = filter->filter->init(filter);

    else if (filter->filter->init_dict)

        ret = filter->filter->init_dict(filter, &options);

    if (ret < 0)

        goto fail;

    if ((e = av_dict_get(options, "", NULL, AV_DICT_IGNORE_SUFFIX))) {

        av_log(filter, AV_LOG_ERROR, "No such option: %s.\n", e->key);

        ret = AVERROR_OPTION_NOT_FOUND;

        goto fail;

    }

fail:

    av_dict_free(&options);

    return ret;

}


void audio_encode_example(const char *filename)

{

    AVCodec *codec;

    AVCodecContext *c= NULL;

    int frame_size, i, j, out_size, outbuf_size;

    FILE *f;

    short *samples;

    float t, tincr;

    uint8_t *outbuf;

    printf("Audio encoding\n");

    /* find the MP2 encoder */

    codec = avcodec_find_encoder(CODEC_ID_MP2);

    if (!codec) {

        fprintf(stderr, "codec not found\n");

        exit(1);

    }

    c= avcodec_alloc_context();

    /* put sample parameters */

    c->bit_rate = 64000;

    c->sample_rate = 44100;

    c->channels = 2;

    /* open it */

    if (avcodec_open(c, codec) < 0) {

        fprintf(stderr, "could not open codec\n");

        exit(1);

    }

    /* the codec gives us the frame size, in samples */

    frame_size = c->frame_size;

    samples = malloc(frame_size * 2 * c->channels);

    outbuf_size = 10000;

    outbuf = malloc(outbuf_size);

    f = fopen(filename, "w");

    if (!f) {

        fprintf(stderr, "could not open %s\n", filename);

        exit(1);

    }

    /* encode a single tone sound */

    t = 0;

    tincr = 2 * M_PI * 440.0 / c->sample_rate;

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

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

            samples[2*j] = (int)(sin(t) * 10000);

            samples[2*j+1] = samples[2*j];

            t += tincr;

        }

        /* encode the samples */

        out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);

        fwrite(outbuf, 1, out_size, f);

    }

    fclose(f);

    free(outbuf);

    free(samples);

    avcodec_close(c);

    free(c);

}


static int w64_read_header(AVFormatContext *s)

{

    int64_t size, data_ofs = 0;

    AVIOContext *pb      = s->pb;

    WAVDemuxContext *wav = s->priv_data;

    AVStream *st;

    uint8_t guid[16];

    int ret;

    avio_read(pb, guid, 16);

    if (memcmp(guid, ff_w64_guid_riff, 16))

    /* riff + wave + fmt + sizes */

    if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)

    avio_read(pb, guid, 16);

    if (memcmp(guid, ff_w64_guid_wave, 16)) {

        av_log(s, AV_LOG_ERROR, "could not find wave guid\n");

    }

    wav->w64 = 1;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    while (!avio_feof(pb)) {

        if (avio_read(pb, guid, 16) != 16)

            break;

        size = avio_rl64(pb);

        if (size <= 24 || INT64_MAX - size < avio_tell(pb))

        if (!memcmp(guid, ff_w64_guid_fmt, 16)) {

            /* subtract chunk header size - normal wav file doesn't count it */

            ret = ff_get_wav_header(s, pb, st->codecpar, size - 24, 0);

            if (ret < 0)

                return ret;

            avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);

            avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

        } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {

            int64_t samples;

            samples = avio_rl64(pb);

            if (samples > 0)

                st->duration = samples;

        } else if (!memcmp(guid, ff_w64_guid_data, 16)) {

            wav->data_end = avio_tell(pb) + size - 24;

            data_ofs = avio_tell(pb);

            if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))

                break;

            avio_skip(pb, size - 24);

        } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {

            int64_t start, end, cur;

            uint32_t count, chunk_size, i;

            start = avio_tell(pb);

            end = start + FFALIGN(size, INT64_C(8)) - 24;

            count = avio_rl32(pb);

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

                char chunk_key[5], *value;

                if (avio_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)

                    break;

                chunk_key[4] = 0;

                avio_read(pb, chunk_key, 4);

                chunk_size = avio_rl32(pb);

                value = av_mallocz(chunk_size + 1);

                if (!value)

                    return AVERROR(ENOMEM);

                ret = avio_get_str16le(pb, chunk_size, value, chunk_size);

                avio_skip(pb, chunk_size - ret);

                av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);

            }

            avio_skip(pb, end - avio_tell(pb));

        } else {

            av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));

            avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);

        }

    }

    if (!data_ofs)

        return AVERROR_EOF;

    ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);

    ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);

    handle_stream_probing(st);

    st->need_parsing = AVSTREAM_PARSE_FULL_RAW;

    avio_seek(pb, data_ofs, SEEK_SET);

    set_spdif(s, wav);

    return 0;

}


static void floor_fit(venc_context_t * venc, floor_t * fc, float * coeffs, int * posts, int samples) {

    int range = 255 / fc->multiplier + 1;

    int i;

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

        int position = fc->list[fc->list[i].sort].x;

        int begin = fc->list[fc->list[FFMAX(i-1, 0)].sort].x;

        int end   = fc->list[fc->list[FFMIN(i+1, fc->values - 1)].sort].x;

        int j;

        float average = 0;

        begin = (position + begin) / 2;

        end   = (position + end  ) / 2;

        assert(end <= samples);

        for (j = begin; j < end; j++) average += fabs(coeffs[j]);

        average /= end - begin;

        average /= 32; // MAGIC!

        for (j = 0; j < range - 1; j++) if (floor1_inverse_db_table[j * fc->multiplier] > average) break;

        posts[fc->list[i].sort] = j;

    }

}


static int audio_decode_frame(VideoState *is)

{

    AVPacket *pkt_temp = &is->audio_pkt_temp;

    AVPacket *pkt = &is->audio_pkt;

    AVCodecContext *dec = is->audio_st->codec;

    int len1, data_size, resampled_data_size;

    int64_t dec_channel_layout;

    int got_frame;

    av_unused double audio_clock0;

    int new_packet = 0;

    int flush_complete = 0;

    int wanted_nb_samples;

    AVRational tb;

    int ret;

    int reconfigure;

    for (;;) {

        /* NOTE: the audio packet can contain several frames */

        while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet) || is->audio_buf_frames_pending) {

            if (!is->frame) {

                if (!(is->frame = avcodec_alloc_frame()))

                    return AVERROR(ENOMEM);

            } else {

                av_frame_unref(is->frame);

                avcodec_get_frame_defaults(is->frame);

            }

            if (is->audioq.serial != is->audio_pkt_temp_serial)

                break;

            if (is->paused)

                return -1;

            if (!is->audio_buf_frames_pending) {

                if (flush_complete)

                    break;

                new_packet = 0;

                len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);

                if (len1 < 0) {

                    /* if error, we skip the frame */

                    pkt_temp->size = 0;

                    break;

                }

                pkt_temp->data += len1;

                pkt_temp->size -= len1;

                if (!got_frame) {

                    /* stop sending empty packets if the decoder is finished */

                    if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)

                        flush_complete = 1;

                    continue;

                }

                tb = (AVRational){1, is->frame->sample_rate};

                if (is->frame->pts != AV_NOPTS_VALUE)

                    is->frame->pts = av_rescale_q(is->frame->pts, dec->time_base, tb);

                else if (is->frame->pkt_pts != AV_NOPTS_VALUE)

                    is->frame->pts = av_rescale_q(is->frame->pkt_pts, is->audio_st->time_base, tb);

                if (pkt_temp->pts != AV_NOPTS_VALUE)

                    pkt_temp->pts += (double) is->frame->nb_samples / is->frame->sample_rate / av_q2d(is->audio_st->time_base);

#if CONFIG_AVFILTER

                dec_channel_layout = get_valid_channel_layout(is->frame->channel_layout, av_frame_get_channels(is->frame));

                reconfigure =

                    cmp_audio_fmts(is->audio_filter_src.fmt, is->audio_filter_src.channels,

                                   is->frame->format, av_frame_get_channels(is->frame))    ||

                    is->audio_filter_src.channel_layout != dec_channel_layout ||

                    is->audio_filter_src.freq           != is->frame->sample_rate ||

                    is->audio_pkt_temp_serial           != is->audio_last_serial;

                if (reconfigure) {

                    char buf1[1024], buf2[1024];

                    av_get_channel_layout_string(buf1, sizeof(buf1), -1, is->audio_filter_src.channel_layout);

                    av_get_channel_layout_string(buf2, sizeof(buf2), -1, dec_channel_layout);

                    av_log(NULL, AV_LOG_DEBUG,

                           "Audio frame changed from rate:%d ch:%d fmt:%s layout:%s serial:%d to rate:%d ch:%d fmt:%s layout:%s serial:%d\n",

                           is->audio_filter_src.freq, is->audio_filter_src.channels, av_get_sample_fmt_name(is->audio_filter_src.fmt), buf1, is->audio_last_serial,

                           is->frame->sample_rate, av_frame_get_channels(is->frame), av_get_sample_fmt_name(is->frame->format), buf2, is->audio_pkt_temp_serial);

                    is->audio_filter_src.fmt            = is->frame->format;

                    is->audio_filter_src.channels       = av_frame_get_channels(is->frame);

                    is->audio_filter_src.channel_layout = dec_channel_layout;

                    is->audio_filter_src.freq           = is->frame->sample_rate;

                    is->audio_last_serial               = is->audio_pkt_temp_serial;

                    if ((ret = configure_audio_filters(is, afilters, 1)) < 0)

                        return ret;

                }

                if ((ret = av_buffersrc_add_frame(is->in_audio_filter, is->frame)) < 0)

                    return ret;

                av_frame_unref(is->frame);

#endif

            }

#if CONFIG_AVFILTER

            if ((ret = av_buffersink_get_frame_flags(is->out_audio_filter, is->frame, 0)) < 0) {

                if (ret == AVERROR(EAGAIN)) {

                    is->audio_buf_frames_pending = 0;

                    continue;

                }

                return ret;

            }

            is->audio_buf_frames_pending = 1;

            tb = is->out_audio_filter->inputs[0]->time_base;

#endif

            data_size = av_samples_get_buffer_size(NULL, av_frame_get_channels(is->frame),

                                                   is->frame->nb_samples,

                                                   is->frame->format, 1);

            dec_channel_layout =

                (is->frame->channel_layout && av_frame_get_channels(is->frame) == av_get_channel_layout_nb_channels(is->frame->channel_layout)) ?

                is->frame->channel_layout : av_get_default_channel_layout(av_frame_get_channels(is->frame));

            wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);

            if (is->frame->format        != is->audio_src.fmt            ||

                dec_channel_layout       != is->audio_src.channel_layout ||

                is->frame->sample_rate   != is->audio_src.freq           ||

                (wanted_nb_samples       != is->frame->nb_samples && !is->swr_ctx)) {

                swr_free(&is->swr_ctx);

                is->swr_ctx = swr_alloc_set_opts(NULL,

                                                 is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,

                                                 dec_channel_layout,           is->frame->format, is->frame->sample_rate,

                                                 0, NULL);

                if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {

                    av_log(NULL, AV_LOG_ERROR,

                           "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",

                            is->frame->sample_rate, av_get_sample_fmt_name(is->frame->format), av_frame_get_channels(is->frame),

                            is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);

                    break;

                }

                is->audio_src.channel_layout = dec_channel_layout;

                is->audio_src.channels       = av_frame_get_channels(is->frame);

                is->audio_src.freq = is->frame->sample_rate;

                is->audio_src.fmt = is->frame->format;

            }

            if (is->swr_ctx) {

                const uint8_t **in = (const uint8_t **)is->frame->extended_data;

                uint8_t **out = &is->audio_buf1;

                int out_count = (int64_t)wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate + 256;

                int out_size  = av_samples_get_buffer_size(NULL, is->audio_tgt.channels, out_count, is->audio_tgt.fmt, 0);

                int len2;

                if (out_size < 0) {

                    av_log(NULL, AV_LOG_ERROR, "av_samples_get_buffer_size() failed\n");

                    break;

                }

                if (wanted_nb_samples != is->frame->nb_samples) {

                    if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / is->frame->sample_rate,

                                                wanted_nb_samples * is->audio_tgt.freq / is->frame->sample_rate) < 0) {

                        av_log(NULL, AV_LOG_ERROR, "swr_set_compensation() failed\n");

                        break;

                    }

                }

                av_fast_malloc(&is->audio_buf1, &is->audio_buf1_size, out_size);

                if (!is->audio_buf1)

                    return AVERROR(ENOMEM);

                len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);

                if (len2 < 0) {

                    av_log(NULL, AV_LOG_ERROR, "swr_convert() failed\n");

                    break;

                }

                if (len2 == out_count) {

                    av_log(NULL, AV_LOG_WARNING, "audio buffer is probably too small\n");

                    swr_init(is->swr_ctx);

                }

                is->audio_buf = is->audio_buf1;

                resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);

            } else {

                is->audio_buf = is->frame->data[0];

                resampled_data_size = data_size;

            }

            audio_clock0 = is->audio_clock;

            /* update the audio clock with the pts */

            if (is->frame->pts != AV_NOPTS_VALUE)

                is->audio_clock = is->frame->pts * av_q2d(tb) + (double) is->frame->nb_samples / is->frame->sample_rate;

            else

                is->audio_clock = NAN;

            is->audio_clock_serial = is->audio_pkt_temp_serial;

#ifdef DEBUG

            {

                static double last_clock;

                printf("audio: delay=%0.3f clock=%0.3f clock0=%0.3f\n",

                       is->audio_clock - last_clock,

                       is->audio_clock, audio_clock0);

                last_clock = is->audio_clock;

            }

#endif

            return resampled_data_size;

        }

        /* free the current packet */

        if (pkt->data)

            av_free_packet(pkt);

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

        if (is->audioq.abort_request) {

            return -1;

        }

        if (is->audioq.nb_packets == 0)

            SDL_CondSignal(is->continue_read_thread);

        /* read next packet */

        if ((new_packet = packet_queue_get(&is->audioq, pkt, 1, &is->audio_pkt_temp_serial)) < 0)

            return -1;

        if (pkt->data == flush_pkt.data) {

            avcodec_flush_buffers(dec);

            flush_complete = 0;

            is->audio_buf_frames_pending = 0;

        }

        *pkt_temp = *pkt;

    }

}


static hwaddr ppc_hash64_pte_raddr(ppc_slb_t *slb, ppc_hash_pte64_t pte,

                                   target_ulong eaddr)

{

    hwaddr mask;

    int target_page_bits;

    hwaddr rpn = pte.pte1 & HPTE64_R_RPN;

    /*

     * We support 4K, 64K and 16M now

     */

    target_page_bits = ppc_hash64_page_shift(slb);

    mask = (1ULL << target_page_bits) - 1;

    return (rpn & ~mask) | (eaddr & mask);

}


static void nfs_file_close(BlockDriverState *bs)

{

    NFSClient *client = bs->opaque;

    nfs_client_close(client);

    qemu_mutex_destroy(&client->mutex);

}


static int mp3_seek(AVFormatContext *s, int stream_index, int64_t timestamp,

                    int flags)

{

    MP3Context *mp3 = s->priv_data;

    AVIndexEntry *ie;

    AVStream *st = s->streams[0];

    int64_t ret  = av_index_search_timestamp(st, timestamp, flags);

    uint32_t header = 0;

    if (!mp3->xing_toc) {

        st->skip_samples = timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;

        return -1;

    }

    if (ret < 0)

        return ret;

    ie = &st->index_entries[ret];

    ret = avio_seek(s->pb, ie->pos, SEEK_SET);

    if (ret < 0)

        return ret;

    while (!s->pb->eof_reached) {

        header = (header << 8) + avio_r8(s->pb);

        if (ff_mpa_check_header(header) >= 0) {

            ff_update_cur_dts(s, st, ie->timestamp);

            ret = avio_seek(s->pb, -4, SEEK_CUR);

            st->skip_samples = ie->timestamp <= 0 ? mp3->start_pad + 528 + 1 : 0;

            return (ret >= 0) ? 0 : ret;

        }

    }

    return AVERROR_EOF;

}


static void test_bmdma_no_busmaster(void)

{

    QPCIDevice *dev;

    void *bmdma_base, *ide_base;

    uint8_t status;

    dev = get_pci_device(&bmdma_base, &ide_base);

    /* No PRDT_EOT, each entry addr 0/size 64k, and in theory qemu shouldn't be

     * able to access it anyway because the Bus Master bit in the PCI command

     * register isn't set. This is complete nonsense, but it used to be pretty

     * good at confusing and occasionally crashing qemu. */

    PrdtEntry prdt[4096] = { };

    status = send_dma_request(CMD_READ_DMA | CMDF_NO_BM, 0, 512,

                              prdt, ARRAY_SIZE(prdt), NULL);

    /* Not entirely clear what the expected result is, but this is what we get

     * in practice. At least we want to be aware of any changes. */

    g_assert_cmphex(status, ==, BM_STS_ACTIVE | BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_base + reg_status), DF | ERR);

}


static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)

{

    char *pix_fmts;

    OutputStream *ost = ofilter->ost;

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

    AVFilterContext *last_filter = out->filter_ctx;

    int pad_idx = out->pad_idx;

    int ret;

    char name[255];

    snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);

    ret = avfilter_graph_create_filter(&ofilter->filter,

                                       avfilter_get_by_name("buffersink"),

                                       name, NULL, pix_fmts, fg->graph);

    if (ret < 0)

        return ret;

    if (codec->width || codec->height) {

        char args[255];

        AVFilterContext *filter;

        snprintf(args, sizeof(args), "%d:%d:flags=0x%X",

                 codec->width,

                 codec->height,

                 (unsigned)ost->sws_flags);

        snprintf(name, sizeof(name), "scaler for output stream %d:%d",

                 ost->file_index, ost->index);

        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),

                                                name, args, NULL, fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)

            return ret;

        last_filter = filter;

        pad_idx = 0;

    }

    if ((pix_fmts = choose_pix_fmts(ost))) {

        AVFilterContext *filter;

        snprintf(name, sizeof(name), "pixel format for output stream %d:%d",

                 ost->file_index, ost->index);

        if ((ret = avfilter_graph_create_filter(&filter,

                                                avfilter_get_by_name("format"),

                                                "format", pix_fmts, NULL,

                                                fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)

            return ret;

        last_filter = filter;

        pad_idx     = 0;

        av_freep(&pix_fmts);

    }

    if (ost->frame_rate.num) {

        AVFilterContext *fps;

        char args[255];

        snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,

                 ost->frame_rate.den);

        snprintf(name, sizeof(name), "fps for output stream %d:%d",

                 ost->file_index, ost->index);

        ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),

                                           name, args, NULL, fg->graph);

        if (ret < 0)

            return ret;

        ret = avfilter_link(last_filter, pad_idx, fps, 0);

        if (ret < 0)

            return ret;

        last_filter = fps;

        pad_idx = 0;

    }

    if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)

        return ret;

    return 0;

}


static inline int handle_cpu_signal(uintptr_t pc, siginfo_t *info,

                                    int is_write, sigset_t *old_set)

{

    CPUState *cpu = current_cpu;

    CPUClass *cc;

    int ret;

    unsigned long address = (unsigned long)info->si_addr;

    /* We must handle PC addresses from two different sources:

     * a call return address and a signal frame address.

     *

     * Within cpu_restore_state_from_tb we assume the former and adjust

     * the address by -GETPC_ADJ so that the address is within the call

     * insn so that addr does not accidentally match the beginning of the

     * next guest insn.

     *

     * However, when the PC comes from the signal frame, it points to

     * the actual faulting host insn and not a call insn.  Subtracting

     * GETPC_ADJ in that case may accidentally match the previous guest insn.

     *

     * So for the later case, adjust forward to compensate for what

     * will be done later by cpu_restore_state_from_tb.

     */

    if (helper_retaddr) {

        pc = helper_retaddr;

    } else {

        pc += GETPC_ADJ;

    }

    /* For synchronous signals we expect to be coming from the vCPU

     * thread (so current_cpu should be valid) and either from running

     * code or during translation which can fault as we cross pages.

     *

     * If neither is true then something has gone wrong and we should

     * abort rather than try and restart the vCPU execution.

     */

    if (!cpu || !cpu->running) {

        printf("qemu:%s received signal outside vCPU context @ pc=0x%"

               PRIxPTR "\n",  __func__, pc);

        abort();

    }

#if defined(DEBUG_SIGNAL)

    printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n",

           pc, address, is_write, *(unsigned long *)old_set);

#endif

    /* XXX: locking issue */

    if (is_write && h2g_valid(address)) {

        switch (page_unprotect(h2g(address), pc)) {

        case 0:

            /* Fault not caused by a page marked unwritable to protect

             * cached translations, must be the guest binary's problem.

             */

            break;

        case 1:

            /* Fault caused by protection of cached translation; TBs

             * invalidated, so resume execution.  Retain helper_retaddr

             * for a possible second fault.

             */

            return 1;

        case 2:

            /* Fault caused by protection of cached translation, and the

             * currently executing TB was modified and must be exited

             * immediately.  Clear helper_retaddr for next execution.

             */

            helper_retaddr = 0;

            cpu_exit_tb_from_sighandler(cpu, old_set);

            /* NORETURN */

        default:

            g_assert_not_reached();

        }

    }

    /* Convert forcefully to guest address space, invalid addresses

       are still valid segv ones */

    address = h2g_nocheck(address);

    cc = CPU_GET_CLASS(cpu);

    /* see if it is an MMU fault */

    g_assert(cc->handle_mmu_fault);

    ret = cc->handle_mmu_fault(cpu, address, is_write, MMU_USER_IDX);

    if (ret == 0) {

        /* The MMU fault was handled without causing real CPU fault.

         *  Retain helper_retaddr for a possible second fault.

         */

        return 1;

    }

    /* All other paths lead to cpu_exit; clear helper_retaddr

     * for next execution.

     */

    helper_retaddr = 0;

    if (ret < 0) {

        return 0; /* not an MMU fault */

    }

    /* Now we have a real cpu fault.  */

    cpu_restore_state(cpu, pc);

    sigprocmask(SIG_SETMASK, old_set, NULL);

    cpu_loop_exit(cpu);

    /* never comes here */

    return 1;

}


static void vc1_sprite_flush(AVCodecContext *avctx)

{

    VC1Context *v     = avctx->priv_data;

    MpegEncContext *s = &v->s;

    AVFrame *f = &s->current_picture.f;

    int plane, i;

    /* Windows Media Image codecs have a convergence interval of two keyframes.

       Since we can't enforce it, clear to black the missing sprite. This is

       wrong but it looks better than doing nothing. */

    if (f->data[0])

        for (plane = 0; plane < (s->flags&CODEC_FLAG_GRAY ? 1 : 3); plane++)

            for (i = 0; i < v->sprite_height>>!!plane; i++)

                memset(f->data[plane] + i * f->linesize[plane],

                       plane ? 128 : 0, f->linesize[plane]);

}


static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,

                           char *res, int res_len, int flags)

{

    OverlayContext *over = ctx->priv;

    int ret;

    if      (!strcmp(cmd, "x"))

        ret = set_expr(&over->x_pexpr, args, ctx);

    else if (!strcmp(cmd, "y"))

        ret = set_expr(&over->y_pexpr, args, ctx);

    else if (!strcmp(cmd, "enable"))

        ret = set_expr(&over->enable_pexpr, args, ctx);

    else

        ret = AVERROR(ENOSYS);

    if (ret < 0)

        return ret;

    if (over->eval_mode == EVAL_MODE_INIT) {

        eval_expr(ctx, EVAL_ALL);

        av_log(ctx, AV_LOG_VERBOSE, "x:%f xi:%d y:%f yi:%d enable:%f\n",

               over->var_values[VAR_X], over->x,

               over->var_values[VAR_Y], over->y,

               over->enable);

    }

    return ret;

}


static int rv20_decode_picture_header(RVDecContext *rv)

{

    MpegEncContext *s = &rv->m;

    int seq, mb_pos, i;

    int rpr_bits;

#if 0

    GetBitContext gb= s->gb;

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

        av_log(s->avctx, AV_LOG_DEBUG, "%d", get_bits1(&gb));

        if(i%4==3) av_log(s->avctx, AV_LOG_DEBUG, " ");

    }

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

#endif

#if 0

    av_log(s->avctx, AV_LOG_DEBUG, "%3dx%03d/%02Xx%02X ", s->width, s->height, s->width/4, s->height/4);

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

        av_log(s->avctx, AV_LOG_DEBUG, "%02X ", ((uint8_t*)s->avctx->extradata)[i]);

        if(i%4==3) av_log(s->avctx, AV_LOG_DEBUG, " ");

    }

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

#endif

    i= get_bits(&s->gb, 2);

    switch(i){

    case 0: s->pict_type= AV_PICTURE_TYPE_I; break;

    case 1: s->pict_type= AV_PICTURE_TYPE_I; break; //hmm ...

    case 2: s->pict_type= AV_PICTURE_TYPE_P; break;

    case 3: s->pict_type= AV_PICTURE_TYPE_B; break;

    default:

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

        return -1;

    }

    if(s->low_delay && s->pict_type==AV_PICTURE_TYPE_B){

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

        return -1;

    }

    if(s->last_picture_ptr==NULL && s->pict_type==AV_PICTURE_TYPE_B){

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

        return -1;

    }

    if (get_bits1(&s->gb)){

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

        return -1;

    }

    s->qscale = get_bits(&s->gb, 5);

    if(s->qscale==0){

        av_log(s->avctx, AV_LOG_ERROR, "error, qscale:0\n");

        return -1;

    }

    if(RV_GET_MINOR_VER(rv->sub_id) >= 2)

        s->loop_filter = get_bits1(&s->gb) && !s->avctx->lowres;

    if(RV_GET_MINOR_VER(rv->sub_id) <= 1)

        seq = get_bits(&s->gb, 8) << 7;

    else

        seq = get_bits(&s->gb, 13) << 2;

    rpr_bits = s->avctx->extradata[1] & 7;

    if(rpr_bits){

        int f, new_w, new_h;

        rpr_bits = FFMIN((rpr_bits >> 1) + 1, 3);

        f = get_bits(&s->gb, rpr_bits);

        if(f){

            new_w= 4*((uint8_t*)s->avctx->extradata)[6+2*f];

            new_h= 4*((uint8_t*)s->avctx->extradata)[7+2*f];

        }else{

            new_w= s->orig_width ;

            new_h= s->orig_height;

        }

        if(new_w != s->width || new_h != s->height){

            AVRational old_aspect = s->avctx->sample_aspect_ratio;

            av_log(s->avctx, AV_LOG_DEBUG, "attempting to change resolution to %dx%d\n", new_w, new_h);

            if (av_image_check_size(new_w, new_h, 0, s->avctx) < 0)

                return -1;

            ff_MPV_common_end(s);

            // attempt to keep aspect during typical resolution switches

            if (!old_aspect.num)

                old_aspect = (AVRational){1, 1};

            if (2 * new_w * s->height == new_h * s->width)

                s->avctx->sample_aspect_ratio = av_mul_q(old_aspect, (AVRational){2, 1});

            if (new_w * s->height == 2 * new_h * s->width)

                s->avctx->sample_aspect_ratio = av_mul_q(old_aspect, (AVRational){1, 2});

            avcodec_set_dimensions(s->avctx, new_w, new_h);

            s->width  = new_w;

            s->height = new_h;

            if (ff_MPV_common_init(s) < 0)

                return -1;

        }

        if(s->avctx->debug & FF_DEBUG_PICT_INFO){

            av_log(s->avctx, AV_LOG_DEBUG, "F %d/%d\n", f, rpr_bits);

        }

    }

    if (av_image_check_size(s->width, s->height, 0, s->avctx) < 0)

        return AVERROR_INVALIDDATA;

    mb_pos = ff_h263_decode_mba(s);

    seq |= s->time &~0x7FFF;

    if(seq - s->time >  0x4000) seq -= 0x8000;

    if(seq - s->time < -0x4000) seq += 0x8000;

    if(seq != s->time){

        if(s->pict_type!=AV_PICTURE_TYPE_B){

            s->time= seq;

            s->pp_time= s->time - s->last_non_b_time;

            s->last_non_b_time= s->time;

        }else{

            s->time= seq;

            s->pb_time= s->pp_time - (s->last_non_b_time - s->time);

            if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){

                av_log(s->avctx, AV_LOG_DEBUG, "messed up order, possible from seeking? skipping current b frame\n");

                return FRAME_SKIPPED;

            }

            ff_mpeg4_init_direct_mv(s);

        }

    }

    s->no_rounding= get_bits1(&s->gb);

    if(RV_GET_MINOR_VER(rv->sub_id) <= 1 && s->pict_type == AV_PICTURE_TYPE_B)

        skip_bits(&s->gb, 5); // binary decoder reads 3+2 bits here but they don't seem to be used

    s->f_code = 1;

    s->unrestricted_mv = 1;

    s->h263_aic= s->pict_type == AV_PICTURE_TYPE_I;

//    s->alt_inter_vlc=1;

//    s->obmc=1;

//    s->umvplus=1;

    s->modified_quant=1;

    if(!s->avctx->lowres)

        s->loop_filter=1;

    if(s->avctx->debug & FF_DEBUG_PICT_INFO){

            av_log(s->avctx, AV_LOG_INFO, "num:%5d x:%2d y:%2d type:%d qscale:%2d rnd:%d\n",

                   seq, s->mb_x, s->mb_y, s->pict_type, s->qscale, s->no_rounding);

    }

    av_assert0(s->pict_type != AV_PICTURE_TYPE_B || !s->low_delay);

    return s->mb_width*s->mb_height - mb_pos;

}


void qio_channel_test_validate(QIOChannelTest *test)

{

    g_assert_cmpint(memcmp(test->input,

                           test->output,

                           test->len), ==, 0);

    g_assert(test->readerr == NULL);

    g_assert(test->writeerr == NULL);

    g_free(test->inputv);

    g_free(test->outputv);

    g_free(test->input);

    g_free(test->output);

    g_free(test);

}


static void vapic_map_rom_writable(VAPICROMState *s)

{

    hwaddr rom_paddr = s->rom_state_paddr & ROM_BLOCK_MASK;

    MemoryRegionSection section;

    MemoryRegion *as;

    size_t rom_size;

    uint8_t *ram;

    as = sysbus_address_space(&s->busdev);

    if (s->rom_mapped_writable) {

        memory_region_del_subregion(as, &s->rom);

        memory_region_destroy(&s->rom);

    }

    /* grab RAM memory region (region @rom_paddr may still be pc.rom) */

    section = memory_region_find(as, 0, 1);

    /* read ROM size from RAM region */

    ram = memory_region_get_ram_ptr(section.mr);

    rom_size = ram[rom_paddr + 2] * ROM_BLOCK_SIZE;

    s->rom_size = rom_size;

    /* We need to round to avoid creating subpages

     * from which we cannot run code. */

    rom_size += rom_paddr & ~TARGET_PAGE_MASK;

    rom_paddr &= TARGET_PAGE_MASK;

    rom_size = TARGET_PAGE_ALIGN(rom_size);

    memory_region_init_alias(&s->rom, OBJECT(s), "kvmvapic-rom", section.mr,

                             rom_paddr, rom_size);

    memory_region_add_subregion_overlap(as, rom_paddr, &s->rom, 1000);

    s->rom_mapped_writable = true;

    memory_region_unref(section.mr);

}


static int handle_intercept(S390CPU *cpu)

{

    CPUState *cs = CPU(cpu);

    struct kvm_run *run = cs->kvm_run;

    int icpt_code = run->s390_sieic.icptcode;

    int r = 0;

    DPRINTF("intercept: 0x%x (at 0x%lx)\n", icpt_code,

            (long)cs->kvm_run->psw_addr);

    switch (icpt_code) {

        case ICPT_INSTRUCTION:

            r = handle_instruction(cpu, run);

            break;

        case ICPT_WAITPSW:

            /* disabled wait, since enabled wait is handled in kernel */

            if (s390_del_running_cpu(cpu) == 0) {

                if (is_special_wait_psw(cs)) {

                    qemu_system_shutdown_request();

                } else {

                    QObject *data;

                    data = qobject_from_jsonf("{ 'action': %s }", "pause");

                    monitor_protocol_event(QEVENT_GUEST_PANICKED, data);

                    qobject_decref(data);

                    vm_stop(RUN_STATE_GUEST_PANICKED);

                }

            }

            r = EXCP_HALTED;

            break;

        case ICPT_CPU_STOP:

            if (s390_del_running_cpu(cpu) == 0) {

                qemu_system_shutdown_request();

            }

            r = EXCP_HALTED;

            break;

        case ICPT_SOFT_INTERCEPT:

            fprintf(stderr, "KVM unimplemented icpt SOFT\n");

            exit(1);

            break;

        case ICPT_IO:

            fprintf(stderr, "KVM unimplemented icpt IO\n");

            exit(1);

            break;

        default:

            fprintf(stderr, "Unknown intercept code: %d\n", icpt_code);

            exit(1);

            break;

    }

    return r;

}


static void dump_op_count(void)

{

    int i;

    FILE *f;

    f = fopen("/tmp/op.log", "w");

    for(i = INDEX_op_end; i < NB_OPS; i++) {

        fprintf(f, "%s %" PRId64 "\n", tcg_op_defs[i].name, tcg_table_op_count[i]);

    }

    fclose(f);

}


static void qed_check_for_leaks(QEDCheck *check)

{

    BDRVQEDState *s = check->s;

    size_t i;

    for (i = s->header.header_size; i < check->nclusters; i++) {

        if (!qed_test_bit(check->used_clusters, i)) {

            check->result->leaks++;

        }

    }

}


static void test_qemu_strtol_full_max(void)

{

    const char *str = g_strdup_printf("%ld", LONG_MAX);

    long res;

    int err;

    err = qemu_strtol(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, LONG_MAX);

}


char *spapr_get_cpu_core_type(const char *model)

{

    char *core_type;

    gchar **model_pieces = g_strsplit(model, ",", 2);

    core_type = g_strdup_printf("%s-%s", model_pieces[0], TYPE_SPAPR_CPU_CORE);

    g_strfreev(model_pieces);

    /* Check whether it exists or whether we have to look up an alias name */

    if (!object_class_by_name(core_type)) {

        const char *realmodel;

        g_free(core_type);

        realmodel = ppc_cpu_lookup_alias(model);

        if (realmodel) {

            return spapr_get_cpu_core_type(realmodel);

        }

        return NULL;

    }

    return core_type;

}


static int get_refcount(BlockDriverState *bs, int64_t cluster_index)

{

    BDRVQcowState *s = bs->opaque;

    int refcount_table_index, block_index;

    int64_t refcount_block_offset;

    int ret;

    uint16_t *refcount_block;

    uint16_t refcount;

    refcount_table_index = cluster_index >> (s->cluster_bits - REFCOUNT_SHIFT);

    if (refcount_table_index >= s->refcount_table_size)

        return 0;

    refcount_block_offset =

        s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;

    if (!refcount_block_offset)

        return 0;

    ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,

        (void**) &refcount_block);

    if (ret < 0) {

        return ret;

    }

    block_index = cluster_index &

        ((1 << (s->cluster_bits - REFCOUNT_SHIFT)) - 1);

    refcount = be16_to_cpu(refcount_block[block_index]);

    ret = qcow2_cache_put(bs, s->refcount_block_cache,

        (void**) &refcount_block);

    if (ret < 0) {

        return ret;

    }

    return refcount;

}


static void openpic_irq_raise(OpenPICState *opp, int n_CPU, IRQ_src_t *src)

{

    int n_ci = IDR_CI0_SHIFT - n_CPU;

    if ((opp->flags & OPENPIC_FLAG_IDE_CRIT) && (src->ide & (1 << n_ci))) {

        qemu_irq_raise(opp->dst[n_CPU].irqs[OPENPIC_OUTPUT_CINT]);

    } else {

        qemu_irq_raise(opp->dst[n_CPU].irqs[OPENPIC_OUTPUT_INT]);

    }

}


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

                                int line, int left,

                                uint8_t lru[3][8])

{

    int x, y;

    int width    = frame->width;

    int ystride = frame->linesize[0];

    int ustride = frame->linesize[1];

    int vstride = frame->linesize[2];

    uint8_t *Y  = frame->data[0] + ystride * line;

    uint8_t *U  = frame->data[1] + (ustride >> 1) * line;

    uint8_t *V  = frame->data[2] + (vstride >> 1) * line;

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

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

            Y[x + 0 + 0 * ystride] = decode_sym(gb, lru[0]);

            Y[x + 1 + 0 * ystride] = decode_sym(gb, lru[0]);

            Y[x + 0 + 1 * ystride] = decode_sym(gb, lru[0]);

            Y[x + 1 + 1 * ystride] = decode_sym(gb, lru[0]);

            U[x >> 1] = decode_sym(gb, lru[1]) ^ 0x80;

            V[x >> 1] = decode_sym(gb, lru[2]) ^ 0x80;

        }

        Y += ystride << 1;

        U += ustride;

        V += vstride;

    }

    return y;

}


static inline void RENAME(bgr16ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

	int i;

        assert(src1==src2);

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

	{

		int d0= ((uint32_t*)src1)[i];

		int dl= (d0&0x07E0F81F);

		int dh= ((d0>>5)&0x07C0F83F);

		int dh2= (dh>>11) + (dh<<21);

		int d= dh2 + dl;

		int b= d&0x7F;

		int r= (d>>11)&0x7F;

		int g= d>>21;

		dstU[i]= ((2*RU*r + GU*g + 2*BU*b)>>(RGB2YUV_SHIFT+1-2)) + 128;

		dstV[i]= ((2*RV*r + GV*g + 2*BV*b)>>(RGB2YUV_SHIFT+1-2)) + 128;

	}

}


static int file_close_dir(URLContext *h)

{

#if HAVE_DIRENT_H

    FileContext *c = h->priv_data;

    closedir(c->dir);

    return 0;

#else

    return AVERROR(ENOSYS);

#endif /* HAVE_DIRENT_H */

}


static int sdp_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    RTSPState *rt = s->priv_data;

    RTSPStream *rtsp_st;

    int size, i, err;

    char *content;

    char url[1024];

    /* read the whole sdp file */

    /* XXX: better loading */

    content = av_malloc(SDP_MAX_SIZE);

    size = get_buffer(s->pb, content, SDP_MAX_SIZE - 1);

    if (size <= 0) {

        av_free(content);

        return AVERROR_INVALIDDATA;

    }

    content[size] ='\0';

    sdp_parse(s, content);

    av_free(content);

    /* open each RTP stream */

    for(i=0;i<rt->nb_rtsp_streams;i++) {

        rtsp_st = rt->rtsp_streams[i];

        snprintf(url, sizeof(url), "rtp://%s:%d?localport=%d&ttl=%d",

                 inet_ntoa(rtsp_st->sdp_ip),

                 rtsp_st->sdp_port,

                 rtsp_st->sdp_port,

                 rtsp_st->sdp_ttl);

        if (url_open(&rtsp_st->rtp_handle, url, URL_RDWR) < 0) {

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

        if ((err = rtsp_open_transport_ctx(s, rtsp_st)))

            goto fail;

    }

    return 0;

 fail:

    rtsp_close_streams(rt);

    return err;

}


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

    int i;

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

        if(nnzc[ scan8[i] ]) ff_h264_idct_add_mmx    (dst + block_offset[i], block + i*16, stride);

        else if(block[i*16]) ff_h264_idct_dc_add_mmx2(dst + block_offset[i], block + i*16, stride);

    }

}


static void floor_encode(vorbis_enc_context *venc, vorbis_enc_floor *fc,

                         PutBitContext *pb, uint16_t *posts,

                         float *floor, int samples)

{

    int range = 255 / fc->multiplier + 1;

    int coded[MAX_FLOOR_VALUES]; // first 2 values are unused

    int i, counter;

    put_bits(pb, 1, 1); // non zero

    put_bits(pb, ilog(range - 1), posts[0]);

    put_bits(pb, ilog(range - 1), posts[1]);

    coded[0] = coded[1] = 1;

    for (i = 2; i < fc->values; i++) {

        int predicted = render_point(fc->list[fc->list[i].low].x,

                                     posts[fc->list[i].low],

                                     fc->list[fc->list[i].high].x,

                                     posts[fc->list[i].high],

                                     fc->list[i].x);

        int highroom = range - predicted;

        int lowroom = predicted;

        int room = FFMIN(highroom, lowroom);

        if (predicted == posts[i]) {

            coded[i] = 0; // must be used later as flag!

            continue;

        } else {

            if (!coded[fc->list[i].low ])

                coded[fc->list[i].low ] = -1;

            if (!coded[fc->list[i].high])

                coded[fc->list[i].high] = -1;

        }

        if (posts[i] > predicted) {

            if (posts[i] - predicted > room)

                coded[i] = posts[i] - predicted + lowroom;

            else

                coded[i] = (posts[i] - predicted) << 1;

        } else {

            if (predicted - posts[i] > room)

                coded[i] = predicted - posts[i] + highroom - 1;

            else

                coded[i] = ((predicted - posts[i]) << 1) - 1;

        }

    }

    counter = 2;

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

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

        int k, cval = 0, csub = 1<<c->subclass;

        if (c->subclass) {

            vorbis_enc_codebook * book = &venc->codebooks[c->masterbook];

            int cshift = 0;

            for (k = 0; k < c->dim; k++) {

                int l;

                for (l = 0; l < csub; l++) {

                    int maxval = 1;

                    if (c->books[l] != -1)

                        maxval = venc->codebooks[c->books[l]].nentries;

                    // coded could be -1, but this still works, cause that is 0

                    if (coded[counter + k] < maxval)

                        break;

                }

                assert(l != csub);

                cval   |= l << cshift;

                cshift += c->subclass;

            }

            put_codeword(pb, book, cval);

        }

        for (k = 0; k < c->dim; k++) {

            int book  = c->books[cval & (csub-1)];

            int entry = coded[counter++];

            cval >>= c->subclass;

            if (book == -1)

                continue;

            if (entry == -1)

                entry = 0;

            put_codeword(pb, &venc->codebooks[book], entry);

        }

    }

    ff_vorbis_floor1_render_list(fc->list, fc->values, posts, coded,

                                 fc->multiplier, floor, samples);

}


void qtest_quit(QTestState *s)

{

    int status;

    pid_t pid = qtest_qemu_pid(s);

    if (pid != -1) {

        kill(pid, SIGTERM);

        waitpid(pid, &status, 0);

    }

    unlink(s->pid_file);

    unlink(s->socket_path);

    unlink(s->qmp_socket_path);

    g_free(s->pid_file);

    g_free(s->socket_path);

    g_free(s->qmp_socket_path);

}