static int pcm_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *src = avpkt->data;

    int buf_size       = avpkt->size;

    PCMDecode *s       = avctx->priv_data;

    AVFrame *frame     = data;

    int sample_size, c, n, ret, samples_per_block;

    uint8_t *samples;

    int32_t *dst_int32_t;

    sample_size = av_get_bits_per_sample(avctx->codec_id) / 8;

    /* av_get_bits_per_sample returns 0 for AV_CODEC_ID_PCM_DVD */

    samples_per_block = 1;

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

        if (avctx->bits_per_coded_sample != 20 &&

            avctx->bits_per_coded_sample != 24) {

            av_log(avctx, AV_LOG_ERROR, "PCM DVD unsupported sample depth\n");

            return AVERROR(EINVAL);

        }

        /* 2 samples are interleaved per block in PCM_DVD */

        samples_per_block = 2;

        sample_size       = avctx->bits_per_coded_sample * 2 / 8;

    } else if (avctx->codec_id == AV_CODEC_ID_PCM_LXF) {

        /* we process 40-bit blocks per channel for LXF */

        samples_per_block = 2;

        sample_size       = 5;

    }

    if (sample_size == 0) {

        av_log(avctx, AV_LOG_ERROR, "Invalid sample_size\n");

        return AVERROR(EINVAL);

    }

    n = avctx->channels * sample_size;

    if (n && buf_size % n) {

        if (buf_size < n) {

            av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n");

            return -1;

        } else

            buf_size -= buf_size % n;

    }

    n = buf_size / sample_size;

    /* get output buffer */

    frame->nb_samples = n * samples_per_block / avctx->channels;

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {

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

        return ret;

    }

    samples = frame->data[0];

    switch (avctx->codec->id) {

    case AV_CODEC_ID_PCM_U32LE:

        DECODE(32, le32, src, samples, n, 0, 0x80000000)

        break;

    case AV_CODEC_ID_PCM_U32BE:

        DECODE(32, be32, src, samples, n, 0, 0x80000000)

        break;

    case AV_CODEC_ID_PCM_S24LE:

        DECODE(32, le24, src, samples, n, 8, 0)

        break;

    case AV_CODEC_ID_PCM_S24BE:

        DECODE(32, be24, src, samples, n, 8, 0)

        break;

    case AV_CODEC_ID_PCM_U24LE:

        DECODE(32, le24, src, samples, n, 8, 0x800000)

        break;

    case AV_CODEC_ID_PCM_U24BE:

        DECODE(32, be24, src, samples, n, 8, 0x800000)

        break;

    case AV_CODEC_ID_PCM_S24DAUD:

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

            uint32_t v = bytestream_get_be24(&src);

            v >>= 4; // sync flags are here

            AV_WN16A(samples, ff_reverse[(v >> 8) & 0xff] +

                             (ff_reverse[v        & 0xff] << 8));

            samples += 2;

        }

        break;

    case AV_CODEC_ID_PCM_S16LE_PLANAR:

    {

        int av_unused n2;

        n /= avctx->channels;

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

            samples = frame->extended_data[c];

#if HAVE_BIGENDIAN

            n2 = n;

            DECODE(16, le16, src, samples, n2, 0, 0)

#else

            memcpy(samples, src, n * 2);

            src += n * 2;

#endif

        }

        break;

    }

    case AV_CODEC_ID_PCM_U16LE:

        DECODE(16, le16, src, samples, n, 0, 0x8000)

        break;

    case AV_CODEC_ID_PCM_U16BE:

        DECODE(16, be16, src, samples, n, 0, 0x8000)

        break;

    case AV_CODEC_ID_PCM_S8:

        for (; n > 0; n--)

            *samples++ = *src++ + 128;

        break;

#if HAVE_BIGENDIAN

    case AV_CODEC_ID_PCM_F64LE:

        DECODE(64, le64, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S32LE:

    case AV_CODEC_ID_PCM_F32LE:

        DECODE(32, le32, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S16LE:

        DECODE(16, le16, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F64BE:

    case AV_CODEC_ID_PCM_F32BE:

    case AV_CODEC_ID_PCM_S32BE:

    case AV_CODEC_ID_PCM_S16BE:

#else

    case AV_CODEC_ID_PCM_F64BE:

        DECODE(64, be64, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F32BE:

    case AV_CODEC_ID_PCM_S32BE:

        DECODE(32, be32, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_S16BE:

        DECODE(16, be16, src, samples, n, 0, 0)

        break;

    case AV_CODEC_ID_PCM_F64LE:

    case AV_CODEC_ID_PCM_F32LE:

    case AV_CODEC_ID_PCM_S32LE:

    case AV_CODEC_ID_PCM_S16LE:

#endif /* HAVE_BIGENDIAN */

    case AV_CODEC_ID_PCM_U8:

        memcpy(samples, src, n * sample_size);

        break;

    case AV_CODEC_ID_PCM_ZORK:

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

            int v = *src++;

            if (v < 128)

                v = 128 - v;

            *samples++ = v;

        }

        break;

    case AV_CODEC_ID_PCM_ALAW:

    case AV_CODEC_ID_PCM_MULAW:

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

            AV_WN16A(samples, s->table[*src++]);

            samples += 2;

        }

        break;

    case AV_CODEC_ID_PCM_DVD:

    {

        const uint8_t *src8;

        dst_int32_t = (int32_t *)frame->data[0];

        n /= avctx->channels;

        switch (avctx->bits_per_coded_sample) {

        case 20:

            while (n--) {

                c    = avctx->channels;

                src8 = src + 4 * c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8   & 0xf0) <<  8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++ & 0x0f) << 12);

                }

                src = src8;

            }

            break;

        case 24:

            while (n--) {

                c    = avctx->channels;

                src8 = src + 4 * c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                }

                src = src8;

            }

            break;

        }

        break;

    }

    case AV_CODEC_ID_PCM_LXF:

    {

        int i;

        n /= avctx->channels;

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

            dst_int32_t = (int32_t *)frame->extended_data[c];

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

                // extract low 20 bits and expand to 32 bits

                *dst_int32_t++ =  (src[2]         << 28) |

                                  (src[1]         << 20) |

                                  (src[0]         << 12) |

                                 ((src[2] & 0x0F) <<  8) |

                                   src[1];

                // extract high 20 bits and expand to 32 bits

                *dst_int32_t++ =  (src[4]         << 24) |

                                  (src[3]         << 16) |

                                 ((src[2] & 0xF0) <<  8) |

                                  (src[4]         <<  4) |

                                  (src[3]         >>  4);

                src += 5;

            }

        }

        break;

    }

    default:

        return -1;

    }

    *got_frame_ptr = 1;

    return buf_size;

}


static void proxy_rewinddir(FsContext *ctx, V9fsFidOpenState *fs)

{

    rewinddir(fs->dir);

}


static int pci_ivshmem_init(PCIDevice *dev)

{

    IVShmemState *s = DO_UPCAST(IVShmemState, dev, dev);

    uint8_t *pci_conf;

    if (s->sizearg == NULL)

        s->ivshmem_size = 4 << 20; /* 4 MB default */

    else {

        s->ivshmem_size = ivshmem_get_size(s);

    }

    register_savevm(&s->dev.qdev, "ivshmem", 0, 0, ivshmem_save, ivshmem_load,

                                                                        dev);

    /* IRQFD requires MSI */

    if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD) &&

        !ivshmem_has_feature(s, IVSHMEM_MSI)) {

        fprintf(stderr, "ivshmem: ioeventfd/irqfd requires MSI\n");

        exit(1);

    }

    /* check that role is reasonable */

    if (s->role) {

        if (strncmp(s->role, "peer", 5) == 0) {

            s->role_val = IVSHMEM_PEER;

        } else if (strncmp(s->role, "master", 7) == 0) {

            s->role_val = IVSHMEM_MASTER;

        } else {

            fprintf(stderr, "ivshmem: 'role' must be 'peer' or 'master'\n");

            exit(1);

        }

    } else {

        s->role_val = IVSHMEM_MASTER; /* default */

    }

    if (s->role_val == IVSHMEM_PEER) {

        register_device_unmigratable(&s->dev.qdev, "ivshmem", s);

    }

    pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REDHAT_QUMRANET);

    pci_conf[0x02] = 0x10;

    pci_conf[0x03] = 0x11;

    pci_conf[PCI_COMMAND] = PCI_COMMAND_IO | PCI_COMMAND_MEMORY;

    pci_config_set_class(pci_conf, PCI_CLASS_MEMORY_RAM);

    pci_conf[PCI_HEADER_TYPE] = PCI_HEADER_TYPE_NORMAL;

    pci_config_set_interrupt_pin(pci_conf, 1);

    s->shm_pci_addr = 0;

    s->ivshmem_offset = 0;

    s->shm_fd = 0;

    s->ivshmem_mmio_io_addr = cpu_register_io_memory(ivshmem_mmio_read,

                                    ivshmem_mmio_write, s, DEVICE_NATIVE_ENDIAN);

    /* region for registers*/

    pci_register_bar(&s->dev, 0, IVSHMEM_REG_BAR_SIZE,

                           PCI_BASE_ADDRESS_SPACE_MEMORY, ivshmem_mmio_map);

    if ((s->server_chr != NULL) &&

                        (strncmp(s->server_chr->filename, "unix:", 5) == 0)) {

        /* if we get a UNIX socket as the parameter we will talk

         * to the ivshmem server to receive the memory region */

        if (s->shmobj != NULL) {

            fprintf(stderr, "WARNING: do not specify both 'chardev' "

                                                "and 'shm' with ivshmem\n");

        }

        IVSHMEM_DPRINTF("using shared memory server (socket = %s)\n",

                                                    s->server_chr->filename);

        if (ivshmem_has_feature(s, IVSHMEM_MSI)) {

            ivshmem_setup_msi(s);

        }

        /* we allocate enough space for 16 guests and grow as needed */

        s->nb_peers = 16;

        s->vm_id = -1;

        /* allocate/initialize space for interrupt handling */

        s->peers = qemu_mallocz(s->nb_peers * sizeof(Peer));

        pci_register_bar(&s->dev, 2, s->ivshmem_size,

                                PCI_BASE_ADDRESS_SPACE_MEMORY, ivshmem_map);

        s->eventfd_chr = qemu_mallocz(s->vectors * sizeof(CharDriverState *));

        qemu_chr_add_handlers(s->server_chr, ivshmem_can_receive, ivshmem_read,

                     ivshmem_event, s);

    } else {

        /* just map the file immediately, we're not using a server */

        int fd;

        if (s->shmobj == NULL) {

            fprintf(stderr, "Must specify 'chardev' or 'shm' to ivshmem\n");

        }

        IVSHMEM_DPRINTF("using shm_open (shm object = %s)\n", s->shmobj);

        /* try opening with O_EXCL and if it succeeds zero the memory

         * by truncating to 0 */

        if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR|O_EXCL,

                        S_IRWXU|S_IRWXG|S_IRWXO)) > 0) {

           /* truncate file to length PCI device's memory */

            if (ftruncate(fd, s->ivshmem_size) != 0) {

                fprintf(stderr, "ivshmem: could not truncate shared file\n");

            }

        } else if ((fd = shm_open(s->shmobj, O_CREAT|O_RDWR,

                        S_IRWXU|S_IRWXG|S_IRWXO)) < 0) {

            fprintf(stderr, "ivshmem: could not open shared file\n");

            exit(-1);

        }

        if (check_shm_size(s, fd) == -1) {

            exit(-1);

        }

        create_shared_memory_BAR(s, fd);

    }

    return 0;

}


void ff_thread_await_progress(ThreadFrame *f, int n, int field)

{

    PerThreadContext *p;

    atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;

    if (!progress ||

        atomic_load_explicit(&progress[field], memory_order_acquire) >= n)

        return;

    p = f->owner[field]->internal->thread_ctx;

    pthread_mutex_lock(&p->progress_mutex);

    if (f->owner[field]->debug&FF_DEBUG_THREADS)

        av_log(f->owner[field], AV_LOG_DEBUG,

               "thread awaiting %d field %d from %p\n", n, field, progress);

    while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)

        pthread_cond_wait(&p->progress_cond, &p->progress_mutex);

    pthread_mutex_unlock(&p->progress_mutex);

}


static void gen_compute_eflags_c(DisasContext *s, TCGv reg, bool inv)

{

    TCGv t0, t1;

    int size;

    switch (s->cc_op) {

    case CC_OP_SUBB ... CC_OP_SUBQ:

        /* (DATA_TYPE)(CC_DST + CC_SRC) < (DATA_TYPE)CC_SRC */

        size = s->cc_op - CC_OP_SUBB;

        t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);

        /* If no temporary was used, be careful not to alias t1 and t0.  */

        t0 = TCGV_EQUAL(t1, cpu_cc_src) ? cpu_tmp0 : reg;

        tcg_gen_add_tl(t0, cpu_cc_dst, cpu_cc_src);

        gen_extu(size, t0);

        goto add_sub;

    case CC_OP_ADDB ... CC_OP_ADDQ:

        /* (DATA_TYPE)CC_DST < (DATA_TYPE)CC_SRC */

        size = s->cc_op - CC_OP_ADDB;

        t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);

        t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);

    add_sub:

        tcg_gen_setcond_tl(inv ? TCG_COND_GEU : TCG_COND_LTU, reg, t0, t1);

        inv = false;

        break;

    case CC_OP_SBBB ... CC_OP_SBBQ:

        /* (DATA_TYPE)(CC_DST + CC_SRC + 1) <= (DATA_TYPE)CC_SRC */

        size = s->cc_op - CC_OP_SBBB;

        t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);

        if (TCGV_EQUAL(t1, reg) && TCGV_EQUAL(reg, cpu_cc_src)) {

            tcg_gen_mov_tl(cpu_tmp0, cpu_cc_src);

            t1 = cpu_tmp0;

        }

        tcg_gen_add_tl(reg, cpu_cc_dst, cpu_cc_src);

        tcg_gen_addi_tl(reg, reg, 1);

        gen_extu(size, reg);

        t0 = reg;

        goto adc_sbb;

    case CC_OP_ADCB ... CC_OP_ADCQ:

        /* (DATA_TYPE)CC_DST <= (DATA_TYPE)CC_SRC */

        size = s->cc_op - CC_OP_ADCB;

        t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);

        t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);

    adc_sbb:

        tcg_gen_setcond_tl(inv ? TCG_COND_GTU : TCG_COND_LEU, reg, t0, t1);

        inv = false;

        break;

    case CC_OP_LOGICB ... CC_OP_LOGICQ:

        tcg_gen_movi_tl(reg, 0);

        break;

    case CC_OP_INCB ... CC_OP_INCQ:

    case CC_OP_DECB ... CC_OP_DECQ:

        if (inv) {

            tcg_gen_xori_tl(reg, cpu_cc_src, 1);

        } else {

            tcg_gen_mov_tl(reg, cpu_cc_src);

        }

        inv = false;

        break;

    case CC_OP_SHLB ... CC_OP_SHLQ:

        /* (CC_SRC >> (DATA_BITS - 1)) & 1 */

        size = s->cc_op - CC_OP_SHLB;

        tcg_gen_shri_tl(reg, cpu_cc_src, (8 << size) - 1);

        tcg_gen_andi_tl(reg, reg, 1);

        break;

    case CC_OP_MULB ... CC_OP_MULQ:

        tcg_gen_setcondi_tl(inv ? TCG_COND_EQ : TCG_COND_NE,

                            reg, cpu_cc_src, 0);

        inv = false;

        break;

    case CC_OP_EFLAGS:

    case CC_OP_SARB ... CC_OP_SARQ:

        /* CC_SRC & 1 */

        tcg_gen_andi_tl(reg, cpu_cc_src, 1);

        break;

    default:

       /* The need to compute only C from CC_OP_DYNAMIC is important

          in efficiently implementing e.g. INC at the start of a TB.  */

       gen_update_cc_op(s);

       gen_helper_cc_compute_c(cpu_tmp2_i32, cpu_env, cpu_cc_op);

       tcg_gen_extu_i32_tl(reg, cpu_tmp2_i32);

       break;

    }

    if (inv) {

        tcg_gen_xori_tl(reg, reg, 1);

    }

}


static void test_struct(gconstpointer opaque)

{

    TestArgs *args = (TestArgs *) opaque;

    const SerializeOps *ops = args->ops;

    TestStruct *ts = struct_create();

    TestStruct *ts_copy = NULL;

    Error *err = NULL;

    void *serialize_data;

    ops->serialize(ts, &serialize_data, visit_struct, &err);

    ops->deserialize((void **)&ts_copy, serialize_data, visit_struct, &err);

    g_assert(err == NULL);

    struct_compare(ts, ts_copy);

    struct_cleanup(ts);

    struct_cleanup(ts_copy);

    ops->cleanup(serialize_data);

    g_free(args);

}


AVResampleContext *av_resample_init(int out_rate, int in_rate, int filter_size, int phase_shift, int linear, double cutoff){

    AVResampleContext *c= av_mallocz(sizeof(AVResampleContext));

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

    int phase_count= 1<<phase_shift;

    c->phase_shift= phase_shift;

    c->phase_mask= phase_count-1;

    c->linear= linear;

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

    c->filter_bank= av_mallocz(c->filter_length*(phase_count+1)*sizeof(FELEM));

    av_build_filter(c->filter_bank, factor, c->filter_length, phase_count, 1<<FILTER_SHIFT, 1);

    memcpy(&c->filter_bank[c->filter_length*phase_count+1], c->filter_bank, (c->filter_length-1)*sizeof(FELEM));

    c->filter_bank[c->filter_length*phase_count]= c->filter_bank[c->filter_length - 1];

    c->src_incr= out_rate;

    c->ideal_dst_incr= c->dst_incr= in_rate * phase_count;

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

    return c;

}


static int mov_read_elst(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

    MOVStreamContext *sc = c->fc->streams[c->fc->nb_streams-1]->priv_data;

    int i, edit_count;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    edit_count= sc->edit_count = get_be32(pb);     /* entries */

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

        int time;

        get_be32(pb); /* Track duration */

        time = get_be32(pb); /* Media time */

        get_be32(pb); /* Media rate */

        if (time != 0)

            av_log(c->fc, AV_LOG_WARNING, "edit list not starting at 0, "

                   "a/v desync might occur, patch welcome\n");

    }

    dprintf(c->fc, "track[%i].edit_count = %i\n", c->fc->nb_streams-1, sc->edit_count);

    return 0;

}


static void set_irq_level(void *opaque, int n, int level)

{

    NVICState *s = opaque;

    VecInfo *vec;

    n += NVIC_FIRST_IRQ;

    assert(n >= NVIC_FIRST_IRQ && n < s->num_irq);

    trace_nvic_set_irq_level(n, level);

    /* The pending status of an external interrupt is

     * latched on rising edge and exception handler return.

     *

     * Pulsing the IRQ will always run the handler

     * once, and the handler will re-run until the

     * level is low when the handler completes.

     */

    vec = &s->vectors[n];

    if (level != vec->level) {

        vec->level = level;

        if (level) {

            armv7m_nvic_set_pending(s, n);

        }

    }

}


static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){

    int time_incr, time_increment;

    s->pict_type = get_bits(gb, 2) + I_TYPE;	/* pict type: I = 0 , P = 1 */

    if(s->pict_type==B_TYPE && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){

        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set, but shouldnt, clearing it\n");

        s->low_delay=0;

    }

    s->partitioned_frame= s->data_partitioning && s->pict_type!=B_TYPE;

    if(s->partitioned_frame)

        s->decode_mb= mpeg4_decode_partitioned_mb;

    else

        s->decode_mb= ff_h263_decode_mb;

    if(s->time_increment_resolution==0){

        s->time_increment_resolution=1;

//        fprintf(stderr, "time_increment_resolution is illegal\n");

    }

    time_incr=0;

    while (get_bits1(gb) != 0)

        time_incr++;

    check_marker(gb, "before time_increment");

    if(s->time_increment_bits==0){

        av_log(s->avctx, AV_LOG_ERROR, "hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");

        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){

            if(show_bits(gb, s->time_increment_bits+1)&1) break;

        }

        av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);

    }

    if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further

    else time_increment= get_bits(gb, s->time_increment_bits);

//    printf("%d %X\n", s->time_increment_bits, time_increment);

//printf(" type:%d modulo_time_base:%d increment:%d\n", s->pict_type, time_incr, time_increment);

    if(s->pict_type!=B_TYPE){

        s->last_time_base= s->time_base;

        s->time_base+= time_incr;

        s->time= s->time_base*s->time_increment_resolution + time_increment;

        if(s->workaround_bugs&FF_BUG_UMP4){

            if(s->time < s->last_non_b_time){

//                fprintf(stderr, "header is not mpeg4 compatible, broken encoder, trying to workaround\n");

                s->time_base++;

                s->time+= s->time_increment_resolution;

            }

        }

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

        s->last_non_b_time= s->time;

    }else{

        s->time= (s->last_time_base + time_incr)*s->time_increment_resolution + time_increment;

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

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

//            printf("messed up order, seeking?, skiping current b frame\n");

            return FRAME_SKIPED;

        }

        if(s->t_frame==0) s->t_frame= s->time - s->last_time_base;

        if(s->t_frame==0) s->t_frame=1; // 1/0 protection

//printf("%Ld %Ld %d %d\n", s->last_non_b_time, s->time, s->pp_time, s->t_frame); fflush(stdout);

        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame)

                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;

        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame)

                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;

    }

    s->current_picture_ptr->pts= s->time*1000LL*1000LL / s->time_increment_resolution;

    if(s->avctx->debug&FF_DEBUG_PTS)

        av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %f\n", s->current_picture_ptr->pts/(1000.0*1000.0));

    check_marker(gb, "before vop_coded");

    /* vop coded */

    if (get_bits1(gb) != 1){

        av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");

        return FRAME_SKIPED;

    }

//printf("time %d %d %d || %Ld %Ld %Ld\n", s->time_increment_bits, s->time_increment_resolution, s->time_base,

//s->time, s->last_non_b_time, s->last_non_b_time - s->pp_time);

    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE

                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {

        /* rounding type for motion estimation */

	s->no_rounding = get_bits1(gb);

    } else {

	s->no_rounding = 0;

    }

//FIXME reduced res stuff

     if (s->shape != RECT_SHAPE) {

         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {

             int width, height, hor_spat_ref, ver_spat_ref;

             width = get_bits(gb, 13);

             skip_bits1(gb);   /* marker */

             height = get_bits(gb, 13);

             skip_bits1(gb);   /* marker */

             hor_spat_ref = get_bits(gb, 13); /* hor_spat_ref */

             skip_bits1(gb);   /* marker */

             ver_spat_ref = get_bits(gb, 13); /* ver_spat_ref */

         }

         skip_bits1(gb); /* change_CR_disable */

         if (get_bits1(gb) != 0) {

             skip_bits(gb, 8); /* constant_alpha_value */

         }

     }

//FIXME complexity estimation stuff

     if (s->shape != BIN_ONLY_SHAPE) {

         s->intra_dc_threshold= mpeg4_dc_threshold[ get_bits(gb, 3) ];

         if(!s->progressive_sequence){

             s->top_field_first= get_bits1(gb);

             s->alternate_scan= get_bits1(gb);

         }else

             s->alternate_scan= 0;

     }

     if(s->alternate_scan){

         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

     } else{

         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

     }

     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){

         mpeg4_decode_sprite_trajectory(s);

         if(s->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n");

         if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");

     }

     if (s->shape != BIN_ONLY_SHAPE) {

         s->qscale = get_bits(gb, s->quant_precision);

         if(s->qscale==0){

             av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (qscale=0)\n");

             return -1; // makes no sense to continue, as there is nothing left from the image then

         }

         if (s->pict_type != I_TYPE) {

             s->f_code = get_bits(gb, 3);	/* fcode_for */

             if(s->f_code==0){

                 av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (f_code=0)\n");

                 return -1; // makes no sense to continue, as the MV decoding will break very quickly

             }

         }else

             s->f_code=1;

         if (s->pict_type == B_TYPE) {

             s->b_code = get_bits(gb, 3);

         }else

             s->b_code=1;

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

             av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d\n",

                 s->qscale, s->f_code, s->b_code,

                 s->pict_type == I_TYPE ? "I" : (s->pict_type == P_TYPE ? "P" : (s->pict_type == B_TYPE ? "B" : "S")),

                 gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first,

                 s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,

                 s->sprite_warping_accuracy, 1-s->no_rounding, s->vo_type, s->vol_control_parameters ? " VOLC" : " ", s->intra_dc_threshold);

         }

         if(!s->scalability){

             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {

                 skip_bits1(gb); // vop shape coding type

             }

         }else{

             if(s->enhancement_type){

                 int load_backward_shape= get_bits1(gb);

                 if(load_backward_shape){

                     av_log(s->avctx, AV_LOG_ERROR, "load backward shape isnt supported\n");

                 }

             }

             skip_bits(gb, 2); //ref_select_code

         }

     }

     /* detect buggy encoders which dont set the low_delay flag (divx4/xvid/opendivx)*/

     // note we cannot detect divx5 without b-frames easyly (allthough its buggy too)

     if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==0 && s->picture_number==0){

         av_log(s->avctx, AV_LOG_ERROR, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");

         s->low_delay=1;

     }

     s->picture_number++; // better than pic number==0 allways ;)

     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support

     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;

     if(s->workaround_bugs&FF_BUG_EDGE){

         s->h_edge_pos= s->width;

         s->v_edge_pos= s->height;

     }

     return 0;

}


static inline void RENAME(uyvytoyv12)(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;

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

	{

#ifdef HAVE_MMX

		asm volatile(

			"xorl %%eax, %%eax		\n\t"

			"pcmpeqw %%mm7, %%mm7		\n\t"

			"psrlw $8, %%mm7		\n\t" // FF,00,FF,00...

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 64(%0, %%eax, 4)	\n\t"

			"movq (%0, %%eax, 4), %%mm0	\n\t" // UYVY UYVY(0)

			"movq 8(%0, %%eax, 4), %%mm1	\n\t" // UYVY UYVY(4)

			"movq %%mm0, %%mm2		\n\t" // UYVY UYVY(0)

			"movq %%mm1, %%mm3		\n\t" // UYVY UYVY(4)

			"pand %%mm7, %%mm0		\n\t" // U0V0 U0V0(0)

			"pand %%mm7, %%mm1		\n\t" // U0V0 U0V0(4)

			"psrlw $8, %%mm2		\n\t" // Y0Y0 Y0Y0(0)

			"psrlw $8, %%mm3		\n\t" // Y0Y0 Y0Y0(4)

			"packuswb %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(0)

			MOVNTQ" %%mm2, (%1, %%eax, 2)	\n\t"

			"movq 16(%0, %%eax, 4), %%mm1	\n\t" // UYVY UYVY(8)

			"movq 24(%0, %%eax, 4), %%mm2	\n\t" // UYVY UYVY(12)

			"movq %%mm1, %%mm3		\n\t" // UYVY UYVY(8)

			"movq %%mm2, %%mm4		\n\t" // UYVY UYVY(12)

			"pand %%mm7, %%mm1		\n\t" // U0V0 U0V0(8)

			"pand %%mm7, %%mm2		\n\t" // U0V0 U0V0(12)

			"psrlw $8, %%mm3		\n\t" // Y0Y0 Y0Y0(8)

			"psrlw $8, %%mm4		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm2, %%mm1		\n\t" // UVUV UVUV(8)

			"packuswb %%mm4, %%mm3		\n\t" // YYYY YYYY(8)

			MOVNTQ" %%mm3, 8(%1, %%eax, 2)	\n\t"

			"movq %%mm0, %%mm2		\n\t" // UVUV UVUV(0)

			"movq %%mm1, %%mm3		\n\t" // UVUV UVUV(8)

			"psrlw $8, %%mm0		\n\t" // V0V0 V0V0(0)

			"psrlw $8, %%mm1		\n\t" // V0V0 V0V0(8)

			"pand %%mm7, %%mm2		\n\t" // U0U0 U0U0(0)

			"pand %%mm7, %%mm3		\n\t" // U0U0 U0U0(8)

			"packuswb %%mm1, %%mm0		\n\t" // VVVV VVVV(0)

			"packuswb %%mm3, %%mm2		\n\t" // UUUU UUUU(0)

			MOVNTQ" %%mm0, (%3, %%eax)	\n\t"

			MOVNTQ" %%mm2, (%2, %%eax)	\n\t"

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

			"cmpl %4, %%eax			\n\t"

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%eax"

		);

		ydst += lumStride;

		src  += srcStride;

		asm volatile(

			"xorl %%eax, %%eax		\n\t"

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 64(%0, %%eax, 4)	\n\t"

			"movq (%0, %%eax, 4), %%mm0	\n\t" // YUYV YUYV(0)

			"movq 8(%0, %%eax, 4), %%mm1	\n\t" // YUYV YUYV(4)

			"movq 16(%0, %%eax, 4), %%mm2	\n\t" // YUYV YUYV(8)

			"movq 24(%0, %%eax, 4), %%mm3	\n\t" // YUYV YUYV(12)

			"psrlw $8, %%mm0		\n\t" // Y0Y0 Y0Y0(0)

			"psrlw $8, %%mm1		\n\t" // Y0Y0 Y0Y0(4)

			"psrlw $8, %%mm2		\n\t" // Y0Y0 Y0Y0(8)

			"psrlw $8, %%mm3		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm1, %%mm0		\n\t" // YYYY YYYY(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(8)

			MOVNTQ" %%mm0, (%1, %%eax, 2)	\n\t"

			MOVNTQ" %%mm2, 8(%1, %%eax, 2)	\n\t"

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

			"cmpl %4, %%eax			\n\t"

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%eax"

		);

#else

		long i;

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

		{

			udst[i] 	= src[4*i+0];

			ydst[2*i+0] 	= src[4*i+1];

			vdst[i] 	= src[4*i+2];

			ydst[2*i+1] 	= src[4*i+3];

		}

		ydst += lumStride;

		src  += srcStride;

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

		{

			ydst[2*i+0] 	= src[4*i+1];

			ydst[2*i+1] 	= src[4*i+3];

		}

#endif

		udst += chromStride;

		vdst += chromStride;

		ydst += lumStride;

		src  += srcStride;

	}

#ifdef HAVE_MMX

asm volatile(   EMMS" \n\t"

        	SFENCE" \n\t"

        	:::"memory");

#endif

}


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

{

    HLSContext *c = s->priv_data;

    int ret, i, minvariant = -1;

    if (c->first_packet) {

        recheck_discard_flags(s, 1);

        c->first_packet = 0;

    }

start:

    c->end_of_segment = 0;

    for (i = 0; i < c->n_variants; i++) {

        struct variant *var = c->variants[i];

        /* Make sure we've got one buffered packet from each open variant

         * stream */

        if (var->needed && !var->pkt.data) {

            while (1) {

                int64_t ts_diff;

                AVStream *st;

                ret = av_read_frame(var->ctx, &var->pkt);

                if (ret < 0) {

                    if (!var->pb.eof_reached)

                        return ret;

                    break;

                } else {

                    if (c->first_timestamp == AV_NOPTS_VALUE &&

                        var->pkt.dts       != AV_NOPTS_VALUE)

                        c->first_timestamp = av_rescale_q(var->pkt.dts,

                            var->ctx->streams[var->pkt.stream_index]->time_base,

                            AV_TIME_BASE_Q);

                }

                if (c->seek_timestamp == AV_NOPTS_VALUE)

                    break;

                if (var->pkt.dts == AV_NOPTS_VALUE) {

                    c->seek_timestamp = AV_NOPTS_VALUE;

                    break;

                }

                st = var->ctx->streams[var->pkt.stream_index];

                ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,

                                         st->time_base.den, AV_ROUND_DOWN) -

                          c->seek_timestamp;

                if (ts_diff >= 0 && (c->seek_flags  & AVSEEK_FLAG_ANY ||

                                     var->pkt.flags & AV_PKT_FLAG_KEY)) {

                    c->seek_timestamp = AV_NOPTS_VALUE;

                    break;

                }

            }

        }

        /* Check if this stream still is on an earlier segment number, or

         * has the packet with the lowest dts */

        if (var->pkt.data) {

            struct variant *minvar = c->variants[minvariant];

            if (minvariant < 0 || var->cur_seq_no < minvar->cur_seq_no) {

                minvariant = i;

            } else if (var->cur_seq_no == minvar->cur_seq_no) {

                int64_t dts     =    var->pkt.dts;

                int64_t mindts  = minvar->pkt.dts;

                AVStream *st    =    var->ctx->streams[var->pkt.stream_index];

                AVStream *minst = minvar->ctx->streams[minvar->pkt.stream_index];

                if (dts == AV_NOPTS_VALUE) {

                    minvariant = i;

                } else if (mindts != AV_NOPTS_VALUE) {

                    if (st->start_time    != AV_NOPTS_VALUE)

                        dts    -= st->start_time;

                    if (minst->start_time != AV_NOPTS_VALUE)

                        mindts -= minst->start_time;

                    if (av_compare_ts(dts, st->time_base,

                                      mindts, minst->time_base) < 0)

                        minvariant = i;

                }

            }

        }

    }

    if (c->end_of_segment) {

        if (recheck_discard_flags(s, 0))

            goto start;

    }

    /* If we got a packet, return it */

    if (minvariant >= 0) {

        *pkt = c->variants[minvariant]->pkt;

        pkt->stream_index += c->variants[minvariant]->stream_offset;

        reset_packet(&c->variants[minvariant]->pkt);

        return 0;

    }

    return AVERROR_EOF;

}


QObject *qmp_dispatch(QObject *request)

{

    Error *err = NULL;

    QObject *ret;

    QDict *rsp;

    ret = do_qmp_dispatch(request, &err);

    rsp = qdict_new();

    if (err) {

        qdict_put_obj(rsp, "error", error_get_qobject(err));

        error_free(err);

    } else if (ret) {

        qdict_put_obj(rsp, "return", ret);

    } else {

        QDECREF(rsp);

        return NULL;

    }

    return QOBJECT(rsp);

}


int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev)

{

    int i, r;

    hdev->started = true;

    r = vhost_dev_set_features(hdev, hdev->log_enabled);

    if (r < 0) {

        goto fail_features;

    }

    r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_MEM_TABLE, hdev->mem);

    if (r < 0) {

        r = -errno;

        goto fail_mem;

    }

    for (i = 0; i < hdev->nvqs; ++i) {

        r = vhost_virtqueue_start(hdev,

                                  vdev,

                                  hdev->vqs + i,

                                  hdev->vq_index + i);

        if (r < 0) {

            goto fail_vq;

        }

    }

    if (hdev->log_enabled) {

        hdev->log_size = vhost_get_log_size(hdev);

        hdev->log = hdev->log_size ?

            g_malloc0(hdev->log_size * sizeof *hdev->log) : NULL;

        r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_LOG_BASE, hdev->log);

        if (r < 0) {

            r = -errno;

            goto fail_log;

        }

    }

    return 0;

fail_log:

fail_vq:

    while (--i >= 0) {

        vhost_virtqueue_stop(hdev,

                             vdev,

                             hdev->vqs + i,

                             hdev->vq_index + i);

    }

    i = hdev->nvqs;

fail_mem:

fail_features:

    hdev->started = false;

    return r;

}


static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)

{

    int layno, reslevelno, compno, precno, ok_reslevel, ret;

    uint8_t prog_order = tile->codsty[0].prog_order;

    uint16_t x;

    uint16_t y;

    s->bit_index = 8;

    switch (prog_order) {

    case JPEG2000_PGOD_LRCP:

        for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {

            ok_reslevel = 1;

            for (reslevelno = 0; ok_reslevel; reslevelno++) {

                ok_reslevel = 0;

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

                    Jpeg2000CodingStyle *codsty = tile->codsty + compno;

                    Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

                    if (reslevelno < codsty->nreslevels) {

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +

                                                   reslevelno;

                        ok_reslevel = 1;

                        for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)

                            if ((ret = jpeg2000_decode_packet(s,

                                                              codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                    }

                }

            }

        }

        break;

    case JPEG2000_PGOD_CPRL:

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

            Jpeg2000CodingStyle *codsty = tile->codsty + compno;

            Jpeg2000QuantStyle *qntsty  = tile->qntsty + compno;

            /* Set bit stream buffer address according to tile-part.

             * For DCinema one tile-part per component, so can be

             * indexed by component. */

            s->buf = tile->tile_part[compno].tp_start_bstrm;

            /* Position loop (y axis)

             * TODO: Automate computing of step 256.

             * Fixed here, but to be computed before entering here. */

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

                /* Position loop (y axis)

                 * TODO: automate computing of step 256.

                 * Fixed here, but to be computed before entering here. */

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

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

                        uint16_t prcx, prcy;

                        uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; //  ==> N_L - r

                        Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;

                        if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||

                              (y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema

                            continue;

                        if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||

                              (x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema

                            continue;

                        // check if a precinct exists

                        prcx   = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;

                        prcy   = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;

                        precno = prcx + rlevel->num_precincts_x * prcy;

                        for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {

                            if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,

                                                              precno, layno,

                                                              qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),

                                                              qntsty->nguardbits)) < 0)

                                return ret;

                        }

                    }

                }

            }

        }

        break;

    default:

        break;

    }

    /* EOC marker reached */

    s->buf += 2;

    return 0;

}


static int io_open_default(AVFormatContext *s, AVIOContext **pb,
                           const char *url, int flags, AVDictionary **options)
{
#if FF_API_OLD_OPEN_CALLBACKS
FF_DISABLE_DEPRECATION_WARNINGS
    if (s->open_cb)
        return s->open_cb(s, pb, url, flags, &s->interrupt_callback, options);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
    return ffio_open_whitelist(pb, url, flags, &s->interrupt_callback, options, s->protocol_whitelist, s->protocol_blacklist);
}


static void mmubooke_dump_mmu(FILE *f, fprintf_function cpu_fprintf,

                                 CPUPPCState *env)

{

    ppcemb_tlb_t *entry;

    int i;

    if (kvm_enabled() && !env->kvm_sw_tlb) {

        cpu_fprintf(f, "Cannot access KVM TLB\n");

        return;

    }

    cpu_fprintf(f, "\nTLB:\n");

    cpu_fprintf(f, "Effective          Physical           Size PID   Prot     "

                "Attr\n");

    entry = &env->tlb.tlbe[0];

    for (i = 0; i < env->nb_tlb; i++, entry++) {

        hwaddr ea, pa;

        target_ulong mask;

        uint64_t size = (uint64_t)entry->size;

        char size_buf[20];

        /* Check valid flag */

        if (!(entry->prot & PAGE_VALID)) {

            continue;

        }

        mask = ~(entry->size - 1);

        ea = entry->EPN & mask;

        pa = entry->RPN & mask;

#if (TARGET_PHYS_ADDR_SPACE_BITS >= 36)

        /* Extend the physical address to 36 bits */

        pa |= (hwaddr)(entry->RPN & 0xF) << 32;

#endif

        size /= 1024;

        if (size >= 1024) {

            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "M", size / 1024);

        } else {

            snprintf(size_buf, sizeof(size_buf), "%3" PRId64 "k", size);

        }

        cpu_fprintf(f, "0x%016" PRIx64 " 0x%016" PRIx64 " %s %-5u %08x %08x\n",

                    (uint64_t)ea, (uint64_t)pa, size_buf, (uint32_t)entry->PID,

                    entry->prot, entry->attr);

    }

}


static void rstrip_spaces_buf(AVBPrint *buf)

{

    while (buf->len > 0 && buf->str[buf->len - 1] == ' ')

        buf->str[--buf->len] = 0;

}


static inline void RENAME(rgb24ToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    RENAME(bgr24ToY_mmx)(dst, src, width, PIX_FMT_RGB24);

#else

    int i;

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

        int r= src[i*3+0];

        int g= src[i*3+1];

        int b= src[i*3+2];

        dst[i]= ((RY*r + GY*g + BY*b + (33<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT);

    }

#endif

}


static int compand_drain(AVFilterLink *outlink)

{

    AVFilterContext *ctx = outlink->src;

    CompandContext *s    = ctx->priv;

    const int channels   = outlink->channels;

    AVFrame *frame       = NULL;

    int chan, i, dindex;

    /* 2048 is to limit output frame size during drain */

    frame = ff_get_audio_buffer(outlink, FFMIN(2048, s->delay_count));

    if (!frame)

        return AVERROR(ENOMEM);

    frame->pts = s->pts;

    s->pts += av_rescale_q(frame->nb_samples,

            (AVRational){ 1, outlink->sample_rate }, outlink->time_base);

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

        AVFrame *delay_frame = s->delay_frame;

        double *dbuf = (double *)delay_frame->extended_data[chan];

        double *dst = (double *)frame->extended_data[chan];

        ChanParam *cp = &s->channels[chan];

        dindex = s->delay_index;

        for (i = 0; i < frame->nb_samples; i++) {

            dst[i] = av_clipd(dbuf[dindex] * get_volume(s, cp->volume),

                    -1, 1);

            dindex = MOD(dindex + 1, s->delay_samples);

        }

    }

    s->delay_count -= frame->nb_samples;

    s->delay_index = dindex;

    return ff_filter_frame(outlink, frame);

}


InetSocketAddress *inet_parse(const char *str, Error **errp)

{

    InetSocketAddress *addr;

    const char *optstr, *h;

    char host[64];

    char port[33];

    int to;

    int pos;

    addr = g_new0(InetSocketAddress, 1);

    /* parse address */

    if (str[0] == ':') {

        /* no host given */

        host[0] = '\0';

        if (1 != sscanf(str, ":%32[^,]%n", port, &pos)) {

            error_setg(errp, "error parsing port in address '%s'", str);

            goto fail;

        }

    } else if (str[0] == '[') {

        /* IPv6 addr */

        if (2 != sscanf(str, "[%64[^]]]:%32[^,]%n", host, port, &pos)) {

            error_setg(errp, "error parsing IPv6 address '%s'", str);

            goto fail;

        }

        addr->ipv6 = addr->has_ipv6 = true;

    } else {

        /* hostname or IPv4 addr */

        if (2 != sscanf(str, "%64[^:]:%32[^,]%n", host, port, &pos)) {

            error_setg(errp, "error parsing address '%s'", str);

            goto fail;

        }

        if (host[strspn(host, "0123456789.")] == '\0') {

            addr->ipv4 = addr->has_ipv4 = true;

        }

    }

    addr->host = g_strdup(host);

    addr->port = g_strdup(port);

    /* parse options */

    optstr = str + pos;

    h = strstr(optstr, ",to=");

    if (h) {

        h += 4;

        if (sscanf(h, "%d%n", &to, &pos) != 1 ||

            (h[pos] != '\0' && h[pos] != ',')) {

            error_setg(errp, "error parsing to= argument");

            goto fail;

        }

        addr->has_to = true;

        addr->to = to;

    }

    if (strstr(optstr, ",ipv4")) {

        addr->ipv4 = addr->has_ipv4 = true;

    }

    if (strstr(optstr, ",ipv6")) {

        addr->ipv6 = addr->has_ipv6 = true;

    }

    return addr;

fail:

    qapi_free_InetSocketAddress(addr);

    return NULL;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PnvChipClass *k = PNV_CHIP_CLASS(klass);

    k->cpu_model = "POWER9";

    k->chip_type = PNV_CHIP_POWER9;

    k->chip_cfam_id = 0x100d104980000000ull; /* P9 Nimbus DD1.0 */

    k->cores_mask = POWER9_CORE_MASK;

    k->core_pir = pnv_chip_core_pir_p9;

    dc->desc = "PowerNV Chip POWER9";

}


static int rtsp_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

    RTSPState *rt = s->priv_data;

    RTSPStream *rtsp_st;

    int ret, len;

    uint8_t buf[RTP_MAX_PACKET_LENGTH];

    /* get next frames from the same RTP packet */

    if (rt->cur_rtp) {

        ret = rtp_parse_packet(rt->cur_rtp, pkt, NULL, 0);

        if (ret == 0) {

            rt->cur_rtp = NULL;

            return 0;

        } else if (ret == 1) {

            return 0;

        } else {

            rt->cur_rtp = NULL;

        }

    }

    /* read next RTP packet */

 redo:

    switch(rt->protocol) {

    default:

    case RTSP_PROTOCOL_RTP_TCP:

        len = tcp_read_packet(s, &rtsp_st, buf, sizeof(buf));

        break;

    case RTSP_PROTOCOL_RTP_UDP:

    case RTSP_PROTOCOL_RTP_UDP_MULTICAST:

        len = udp_read_packet(s, &rtsp_st, buf, sizeof(buf));

        if (rtsp_st->rtp_ctx)

            rtp_check_and_send_back_rr(rtsp_st->rtp_ctx, len);

        break;

    }

    if (len < 0)

        return AVERROR_IO;

    ret = rtp_parse_packet(rtsp_st->rtp_ctx, pkt, buf, len);

    if (ret < 0)

        goto redo;

    if (ret == 1) {

        /* more packets may follow, so we save the RTP context */

        rt->cur_rtp = rtsp_st->rtp_ctx;

    }

    return 0;

}


static void omap_rfbi_transfer_start(struct omap_dss_s *s)

{

    void *data;

    hwaddr len;

    hwaddr data_addr;

    int pitch;

    static void *bounce_buffer;

    static hwaddr bounce_len;

    if (!s->rfbi.enable || s->rfbi.busy)

        return;

    if (s->rfbi.control & (1 << 1)) {				/* BYPASS */

        /* TODO: in non-Bypass mode we probably need to just assert the

         * DRQ and wait for DMA to write the pixels.  */

        fprintf(stderr, "%s: Bypass mode unimplemented\n", __FUNCTION__);

        return;

    }

    if (!(s->dispc.control & (1 << 11)))			/* RFBIMODE */

        return;

    /* TODO: check that LCD output is enabled in DISPC.  */

    s->rfbi.busy = 1;

    len = s->rfbi.pixels * 2;

    data_addr = s->dispc.l[0].addr[0];

    data = cpu_physical_memory_map(data_addr, &len, 0);

    if (data && len != s->rfbi.pixels * 2) {

        cpu_physical_memory_unmap(data, len, 0, 0);

        data = NULL;

        len = s->rfbi.pixels * 2;

    }

    if (!data) {

        if (len > bounce_len) {

            bounce_buffer = g_realloc(bounce_buffer, len);

        }

        data = bounce_buffer;

        cpu_physical_memory_read(data_addr, data, len);

    }

    /* TODO bpp */

    s->rfbi.pixels = 0;

    /* TODO: negative values */

    pitch = s->dispc.l[0].nx + (s->dispc.l[0].rowinc - 1) / 2;

    if ((s->rfbi.control & (1 << 2)) && s->rfbi.chip[0])

        s->rfbi.chip[0]->block(s->rfbi.chip[0]->opaque, 1, data, len, pitch);

    if ((s->rfbi.control & (1 << 3)) && s->rfbi.chip[1])

        s->rfbi.chip[1]->block(s->rfbi.chip[1]->opaque, 1, data, len, pitch);

    if (data != bounce_buffer) {

        cpu_physical_memory_unmap(data, len, 0, len);

    }

    omap_rfbi_transfer_stop(s);

    /* TODO */

    s->dispc.irqst |= 1;					/* FRAMEDONE */

    omap_dispc_interrupt_update(s);

}


static bool aio_epoll_check_poll(AioContext *ctx, GPollFD *pfds,

                          unsigned npfd, int64_t timeout)

{

    return false;

}


static int source_config_props(AVFilterLink *outlink)

{

    AVFilterContext *ctx = outlink->src;

    Frei0rContext *s = ctx->priv;

    if (av_image_check_size(s->w, s->h, 0, ctx) < 0)

        return AVERROR(EINVAL);

    outlink->w = s->w;

    outlink->h = s->h;

    outlink->time_base = s->time_base;

    if (!(s->instance = s->construct(outlink->w, outlink->h))) {

        av_log(ctx, AV_LOG_ERROR, "Impossible to load frei0r instance");

        return AVERROR(EINVAL);

    }

    return set_params(ctx, s->params);

}


void spapr_tce_reset(DMAContext *dma)

{

    if (dma) {

        sPAPRTCETable *tcet = DO_UPCAST(sPAPRTCETable, dma, dma);

        size_t table_size = (tcet->window_size >> SPAPR_TCE_PAGE_SHIFT)

            * sizeof(sPAPRTCE);

        memset(tcet->table, 0, table_size);

    }

}


static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,

                             const char *replaces,

                             int64_t speed, uint32_t granularity,

                             int64_t buf_size,

                             BlockMirrorBackingMode backing_mode,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    }

    assert ((granularity & (granularity - 1)) == 0);

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    }

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    s = block_job_create(driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->target = blk_new();

    blk_insert_bs(s->target, target);

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->is_none_mode = is_none_mode;

    s->backing_mode = backing_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        g_free(s->replaces);

        blk_unref(s->target);

        block_job_unref(&s->common);

        return;

    }

    bdrv_op_block_all(target, s->common.blocker);

    s->common.co = qemu_coroutine_create(mirror_run);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


static inline int fp_reg_hi_offset(int regno)

{

    return offsetof(CPUARMState, vfp.regs[regno * 2 + 1]);

}


void qemu_spice_display_init(DisplayState *ds)

{

    assert(sdpy.ds == NULL);

    sdpy.ds = ds;

    sdpy.bufsize = (16 * 1024 * 1024);

    sdpy.buf = qemu_malloc(sdpy.bufsize);

    pthread_mutex_init(&sdpy.lock, NULL);

    register_displaychangelistener(ds, &display_listener);

    sdpy.qxl.base.sif = &dpy_interface.base;

    qemu_spice_add_interface(&sdpy.qxl.base);

    assert(sdpy.worker);

    qemu_add_vm_change_state_handler(qemu_spice_vm_change_state_handler, &sdpy);

    qemu_spice_create_host_memslot(&sdpy);

    qemu_spice_create_host_primary(&sdpy);

}


const DVprofile* ff_dv_frame_profile2(AVCodecContext* codec, const DVprofile *sys,

                                  const uint8_t* frame, unsigned buf_size)

{

   int i;

   int dsf = (frame[3] & 0x80) >> 7;

   int stype = frame[80*5 + 48 + 3] & 0x1f;

   /* 576i50 25Mbps 4:1:1 is a special case */

   if (dsf == 1 && stype == 0 && frame[4] & 0x07 /* the APT field */) {

       return &dv_profiles[2];

   }

   if(codec && codec->codec_tag==AV_RL32("dvsd") &&  codec->width==720 && codec->height==576)

       return &dv_profiles[1];

   for (i=0; i<FF_ARRAY_ELEMS(dv_profiles); i++)

       if (dsf == dv_profiles[i].dsf && stype == dv_profiles[i].video_stype)

           return &dv_profiles[i];

   /* check if old sys matches and assumes corrupted input */

   if (sys && buf_size == sys->frame_size)

       return sys;

   return NULL;

}


static void cryptodev_builtin_cleanup(

             CryptoDevBackend *backend,

             Error **errp)

{

    CryptoDevBackendBuiltin *builtin =

                      CRYPTODEV_BACKEND_BUILTIN(backend);

    size_t i;

    int queues = backend->conf.peers.queues;

    CryptoDevBackendClient *cc;

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

        if (builtin->sessions[i] != NULL) {

            cryptodev_builtin_sym_close_session(

                    backend, i, 0, errp);

        }

    }

    assert(queues == 1);

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

        cc = backend->conf.peers.ccs[i];

        if (cc) {

            cryptodev_backend_free_client(cc);

            backend->conf.peers.ccs[i] = NULL;

        }

    }

    cryptodev_backend_set_ready(backend, false);

}


static void clear_commits(BDRVVVFATState* s)

{

    int i;

DLOG(fprintf(stderr, "clear_commits (%d commits)\n", s->commits.next));

    for (i = 0; i < s->commits.next; i++) {

	commit_t* commit = array_get(&(s->commits), i);

	assert(commit->path || commit->action == ACTION_WRITEOUT);

	if (commit->action != ACTION_WRITEOUT) {

	    assert(commit->path);

	    free(commit->path);

	} else

	    assert(commit->path == NULL);

    }

    s->commits.next = 0;

}


vmxnet3_dump_rx_descr(struct Vmxnet3_RxDesc *descr)

{

    VMW_PKPRN("RX DESCR: addr %" PRIx64 ", len: %d, gen: %d, rsvd: %d, "

              "dtype: %d, ext1: %d, btype: %d",

              le64_to_cpu(descr->addr), descr->len, descr->gen,

              descr->rsvd, descr->dtype, descr->ext1, descr->btype);

}


static int mxf_compute_sample_count(MXFContext *mxf, int stream_index, uint64_t *sample_count)

{

    int i, total = 0, size = 0;

    AVStream *st = mxf->fc->streams[stream_index];

    MXFTrack *track = st->priv_data;

    AVRational time_base = av_inv_q(track->edit_rate);

    AVRational sample_rate = av_inv_q(st->time_base);

    const MXFSamplesPerFrame *spf = NULL;

    if ((sample_rate.num / sample_rate.den) == 48000)

        spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base);

    if (!spf) {

        int remainder = (sample_rate.num * time_base.num) % (time_base.den * sample_rate.den);

        *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1},

                                        av_mul_q(sample_rate, time_base)));

        if (remainder)

            av_log(mxf->fc, AV_LOG_WARNING,

                   "seeking detected on stream #%d with time base (%d/%d) and sample rate (%d/%d), audio pts won't be accurate.\n",

                   stream_index, time_base.num, time_base.den, sample_rate.num, sample_rate.den);

        return 0;

    }

    while (spf->samples_per_frame[size]) {

        total += spf->samples_per_frame[size];

        size++;

    }

    av_assert2(size);

    *sample_count = (mxf->current_edit_unit / size) * total;

    for (i = 0; i < mxf->current_edit_unit % size; i++) {

        *sample_count += spf->samples_per_frame[i];

    }

    return 0;

}


int do_netdev_del(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

    VLANClientState *vc;

    vc = qemu_find_netdev(id);

    if (!vc || vc->info->type == NET_CLIENT_TYPE_NIC) {

        qerror_report(QERR_DEVICE_NOT_FOUND, id);

        return -1;

    }

    if (vc->peer) {

        qerror_report(QERR_DEVICE_IN_USE, id);

        return -1;

    }

    qemu_del_vlan_client(vc);

    qemu_opts_del(qemu_opts_find(&qemu_netdev_opts, id));

    return 0;

}


int qcrypto_pbkdf2(QCryptoHashAlgorithm hash G_GNUC_UNUSED,

                   const uint8_t *key G_GNUC_UNUSED,

                   size_t nkey G_GNUC_UNUSED,

                   const uint8_t *salt G_GNUC_UNUSED,

                   size_t nsalt G_GNUC_UNUSED,

                   unsigned int iterations G_GNUC_UNUSED,

                   uint8_t *out G_GNUC_UNUSED,

                   size_t nout G_GNUC_UNUSED,

                   Error **errp)

{

    error_setg_errno(errp, ENOSYS,

                     "No crypto library supporting PBKDF in this build");

    return -1;

}


static void qmp_chardev_open_socket(Chardev *chr,

                                    ChardevBackend *backend,

                                    bool *be_opened,

                                    Error **errp)

{

    SocketChardev *s = SOCKET_CHARDEV(chr);

    ChardevSocket *sock = backend->u.socket.data;

    SocketAddress *addr = sock->addr;

    bool do_nodelay     = sock->has_nodelay ? sock->nodelay : false;

    bool is_listen      = sock->has_server  ? sock->server  : true;

    bool is_telnet      = sock->has_telnet  ? sock->telnet  : false;

    bool is_tn3270      = sock->has_tn3270  ? sock->tn3270  : false;

    bool is_waitconnect = sock->has_wait    ? sock->wait    : false;

    int64_t reconnect   = sock->has_reconnect ? sock->reconnect : 0;

    QIOChannelSocket *sioc = NULL;

    s->is_listen = is_listen;

    s->is_telnet = is_telnet;

    s->is_tn3270 = is_tn3270;

    s->do_nodelay = do_nodelay;

    if (sock->tls_creds) {

        Object *creds;

        creds = object_resolve_path_component(

            object_get_objects_root(), sock->tls_creds);

        if (!creds) {

            error_setg(errp, "No TLS credentials with id '%s'",

                       sock->tls_creds);

            goto error;

        }

        s->tls_creds = (QCryptoTLSCreds *)

            object_dynamic_cast(creds,

                                TYPE_QCRYPTO_TLS_CREDS);

        if (!s->tls_creds) {

            error_setg(errp, "Object with id '%s' is not TLS credentials",

                       sock->tls_creds);

            goto error;

        }

        object_ref(OBJECT(s->tls_creds));

        if (is_listen) {

            if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {

                error_setg(errp, "%s",

                           "Expected TLS credentials for server endpoint");

                goto error;

            }

        } else {

            if (s->tls_creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {

                error_setg(errp, "%s",

                           "Expected TLS credentials for client endpoint");

                goto error;

            }

        }

    }

    s->addr = QAPI_CLONE(SocketAddress, sock->addr);

    qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_RECONNECTABLE);

    /* TODO SOCKET_ADDRESS_FD where fd has AF_UNIX */

    if (addr->type == SOCKET_ADDRESS_KIND_UNIX) {

        qemu_chr_set_feature(chr, QEMU_CHAR_FEATURE_FD_PASS);

    }

    /* be isn't opened until we get a connection */

    *be_opened = false;

    update_disconnected_filename(s);

    if (is_listen) {

        if (is_telnet || is_tn3270) {

            s->do_telnetopt = 1;

        }

    } else if (reconnect > 0) {

        s->reconnect_time = reconnect;

    }

    if (s->reconnect_time) {

        sioc = qio_channel_socket_new();

        tcp_chr_set_client_ioc_name(chr, sioc);

        qio_channel_socket_connect_async(sioc, s->addr,

                                         qemu_chr_socket_connected,

                                         chr, NULL);

    } else {

        if (s->is_listen) {

            char *name;

            sioc = qio_channel_socket_new();

            name = g_strdup_printf("chardev-tcp-listener-%s", chr->label);

            qio_channel_set_name(QIO_CHANNEL(sioc), name);

            g_free(name);

            if (qio_channel_socket_listen_sync(sioc, s->addr, errp) < 0) {

                goto error;

            }

            qapi_free_SocketAddress(s->addr);

            s->addr = socket_local_address(sioc->fd, errp);

            update_disconnected_filename(s);

            s->listen_ioc = sioc;

            if (is_waitconnect &&

                qemu_chr_wait_connected(chr, errp) < 0) {

                return;

            }

            if (!s->ioc) {

                s->listen_tag = qio_channel_add_watch(

                    QIO_CHANNEL(s->listen_ioc), G_IO_IN,

                    tcp_chr_accept, chr, NULL);

            }

        } else if (qemu_chr_wait_connected(chr, errp) < 0) {

            goto error;

        }

    }

    return;

error:

    if (sioc) {

        object_unref(OBJECT(sioc));

    }

}


int mpeg4_decode_picture_header(MpegEncContext * s)

{

    int time_incr, startcode, state, v;

 redo:

    /* search next start code */

    align_get_bits(&s->gb);

    state = 0xff;

    for(;;) {

        v = get_bits(&s->gb, 8);

        if (state == 0x000001) {

            state = ((state << 8) | v) & 0xffffff;

            startcode = state;

            break;

        }

        state = ((state << 8) | v) & 0xffffff;

        if( get_bits_count(&s->gb) > s->gb.size*8){

            printf("no VOP startcode found\n");

            return -1;

        }

    }

//printf("startcode %X %d\n", startcode, get_bits_count(&s->gb));

    if (startcode == 0x120) { // Video Object Layer

        int width, height, vo_ver_id;

        /* vol header */

        skip_bits(&s->gb, 1); /* random access */

        skip_bits(&s->gb, 8); /* vo_type */

        if (get_bits1(&s->gb) != 0) { /* is_ol_id */

            vo_ver_id = get_bits(&s->gb, 4); /* vo_ver_id */

            skip_bits(&s->gb, 3); /* vo_priority */

        } else {

            vo_ver_id = 1;

        }

        s->aspect_ratio_info= get_bits(&s->gb, 4);

	if(s->aspect_ratio_info == EXTENDET_PAR){

            skip_bits(&s->gb, 8); //par_width

            skip_bits(&s->gb, 8); // par_height

        }

        if(get_bits1(&s->gb)){ /* vol control parameter */

            printf("vol control parameter not supported\n");

            return -1;

        }

        s->shape = get_bits(&s->gb, 2); /* vol shape */

        if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");

        if(s->shape == GRAY_SHAPE && vo_ver_id != 1){

            printf("Gray shape not supported\n");

            skip_bits(&s->gb, 4);  //video_object_layer_shape_extension

        }

        skip_bits1(&s->gb);   /* marker */

        s->time_increment_resolution = get_bits(&s->gb, 16);

        s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;

        if (s->time_increment_bits < 1)

            s->time_increment_bits = 1;

        skip_bits1(&s->gb);   /* marker */

        if (get_bits1(&s->gb) != 0) {   /* fixed_vop_rate  */

            skip_bits(&s->gb, s->time_increment_bits);

        }

        if (s->shape != BIN_ONLY_SHAPE) {

            if (s->shape == RECT_SHAPE) {

                skip_bits1(&s->gb);   /* marker */

                width = get_bits(&s->gb, 13);

                skip_bits1(&s->gb);   /* marker */

                height = get_bits(&s->gb, 13);

                skip_bits1(&s->gb);   /* marker */

                if(width && height){ /* they should be non zero but who knows ... */

                    s->width = width;

                    s->height = height;

//                    printf("%d %d\n", width, height);

                }

            }

            if(get_bits1(&s->gb)) printf("interlaced not supported\n");   /* interlaced */

            if(!get_bits1(&s->gb)) printf("OBMC not supported\n");   /* OBMC Disable */

            if (vo_ver_id == 1) {

                s->vol_sprite_usage = get_bits1(&s->gb); /* vol_sprite_usage */

            } else {

                s->vol_sprite_usage = get_bits(&s->gb, 2); /* vol_sprite_usage */

            }

            if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");

            if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){

                if(s->vol_sprite_usage==STATIC_SPRITE){

                    s->sprite_width = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_height= get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_left  = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                    s->sprite_top   = get_bits(&s->gb, 13);

                    skip_bits1(&s->gb); /* marker */

                }

                s->num_sprite_warping_points= get_bits(&s->gb, 6);

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

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

                if(s->vol_sprite_usage==STATIC_SPRITE)

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

            }

            // FIXME sadct disable bit if verid!=1 && shape not rect

            if (get_bits1(&s->gb) == 1) {   /* not_8_bit */

                s->quant_precision = get_bits(&s->gb, 4); /* quant_precision */

                if(get_bits(&s->gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */

            } else {

                s->quant_precision = 5;

            }

            // FIXME a bunch of grayscale shape things

            if(get_bits1(&s->gb)) printf("Quant-Type not supported\n");  /* vol_quant_type */ //FIXME

            if(vo_ver_id != 1)

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

            else s->quarter_sample=0;

            if(!get_bits1(&s->gb)) printf("Complexity estimation not supported\n");

#if 0

            if(get_bits1(&s->gb)) printf("resync disable\n");

#else

            skip_bits1(&s->gb);   /* resync_marker_disabled */

#endif

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

            if(s->data_partioning){

                printf("data partitioning not supported\n");

                skip_bits1(&s->gb); // reversible vlc

            }

            if(vo_ver_id != 1) {

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

                if(s->new_pred){

                    printf("new pred not supported\n");

                    skip_bits(&s->gb, 2); /* requested upstream message type */

                    skip_bits1(&s->gb); /* newpred segment type */

                }

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

                if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");

            }

            else{

                s->new_pred=0;

                s->reduced_res_vop= 0;

            }

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

            if (s->scalability) {

                printf("bad scalability!!!\n");

                return -1;

            }

        }

//printf("end Data %X %d\n", show_bits(&s->gb, 32), get_bits_count(&s->gb)&0x7);

        goto redo;

    } else if (startcode == 0x1b2) { //userdata

        char buf[256];

        int i;

        int e;

        int ver, build;

//printf("user Data %X\n", show_bits(&s->gb, 32));

        buf[0]= show_bits(&s->gb, 8);

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

            buf[i]= show_bits(&s->gb, 16)&0xFF;

            if(buf[i]==0) break;

            skip_bits(&s->gb, 8);

        }

        buf[255]=0;

        e=sscanf(buf, "DivX%dBuild%d", &ver, &build);

        if(e==2){

            s->divx_version= ver;

            s->divx_build= build;

            if(s->picture_number==0){

                printf("This file was encoded with DivX%d Build%d\n", ver, build);

                if(ver==500 && build==413){ //most likely all version are indeed totally buggy but i dunno for sure ...

                    printf("WARNING: this version of DivX is not MPEG4 compatible, trying to workaround these bugs...\n");

                }else{

                    printf("hmm, i havnt seen that version of divx yet, lets assume they fixed these bugs ...\n"

                           "using mpeg4 decoder, if it fails contact the developers (of ffmpeg)\n");

                }

            }

        }

//printf("User Data: %s\n", buf);

        goto redo;

    } else if (startcode != 0x1b6) { //VOP

        goto redo;

    }

    s->pict_type = get_bits(&s->gb, 2) + 1;	/* pict type: I = 0 , P = 1 */

//printf("pic: %d\n", s->pict_type);

    time_incr=0;

    while (get_bits1(&s->gb) != 0)

        time_incr++;

    check_marker(&s->gb, "before time_increment");

    s->time_increment= get_bits(&s->gb, s->time_increment_bits);

    if(s->pict_type!=B_TYPE){

        s->time_base+= time_incr;

        s->last_non_b_time[1]= s->last_non_b_time[0];

        s->last_non_b_time[0]= s->time_base*s->time_increment_resolution + s->time_increment;

    }else{

        s->time= (s->last_non_b_time[1]/s->time_increment_resolution + time_incr)*s->time_increment_resolution;

        s->time+= s->time_increment;

    }

    if(check_marker(&s->gb, "before vop_coded")==0 && s->picture_number==0){

        printf("hmm, seems the headers arnt complete, trying to guess time_increment_bits\n");

        for(s->time_increment_bits++ ;s->time_increment_bits<16; s->time_increment_bits++){

            if(get_bits1(&s->gb)) break;

        }

        printf("my guess is %d bits ;)\n",s->time_increment_bits);

    }

    /* vop coded */

    if (get_bits1(&s->gb) != 1)

        goto redo;

//printf("time %d %d %d || %d %d %d\n", s->time_increment_bits, s->time_increment, s->time_base,

//s->time, s->last_non_b_time[0], s->last_non_b_time[1]);

    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == P_TYPE

                          || (s->pict_type == S_TYPE && s->vol_sprite_usage==GMC_SPRITE))) {

        /* rounding type for motion estimation */

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

    } else {

	s->no_rounding = 0;

    }

//FIXME reduced res stuff

     if (s->shape != RECT_SHAPE) {

         if (s->vol_sprite_usage != 1 || s->pict_type != I_TYPE) {

             int width, height, hor_spat_ref, ver_spat_ref;

             width = get_bits(&s->gb, 13);

             skip_bits1(&s->gb);   /* marker */

             height = get_bits(&s->gb, 13);

             skip_bits1(&s->gb);   /* marker */

             hor_spat_ref = get_bits(&s->gb, 13); /* hor_spat_ref */

             skip_bits1(&s->gb);   /* marker */

             ver_spat_ref = get_bits(&s->gb, 13); /* ver_spat_ref */

         }

         skip_bits1(&s->gb); /* change_CR_disable */

         if (get_bits1(&s->gb) != 0) {

             skip_bits(&s->gb, 8); /* constant_alpha_value */

         }

     }

//FIXME complexity estimation stuff

     if (s->shape != BIN_ONLY_SHAPE) {

         skip_bits(&s->gb, 3); /* intra dc VLC threshold */

         //FIXME interlaced specific bits

     }

     if(s->pict_type == S_TYPE && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){

         if(s->num_sprite_warping_points){

             mpeg4_decode_sprite_trajectory(s);

         }

         if(s->sprite_brightness_change) printf("sprite_brightness_change not supported\n");

         if(s->vol_sprite_usage==STATIC_SPRITE) printf("static sprite not supported\n");

     }

     if (s->shape != BIN_ONLY_SHAPE) {

         /* note: we do not use quant_precision to avoid problem if no

            MPEG4 vol header as it is found on some old opendivx

            movies */

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

         if(s->qscale==0){

             printf("Error, header damaged or not MPEG4 header (qscale=0)\n");

             return -1; // makes no sense to continue, as there is nothing left from the image then

         }

         if (s->pict_type != I_TYPE) {

             s->f_code = get_bits(&s->gb, 3);	/* fcode_for */

             if(s->f_code==0){

                 printf("Error, header damaged or not MPEG4 header (f_code=0)\n");

                 return -1; // makes no sense to continue, as the MV decoding will break very quickly

             }

         }

         if (s->pict_type == B_TYPE) {

             s->b_code = get_bits(&s->gb, 3);

//printf("b-code %d\n", s->b_code);

         }

//printf("quant:%d fcode:%d\n", s->qscale, s->f_code);

         if(!s->scalability){

             if (s->shape!=RECT_SHAPE && s->pict_type!=I_TYPE) {

                 skip_bits1(&s->gb); // vop shape coding type

             }

         }

     }

     s->picture_number++; // better than pic number==0 allways ;)

     return 0;

}


static inline void vmxnet3_ring_read_curr_cell(Vmxnet3Ring *ring, void *buff)

{

    vmw_shmem_read(vmxnet3_ring_curr_cell_pa(ring), buff, ring->cell_size);

}


static CharDriverState* create_eventfd_chr_device(void * opaque, EventNotifier *n,

                                                  int vector)

{

    /* create a event character device based on the passed eventfd */

    IVShmemState *s = opaque;

    CharDriverState * chr;

    int eventfd = event_notifier_get_fd(n);

    chr = qemu_chr_open_eventfd(eventfd);

    if (chr == NULL) {

        fprintf(stderr, "creating eventfd for eventfd %d failed\n", eventfd);

        exit(-1);

    }

    /* if MSI is supported we need multiple interrupts */

    if (ivshmem_has_feature(s, IVSHMEM_MSI)) {

        s->eventfd_table[vector].pdev = &s->dev;

        s->eventfd_table[vector].vector = vector;

        qemu_chr_add_handlers(chr, ivshmem_can_receive, fake_irqfd,

                      ivshmem_event, &s->eventfd_table[vector]);

    } else {

        qemu_chr_add_handlers(chr, ivshmem_can_receive, ivshmem_receive,

                      ivshmem_event, s);

    }

    return chr;

}


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

{

    XICSState *icp = XICS(dev);

    Error *error = NULL;

    int i;

    if (!icp->nr_servers) {

        error_setg(errp, "Number of servers needs to be greater 0");

        return;

    }

    /* Registration of global state belongs into realize */

    spapr_rtas_register("ibm,set-xive", rtas_set_xive);

    spapr_rtas_register("ibm,get-xive", rtas_get_xive);

    spapr_rtas_register("ibm,int-off", rtas_int_off);

    spapr_rtas_register("ibm,int-on", rtas_int_on);

    spapr_register_hypercall(H_CPPR, h_cppr);

    spapr_register_hypercall(H_IPI, h_ipi);

    spapr_register_hypercall(H_XIRR, h_xirr);

    spapr_register_hypercall(H_XIRR_X, h_xirr_x);

    spapr_register_hypercall(H_EOI, h_eoi);

    spapr_register_hypercall(H_IPOLL, h_ipoll);

    object_property_set_bool(OBJECT(icp->ics), true, "realized", &error);

    if (error) {

        error_propagate(errp, error);

        return;

    }

    for (i = 0; i < icp->nr_servers; i++) {

        object_property_set_bool(OBJECT(&icp->ss[i]), true, "realized", &error);

        if (error) {

            error_propagate(errp, error);

            return;

        }

    }

}


int nbd_trip(BlockDriverState *bs, int csock, off_t size,

             uint64_t dev_offset, uint32_t nbdflags,

             uint8_t *data)

{

    struct nbd_request request;

    struct nbd_reply reply;

    int ret;

    TRACE("Reading request.");

    if (nbd_receive_request(csock, &request) == -1)

        return -1;

    if (request.len > NBD_BUFFER_SIZE) {

        LOG("len (%u) is larger than max len (%u)",

            request.len, NBD_BUFFER_SIZE);

        errno = EINVAL;

        return -1;

    }

    if ((request.from + request.len) < request.from) {

        LOG("integer overflow detected! "

            "you're probably being attacked");

        errno = EINVAL;

        return -1;

    }

    if ((request.from + request.len) > size) {

            LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64

            ", Offset: %" PRIu64 "\n",

                    request.from, request.len, (uint64_t)size, dev_offset);

        LOG("requested operation past EOF--bad client?");

        errno = EINVAL;

        return -1;

    }

    TRACE("Decoding type");

    reply.handle = request.handle;

    reply.error = 0;

    switch (request.type & NBD_CMD_MASK_COMMAND) {

    case NBD_CMD_READ:

        TRACE("Request type is READ");

        ret = bdrv_read(bs, (request.from + dev_offset) / 512,

                        data, request.len / 512);

        if (ret < 0) {

            LOG("reading from file failed");

            reply.error = -ret;

            request.len = 0;

        }

        TRACE("Read %u byte(s)", request.len);

        if (nbd_do_send_reply(csock, &reply, data, request.len) < 0)

            return -1;

        break;

    case NBD_CMD_WRITE:

        TRACE("Request type is WRITE");

        TRACE("Reading %u byte(s)", request.len);

        if (read_sync(csock, data, request.len) != request.len) {

            LOG("reading from socket failed");

            errno = EINVAL;

            return -1;

        }

        if (nbdflags & NBD_FLAG_READ_ONLY) {

            TRACE("Server is read-only, return error");

            reply.error = 1;

        } else {

            TRACE("Writing to device");

            ret = bdrv_write(bs, (request.from + dev_offset) / 512,

                             data, request.len / 512);

            if (ret < 0) {

                LOG("writing to file failed");

                reply.error = -ret;

                request.len = 0;

            }

            if (request.type & NBD_CMD_FLAG_FUA) {

                ret = bdrv_flush(bs);

                if (ret < 0) {

                    LOG("flush failed");

                    reply.error = -ret;

                }

            }

        }

        if (nbd_do_send_reply(csock, &reply, NULL, 0) < 0)

            return -1;

        break;

    case NBD_CMD_DISC:

        TRACE("Request type is DISCONNECT");

        errno = 0;

        return 1;

    case NBD_CMD_FLUSH:

        TRACE("Request type is FLUSH");

        ret = bdrv_flush(bs);

        if (ret < 0) {

            LOG("flush failed");

            reply.error = -ret;

        }

        if (nbd_do_send_reply(csock, &reply, NULL, 0) < 0)

            return -1;

        break;

    case NBD_CMD_TRIM:

        TRACE("Request type is TRIM");

        ret = bdrv_discard(bs, (request.from + dev_offset) / 512,

                           request.len / 512);

        if (ret < 0) {

            LOG("discard failed");

            reply.error = -ret;

        }

        if (nbd_do_send_reply(csock, &reply, NULL, 0) < 0)

            return -1;

        break;

    default:

        LOG("invalid request type (%u) received", request.type);

        errno = EINVAL;

        return -1;

    }

    TRACE("Request/Reply complete");

    return 0;

}


static int resample(SwrContext *s, AudioData *out_param, int out_count,

                             const AudioData * in_param, int in_count){

    AudioData in, out, tmp;

    int ret_sum=0;

    int border=0;

    av_assert1(s->in_buffer.ch_count == in_param->ch_count);

    av_assert1(s->in_buffer.planar   == in_param->planar);

    av_assert1(s->in_buffer.fmt      == in_param->fmt);

    tmp=out=*out_param;

    in =  *in_param;

    do{

        int ret, size, consumed;

        if(!s->resample_in_constraint && s->in_buffer_count){

            buf_set(&tmp, &s->in_buffer, s->in_buffer_index);

            ret= s->resampler->multiple_resample(s->resample, &out, out_count, &tmp, s->in_buffer_count, &consumed);

            out_count -= ret;

            ret_sum += ret;

            buf_set(&out, &out, ret);

            s->in_buffer_count -= consumed;

            s->in_buffer_index += consumed;

            if(!in_count)

                break;

            if(s->in_buffer_count <= border){

                buf_set(&in, &in, -s->in_buffer_count);

                in_count += s->in_buffer_count;

                s->in_buffer_count=0;

                s->in_buffer_index=0;

                border = 0;

            }

        }

        if((s->flushed || in_count) && !s->in_buffer_count){

            s->in_buffer_index=0;

            ret= s->resampler->multiple_resample(s->resample, &out, out_count, &in, in_count, &consumed);

            out_count -= ret;

            ret_sum += ret;

            buf_set(&out, &out, ret);

            in_count -= consumed;

            buf_set(&in, &in, consumed);

        }

        //TODO is this check sane considering the advanced copy avoidance below

        size= s->in_buffer_index + s->in_buffer_count + in_count;

        if(   size > s->in_buffer.count

           && s->in_buffer_count + in_count <= s->in_buffer_index){

            buf_set(&tmp, &s->in_buffer, s->in_buffer_index);

            copy(&s->in_buffer, &tmp, s->in_buffer_count);

            s->in_buffer_index=0;

        }else

            if((ret=swri_realloc_audio(&s->in_buffer, size)) < 0)

                return ret;

        if(in_count){

            int count= in_count;

            if(s->in_buffer_count && s->in_buffer_count+2 < count && out_count) count= s->in_buffer_count+2;

            buf_set(&tmp, &s->in_buffer, s->in_buffer_index + s->in_buffer_count);

            copy(&tmp, &in, /*in_*/count);

            s->in_buffer_count += count;

            in_count -= count;

            border += count;

            buf_set(&in, &in, count);

            s->resample_in_constraint= 0;

            if(s->in_buffer_count != count || in_count)

                continue;

        }

        break;

    }while(1);

    s->resample_in_constraint= !!out_count;

    return ret_sum;

}


static bool msi_is_masked(const PCIDevice *dev, unsigned int vector)

{

    uint16_t flags = pci_get_word(dev->config + msi_flags_off(dev));

    uint32_t mask;

    assert(vector < PCI_MSI_VECTORS_MAX);

    if (!(flags & PCI_MSI_FLAGS_MASKBIT)) {

        return false;

    }

    mask = pci_get_long(dev->config +

                        msi_mask_off(dev, flags & PCI_MSI_FLAGS_64BIT));

    return mask & (1U << vector);

}


static void ehci_opreg_write(void *ptr, hwaddr addr,

                             uint64_t val, unsigned size)

{

    EHCIState *s = ptr;

    uint32_t *mmio = s->opreg + (addr >> 2);

    uint32_t old = *mmio;

    int i;

    trace_usb_ehci_opreg_write(addr + s->opregbase, addr2str(addr), val);

    switch (addr) {

    case USBCMD:

        if (val & USBCMD_HCRESET) {

            ehci_reset(s);

            val = s->usbcmd;

            break;

        }

        /* not supporting dynamic frame list size at the moment */

        if ((val & USBCMD_FLS) && !(s->usbcmd & USBCMD_FLS)) {

            fprintf(stderr, "attempt to set frame list size -- value %d\n",

                    (int)val & USBCMD_FLS);

            val &= ~USBCMD_FLS;

        }

        if (val & USBCMD_IAAD) {

            /*

             * Process IAAD immediately, otherwise the Linux IAAD watchdog may

             * trigger and re-use a qh without us seeing the unlink.

             */

            s->async_stepdown = 0;

            qemu_bh_schedule(s->async_bh);

            trace_usb_ehci_doorbell_ring();

        }

        if (((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & val) !=

            ((USBCMD_RUNSTOP | USBCMD_PSE | USBCMD_ASE) & s->usbcmd)) {

            if (s->pstate == EST_INACTIVE) {

                SET_LAST_RUN_CLOCK(s);

            }

            s->usbcmd = val; /* Set usbcmd for ehci_update_halt() */

            ehci_update_halt(s);

            s->async_stepdown = 0;

            qemu_bh_schedule(s->async_bh);

        }

        break;

    case USBSTS:

        val &= USBSTS_RO_MASK;              // bits 6 through 31 are RO

        ehci_clear_usbsts(s, val);          // bits 0 through 5 are R/WC

        val = s->usbsts;

        ehci_update_irq(s);

        break;

    case USBINTR:

        val &= USBINTR_MASK;

        if (ehci_enabled(s) && (USBSTS_FLR & val)) {

            qemu_bh_schedule(s->async_bh);

        }

        break;

    case FRINDEX:

        val &= 0x00003ff8; /* frindex is 14bits and always a multiple of 8 */

        break;

    case CONFIGFLAG:

        val &= 0x1;

        if (val) {

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

                handle_port_owner_write(s, i, 0);

        }

        break;

    case PERIODICLISTBASE:

        if (ehci_periodic_enabled(s)) {

            fprintf(stderr,

              "ehci: PERIODIC list base register set while periodic schedule\n"

              "      is enabled and HC is enabled\n");

        }

        break;

    case ASYNCLISTADDR:

        if (ehci_async_enabled(s)) {

            fprintf(stderr,

              "ehci: ASYNC list address register set while async schedule\n"

              "      is enabled and HC is enabled\n");

        }

        break;

    }

    *mmio = val;

    trace_usb_ehci_opreg_change(addr + s->opregbase, addr2str(addr),

                                *mmio, old);

}


static void vfio_bar_quirk_teardown(VFIOPCIDevice *vdev, int nr)

{

    VFIOBAR *bar = &vdev->bars[nr];

    while (!QLIST_EMPTY(&bar->quirks)) {

        VFIOQuirk *quirk = QLIST_FIRST(&bar->quirks);

        memory_region_del_subregion(&bar->region.mem, &quirk->mem);

        object_unparent(OBJECT(&quirk->mem));

        QLIST_REMOVE(quirk, next);

        g_free(quirk);

    }

}


static int blkdebug_open(BlockDriverState *bs, QDict *options, int flags,

                         Error **errp)

{

    BDRVBlkdebugState *s = bs->opaque;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *config;

    uint64_t align;

    int ret;

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    /* Read rules from config file or command line options */

    config = qemu_opt_get(opts, "config");

    ret = read_config(s, config, options, errp);

    if (ret) {

        goto fail;

    }

    /* Set initial state */

    s->state = 1;

    /* Open the backing file */

    ret = bdrv_open_image(&bs->file, qemu_opt_get(opts, "x-image"), options, "image",

                          flags, true, false, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto fail;

    }

    /* Set request alignment */

    align = qemu_opt_get_size(opts, "align", bs->request_alignment);

    if (align > 0 && align < INT_MAX && !(align & (align - 1))) {

        bs->request_alignment = align;

    } else {

        error_setg(errp, "Invalid alignment");

        ret = -EINVAL;

        goto fail;

    }

    ret = 0;

fail:

    qemu_opts_del(opts);

    return ret;

}


void qemu_aio_init(void)

{

    struct sigaction act;

    aio_initialized = 1;

    sigfillset(&act.sa_mask);

    act.sa_flags = 0; /* do not restart syscalls to interrupt select() */

    act.sa_handler = aio_signal_handler;

    sigaction(aio_sig_num, &act, NULL);

#if defined(__GLIBC__) && defined(__linux__)

    {

        /* XXX: aio thread exit seems to hang on RedHat 9 and this init

           seems to fix the problem. */

        struct aioinit ai;

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

        ai.aio_threads = 1;

        ai.aio_num = 1;

        ai.aio_idle_time = 365 * 100000;

        aio_init(&ai);

    }

#endif

}


static void zynq_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    ObjectClass *cpu_oc;

    ARMCPU *cpu;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ext_ram = g_new(MemoryRegion, 1);

    MemoryRegion *ocm_ram = g_new(MemoryRegion, 1);

    DeviceState *dev;

    SysBusDevice *busdev;

    qemu_irq pic[64];

    Error *err = NULL;

    int n;

    if (!cpu_model) {

        cpu_model = "cortex-a9";

    }

    cpu_oc = cpu_class_by_name(TYPE_ARM_CPU, cpu_model);

    cpu = ARM_CPU(object_new(object_class_get_name(cpu_oc)));

    /* By default A9 CPUs have EL3 enabled.  This board does not

     * currently support EL3 so the CPU EL3 property is disabled before

     * realization.

     */

    if (object_property_find(OBJECT(cpu), "has_el3", NULL)) {

        object_property_set_bool(OBJECT(cpu), false, "has_el3", &err);

        if (err) {

            error_report_err(err);

            exit(1);

        }

    }

    object_property_set_int(OBJECT(cpu), ZYNQ_BOARD_MIDR, "midr", &err);

    if (err) {

        error_report_err(err);

        exit(1);

    }

    object_property_set_int(OBJECT(cpu), MPCORE_PERIPHBASE, "reset-cbar", &err);

    if (err) {

        error_report_err(err);

        exit(1);

    }

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

    if (err) {

        error_report_err(err);

        exit(1);

    }

    /* max 2GB ram */

    if (ram_size > 0x80000000) {

        ram_size = 0x80000000;

    }

    /* DDR remapped to address zero.  */

    memory_region_allocate_system_memory(ext_ram, NULL, "zynq.ext_ram",

                                         ram_size);

    memory_region_add_subregion(address_space_mem, 0, ext_ram);

    /* 256K of on-chip memory */

    memory_region_init_ram(ocm_ram, NULL, "zynq.ocm_ram", 256 << 10,

                           &error_abort);

    vmstate_register_ram_global(ocm_ram);

    memory_region_add_subregion(address_space_mem, 0xFFFC0000, ocm_ram);

    DriveInfo *dinfo = drive_get(IF_PFLASH, 0, 0);

    /* AMD */

    pflash_cfi02_register(0xe2000000, NULL, "zynq.pflash", FLASH_SIZE,

                          dinfo ? blk_by_legacy_dinfo(dinfo) : NULL,

                          FLASH_SECTOR_SIZE,

                          FLASH_SIZE/FLASH_SECTOR_SIZE, 1,

                          1, 0x0066, 0x0022, 0x0000, 0x0000, 0x0555, 0x2aa,

                              0);

    dev = qdev_create(NULL, "xilinx,zynq_slcr");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xF8000000);

    dev = qdev_create(NULL, "a9mpcore_priv");

    qdev_prop_set_uint32(dev, "num-cpu", 1);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, MPCORE_PERIPHBASE);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ));

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

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    zynq_init_spi_flashes(0xE0006000, pic[58-IRQ_OFFSET], false);

    zynq_init_spi_flashes(0xE0007000, pic[81-IRQ_OFFSET], false);

    zynq_init_spi_flashes(0xE000D000, pic[51-IRQ_OFFSET], true);

    sysbus_create_simple("xlnx,ps7-usb", 0xE0002000, pic[53-IRQ_OFFSET]);

    sysbus_create_simple("xlnx,ps7-usb", 0xE0003000, pic[76-IRQ_OFFSET]);

    sysbus_create_simple("cadence_uart", 0xE0000000, pic[59-IRQ_OFFSET]);

    sysbus_create_simple("cadence_uart", 0xE0001000, pic[82-IRQ_OFFSET]);

    sysbus_create_varargs("cadence_ttc", 0xF8001000,

            pic[42-IRQ_OFFSET], pic[43-IRQ_OFFSET], pic[44-IRQ_OFFSET], NULL);

    sysbus_create_varargs("cadence_ttc", 0xF8002000,

            pic[69-IRQ_OFFSET], pic[70-IRQ_OFFSET], pic[71-IRQ_OFFSET], NULL);

    gem_init(&nd_table[0], 0xE000B000, pic[54-IRQ_OFFSET]);

    gem_init(&nd_table[1], 0xE000C000, pic[77-IRQ_OFFSET]);

    dev = qdev_create(NULL, "generic-sdhci");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xE0100000);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[56-IRQ_OFFSET]);

    dev = qdev_create(NULL, "generic-sdhci");

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xE0101000);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[79-IRQ_OFFSET]);

    dev = qdev_create(NULL, "pl330");

    qdev_prop_set_uint8(dev, "num_chnls",  8);

    qdev_prop_set_uint8(dev, "num_periph_req",  4);

    qdev_prop_set_uint8(dev, "num_events",  16);

    qdev_prop_set_uint8(dev, "data_width",  64);

    qdev_prop_set_uint8(dev, "wr_cap",  8);

    qdev_prop_set_uint8(dev, "wr_q_dep",  16);

    qdev_prop_set_uint8(dev, "rd_cap",  8);

    qdev_prop_set_uint8(dev, "rd_q_dep",  16);

    qdev_prop_set_uint16(dev, "data_buffer_dep",  256);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xF8003000);

    sysbus_connect_irq(busdev, 0, pic[45-IRQ_OFFSET]); /* abort irq line */

    for (n = 0; n < 8; ++n) { /* event irqs */

        sysbus_connect_irq(busdev, n + 1, pic[dma_irqs[n] - IRQ_OFFSET]);

    }

    zynq_binfo.ram_size = ram_size;

    zynq_binfo.kernel_filename = kernel_filename;

    zynq_binfo.kernel_cmdline = kernel_cmdline;

    zynq_binfo.initrd_filename = initrd_filename;

    zynq_binfo.nb_cpus = 1;

    zynq_binfo.board_id = 0xd32;

    zynq_binfo.loader_start = 0;

    arm_load_kernel(ARM_CPU(first_cpu), &zynq_binfo);

}