static ssize_t nic_receive(NetClientState *nc, const uint8_t * buf, size_t size)

{

    /* TODO:

     * - Magic packets should set bit 30 in power management driver register.

     * - Interesting packets should set bit 29 in power management driver register.

     */

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

    uint16_t rfd_status = 0xa000;

#if defined(CONFIG_PAD_RECEIVED_FRAMES)

    uint8_t min_buf[60];

#endif

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

#if defined(CONFIG_PAD_RECEIVED_FRAMES)

    /* Pad to minimum Ethernet frame length */

    if (size < sizeof(min_buf)) {

        memcpy(min_buf, buf, size);

        memset(&min_buf[size], 0, sizeof(min_buf) - size);

        buf = min_buf;

        size = sizeof(min_buf);

    }

#endif

    if (s->configuration[8] & 0x80) {

        /* CSMA is disabled. */

        logout("%p received while CSMA is disabled\n", s);

        return -1;

#if !defined(CONFIG_PAD_RECEIVED_FRAMES)

    } else if (size < 64 && (s->configuration[7] & BIT(0))) {

        /* Short frame and configuration byte 7/0 (discard short receive) set:

         * Short frame is discarded */

        logout("%p received short frame (%zu byte)\n", s, size);

        s->statistics.rx_short_frame_errors++;

        return -1;

#endif

    } else if ((size > MAX_ETH_FRAME_SIZE + 4) && !(s->configuration[18] & BIT(3))) {

        /* Long frame and configuration byte 18/3 (long receive ok) not set:

         * Long frames are discarded. */

        logout("%p received long frame (%zu byte), ignored\n", s, size);

        return -1;

    } else if (memcmp(buf, s->conf.macaddr.a, 6) == 0) {       /* !!! */

        /* Frame matches individual address. */

        /* TODO: check configuration byte 15/4 (ignore U/L). */

        TRACE(RXTX, logout("%p received frame for me, len=%zu\n", s, size));

    } else if (memcmp(buf, broadcast_macaddr, 6) == 0) {

        /* Broadcast frame. */

        TRACE(RXTX, logout("%p received broadcast, len=%zu\n", s, size));

        rfd_status |= 0x0002;

    } else if (buf[0] & 0x01) {

        /* Multicast frame. */

        TRACE(RXTX, logout("%p received multicast, len=%zu,%s\n", s, size, nic_dump(buf, size)));

        if (s->configuration[21] & BIT(3)) {

          /* Multicast all bit is set, receive all multicast frames. */

        } else {

          unsigned mcast_idx = e100_compute_mcast_idx(buf);

          assert(mcast_idx < 64);

          if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) {

            /* Multicast frame is allowed in hash table. */

          } else if (s->configuration[15] & BIT(0)) {

              /* Promiscuous: receive all. */

              rfd_status |= 0x0004;

          } else {

              TRACE(RXTX, logout("%p multicast ignored\n", s));

              return -1;

          }

        }

        /* TODO: Next not for promiscuous mode? */

        rfd_status |= 0x0002;

    } else if (s->configuration[15] & BIT(0)) {

        /* Promiscuous: receive all. */

        TRACE(RXTX, logout("%p received frame in promiscuous mode, len=%zu\n", s, size));

        rfd_status |= 0x0004;

    } else if (s->configuration[20] & BIT(6)) {

        /* Multiple IA bit set. */

        unsigned mcast_idx = compute_mcast_idx(buf);

        assert(mcast_idx < 64);

        if (s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7))) {

            TRACE(RXTX, logout("%p accepted, multiple IA bit set\n", s));

        } else {

            TRACE(RXTX, logout("%p frame ignored, multiple IA bit set\n", s));

            return -1;

        }

    } else {

        TRACE(RXTX, logout("%p received frame, ignored, len=%zu,%s\n", s, size,

              nic_dump(buf, size)));

        return size;

    }

    if (get_ru_state(s) != ru_ready) {

        /* No resources available. */

        logout("no resources, state=%u\n", get_ru_state(s));

        /* TODO: RNR interrupt only at first failed frame? */

        eepro100_rnr_interrupt(s);

        s->statistics.rx_resource_errors++;

#if 0

        assert(!"no resources");

#endif

        return -1;

    }

    /* !!! */

    eepro100_rx_t rx;

    pci_dma_read(&s->dev, s->ru_base + s->ru_offset,

                 &rx, sizeof(eepro100_rx_t));

    uint16_t rfd_command = le16_to_cpu(rx.command);

    uint16_t rfd_size = le16_to_cpu(rx.size);

    if (size > rfd_size) {

        logout("Receive buffer (%" PRId16 " bytes) too small for data "

            "(%zu bytes); data truncated\n", rfd_size, size);

        size = rfd_size;

    }

#if !defined(CONFIG_PAD_RECEIVED_FRAMES)

    if (size < 64) {

        rfd_status |= 0x0080;

    }

#endif

    TRACE(OTHER, logout("command 0x%04x, link 0x%08x, addr 0x%08x, size %u\n",

          rfd_command, rx.link, rx.rx_buf_addr, rfd_size));

    stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset +

                offsetof(eepro100_rx_t, status), rfd_status);

    stw_le_pci_dma(&s->dev, s->ru_base + s->ru_offset +

                offsetof(eepro100_rx_t, count), size);

    /* Early receive interrupt not supported. */

#if 0

    eepro100_er_interrupt(s);

#endif

    /* Receive CRC Transfer not supported. */

    if (s->configuration[18] & BIT(2)) {

        missing("Receive CRC Transfer");

        return -1;

    }

    /* TODO: check stripping enable bit. */

#if 0

    assert(!(s->configuration[17] & BIT(0)));

#endif

    pci_dma_write(&s->dev, s->ru_base + s->ru_offset +

                  sizeof(eepro100_rx_t), buf, size);

    s->statistics.rx_good_frames++;

    eepro100_fr_interrupt(s);

    s->ru_offset = le32_to_cpu(rx.link);

    if (rfd_command & COMMAND_EL) {

        /* EL bit is set, so this was the last frame. */

        logout("receive: Running out of frames\n");

        set_ru_state(s, ru_suspended);

    }

    if (rfd_command & COMMAND_S) {

        /* S bit is set. */

        set_ru_state(s, ru_suspended);

    }

    return size;

}


void pci_bus_get_w64_range(PCIBus *bus, Range *range)

{

    range->begin = range->end = 0;

    pci_for_each_device_under_bus(bus, pci_dev_get_w64, range);

}


static void m5208_timer_write(void *opaque, target_phys_addr_t offset,

                              uint64_t value, unsigned size)

{

    m5208_timer_state *s = (m5208_timer_state *)opaque;

    int prescale;

    int limit;

    switch (offset) {

    case 0:

        /* The PIF bit is set-to-clear.  */

        if (value & PCSR_PIF) {

            s->pcsr &= ~PCSR_PIF;

            value &= ~PCSR_PIF;

        }

        /* Avoid frobbing the timer if we're just twiddling IRQ bits. */

        if (((s->pcsr ^ value) & ~PCSR_PIE) == 0) {

            s->pcsr = value;

            m5208_timer_update(s);

            return;

        }

        if (s->pcsr & PCSR_EN)

            ptimer_stop(s->timer);

        s->pcsr = value;

        prescale = 1 << ((s->pcsr & PCSR_PRE_MASK) >> PCSR_PRE_SHIFT);

        ptimer_set_freq(s->timer, (SYS_FREQ / 2) / prescale);

        if (s->pcsr & PCSR_RLD)

            limit = s->pmr;

        else

            limit = 0xffff;

        ptimer_set_limit(s->timer, limit, 0);

        if (s->pcsr & PCSR_EN)

            ptimer_run(s->timer, 0);

        break;

    case 2:

        s->pmr = value;

        s->pcsr &= ~PCSR_PIF;

        if ((s->pcsr & PCSR_RLD) == 0) {

            if (s->pcsr & PCSR_OVW)

                ptimer_set_count(s->timer, value);

        } else {

            ptimer_set_limit(s->timer, value, s->pcsr & PCSR_OVW);

        }

        break;

    case 4:

        break;

    default:

        hw_error("m5208_timer_write: Bad offset 0x%x\n", (int)offset);

        break;

    }

    m5208_timer_update(s);

}


static void free_tables(H264Context *h){

    int i;

    H264Context *hx;

    av_freep(&h->intra4x4_pred_mode);

    av_freep(&h->chroma_pred_mode_table);

    av_freep(&h->cbp_table);

    av_freep(&h->mvd_table[0]);

    av_freep(&h->mvd_table[1]);

    av_freep(&h->direct_table);

    av_freep(&h->non_zero_count);

    av_freep(&h->slice_table_base);

    h->slice_table= NULL;

    av_freep(&h->list_counts);

    av_freep(&h->mb2b_xy);

    av_freep(&h->mb2br_xy);

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

        hx = h->thread_context[i];

        if(!hx) continue;

        av_freep(&hx->top_borders[1]);

        av_freep(&hx->top_borders[0]);

        av_freep(&hx->s.obmc_scratchpad);

        av_freep(&hx->rbsp_buffer[1]);

        av_freep(&hx->rbsp_buffer[0]);

        hx->rbsp_buffer_size[0] = 0;

        hx->rbsp_buffer_size[1] = 0;

        if (i) av_freep(&h->thread_context[i]);

    }

}


CBus *cbus_init(qemu_irq dat)

{

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

    s->dat_out = dat;

    s->cbus.clk = qemu_allocate_irqs(cbus_clk, s, 1)[0];

    s->cbus.dat = qemu_allocate_irqs(cbus_dat, s, 1)[0];

    s->cbus.sel = qemu_allocate_irqs(cbus_sel, s, 1)[0];

    s->sel = 1;

    s->clk = 0;

    s->dat = 0;

    return &s->cbus;

}


static int cp15_tls_load_store(CPUState *env, DisasContext *s, uint32_t insn, uint32_t rd)

{

    TCGv tmp;

    int cpn = (insn >> 16) & 0xf;

    int cpm = insn & 0xf;

    int op = ((insn >> 5) & 7) | ((insn >> 18) & 0x38);

    if (!arm_feature(env, ARM_FEATURE_V6K))

        return 0;

    if (!(cpn == 13 && cpm == 0))

        return 0;

    if (insn & ARM_CP_RW_BIT) {

        switch (op) {

        case 2:

            tmp = load_cpu_field(cp15.c13_tls1);

            break;

        case 3:

            tmp = load_cpu_field(cp15.c13_tls2);

            break;

        case 4:

            tmp = load_cpu_field(cp15.c13_tls3);

            break;

        default:

            return 0;

        }

        store_reg(s, rd, tmp);

    } else {

        tmp = load_reg(s, rd);

        switch (op) {

        case 2:

            store_cpu_field(tmp, cp15.c13_tls1);

            break;

        case 3:

            store_cpu_field(tmp, cp15.c13_tls2);

            break;

        case 4:

            store_cpu_field(tmp, cp15.c13_tls3);

            break;

        default:

            dead_tmp(tmp);

            return 0;

        }

    }

    return 1;

}


void hmp_pci_add(Monitor *mon, const QDict *qdict)

{

    PCIDevice *dev = NULL;

    const char *pci_addr = qdict_get_str(qdict, "pci_addr");

    const char *type = qdict_get_str(qdict, "type");

    const char *opts = qdict_get_try_str(qdict, "opts");

    /* strip legacy tag */

    if (!strncmp(pci_addr, "pci_addr=", 9)) {

        pci_addr += 9;

    }

    if (!opts) {

        opts = "";

    }

    if (!strcmp(pci_addr, "auto"))

        pci_addr = NULL;

    if (strcmp(type, "nic") == 0) {

        dev = qemu_pci_hot_add_nic(mon, pci_addr, opts);

    } else if (strcmp(type, "storage") == 0) {

        dev = qemu_pci_hot_add_storage(mon, pci_addr, opts);

    } else {

        monitor_printf(mon, "invalid type: %s\n", type);

    }

    if (dev) {

        monitor_printf(mon, "OK root bus %s, bus %d, slot %d, function %d\n",

                       pci_root_bus_path(dev),

                       pci_bus_num(dev->bus), PCI_SLOT(dev->devfn),

                       PCI_FUNC(dev->devfn));

    } else

        monitor_printf(mon, "failed to add %s\n", opts);

}


static int ape_decode_frame(AVCodecContext * avctx,
                            void *data, int *data_size,
                            const uint8_t * buf, int buf_size)
{
    APEContext *s = avctx->priv_data;
    int16_t *samples = data;
    int nblocks;
    int i, n;
    int blockstodecode;
    int bytes_used;
    if (buf_size == 0 && !s->samples) {
        *data_size = 0;
        return 0;
    /* should not happen but who knows */
    if (BLOCKS_PER_LOOP * 2 * avctx->channels > *data_size) {
        av_log (avctx, AV_LOG_ERROR, "Packet size is too big to be handled in lavc! (max is %d where you have %d)\n", *data_size, s->samples * 2 * avctx->channels);
    if(!s->samples){
        s->data = av_realloc(s->data, (buf_size + 3) & ~3);
        s->dsp.bswap_buf((uint32_t*)s->data, (const uint32_t*)buf, buf_size >> 2);
        s->ptr = s->last_ptr = s->data;
        s->data_end = s->data + buf_size;
        nblocks = s->samples = bytestream_get_be32(&s->ptr);
        n =  bytestream_get_be32(&s->ptr);
        if(n < 0 || n > 3){
            av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
            s->data = NULL;
        s->ptr += n;
        s->currentframeblocks = nblocks;
        buf += 4;
        if (s->samples <= 0) {
            *data_size = 0;
            return buf_size;
        memset(s->decoded0,  0, sizeof(s->decoded0));
        memset(s->decoded1,  0, sizeof(s->decoded1));
        /* Initialize the frame decoder */
        init_frame_decoder(s);
    if (!s->data) {
        *data_size = 0;
        return buf_size;
    nblocks = s->samples;
    blockstodecode = FFMIN(BLOCKS_PER_LOOP, nblocks);
    if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
        ape_unpack_mono(s, blockstodecode);
    else
        ape_unpack_stereo(s, blockstodecode);
    for (i = 0; i < blockstodecode; i++) {
        *samples++ = s->decoded0[i];
        if(s->channels == 2)
            *samples++ = s->decoded1[i];
    s->samples -= blockstodecode;
    *data_size = blockstodecode * 2 * s->channels;
    bytes_used = s->samples ? s->ptr - s->last_ptr : buf_size;
    s->last_ptr = s->ptr;
    return bytes_used;


AVAES *av_aes_init(uint8_t *key, int key_bits, int decrypt) {

    AVAES *a;

    int i, j, t, rconpointer = 0;

    uint8_t tk[8][4];

    int KC= key_bits>>5;

    int rounds= KC + 6;

    uint8_t  log8[256];

    uint8_t alog8[512];

    if(!sbox[255]){

        j=1;

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

            alog8[i]=

            alog8[i+255]= j;

            log8[j]= i;

            j^= j+j;

            if(j>255) j^= 0x11B;

        }

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

            j= i ? alog8[255-log8[i]] : 0;

            j ^= (j<<1) ^ (j<<2) ^ (j<<3) ^ (j<<4);

            j = (j ^ (j>>8) ^ 99) & 255;

            inv_sbox[j]= i;

            sbox    [i]= j;

        }

        init_multbl2(dec_multbl[0], (int[4]){0xe, 0x9, 0xd, 0xb}, log8, alog8, inv_sbox);

        init_multbl2(enc_multbl[0], (int[4]){0x2, 0x1, 0x1, 0x3}, log8, alog8, sbox);

    }

    if(key_bits!=128 && key_bits!=192 && key_bits!=256)

        return NULL;

    a= av_malloc(sizeof(AVAES));

    a->rounds= rounds;

    memcpy(tk, key, KC*4);

    for(t= 0; t < (rounds+1)*4;) {

        memcpy(a->round_key[0][t], tk, KC*4);

        t+= KC;

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

            tk[0][i] ^= sbox[tk[KC-1][(i+1)&3]];

        tk[0][0] ^= rcon[rconpointer++];

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

            if(KC != 8 || j != KC>>1)

                for(i = 0; i < 4; i++) tk[j][i] ^=      tk[j-1][i];

            else

                for(i = 0; i < 4; i++) tk[j][i] ^= sbox[tk[j-1][i]];

        }

    }

    if(decrypt){

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

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

                a->round_key[i][0][j]= sbox[a->round_key[i][0][j]];

            mix(a->round_key[i], dec_multbl);

        }

    }else{

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

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

                FFSWAP(int, a->round_key[i][0][j], a->round_key[rounds-i][0][j]);

        }

    }

    return a;

}


av_cold void ff_mpadsp_init(MPADSPContext *s)

{

    DCTContext dct;

    ff_dct_init(&dct, 5, DCT_II);

    ff_init_mpadsp_tabs_float();

    ff_init_mpadsp_tabs_fixed();

    s->apply_window_float = ff_mpadsp_apply_window_float;

    s->apply_window_fixed = ff_mpadsp_apply_window_fixed;

    s->dct32_float = dct.dct32;

    s->dct32_fixed = ff_dct32_fixed;

    s->imdct36_blocks_float = ff_imdct36_blocks_float;

    s->imdct36_blocks_fixed = ff_imdct36_blocks_fixed;

    if (ARCH_AARCH64) ff_mpadsp_init_aarch64(s);

    if (ARCH_ARM)     ff_mpadsp_init_arm(s);

    if (ARCH_PPC)     ff_mpadsp_init_ppc(s);

    if (ARCH_X86)     ff_mpadsp_init_x86(s);

    if (HAVE_MIPSFPU)   ff_mpadsp_init_mipsfpu(s);

    if (HAVE_MIPSDSP) ff_mpadsp_init_mipsdsp(s);

}


static int get_range_off(int *off, int *y_rng, int *uv_rng,

                         enum AVColorRange rng, int depth)

{

    switch (rng) {

    case AVCOL_RANGE_MPEG:

        *off = 16 << (depth - 8);

        *y_rng = 219 << (depth - 8);

        *uv_rng = 224 << (depth - 8);

        break;

    case AVCOL_RANGE_JPEG:

        *off = 0;

        *y_rng = *uv_rng = (256 << (depth - 8)) - 1;

        break;

    default:

        return AVERROR(EINVAL);

    }

    return 0;

}


static av_always_inline void fill_filter_caches_inter(const H264Context *h,

                                                      H264SliceContext *sl,

                                                      int mb_type, int top_xy,

                                                      int left_xy[LEFT_MBS],

                                                      int top_type,

                                                      int left_type[LEFT_MBS],

                                                      int mb_xy, int list)

{

    int b_stride = h->b_stride;

    int16_t(*mv_dst)[2] = &sl->mv_cache[list][scan8[0]];

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

    if (IS_INTER(mb_type) || IS_DIRECT(mb_type)) {

        if (USES_LIST(top_type, list)) {

            const int b_xy  = h->mb2b_xy[top_xy] + 3 * b_stride;

            const int b8_xy = 4 * top_xy + 2;

            int (*ref2frm)[64] = sl->ref2frm[h->slice_table[top_xy] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);

            AV_COPY128(mv_dst - 1 * 8, h->cur_pic.motion_val[list][b_xy + 0]);

            ref_cache[0 - 1 * 8] =

            ref_cache[1 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 0]];

            ref_cache[2 - 1 * 8] =

            ref_cache[3 - 1 * 8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 1]];

        } else {

            AV_ZERO128(mv_dst - 1 * 8);

            AV_WN32A(&ref_cache[0 - 1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);

        }

        if (!IS_INTERLACED(mb_type ^ left_type[LTOP])) {

            if (USES_LIST(left_type[LTOP], list)) {

                const int b_xy  = h->mb2b_xy[left_xy[LTOP]] + 3;

                const int b8_xy = 4 * left_xy[LTOP] + 1;

                int (*ref2frm)[64] = sl->ref2frm[h->slice_table[left_xy[LTOP]] & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);

                AV_COPY32(mv_dst - 1 +  0, h->cur_pic.motion_val[list][b_xy + b_stride * 0]);

                AV_COPY32(mv_dst - 1 +  8, h->cur_pic.motion_val[list][b_xy + b_stride * 1]);

                AV_COPY32(mv_dst - 1 + 16, h->cur_pic.motion_val[list][b_xy + b_stride * 2]);

                AV_COPY32(mv_dst - 1 + 24, h->cur_pic.motion_val[list][b_xy + b_stride * 3]);

                ref_cache[-1 +  0] =

                ref_cache[-1 +  8] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 0]];

                ref_cache[-1 + 16] =

                ref_cache[-1 + 24] = ref2frm[list][h->cur_pic.ref_index[list][b8_xy + 2 * 1]];

            } else {

                AV_ZERO32(mv_dst - 1 +  0);

                AV_ZERO32(mv_dst - 1 +  8);

                AV_ZERO32(mv_dst - 1 + 16);

                AV_ZERO32(mv_dst - 1 + 24);

                ref_cache[-1 +  0] =

                ref_cache[-1 +  8] =

                ref_cache[-1 + 16] =

                ref_cache[-1 + 24] = LIST_NOT_USED;

            }

        }

    }

    if (!USES_LIST(mb_type, list)) {

        fill_rectangle(mv_dst, 4, 4, 8, pack16to32(0, 0), 4);

        AV_WN32A(&ref_cache[0 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);

        AV_WN32A(&ref_cache[1 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);

        AV_WN32A(&ref_cache[2 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);

        AV_WN32A(&ref_cache[3 * 8], ((LIST_NOT_USED) & 0xFF) * 0x01010101u);

        return;

    }

    {

        int8_t *ref = &h->cur_pic.ref_index[list][4 * mb_xy];

        int (*ref2frm)[64] = sl->ref2frm[sl->slice_num & (MAX_SLICES - 1)][0] + (MB_MBAFF(sl) ? 20 : 2);

        uint32_t ref01 = (pack16to32(ref2frm[list][ref[0]], ref2frm[list][ref[1]]) & 0x00FF00FF) * 0x0101;

        uint32_t ref23 = (pack16to32(ref2frm[list][ref[2]], ref2frm[list][ref[3]]) & 0x00FF00FF) * 0x0101;

        AV_WN32A(&ref_cache[0 * 8], ref01);

        AV_WN32A(&ref_cache[1 * 8], ref01);

        AV_WN32A(&ref_cache[2 * 8], ref23);

        AV_WN32A(&ref_cache[3 * 8], ref23);

    }

    {

        int16_t(*mv_src)[2] = &h->cur_pic.motion_val[list][4 * sl->mb_x + 4 * sl->mb_y * b_stride];

        AV_COPY128(mv_dst + 8 * 0, mv_src + 0 * b_stride);

        AV_COPY128(mv_dst + 8 * 1, mv_src + 1 * b_stride);

        AV_COPY128(mv_dst + 8 * 2, mv_src + 2 * b_stride);

        AV_COPY128(mv_dst + 8 * 3, mv_src + 3 * b_stride);

    }

}


static int adpcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    ADPCMContext *c = avctx->priv_data;

    ADPCMChannelStatus *cs;

    int n, m, channel, i;

    int block_predictor[2];

    short *samples;

    short *samples_end;

    uint8_t *src;

    int st; /* stereo */

    /* DK3 ADPCM accounting variables */

    unsigned char last_byte = 0;

    unsigned char nibble;

    int decode_top_nibble_next = 0;

    int diff_channel;

    /* EA ADPCM state variables */

    uint32_t samples_in_chunk;

    int32_t previous_left_sample, previous_right_sample;

    int32_t current_left_sample, current_right_sample;

    int32_t next_left_sample, next_right_sample;

    int32_t coeff1l, coeff2l, coeff1r, coeff2r;

    uint8_t shift_left, shift_right;

    int count1, count2;

    if (!buf_size)

        return 0;

    //should protect all 4bit ADPCM variants

    //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels

    //

    if(*data_size/4 < buf_size + 8)

        return -1;

    samples = data;

    samples_end= samples + *data_size/2;

    *data_size= 0;

    src = buf;

    st = avctx->channels == 2 ? 1 : 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT:

        n = (buf_size - 2);/* >> 2*avctx->channels;*/

        channel = c->channel;

        cs = &(c->status[channel]);

        /* (pppppp) (piiiiiii) */

        /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */

        cs->predictor = (*src++) << 8;

        cs->predictor |= (*src & 0x80);

        cs->predictor &= 0xFF80;

        /* sign extension */

        if(cs->predictor & 0x8000)

            cs->predictor -= 0x10000;

        cs->predictor = av_clip_int16(cs->predictor);

        cs->step_index = (*src++) & 0x7F;

        if (cs->step_index > 88){

            av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

            cs->step_index = 88;

        }

        cs->step = step_table[cs->step_index];

        if (st && channel)

            samples++;

        for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */

            *samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);

            samples += avctx->channels;

            *samples = adpcm_ima_expand_nibble(cs, (src[0] >> 4) & 0x0F, 3);

            samples += avctx->channels;

            src ++;

        }

        if(st) { /* handle stereo interlacing */

            c->channel = (channel + 1) % 2; /* we get one packet for left, then one for right data */

            if(channel == 1) { /* wait for the other packet before outputing anything */

                return src - buf;

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

//        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;

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

            cs = &(c->status[i]);

            cs->predictor = (int16_t)(src[0] + (src[1]<<8));

            src+=2;

        // XXX: is this correct ??: *samples++ = cs->predictor;

            cs->step_index = *src++;

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */

        }

        while(src < buf + buf_size){

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

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);

                src++;

            }

            src += 4*st;

        }

        break;

    case CODEC_ID_ADPCM_4XM:

        cs = &(c->status[0]);

        c->status[0].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        c->status[0].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        if(st){

            c->status[1].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;

        }

        if (cs->step_index < 0) cs->step_index = 0;

        if (cs->step_index > 88) cs->step_index = 88;

        m= (buf_size - (src - buf))>>st;

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

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);

        }

        src += m<<st;

        break;

    case CODEC_ID_ADPCM_MS:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        n = buf_size - 7 * avctx->channels;

        if (n < 0)

            return -1;

        block_predictor[0] = av_clip(*src++, 0, 7);

        block_predictor[1] = 0;

        if (st)

            block_predictor[1] = av_clip(*src++, 0, 7);

        c->status[0].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st){

            c->status[1].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

            src+=2;

        }

        c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];

        c->status[0].coeff2 = AdaptCoeff2[block_predictor[0]];

        c->status[1].coeff1 = AdaptCoeff1[block_predictor[1]];

        c->status[1].coeff2 = AdaptCoeff2[block_predictor[1]];

        c->status[0].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        c->status[0].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        src+=2;

        if (st) c->status[1].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));

        if (st) src+=2;

        *samples++ = c->status[0].sample1;

        if (st) *samples++ = c->status[1].sample1;

        *samples++ = c->status[0].sample2;

        if (st) *samples++ = c->status[1].sample2;

        for(;n>0;n--) {

            *samples++ = adpcm_ms_expand_nibble(&c->status[0], (src[0] >> 4) & 0x0F);

            *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);

            src ++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        c->status[0].predictor = (int16_t)(src[0] | (src[1] << 8));

        c->status[0].step_index = src[2];

        src += 4;

        *samples++ = c->status[0].predictor;

        if (st) {

            c->status[1].predictor = (int16_t)(src[0] | (src[1] << 8));

            c->status[1].step_index = src[2];

            src += 4;

            *samples++ = c->status[1].predictor;

        }

        while (src < buf + buf_size) {

            /* take care of the top nibble (always left or mono channel) */

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                (src[0] >> 4) & 0x0F, 3);

            /* take care of the bottom nibble, which is right sample for

             * stereo, or another mono sample */

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            else

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK3:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        if(buf_size + 16 > (samples_end - samples)*3/8)

            return -1;

        c->status[0].predictor = (int16_t)(src[10] | (src[11] << 8));

        c->status[1].predictor = (int16_t)(src[12] | (src[13] << 8));

        c->status[0].step_index = src[14];

        c->status[1].step_index = src[15];

        /* sign extend the predictors */

        src += 16;

        diff_channel = c->status[1].predictor;

        /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when

         * the buffer is consumed */

        while (1) {

            /* for this algorithm, c->status[0] is the sum channel and

             * c->status[1] is the diff channel */

            /* process the first predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the diff channel predictor */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[1], nibble, 3);

            /* process the first pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

            /* process the second predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the second pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        /* no per-block initialization; just start decoding the data */

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[1],

                    src[0] & 0x0F, 3);

            } else {

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 3);

                *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                    src[0] & 0x0F, 3);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_XA:

        c->status[0].sample1 = c->status[0].sample2 =

        c->status[1].sample1 = c->status[1].sample2 = 0;

        while (buf_size >= 128) {

            xa_decode(samples, src, &c->status[0], &c->status[1],

                avctx->channels);

            src += 128;

            samples += 28 * 8;

            buf_size -= 128;

        }

        break;

    case CODEC_ID_ADPCM_EA:

        samples_in_chunk = AV_RL32(src);

        if (samples_in_chunk >= ((buf_size - 12) * 2)) {

            src += buf_size;

            break;

        }

        src += 4;

        current_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_left_sample = (int16_t)AV_RL16(src);

        src += 2;

        current_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        previous_right_sample = (int16_t)AV_RL16(src);

        src += 2;

        for (count1 = 0; count1 < samples_in_chunk/28;count1++) {

            coeff1l = ea_adpcm_table[(*src >> 4) & 0x0F];

            coeff2l = ea_adpcm_table[((*src >> 4) & 0x0F) + 4];

            coeff1r = ea_adpcm_table[*src & 0x0F];

            coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];

            src++;

            shift_left = ((*src >> 4) & 0x0F) + 8;

            shift_right = (*src & 0x0F) + 8;

            src++;

            for (count2 = 0; count2 < 28; count2++) {

                next_left_sample = (((*src & 0xF0) << 24) >> shift_left);

                next_right_sample = (((*src & 0x0F) << 28) >> shift_right);

                src++;

                next_left_sample = (next_left_sample +

                    (current_left_sample * coeff1l) +

                    (previous_left_sample * coeff2l) + 0x80) >> 8;

                next_right_sample = (next_right_sample +

                    (current_right_sample * coeff1r) +

                    (previous_right_sample * coeff2r) + 0x80) >> 8;

                previous_left_sample = current_left_sample;

                current_left_sample = av_clip_int16(next_left_sample);

                previous_right_sample = current_right_sample;

                current_right_sample = av_clip_int16(next_right_sample);

                *samples++ = (unsigned short)current_left_sample;

                *samples++ = (unsigned short)current_right_sample;

            }

        }

        break;

    case CODEC_ID_ADPCM_IMA_AMV:

    case CODEC_ID_ADPCM_IMA_SMJPEG:

        c->status[0].predictor = *src;

        src += 2;

        c->status[0].step_index = *src++;

        src++;  /* skip another byte before getting to the meat */

        if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

            src+=4;

        while (src < buf + buf_size) {

            char hi, lo;

            lo = *src & 0x0F;

            hi = (*src >> 4) & 0x0F;

            if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

                FFSWAP(char, hi, lo);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                lo, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                hi, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_CT:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F);

                *samples++ = adpcm_ct_expand_nibble(&c->status[1],

                    src[0] & 0x0F);

            } else {

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F);

                *samples++ = adpcm_ct_expand_nibble(&c->status[0],

                    src[0] & 0x0F);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_SBPRO_4:

    case CODEC_ID_ADPCM_SBPRO_3:

    case CODEC_ID_ADPCM_SBPRO_2:

        if (!c->status[0].step_index) {

            /* the first byte is a raw sample */

            *samples++ = 128 * (*src++ - 0x80);

            if (st)

              *samples++ = 128 * (*src++ - 0x80);

            c->status[0].step_index = 1;

        }

        if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {

            while (src < buf + buf_size) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 4) & 0x0F, 4, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x0F, 4, 0);

                src++;

            }

        } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {

            while (src < buf + buf_size && samples + 2 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 5) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] & 0x03, 2, 0);

                src++;

            }

        } else {

            while (src < buf + buf_size && samples + 3 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 6) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    (src[0] >> 4) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x03, 2, 2);

                src++;

            }

        }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        GetBitContext gb;

        const int *table;

        int k0, signmask, nb_bits, count;

        int size = buf_size*8;

        init_get_bits(&gb, buf, size);

        //read bits & initial values

        nb_bits = get_bits(&gb, 2)+2;

        //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);

        table = swf_index_tables[nb_bits-2];

        k0 = 1 << (nb_bits-2);

        signmask = 1 << (nb_bits-1);

        while (get_bits_count(&gb) <= size - 22*avctx->channels) {

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

                *samples++ = c->status[i].predictor = get_sbits(&gb, 16);

                c->status[i].step_index = get_bits(&gb, 6);

            }

            for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {

                int i;

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

                    // similar to IMA adpcm

                    int delta = get_bits(&gb, nb_bits);

                    int step = step_table[c->status[i].step_index];

                    long vpdiff = 0; // vpdiff = (delta+0.5)*step/4

                    int k = k0;

                    do {

                        if (delta & k)

                            vpdiff += step;

                        step >>= 1;

                        k >>= 1;

                    } while(k);

                    vpdiff += step;

                    if (delta & signmask)

                        c->status[i].predictor -= vpdiff;

                    else

                        c->status[i].predictor += vpdiff;

                    c->status[i].step_index += table[delta & (~signmask)];

                    c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

                    c->status[i].predictor = av_clip_int16(c->status[i].predictor);

                    *samples++ = c->status[i].predictor;

                    if (samples >= samples_end) {

                        av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

                        return -1;

                    }

                }

            }

        }

        src += buf_size;

        break;

    }

    case CODEC_ID_ADPCM_YAMAHA:

        while (src < buf + buf_size) {

            if (st) {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[1],

                        (src[0] >> 4) & 0x0F);

            } else {

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        src[0] & 0x0F);

                *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],

                        (src[0] >> 4) & 0x0F);

            }

            src++;

        }

        break;

    case CODEC_ID_ADPCM_THP:

    {

        int table[2][16];

        unsigned int samplecnt;

        int prev[2][2];

        int ch;

        if (buf_size < 80) {

            av_log(avctx, AV_LOG_ERROR, "frame too small\n");

            return -1;

        }

        src+=4;

        samplecnt = bytestream_get_be32(&src);

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

            table[0][i] = (int16_t)bytestream_get_be16(&src);

        /* Initialize the previous sample.  */

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

            prev[0][i] = (int16_t)bytestream_get_be16(&src);

        if (samplecnt >= (samples_end - samples) /  (st + 1)) {

            av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

            return -1;

        }

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

            samples = (unsigned short *) data + ch;

            /* Read in every sample for this channel.  */

            for (i = 0; i < samplecnt / 14; i++) {

                int index = (*src >> 4) & 7;

                unsigned int exp = 28 - (*src++ & 15);

                int factor1 = table[ch][index * 2];

                int factor2 = table[ch][index * 2 + 1];

                /* Decode 14 samples.  */

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

                    int32_t sampledat;

                    if(n&1) sampledat=  *src++    <<28;

                    else    sampledat= (*src&0xF0)<<24;

                    sampledat = ((prev[ch][0]*factor1

                                + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);

                    *samples = av_clip_int16(sampledat);

                    prev[ch][1] = prev[ch][0];

                    prev[ch][0] = *samples++;

                    /* In case of stereo, skip one sample, this sample

                       is for the other channel.  */

                    samples += st;

                }

            }

        }

        /* In the previous loop, in case stereo is used, samples is

           increased exactly one time too often.  */

        samples -= st;

        break;

    }

    default:

        return -1;

    }

    *data_size = (uint8_t *)samples - (uint8_t *)data;

    return src - buf;

}


static void ff_h264_idct_add16intra_sse2(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+=2){

        if(nnzc[ scan8[i+0] ]|nnzc[ scan8[i+1] ])

            ff_x264_add8x4_idct_sse2 (dst + block_offset[i], block + i*16, stride);

        else if(block[i*16]|block[i*16+16])

            ff_h264_idct_dc_add8_mmx2(dst + block_offset[i], block + i*16, stride);

    }

}


int swr_init(SwrContext *s){

    s->in_buffer_index= 0;

    s->in_buffer_count= 0;

    s->resample_in_constraint= 0;

    free_temp(&s->postin);

    free_temp(&s->midbuf);

    free_temp(&s->preout);

    free_temp(&s->in_buffer);

    swr_audio_convert_free(&s-> in_convert);

    swr_audio_convert_free(&s->out_convert);

    s-> in.planar= s-> in_sample_fmt >= 0x100;

    s->out.planar= s->out_sample_fmt >= 0x100;

    s-> in_sample_fmt &= 0xFF;

    s->out_sample_fmt &= 0xFF;

    //We assume AVOptions checked the various values and the defaults where allowed

    if(   s->int_sample_fmt != AV_SAMPLE_FMT_S16

        &&s->int_sample_fmt != AV_SAMPLE_FMT_FLT){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is not supported internally, only float & S16 is supported\n", av_get_sample_fmt_name(s->int_sample_fmt));

        return AVERROR(EINVAL);

    }

    //FIXME should we allow/support using FLT on material that doesnt need it ?

    if(s->in_sample_fmt <= AV_SAMPLE_FMT_S16 || s->int_sample_fmt==AV_SAMPLE_FMT_S16){

        s->int_sample_fmt= AV_SAMPLE_FMT_S16;

    }else

        s->int_sample_fmt= AV_SAMPLE_FMT_FLT;

    if (s->out_sample_rate!=s->in_sample_rate || (s->flags & SWR_FLAG_RESAMPLE)){

        s->resample = swr_resample_init(s->resample, s->out_sample_rate, s->in_sample_rate, 16, 10, 0, 0.8);

    }else

        swr_resample_free(&s->resample);

    if(s->int_sample_fmt != AV_SAMPLE_FMT_S16 && s->resample){

        av_log(s, AV_LOG_ERROR, "Resampling only supported with internal s16 currently\n"); //FIXME

        return -1;

    }

    if(!s-> in_ch_layout)

        s-> in_ch_layout= guess_layout(s->in.ch_count);

    if(!s->out_ch_layout)

        s->out_ch_layout= guess_layout(s->out.ch_count);

    s->rematrix= s->out_ch_layout  !=s->in_ch_layout;

#define RSC 1 //FIXME finetune

    if(!s-> in.ch_count)

        s-> in.ch_count= av_get_channel_layout_nb_channels(s-> in_ch_layout);

    if(!s->out.ch_count)

        s->out.ch_count= av_get_channel_layout_nb_channels(s->out_ch_layout);

av_assert0(s-> in.ch_count);

av_assert0(s->out.ch_count);

    s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0;

    s-> in.bps= av_get_bits_per_sample_fmt(s-> in_sample_fmt)/8;

    s->int_bps= av_get_bits_per_sample_fmt(s->int_sample_fmt)/8;

    s->out.bps= av_get_bits_per_sample_fmt(s->out_sample_fmt)/8;

    s->in_convert = swr_audio_convert_alloc(s->int_sample_fmt,

                                            s-> in_sample_fmt, s-> in.ch_count, 0);

    s->out_convert= swr_audio_convert_alloc(s->out_sample_fmt,

                                            s->int_sample_fmt, s->out.ch_count, 0);

    s->postin= s->in;

    s->preout= s->out;

    s->midbuf= s->in;

    s->in_buffer= s->in;

    if(!s->resample_first){

        s->midbuf.ch_count= s->out.ch_count;

        s->in_buffer.ch_count = s->out.ch_count;

    }

    s->in_buffer.bps = s->postin.bps = s->midbuf.bps = s->preout.bps =  s->int_bps;

    s->in_buffer.planar = s->postin.planar = s->midbuf.planar = s->preout.planar =  1;

    if(s->rematrix && swr_rematrix_init(s)<0)

        return -1;

    return 0;

}


static inline void RENAME(rgb24toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

	long width, long height,

	long lumStride, long chromStride, long srcStride)

{

	long y;

	const long chromWidth= width>>1;

#ifdef HAVE_MMX

	for(y=0; y<height-2; y+=2)

	{

		long i;

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

		{

			asm volatile(

				"mov %2, %%"REG_a"		\n\t"

				"movq "MANGLE(bgr2YCoeff)", %%mm6		\n\t"

				"movq "MANGLE(w1111)", %%mm5		\n\t"

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

				"lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"\n\t"

				ASMALIGN(4)

				"1:				\n\t"

				PREFETCH" 64(%0, %%"REG_d")	\n\t"

				"movd (%0, %%"REG_d"), %%mm0	\n\t"

				"movd 3(%0, %%"REG_d"), %%mm1	\n\t"

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

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

				"movd 6(%0, %%"REG_d"), %%mm2	\n\t"

				"movd 9(%0, %%"REG_d"), %%mm3	\n\t"

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

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

				"pmaddwd %%mm6, %%mm0		\n\t"

				"pmaddwd %%mm6, %%mm1		\n\t"

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

				"pmaddwd %%mm6, %%mm3		\n\t"

#ifndef FAST_BGR2YV12

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

				"psrad $8, %%mm1		\n\t"

				"psrad $8, %%mm2		\n\t"

				"psrad $8, %%mm3		\n\t"

#endif

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

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

				"pmaddwd %%mm5, %%mm0		\n\t"

				"pmaddwd %%mm5, %%mm2		\n\t"

				"packssdw %%mm2, %%mm0		\n\t"

				"psraw $7, %%mm0		\n\t"

				"movd 12(%0, %%"REG_d"), %%mm4	\n\t"

				"movd 15(%0, %%"REG_d"), %%mm1	\n\t"

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

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

				"movd 18(%0, %%"REG_d"), %%mm2	\n\t"

				"movd 21(%0, %%"REG_d"), %%mm3	\n\t"

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

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

				"pmaddwd %%mm6, %%mm4		\n\t"

				"pmaddwd %%mm6, %%mm1		\n\t"

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

				"pmaddwd %%mm6, %%mm3		\n\t"

#ifndef FAST_BGR2YV12

				"psrad $8, %%mm4		\n\t"

				"psrad $8, %%mm1		\n\t"

				"psrad $8, %%mm2		\n\t"

				"psrad $8, %%mm3		\n\t"

#endif

				"packssdw %%mm1, %%mm4		\n\t"

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

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

				"pmaddwd %%mm5, %%mm2		\n\t"

				"add $24, %%"REG_d"		\n\t"

				"packssdw %%mm2, %%mm4		\n\t"

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

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

				"paddusb "MANGLE(bgr2YOffset)", %%mm0	\n\t"

				MOVNTQ" %%mm0, (%1, %%"REG_a")	\n\t"

				"add $8, %%"REG_a"		\n\t"

				" js 1b				\n\t"

				: : "r" (src+width*3), "r" (ydst+width), "g" (-width)

				: "%"REG_a, "%"REG_d

			);

			ydst += lumStride;

			src  += srcStride;

		}

		src -= srcStride*2;

		asm volatile(

			"mov %4, %%"REG_a"		\n\t"

			"movq "MANGLE(w1111)", %%mm5		\n\t"

			"movq "MANGLE(bgr2UCoeff)", %%mm6		\n\t"

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

			"lea (%%"REG_a", %%"REG_a", 2), %%"REG_d"\n\t"

			"add %%"REG_d", %%"REG_d"	\n\t"

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 64(%0, %%"REG_d")	\n\t"

			PREFETCH" 64(%1, %%"REG_d")	\n\t"

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

			"movq (%0, %%"REG_d"), %%mm0	\n\t"

			"movq (%1, %%"REG_d"), %%mm1	\n\t"

			"movq 6(%0, %%"REG_d"), %%mm2	\n\t"

			"movq 6(%1, %%"REG_d"), %%mm3	\n\t"

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

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

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

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

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

			"psrlq $24, %%mm2		\n\t"

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

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

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

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

#else

			"movd (%0, %%"REG_d"), %%mm0	\n\t"

			"movd (%1, %%"REG_d"), %%mm1	\n\t"

			"movd 3(%0, %%"REG_d"), %%mm2	\n\t"

			"movd 3(%1, %%"REG_d"), %%mm3	\n\t"

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

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

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

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

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

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

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

			"movd 6(%0, %%"REG_d"), %%mm4	\n\t"

			"movd 6(%1, %%"REG_d"), %%mm1	\n\t"

			"movd 9(%0, %%"REG_d"), %%mm2	\n\t"

			"movd 9(%1, %%"REG_d"), %%mm3	\n\t"

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

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

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

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

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

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

			"paddw %%mm4, %%mm2		\n\t"

			"psrlw $2, %%mm0		\n\t"

			"psrlw $2, %%mm2		\n\t"

#endif

			"movq "MANGLE(bgr2VCoeff)", %%mm1		\n\t"

			"movq "MANGLE(bgr2VCoeff)", %%mm3		\n\t"

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

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

			"pmaddwd %%mm6, %%mm0		\n\t"

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

#ifndef FAST_BGR2YV12

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

			"psrad $8, %%mm1		\n\t"

			"psrad $8, %%mm2		\n\t"

			"psrad $8, %%mm3		\n\t"

#endif

			"packssdw %%mm2, %%mm0		\n\t"

			"packssdw %%mm3, %%mm1		\n\t"

			"pmaddwd %%mm5, %%mm0		\n\t"

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

			"packssdw %%mm1, %%mm0		\n\t" // V1 V0 U1 U0

			"psraw $7, %%mm0		\n\t"

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

			"movq 12(%0, %%"REG_d"), %%mm4	\n\t"

			"movq 12(%1, %%"REG_d"), %%mm1	\n\t"

			"movq 18(%0, %%"REG_d"), %%mm2	\n\t"

			"movq 18(%1, %%"REG_d"), %%mm3	\n\t"

			PAVGB" %%mm1, %%mm4		\n\t"

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

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

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

			"psrlq $24, %%mm4		\n\t"

			"psrlq $24, %%mm2		\n\t"

			PAVGB" %%mm1, %%mm4		\n\t"

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

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

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

#else

			"movd 12(%0, %%"REG_d"), %%mm4	\n\t"

			"movd 12(%1, %%"REG_d"), %%mm1	\n\t"

			"movd 15(%0, %%"REG_d"), %%mm2	\n\t"

			"movd 15(%1, %%"REG_d"), %%mm3	\n\t"

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

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

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

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

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

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

			"paddw %%mm2, %%mm4		\n\t"

			"movd 18(%0, %%"REG_d"), %%mm5	\n\t"

			"movd 18(%1, %%"REG_d"), %%mm1	\n\t"

			"movd 21(%0, %%"REG_d"), %%mm2	\n\t"

			"movd 21(%1, %%"REG_d"), %%mm3	\n\t"

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

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

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

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

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

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

			"paddw %%mm5, %%mm2		\n\t"

			"movq "MANGLE(w1111)", %%mm5		\n\t"

			"psrlw $2, %%mm4		\n\t"

			"psrlw $2, %%mm2		\n\t"

#endif

			"movq "MANGLE(bgr2VCoeff)", %%mm1		\n\t"

			"movq "MANGLE(bgr2VCoeff)", %%mm3		\n\t"

			"pmaddwd %%mm4, %%mm1		\n\t"

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

			"pmaddwd %%mm6, %%mm4		\n\t"

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

#ifndef FAST_BGR2YV12

			"psrad $8, %%mm4		\n\t"

			"psrad $8, %%mm1		\n\t"

			"psrad $8, %%mm2		\n\t"

			"psrad $8, %%mm3		\n\t"

#endif

			"packssdw %%mm2, %%mm4		\n\t"

			"packssdw %%mm3, %%mm1		\n\t"

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

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

			"add $24, %%"REG_d"		\n\t"

			"packssdw %%mm1, %%mm4		\n\t" // V3 V2 U3 U2

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

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

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

			"punpckhdq %%mm4, %%mm1		\n\t"

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

			"paddb "MANGLE(bgr2UVOffset)", %%mm0	\n\t"

			"movd %%mm0, (%2, %%"REG_a")	\n\t"

			"punpckhdq %%mm0, %%mm0		\n\t"

			"movd %%mm0, (%3, %%"REG_a")	\n\t"

			"add $4, %%"REG_a"		\n\t"

			" js 1b				\n\t"

			: : "r" (src+chromWidth*6), "r" (src+srcStride+chromWidth*6), "r" (udst+chromWidth), "r" (vdst+chromWidth), "g" (-chromWidth)

			: "%"REG_a, "%"REG_d

		);

		udst += chromStride;

		vdst += chromStride;

		src  += srcStride*2;

	}

	asm volatile(   EMMS" \n\t"

			SFENCE" \n\t"

			:::"memory");

#else

	y=0;

#endif

	for(; y<height; y+=2)

	{

		long i;

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

		{

			unsigned int b= src[6*i+0];

			unsigned int g= src[6*i+1];

			unsigned int r= src[6*i+2];

			unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

			unsigned int V  =  ((RV*r + GV*g + BV*b)>>RGB2YUV_SHIFT) + 128;

			unsigned int U  =  ((RU*r + GU*g + BU*b)>>RGB2YUV_SHIFT) + 128;

			udst[i] 	= U;

			vdst[i] 	= V;

			ydst[2*i] 	= Y;

			b= src[6*i+3];

			g= src[6*i+4];

			r= src[6*i+5];

			Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

			ydst[2*i+1] 	= Y;

		}

		ydst += lumStride;

		src  += srcStride;

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

		{

			unsigned int b= src[6*i+0];

			unsigned int g= src[6*i+1];

			unsigned int r= src[6*i+2];

			unsigned int Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

			ydst[2*i] 	= Y;

			b= src[6*i+3];

			g= src[6*i+4];

			r= src[6*i+5];

			Y  =  ((RY*r + GY*g + BY*b)>>RGB2YUV_SHIFT) + 16;

			ydst[2*i+1] 	= Y;

		}

		udst += chromStride;

		vdst += chromStride;

		ydst += lumStride;

		src  += srcStride;

	}

}


static inline void gen_mtcr(CPUTriCoreState *env, DisasContext *ctx, TCGv r1,

                            int32_t offset)

{

    if (ctx->hflags & TRICORE_HFLAG_SM) {

        /* since we're caching PSW make this a special case */

        if (offset == 0xfe04) {

            gen_helper_psw_write(cpu_env, r1);

        } else {

            switch (offset) {

#include "csfr.def"

            }

        }

    } else {

        /* generate privilege trap */

    }

}


m_free(struct mbuf *m)

{

  DEBUG_CALL("m_free");

  DEBUG_ARG("m = %lx", (long )m);

  if(m) {

	/* Remove from m_usedlist */

	if (m->m_flags & M_USEDLIST)

	   remque(m);

	/* If it's M_EXT, free() it */

	if (m->m_flags & M_EXT)

	   free(m->m_ext);

	/*

	 * Either free() it or put it on the free list

	 */

	if (m->m_flags & M_DOFREE) {

		free(m);

		m->slirp->mbuf_alloced--;

	} else if ((m->m_flags & M_FREELIST) == 0) {

		insque(m,&m->slirp->m_freelist);

		m->m_flags = M_FREELIST; /* Clobber other flags */

	}

  } /* if(m) */

}


static int qcow_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVQcowState *s = bs->opaque;

    int len, i, shift, ret;

    QCowHeader header;

    ret = bdrv_file_open(&s->hd, filename, flags | BDRV_O_AUTOGROW);

    if (ret < 0)

        return ret;

    if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))

        goto fail;

    be32_to_cpus(&header.magic);

    be32_to_cpus(&header.version);

    be64_to_cpus(&header.backing_file_offset);

    be32_to_cpus(&header.backing_file_size);

    be64_to_cpus(&header.size);

    be32_to_cpus(&header.cluster_bits);

    be32_to_cpus(&header.crypt_method);

    be64_to_cpus(&header.l1_table_offset);

    be32_to_cpus(&header.l1_size);

    be64_to_cpus(&header.refcount_table_offset);

    be32_to_cpus(&header.refcount_table_clusters);

    be64_to_cpus(&header.snapshots_offset);

    be32_to_cpus(&header.nb_snapshots);

    if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)

        goto fail;

    if (header.size <= 1 ||

        header.cluster_bits < 9 ||

        header.cluster_bits > 16)

        goto fail;

    if (header.crypt_method > QCOW_CRYPT_AES)

        goto fail;

    s->crypt_method_header = header.crypt_method;

    if (s->crypt_method_header)

        bs->encrypted = 1;

    s->cluster_bits = header.cluster_bits;

    s->cluster_size = 1 << s->cluster_bits;

    s->cluster_sectors = 1 << (s->cluster_bits - 9);

    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */

    s->l2_size = 1 << s->l2_bits;

    bs->total_sectors = header.size / 512;

    s->csize_shift = (62 - (s->cluster_bits - 8));

    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;

    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;

    s->refcount_table_offset = header.refcount_table_offset;

    s->refcount_table_size =

        header.refcount_table_clusters << (s->cluster_bits - 3);

    s->snapshots_offset = header.snapshots_offset;

    s->nb_snapshots = header.nb_snapshots;

    /* read the level 1 table */

    s->l1_size = header.l1_size;

    shift = s->cluster_bits + s->l2_bits;

    s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;

    /* the L1 table must contain at least enough entries to put

       header.size bytes */

    if (s->l1_size < s->l1_vm_state_index)

        goto fail;

    s->l1_table_offset = header.l1_table_offset;

    s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));

    if (!s->l1_table)

        goto fail;

    if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=

        s->l1_size * sizeof(uint64_t))

        goto fail;

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

        be64_to_cpus(&s->l1_table[i]);

    }

    /* alloc L2 cache */

    s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));

    if (!s->l2_cache)

        goto fail;

    s->cluster_cache = qemu_malloc(s->cluster_size);

    if (!s->cluster_cache)

        goto fail;

    /* one more sector for decompressed data alignment */

    s->cluster_data = qemu_malloc(s->cluster_size + 512);

    if (!s->cluster_data)

        goto fail;

    s->cluster_cache_offset = -1;

    if (refcount_init(bs) < 0)

        goto fail;

    /* read the backing file name */

    if (header.backing_file_offset != 0) {

        len = header.backing_file_size;

        if (len > 1023)

            len = 1023;

        if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)

            goto fail;

        bs->backing_file[len] = '\0';

    }

    if (qcow_read_snapshots(bs) < 0)

        goto fail;

#ifdef DEBUG_ALLOC

    check_refcounts(bs);

#endif

    return 0;

 fail:

    qcow_free_snapshots(bs);

    refcount_close(bs);

    qemu_free(s->l1_table);

    qemu_free(s->l2_cache);

    qemu_free(s->cluster_cache);

    qemu_free(s->cluster_data);

    bdrv_delete(s->hd);

    return -1;

}


static uint32_t rtl8139_io_readl(void *opaque, uint8_t addr)

{

    RTL8139State *s = opaque;

    uint32_t ret;

    switch (addr)

    {

        case RxMissed:

            ret = s->RxMissed;

            DPRINTF("RxMissed read val=0x%08x\n", ret);

            break;

        case TxConfig:

            ret = rtl8139_TxConfig_read(s);

            break;

        case RxConfig:

            ret = rtl8139_RxConfig_read(s);

            break;

        case TxStatus0 ... TxStatus0+4*4-1:

            ret = rtl8139_TxStatus_read(s, addr, 4);

            break;

        case TxAddr0 ... TxAddr0+4*4-1:

            ret = rtl8139_TxAddr_read(s, addr-TxAddr0);

            break;

        case RxBuf:

            ret = rtl8139_RxBuf_read(s);

            break;

        case RxRingAddrLO:

            ret = s->RxRingAddrLO;

            DPRINTF("C+ RxRing low bits read val=0x%08x\n", ret);

            break;

        case RxRingAddrHI:

            ret = s->RxRingAddrHI;

            DPRINTF("C+ RxRing high bits read val=0x%08x\n", ret);

            break;

        case Timer:

            ret = muldiv64(qemu_get_clock_ns(vm_clock) - s->TCTR_base,

                           PCI_FREQUENCY, get_ticks_per_sec());

            DPRINTF("TCTR Timer read val=0x%08x\n", ret);

            break;

        case FlashReg:

            ret = s->TimerInt;

            DPRINTF("FlashReg TimerInt read val=0x%08x\n", ret);

            break;

        default:

            DPRINTF("ioport read(l) addr=0x%x via read(b)\n", addr);

            ret  = rtl8139_io_readb(opaque, addr);

            ret |= rtl8139_io_readb(opaque, addr + 1) << 8;

            ret |= rtl8139_io_readb(opaque, addr + 2) << 16;

            ret |= rtl8139_io_readb(opaque, addr + 3) << 24;

            DPRINTF("read(l) addr=0x%x val=%08x\n", addr, ret);

            break;

    }

    return ret;

}


static void video_decode_example(const char *outfilename, const char *filename)

{

    AVCodec *codec;

    AVCodecContext *c= NULL;

    int frame, got_picture, len;

    FILE *f;

    AVFrame *picture;

    uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];

    char buf[1024];

    AVPacket avpkt;

    av_init_packet(&avpkt);

    /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */

    memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    printf("Decode video file %s\n", filename);

    /* find the mpeg1 video decoder */

    codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);

    if (!codec) {

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

        exit(1);

    }

    c = avcodec_alloc_context3(codec);

    picture= avcodec_alloc_frame();

    if(codec->capabilities&CODEC_CAP_TRUNCATED)

        c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */

    /* For some codecs, such as msmpeg4 and mpeg4, width and height

       MUST be initialized there because this information is not

       available in the bitstream. */

    /* open it */

    if (avcodec_open2(c, codec, NULL) < 0) {

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

        exit(1);

    }

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

    f = fopen(filename, "rb");

    if (!f) {

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

        exit(1);

    }

    frame = 0;

    for(;;) {

        avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);

        if (avpkt.size == 0)

            break;

        /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)

           and this is the only method to use them because you cannot

           know the compressed data size before analysing it.

           BUT some other codecs (msmpeg4, mpeg4) are inherently frame

           based, so you must call them with all the data for one

           frame exactly. You must also initialize 'width' and

           'height' before initializing them. */

        /* NOTE2: some codecs allow the raw parameters (frame size,

           sample rate) to be changed at any frame. We handle this, so

           you should also take care of it */

        /* here, we use a stream based decoder (mpeg1video), so we

           feed decoder and see if it could decode a frame */

        avpkt.data = inbuf;

        while (avpkt.size > 0) {

            len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);

            if (len < 0) {

                fprintf(stderr, "Error while decoding frame %d\n", frame);

                exit(1);

            }

            if (got_picture) {

                printf("saving frame %3d\n", frame);

                fflush(stdout);

                /* the picture is allocated by the decoder. no need to

                   free it */

                snprintf(buf, sizeof(buf), outfilename, frame);

                pgm_save(picture->data[0], picture->linesize[0],

                         c->width, c->height, buf);

                frame++;

            }

            avpkt.size -= len;

            avpkt.data += len;

        }

    }

    /* some codecs, such as MPEG, transmit the I and P frame with a

       latency of one frame. You must do the following to have a

       chance to get the last frame of the video */

    avpkt.data = NULL;

    avpkt.size = 0;

    len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);

    if (got_picture) {

        printf("saving last frame %3d\n", frame);

        fflush(stdout);

        /* the picture is allocated by the decoder. no need to

           free it */

        snprintf(buf, sizeof(buf), outfilename, frame);

        pgm_save(picture->data[0], picture->linesize[0],

                 c->width, c->height, buf);

        frame++;

    }

    fclose(f);

    avcodec_close(c);

    av_free(c);

    av_free(picture);

    printf("\n");

}


static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)

{

    AVDictionary *opts = NULL;

    int ret;

    // broker prior HTTP options that should be consistent across requests

    av_dict_set(&opts, "user-agent", c->user_agent, 0);

    av_dict_set(&opts, "cookies", c->cookies, 0);

    av_dict_set(&opts, "headers", c->headers, 0);

    av_dict_set(&opts, "http_proxy", c->http_proxy, 0);

    av_dict_set(&opts, "seekable", "0", 0);

    if (seg->size >= 0) {

        /* try to restrict the HTTP request to the part we want

         * (if this is in fact a HTTP request) */

        av_dict_set_int(&opts, "offset", seg->url_offset, 0);

        av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);

    }

    av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",

           seg->url, seg->url_offset, pls->index);

    if (seg->key_type == KEY_NONE) {

        ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts);

    } else if (seg->key_type == KEY_AES_128) {

        AVDictionary *opts2 = NULL;

        char iv[33], key[33], url[MAX_URL_SIZE];

        if (strcmp(seg->key, pls->key_url)) {

            AVIOContext *pb;

            if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts) == 0) {

                ret = avio_read(pb, pls->key, sizeof(pls->key));

                if (ret != sizeof(pls->key)) {

                    av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",

                           seg->key);

                }

                ff_format_io_close(pls->parent, &pb);

            } else {

                av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",

                       seg->key);

            }

            av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));

        }

        ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);

        ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);

        iv[32] = key[32] = '\0';

        if (strstr(seg->url, "://"))

            snprintf(url, sizeof(url), "crypto+%s", seg->url);

        else

            snprintf(url, sizeof(url), "crypto:%s", seg->url);

        av_dict_copy(&opts2, c->avio_opts, 0);

        av_dict_set(&opts2, "key", key, 0);

        av_dict_set(&opts2, "iv", iv, 0);

        ret = open_url(pls->parent, &pls->input, url, opts2, opts);

        av_dict_free(&opts2);

        if (ret < 0) {

            goto cleanup;

        }

        ret = 0;

    } else if (seg->key_type == KEY_SAMPLE_AES) {

        av_log(pls->parent, AV_LOG_ERROR,

               "SAMPLE-AES encryption is not supported yet\n");

        ret = AVERROR_PATCHWELCOME;

    }

    else

      ret = AVERROR(ENOSYS);

    /* Seek to the requested position. If this was a HTTP request, the offset

     * should already be where want it to, but this allows e.g. local testing

     * without a HTTP server. */

    if (ret == 0 && seg->key_type == KEY_NONE && seg->url_offset) {

        int seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);

        if (seekret < 0) {

            av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);

            ret = seekret;

            ff_format_io_close(pls->parent, &pls->input);

        }

    }

cleanup:

    av_dict_free(&opts);

    pls->cur_seg_offset = 0;

    return ret;

}


static int dvvideo_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DVVideoContext *s = avctx->priv_data;

    s->sys = dv_frame_profile(buf);

    if (!s->sys || buf_size < s->sys->frame_size || dv_init_dynamic_tables(s->sys))

        return -1; /* NOTE: we only accept several full frames */

    if (s->picture.data[0])

        avctx->release_buffer(avctx, &s->picture);

    s->picture.reference = 0;

    s->picture.key_frame = 1;

    s->picture.pict_type = FF_I_TYPE;

    avctx->pix_fmt   = s->sys->pix_fmt;

    avctx->time_base = s->sys->time_base;

    avcodec_set_dimensions(avctx, s->sys->width, s->sys->height);

    if (avctx->get_buffer(avctx, &s->picture) < 0) {

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

        return -1;

    }

    s->picture.interlaced_frame = 1;

    s->picture.top_field_first  = 0;

    s->buf = buf;

    avctx->execute(avctx, dv_decode_video_segment, s->sys->work_chunks, NULL,

                   dv_work_pool_size(s->sys), sizeof(DVwork_chunk));

    emms_c();

    /* return image */

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->picture;

    return s->sys->frame_size;

}


target_ulong helper_dvpe(target_ulong arg1)

{

    // TODO

    arg1 = 0;

    // rt = arg1

    return arg1;

}


static void colo_compare_finalize(Object *obj)

{

    CompareState *s = COLO_COMPARE(obj);

    qemu_chr_fe_deinit(&s->chr_pri_in);

    qemu_chr_fe_deinit(&s->chr_sec_in);

    qemu_chr_fe_deinit(&s->chr_out);

    g_queue_free(&s->conn_list);

    if (qemu_thread_is_self(&s->thread)) {

        /* compare connection */

        g_queue_foreach(&s->conn_list, colo_compare_connection, s);

        qemu_thread_join(&s->thread);

    }

    g_free(s->pri_indev);

    g_free(s->sec_indev);

    g_free(s->outdev);

}


void cpu_dump_state(CPUState *env, FILE *f,

                    int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                    int flags)

{

#if defined(TARGET_PPC64) || 1

#define FILL ""

#define RGPL  4

#define RFPL  4

#else

#define FILL "        "

#define RGPL  8

#define RFPL  4

#endif

    int i;

    cpu_fprintf(f, "NIP " REGX " LR " REGX " CTR " REGX "\n",

                env->nip, env->lr, env->ctr);

    cpu_fprintf(f, "MSR " REGX FILL " XER %08x      TB %08x %08x "

#if !defined(CONFIG_USER_ONLY)

                "DECR %08x"

#endif

                "\n",

                do_load_msr(env), load_xer(env), cpu_ppc_load_tbu(env),

                cpu_ppc_load_tbl(env)

#if !defined(CONFIG_USER_ONLY)

                , cpu_ppc_load_decr(env)

#endif

                );

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

        if ((i & (RGPL - 1)) == 0)

            cpu_fprintf(f, "GPR%02d", i);

        cpu_fprintf(f, " " REGX, env->gpr[i]);

        if ((i & (RGPL - 1)) == (RGPL - 1))

            cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "CR ");

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

        cpu_fprintf(f, "%01x", env->crf[i]);

    cpu_fprintf(f, "  [");

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

        char a = '-';

        if (env->crf[i] & 0x08)

            a = 'L';

        else if (env->crf[i] & 0x04)

            a = 'G';

        else if (env->crf[i] & 0x02)

            a = 'E';

        cpu_fprintf(f, " %c%c", a, env->crf[i] & 0x01 ? 'O' : ' ');

    }

    cpu_fprintf(f, " ]             " FILL "RES " REGX "\n", env->reserve);

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

        if ((i & (RFPL - 1)) == 0)

            cpu_fprintf(f, "FPR%02d", i);

        cpu_fprintf(f, " %016" PRIx64, *((uint64_t *)&env->fpr[i]));

        if ((i & (RFPL - 1)) == (RFPL - 1))

            cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "SRR0 " REGX " SRR1 " REGX "         " FILL FILL FILL

                "SDR1 " REGX "\n",

                env->spr[SPR_SRR0], env->spr[SPR_SRR1], env->sdr1);

#undef REGX

#undef RGPL

#undef RFPL

#undef FILL

}


static void tci_out_label(TCGContext *s, TCGArg arg)

{

    TCGLabel *label = &s->labels[arg];

    if (label->has_value) {

        tcg_out_i(s, label->u.value);

        assert(label->u.value);

    } else {

        tcg_out_reloc(s, s->code_ptr, sizeof(tcg_target_ulong), arg, 0);

        tcg_out_i(s, 0);

    }

}


int64_t ff_gen_search(AVFormatContext *s, int stream_index, int64_t target_ts,

                      int64_t pos_min, int64_t pos_max, int64_t pos_limit,

                      int64_t ts_min, int64_t ts_max, int flags, int64_t *ts_ret,

                      int64_t (*read_timestamp)(struct AVFormatContext *, int , int64_t *, int64_t ))

{

    int64_t pos, ts;

    int64_t start_pos, filesize;

    int no_change;

    av_dlog(s, "gen_seek: %d %s\n", stream_index, av_ts2str(target_ts));

    if(ts_min == AV_NOPTS_VALUE){

        pos_min = s->data_offset;

        ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

        if (ts_min == AV_NOPTS_VALUE)

            return -1;

    }

    if(ts_min >= target_ts){

        *ts_ret= ts_min;

        return pos_min;

    }

    if(ts_max == AV_NOPTS_VALUE){

        int64_t step= 1024;

        int64_t limit;

        filesize = avio_size(s->pb);

        pos_max = filesize - 1;

        do{

            limit = pos_max;

            pos_max = FFMAX(0, pos_max - step);

            ts_max = ff_read_timestamp(s, stream_index, &pos_max, limit, read_timestamp);

            step += step;

        }while(ts_max == AV_NOPTS_VALUE && pos_max > 0);

        if (ts_max == AV_NOPTS_VALUE)

            return -1;

        for(;;){

            int64_t tmp_pos= pos_max + 1;

            int64_t tmp_ts= ff_read_timestamp(s, stream_index, &tmp_pos, INT64_MAX, read_timestamp);

            if(tmp_ts == AV_NOPTS_VALUE)

                break;

            ts_max= tmp_ts;

            pos_max= tmp_pos;

            if(tmp_pos >= filesize)

                break;

        }

        pos_limit= pos_max;

    }

    if(ts_max <= target_ts){

        *ts_ret= ts_max;

        return pos_max;

    }

    if(ts_min > ts_max){

        return -1;

    }else if(ts_min == ts_max){

        pos_limit= pos_min;

    }

    no_change=0;

    while (pos_min < pos_limit) {

        av_dlog(s, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%s dts_max=%s\n",

                pos_min, pos_max, av_ts2str(ts_min), av_ts2str(ts_max));

        assert(pos_limit <= pos_max);

        if(no_change==0){

            int64_t approximate_keyframe_distance= pos_max - pos_limit;

            // interpolate position (better than dichotomy)

            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)

                + pos_min - approximate_keyframe_distance;

        }else if(no_change==1){

            // bisection, if interpolation failed to change min or max pos last time

            pos = (pos_min + pos_limit)>>1;

        }else{

            /* linear search if bisection failed, can only happen if there

               are very few or no keyframes between min/max */

            pos=pos_min;

        }

        if(pos <= pos_min)

            pos= pos_min + 1;

        else if(pos > pos_limit)

            pos= pos_limit;

        start_pos= pos;

        ts = ff_read_timestamp(s, stream_index, &pos, INT64_MAX, read_timestamp); //may pass pos_limit instead of -1

        if(pos == pos_max)

            no_change++;

        else

            no_change=0;

        av_dlog(s, "%"PRId64" %"PRId64" %"PRId64" / %s %s %s target:%s limit:%"PRId64" start:%"PRId64" noc:%d\n",

                pos_min, pos, pos_max,

                av_ts2str(ts_min), av_ts2str(ts), av_ts2str(ts_max), av_ts2str(target_ts),

                pos_limit, start_pos, no_change);

        if(ts == AV_NOPTS_VALUE){

            av_log(s, AV_LOG_ERROR, "read_timestamp() failed in the middle\n");

            return -1;

        }

        assert(ts != AV_NOPTS_VALUE);

        if (target_ts <= ts) {

            pos_limit = start_pos - 1;

            pos_max = pos;

            ts_max = ts;

        }

        if (target_ts >= ts) {

            pos_min = pos;

            ts_min = ts;

        }

    }

    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;

    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;

#if 0

    pos_min = pos;

    ts_min = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

    pos_min++;

    ts_max = ff_read_timestamp(s, stream_index, &pos_min, INT64_MAX, read_timestamp);

    av_dlog(s, "pos=0x%"PRIx64" %s<=%s<=%s\n",

            pos, av_ts2str(ts_min), av_ts2str(target_ts), av_ts2str(ts_max));

#endif

    *ts_ret= ts;

    return pos;

}


static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,

                              AVFormatContext *s)

{

    AVIOContext *pb_buf;

    int i, ret, size;

    uint8_t *buf;

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

        if (s->flags & AVFMT_FLAG_BITEXACT) {

            return 0;

        }

    ret = avio_open_dyn_buf(&pb_buf);

    if (ret < 0)

        return ret;

    if (mov->mode & MODE_3GP) {

        mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");

        mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");

        mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");

        mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");

        mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");

        mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");

        mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");

        mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");

    } else if (mov->mode == MODE_MOV) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4

        mov_write_string_metadata(s, pb_buf, "\251ART", "artist",      0);

        mov_write_string_metadata(s, pb_buf, "\251nam", "title",       0);

        mov_write_string_metadata(s, pb_buf, "\251aut", "author",      0);

        mov_write_string_metadata(s, pb_buf, "\251alb", "album",       0);

        mov_write_string_metadata(s, pb_buf, "\251day", "date",        0);

        mov_write_string_metadata(s, pb_buf, "\251swr", "encoder",     0);

        mov_write_string_metadata(s, pb_buf, "\251des", "comment",     0);

        mov_write_string_metadata(s, pb_buf, "\251gen", "genre",       0);

        mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright",   0);

    } else {

        /* iTunes meta data */

        mov_write_meta_tag(pb_buf, mov, s);

    }

    if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))

        mov_write_chpl_tag(pb_buf, s);

    if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {

        avio_wb32(pb, size + 8);

        ffio_wfourcc(pb, "udta");

        avio_write(pb, buf, size);

    }

    av_free(buf);

    return 0;

}


static void write_video_frame(AVFormatContext *oc, AVStream *st)

{

    int ret;

    static struct SwsContext *sws_ctx;

    AVCodecContext *c = st->codec;

    if (frame_count >= STREAM_NB_FRAMES) {

        /* No more frames to compress. The codec has a latency of a few

         * frames if using B-frames, so we get the last frames by

         * passing the same picture again. */

    } else {

        if (c->pix_fmt != AV_PIX_FMT_YUV420P) {

            /* as we only generate a YUV420P picture, we must convert it

             * to the codec pixel format if needed */

            if (!sws_ctx) {

                sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,

                                         c->width, c->height, c->pix_fmt,

                                         sws_flags, NULL, NULL, NULL);

                if (!sws_ctx) {

                    fprintf(stderr,

                            "Could not initialize the conversion context\n");

                    exit(1);

                }

            }

            fill_yuv_image(&src_picture, frame_count, c->width, c->height);

            sws_scale(sws_ctx,

                      (const uint8_t * const *)src_picture.data, src_picture.linesize,

                      0, c->height, dst_picture.data, dst_picture.linesize);

        } else {

            fill_yuv_image(&dst_picture, frame_count, c->width, c->height);

        }

    }

    if (oc->oformat->flags & AVFMT_RAWPICTURE) {

        /* Raw video case - directly store the picture in the packet */

        AVPacket pkt;

        av_init_packet(&pkt);

        pkt.flags        |= AV_PKT_FLAG_KEY;

        pkt.stream_index  = st->index;

        pkt.data          = dst_picture.data[0];

        pkt.size          = sizeof(AVPicture);

        ret = av_interleaved_write_frame(oc, &pkt);

    } else {

        AVPacket pkt = { 0 };

        int got_packet;

        av_init_packet(&pkt);

        /* encode the image */

        frame->pts = frame_count;

        ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);

        if (ret < 0) {

            fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));

            exit(1);

        }

        /* If size is zero, it means the image was buffered. */

        if (got_packet) {

            ret = write_frame(oc, &c->time_base, st, &pkt);

        } else {

            ret = 0;

        }

    }

    if (ret != 0) {

        fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));

        exit(1);

    }

    frame_count++;

}


static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,

                                   AVCodecContext *avctx, const char *args,

                                   uint8_t  **poutbuf, int *poutbuf_size,

                                   const uint8_t *buf, int      buf_size,

                                   int keyframe) {

    H264BSFContext *ctx = bsfc->priv_data;

    uint8_t unit_type;

    uint32_t nal_size, cumul_size = 0;

    /* nothing to filter */

    if (!avctx->extradata || avctx->extradata_size < 6) {

        *poutbuf = (uint8_t*) buf;

        *poutbuf_size = buf_size;

        return 0;

    }

    /* retrieve sps and pps NAL units from extradata */

    if (!ctx->sps_pps_data) {

        uint16_t unit_size;

        uint32_t total_size = 0;

        uint8_t *out = NULL, unit_nb, sps_done = 0;

        const uint8_t *extradata = avctx->extradata+4;

        static const uint8_t nalu_header[4] = {0, 0, 0, 1};

        /* retrieve length coded size */

        ctx->length_size = (*extradata++ & 0x3) + 1;

        if (ctx->length_size == 3)

            return AVERROR(EINVAL);

        /* retrieve sps and pps unit(s) */

        unit_nb = *extradata++ & 0x1f; /* number of sps unit(s) */

        if (!unit_nb) {

            unit_nb = *extradata++; /* number of pps unit(s) */

            sps_done++;

        }

        while (unit_nb--) {

            unit_size = AV_RB16(extradata);

            total_size += unit_size+4;

            if (extradata+2+unit_size > avctx->extradata+avctx->extradata_size) {

                av_free(out);

                return AVERROR(EINVAL);

            }

            out = av_realloc(out, total_size);

            if (!out)

                return AVERROR(ENOMEM);

            memcpy(out+total_size-unit_size-4, nalu_header, 4);

            memcpy(out+total_size-unit_size,   extradata+2, unit_size);

            extradata += 2+unit_size;

            if (!unit_nb && !sps_done++)

                unit_nb = *extradata++; /* number of pps unit(s) */

        }

        ctx->sps_pps_data = out;

        ctx->size = total_size;

        ctx->first_idr = 1;

    }

    *poutbuf_size = 0;

    *poutbuf = NULL;

    do {

        if (ctx->length_size == 1)

            nal_size = buf[0];

        else if (ctx->length_size == 2)

            nal_size = AV_RB16(buf);

        else

            nal_size = AV_RB32(buf);

        buf += ctx->length_size;

        unit_type = *buf & 0x1f;

        /* prepend only to the first type 5 NAL unit of an IDR picture */

        if (ctx->first_idr && unit_type == 5) {

            alloc_and_copy(poutbuf, poutbuf_size,

                           ctx->sps_pps_data, ctx->size,

                           buf, nal_size);

            ctx->first_idr = 0;

        }

        else {

            alloc_and_copy(poutbuf, poutbuf_size,

                           NULL, 0,

                           buf, nal_size);

            if (!ctx->first_idr && unit_type == 1)

                ctx->first_idr = 1;

        }

        buf += nal_size;

        cumul_size += nal_size + ctx->length_size;

    } while (cumul_size < buf_size);

    return 1;

}


static uint_fast8_t vorbis_floor0_decode(vorbis_context *vc,

                                         vorbis_floor_data *vfu, float *vec) {

    vorbis_floor0 * vf=&vfu->t0;

    float * lsp=vf->lsp;

    uint_fast32_t amplitude;

    uint_fast32_t book_idx;

    amplitude=get_bits(&vc->gb, vf->amplitude_bits);

    if (amplitude>0) {

        float last = 0;

        uint_fast16_t lsp_len = 0;

        uint_fast16_t idx;

        vorbis_codebook codebook;

        book_idx=get_bits(&vc->gb, ilog(vf->num_books));

        if ( book_idx >= vf->num_books ) {

            av_log( vc->avccontext, AV_LOG_ERROR,

                    "floor0 dec: booknumber too high!\n" );

            //FIXME: look above

        }

        AV_DEBUG( "floor0 dec: booknumber: %u\n", book_idx );

        codebook=vc->codebooks[vf->book_list[book_idx]];

        while (lsp_len<vf->order) {

            int vec_off;

            AV_DEBUG( "floor0 dec: book dimension: %d\n", codebook.dimensions );

            AV_DEBUG( "floor0 dec: maximum depth: %d\n", codebook.maxdepth );

            /* read temp vector */

            vec_off=get_vlc2(&vc->gb,

                             codebook.vlc.table,

                             codebook.nb_bits,

                             codebook.maxdepth ) *

                             codebook.dimensions;

            AV_DEBUG( "floor0 dec: vector offset: %d\n", vec_off );

            /* copy each vector component and add last to it */

            for (idx=0; idx<codebook.dimensions; ++idx) {

                lsp[lsp_len+idx]=codebook.codevectors[vec_off+idx]+last;

            }

            last=lsp[lsp_len+idx-1]; /* set last to last vector component */

            lsp_len += codebook.dimensions;

        }

#ifdef V_DEBUG

        /* DEBUG: output lsp coeffs */

        {

            int idx;

            for ( idx = 0; idx < lsp_len; ++idx )

                AV_DEBUG("floor0 dec: coeff at %d is %f\n", idx, lsp[idx] );

        }

#endif

        /* synthesize floor output vector */

        {

            int i;

            int order=vf->order;

            float wstep=M_PI/vf->bark_map_size;

            for(i=0;i<order;i++) { lsp[i]=2.0f*cos(lsp[i]); }

            AV_DEBUG("floor0 synth: map_size=%d; m=%d; wstep=%f\n",

                     vf->map_size, order, wstep);

            i=0;

            while(i<vf->map_size) {

                int j, iter_cond=vf->map[i];

                float p=0.5f;

                float q=0.5f;

                float two_cos_w=2.0f*cos(wstep*iter_cond); // needed all times

                /* similar part for the q and p products */

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

                    q *= lsp[j]  -two_cos_w;

                    p *= lsp[j+1]-two_cos_w;

                }

                if(j==order) { // even order

                    p *= p*(2.0f-two_cos_w);

                    q *= q*(2.0f+two_cos_w);

                }

                else { // odd order

                    q *= two_cos_w-lsp[j]; // one more time for q

                    /* final step and square */

                    p *= p*(4.f-two_cos_w*two_cos_w);

                    q *= q;

                }

                /* calculate linear floor value */

                {

                    int_fast32_t pow_of_two=2, exponent=vf->amplitude_bits;

                    if ( vf->amplitude_bits ) {

                        while ( --exponent ) { pow_of_two <<= 1; }

                    }

                    else { pow_of_two=1; }

                    q=exp( (

                             ( (amplitude*vf->amplitude_offset)/

                               ((pow_of_two-1) * sqrt(p+q)) )

                             - vf->amplitude_offset ) * .11512925f

                         );

                }

                /* fill vector */

                do { vec[i]=q; ++i; }while(vf->map[i]==iter_cond);

            }

        }

    }

    else {

        /* this channel is unused */

        return 1;

    }

    AV_DEBUG(" Floor0 decoded\n");

    return 0;

}


static void check_itxfm(void)

{

    LOCAL_ALIGNED_32(uint8_t, src, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(uint8_t, dst, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(uint8_t, dst0, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(uint8_t, dst1, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(int16_t, coef, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(int16_t, subcoef0, [32 * 32 * 2]);

    LOCAL_ALIGNED_32(int16_t, subcoef1, [32 * 32 * 2]);

    declare_func_emms(AV_CPU_FLAG_MMX | AV_CPU_FLAG_MMXEXT, void, uint8_t *dst, ptrdiff_t stride, int16_t *block, int eob);

    VP9DSPContext dsp;

    int y, x, tx, txtp, bit_depth, sub;

    static const char *const txtp_types[N_TXFM_TYPES] = {

        [DCT_DCT] = "dct_dct", [DCT_ADST] = "adst_dct",

        [ADST_DCT] = "dct_adst", [ADST_ADST] = "adst_adst"

    };

    for (bit_depth = 8; bit_depth <= 12; bit_depth += 2) {

        ff_vp9dsp_init(&dsp, bit_depth, 0);

        for (tx = TX_4X4; tx <= N_TXFM_SIZES /* 4 = lossless */; tx++) {

            int sz = 4 << (tx & 3);

            int n_txtps = tx < TX_32X32 ? N_TXFM_TYPES : 1;

            for (txtp = 0; txtp < n_txtps; txtp++) {

                if (check_func(dsp.itxfm_add[tx][txtp], "vp9_inv_%s_%dx%d_add_%d",

                               tx == 4 ? "wht_wht" : txtp_types[txtp], sz, sz,

                               bit_depth)) {

                    randomize_buffers();

                    ftx(coef, tx, txtp, sz, bit_depth);

                    for (sub = (txtp == 0) ? 1 : 2; sub <= sz; sub <<= 1) {

                        int eob;

                        if (sub < sz) {

                            eob = copy_subcoefs(subcoef0, coef, tx, txtp,

                                                sz, sub, bit_depth);

                        } else {

                            eob = sz * sz;

                            memcpy(subcoef0, coef, sz * sz * SIZEOF_COEF);

                        }

                        memcpy(dst0, dst, sz * sz * SIZEOF_PIXEL);

                        memcpy(dst1, dst, sz * sz * SIZEOF_PIXEL);

                        memcpy(subcoef1, subcoef0, sz * sz * SIZEOF_COEF);

                        call_ref(dst0, sz * SIZEOF_PIXEL, subcoef0, eob);

                        call_new(dst1, sz * SIZEOF_PIXEL, subcoef1, eob);

                        if (memcmp(dst0, dst1, sz * sz * SIZEOF_PIXEL) ||

                            !iszero(subcoef0, sz * sz * SIZEOF_COEF) ||

                            !iszero(subcoef1, sz * sz * SIZEOF_COEF))

                            fail();

                    }

                    bench_new(dst, sz * SIZEOF_PIXEL, coef, sz * sz);

                }

            }

        }

    }

    report("itxfm");

}


void ff_put_h264_qpel4_mc32_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midh_qrt_4w_msa(src - (2 * stride) - 2, stride, dst, stride, 4, 1);

}


static void put_ebml_utf8(ByteIOContext *pb, unsigned int elementid, char *str)

{

    put_ebml_binary(pb, elementid, str, strlen(str));

}


static void compute_antialias_fixed(MPADecodeContext *s, GranuleDef *g)

{

    int32_t *ptr, *csa;

    int n, i;

    /* we antialias only "long" bands */

    if (g->block_type == 2) {

        if (!g->switch_point)

            return;

        /* XXX: check this for 8000Hz case */

        n = 1;

    } else {

        n = SBLIMIT - 1;

    }

    ptr = g->sb_hybrid + 18;

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

        int tmp0, tmp1, tmp2;

        csa = &csa_table[0][0];

#define INT_AA(j) \

            tmp0 = ptr[-1-j];\

            tmp1 = ptr[   j];\

            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\

            ptr[-1-j] = 4*(tmp2 - MULH(tmp1, csa[2+4*j]));\

            ptr[   j] = 4*(tmp2 + MULH(tmp0, csa[3+4*j]));

        INT_AA(0)

        INT_AA(1)

        INT_AA(2)

        INT_AA(3)

        INT_AA(4)

        INT_AA(5)

        INT_AA(6)

        INT_AA(7)

        ptr += 18;

    }

}


av_cold struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(enum IIRFilterType filt_type,

                                                    enum IIRFilterMode filt_mode,

                                                    int order, float cutoff_ratio,

                                                    float stopband, float ripple)

{

    int i, j;

    FFIIRFilterCoeffs *c;

    double wa;

    double p[MAXORDER + 1][2];

    if(filt_type != FF_FILTER_TYPE_BUTTERWORTH || filt_mode != FF_FILTER_MODE_LOWPASS)

        return NULL;

    if(order <= 1 || (order & 1) || order > MAXORDER || cutoff_ratio >= 1.0)

        return NULL;

    c = av_malloc(sizeof(FFIIRFilterCoeffs));

    c->cx = av_malloc(sizeof(c->cx[0]) * ((order >> 1) + 1));

    c->cy = av_malloc(sizeof(c->cy[0]) * order);

    c->order = order;

    wa = 2 * tan(M_PI * 0.5 * cutoff_ratio);

    c->cx[0] = 1;

    for(i = 1; i < (order >> 1) + 1; i++)

        c->cx[i] = c->cx[i - 1] * (order - i + 1LL) / i;

    p[0][0] = 1.0;

    p[0][1] = 0.0;

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

        p[i][0] = p[i][1] = 0.0;

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

        double zp[2];

        double th = (i + (order >> 1) + 0.5) * M_PI / order;

        double a_re, a_im, c_re, c_im;

        zp[0] = cos(th) * wa;

        zp[1] = sin(th) * wa;

        a_re = zp[0] + 2.0;

        c_re = zp[0] - 2.0;

        a_im =

        c_im = zp[1];

        zp[0] = (a_re * c_re + a_im * c_im) / (c_re * c_re + c_im * c_im);

        zp[1] = (a_im * c_re - a_re * c_im) / (c_re * c_re + c_im * c_im);

        for(j = order; j >= 1; j--)

        {

            a_re = p[j][0];

            a_im = p[j][1];

            p[j][0] = a_re*zp[0] - a_im*zp[1] + p[j-1][0];

            p[j][1] = a_re*zp[1] + a_im*zp[0] + p[j-1][1];

        }

        a_re    = p[0][0]*zp[0] - p[0][1]*zp[1];

        p[0][1] = p[0][0]*zp[1] + p[0][1]*zp[0];

        p[0][0] = a_re;

    }

    c->gain = p[order][0];

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

        c->gain += p[i][0];

        c->cy[i] = (-p[i][0] * p[order][0] + -p[i][1] * p[order][1]) /

                   (p[order][0] * p[order][0] + p[order][1] * p[order][1]);

    }

    c->gain /= 1 << order;

    return c;

}


static inline uint64_t ram_chunk_index(const uint8_t *start,

                                       const uint8_t *host)

{

    return ((uintptr_t) host - (uintptr_t) start) >> RDMA_REG_CHUNK_SHIFT;

}


static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)

{

    int64_t filesize, duration;

    int bit_rate, i;

    AVStream *st;

    /* if bit_rate is already set, we believe it */

    if (ic->bit_rate == 0) {

        bit_rate = 0;

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

            st = ic->streams[i];

            bit_rate += st->codec->bit_rate;

        }

        ic->bit_rate = bit_rate;

    }

    /* if duration is already set, we believe it */

    if (ic->duration == AV_NOPTS_VALUE &&

        ic->bit_rate != 0 &&

        ic->file_size != 0)  {

        filesize = ic->file_size;

        if (filesize > 0) {

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

                st = ic->streams[i];

                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);

                if (st->duration == AV_NOPTS_VALUE)

                    st->duration = duration;

            }

        }

    }

}


static void arm_tr_insn_start(DisasContextBase *dcbase, CPUState *cpu)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    dc->insn_start_idx = tcg_op_buf_count();

    tcg_gen_insn_start(dc->pc,

                       (dc->condexec_cond << 4) | (dc->condexec_mask >> 1),

                       0);

}


static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)

{

    int j, l, np, np2;

    int nblocks, nloops;

    register IComplex *p,*q;

    int tmp_re, tmp_im;

    np = 1 << ln;

    /* reverse */

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

        int k = av_reverse[j] >> (8 - ln);

        if (k < j)

            FFSWAP(IComplex, z[k], z[j]);

    }

    /* pass 0 */

    p = &z[0];

    j = np >> 1;

    do {

        BF(p[0].re, p[0].im, p[1].re, p[1].im,

           p[0].re, p[0].im, p[1].re, p[1].im);

        p += 2;

    } while (--j);

    /* pass 1 */

    p = &z[0];

    j = np >> 2;

    do {

        BF(p[0].re, p[0].im, p[2].re,  p[2].im,

           p[0].re, p[0].im, p[2].re,  p[2].im);

        BF(p[1].re, p[1].im, p[3].re,  p[3].im,

           p[1].re, p[1].im, p[3].im, -p[3].re);

        p+=4;

    } while (--j);

    /* pass 2 .. ln-1 */

    nblocks = np >> 3;

    nloops  =  1 << 2;

    np2     = np >> 1;

    do {

        p = z;

        q = z + nloops;

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

            BF(p->re, p->im, q->re, q->im,

               p->re, p->im, q->re, q->im);

            p++;

            q++;

            for(l = nblocks; l < np2; l += nblocks) {

                CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);

                BF(p->re, p->im, q->re,  q->im,

                   p->re, p->im, tmp_re, tmp_im);

                p++;

                q++;

            }

            p += nloops;

            q += nloops;

        }

        nblocks = nblocks >> 1;

        nloops  = nloops  << 1;

    } while (nblocks);

}