static int img_create(int argc, char **argv)

{

    int c, ret, flags;

    const char *fmt = "raw";

    const char *base_fmt = NULL;

    const char *filename;

    const char *base_filename = NULL;

    BlockDriver *drv;

    QEMUOptionParameter *param = NULL;

    char *options = NULL;

    flags = 0;

    for(;;) {

        c = getopt(argc, argv, "F:b:f:he6o:");

        if (c == -1)

            break;

        switch(c) {

        case 'h':

            help();

            break;

        case 'F':

            base_fmt = optarg;

            break;

        case 'b':

            base_filename = optarg;

            break;

        case 'f':

            fmt = optarg;

            break;

        case 'e':

            flags |= BLOCK_FLAG_ENCRYPT;

            break;

        case '6':

            flags |= BLOCK_FLAG_COMPAT6;

            break;

        case 'o':

            options = optarg;

            break;

        }

    }

    /* Find driver and parse its options */

    drv = bdrv_find_format(fmt);

    if (!drv)

        error("Unknown file format '%s'", fmt);

    if (options && !strcmp(options, "?")) {

        print_option_help(drv->create_options);

        return 0;

    }

    if (options) {

        param = parse_option_parameters(options, drv->create_options, param);

        if (param == NULL) {

            error("Invalid options for file format '%s'.", fmt);

        }

    } else {

        param = parse_option_parameters("", drv->create_options, param);

    }

    /* Get the filename */

    if (optind >= argc)

        help();

    filename = argv[optind++];

    /* Add size to parameters */

    if (optind < argc) {

        set_option_parameter(param, BLOCK_OPT_SIZE, argv[optind++]);

    }

    /* Add old-style options to parameters */

    add_old_style_options(fmt, param, flags, base_filename, base_fmt);

    // The size for the image must always be specified, with one exception:

    // If we are using a backing file, we can obtain the size from there

    if (get_option_parameter(param, BLOCK_OPT_SIZE)->value.n == 0) {

        QEMUOptionParameter *backing_file =

            get_option_parameter(param, BLOCK_OPT_BACKING_FILE);

        QEMUOptionParameter *backing_fmt =

            get_option_parameter(param, BLOCK_OPT_BACKING_FMT);

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

            BlockDriverState *bs;

            uint64_t size;

            const char *fmt = NULL;

            char buf[32];

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

                 if (bdrv_find_format(backing_fmt->value.s)) {

                     fmt = backing_fmt->value.s;

                } else {

                     error("Unknown backing file format '%s'",

                        backing_fmt->value.s);

                }

            }

            bs = bdrv_new_open(backing_file->value.s, fmt);

            bdrv_get_geometry(bs, &size);

            size *= 512;

            bdrv_delete(bs);

            snprintf(buf, sizeof(buf), "%" PRId64, size);

            set_option_parameter(param, BLOCK_OPT_SIZE, buf);

        } else {

            error("Image creation needs a size parameter");

        }

    }

    printf("Formatting '%s', fmt=%s ", filename, fmt);

    print_option_parameters(param);

    puts("");

    ret = bdrv_create(drv, filename, param);

    free_option_parameters(param);

    if (ret < 0) {

        if (ret == -ENOTSUP) {

            error("Formatting or formatting option not supported for file format '%s'", fmt);

        } else if (ret == -EFBIG) {

            error("The image size is too large for file format '%s'", fmt);

        } else {

            error("Error while formatting");

        }

    }

    return 0;

}


static int fill_filter_caches(H264Context *h, int mb_type){

    MpegEncContext * const s = &h->s;

    const int mb_xy= h->mb_xy;

    int top_xy, left_xy[2];

    int top_type, left_type[2];

    top_xy     = mb_xy  - (s->mb_stride << MB_FIELD);

    //FIXME deblocking could skip the intra and nnz parts.

    /* Wow, what a mess, why didn't they simplify the interlacing & intra

     * stuff, I can't imagine that these complex rules are worth it. */

    left_xy[1] = left_xy[0] = mb_xy-1;

    if(FRAME_MBAFF){

        const int left_mb_field_flag     = IS_INTERLACED(s->current_picture.mb_type[mb_xy-1]);

        const int curr_mb_field_flag     = IS_INTERLACED(mb_type);

        if(s->mb_y&1){

            if (left_mb_field_flag != curr_mb_field_flag) {

                left_xy[0] -= s->mb_stride;

            }

        }else{

            if(curr_mb_field_flag){

                top_xy      += s->mb_stride & (((s->current_picture.mb_type[top_xy    ]>>7)&1)-1);

            }

            if (left_mb_field_flag != curr_mb_field_flag) {

                left_xy[1] += s->mb_stride;

            }

        }

    }

    h->top_mb_xy = top_xy;

    h->left_mb_xy[0] = left_xy[0];

    h->left_mb_xy[1] = left_xy[1];

    {

        //for sufficiently low qp, filtering wouldn't do anything

        //this is a conservative estimate: could also check beta_offset and more accurate chroma_qp

        int qp_thresh = h->qp_thresh; //FIXME strictly we should store qp_thresh for each mb of a slice

        int qp = s->current_picture.qscale_table[mb_xy];

        if(qp <= qp_thresh

           && (left_xy[0]<0 || ((qp + s->current_picture.qscale_table[left_xy[0]] + 1)>>1) <= qp_thresh)

           && (top_xy   < 0 || ((qp + s->current_picture.qscale_table[top_xy    ] + 1)>>1) <= qp_thresh)){

            if(!FRAME_MBAFF)

                return 1;

            if(   (left_xy[0]< 0            || ((qp + s->current_picture.qscale_table[left_xy[1]             ] + 1)>>1) <= qp_thresh)

               && (top_xy    < s->mb_stride || ((qp + s->current_picture.qscale_table[top_xy    -s->mb_stride] + 1)>>1) <= qp_thresh))

                return 1;

        }

    }

    top_type     = s->current_picture.mb_type[top_xy]    ;

    left_type[0] = s->current_picture.mb_type[left_xy[0]];

    left_type[1] = s->current_picture.mb_type[left_xy[1]];

    if(h->deblocking_filter == 2){

        if(h->slice_table[top_xy     ] != h->slice_num) top_type= 0;

        if(h->slice_table[left_xy[0] ] != h->slice_num) left_type[0]= left_type[1]= 0;

    }else{

        if(h->slice_table[top_xy     ] == 0xFFFF) top_type= 0;

        if(h->slice_table[left_xy[0] ] == 0xFFFF) left_type[0]= left_type[1] =0;

    }

    h->top_type    = top_type    ;

    h->left_type[0]= left_type[0];

    h->left_type[1]= left_type[1];

    if(IS_INTRA(mb_type))

        return 0;

    AV_COPY32(&h->non_zero_count_cache[4+8* 1], &h->non_zero_count[mb_xy][ 0]);

    AV_COPY32(&h->non_zero_count_cache[4+8* 2], &h->non_zero_count[mb_xy][ 4]);

    AV_COPY32(&h->non_zero_count_cache[4+8* 3], &h->non_zero_count[mb_xy][ 8]);

    AV_COPY32(&h->non_zero_count_cache[4+8* 4], &h->non_zero_count[mb_xy][12]);

    h->cbp= h->cbp_table[mb_xy];

    {

        int list;

        for(list=0; list<h->list_count; list++){

            int8_t *ref;

            int y, b_stride;

            int16_t (*mv_dst)[2];

            int16_t (*mv_src)[2];

            if(!USES_LIST(mb_type, list)){

                fill_rectangle(  h->mv_cache[list][scan8[0]], 4, 4, 8, pack16to32(0,0), 4);

                AV_WN32A(&h->ref_cache[list][scan8[ 0]], ((LIST_NOT_USED)&0xFF)*0x01010101u);

                AV_WN32A(&h->ref_cache[list][scan8[ 2]], ((LIST_NOT_USED)&0xFF)*0x01010101u);

                AV_WN32A(&h->ref_cache[list][scan8[ 8]], ((LIST_NOT_USED)&0xFF)*0x01010101u);

                AV_WN32A(&h->ref_cache[list][scan8[10]], ((LIST_NOT_USED)&0xFF)*0x01010101u);

                continue;

            }

            ref = &s->current_picture.ref_index[list][4*mb_xy];

            {

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

                AV_WN32A(&h->ref_cache[list][scan8[ 0]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);

                AV_WN32A(&h->ref_cache[list][scan8[ 2]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);

                ref += 2;

                AV_WN32A(&h->ref_cache[list][scan8[ 8]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);

                AV_WN32A(&h->ref_cache[list][scan8[10]], (pack16to32(ref2frm[list][ref[0]],ref2frm[list][ref[1]])&0x00FF00FF)*0x0101);

            }

            b_stride = h->b_stride;

            mv_dst   = &h->mv_cache[list][scan8[0]];

            mv_src   = &s->current_picture.motion_val[list][4*s->mb_x + 4*s->mb_y*b_stride];

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

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

            }

        }

    }

/*

0 . T T. T T T T

1 L . .L . . . .

2 L . .L . . . .

3 . T TL . . . .

4 L . .L . . . .

5 L . .. . . . .

*/

//FIXME constraint_intra_pred & partitioning & nnz (let us hope this is just a typo in the spec)

    if(top_type){

        AV_COPY32(&h->non_zero_count_cache[4+8*0], &h->non_zero_count[top_xy][3*4]);

    }

    if(left_type[0]){

        h->non_zero_count_cache[3+8*1]= h->non_zero_count[left_xy[0]][3+0*4];

        h->non_zero_count_cache[3+8*2]= h->non_zero_count[left_xy[0]][3+1*4];

        h->non_zero_count_cache[3+8*3]= h->non_zero_count[left_xy[0]][3+2*4];

        h->non_zero_count_cache[3+8*4]= h->non_zero_count[left_xy[0]][3+3*4];

    }

    // CAVLC 8x8dct requires NNZ values for residual decoding that differ from what the loop filter needs

    if(!CABAC && h->pps.transform_8x8_mode){

        if(IS_8x8DCT(top_type)){

            h->non_zero_count_cache[4+8*0]=

            h->non_zero_count_cache[5+8*0]= (h->cbp_table[top_xy] & 0x4000) >> 12;

            h->non_zero_count_cache[6+8*0]=

            h->non_zero_count_cache[7+8*0]= (h->cbp_table[top_xy] & 0x8000) >> 12;

        }

        if(IS_8x8DCT(left_type[0])){

            h->non_zero_count_cache[3+8*1]=

            h->non_zero_count_cache[3+8*2]= (h->cbp_table[left_xy[0]]&0x2000) >> 12; //FIXME check MBAFF

        }

        if(IS_8x8DCT(left_type[1])){

            h->non_zero_count_cache[3+8*3]=

            h->non_zero_count_cache[3+8*4]= (h->cbp_table[left_xy[1]]&0x8000) >> 12; //FIXME check MBAFF

        }

        if(IS_8x8DCT(mb_type)){

            h->non_zero_count_cache[scan8[0   ]]= h->non_zero_count_cache[scan8[1   ]]=

            h->non_zero_count_cache[scan8[2   ]]= h->non_zero_count_cache[scan8[3   ]]= (h->cbp & 0x1000) >> 12;

            h->non_zero_count_cache[scan8[0+ 4]]= h->non_zero_count_cache[scan8[1+ 4]]=

            h->non_zero_count_cache[scan8[2+ 4]]= h->non_zero_count_cache[scan8[3+ 4]]= (h->cbp & 0x2000) >> 12;

            h->non_zero_count_cache[scan8[0+ 8]]= h->non_zero_count_cache[scan8[1+ 8]]=

            h->non_zero_count_cache[scan8[2+ 8]]= h->non_zero_count_cache[scan8[3+ 8]]= (h->cbp & 0x4000) >> 12;

            h->non_zero_count_cache[scan8[0+12]]= h->non_zero_count_cache[scan8[1+12]]=

            h->non_zero_count_cache[scan8[2+12]]= h->non_zero_count_cache[scan8[3+12]]= (h->cbp & 0x8000) >> 12;

        }

    }

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

        int list;

        for(list=0; list<h->list_count; list++){

            if(USES_LIST(top_type, list)){

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

                const int b8_xy= 4*top_xy + 2;

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

                AV_COPY128(h->mv_cache[list][scan8[0] + 0 - 1*8], s->current_picture.motion_val[list][b_xy + 0]);

                h->ref_cache[list][scan8[0] + 0 - 1*8]=

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

                h->ref_cache[list][scan8[0] + 2 - 1*8]=

                h->ref_cache[list][scan8[0] + 3 - 1*8]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 1]];

            }else{

                AV_ZERO128(h->mv_cache[list][scan8[0] + 0 - 1*8]);

                AV_WN32A(&h->ref_cache[list][scan8[0] + 0 - 1*8], ((LIST_NOT_USED)&0xFF)*0x01010101u);

            }

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

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

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

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

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

                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 0 ], s->current_picture.motion_val[list][b_xy + h->b_stride*0]);

                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 + 8 ], s->current_picture.motion_val[list][b_xy + h->b_stride*1]);

                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +16 ], s->current_picture.motion_val[list][b_xy + h->b_stride*2]);

                    AV_COPY32(h->mv_cache[list][scan8[0] - 1 +24 ], s->current_picture.motion_val[list][b_xy + h->b_stride*3]);

                    h->ref_cache[list][scan8[0] - 1 + 0 ]=

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

                    h->ref_cache[list][scan8[0] - 1 +16 ]=

                    h->ref_cache[list][scan8[0] - 1 +24 ]= ref2frm[list][s->current_picture.ref_index[list][b8_xy + 2*1]];

                }else{

                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 0 ]);

                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 + 8 ]);

                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +16 ]);

                    AV_ZERO32(h->mv_cache [list][scan8[0] - 1 +24 ]);

                    h->ref_cache[list][scan8[0] - 1 + 0  ]=

                    h->ref_cache[list][scan8[0] - 1 + 8  ]=

                    h->ref_cache[list][scan8[0] - 1 + 16 ]=

                    h->ref_cache[list][scan8[0] - 1 + 24 ]= LIST_NOT_USED;

                }

            }

        }

    }

    return 0;

}


static void test_visitor_in_list(TestInputVisitorData *data,

                                 const void *unused)

{

    UserDefOneList *item, *head = NULL;

    Error *err = NULL;

    Visitor *v;

    int i;

    v = visitor_input_test_init(data, "[ { 'string': 'string0', 'integer': 42 }, { 'string': 'string1', 'integer': 43 }, { 'string': 'string2', 'integer': 44 } ]");

    visit_type_UserDefOneList(v, &head, NULL, &err);

    g_assert(!err);

    g_assert(head != NULL);

    for (i = 0, item = head; item; item = item->next, i++) {

        char string[12];

        snprintf(string, sizeof(string), "string%d", i);

        g_assert_cmpstr(item->value->string, ==, string);

        g_assert_cmpint(item->value->base->integer, ==, 42 + i);

    }

    qapi_free_UserDefOneList(head);

}


static inline void tcg_out_ext8u(TCGContext *s, int dest, int src)

{

    /* movzbl */

    assert(src < 4 || TCG_TARGET_REG_BITS == 64);

    tcg_out_modrm(s, OPC_MOVZBL + P_REXB_RM, dest, src);

}


static int cpu_post_load(void *opaque, int version_id)

{

    ARMCPU *cpu = opaque;

    int i, v;

    /* Update the values list from the incoming migration data.

     * Anything in the incoming data which we don't know about is

     * a migration failure; anything we know about but the incoming

     * data doesn't specify retains its current (reset) value.

     * The indexes list remains untouched -- we only inspect the

     * incoming migration index list so we can match the values array

     * entries with the right slots in our own values array.

     */

    for (i = 0, v = 0; i < cpu->cpreg_array_len

             && v < cpu->cpreg_vmstate_array_len; i++) {

        if (cpu->cpreg_vmstate_indexes[v] > cpu->cpreg_indexes[i]) {

            /* register in our list but not incoming : skip it */

            continue;

        }

        if (cpu->cpreg_vmstate_indexes[v] < cpu->cpreg_indexes[i]) {

            /* register in their list but not ours: fail migration */

            return -1;

        }

        /* matching register, copy the value over */

        cpu->cpreg_values[i] = cpu->cpreg_vmstate_values[v];

        v++;

    }

    if (kvm_enabled()) {

        if (!write_list_to_kvmstate(cpu)) {

            return -1;

        }

        /* Note that it's OK for the TCG side not to know about

         * every register in the list; KVM is authoritative if

         * we're using it.

         */

        write_list_to_cpustate(cpu);

    } else {

        if (!write_list_to_cpustate(cpu)) {

            return -1;

        }

    }

    hw_breakpoint_update_all(cpu);

    hw_watchpoint_update_all(cpu);

    return 0;

}


static void vhost_virtqueue_stop(struct vhost_dev *dev,

                                    struct VirtIODevice *vdev,

                                    struct vhost_virtqueue *vq,

                                    unsigned idx)

{

    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);

    struct vhost_vring_state state = {

        .index = vhost_vq_index,

    };

    int r;

    r = dev->vhost_ops->vhost_get_vring_base(dev, &state);

    if (r < 0) {

        fprintf(stderr, "vhost VQ %d ring restore failed: %d\n", idx, r);

        fflush(stderr);

    }

    virtio_queue_set_last_avail_idx(vdev, idx, state.num);

    virtio_queue_invalidate_signalled_used(vdev, idx);

    /* In the cross-endian case, we need to reset the vring endianness to

     * native as legacy devices expect so by default.

     */

    if (!virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1) &&

        vhost_needs_vring_endian(vdev)) {

        r = vhost_virtqueue_set_vring_endian_legacy(dev,

                                                    !virtio_is_big_endian(vdev),

                                                    vhost_vq_index);

        if (r < 0) {

            error_report("failed to reset vring endianness");

        }

    }

    assert (r >= 0);

    cpu_physical_memory_unmap(vq->ring, virtio_queue_get_ring_size(vdev, idx),

                              0, virtio_queue_get_ring_size(vdev, idx));

    cpu_physical_memory_unmap(vq->used, virtio_queue_get_used_size(vdev, idx),

                              1, virtio_queue_get_used_size(vdev, idx));

    cpu_physical_memory_unmap(vq->avail, virtio_queue_get_avail_size(vdev, idx),

                              0, virtio_queue_get_avail_size(vdev, idx));

    cpu_physical_memory_unmap(vq->desc, virtio_queue_get_desc_size(vdev, idx),

                              0, virtio_queue_get_desc_size(vdev, idx));

}


static void pci_map(PCIDevice * pci_dev, int region_num,

                    uint32_t addr, uint32_t size, int type)

{

    PCIEEPRO100State *d = DO_UPCAST(PCIEEPRO100State, dev, pci_dev);

    EEPRO100State *s = &d->eepro100;

    logout("region %d, addr=0x%08x, size=0x%08x, type=%d\n",

           region_num, addr, size, type);

    assert(region_num == 1);

    register_ioport_write(addr, size, 1, ioport_write1, s);

    register_ioport_read(addr, size, 1, ioport_read1, s);

    register_ioport_write(addr, size, 2, ioport_write2, s);

    register_ioport_read(addr, size, 2, ioport_read2, s);

    register_ioport_write(addr, size, 4, ioport_write4, s);

    register_ioport_read(addr, size, 4, ioport_read4, s);

    s->region[region_num] = addr;

}


static void host_signal_handler(int host_signum, siginfo_t *info,

                                void *puc)

{

    int sig;

    target_siginfo_t tinfo;

    /* the CPU emulator uses some host signals to detect exceptions,

       we forward to it some signals */

    if ((host_signum == SIGSEGV || host_signum == SIGBUS)

        && info->si_code > 0) {

        if (cpu_signal_handler(host_signum, info, puc))

            return;

    }

    /* get target signal number */

    sig = host_to_target_signal(host_signum);

    if (sig < 1 || sig > TARGET_NSIG)

        return;

#if defined(DEBUG_SIGNAL)

    fprintf(stderr, "qemu: got signal %d\n", sig);

#endif

    host_to_target_siginfo_noswap(&tinfo, info);

    if (queue_signal(thread_env, sig, &tinfo) == 1) {

        /* interrupt the virtual CPU as soon as possible */

        cpu_interrupt(thread_env, CPU_INTERRUPT_EXIT);

    }

}


static char *scsibus_get_fw_dev_path(DeviceState *dev)

{

    SCSIDevice *d = SCSI_DEVICE(dev);

    char path[100];

    snprintf(path, sizeof(path), "channel@%x/%s@%x,%x", d->channel,

             qdev_fw_name(dev), d->id, d->lun);

    return strdup(path);

}


static void lsi_do_command(LSIState *s)

{

    SCSIDevice *dev;

    uint8_t buf[16];

    uint32_t id;

    int n;

    DPRINTF("Send command len=%d\n", s->dbc);

    if (s->dbc > 16)

        s->dbc = 16;

    cpu_physical_memory_read(s->dnad, buf, s->dbc);

    s->sfbr = buf[0];

    s->command_complete = 0;

    id = (s->select_tag >> 8) & 0xf;

    dev = s->bus.devs[id];

    if (!dev) {

        lsi_bad_selection(s, id);

        return;

    }

    assert(s->current == NULL);

    s->current = qemu_mallocz(sizeof(lsi_request));

    s->current->tag = s->select_tag;

    s->current->req = scsi_req_new(dev, s->current->tag, s->current_lun,

                                   s->current);

    n = scsi_req_enqueue(s->current->req, buf);

    if (n) {

        if (n > 0) {

            lsi_set_phase(s, PHASE_DI);

        } else if (n < 0) {

            lsi_set_phase(s, PHASE_DO);

        }

        scsi_req_continue(s->current->req);

    }

    if (!s->command_complete) {

        if (n) {

            /* Command did not complete immediately so disconnect.  */

            lsi_add_msg_byte(s, 2); /* SAVE DATA POINTER */

            lsi_add_msg_byte(s, 4); /* DISCONNECT */

            /* wait data */

            lsi_set_phase(s, PHASE_MI);

            s->msg_action = 1;

            lsi_queue_command(s);

        } else {

            /* wait command complete */

            lsi_set_phase(s, PHASE_DI);

        }

    }

}


void ioinst_handle_chsc(S390CPU *cpu, uint32_t ipb)

{

    ChscReq *req;

    ChscResp *res;

    uint64_t addr;

    int reg;

    uint16_t len;

    uint16_t command;

    CPUS390XState *env = &cpu->env;

    uint8_t buf[TARGET_PAGE_SIZE];

    trace_ioinst("chsc");

    reg = (ipb >> 20) & 0x00f;

    addr = env->regs[reg];

    /* Page boundary? */

    if (addr & 0xfff) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return;

    }

    /*

     * Reading sizeof(ChscReq) bytes is currently enough for all of our

     * present CHSC sub-handlers ... if we ever need more, we should take

     * care of req->len here first.

     */

    if (s390_cpu_virt_mem_read(cpu, addr, reg, buf, sizeof(ChscReq))) {

        return;

    }

    req = (ChscReq *)buf;

    len = be16_to_cpu(req->len);

    /* Length field valid? */

    if ((len < 16) || (len > 4088) || (len & 7)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return;

    }

    memset((char *)req + len, 0, TARGET_PAGE_SIZE - len);

    res = (void *)((char *)req + len);

    command = be16_to_cpu(req->command);

    trace_ioinst_chsc_cmd(command, len);

    switch (command) {

    case CHSC_SCSC:

        ioinst_handle_chsc_scsc(req, res);

        break;

    case CHSC_SCPD:

        ioinst_handle_chsc_scpd(req, res);

        break;

    case CHSC_SDA:

        ioinst_handle_chsc_sda(req, res);

        break;

    case CHSC_SEI:

        ioinst_handle_chsc_sei(req, res);

        break;

    default:

        ioinst_handle_chsc_unimplemented(res);

        break;

    }

    if (!s390_cpu_virt_mem_write(cpu, addr + len, reg, res,

                                 be16_to_cpu(res->len))) {

        setcc(cpu, 0);    /* Command execution complete */

    }

}


static int ff_estimate_motion_b(MpegEncContext * s,

                       int mb_x, int mb_y, int16_t (*mv_table)[2], Picture *picture, int f_code)

{

    int mx, my, range, dmin;

    int xmin, ymin, xmax, ymax;

    int rel_xmin, rel_ymin, rel_xmax, rel_ymax;

    int pred_x=0, pred_y=0;

    int P[10][2];

    const int shift= 1+s->quarter_sample;

    const int mot_stride = s->mb_width + 2;

    const int mot_xy = (mb_y + 1)*mot_stride + mb_x + 1;

    uint8_t * const ref_picture= picture->data[0];

    uint16_t * const mv_penalty= s->me.mv_penalty[f_code] + MAX_MV;

    int mv_scale;

    s->me.penalty_factor    = get_penalty_factor(s, s->avctx->me_cmp);

    s->me.sub_penalty_factor= get_penalty_factor(s, s->avctx->me_sub_cmp);

    s->me.mb_penalty_factor = get_penalty_factor(s, s->avctx->mb_cmp);

    get_limits(s, &range, &xmin, &ymin, &xmax, &ymax, f_code);

    rel_xmin= xmin - mb_x*16;

    rel_xmax= xmax - mb_x*16;

    rel_ymin= ymin - mb_y*16;

    rel_ymax= ymax - mb_y*16;

    switch(s->me_method) {

    case ME_ZERO:

    default:

	no_motion_search(s, &mx, &my);

        dmin = 0;

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_FULL:

	dmin = full_motion_search(s, &mx, &my, range, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_LOG:

	dmin = log_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_PHODS:

	dmin = phods_motion_search(s, &mx, &my, range / 2, xmin, ymin, xmax, ymax, ref_picture);

        mx-= mb_x*16;

        my-= mb_y*16;

        break;

    case ME_X1:

    case ME_EPZS:

       {

            P_LEFT[0]        = mv_table[mot_xy - 1][0];

            P_LEFT[1]        = mv_table[mot_xy - 1][1];

            if(P_LEFT[0]       > (rel_xmax<<shift)) P_LEFT[0]       = (rel_xmax<<shift);

            /* special case for first line */

            if (mb_y) {

                P_TOP[0] = mv_table[mot_xy - mot_stride             ][0];

                P_TOP[1] = mv_table[mot_xy - mot_stride             ][1];

                P_TOPRIGHT[0] = mv_table[mot_xy - mot_stride + 1         ][0];

                P_TOPRIGHT[1] = mv_table[mot_xy - mot_stride + 1         ][1];

                if(P_TOP[1] > (rel_ymax<<shift)) P_TOP[1]= (rel_ymax<<shift);

                if(P_TOPRIGHT[0] < (rel_xmin<<shift)) P_TOPRIGHT[0]= (rel_xmin<<shift);

                if(P_TOPRIGHT[1] > (rel_ymax<<shift)) P_TOPRIGHT[1]= (rel_ymax<<shift);

                P_MEDIAN[0]= mid_pred(P_LEFT[0], P_TOP[0], P_TOPRIGHT[0]);

                P_MEDIAN[1]= mid_pred(P_LEFT[1], P_TOP[1], P_TOPRIGHT[1]);

            }

            pred_x= P_LEFT[0];

            pred_y= P_LEFT[1];

        }

        if(mv_table == s->b_forw_mv_table){

            mv_scale= (s->pb_time<<16) / (s->pp_time<<shift);

        }else{

            mv_scale= ((s->pb_time - s->pp_time)<<16) / (s->pp_time<<shift);

        }

        dmin = s->me.motion_search[0](s, 0, &mx, &my, P, pred_x, pred_y, rel_xmin, rel_ymin, rel_xmax, rel_ymax,

                                      picture, s->p_mv_table, mv_scale, mv_penalty);

        break;

    }

    dmin= s->me.sub_motion_search(s, &mx, &my, dmin, rel_xmin, rel_ymin, rel_xmax, rel_ymax,

				   pred_x, pred_y, picture, 0, 0, mv_penalty);

    if(s->avctx->me_sub_cmp != s->avctx->mb_cmp && !s->me.skip)

        dmin= s->me.get_mb_score(s, mx, my, pred_x, pred_y, picture, mv_penalty);

//printf("%d %d %d %d//", s->mb_x, s->mb_y, mx, my);

//    s->mb_type[mb_y*s->mb_width + mb_x]= mb_type;

    mv_table[mot_xy][0]= mx;

    mv_table[mot_xy][1]= my;

    return dmin;

}


int inet_connect_opts(QemuOpts *opts, Error **errp,

                      NonBlockingConnectHandler *callback, void *opaque)

{

    struct addrinfo *res, *e;

    int sock = -1;

    bool in_progress;

    ConnectState *connect_state = NULL;

    res = inet_parse_connect_opts(opts, errp);

    if (!res) {

        return -1;

    }

    if (callback != NULL) {

        connect_state = g_malloc0(sizeof(*connect_state));

        connect_state->addr_list = res;

        connect_state->callback = callback;

        connect_state->opaque = opaque;

    }

    for (e = res; e != NULL; e = e->ai_next) {

        if (error_is_set(errp)) {

            error_free(*errp);

            *errp = NULL;

        }

        if (connect_state != NULL) {

            connect_state->current_addr = e;

        }

        sock = inet_connect_addr(e, &in_progress, connect_state, errp);

        if (in_progress) {

            return sock;

        } else if (sock >= 0) {

            /* non blocking socket immediate success, call callback */

            if (callback != NULL) {

                callback(sock, opaque);

            }

            break;

        }

    }

    g_free(connect_state);

    freeaddrinfo(res);

    return sock;

}


static void channel_run(DBDMA_channel *ch)

{

    dbdma_cmd *current = &ch->current;

    uint16_t cmd, key;

    uint16_t req_count;

    uint32_t phy_addr;

    DBDMA_DPRINTF("channel_run\n");

    dump_dbdma_cmd(current);

    /* clear WAKE flag at command fetch */

    ch->regs[DBDMA_STATUS] &= cpu_to_be32(~WAKE);

    cmd = le16_to_cpu(current->command) & COMMAND_MASK;

    switch (cmd) {

    case DBDMA_NOP:

        nop(ch);

	return;

    case DBDMA_STOP:

        stop(ch);

	return;

    }

    key = le16_to_cpu(current->command) & 0x0700;

    req_count = le16_to_cpu(current->req_count);

    phy_addr = le32_to_cpu(current->phy_addr);

    if (key == KEY_STREAM4) {

        printf("command %x, invalid key 4\n", cmd);

        kill_channel(ch);

        return;

    }

    switch (cmd) {

    case OUTPUT_MORE:

        start_output(ch, key, phy_addr, req_count, 0);

	return;

    case OUTPUT_LAST:

        start_output(ch, key, phy_addr, req_count, 1);

	return;

    case INPUT_MORE:

        start_input(ch, key, phy_addr, req_count, 0);

	return;

    case INPUT_LAST:

        start_input(ch, key, phy_addr, req_count, 1);

	return;

    }

    if (key < KEY_REGS) {

        printf("command %x, invalid key %x\n", cmd, key);

        key = KEY_SYSTEM;

    }

    /* for LOAD_WORD and STORE_WORD, req_count is on 3 bits

     * and BRANCH is invalid

     */

    req_count = req_count & 0x0007;

    if (req_count & 0x4) {

        req_count = 4;

        phy_addr &= ~3;

    } else if (req_count & 0x2) {

        req_count = 2;

        phy_addr &= ~1;

    } else

        req_count = 1;

    switch (cmd) {

    case LOAD_WORD:

        load_word(ch, key, phy_addr, req_count);

	return;

    case STORE_WORD:

        store_word(ch, key, phy_addr, req_count);

	return;

    }

}


static void error(const char *fmt, ...)

{

    va_list ap;

    va_start(ap, fmt);

    fprintf(stderr, "qemu-img: ");

    vfprintf(stderr, fmt, ap);

    fprintf(stderr, "\n");

    va_end(ap);

}


void aio_set_fd_handler(AioContext *ctx,

                        int fd,

                        IOHandler *io_read,

                        IOHandler *io_write,

                        void *opaque)

{

    /* fd is a SOCKET in our case */

    AioHandler *node;

    QLIST_FOREACH(node, &ctx->aio_handlers, node) {

        if (node->pfd.fd == fd && !node->deleted) {

            break;

        }

    }

    /* Are we deleting the fd handler? */

    if (!io_read && !io_write) {

        if (node) {

            /* If the lock is held, just mark the node as deleted */

            if (ctx->walking_handlers) {

                node->deleted = 1;

                node->pfd.revents = 0;

            } else {

                /* Otherwise, delete it for real.  We can't just mark it as

                 * deleted because deleted nodes are only cleaned up after

                 * releasing the walking_handlers lock.

                 */

                QLIST_REMOVE(node, node);

                g_free(node);

            }

        }

    } else {

        HANDLE event;

        if (node == NULL) {

            /* Alloc and insert if it's not already there */

            node = g_malloc0(sizeof(AioHandler));

            node->pfd.fd = fd;

            QLIST_INSERT_HEAD(&ctx->aio_handlers, node, node);

        }

        node->pfd.events = 0;

        if (node->io_read) {

            node->pfd.events |= G_IO_IN;

        }

        if (node->io_write) {

            node->pfd.events |= G_IO_OUT;

        }

        node->e = &ctx->notifier;

        /* Update handler with latest information */

        node->opaque = opaque;

        node->io_read = io_read;

        node->io_write = io_write;

        event = event_notifier_get_handle(&ctx->notifier);

        WSAEventSelect(node->pfd.fd, event,

                       FD_READ | FD_ACCEPT | FD_CLOSE |

                       FD_CONNECT | FD_WRITE | FD_OOB);

    }

    aio_notify(ctx);

}


static int proxy_truncate(FsContext *ctx, V9fsPath *fs_path, off_t size)

{

    int retval;

    retval = v9fs_request(ctx->private, T_TRUNCATE, NULL, "sq", fs_path, size);

    if (retval < 0) {

        errno = -retval;

        return -1;

    }

    return 0;

}


static uint64_t e1000_io_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    E1000State *s = opaque;

    (void)s;

    return 0;

}


static void pci_vpb_init(Object *obj)

{

    PCIHostState *h = PCI_HOST_BRIDGE(obj);

    PCIVPBState *s = PCI_VPB(obj);

    memory_region_init(&s->pci_io_space, OBJECT(s), "pci_io", 1ULL << 32);

    memory_region_init(&s->pci_mem_space, OBJECT(s), "pci_mem", 1ULL << 32);

    pci_bus_new_inplace(&s->pci_bus, sizeof(s->pci_bus), DEVICE(obj), "pci",

                        &s->pci_mem_space, &s->pci_io_space,

                        PCI_DEVFN(11, 0), TYPE_PCI_BUS);

    h->bus = &s->pci_bus;

    object_initialize(&s->pci_dev, sizeof(s->pci_dev), TYPE_VERSATILE_PCI_HOST);

    qdev_set_parent_bus(DEVICE(&s->pci_dev), BUS(&s->pci_bus));

    /* Window sizes for VersatilePB; realview_pci's init will override */

    s->mem_win_size[0] = 0x0c000000;

    s->mem_win_size[1] = 0x10000000;

    s->mem_win_size[2] = 0x10000000;

}


BlockDriverState *bdrv_new(const char *device_name)

{

    BlockDriverState *bs;

    bs = g_malloc0(sizeof(BlockDriverState));

    QLIST_INIT(&bs->dirty_bitmaps);

    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);

    if (device_name[0] != '\0') {

        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);

    }

    bdrv_iostatus_disable(bs);

    notifier_list_init(&bs->close_notifiers);

    notifier_with_return_list_init(&bs->before_write_notifiers);

    qemu_co_queue_init(&bs->throttled_reqs[0]);

    qemu_co_queue_init(&bs->throttled_reqs[1]);

    bs->refcnt = 1;

    return bs;

}


static inline int get_scale(GetBitContext *gb, int level, int value)

{

    if (level < 5) {

        /* huffman encoded */

        value += get_bitalloc(gb, &dca_scalefactor, level);

    } else if (level < 8)

        value = get_bits(gb, level + 1);

    return value;

}


int s390_cpu_handle_mmu_fault(CPUState *cs, vaddr orig_vaddr,

                              int rw, int mmu_idx)

{

    S390CPU *cpu = S390_CPU(cs);

    CPUS390XState *env = &cpu->env;

    target_ulong vaddr, raddr;

    uint64_t asc;

    int prot;

    DPRINTF("%s: address 0x%" VADDR_PRIx " rw %d mmu_idx %d\n",

            __func__, orig_vaddr, rw, mmu_idx);

    orig_vaddr &= TARGET_PAGE_MASK;

    vaddr = orig_vaddr;

    if (mmu_idx < MMU_REAL_IDX) {

        asc = cpu_mmu_idx_to_asc(mmu_idx);

        /* 31-Bit mode */

        if (!(env->psw.mask & PSW_MASK_64)) {

            vaddr &= 0x7fffffff;

        }

        if (mmu_translate(env, vaddr, rw, asc, &raddr, &prot, true)) {

            return 1;

        }

    } else if (mmu_idx == MMU_REAL_IDX) {

        if (mmu_translate_real(env, vaddr, rw, &raddr, &prot)) {

            return 1;

        }

    } else {

        abort();

    }

    /* check out of RAM access */

    if (!address_space_access_valid(&address_space_memory, raddr,

                                    TARGET_PAGE_SIZE, rw)) {

        DPRINTF("%s: raddr %" PRIx64 " > ram_size %" PRIx64 "\n", __func__,

                (uint64_t)raddr, (uint64_t)ram_size);

        trigger_pgm_exception(env, PGM_ADDRESSING, ILEN_AUTO);

        return 1;

    }

    qemu_log_mask(CPU_LOG_MMU, "%s: set tlb %" PRIx64 " -> %" PRIx64 " (%x)\n",

            __func__, (uint64_t)vaddr, (uint64_t)raddr, prot);

    tlb_set_page(cs, orig_vaddr, raddr, prot,

                 mmu_idx, TARGET_PAGE_SIZE);

    return 0;

}


uint64_t kvmppc_rma_size(uint64_t current_size, unsigned int hash_shift)

{

    if (cap_ppc_rma >= 2) {

        return current_size;

    }

    return MIN(current_size,

               getrampagesize() << (hash_shift - 7));

}


setup_sigcontext(struct target_sigcontext *sc, /*struct _fpstate *fpstate,*/

		 CPUState *env, unsigned long mask)

{

	int err = 0;

	__put_user_error(env->regs[0], &sc->arm_r0, err);

	__put_user_error(env->regs[1], &sc->arm_r1, err);

	__put_user_error(env->regs[2], &sc->arm_r2, err);

	__put_user_error(env->regs[3], &sc->arm_r3, err);

	__put_user_error(env->regs[4], &sc->arm_r4, err);

	__put_user_error(env->regs[5], &sc->arm_r5, err);

	__put_user_error(env->regs[6], &sc->arm_r6, err);

	__put_user_error(env->regs[7], &sc->arm_r7, err);

	__put_user_error(env->regs[8], &sc->arm_r8, err);

	__put_user_error(env->regs[9], &sc->arm_r9, err);

	__put_user_error(env->regs[10], &sc->arm_r10, err);

	__put_user_error(env->regs[11], &sc->arm_fp, err);

	__put_user_error(env->regs[12], &sc->arm_ip, err);

	__put_user_error(env->regs[13], &sc->arm_sp, err);

	__put_user_error(env->regs[14], &sc->arm_lr, err);

	__put_user_error(env->regs[15], &sc->arm_pc, err);

#ifdef TARGET_CONFIG_CPU_32

	__put_user_error(cpsr_read(env), &sc->arm_cpsr, err);

#endif

	__put_user_error(/* current->thread.trap_no */ 0, &sc->trap_no, err);

	__put_user_error(/* current->thread.error_code */ 0, &sc->error_code, err);

	__put_user_error(/* current->thread.address */ 0, &sc->fault_address, err);

	__put_user_error(mask, &sc->oldmask, err);

	return err;

}


void hd_geometry_guess(BlockDriverState *bs,

                       int *pcyls, int *pheads, int *psecs)

{

    int cylinders, heads, secs, translation;

    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);

    translation = bdrv_get_translation_hint(bs);

    if (cylinders != 0) {

        /* already got a geometry hint: use it */

        *pcyls = cylinders;

        *pheads = heads;

        *psecs = secs;

        return;

    }

    if (guess_disk_lchs(bs, &cylinders, &heads, &secs) < 0) {

        /* no LCHS guess: use a standard physical disk geometry  */

        guess_chs_for_size(bs, pcyls, pheads, psecs);

    } else if (heads > 16) {

        /* LCHS guess with heads > 16 means that a BIOS LBA

           translation was active, so a standard physical disk

           geometry is OK */

        guess_chs_for_size(bs, pcyls, pheads, psecs);

        if (translation == BIOS_ATA_TRANSLATION_AUTO) {

            bdrv_set_translation_hint(bs,

                                      *pcyls * *pheads <= 131072

                                      ? BIOS_ATA_TRANSLATION_LARGE

                                      : BIOS_ATA_TRANSLATION_LBA);

        }

    } else {

        /* LCHS guess with heads <= 16: use as physical geometry */

        *pcyls = cylinders;

        *pheads = heads;

        *psecs = secs;

        /* disable any translation to be in sync with

           the logical geometry */

        if (translation == BIOS_ATA_TRANSLATION_AUTO) {

            bdrv_set_translation_hint(bs,

                                      BIOS_ATA_TRANSLATION_NONE);

        }

    }

    bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);

    trace_hd_geometry_guess(bs, *pcyls, *pheads, *psecs, translation);

}


static void test_visitor_in_intList(TestInputVisitorData *data,

                                    const void *unused)

{

    int64_t value[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20};

    int16List *res = NULL, *tmp;

    Error *err = NULL;

    Visitor *v;

    int i = 0;

    v = visitor_input_test_init(data, "1,2,0,2-4,20,5-9,1-8");

    visit_type_int16List(v, NULL, &res, &error_abort);

    tmp = res;

    while (i < sizeof(value) / sizeof(value[0])) {

        g_assert(tmp);

        g_assert_cmpint(tmp->value, ==, value[i++]);

        tmp = tmp->next;

    }

    g_assert(!tmp);

    qapi_free_int16List(res);

    visitor_input_teardown(data, unused);

    v = visitor_input_test_init(data, "not an int list");

    /* FIXME: res should be NULL on failure, regardless of starting value */

    res = NULL;

    visit_type_int16List(v, NULL, &res, &err);

    error_free_or_abort(&err);

    g_assert(!res);

}


int init_timer_alarm(void)

{

    struct qemu_alarm_timer *t = NULL;

    int i, err = -1;

    for (i = 0; alarm_timers[i].name; i++) {

        t = &alarm_timers[i];

        err = t->start(t);

        if (!err)

            break;

    }

    if (err) {

        err = -ENOENT;

        goto fail;

    }

    /* first event is at time 0 */

    atexit(quit_timers);

    t->pending = true;

    alarm_timer = t;

    return 0;

fail:

    return err;

}


static void i386_tr_translate_insn(DisasContextBase *dcbase, CPUState *cpu)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    target_ulong pc_next = disas_insn(dc, cpu);

    if (dc->tf || (dc->base.tb->flags & HF_INHIBIT_IRQ_MASK)) {

        /* if single step mode, we generate only one instruction and

           generate an exception */

        /* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear

           the flag and abort the translation to give the irqs a

           chance to happen */

        dc->base.is_jmp = DISAS_TOO_MANY;

    } else if ((dc->base.tb->cflags & CF_USE_ICOUNT)

               && ((dc->base.pc_next & TARGET_PAGE_MASK)

                   != ((dc->base.pc_next + TARGET_MAX_INSN_SIZE - 1)

                       & TARGET_PAGE_MASK)

                   || (dc->base.pc_next & ~TARGET_PAGE_MASK) == 0)) {

        /* Do not cross the boundary of the pages in icount mode,

           it can cause an exception. Do it only when boundary is

           crossed by the first instruction in the block.

           If current instruction already crossed the bound - it's ok,

           because an exception hasn't stopped this code.

         */

        dc->base.is_jmp = DISAS_TOO_MANY;

    } else if ((pc_next - dc->base.pc_first) >= (TARGET_PAGE_SIZE - 32)) {

        dc->base.is_jmp = DISAS_TOO_MANY;

    }

    dc->base.pc_next = pc_next;

}


static av_cold int alac_decode_init(AVCodecContext * avctx)

{

    int ret;

    int req_packed;

    ALACContext *alac = avctx->priv_data;

    alac->avctx = avctx;

    /* initialize from the extradata */

    if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "expected %d extradata bytes\n",

            ALAC_EXTRADATA_SIZE);

        return -1;

    }

    if (alac_set_info(alac)) {

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

        return -1;

    }

    req_packed = LIBAVCODEC_VERSION_MAJOR < 55 && !av_sample_fmt_is_planar(avctx->request_sample_fmt);

    switch (alac->sample_size) {

    case 16: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S16 : AV_SAMPLE_FMT_S16P;

             break;

    case 24:

    case 32: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S32 : AV_SAMPLE_FMT_S32P;

             break;

    default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",

                                   alac->sample_size);

             return AVERROR_PATCHWELCOME;

    }

    avctx->bits_per_raw_sample = alac->sample_size;

    if (alac->channels < 1) {

        av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");

        alac->channels = avctx->channels;

    } else {

        if (alac->channels > MAX_CHANNELS)

            alac->channels = avctx->channels;

        else

            avctx->channels = alac->channels;

    }

    if (avctx->channels > MAX_CHANNELS) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",

               avctx->channels);

        return AVERROR_PATCHWELCOME;

    }

    avctx->channel_layout = alac_channel_layouts[alac->channels - 1];

    if ((ret = allocate_buffers(alac)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");

        return ret;

    }

    avcodec_get_frame_defaults(&alac->frame);

    avctx->coded_frame = &alac->frame;

    return 0;

}


static void qtrle_decode_8bpp(QtrleContext *s)

{

    int stream_ptr;

    int header;

    int start_line;

    int lines_to_change;

    signed char rle_code;

    int row_ptr, pixel_ptr;

    int row_inc = s->frame.linesize[0];

    unsigned char pi1, pi2, pi3, pi4;  /* 4 palette indices */

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    /* check if this frame is even supposed to change */

    if (s->size < 8)

        return;

    /* start after the chunk size */

    stream_ptr = 4;

    /* fetch the header */

    CHECK_STREAM_PTR(2);

    header = BE_16(&s->buf[stream_ptr]);

    stream_ptr += 2;

    /* if a header is present, fetch additional decoding parameters */

    if (header & 0x0008) {

        CHECK_STREAM_PTR(8);

        start_line = BE_16(&s->buf[stream_ptr]);

        stream_ptr += 4;

        lines_to_change = BE_16(&s->buf[stream_ptr]);

        stream_ptr += 4;

    } else {

        start_line = 0;

        lines_to_change = s->avctx->height;

    }

    row_ptr = row_inc * start_line;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (4 * (s->buf[stream_ptr++] - 1));

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (4 * (s->buf[stream_ptr++] - 1));

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                /* get the next 4 bytes from the stream, treat them as palette

                 * indices, and output them rle_code times */

                CHECK_STREAM_PTR(4);

                pi1 = s->buf[stream_ptr++];

                pi2 = s->buf[stream_ptr++];

                pi3 = s->buf[stream_ptr++];

                pi4 = s->buf[stream_ptr++];

                CHECK_PIXEL_PTR(rle_code * 4);

                while (rle_code--) {

                    rgb[pixel_ptr++] = pi1;

                    rgb[pixel_ptr++] = pi2;

                    rgb[pixel_ptr++] = pi3;

                    rgb[pixel_ptr++] = pi4;

                }

            } else {

                /* copy the same pixel directly to output 4 times */

                rle_code *= 4;

                CHECK_STREAM_PTR(rle_code);

                CHECK_PIXEL_PTR(rle_code);

                while (rle_code--) {

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                }

            }

        }

        row_ptr += row_inc;

    }

}


static int mxf_read_source_package(MXFPackage *package, ByteIOContext *pb, int tag)

{

    switch(tag) {

    case 0x4403:

        package->tracks_count = get_be32(pb);

        if (package->tracks_count >= UINT_MAX / sizeof(UID))

            return -1;

        package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));

        if (!package->tracks_refs)

            return -1;

        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */

        get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));

        break;

    case 0x4401:

        /* UMID, only get last 16 bytes */

        url_fskip(pb, 16);

        get_buffer(pb, package->package_uid, 16);

        break;

    case 0x4701:

        get_buffer(pb, package->descriptor_ref, 16);

        break;

    }

    return 0;

}


static int decode_packet(AVCodecContext *avctx, void *data,
                         int *got_frame_ptr, AVPacket* avpkt)
{
    WMAProDecodeCtx *s = avctx->priv_data;
    GetBitContext* gb  = &s->pgb;
    const uint8_t* buf = avpkt->data;
    int buf_size       = avpkt->size;
    int num_bits_prev_frame;
    int packet_sequence_number;
    *got_frame_ptr = 0;
    if (s->skip_packets > 0) {
        s->skip_packets--;
        return FFMIN(avpkt->size, avctx->block_align);
    if (s->packet_done || s->packet_loss) {
        s->packet_done = 0;
        /** sanity check for the buffer length */
        if (avctx->codec_id == AV_CODEC_ID_WMAPRO && buf_size < avctx->block_align) {
            av_log(avctx, AV_LOG_ERROR, "Input packet too small (%d < %d)\n",
                   buf_size, avctx->block_align);
            return AVERROR_INVALIDDATA;
        if (avctx->codec_id == AV_CODEC_ID_WMAPRO) {
            s->next_packet_start = buf_size - avctx->block_align;
            buf_size = avctx->block_align;
        } else {
            s->next_packet_start = buf_size - FFMIN(buf_size, avctx->block_align);
            buf_size = FFMIN(buf_size, avctx->block_align);
        s->buf_bit_size = buf_size << 3;
        /** parse packet header */
        init_get_bits(gb, buf, s->buf_bit_size);
        if (avctx->codec_id != AV_CODEC_ID_XMA2) {
            packet_sequence_number = get_bits(gb, 4);
            skip_bits(gb, 2);
        } else {
            s->num_frames = get_bits(gb, 6);
            packet_sequence_number = 0;
        /** get number of bits that need to be added to the previous frame */
        num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
        if (avctx->codec_id != AV_CODEC_ID_WMAPRO) {
            skip_bits(gb, 3);
            s->skip_packets = get_bits(gb, 8);
        ff_dlog(avctx, "packet[%d]: nbpf %x\n", avctx->frame_number,
                num_bits_prev_frame);
        /** check for packet loss */
        if (avctx->codec_id != AV_CODEC_ID_XMA2 && !s->packet_loss &&
            ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
            av_log(avctx, AV_LOG_ERROR,
                   "Packet loss detected! seq %"PRIx8" vs %x\n",
                   s->packet_sequence_number, packet_sequence_number);
        s->packet_sequence_number = packet_sequence_number;
        if (num_bits_prev_frame > 0) {
            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
            if (num_bits_prev_frame >= remaining_packet_bits) {
                num_bits_prev_frame = remaining_packet_bits;
                s->packet_done = 1;
            /** append the previous frame data to the remaining data from the
                previous packet to create a full frame */
            save_bits(s, gb, num_bits_prev_frame, 1);
            ff_dlog(avctx, "accumulated %x bits of frame data\n",
                    s->num_saved_bits - s->frame_offset);
            /** decode the cross packet frame if it is valid */
            if (!s->packet_loss)
                decode_frame(s, data, got_frame_ptr);
        } else if (s->num_saved_bits - s->frame_offset) {
            ff_dlog(avctx, "ignoring %x previously saved bits\n",
                    s->num_saved_bits - s->frame_offset);
        if (s->packet_loss) {
            /** reset number of saved bits so that the decoder
                does not start to decode incomplete frames in the
                s->len_prefix == 0 case */
            s->num_saved_bits = 0;
            s->packet_loss = 0;
    } else {
        int frame_size;
        s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
        init_get_bits(gb, avpkt->data, s->buf_bit_size);
        skip_bits(gb, s->packet_offset);
        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
            (frame_size = show_bits(gb, s->log2_frame_size)) &&
            frame_size <= remaining_bits(s, gb)) {
            save_bits(s, gb, frame_size, 0);
            if (!s->packet_loss)
                s->packet_done = !decode_frame(s, data, got_frame_ptr);
        } else if (!s->len_prefix
                   && s->num_saved_bits > get_bits_count(&s->gb)) {
            /** when the frames do not have a length prefix, we don't know
                the compressed length of the individual frames
                however, we know what part of a new packet belongs to the
                previous frame
                therefore we save the incoming packet first, then we append
                the "previous frame" data from the next packet so that
                we get a buffer that only contains full frames */
            s->packet_done = !decode_frame(s, data, got_frame_ptr);
        } else
            s->packet_done = 1;
    if (s->packet_done && !s->packet_loss &&
        remaining_bits(s, gb) > 0) {
        /** save the rest of the data so that it can be decoded
            with the next packet */
        save_bits(s, gb, remaining_bits(s, gb), 0);
    s->packet_offset = get_bits_count(gb) & 7;
    if (s->packet_loss)
        return AVERROR_INVALIDDATA;
    return get_bits_count(gb) >> 3;


int ff_pca(PCA *pca, double *eigenvector, double *eigenvalue){

    int i, j, k, pass;

    const int n= pca->n;

    double z[n];

    memset(eigenvector, 0, sizeof(double)*n*n);

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

        pca->mean[j] /= pca->count;

        eigenvector[j + j*n] = 1.0;

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

            pca->covariance[j + i*n] /= pca->count;

            pca->covariance[j + i*n] -= pca->mean[i] * pca->mean[j];

            pca->covariance[i + j*n] = pca->covariance[j + i*n];

        }

        eigenvalue[j]= pca->covariance[j + j*n];

        z[j]= 0;

    }

    for(pass=0; pass < 50; pass++){

        double sum=0;

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

            for(j=i+1; j<n; j++)

                sum += fabs(pca->covariance[j + i*n]);

        if(sum == 0){

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

                double maxvalue= -1;

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

                    if(eigenvalue[j] > maxvalue){

                        maxvalue= eigenvalue[j];

                        k= j;

                    }

                }

                eigenvalue[k]= eigenvalue[i];

                eigenvalue[i]= maxvalue;

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

                    double tmp= eigenvector[k + j*n];

                    eigenvector[k + j*n]= eigenvector[i + j*n];

                    eigenvector[i + j*n]= tmp;

                }

            }

            return pass;

        }

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

            for(j=i+1; j<n; j++){

                double covar= pca->covariance[j + i*n];

                double t,c,s,tau,theta, h;

                if(pass < 3 && fabs(covar) < sum / (5*n*n)) //FIXME why pass < 3

                    continue;

                if(fabs(covar) == 0.0) //FIXME shouldnt be needed

                    continue;

                if(pass >=3 && fabs((eigenvalue[j]+z[j])/covar) > (1LL<<32) && fabs((eigenvalue[i]+z[i])/covar) > (1LL<<32)){

                    pca->covariance[j + i*n]=0.0;

                    continue;

                }

                h= (eigenvalue[j]+z[j]) - (eigenvalue[i]+z[i]);

                theta=0.5*h/covar;

                t=1.0/(fabs(theta)+sqrt(1.0+theta*theta));

                if(theta < 0.0) t = -t;

                c=1.0/sqrt(1+t*t);

                s=t*c;

                tau=s/(1.0+c);

                z[i] -= t*covar;

                z[j] += t*covar;

#define ROTATE(a,i,j,k,l) {\

    double g=a[j + i*n];\

    double h=a[l + k*n];\

    a[j + i*n]=g-s*(h+g*tau);\

    a[l + k*n]=h+s*(g-h*tau); }

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

                    if(k!=i && k!=j){

                        ROTATE(pca->covariance,FFMIN(k,i),FFMAX(k,i),FFMIN(k,j),FFMAX(k,j))

                    }

                    ROTATE(eigenvector,k,i,k,j)

                }

                pca->covariance[j + i*n]=0.0;

            }

        }

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

            eigenvalue[i] += z[i];

            z[i]=0.0;

        }

    }

    return -1;

}


qcrypto_tls_creds_check_cert_key_purpose(QCryptoTLSCredsX509 *creds,

                                         gnutls_x509_crt_t cert,

                                         const char *certFile,

                                         bool isServer,

                                         Error **errp)

{

    int status;

    size_t i;

    unsigned int purposeCritical;

    unsigned int critical;

    char *buffer = NULL;

    size_t size;

    bool allowClient = false, allowServer = false;

    critical = 0;

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

        size = 0;

        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer,

                                                     &size, NULL);

        if (status == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {

            /* If there is no data at all, then we must allow

               client/server to pass */

            if (i == 0) {

                allowServer = allowClient = true;

            }

            break;

        }

        if (status != GNUTLS_E_SHORT_MEMORY_BUFFER) {

            error_setg(errp,

                       "Unable to query certificate %s key purpose: %s",

                       certFile, gnutls_strerror(status));

            return -1;

        }

        buffer = g_new0(char, size);

        status = gnutls_x509_crt_get_key_purpose_oid(cert, i, buffer,

                                                     &size, &purposeCritical);

        if (status < 0) {

            trace_qcrypto_tls_creds_x509_check_key_purpose(

                creds, certFile, status, "<none>", purposeCritical);

            g_free(buffer);

            error_setg(errp,

                       "Unable to query certificate %s key purpose: %s",

                       certFile, gnutls_strerror(status));

            return -1;

        }

        trace_qcrypto_tls_creds_x509_check_key_purpose(

            creds, certFile, status, buffer, purposeCritical);

        if (purposeCritical) {

            critical = true;

        }

        if (g_str_equal(buffer, GNUTLS_KP_TLS_WWW_SERVER)) {

            allowServer = true;

        } else if (g_str_equal(buffer, GNUTLS_KP_TLS_WWW_CLIENT)) {

            allowClient = true;

        } else if (g_str_equal(buffer, GNUTLS_KP_ANY)) {

            allowServer = allowClient = true;

        }

        g_free(buffer);

    }

    if (isServer) {

        if (!allowServer) {

            if (critical) {

                error_setg(errp,

                           "Certificate %s purpose does not allow "

                           "use with a TLS server", certFile);

                return -1;

            }

        }

    } else {

        if (!allowClient) {

            if (critical) {

                error_setg(errp,

                           "Certificate %s purpose does not allow use "

                           "with a TLS client", certFile);

                return -1;

            }

        }

    }

    return 0;

}


void HELPER(window_check)(CPUXtensaState *env, uint32_t pc, uint32_t w)

{

    uint32_t windowbase = windowbase_bound(env->sregs[WINDOW_BASE], env);

    uint32_t windowstart = env->sregs[WINDOW_START];

    uint32_t m, n;

    if ((env->sregs[PS] & (PS_WOE | PS_EXCM)) ^ PS_WOE) {

        return;

    }

    for (n = 1; ; ++n) {

        if (n > w) {

            return;

        }

        if (windowstart & windowstart_bit(windowbase + n, env)) {

            break;

        }

    }

    m = windowbase_bound(windowbase + n, env);

    rotate_window(env, n);

    env->sregs[PS] = (env->sregs[PS] & ~PS_OWB) |

        (windowbase << PS_OWB_SHIFT) | PS_EXCM;

    env->sregs[EPC1] = env->pc = pc;

    if (windowstart & windowstart_bit(m + 1, env)) {

        HELPER(exception)(env, EXC_WINDOW_OVERFLOW4);

    } else if (windowstart & windowstart_bit(m + 2, env)) {

        HELPER(exception)(env, EXC_WINDOW_OVERFLOW8);

    } else {

        HELPER(exception)(env, EXC_WINDOW_OVERFLOW12);

    }

}


QDict *qobject_to_qdict(const QObject *obj)

{

    if (qobject_type(obj) != QTYPE_QDICT)

        return NULL;

    return container_of(obj, QDict, base);

}


PXA2xxLCDState *pxa2xx_lcdc_init(MemoryRegion *sysmem,

                                 target_phys_addr_t base, qemu_irq irq)

{

    PXA2xxLCDState *s;

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

    s->invalidated = 1;

    s->irq = irq;

    s->sysmem = sysmem;

    pxa2xx_lcdc_orientation(s, graphic_rotate);

    memory_region_init_io(&s->iomem, &pxa2xx_lcdc_ops, s,

                          "pxa2xx-lcd-controller", 0x00100000);

    memory_region_add_subregion(sysmem, base, &s->iomem);

    s->ds = graphic_console_init(pxa2xx_update_display,

                                 pxa2xx_invalidate_display,

                                 pxa2xx_screen_dump, NULL, s);

    switch (ds_get_bits_per_pixel(s->ds)) {

    case 0:

        s->dest_width = 0;

        break;

    case 8:

        s->line_fn[0] = pxa2xx_draw_fn_8;

        s->line_fn[1] = pxa2xx_draw_fn_8t;

        s->dest_width = 1;

        break;

    case 15:

        s->line_fn[0] = pxa2xx_draw_fn_15;

        s->line_fn[1] = pxa2xx_draw_fn_15t;

        s->dest_width = 2;

        break;

    case 16:

        s->line_fn[0] = pxa2xx_draw_fn_16;

        s->line_fn[1] = pxa2xx_draw_fn_16t;

        s->dest_width = 2;

        break;

    case 24:

        s->line_fn[0] = pxa2xx_draw_fn_24;

        s->line_fn[1] = pxa2xx_draw_fn_24t;

        s->dest_width = 3;

        break;

    case 32:

        s->line_fn[0] = pxa2xx_draw_fn_32;

        s->line_fn[1] = pxa2xx_draw_fn_32t;

        s->dest_width = 4;

        break;

    default:

        fprintf(stderr, "%s: Bad color depth\n", __FUNCTION__);

        exit(1);

    }

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

    return s;

}


static int decode_mips16_opc (CPUMIPSState *env, DisasContext *ctx,

                              int *is_branch)

{

    int rx, ry;

    int sa;

    int op, cnvt_op, op1, offset;

    int funct;

    int n_bytes;

    op = (ctx->opcode >> 11) & 0x1f;

    sa = (ctx->opcode >> 2) & 0x7;

    sa = sa == 0 ? 8 : sa;

    rx = xlat((ctx->opcode >> 8) & 0x7);

    cnvt_op = (ctx->opcode >> 5) & 0x7;

    ry = xlat((ctx->opcode >> 5) & 0x7);

    op1 = offset = ctx->opcode & 0x1f;

    n_bytes = 2;

    switch (op) {

    case M16_OPC_ADDIUSP:

        {

            int16_t imm = ((uint8_t) ctx->opcode) << 2;

            gen_arith_imm(ctx, OPC_ADDIU, rx, 29, imm);

        }

        break;

    case M16_OPC_ADDIUPC:

        gen_addiupc(ctx, rx, ((uint8_t) ctx->opcode) << 2, 0, 0);

        break;

    case M16_OPC_B:

        offset = (ctx->opcode & 0x7ff) << 1;

        offset = (int16_t)(offset << 4) >> 4;

        gen_compute_branch(ctx, OPC_BEQ, 2, 0, 0, offset);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_JAL:

        offset = cpu_lduw_code(env, ctx->pc + 2);

        offset = (((ctx->opcode & 0x1f) << 21)

                  | ((ctx->opcode >> 5) & 0x1f) << 16

                  | offset) << 2;

        op = ((ctx->opcode >> 10) & 0x1) ? OPC_JALXS : OPC_JALS;

        gen_compute_branch(ctx, op, 4, rx, ry, offset);

        n_bytes = 4;

        *is_branch = 1;

        break;

    case M16_OPC_BEQZ:

        gen_compute_branch(ctx, OPC_BEQ, 2, rx, 0, ((int8_t)ctx->opcode) << 1);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_BNEQZ:

        gen_compute_branch(ctx, OPC_BNE, 2, rx, 0, ((int8_t)ctx->opcode) << 1);

        /* No delay slot, so just process as a normal instruction */

        break;

    case M16_OPC_SHIFT:

        switch (ctx->opcode & 0x3) {

        case 0x0:

            gen_shift_imm(ctx, OPC_SLL, rx, ry, sa);

            break;

        case 0x1:

#if defined(TARGET_MIPS64)

            check_mips_64(ctx);

            gen_shift_imm(ctx, OPC_DSLL, rx, ry, sa);

#else

            generate_exception(ctx, EXCP_RI);

#endif

            break;

        case 0x2:

            gen_shift_imm(ctx, OPC_SRL, rx, ry, sa);

            break;

        case 0x3:

            gen_shift_imm(ctx, OPC_SRA, rx, ry, sa);

            break;

        }

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_LD:

        check_mips_64(ctx);

        gen_ld(ctx, OPC_LD, ry, rx, offset << 3);

        break;

#endif

    case M16_OPC_RRIA:

        {

            int16_t imm = (int8_t)((ctx->opcode & 0xf) << 4) >> 4;

            if ((ctx->opcode >> 4) & 1) {

#if defined(TARGET_MIPS64)

                check_mips_64(ctx);

                gen_arith_imm(ctx, OPC_DADDIU, ry, rx, imm);

#else

                generate_exception(ctx, EXCP_RI);

#endif

            } else {

                gen_arith_imm(ctx, OPC_ADDIU, ry, rx, imm);

            }

        }

        break;

    case M16_OPC_ADDIU8:

        {

            int16_t imm = (int8_t) ctx->opcode;

            gen_arith_imm(ctx, OPC_ADDIU, rx, rx, imm);

        }

        break;

    case M16_OPC_SLTI:

        {

            int16_t imm = (uint8_t) ctx->opcode;

            gen_slt_imm(ctx, OPC_SLTI, 24, rx, imm);

        }

        break;

    case M16_OPC_SLTIU:

        {

            int16_t imm = (uint8_t) ctx->opcode;

            gen_slt_imm(ctx, OPC_SLTIU, 24, rx, imm);

        }

        break;

    case M16_OPC_I8:

        {

            int reg32;

            funct = (ctx->opcode >> 8) & 0x7;

            switch (funct) {

            case I8_BTEQZ:

                gen_compute_branch(ctx, OPC_BEQ, 2, 24, 0,

                                   ((int8_t)ctx->opcode) << 1);

                break;

            case I8_BTNEZ:

                gen_compute_branch(ctx, OPC_BNE, 2, 24, 0,

                                   ((int8_t)ctx->opcode) << 1);

                break;

            case I8_SWRASP:

                gen_st(ctx, OPC_SW, 31, 29, (ctx->opcode & 0xff) << 2);

                break;

            case I8_ADJSP:

                gen_arith_imm(ctx, OPC_ADDIU, 29, 29,

                              ((int8_t)ctx->opcode) << 3);

                break;

            case I8_SVRS:

                {

                    int do_ra = ctx->opcode & (1 << 6);

                    int do_s0 = ctx->opcode & (1 << 5);

                    int do_s1 = ctx->opcode & (1 << 4);

                    int framesize = ctx->opcode & 0xf;

                    if (framesize == 0) {

                        framesize = 128;

                    } else {

                        framesize = framesize << 3;

                    }

                    if (ctx->opcode & (1 << 7)) {

                        gen_mips16_save(ctx, 0, 0,

                                        do_ra, do_s0, do_s1, framesize);

                    } else {

                        gen_mips16_restore(ctx, 0, 0,

                                           do_ra, do_s0, do_s1, framesize);

                    }

                }

                break;

            case I8_MOV32R:

                {

                    int rz = xlat(ctx->opcode & 0x7);

                    reg32 = (((ctx->opcode >> 3) & 0x3) << 3) |

                        ((ctx->opcode >> 5) & 0x7);

                    gen_arith(ctx, OPC_ADDU, reg32, rz, 0);

                }

                break;

            case I8_MOVR32:

                reg32 = ctx->opcode & 0x1f;

                gen_arith(ctx, OPC_ADDU, ry, reg32, 0);

                break;

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

        }

        break;

    case M16_OPC_LI:

        {

            int16_t imm = (uint8_t) ctx->opcode;

            gen_arith_imm(ctx, OPC_ADDIU, rx, 0, imm);

        }

        break;

    case M16_OPC_CMPI:

        {

            int16_t imm = (uint8_t) ctx->opcode;

            gen_logic_imm(ctx, OPC_XORI, 24, rx, imm);

        }

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_SD:

        check_mips_64(ctx);

        gen_st(ctx, OPC_SD, ry, rx, offset << 3);

        break;

#endif

    case M16_OPC_LB:

        gen_ld(ctx, OPC_LB, ry, rx, offset);

        break;

    case M16_OPC_LH:

        gen_ld(ctx, OPC_LH, ry, rx, offset << 1);

        break;

    case M16_OPC_LWSP:

        gen_ld(ctx, OPC_LW, rx, 29, ((uint8_t)ctx->opcode) << 2);

        break;

    case M16_OPC_LW:

        gen_ld(ctx, OPC_LW, ry, rx, offset << 2);

        break;

    case M16_OPC_LBU:

        gen_ld(ctx, OPC_LBU, ry, rx, offset);

        break;

    case M16_OPC_LHU:

        gen_ld(ctx, OPC_LHU, ry, rx, offset << 1);

        break;

    case M16_OPC_LWPC:

        gen_ld(ctx, OPC_LWPC, rx, 0, ((uint8_t)ctx->opcode) << 2);

        break;

#if defined (TARGET_MIPS64)

    case M16_OPC_LWU:

        check_mips_64(ctx);

        gen_ld(ctx, OPC_LWU, ry, rx, offset << 2);

        break;

#endif

    case M16_OPC_SB:

        gen_st(ctx, OPC_SB, ry, rx, offset);

        break;

    case M16_OPC_SH:

        gen_st(ctx, OPC_SH, ry, rx, offset << 1);

        break;

    case M16_OPC_SWSP:

        gen_st(ctx, OPC_SW, rx, 29, ((uint8_t)ctx->opcode) << 2);

        break;

    case M16_OPC_SW:

        gen_st(ctx, OPC_SW, ry, rx, offset << 2);

        break;

    case M16_OPC_RRR:

        {

            int rz = xlat((ctx->opcode >> 2) & 0x7);

            int mips32_op;

            switch (ctx->opcode & 0x3) {

            case RRR_ADDU:

                mips32_op = OPC_ADDU;

                break;

            case RRR_SUBU:

                mips32_op = OPC_SUBU;

                break;

#if defined(TARGET_MIPS64)

            case RRR_DADDU:

                mips32_op = OPC_DADDU;

                check_mips_64(ctx);

                break;

            case RRR_DSUBU:

                mips32_op = OPC_DSUBU;

                check_mips_64(ctx);

                break;

#endif

            default:

                generate_exception(ctx, EXCP_RI);

                goto done;

            }

            gen_arith(ctx, mips32_op, rz, rx, ry);

        done:

            ;

        }

        break;

    case M16_OPC_RR:

        switch (op1) {

        case RR_JR:

            {

                int nd = (ctx->opcode >> 7) & 0x1;

                int link = (ctx->opcode >> 6) & 0x1;

                int ra = (ctx->opcode >> 5) & 0x1;

                if (link) {

                    op = nd ? OPC_JALRC : OPC_JALRS;

                } else {

                    op = OPC_JR;

                }

                gen_compute_branch(ctx, op, 2, ra ? 31 : rx, 31, 0);

                if (!nd) {

                    *is_branch = 1;

                }

            }

            break;

        case RR_SDBBP:

            /* XXX: not clear which exception should be raised

             *      when in debug mode...

             */

            check_insn(ctx, ISA_MIPS32);

            if (!(ctx->hflags & MIPS_HFLAG_DM)) {

                generate_exception(ctx, EXCP_DBp);

            } else {

                generate_exception(ctx, EXCP_DBp);

            }

            break;

        case RR_SLT:

            gen_slt(ctx, OPC_SLT, 24, rx, ry);

            break;

        case RR_SLTU:

            gen_slt(ctx, OPC_SLTU, 24, rx, ry);

            break;

        case RR_BREAK:

            generate_exception(ctx, EXCP_BREAK);

            break;

        case RR_SLLV:

            gen_shift(ctx, OPC_SLLV, ry, rx, ry);

            break;

        case RR_SRLV:

            gen_shift(ctx, OPC_SRLV, ry, rx, ry);

            break;

        case RR_SRAV:

            gen_shift(ctx, OPC_SRAV, ry, rx, ry);

            break;

#if defined (TARGET_MIPS64)

        case RR_DSRL:

            check_mips_64(ctx);

            gen_shift_imm(ctx, OPC_DSRL, ry, ry, sa);

            break;

#endif

        case RR_CMP:

            gen_logic(ctx, OPC_XOR, 24, rx, ry);

            break;

        case RR_NEG:

            gen_arith(ctx, OPC_SUBU, rx, 0, ry);

            break;

        case RR_AND:

            gen_logic(ctx, OPC_AND, rx, rx, ry);

            break;

        case RR_OR:

            gen_logic(ctx, OPC_OR, rx, rx, ry);

            break;

        case RR_XOR:

            gen_logic(ctx, OPC_XOR, rx, rx, ry);

            break;

        case RR_NOT:

            gen_logic(ctx, OPC_NOR, rx, ry, 0);

            break;

        case RR_MFHI:

            gen_HILO(ctx, OPC_MFHI, 0, rx);

            break;

        case RR_CNVT:

            switch (cnvt_op) {

            case RR_RY_CNVT_ZEB:

                tcg_gen_ext8u_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

            case RR_RY_CNVT_ZEH:

                tcg_gen_ext16u_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

            case RR_RY_CNVT_SEB:

                tcg_gen_ext8s_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

            case RR_RY_CNVT_SEH:

                tcg_gen_ext16s_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

#if defined (TARGET_MIPS64)

            case RR_RY_CNVT_ZEW:

                check_mips_64(ctx);

                tcg_gen_ext32u_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

            case RR_RY_CNVT_SEW:

                check_mips_64(ctx);

                tcg_gen_ext32s_tl(cpu_gpr[rx], cpu_gpr[rx]);

                break;

#endif

            default:

                generate_exception(ctx, EXCP_RI);

                break;

            }

            break;

        case RR_MFLO:

            gen_HILO(ctx, OPC_MFLO, 0, rx);

            break;

#if defined (TARGET_MIPS64)

        case RR_DSRA:

            check_mips_64(ctx);

            gen_shift_imm(ctx, OPC_DSRA, ry, ry, sa);

            break;

        case RR_DSLLV:

            check_mips_64(ctx);

            gen_shift(ctx, OPC_DSLLV, ry, rx, ry);

            break;

        case RR_DSRLV:

            check_mips_64(ctx);

            gen_shift(ctx, OPC_DSRLV, ry, rx, ry);

            break;

        case RR_DSRAV:

            check_mips_64(ctx);

            gen_shift(ctx, OPC_DSRAV, ry, rx, ry);

            break;

#endif

        case RR_MULT:

            gen_muldiv(ctx, OPC_MULT, 0, rx, ry);

            break;

        case RR_MULTU:

            gen_muldiv(ctx, OPC_MULTU, 0, rx, ry);

            break;

        case RR_DIV:

            gen_muldiv(ctx, OPC_DIV, 0, rx, ry);

            break;

        case RR_DIVU:

            gen_muldiv(ctx, OPC_DIVU, 0, rx, ry);

            break;

#if defined (TARGET_MIPS64)

        case RR_DMULT:

            check_mips_64(ctx);

            gen_muldiv(ctx, OPC_DMULT, 0, rx, ry);

            break;

        case RR_DMULTU:

            check_mips_64(ctx);

            gen_muldiv(ctx, OPC_DMULTU, 0, rx, ry);

            break;

        case RR_DDIV:

            check_mips_64(ctx);

            gen_muldiv(ctx, OPC_DDIV, 0, rx, ry);

            break;

        case RR_DDIVU:

            check_mips_64(ctx);

            gen_muldiv(ctx, OPC_DDIVU, 0, rx, ry);

            break;

#endif

        default:

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

    case M16_OPC_EXTEND:

        decode_extended_mips16_opc(env, ctx, is_branch);

        n_bytes = 4;

        break;

#if defined(TARGET_MIPS64)

    case M16_OPC_I64:

        funct = (ctx->opcode >> 8) & 0x7;

        decode_i64_mips16(ctx, ry, funct, offset, 0);

        break;

#endif

    default:

        generate_exception(ctx, EXCP_RI);

        break;

    }

    return n_bytes;

}


static int arm_gic_common_init(SysBusDevice *dev)

{

    GICState *s = FROM_SYSBUS(GICState, dev);

    int num_irq = s->num_irq;

    if (s->num_cpu > NCPU) {

        hw_error("requested %u CPUs exceeds GIC maximum %d\n",

                 s->num_cpu, NCPU);

    }

    s->num_irq += GIC_BASE_IRQ;

    if (s->num_irq > GIC_MAXIRQ) {

        hw_error("requested %u interrupt lines exceeds GIC maximum %d\n",

                 num_irq, GIC_MAXIRQ);

    }

    /* ITLinesNumber is represented as (N / 32) - 1 (see

     * gic_dist_readb) so this is an implementation imposed

     * restriction, not an architectural one:

     */

    if (s->num_irq < 32 || (s->num_irq % 32)) {

        hw_error("%d interrupt lines unsupported: not divisible by 32\n",

                 num_irq);

    }

    register_savevm(NULL, "arm_gic", -1, 3, gic_save, gic_load, s);

    return 0;

}


static kbd_layout_t *parse_keyboard_layout(const name2keysym_t *table,

					   const char *language,

					   kbd_layout_t * k)

{

    FILE *f;

    char * filename;

    char line[1024];

    int len;

    filename = qemu_find_file(QEMU_FILE_TYPE_KEYMAP, language);

    if (!k)

	k = g_malloc0(sizeof(kbd_layout_t));

    if (!(filename && (f = fopen(filename, "r")))) {

	fprintf(stderr,

		"Could not read keymap file: '%s'\n", language);

	return NULL;

    }

    g_free(filename);

    for(;;) {

	if (fgets(line, 1024, f) == NULL)

            break;

        len = strlen(line);

        if (len > 0 && line[len - 1] == '\n')

            line[len - 1] = '\0';

        if (line[0] == '#')

	    continue;

	if (!strncmp(line, "map ", 4))

	    continue;

	if (!strncmp(line, "include ", 8)) {

	    parse_keyboard_layout(table, line + 8, k);

        } else {

	    char *end_of_keysym = line;

	    while (*end_of_keysym != 0 && *end_of_keysym != ' ')

		end_of_keysym++;

	    if (*end_of_keysym) {

		int keysym;

		*end_of_keysym = 0;

		keysym = get_keysym(table, line);

		if (keysym == 0) {

                    //		    fprintf(stderr, "Warning: unknown keysym %s\n", line);

		} else {

		    const char *rest = end_of_keysym + 1;

		    char *rest2;

		    int keycode = strtol(rest, &rest2, 0);

		    if (rest && strstr(rest, "numlock")) {

			add_to_key_range(&k->keypad_range, keycode);

			add_to_key_range(&k->numlock_range, keysym);

			//fprintf(stderr, "keypad keysym %04x keycode %d\n", keysym, keycode);

		    }

		    if (rest && strstr(rest, "shift"))

			keycode |= SCANCODE_SHIFT;

		    if (rest && strstr(rest, "altgr"))

			keycode |= SCANCODE_ALTGR;

		    if (rest && strstr(rest, "ctrl"))

			keycode |= SCANCODE_CTRL;

		    add_keysym(line, keysym, keycode, k);

		    if (rest && strstr(rest, "addupper")) {

			char *c;

			for (c = line; *c; c++)

			    *c = qemu_toupper(*c);

			keysym = get_keysym(table, line);

			if (keysym)

			    add_keysym(line, keysym, keycode | SCANCODE_SHIFT, k);

		    }

		}

	    }

	}

    }

    fclose(f);

    return k;

}


static void *virtio_scsi_load_request(QEMUFile *f, SCSIRequest *sreq)

{

    SCSIBus *bus = sreq->bus;

    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    VirtIOSCSIReq *req;

    uint32_t n;

    req = g_malloc(sizeof(*req));

    qemu_get_be32s(f, &n);

    assert(n < vs->conf.num_queues);

    qemu_get_buffer(f, (unsigned char *)&req->elem, sizeof(req->elem));

    virtio_scsi_parse_req(s, vs->cmd_vqs[n], req);

    scsi_req_ref(sreq);

    req->sreq = sreq;

    if (req->sreq->cmd.mode != SCSI_XFER_NONE) {

        int req_mode =

            (req->elem.in_num > 1 ? SCSI_XFER_FROM_DEV : SCSI_XFER_TO_DEV);

        assert(req->sreq->cmd.mode == req_mode);

    }

    return req;

}


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

                             int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MpegEncContext *s  = avctx->priv_data;

    uint8_t *current, *previous;

    int result, i, x, y, width, height;

    AVFrame *pict = data;

    svq1_pmv *pmv;

    /* initialize bit buffer */

    init_get_bits(&s->gb, buf, buf_size * 8);

    /* decode frame header */

    s->f_code = get_bits(&s->gb, 22);

    if ((s->f_code & ~0x70) || !(s->f_code & 0x60))

        return AVERROR_INVALIDDATA;

    /* swap some header bytes (why?) */

    if (s->f_code != 0x20) {

        uint32_t *src = (uint32_t *)(buf + 4);

        if (buf_size < 36)

            return AVERROR_INVALIDDATA;

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

            src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];

    }

    result = svq1_decode_frame_header(&s->gb, s);

    if (result) {

        av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n", result);

        return result;

    }

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

    /* FIXME: This avoids some confusion for "B frames" without 2 references.

     * This should be removed after libavcodec can handle more flexible

     * picture types & ordering */

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

        return buf_size;

    if ((avctx->skip_frame >= AVDISCARD_NONREF &&

         s->pict_type == AV_PICTURE_TYPE_B)    ||

        (avctx->skip_frame >= AVDISCARD_NONKEY &&

         s->pict_type != AV_PICTURE_TYPE_I)    ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return buf_size;

    if ((result = ff_MPV_frame_start(s, avctx)) < 0)

        return result;

    pmv = av_malloc((FFALIGN(s->width, 16) / 8 + 3) * sizeof(*pmv));

    if (!pmv)

        return AVERROR(ENOMEM);

    /* decode y, u and v components */

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

        int linesize;

        if (i == 0) {

            width    = FFALIGN(s->width,  16);

            height   = FFALIGN(s->height, 16);

            linesize = s->linesize;

        } else {

            if (s->flags & CODEC_FLAG_GRAY)

                break;

            width    = FFALIGN(s->width  / 4, 16);

            height   = FFALIGN(s->height / 4, 16);

            linesize = s->uvlinesize;

        }

        current = s->current_picture.f.data[i];

        if (s->pict_type == AV_PICTURE_TYPE_B)

            previous = s->next_picture.f.data[i];

        else

            previous = s->last_picture.f.data[i];

        if (s->pict_type == AV_PICTURE_TYPE_I) {

            /* keyframe */

            for (y = 0; y < height; y += 16) {

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

                    result = svq1_decode_block_intra(&s->gb, &current[x],

                                                     linesize);

                    if (result) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Error in svq1_decode_block %i (keyframe)\n",

                               result);

                        goto err;

                    }

                }

                current += 16 * linesize;

            }

        } else {

            /* delta frame */

            memset(pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));

            for (y = 0; y < height; y += 16) {

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

                    result = svq1_decode_delta_block(s, &s->gb, &current[x],

                                                     previous, linesize,

                                                     pmv, x, y);

                    if (result) {

                        av_dlog(s->avctx,

                                "Error in svq1_decode_delta_block %i\n",

                                result);

                        goto err;

                    }

                }

                pmv[0].x     =

                    pmv[0].y = 0;

                current += 16 * linesize;

            }

        }

    }

    *pict = s->current_picture.f;

    ff_MPV_frame_end(s);

    *data_size = sizeof(AVFrame);

    result     = buf_size;

err:

    av_free(pmv);

    return result;

}


bool migrate_rdma_pin_all(void)

{

    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL];

}


static void openpic_reset (void *opaque)

{

    openpic_t *opp = (openpic_t *)opaque;

    int i;

    opp->glbc = 0x80000000;

    /* Initialise controller registers */

    opp->frep = ((OPENPIC_EXT_IRQ - 1) << 16) | ((MAX_CPU - 1) << 8) | VID;

    opp->veni = VENI;

    opp->pint = 0x00000000;

    opp->spve = 0x000000FF;

    opp->tifr = 0x003F7A00;

    /* ? */

    opp->micr = 0x00000000;

    /* Initialise IRQ sources */

    for (i = 0; i < opp->max_irq; i++) {

	opp->src[i].ipvp = 0xA0000000;

	opp->src[i].ide  = 0x00000000;

    }

    /* Initialise IRQ destinations */

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

	opp->dst[i].pctp      = 0x0000000F;

	opp->dst[i].pcsr      = 0x00000000;

	memset(&opp->dst[i].raised, 0, sizeof(IRQ_queue_t));

	memset(&opp->dst[i].servicing, 0, sizeof(IRQ_queue_t));

    }

    /* Initialise timers */

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

	opp->timers[i].ticc = 0x00000000;

	opp->timers[i].tibc = 0x80000000;

    }

    /* Initialise doorbells */

#if MAX_DBL > 0

    opp->dar = 0x00000000;

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

	opp->doorbells[i].dmr  = 0x00000000;

    }

#endif

    /* Initialise mailboxes */

#if MAX_MBX > 0

    for (i = 0; i < MAX_MBX; i++) { /* ? */

	opp->mailboxes[i].mbr   = 0x00000000;

    }

#endif

    /* Go out of RESET state */

    opp->glbc = 0x00000000;

}


static av_cold void movie_uninit(AVFilterContext *ctx)

{

    MovieContext *movie = ctx->priv;

    int i;

    for (i = 0; i < ctx->nb_outputs; i++) {

        av_freep(&ctx->output_pads[i].name);

        if (movie->st[i].st)

            avcodec_close(movie->st[i].st->codec);

    }

    av_freep(&movie->st);

    av_freep(&movie->out_index);

    av_frame_free(&movie->frame);

    if (movie->format_ctx)

        avformat_close_input(&movie->format_ctx);

}


static XICSState *xics_system_init(MachineState *machine,

                                   int nr_servers, int nr_irqs)

{

    XICSState *icp = NULL;

    if (kvm_enabled()) {

        Error *err = NULL;

        if (machine_kernel_irqchip_allowed(machine)) {

            icp = try_create_xics(TYPE_KVM_XICS, nr_servers, nr_irqs, &err);

        }

        if (machine_kernel_irqchip_required(machine) && !icp) {

            error_report("kernel_irqchip requested but unavailable: %s",

                         error_get_pretty(err));

        }

    }

    if (!icp) {

        icp = try_create_xics(TYPE_XICS, nr_servers, nr_irqs, &error_abort);

    }

    return icp;

}


static void chroma(WaveformContext *s, AVFrame *in, AVFrame *out,

                   int component, int intensity, int offset, int column)

{

    const int plane = s->desc->comp[component].plane;

    const int mirror = s->mirror;

    const int c0_linesize = in->linesize[(plane + 1) % s->ncomp];

    const int c1_linesize = in->linesize[(plane + 2) % s->ncomp];

    const int dst_linesize = out->linesize[plane];

    const int max = 255 - intensity;

    const int src_h = in->height;

    const int src_w = in->width;

    int x, y;

    if (column) {

        const int dst_signed_linesize = dst_linesize * (mirror == 1 ? -1 : 1);

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

            const uint8_t *c0_data = in->data[(plane + 1) % s->ncomp];

            const uint8_t *c1_data = in->data[(plane + 2) % s->ncomp];

            uint8_t *dst_data = out->data[plane] + offset * dst_linesize;

            uint8_t * const dst_bottom_line = dst_data + dst_linesize * (s->size - 1);

            uint8_t * const dst_line = (mirror ? dst_bottom_line : dst_data);

            uint8_t *dst = dst_line;

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

                const int sum = FFABS(c0_data[x] - 128) + FFABS(c1_data[x] - 128);

                uint8_t *target;

                int p;

                for (p = 256 - sum; p < 256 + sum; p++) {

                    target = dst + x + dst_signed_linesize * p;

                    update(target, max, 1);

                }

                c0_data += c0_linesize;

                c1_data += c1_linesize;

                dst_data += dst_linesize;

            }

        }

    } else {

        const uint8_t *c0_data = in->data[(plane + 1) % s->ncomp];

        const uint8_t *c1_data = in->data[(plane + 2) % s->ncomp];

        uint8_t *dst_data = out->data[plane] + offset;

        if (mirror)

            dst_data += s->size - 1;

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

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

                const int sum = FFABS(c0_data[x] - 128) + FFABS(c1_data[x] - 128);

                uint8_t *target;

                int p;

                for (p = 256 - sum; p < 256 + sum; p++) {

                    if (mirror)

                        target = dst_data - p;

                    else

                        target = dst_data + p;

                    update(target, max, 1);

                }

            }

            c0_data += c0_linesize;

            c1_data += c1_linesize;

            dst_data += dst_linesize;

        }

    }

    envelope(s, out, plane, (plane + 0) % s->ncomp);

}


target_ulong helper_lwr(CPUMIPSState *env, target_ulong arg1,

                        target_ulong arg2, int mem_idx)

{

    target_ulong tmp;

    tmp = do_lbu(env, arg2, mem_idx);

    arg1 = (arg1 & 0xFFFFFF00) | tmp;

    if (GET_LMASK(arg2) >= 1) {

        tmp = do_lbu(env, GET_OFFSET(arg2, -1), mem_idx);

        arg1 = (arg1 & 0xFFFF00FF) | (tmp << 8);

    }

    if (GET_LMASK(arg2) >= 2) {

        tmp = do_lbu(env, GET_OFFSET(arg2, -2), mem_idx);

        arg1 = (arg1 & 0xFF00FFFF) | (tmp << 16);

    }

    if (GET_LMASK(arg2) == 3) {

        tmp = do_lbu(env, GET_OFFSET(arg2, -3), mem_idx);

        arg1 = (arg1 & 0x00FFFFFF) | (tmp << 24);

    }

    return (int32_t)arg1;

}


read_help(void)

{

	printf(

"\n"

" reads a range of bytes from the given offset\n"

"\n"

" Example:\n"

" 'read -v 512 1k' - dumps 1 kilobyte read from 512 bytes into the file\n"

"\n"

" Reads a segment of the currently open file, optionally dumping it to the\n"

" standard output stream (with -v option) for subsequent inspection.\n"

" -p, -- use bdrv_pread to read the file\n"

" -P, -- use a pattern to verify read data\n"

" -C, -- report statistics in a machine parsable format\n"

" -v, -- dump buffer to standard output\n"

" -q, -- quite mode, do not show I/O statistics\n"

"\n");

}


QEMUSizedBuffer *qsb_clone(const QEMUSizedBuffer *qsb)

{

    QEMUSizedBuffer *out = qsb_create(NULL, qsb_get_length(qsb));

    size_t i;

    ssize_t res;

    off_t pos = 0;

    if (!out) {

        return NULL;

    }

    for (i = 0; i < qsb->n_iov; i++) {

        res =  qsb_write_at(out, qsb->iov[i].iov_base,

                            pos, qsb->iov[i].iov_len);

        if (res < 0) {

            qsb_free(out);

            return NULL;

        }

        pos += res;

    }

    return out;

}


int put_wav_header(ByteIOContext *pb, AVCodecContext *enc)

{

    int bps, blkalign, bytespersec;

    int hdrsize = 18;

    if(!enc->codec_tag || enc->codec_tag > 0xffff)

       enc->codec_tag = codec_get_tag(codec_wav_tags, enc->codec_id);

    if(!enc->codec_tag)

        return -1;

    put_le16(pb, enc->codec_tag);

    put_le16(pb, enc->channels);

    put_le32(pb, enc->sample_rate);

    if (enc->codec_id == CODEC_ID_PCM_U8 ||

        enc->codec_id == CODEC_ID_PCM_ALAW ||

        enc->codec_id == CODEC_ID_PCM_MULAW) {

        bps = 8;

    } else if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3) {

        bps = 0;

    } else if (enc->codec_id == CODEC_ID_ADPCM_IMA_WAV || enc->codec_id == CODEC_ID_ADPCM_MS || enc->codec_id == CODEC_ID_ADPCM_G726 || enc->codec_id == CODEC_ID_ADPCM_YAMAHA) { //

        bps = 4;

    } else if (enc->codec_id == CODEC_ID_PCM_S24LE) {

        bps = 24;

    } else if (enc->codec_id == CODEC_ID_PCM_S32LE) {

        bps = 32;

    } else {

        bps = 16;

    }

    if (enc->codec_id == CODEC_ID_MP2 || enc->codec_id == CODEC_ID_MP3) {

        blkalign = enc->frame_size; //this is wrong, but seems many demuxers dont work if this is set correctly

        //blkalign = 144 * enc->bit_rate/enc->sample_rate;

    } else if (enc->codec_id == CODEC_ID_ADPCM_G726) { //

        blkalign = 1;

    } else if (enc->block_align != 0) { /* specified by the codec */

        blkalign = enc->block_align;

    } else

        blkalign = enc->channels*bps >> 3;

    if (enc->codec_id == CODEC_ID_PCM_U8 ||

        enc->codec_id == CODEC_ID_PCM_S24LE ||

        enc->codec_id == CODEC_ID_PCM_S32LE ||

        enc->codec_id == CODEC_ID_PCM_S16LE) {

        bytespersec = enc->sample_rate * blkalign;

    } else {

        bytespersec = enc->bit_rate / 8;

    }

    put_le32(pb, bytespersec); /* bytes per second */

    put_le16(pb, blkalign); /* block align */

    put_le16(pb, bps); /* bits per sample */

    if (enc->codec_id == CODEC_ID_MP3) {

        put_le16(pb, 12); /* wav_extra_size */

        hdrsize += 12;

        put_le16(pb, 1); /* wID */

        put_le32(pb, 2); /* fdwFlags */

        put_le16(pb, 1152); /* nBlockSize */

        put_le16(pb, 1); /* nFramesPerBlock */

        put_le16(pb, 1393); /* nCodecDelay */

    } else if (enc->codec_id == CODEC_ID_MP2) {

        put_le16(pb, 22); /* wav_extra_size */

        hdrsize += 22;

        put_le16(pb, 2);  /* fwHeadLayer */

        put_le32(pb, enc->bit_rate); /* dwHeadBitrate */

        put_le16(pb, enc->channels == 2 ? 1 : 8); /* fwHeadMode */

        put_le16(pb, 0);  /* fwHeadModeExt */

        put_le16(pb, 1);  /* wHeadEmphasis */

        put_le16(pb, 16); /* fwHeadFlags */

        put_le32(pb, 0);  /* dwPTSLow */

        put_le32(pb, 0);  /* dwPTSHigh */

    } else if (enc->codec_id == CODEC_ID_ADPCM_IMA_WAV) {

        put_le16(pb, 2); /* wav_extra_size */

        hdrsize += 2;

        put_le16(pb, ((enc->block_align - 4 * enc->channels) / (4 * enc->channels)) * 8 + 1); /* wSamplesPerBlock */

    } else if(enc->extradata_size){

        put_le16(pb, enc->extradata_size);

        put_buffer(pb, enc->extradata, enc->extradata_size);

        hdrsize += enc->extradata_size;

        if(hdrsize&1){

            hdrsize++;

            put_byte(pb, 0);

        }

    } else {

        hdrsize -= 2;

    }

    return hdrsize;

}


static inline int get_egolomb(GetBitContext *gb)

{

    int v = 4;

    while (get_bits1(gb)) v++;

    return (1 << v) + get_bits(gb, v);

}