static void coroutine_fn backup_run(void *opaque)

{

    BackupBlockJob *job = opaque;

    BackupCompleteData *data;

    BlockDriverState *bs = job->common.bs;

    BlockDriverState *target = job->target;

    BlockdevOnError on_target_error = job->on_target_error;

    NotifierWithReturn before_write = {

        .notify = backup_before_write_notify,

    };

    int64_t start, end;

    int ret = 0;

    QLIST_INIT(&job->inflight_reqs);

    qemu_co_rwlock_init(&job->flush_rwlock);

    start = 0;

    end = DIV_ROUND_UP(job->common.len / BDRV_SECTOR_SIZE,

                       BACKUP_SECTORS_PER_CLUSTER);

    job->bitmap = hbitmap_alloc(end, 0);

    bdrv_set_enable_write_cache(target, true);

    bdrv_set_on_error(target, on_target_error, on_target_error);

    bdrv_iostatus_enable(target);

    bdrv_add_before_write_notifier(bs, &before_write);

    if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {

        while (!block_job_is_cancelled(&job->common)) {

            /* Yield until the job is cancelled.  We just let our before_write

             * notify callback service CoW requests. */

            job->common.busy = false;

            qemu_coroutine_yield();

            job->common.busy = true;

        }

    } else {

        /* Both FULL and TOP SYNC_MODE's require copying.. */

        for (; start < end; start++) {

            bool error_is_read;

            if (block_job_is_cancelled(&job->common)) {

                break;

            }

            /* we need to yield so that qemu_aio_flush() returns.

             * (without, VM does not reboot)

             */

            if (job->common.speed) {

                uint64_t delay_ns = ratelimit_calculate_delay(

                        &job->limit, job->sectors_read);

                job->sectors_read = 0;

                block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, delay_ns);

            } else {

                block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, 0);

            }

            if (block_job_is_cancelled(&job->common)) {

                break;

            }

            if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {

                int i, n;

                int alloced = 0;

                /* Check to see if these blocks are already in the

                 * backing file. */

                for (i = 0; i < BACKUP_SECTORS_PER_CLUSTER;) {

                    /* bdrv_is_allocated() only returns true/false based

                     * on the first set of sectors it comes across that

                     * are are all in the same state.

                     * For that reason we must verify each sector in the

                     * backup cluster length.  We end up copying more than

                     * needed but at some point that is always the case. */

                    alloced =

                        bdrv_is_allocated(bs,

                                start * BACKUP_SECTORS_PER_CLUSTER + i,

                                BACKUP_SECTORS_PER_CLUSTER - i, &n);

                    i += n;

                    if (alloced == 1 || n == 0) {

                        break;

                    }

                }

                /* If the above loop never found any sectors that are in

                 * the topmost image, skip this backup. */

                if (alloced == 0) {

                    continue;

                }

            }

            /* FULL sync mode we copy the whole drive. */

            ret = backup_do_cow(bs, start * BACKUP_SECTORS_PER_CLUSTER,

                    BACKUP_SECTORS_PER_CLUSTER, &error_is_read);

            if (ret < 0) {

                /* Depending on error action, fail now or retry cluster */

                BlockErrorAction action =

                    backup_error_action(job, error_is_read, -ret);

                if (action == BLOCK_ERROR_ACTION_REPORT) {

                    break;

                } else {

                    start--;

                    continue;

                }

            }

        }

    }

    notifier_with_return_remove(&before_write);

    /* wait until pending backup_do_cow() calls have completed */

    qemu_co_rwlock_wrlock(&job->flush_rwlock);

    qemu_co_rwlock_unlock(&job->flush_rwlock);

    hbitmap_free(job->bitmap);

    bdrv_iostatus_disable(target);

    data = g_malloc(sizeof(*data));

    data->ret = ret;

    block_job_defer_to_main_loop(&job->common, backup_complete, data);

}


static void force_sigsegv(int oldsig)

{

    CPUState *cpu = thread_cpu;

    CPUArchState *env = cpu->env_ptr;

    target_siginfo_t info;

    if (oldsig == SIGSEGV) {

        /* Make sure we don't try to deliver the signal again; this will

         * end up with handle_pending_signal() calling force_sig().

         */

        sigact_table[oldsig - 1]._sa_handler = TARGET_SIG_DFL;

    }

    info.si_signo = TARGET_SIGSEGV;

    info.si_errno = 0;

    info.si_code = TARGET_SI_KERNEL;

    info._sifields._kill._pid = 0;

    info._sifields._kill._uid = 0;

    queue_signal(env, info.si_signo, QEMU_SI_KILL, &info);

}


static void vnc_update_client(void *opaque)

{

    VncState *vs = opaque;

    if (vs->need_update && vs->csock != -1) {

        int y;

        uint8_t *row;

        char *old_row;

        uint32_t width_mask[VNC_DIRTY_WORDS];

        int n_rectangles;

        int saved_offset;

        int has_dirty = 0;

        vga_hw_update();

        vnc_set_bits(width_mask, (ds_get_width(vs->ds) / 16), VNC_DIRTY_WORDS);

        /* Walk through the dirty map and eliminate tiles that

           really aren't dirty */

        row = ds_get_data(vs->ds);

        old_row = vs->old_data;

        for (y = 0; y < ds_get_height(vs->ds); y++) {

            if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {

                int x;

                uint8_t *ptr;

                char *old_ptr;

                ptr = row;

                old_ptr = (char*)old_row;

                for (x = 0; x < ds_get_width(vs->ds); x += 16) {

                    if (memcmp(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds)) == 0) {

                        vnc_clear_bit(vs->dirty_row[y], (x / 16));

                    } else {

                        has_dirty = 1;

                        memcpy(old_ptr, ptr, 16 * ds_get_bytes_per_pixel(vs->ds));

                    }

                    ptr += 16 * ds_get_bytes_per_pixel(vs->ds);

                    old_ptr += 16 * ds_get_bytes_per_pixel(vs->ds);

                }

            }

            row += ds_get_linesize(vs->ds);

            old_row += ds_get_linesize(vs->ds);

        }

        if (!has_dirty && !vs->audio_cap) {

            qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);

            return;

        }

        /* Count rectangles */

        n_rectangles = 0;

        vnc_write_u8(vs, 0);  /* msg id */

        vnc_write_u8(vs, 0);

        saved_offset = vs->output.offset;

        vnc_write_u16(vs, 0);

        for (y = 0; y < vs->serverds.height; y++) {

            int x;

            int last_x = -1;

            for (x = 0; x < vs->serverds.width / 16; x++) {

                if (vnc_get_bit(vs->dirty_row[y], x)) {

                    if (last_x == -1) {

                        last_x = x;

                    }

                    vnc_clear_bit(vs->dirty_row[y], x);

                } else {

                    if (last_x != -1) {

                        int h = find_dirty_height(vs, y, last_x, x);

                        send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);

                        n_rectangles++;

                    }

                    last_x = -1;

                }

            }

            if (last_x != -1) {

                int h = find_dirty_height(vs, y, last_x, x);

                send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);

                n_rectangles++;

            }

        }

        vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;

        vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;

        vnc_flush(vs);

    }

    if (vs->csock != -1) {

        qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);

    }

}


static int video_open(VideoState *is)

{

    int w,h;

    if (screen_width) {

        w = screen_width;

        h = screen_height;

    } else {

        w = default_width;

        h = default_height;

    }

    if (!window) {

        int flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;

        if (!window_title)

            window_title = input_filename;

        if (is_full_screen)

            flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;

        window = SDL_CreateWindow(window_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags);

        SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");

        if (window) {

            SDL_RendererInfo info;

            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

            if (!renderer) {

                av_log(NULL, AV_LOG_WARNING, "Failed to initialize a hardware accelerated renderer: %s\n", SDL_GetError());

                renderer = SDL_CreateRenderer(window, -1, 0);

            }

            if (renderer) {

                if (!SDL_GetRendererInfo(renderer, &info))

                    av_log(NULL, AV_LOG_VERBOSE, "Initialized %s renderer.\n", info.name);

            }

        }

    } else {

        SDL_SetWindowSize(window, w, h);

    }

    if (!window || !renderer) {

        av_log(NULL, AV_LOG_FATAL, "SDL: could not set video mode - exiting\n");

        do_exit(is);

    }

    is->width  = w;

    is->height = h;

    return 0;

}


static void FUNCC(pred4x4_129_dc)(uint8_t *_src, const uint8_t *topright, int _stride){

    pixel *src = (pixel*)_src;

    int stride = _stride/sizeof(pixel);

    ((pixel4*)(src+0*stride))[0]=

    ((pixel4*)(src+1*stride))[0]=

    ((pixel4*)(src+2*stride))[0]=

    ((pixel4*)(src+3*stride))[0]= PIXEL_SPLAT_X4((1<<(BIT_DEPTH-1))+1);

}


static int ehci_reset_queue(EHCIQueue *q)

{

    int packets;

    trace_usb_ehci_queue_action(q, "reset");

    packets = ehci_cancel_queue(q);

    q->dev = NULL;

    q->qtdaddr = 0;

    return packets;

}


static void fill_caches(H264Context *h, int mb_type, int for_deblock){

    MpegEncContext * const s = &h->s;

    const int mb_xy= h->mb_xy;

    int topleft_xy, top_xy, topright_xy, left_xy[2];

    int topleft_type, top_type, topright_type, left_type[2];

    int * left_block;

    int topleft_partition= -1;

    int i;

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

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

    if(for_deblock && (h->slice_num == 1 || h->slice_table[mb_xy] == h->slice_table[top_xy]) && !FRAME_MBAFF)

        return;

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

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

    topleft_xy = top_xy - 1;

    topright_xy= top_xy + 1;

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

    left_block = left_block_options[0];

    if(FRAME_MBAFF){

        const int pair_xy          = s->mb_x     + (s->mb_y & ~1)*s->mb_stride;

        const int top_pair_xy      = pair_xy     - s->mb_stride;

        const int topleft_pair_xy  = top_pair_xy - 1;

        const int topright_pair_xy = top_pair_xy + 1;

        const int topleft_mb_frame_flag  = !IS_INTERLACED(s->current_picture.mb_type[topleft_pair_xy]);

        const int top_mb_frame_flag      = !IS_INTERLACED(s->current_picture.mb_type[top_pair_xy]);

        const int topright_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[topright_pair_xy]);

        const int left_mb_frame_flag = !IS_INTERLACED(s->current_picture.mb_type[pair_xy-1]);

        const int curr_mb_frame_flag = !IS_INTERLACED(mb_type);

        const int bottom = (s->mb_y & 1);

        tprintf(s->avctx, "fill_caches: curr_mb_frame_flag:%d, left_mb_frame_flag:%d, topleft_mb_frame_flag:%d, top_mb_frame_flag:%d, topright_mb_frame_flag:%d\n", curr_mb_frame_flag, left_mb_frame_flag, topleft_mb_frame_flag, top_mb_frame_flag, topright_mb_frame_flag);

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !top_mb_frame_flag) // top macroblock

                ) {

            top_xy -= s->mb_stride;

        }

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !topleft_mb_frame_flag) // top macroblock

                ) {

            topleft_xy -= s->mb_stride;

        } else if(bottom && curr_mb_frame_flag && !left_mb_frame_flag) {

            topleft_xy += s->mb_stride;

            // take top left mv from the middle of the mb, as opposed to all other modes which use the bottom right partition

            topleft_partition = 0;

        }

        if (bottom

                ? !curr_mb_frame_flag // bottom macroblock

                : (!curr_mb_frame_flag && !topright_mb_frame_flag) // top macroblock

                ) {

            topright_xy -= s->mb_stride;

        }

        if (left_mb_frame_flag != curr_mb_frame_flag) {

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

            if (curr_mb_frame_flag) {

                if (bottom) {

                    left_block = left_block_options[1];

                } else {

                    left_block= left_block_options[2];

                }

            } else {

                left_xy[1] += s->mb_stride;

                left_block = left_block_options[3];

            }

        }

    }

    h->top_mb_xy = top_xy;

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

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

    if(for_deblock){

        topleft_type = 0;

        topright_type = 0;

        top_type     = h->slice_table[top_xy     ] < 255 ? s->current_picture.mb_type[top_xy]     : 0;

        left_type[0] = h->slice_table[left_xy[0] ] < 255 ? s->current_picture.mb_type[left_xy[0]] : 0;

        left_type[1] = h->slice_table[left_xy[1] ] < 255 ? s->current_picture.mb_type[left_xy[1]] : 0;

        if(FRAME_MBAFF && !IS_INTRA(mb_type)){

            int list;

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

                if(USES_LIST(mb_type,list)){

                    int8_t *ref = &s->current_picture.ref_index[list][h->mb2b8_xy[mb_xy]];

                    *(uint32_t*)&h->ref_cache[list][scan8[ 0]] =

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

                    ref += h->b8_stride;

                    *(uint32_t*)&h->ref_cache[list][scan8[ 8]] =

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

                }else{

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

                    fill_rectangle(&h->ref_cache[list][scan8[ 0]], 4, 4, 8, (uint8_t)LIST_NOT_USED, 1);

                }

            }

        }

    }else{

        topleft_type = h->slice_table[topleft_xy ] == h->slice_num ? s->current_picture.mb_type[topleft_xy] : 0;

        top_type     = h->slice_table[top_xy     ] == h->slice_num ? s->current_picture.mb_type[top_xy]     : 0;

        topright_type= h->slice_table[topright_xy] == h->slice_num ? s->current_picture.mb_type[topright_xy]: 0;

        left_type[0] = h->slice_table[left_xy[0] ] == h->slice_num ? s->current_picture.mb_type[left_xy[0]] : 0;

        left_type[1] = h->slice_table[left_xy[1] ] == h->slice_num ? s->current_picture.mb_type[left_xy[1]] : 0;

    }

    if(IS_INTRA(mb_type)){

        h->topleft_samples_available=

        h->top_samples_available=

        h->left_samples_available= 0xFFFF;

        h->topright_samples_available= 0xEEEA;

        if(!IS_INTRA(top_type) && (top_type==0 || h->pps.constrained_intra_pred)){

            h->topleft_samples_available= 0xB3FF;

            h->top_samples_available= 0x33FF;

            h->topright_samples_available= 0x26EA;

        }

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

            if(!IS_INTRA(left_type[i]) && (left_type[i]==0 || h->pps.constrained_intra_pred)){

                h->topleft_samples_available&= 0xDF5F;

                h->left_samples_available&= 0x5F5F;

            }

        }

        if(!IS_INTRA(topleft_type) && (topleft_type==0 || h->pps.constrained_intra_pred))

            h->topleft_samples_available&= 0x7FFF;

        if(!IS_INTRA(topright_type) && (topright_type==0 || h->pps.constrained_intra_pred))

            h->topright_samples_available&= 0xFBFF;

        if(IS_INTRA4x4(mb_type)){

            if(IS_INTRA4x4(top_type)){

                h->intra4x4_pred_mode_cache[4+8*0]= h->intra4x4_pred_mode[top_xy][4];

                h->intra4x4_pred_mode_cache[5+8*0]= h->intra4x4_pred_mode[top_xy][5];

                h->intra4x4_pred_mode_cache[6+8*0]= h->intra4x4_pred_mode[top_xy][6];

                h->intra4x4_pred_mode_cache[7+8*0]= h->intra4x4_pred_mode[top_xy][3];

            }else{

                int pred;

                if(!top_type || (IS_INTER(top_type) && h->pps.constrained_intra_pred))

                    pred= -1;

                else{

                    pred= 2;

                }

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

                h->intra4x4_pred_mode_cache[5+8*0]=

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

                h->intra4x4_pred_mode_cache[7+8*0]= pred;

            }

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

                if(IS_INTRA4x4(left_type[i])){

                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[0+2*i]];

                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= h->intra4x4_pred_mode[left_xy[i]][left_block[1+2*i]];

                }else{

                    int pred;

                    if(!left_type[i] || (IS_INTER(left_type[i]) && h->pps.constrained_intra_pred))

                        pred= -1;

                    else{

                        pred= 2;

                    }

                    h->intra4x4_pred_mode_cache[3+8*1 + 2*8*i]=

                    h->intra4x4_pred_mode_cache[3+8*2 + 2*8*i]= pred;

                }

            }

        }

    }

/*

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){

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

        h->non_zero_count_cache[5+8*0]= h->non_zero_count[top_xy][5];

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

        h->non_zero_count_cache[7+8*0]= h->non_zero_count[top_xy][3];

        h->non_zero_count_cache[1+8*0]= h->non_zero_count[top_xy][9];

        h->non_zero_count_cache[2+8*0]= h->non_zero_count[top_xy][8];

        h->non_zero_count_cache[1+8*3]= h->non_zero_count[top_xy][12];

        h->non_zero_count_cache[2+8*3]= h->non_zero_count[top_xy][11];

    }else{

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

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

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

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

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

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

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

        h->non_zero_count_cache[2+8*3]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;

    }

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

        if(left_type[i]){

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

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

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

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

        }else{

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

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

            h->non_zero_count_cache[0+8*1 +   8*i]=

            h->non_zero_count_cache[0+8*4 +   8*i]= h->pps.cabac && !IS_INTRA(mb_type) ? 0 : 64;

        }

    }

    if( h->pps.cabac ) {

        // top_cbp

        if(top_type) {

            h->top_cbp = h->cbp_table[top_xy];

        } else if(IS_INTRA(mb_type)) {

            h->top_cbp = 0x1C0;

        } else {

            h->top_cbp = 0;

        }

        // left_cbp

        if (left_type[0]) {

            h->left_cbp = h->cbp_table[left_xy[0]] & 0x1f0;

        } else if(IS_INTRA(mb_type)) {

            h->left_cbp = 0x1C0;

        } else {

            h->left_cbp = 0;

        }

        if (left_type[0]) {

            h->left_cbp |= ((h->cbp_table[left_xy[0]]>>((left_block[0]&(~1))+1))&0x1) << 1;

        }

        if (left_type[1]) {

            h->left_cbp |= ((h->cbp_table[left_xy[1]]>>((left_block[2]&(~1))+1))&0x1) << 3;

        }

    }

#if 1

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

        int list;

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

            if(!USES_LIST(mb_type, list) && !IS_DIRECT(mb_type) && !h->deblocking_filter){

                /*if(!h->mv_cache_clean[list]){

                    memset(h->mv_cache [list],  0, 8*5*2*sizeof(int16_t)); //FIXME clean only input? clean at all?

                    memset(h->ref_cache[list], PART_NOT_AVAILABLE, 8*5*sizeof(int8_t));

                    h->mv_cache_clean[list]= 1;

                }*/

                continue;

            }

            h->mv_cache_clean[list]= 0;

            if(USES_LIST(top_type, list)){

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

                const int b8_xy= h->mb2b8_xy[top_xy] + h->b8_stride;

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

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

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

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

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

                h->ref_cache[list][scan8[0] + 1 - 1*8]= 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]= s->current_picture.ref_index[list][b8_xy + 1];

            }else{

                *(uint32_t*)h->mv_cache [list][scan8[0] + 0 - 1*8]=

                *(uint32_t*)h->mv_cache [list][scan8[0] + 1 - 1*8]=

                *(uint32_t*)h->mv_cache [list][scan8[0] + 2 - 1*8]=

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

                *(uint32_t*)&h->ref_cache[list][scan8[0] + 0 - 1*8]= ((top_type ? LIST_NOT_USED : PART_NOT_AVAILABLE)&0xFF)*0x01010101;

            }

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

                int cache_idx = scan8[0] - 1 + i*2*8;

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

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

                    const int b8_xy= h->mb2b8_xy[left_xy[i]] + 1;

                    *(uint32_t*)h->mv_cache[list][cache_idx  ]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[0+i*2]];

                    *(uint32_t*)h->mv_cache[list][cache_idx+8]= *(uint32_t*)s->current_picture.motion_val[list][b_xy + h->b_stride*left_block[1+i*2]];

                    h->ref_cache[list][cache_idx  ]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[0+i*2]>>1)];

                    h->ref_cache[list][cache_idx+8]= s->current_picture.ref_index[list][b8_xy + h->b8_stride*(left_block[1+i*2]>>1)];

                }else{

                    *(uint32_t*)h->mv_cache [list][cache_idx  ]=

                    *(uint32_t*)h->mv_cache [list][cache_idx+8]= 0;

                    h->ref_cache[list][cache_idx  ]=

                    h->ref_cache[list][cache_idx+8]= left_type[i] ? LIST_NOT_USED : PART_NOT_AVAILABLE;

                }

            }

            if((for_deblock || (IS_DIRECT(mb_type) && !h->direct_spatial_mv_pred)) && !FRAME_MBAFF)

                continue;

            if(USES_LIST(topleft_type, list)){

                const int b_xy = h->mb2b_xy[topleft_xy] + 3 + h->b_stride + (topleft_partition & 2*h->b_stride);

                const int b8_xy= h->mb2b8_xy[topleft_xy] + 1 + (topleft_partition & h->b8_stride);

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

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

            }else{

                *(uint32_t*)h->mv_cache[list][scan8[0] - 1 - 1*8]= 0;

                h->ref_cache[list][scan8[0] - 1 - 1*8]= topleft_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;

            }

            if(USES_LIST(topright_type, list)){

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

                const int b8_xy= h->mb2b8_xy[topright_xy] + h->b8_stride;

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

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

            }else{

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

                h->ref_cache[list][scan8[0] + 4 - 1*8]= topright_type ? LIST_NOT_USED : PART_NOT_AVAILABLE;

            }

            if((IS_SKIP(mb_type) || IS_DIRECT(mb_type)) && !FRAME_MBAFF)

                continue;

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

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

            h->ref_cache[list][scan8[13]+1] =  //FIXME remove past 3 (init somewhere else)

            h->ref_cache[list][scan8[4 ]] =

            h->ref_cache[list][scan8[12]] = PART_NOT_AVAILABLE;

            *(uint32_t*)h->mv_cache [list][scan8[5 ]+1]=

            *(uint32_t*)h->mv_cache [list][scan8[7 ]+1]=

            *(uint32_t*)h->mv_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)

            *(uint32_t*)h->mv_cache [list][scan8[4 ]]=

            *(uint32_t*)h->mv_cache [list][scan8[12]]= 0;

            if( h->pps.cabac ) {

                /* XXX beurk, Load mvd */

                if(USES_LIST(top_type, list)){

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

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 0 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 0];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 1 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 1];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 2 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 2];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] + 3 - 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + 3];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 0 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 1 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 2 - 1*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] + 3 - 1*8]= 0;

                }

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

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

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 0*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[0]];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 1*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[1]];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 0*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 1*8]= 0;

                }

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

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

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 2*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[2]];

                    *(uint32_t*)h->mvd_cache[list][scan8[0] - 1 + 3*8]= *(uint32_t*)h->mvd_table[list][b_xy + h->b_stride*left_block[3]];

                }else{

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 2*8]=

                    *(uint32_t*)h->mvd_cache [list][scan8[0] - 1 + 3*8]= 0;

                }

                *(uint32_t*)h->mvd_cache [list][scan8[5 ]+1]=

                *(uint32_t*)h->mvd_cache [list][scan8[7 ]+1]=

                *(uint32_t*)h->mvd_cache [list][scan8[13]+1]= //FIXME remove past 3 (init somewhere else)

                *(uint32_t*)h->mvd_cache [list][scan8[4 ]]=

                *(uint32_t*)h->mvd_cache [list][scan8[12]]= 0;

                if(h->slice_type_nos == FF_B_TYPE){

                    fill_rectangle(&h->direct_cache[scan8[0]], 4, 4, 8, 0, 1);

                    if(IS_DIRECT(top_type)){

                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0x01010101;

                    }else if(IS_8X8(top_type)){

                        int b8_xy = h->mb2b8_xy[top_xy] + h->b8_stride;

                        h->direct_cache[scan8[0] + 0 - 1*8]= h->direct_table[b8_xy];

                        h->direct_cache[scan8[0] + 2 - 1*8]= h->direct_table[b8_xy + 1];

                    }else{

                        *(uint32_t*)&h->direct_cache[scan8[0] - 1*8]= 0;

                    }

                    if(IS_DIRECT(left_type[0]))

                        h->direct_cache[scan8[0] - 1 + 0*8]= 1;

                    else if(IS_8X8(left_type[0]))

                        h->direct_cache[scan8[0] - 1 + 0*8]= h->direct_table[h->mb2b8_xy[left_xy[0]] + 1 + h->b8_stride*(left_block[0]>>1)];

                    else

                        h->direct_cache[scan8[0] - 1 + 0*8]= 0;

                    if(IS_DIRECT(left_type[1]))

                        h->direct_cache[scan8[0] - 1 + 2*8]= 1;

                    else if(IS_8X8(left_type[1]))

                        h->direct_cache[scan8[0] - 1 + 2*8]= h->direct_table[h->mb2b8_xy[left_xy[1]] + 1 + h->b8_stride*(left_block[2]>>1)];

                    else

                        h->direct_cache[scan8[0] - 1 + 2*8]= 0;

                }

            }

            if(FRAME_MBAFF){

#define MAP_MVS\

                    MAP_F2F(scan8[0] - 1 - 1*8, topleft_type)\

                    MAP_F2F(scan8[0] + 0 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 1 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 2 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 3 - 1*8, top_type)\

                    MAP_F2F(scan8[0] + 4 - 1*8, topright_type)\

                    MAP_F2F(scan8[0] - 1 + 0*8, left_type[0])\

                    MAP_F2F(scan8[0] - 1 + 1*8, left_type[0])\

                    MAP_F2F(scan8[0] - 1 + 2*8, left_type[1])\

                    MAP_F2F(scan8[0] - 1 + 3*8, left_type[1])

                if(MB_FIELD){

#define MAP_F2F(idx, mb_type)\

                    if(!IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\

                        h->ref_cache[list][idx] <<= 1;\

                        h->mv_cache[list][idx][1] /= 2;\

                        h->mvd_cache[list][idx][1] /= 2;\

                    }

                    MAP_MVS

#undef MAP_F2F

                }else{

#define MAP_F2F(idx, mb_type)\

                    if(IS_INTERLACED(mb_type) && h->ref_cache[list][idx] >= 0){\

                        h->ref_cache[list][idx] >>= 1;\

                        h->mv_cache[list][idx][1] <<= 1;\

                        h->mvd_cache[list][idx][1] <<= 1;\

                    }

                    MAP_MVS

#undef MAP_F2F

                }

            }

        }

    }

#endif

    h->neighbor_transform_size= !!IS_8x8DCT(top_type) + !!IS_8x8DCT(left_type[0]);

}


static void lsi_scsi_init(PCIDevice *dev)
{
    LSIState *s = (LSIState *)dev;
    uint8_t *pci_conf;
    pci_conf = s->pci_dev.config;
    /* PCI Vendor ID (word) */
    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_LSI_LOGIC);
    /* PCI device ID (word) */
    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_LSI_53C895A);
    /* PCI base class code */
    pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_SCSI);
    /* PCI subsystem ID */
    pci_conf[0x2e] = 0x00;
    pci_conf[0x2f] = 0x10;
    /* PCI latency timer = 255 */
    pci_conf[0x0d] = 0xff;
    /* Interrupt pin 1 */
    pci_conf[0x3d] = 0x01;
    s->mmio_io_addr = cpu_register_io_memory(lsi_mmio_readfn,
                                             lsi_mmio_writefn, s);
    s->ram_io_addr = cpu_register_io_memory(lsi_ram_readfn,
                                            lsi_ram_writefn, s);
    pci_register_bar((struct PCIDevice *)s, 0, 256,
                           PCI_ADDRESS_SPACE_IO, lsi_io_mapfunc);
    pci_register_bar((struct PCIDevice *)s, 1, 0x400,
                           PCI_ADDRESS_SPACE_MEM, lsi_mmio_mapfunc);
    pci_register_bar((struct PCIDevice *)s, 2, 0x2000,
                           PCI_ADDRESS_SPACE_MEM, lsi_ram_mapfunc);
    s->queue = qemu_malloc(sizeof(lsi_queue));
    s->queue_len = 1;
    s->active_commands = 0;
    s->pci_dev.unregister = lsi_scsi_uninit;
    lsi_soft_reset(s);
    scsi_bus_new(&dev->qdev, lsi_scsi_attach);
}


int ff_j2k_init_component(J2kComponent *comp, J2kCodingStyle *codsty, J2kQuantStyle *qntsty, int cbps, int dx, int dy)

{

    int reslevelno, bandno, gbandno = 0, ret, i, j, csize = 1;

    if (ret=ff_j2k_dwt_init(&comp->dwt, comp->coord, codsty->nreslevels-1, codsty->transform))

        return ret;

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

        csize *= comp->coord[i][1] - comp->coord[i][0];

    comp->data = av_malloc(csize * sizeof(int));

    if (!comp->data)

        return AVERROR(ENOMEM);

    comp->reslevel = av_malloc(codsty->nreslevels * sizeof(J2kResLevel));

    if (!comp->reslevel)

        return AVERROR(ENOMEM);

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

        int declvl = codsty->nreslevels - reslevelno;

        J2kResLevel *reslevel = comp->reslevel + reslevelno;

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

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

                reslevel->coord[i][j] =

                    ff_j2k_ceildivpow2(comp->coord[i][j], declvl - 1);

        if (reslevelno == 0)

            reslevel->nbands = 1;

        else

            reslevel->nbands = 3;

        if (reslevel->coord[0][1] == reslevel->coord[0][0])

            reslevel->num_precincts_x = 0;

        else

            reslevel->num_precincts_x = ff_j2k_ceildivpow2(reslevel->coord[0][1], codsty->log2_prec_width)

                                        - (reslevel->coord[0][0] >> codsty->log2_prec_width);

        if (reslevel->coord[1][1] == reslevel->coord[1][0])

            reslevel->num_precincts_y = 0;

        else

            reslevel->num_precincts_y = ff_j2k_ceildivpow2(reslevel->coord[1][1], codsty->log2_prec_height)

                                        - (reslevel->coord[1][0] >> codsty->log2_prec_height);

        reslevel->band = av_malloc(reslevel->nbands * sizeof(J2kBand));

        if (!reslevel->band)

            return AVERROR(ENOMEM);

        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++){

            J2kBand *band = reslevel->band + bandno;

            int cblkno, precx, precy, precno;

            int x0, y0, x1, y1;

            int xi0, yi0, xi1, yi1;

            int cblkperprecw, cblkperprech;

            if (qntsty->quantsty != J2K_QSTY_NONE){

                static const uint8_t lut_gain[2][4] = {{0, 0, 0, 0}, {0, 1, 1, 2}};

                int numbps;

                numbps = cbps + lut_gain[codsty->transform][bandno + reslevelno>0];

                band->stepsize = SHL(2048 + qntsty->mant[gbandno], 2 + numbps - qntsty->expn[gbandno]);

            } else

                band->stepsize = 1 << 13;

            if (reslevelno == 0){  // the same everywhere

                band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width-1);

                band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height-1);

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

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

                        band->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j], declvl-1);

            } else{

                band->codeblock_width = 1 << FFMIN(codsty->log2_cblk_width, codsty->log2_prec_width);

                band->codeblock_height = 1 << FFMIN(codsty->log2_cblk_height, codsty->log2_prec_height);

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

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

                        band->coord[i][j] = ff_j2k_ceildivpow2(comp->coord[i][j] - (((bandno+1>>i)&1) << declvl-1), declvl);

            }

            band->cblknx = ff_j2k_ceildiv(band->coord[0][1], band->codeblock_width)  - band->coord[0][0] / band->codeblock_width;

            band->cblkny = ff_j2k_ceildiv(band->coord[1][1], band->codeblock_height) - band->coord[1][0] / band->codeblock_height;

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

                band->coord[0][j] = ff_j2k_ceildiv(band->coord[0][j], dx);

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

                band->coord[1][j] = ff_j2k_ceildiv(band->coord[1][j], dy);

            band->cblknx = ff_j2k_ceildiv(band->cblknx, dx);

            band->cblkny = ff_j2k_ceildiv(band->cblkny, dy);

            band->cblk = av_malloc(band->cblknx * band->cblkny * sizeof(J2kCblk));

            if (!band->cblk)

                return AVERROR(ENOMEM);

            band->prec = av_malloc(reslevel->num_precincts_x * reslevel->num_precincts_y * sizeof(J2kPrec));

            if (!band->prec)

                return AVERROR(ENOMEM);

            for (cblkno = 0; cblkno < band->cblknx * band->cblkny; cblkno++){

                J2kCblk *cblk = band->cblk + cblkno;

                cblk->zero = 0;

                cblk->lblock = 3;

                cblk->length = 0;

                cblk->lengthinc = 0;

                cblk->npasses = 0;

            }

            y0 = band->coord[1][0];

            y1 = ((band->coord[1][0] + (1<<codsty->log2_prec_height)) & ~((1<<codsty->log2_prec_height)-1)) - y0;

            yi0 = 0;

            yi1 = ff_j2k_ceildivpow2(y1 - y0, codsty->log2_cblk_height) << codsty->log2_cblk_height;

            yi1 = FFMIN(yi1, band->cblkny);

            cblkperprech = 1<<(codsty->log2_prec_height - codsty->log2_cblk_height);

            for (precy = 0, precno = 0; precy < reslevel->num_precincts_y; precy++){

                for (precx = 0; precx < reslevel->num_precincts_x; precx++, precno++){

                    band->prec[precno].yi0 = yi0;

                    band->prec[precno].yi1 = yi1;

                }

                yi1 += cblkperprech;

                yi0 = yi1 - cblkperprech;

                yi1 = FFMIN(yi1, band->cblkny);

            }

            x0 = band->coord[0][0];

            x1 = ((band->coord[0][0] + (1<<codsty->log2_prec_width)) & ~((1<<codsty->log2_prec_width)-1)) - x0;

            xi0 = 0;

            xi1 = ff_j2k_ceildivpow2(x1 - x0, codsty->log2_cblk_width) << codsty->log2_cblk_width;

            xi1 = FFMIN(xi1, band->cblknx);

            cblkperprecw = 1<<(codsty->log2_prec_width - codsty->log2_cblk_width);

            for (precx = 0, precno = 0; precx < reslevel->num_precincts_x; precx++){

                for (precy = 0; precy < reslevel->num_precincts_y; precy++, precno = 0){

                    J2kPrec *prec = band->prec + precno;

                    prec->xi0 = xi0;

                    prec->xi1 = xi1;

                    prec->cblkincl = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0,

                                                          prec->yi1 - prec->yi0);

                    prec->zerobits = ff_j2k_tag_tree_init(prec->xi1 - prec->xi0,

                                                          prec->yi1 - prec->yi0);

                    if (!prec->cblkincl || !prec->zerobits)

                        return AVERROR(ENOMEM);

                }

                xi1 += cblkperprecw;

                xi0 = xi1 - cblkperprecw;

                xi1 = FFMIN(xi1, band->cblknx);

            }

        }

    }

    return 0;

}


void vncws_tls_handshake_io(void *opaque)

{

    VncState *vs = (VncState *)opaque;

    if (!vs->tls.session) {

        VNC_DEBUG("TLS Websocket setup\n");

        if (vnc_tls_client_setup(vs, vs->vd->tls.x509cert != NULL) < 0) {

            return;

        }

    }

    VNC_DEBUG("Handshake IO continue\n");

    vncws_start_tls_handshake(vs);

}


int css_do_rsch(SubchDev *sch)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    int ret;

    if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {

        ret = -ENODEV;

        goto out;

    }

    if (s->ctrl & SCSW_STCTL_STATUS_PEND) {

        ret = -EINPROGRESS;

        goto out;

    }

    if (((s->ctrl & SCSW_CTRL_MASK_FCTL) != SCSW_FCTL_START_FUNC) ||

        (s->ctrl & SCSW_ACTL_RESUME_PEND) ||

        (!(s->ctrl & SCSW_ACTL_SUSP))) {

        ret = -EINVAL;

        goto out;

    }

    /* If monitoring is active, update counter. */

    if (channel_subsys.chnmon_active) {

        css_update_chnmon(sch);

    }

    s->ctrl |= SCSW_ACTL_RESUME_PEND;

    do_subchannel_work(sch);

    ret = 0;

out:

    return ret;

}


ram_addr_t ppc4xx_sdram_adjust(ram_addr_t ram_size, int nr_banks,

                               MemoryRegion ram_memories[],

                               hwaddr ram_bases[],

                               hwaddr ram_sizes[],

                               const unsigned int sdram_bank_sizes[])

{

    ram_addr_t size_left = ram_size;

    ram_addr_t base = 0;

    int i;

    int j;

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

        for (j = 0; sdram_bank_sizes[j] != 0; j++) {

            unsigned int bank_size = sdram_bank_sizes[j];

            if (bank_size <= size_left) {

                char name[32];

                snprintf(name, sizeof(name), "ppc4xx.sdram%d", i);

                memory_region_allocate_system_memory(&ram_memories[i], NULL,

                                                     name, bank_size);

                ram_bases[i] = base;

                ram_sizes[i] = bank_size;

                base += bank_size;

                size_left -= bank_size;

                break;

            }

        }

        if (!size_left) {

            /* No need to use the remaining banks. */

            break;

        }

    }

    ram_size -= size_left;

    if (size_left)

        printf("Truncating memory to %d MiB to fit SDRAM controller limits.\n",

               (int)(ram_size >> 20));

    return ram_size;

}


static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFCryptoContext *cryptocontext = arg;

    if (size != 16)

        return -1;

    if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul))

        avio_read(pb, cryptocontext->source_container_ul, 16);

    return 0;

}


void ff_eac3_decode_transform_coeffs_aht_ch(AC3DecodeContext *s, int ch)

{

    int bin, blk, gs;

    int end_bap, gaq_mode;

    GetBitContext *gbc = &s->gbc;

    int gaq_gain[AC3_MAX_COEFS];

    gaq_mode = get_bits(gbc, 2);

    end_bap = (gaq_mode < 2) ? 12 : 17;

    /* if GAQ gain is used, decode gain codes for bins with hebap between

       8 and end_bap */

    gs = 0;

    if (gaq_mode == EAC3_GAQ_12 || gaq_mode == EAC3_GAQ_14) {

        /* read 1-bit GAQ gain codes */

        for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

            if (s->bap[ch][bin] > 7 && s->bap[ch][bin] < end_bap)

                gaq_gain[gs++] = get_bits1(gbc) << (gaq_mode-1);

        }

    } else if (gaq_mode == EAC3_GAQ_124) {

        /* read 1.67-bit GAQ gain codes (3 codes in 5 bits) */

        int gc = 2;

        for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

            if (s->bap[ch][bin] > 7 && s->bap[ch][bin] < 17) {

                if (gc++ == 2) {

                    int group_code = get_bits(gbc, 5);

                    if (group_code > 26) {

                        av_log(s->avctx, AV_LOG_WARNING, "GAQ gain group code out-of-range\n");

                        group_code = 26;

                    }

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][0];

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][1];

                    gaq_gain[gs++] = ff_ac3_ungroup_3_in_5_bits_tab[group_code][2];

                    gc = 0;

                }

            }

        }

    }

    gs=0;

    for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {

        int hebap = s->bap[ch][bin];

        int bits = ff_eac3_bits_vs_hebap[hebap];

        if (!hebap) {

            /* zero-mantissa dithering */

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

                s->pre_mantissa[ch][bin][blk] = (av_lfg_get(&s->dith_state) & 0x7FFFFF) - 0x400000;

            }

        } else if (hebap < 8) {

            /* Vector Quantization */

            int v = get_bits(gbc, bits);

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

                s->pre_mantissa[ch][bin][blk] = ff_eac3_mantissa_vq[hebap][v][blk] << 8;

            }

        } else {

            /* Gain Adaptive Quantization */

            int gbits, log_gain;

            if (gaq_mode != EAC3_GAQ_NO && hebap < end_bap) {

                log_gain = gaq_gain[gs++];

            } else {

                log_gain = 0;

            }

            gbits = bits - log_gain;

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

                int mant = get_sbits(gbc, gbits);

                if (log_gain && mant == -(1 << (gbits-1))) {

                    /* large mantissa */

                    int b;

                    int mbits = bits - (2 - log_gain);

                    mant = get_sbits(gbc, mbits);

                    mant <<= (23 - (mbits - 1));

                    /* remap mantissa value to correct for asymmetric quantization */

                    if (mant >= 0)

                        b = 1 << (23 - log_gain);

                    else

                        b = ff_eac3_gaq_remap_2_4_b[hebap-8][log_gain-1] << 8;

                    mant += ((ff_eac3_gaq_remap_2_4_a[hebap-8][log_gain-1] * (int64_t)mant) >> 15) + b;

                } else {

                    /* small mantissa, no GAQ, or Gk=1 */

                    mant <<= 24 - bits;

                    if (!log_gain) {

                        /* remap mantissa value for no GAQ or Gk=1 */

                        mant += (ff_eac3_gaq_remap_1[hebap-8] * (int64_t)mant) >> 15;

                    }

                }

                s->pre_mantissa[ch][bin][blk] = mant;

            }

        }

        idct6(s->pre_mantissa[ch][bin]);

    }

}


void unregister_displaychangelistener(DisplayChangeListener *dcl)

{

    DisplayState *ds = dcl->ds;

    trace_displaychangelistener_unregister(dcl, dcl->ops->dpy_name);

    if (dcl->con) {

        dcl->con->dcls--;

    }

    QLIST_REMOVE(dcl, next);

    gui_setup_refresh(ds);

}


int avpicture_layout(const AVPicture* src, enum AVPixelFormat pix_fmt,

                     int width, int height,

                     unsigned char *dest, int dest_size)

{

    int i, j, nb_planes = 0, linesizes[4];

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);

    int size = avpicture_get_size(pix_fmt, width, height);

    if (size > dest_size || size < 0)

        return AVERROR(EINVAL);

    for (i = 0; i < desc->nb_components; i++)

        nb_planes = FFMAX(desc->comp[i].plane, nb_planes);

    nb_planes++;

    av_image_fill_linesizes(linesizes, pix_fmt, width);

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

        int h, shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;

        const unsigned char *s = src->data[i];

        h = (height + (1 << shift) - 1) >> shift;

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

            memcpy(dest, s, linesizes[i]);

            dest += linesizes[i];

            s += src->linesize[i];

        }

    }

    if (desc->flags & AV_PIX_FMT_FLAG_PAL)

        memcpy((unsigned char *)(((size_t)dest + 3) & ~3),

               src->data[1], 256 * 4);

    return size;

}


static int pipe_open(URLContext *h, const char *filename, int flags)

{

    int fd;

    if (flags & URL_WRONLY) {

        fd = 1;

    } else {

        fd = 0;

    }

#if defined(__MINGW32__) || defined(CONFIG_OS2) || defined(__CYGWIN__)

    setmode(fd, O_BINARY);

#endif

    h->priv_data = (void *)(size_t)fd;

    h->is_streamed = 1;

    return 0;

}


static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)

{

    AVFrame *decoded_frame, *f;

    void *buffer_to_free = NULL;

    int i, ret = 0, err = 0, resample_changed;

    int64_t best_effort_timestamp;

    AVRational *frame_sample_aspect;

    if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    decoded_frame = ist->decoded_frame;

    pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);

    update_benchmark(NULL);

    ret = avcodec_decode_video2(ist->st->codec,

                                decoded_frame, got_output, pkt);

    update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);

    if (!*got_output || ret < 0) {

        if (!pkt->size) {

            for (i = 0; i < ist->nb_filters; i++)

#if 1

                av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);

#else

                av_buffersrc_add_frame(ist->filters[i]->filter, NULL);

#endif

        }

        return ret;

    }

    if(ist->top_field_first>=0)

        decoded_frame->top_field_first = ist->top_field_first;

    best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);

    if(best_effort_timestamp != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "

                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",

                ist->st->index, av_ts2str(decoded_frame->pts),

                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),

                best_effort_timestamp,

                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),

                decoded_frame->key_frame, decoded_frame->pict_type);

    }

    pkt->size = 0;

#if FF_API_DEINTERLACE

    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

#endif

    rate_emu_sleep(ist);

    if (ist->st->sample_aspect_ratio.num)

        decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;

    resample_changed = ist->resample_width   != decoded_frame->width  ||

                       ist->resample_height  != decoded_frame->height ||

                       ist->resample_pix_fmt != decoded_frame->format;

    if (resample_changed) {

        av_log(NULL, AV_LOG_INFO,

               "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",

               ist->file_index, ist->st->index,

               ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),

               decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));

        ist->resample_width   = decoded_frame->width;

        ist->resample_height  = decoded_frame->height;

        ist->resample_pix_fmt = decoded_frame->format;

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

            if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&

                configure_filtergraph(filtergraphs[i]) < 0) {

                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");

                exit(1);

            }

        }

    }

    frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");

    for (i = 0; i < ist->nb_filters; i++) {

        if (!frame_sample_aspect->num)

            *frame_sample_aspect = ist->st->sample_aspect_ratio;

        if (i < ist->nb_filters - 1) {

            f = ist->filter_frame;

            err = av_frame_ref(f, decoded_frame);

            if (err < 0)

                break;

        } else

            f = decoded_frame;

        if(av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,

                                        AV_BUFFERSRC_FLAG_PUSH)<0) {

            av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");

            exit(1);

        }

    }

    av_frame_unref(ist->filter_frame);

    av_frame_unref(decoded_frame);

    av_free(buffer_to_free);

    return err < 0 ? err : ret;

}


static void audio_encode_example(const char *filename)

{

    AVCodec *codec;

    AVCodecContext *c= NULL;

    AVFrame *frame;

    AVPacket pkt;

    int i, j, k, ret, got_output;

    int buffer_size;

    FILE *f;

    uint16_t *samples;

    float t, tincr;

    printf("Encode audio file %s\n", filename);

    /* find the MP2 encoder */

    codec = avcodec_find_encoder(AV_CODEC_ID_MP2);

    if (!codec) {

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

        exit(1);

    }

    c = avcodec_alloc_context3(codec);

    if (!c) {

        fprintf(stderr, "Could not allocate audio codec context\n");

        exit(1);

    }

    /* put sample parameters */

    c->bit_rate = 64000;

    /* check that the encoder supports s16 pcm input */

    c->sample_fmt = AV_SAMPLE_FMT_S16;

    if (!check_sample_fmt(codec, c->sample_fmt)) {

        fprintf(stderr, "Encoder does not support sample format %s",

                av_get_sample_fmt_name(c->sample_fmt));

        exit(1);

    }

    /* select other audio parameters supported by the encoder */

    c->sample_rate    = select_sample_rate(codec);

    c->channel_layout = select_channel_layout(codec);

    c->channels       = av_get_channel_layout_nb_channels(c->channel_layout);

    /* open it */

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

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

        exit(1);

    }

    f = fopen(filename, "wb");

    if (!f) {

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

        exit(1);

    }

    /* frame containing input raw audio */

    frame = av_frame_alloc();

    if (!frame) {

        fprintf(stderr, "Could not allocate audio frame\n");

        exit(1);

    }

    frame->nb_samples     = c->frame_size;

    frame->format         = c->sample_fmt;

    frame->channel_layout = c->channel_layout;

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

     * we calculate the size of the samples buffer in bytes */

    buffer_size = av_samples_get_buffer_size(NULL, c->channels, c->frame_size,

                                             c->sample_fmt, 0);

    if (!buffer_size) {

        fprintf(stderr, "Could not get sample buffer size\n");

        exit(1);

    }

    samples = av_malloc(buffer_size);

    if (!samples) {

        fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",

                buffer_size);

        exit(1);

    }

    /* setup the data pointers in the AVFrame */

    ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,

                                   (const uint8_t*)samples, buffer_size, 0);

    if (ret < 0) {

        fprintf(stderr, "Could not setup audio frame\n");

        exit(1);

    }

    /* encode a single tone sound */

    t = 0;

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

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

        av_init_packet(&pkt);

        pkt.data = NULL; // packet data will be allocated by the encoder

        pkt.size = 0;

        for (j = 0; j < c->frame_size; j++) {

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

            for (k = 1; k < c->channels; k++)

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

            t += tincr;

        }

        /* encode the samples */

        ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);

        if (ret < 0) {

            fprintf(stderr, "Error encoding audio frame\n");

            exit(1);

        }

        if (got_output) {

            fwrite(pkt.data, 1, pkt.size, f);

            av_free_packet(&pkt);

        }

    }

    /* get the delayed frames */

    for (got_output = 1; got_output; i++) {

        ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);

        if (ret < 0) {

            fprintf(stderr, "Error encoding frame\n");

            exit(1);

        }

        if (got_output) {

            fwrite(pkt.data, 1, pkt.size, f);

            av_free_packet(&pkt);

        }

    }

    fclose(f);

    av_freep(&samples);

    av_frame_free(&frame);

    avcodec_close(c);

    av_free(c);

}


static void avconv_cleanup(int ret)

{

    int i, j;

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

        FilterGraph *fg = filtergraphs[i];

        avfilter_graph_free(&fg->graph);

        for (j = 0; j < fg->nb_inputs; j++) {

            while (av_fifo_size(fg->inputs[j]->frame_queue)) {

                AVFrame *frame;

                av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,

                                     sizeof(frame), NULL);

                av_frame_free(&frame);

            }

            av_fifo_free(fg->inputs[j]->frame_queue);

            av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);

            av_freep(&fg->inputs[j]->name);

            av_freep(&fg->inputs[j]);

        }

        av_freep(&fg->inputs);

        for (j = 0; j < fg->nb_outputs; j++) {

            av_freep(&fg->outputs[j]->name);

            av_freep(&fg->outputs[j]->formats);

            av_freep(&fg->outputs[j]->channel_layouts);

            av_freep(&fg->outputs[j]->sample_rates);

            av_freep(&fg->outputs[j]);

        }

        av_freep(&fg->outputs);

        av_freep(&fg->graph_desc);

        av_freep(&filtergraphs[i]);

    }

    av_freep(&filtergraphs);

    /* close files */

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

        OutputFile *of = output_files[i];

        AVFormatContext *s = of->ctx;

        if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)

            avio_close(s->pb);

        avformat_free_context(s);

        av_dict_free(&of->opts);

        av_freep(&output_files[i]);

    }

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

        OutputStream *ost = output_streams[i];

        for (j = 0; j < ost->nb_bitstream_filters; j++)

            av_bsf_free(&ost->bsf_ctx[j]);

        av_freep(&ost->bsf_ctx);

        av_freep(&ost->bitstream_filters);

        av_frame_free(&ost->filtered_frame);

        av_parser_close(ost->parser);

        avcodec_free_context(&ost->parser_avctx);

        av_freep(&ost->forced_keyframes);

        av_freep(&ost->avfilter);

        av_freep(&ost->logfile_prefix);

        avcodec_free_context(&ost->enc_ctx);

        while (av_fifo_size(ost->muxing_queue)) {

            AVPacket pkt;

            av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);

            av_packet_unref(&pkt);

        }

        av_fifo_free(ost->muxing_queue);

        av_freep(&output_streams[i]);

    }

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

        avformat_close_input(&input_files[i]->ctx);

        av_freep(&input_files[i]);

    }

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

        InputStream *ist = input_streams[i];

        av_frame_free(&ist->decoded_frame);

        av_frame_free(&ist->filter_frame);

        av_dict_free(&ist->decoder_opts);

        av_freep(&ist->filters);

        av_freep(&ist->hwaccel_device);

        avcodec_free_context(&ist->dec_ctx);

        av_freep(&input_streams[i]);

    }

    if (vstats_file)

        fclose(vstats_file);

    av_free(vstats_filename);

    av_freep(&input_streams);

    av_freep(&input_files);

    av_freep(&output_streams);

    av_freep(&output_files);

    uninit_opts();

    avformat_network_deinit();

    if (received_sigterm) {

        av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",

               (int) received_sigterm);

        exit (255);

    }

}


static void dump_stream_format(AVFormatContext *ic, int i, int index, int is_output)

{

    char buf[256];

    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);

    AVStream *st = ic->streams[i];

    int g = ff_gcd(st->time_base.num, st->time_base.den);

    avcodec_string(buf, sizeof(buf), st->codec, is_output);

    av_log(NULL, AV_LOG_INFO, "    Stream #%d.%d", index, i);

    /* the pid is an important information, so we display it */

    /* XXX: add a generic system */

    if (flags & AVFMT_SHOW_IDS)

        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);

    if (strlen(st->language) > 0)

        av_log(NULL, AV_LOG_INFO, "(%s)", st->language);

    av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);

    av_log(NULL, AV_LOG_INFO, ": %s", buf);

    if(st->codec->codec_type == CODEC_TYPE_VIDEO){

        if(st->r_frame_rate.den && st->r_frame_rate.num)

            av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));

/*      else if(st->time_base.den && st->time_base.num)

            av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/

        else

            av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));

    }

    av_log(NULL, AV_LOG_INFO, "\n");

}


static inline void rv34_decode_block(DCTELEM *dst, GetBitContext *gb, RV34VLC *rvlc, int fc, int sc, int q_dc, int q_ac1, int q_ac2)

{

    int code, pattern;

    code = get_vlc2(gb, rvlc->first_pattern[fc].table, 9, 2);

    pattern = code & 0x7;

    code >>= 3;

    decode_subblock3(dst, code, 0, gb, &rvlc->coefficient, q_dc, q_ac1, q_ac2);

    if(pattern & 4){

        code = get_vlc2(gb, rvlc->second_pattern[sc].table, 9, 2);

        decode_subblock(dst + 2, code, 0, gb, &rvlc->coefficient, q_ac2);

    }

    if(pattern & 2){ // Looks like coefficients 1 and 2 are swapped for this block

        code = get_vlc2(gb, rvlc->second_pattern[sc].table, 9, 2);

        decode_subblock(dst + 8*2, code, 1, gb, &rvlc->coefficient, q_ac2);

    }

    if(pattern & 1){

        code = get_vlc2(gb, rvlc->third_pattern[sc].table, 9, 2);

        decode_subblock(dst + 8*2+2, code, 0, gb, &rvlc->coefficient, q_ac2);

    }

}


static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,

                                  bool assign, uint32_t size, bool datamatch)

{

    int ret;

    struct kvm_ioeventfd iofd;

    iofd.datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0;

    iofd.addr = addr;

    iofd.len = size;

    iofd.flags = 0;

    iofd.fd = fd;

    if (!kvm_enabled()) {

        return -ENOSYS;

    }

    if (datamatch) {

        iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;

    }

    if (!assign) {

        iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;

    }

    ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);

    if (ret < 0) {

        return -errno;

    }

    return 0;

}


AVFrameSideData *av_frame_new_side_data(AVFrame *frame,

                                        enum AVFrameSideDataType type,

                                        int size)

{

    AVFrameSideData *ret, **tmp;

    if (frame->nb_side_data > INT_MAX / sizeof(*frame->side_data) - 1)

        return NULL;

    tmp = av_realloc(frame->side_data,

                     (frame->nb_side_data + 1) * sizeof(*frame->side_data));

    if (!tmp)

        return NULL;

    frame->side_data = tmp;

    ret = av_mallocz(sizeof(*ret));

    if (!ret)

        return NULL;

    if (size > 0) {

        ret->buf = av_buffer_alloc(size);

        if (!ret->buf) {

            av_freep(&ret);

            return NULL;

        }

        ret->data = ret->buf->data;

        ret->size = size;

    }

    ret->type = type;

    frame->side_data[frame->nb_side_data++] = ret;

    return ret;

}


DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)

{

    const char *value;

    DriveInfo *dinfo = NULL;

    QDict *bs_opts;

    QemuOpts *legacy_opts;

    DriveMediaType media = MEDIA_DISK;

    BlockInterfaceType type;

    int cyls, heads, secs, translation;

    int max_devs, bus_id, unit_id, index;

    const char *devaddr;

    const char *werror, *rerror;

    bool read_only = false;

    bool copy_on_read;

    const char *filename;

    Error *local_err = NULL;

    /* Change legacy command line options into QMP ones */

    qemu_opt_rename(all_opts, "iops", "throttling.iops-total");

    qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");

    qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");

    qemu_opt_rename(all_opts, "bps", "throttling.bps-total");

    qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");

    qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");

    qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");

    qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");

    qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");

    qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");

    qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");

    qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");

    qemu_opt_rename(all_opts,

                    "iops_size", "throttling.iops-size");

    qemu_opt_rename(all_opts, "readonly", "read-only");

    value = qemu_opt_get(all_opts, "cache");

    if (value) {

        int flags = 0;

        if (bdrv_parse_cache_flags(value, &flags) != 0) {

            error_report("invalid cache option");

            return NULL;

        }

        /* Specific options take precedence */

        if (!qemu_opt_get(all_opts, "cache.writeback")) {

            qemu_opt_set_bool(all_opts, "cache.writeback",

                              !!(flags & BDRV_O_CACHE_WB));

        }

        if (!qemu_opt_get(all_opts, "cache.direct")) {

            qemu_opt_set_bool(all_opts, "cache.direct",

                              !!(flags & BDRV_O_NOCACHE));

        }

        if (!qemu_opt_get(all_opts, "cache.no-flush")) {

            qemu_opt_set_bool(all_opts, "cache.no-flush",

                              !!(flags & BDRV_O_NO_FLUSH));

        }

        qemu_opt_unset(all_opts, "cache");

    }

    /* Get a QDict for processing the options */

    bs_opts = qdict_new();

    qemu_opts_to_qdict(all_opts, bs_opts);

    legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,

                                   &error_abort);

    qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);

    if (local_err) {

        error_report("%s", error_get_pretty(local_err));

        error_free(local_err);

        goto fail;

    }

    /* Deprecated option boot=[on|off] */

    if (qemu_opt_get(legacy_opts, "boot") != NULL) {

        fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "

                "ignored. Future versions will reject this parameter. Please "

                "update your scripts.\n");

    }

    /* Media type */

    value = qemu_opt_get(legacy_opts, "media");

    if (value) {

        if (!strcmp(value, "disk")) {

            media = MEDIA_DISK;

        } else if (!strcmp(value, "cdrom")) {

            media = MEDIA_CDROM;

            read_only = true;

        } else {

            error_report("'%s' invalid media", value);

            goto fail;

        }

    }

    /* copy-on-read is disabled with a warning for read-only devices */

    read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);

    copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);

    if (read_only && copy_on_read) {

        error_report("warning: disabling copy-on-read on read-only drive");

        copy_on_read = false;

    }

    qdict_put(bs_opts, "read-only",

              qstring_from_str(read_only ? "on" : "off"));

    qdict_put(bs_opts, "copy-on-read",

              qstring_from_str(copy_on_read ? "on" :"off"));

    /* Controller type */

    value = qemu_opt_get(legacy_opts, "if");

    if (value) {

        for (type = 0;

             type < IF_COUNT && strcmp(value, if_name[type]);

             type++) {

        }

        if (type == IF_COUNT) {

            error_report("unsupported bus type '%s'", value);

            goto fail;

        }

    } else {

        type = block_default_type;

    }

    /* Geometry */

    cyls  = qemu_opt_get_number(legacy_opts, "cyls", 0);

    heads = qemu_opt_get_number(legacy_opts, "heads", 0);

    secs  = qemu_opt_get_number(legacy_opts, "secs", 0);

    if (cyls || heads || secs) {

        if (cyls < 1) {

            error_report("invalid physical cyls number");

            goto fail;

        }

        if (heads < 1) {

            error_report("invalid physical heads number");

            goto fail;

        }

        if (secs < 1) {

            error_report("invalid physical secs number");

            goto fail;

        }

    }

    translation = BIOS_ATA_TRANSLATION_AUTO;

    value = qemu_opt_get(legacy_opts, "trans");

    if (value != NULL) {

        if (!cyls) {

            error_report("'%s' trans must be used with cyls, heads and secs",

                         value);

            goto fail;

        }

        if (!strcmp(value, "none")) {

            translation = BIOS_ATA_TRANSLATION_NONE;

        } else if (!strcmp(value, "lba")) {

            translation = BIOS_ATA_TRANSLATION_LBA;

        } else if (!strcmp(value, "large")) {

            translation = BIOS_ATA_TRANSLATION_LARGE;

        } else if (!strcmp(value, "rechs")) {

            translation = BIOS_ATA_TRANSLATION_RECHS;

        } else if (!strcmp(value, "auto")) {

            translation = BIOS_ATA_TRANSLATION_AUTO;

        } else {

            error_report("'%s' invalid translation type", value);

            goto fail;

        }

    }

    if (media == MEDIA_CDROM) {

        if (cyls || secs || heads) {

            error_report("CHS can't be set with media=cdrom");

            goto fail;

        }

    }

    /* Device address specified by bus/unit or index.

     * If none was specified, try to find the first free one. */

    bus_id  = qemu_opt_get_number(legacy_opts, "bus", 0);

    unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);

    index   = qemu_opt_get_number(legacy_opts, "index", -1);

    max_devs = if_max_devs[type];

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            error_report("index cannot be used with bus and unit");

            goto fail;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get(type, bus_id, unit_id) != NULL) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    if (max_devs && unit_id >= max_devs) {

        error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);

        goto fail;

    }

    if (drive_get(type, bus_id, unit_id) != NULL) {

        error_report("drive with bus=%d, unit=%d (index=%d) exists",

                     bus_id, unit_id, index);

        goto fail;

    }

    /* no id supplied -> create one */

    if (qemu_opts_id(all_opts) == NULL) {

        char *new_id;

        const char *mediastr = "";

        if (type == IF_IDE || type == IF_SCSI) {

            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

        }

        if (max_devs) {

            new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,

                                     mediastr, unit_id);

        } else {

            new_id = g_strdup_printf("%s%s%i", if_name[type],

                                     mediastr, unit_id);

        }

        qdict_put(bs_opts, "id", qstring_from_str(new_id));

        g_free(new_id);

    }

    /* Add virtio block device */

    devaddr = qemu_opt_get(legacy_opts, "addr");

    if (devaddr && type != IF_VIRTIO) {

        error_report("addr is not supported by this bus type");

        goto fail;

    }

    if (type == IF_VIRTIO) {

        QemuOpts *devopts;

        devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,

                                   &error_abort);

        if (arch_type == QEMU_ARCH_S390X) {

            qemu_opt_set(devopts, "driver", "virtio-blk-s390");

        } else {

            qemu_opt_set(devopts, "driver", "virtio-blk-pci");

        }

        qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));

        if (devaddr) {

            qemu_opt_set(devopts, "addr", devaddr);

        }

    }

    filename = qemu_opt_get(legacy_opts, "file");

    /* Check werror/rerror compatibility with if=... */

    werror = qemu_opt_get(legacy_opts, "werror");

    if (werror != NULL) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&

            type != IF_NONE) {

            error_report("werror is not supported by this bus type");

            goto fail;

        }

        qdict_put(bs_opts, "werror", qstring_from_str(werror));

    }

    rerror = qemu_opt_get(legacy_opts, "rerror");

    if (rerror != NULL) {

        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&

            type != IF_NONE) {

            error_report("rerror is not supported by this bus type");

            goto fail;

        }

        qdict_put(bs_opts, "rerror", qstring_from_str(rerror));

    }

    /* Actual block device init: Functionality shared with blockdev-add */

    dinfo = blockdev_init(filename, bs_opts, &local_err);

    if (dinfo == NULL) {

        if (local_err) {

            error_report("%s", error_get_pretty(local_err));

            error_free(local_err);

        }

        goto fail;

    } else {

        assert(!local_err);

    }

    /* Set legacy DriveInfo fields */

    dinfo->enable_auto_del = true;

    dinfo->opts = all_opts;

    dinfo->cyls = cyls;

    dinfo->heads = heads;

    dinfo->secs = secs;

    dinfo->trans = translation;

    dinfo->type = type;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->devaddr = devaddr;

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        dinfo->media_cd = media == MEDIA_CDROM;

        break;

    default:

        break;

    }

fail:

    qemu_opts_del(legacy_opts);

    QDECREF(bs_opts);

    return dinfo;

}


static int connect_to_ssh(BDRVSSHState *s, QDict *options,

                          int ssh_flags, int creat_mode, Error **errp)

{

    int r, ret;

    const char *host, *user, *path, *host_key_check;

    int port;

    if (!qdict_haskey(options, "host")) {

        ret = -EINVAL;

        error_setg(errp, "No hostname was specified");

        goto err;

    }

    host = qdict_get_str(options, "host");

    if (qdict_haskey(options, "port")) {

        port = qdict_get_int(options, "port");

    } else {

        port = 22;

    }

    if (!qdict_haskey(options, "path")) {

        ret = -EINVAL;

        error_setg(errp, "No path was specified");

        goto err;

    }

    path = qdict_get_str(options, "path");

    if (qdict_haskey(options, "user")) {

        user = qdict_get_str(options, "user");

    } else {

        user = g_get_user_name();

        if (!user) {

            error_setg_errno(errp, errno, "Can't get user name");

            ret = -errno;

            goto err;

        }

    }

    if (qdict_haskey(options, "host_key_check")) {

        host_key_check = qdict_get_str(options, "host_key_check");

    } else {

        host_key_check = "yes";

    }

    /* Construct the host:port name for inet_connect. */

    g_free(s->hostport);

    s->hostport = g_strdup_printf("%s:%d", host, port);

    /* Open the socket and connect. */

    s->sock = inet_connect(s->hostport, errp);

    if (s->sock < 0) {

        ret = -EIO;

        goto err;

    }

    /* Create SSH session. */

    s->session = libssh2_session_init();

    if (!s->session) {

        ret = -EINVAL;

        session_error_setg(errp, s, "failed to initialize libssh2 session");

        goto err;

    }

#if TRACE_LIBSSH2 != 0

    libssh2_trace(s->session, TRACE_LIBSSH2);

#endif

    r = libssh2_session_handshake(s->session, s->sock);

    if (r != 0) {

        ret = -EINVAL;

        session_error_setg(errp, s, "failed to establish SSH session");

        goto err;

    }

    /* Check the remote host's key against known_hosts. */

    ret = check_host_key(s, host, port, host_key_check, errp);

    if (ret < 0) {

        goto err;

    }

    /* Authenticate. */

    ret = authenticate(s, user, errp);

    if (ret < 0) {

        goto err;

    }

    /* Start SFTP. */

    s->sftp = libssh2_sftp_init(s->session);

    if (!s->sftp) {

        session_error_setg(errp, s, "failed to initialize sftp handle");

        ret = -EINVAL;

        goto err;

    }

    /* Open the remote file. */

    DPRINTF("opening file %s flags=0x%x creat_mode=0%o",

            path, ssh_flags, creat_mode);

    s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode);

    if (!s->sftp_handle) {

        session_error_setg(errp, s, "failed to open remote file '%s'", path);

        ret = -EINVAL;

        goto err;

    }

    r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);

    if (r < 0) {

        sftp_error_setg(errp, s, "failed to read file attributes");

        return -EINVAL;

    }

    /* Delete the options we've used; any not deleted will cause the

     * block layer to give an error about unused options.

     */

    qdict_del(options, "host");

    qdict_del(options, "port");

    qdict_del(options, "user");

    qdict_del(options, "path");

    qdict_del(options, "host_key_check");

    return 0;

 err:

    if (s->sftp_handle) {

        libssh2_sftp_close(s->sftp_handle);

    }

    s->sftp_handle = NULL;

    if (s->sftp) {

        libssh2_sftp_shutdown(s->sftp);

    }

    s->sftp = NULL;

    if (s->session) {

        libssh2_session_disconnect(s->session,

                                   "from qemu ssh client: "

                                   "error opening connection");

        libssh2_session_free(s->session);

    }

    s->session = NULL;

    return ret;

}


void ff_configure_buffers_for_index(AVFormatContext *s, int64_t time_tolerance)

{

    int ist1, ist2;

    int64_t pos_delta = 0;

    //We could use URLProtocol flags here but as many user applications do not use URLProtocols this would be unreliable

    const char *proto = avio_find_protocol_name(s->filename);

    if (!(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))

        return;

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

        AVStream *st1 = s->streams[ist1];

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

            AVStream *st2 = s->streams[ist2];

            int i1, i2;

            if (ist1 == ist2)

                continue;

            for (i1 = i2 = 0; i1 < st1->nb_index_entries; i1++) {

                AVIndexEntry *e1 = &st1->index_entries[i1];

                int64_t e1_pts = av_rescale_q(e1->timestamp, st1->time_base, AV_TIME_BASE_Q);

                for (; i2 < st2->nb_index_entries; i2++) {

                    AVIndexEntry *e2 = &st2->index_entries[i2];

                    int64_t e2_pts = av_rescale_q(e2->timestamp, st2->time_base, AV_TIME_BASE_Q);

                    if (e2_pts - e1_pts < time_tolerance)

                        continue;

                    pos_delta = FFMAX(pos_delta, e1->pos - e2->pos);

                    break;

                }

            }

        }

    }

    pos_delta *= 2;

    /* XXX This could be adjusted depending on protocol*/

    if (s->pb->buffer_size < pos_delta && pos_delta < (1<<24)) {

        av_log(s, AV_LOG_VERBOSE, "Reconfiguring buffers to size %"PRId64"\n", pos_delta);

        ffio_set_buf_size(s->pb, pos_delta);

        s->pb->short_seek_threshold = FFMAX(s->pb->short_seek_threshold, pos_delta/2);

    }

}


int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,

                                              AVFrame *frame,

                                              int *got_frame_ptr,

                                              const AVPacket *avpkt)

{

    AVCodecInternal *avci = avctx->internal;

    int planar, channels;

    int ret = 0;

    *got_frame_ptr = 0;

    if (!avpkt->data && avpkt->size) {

        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");

    }

    if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {

        av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");

    }

    avcodec_get_frame_defaults(frame);

    if (!avctx->refcounted_frames)

        av_frame_unref(&avci->to_free);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {

        uint8_t *side;

        int side_size;

        // copy to ensure we do not change avpkt

        AVPacket tmp = *avpkt;

        int did_split = av_packet_split_side_data(&tmp);

        apply_param_change(avctx, &tmp);

        avctx->pkt = &tmp;

        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)

            ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);

        else {

            ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);

            frame->pkt_dts = avpkt->dts;

        }

        if (ret >= 0 && *got_frame_ptr) {

            add_metadata_from_side_data(avctx, frame);

            avctx->frame_number++;

            av_frame_set_best_effort_timestamp(frame,

                                               guess_correct_pts(avctx,

                                                                 frame->pkt_pts,

                                                                 frame->pkt_dts));

            if (frame->format == AV_SAMPLE_FMT_NONE)

                frame->format = avctx->sample_fmt;

            if (!frame->channel_layout)

                frame->channel_layout = avctx->channel_layout;

            if (!av_frame_get_channels(frame))

                av_frame_set_channels(frame, avctx->channels);

            if (!frame->sample_rate)

                frame->sample_rate = avctx->sample_rate;

        }

        side= av_packet_get_side_data(avctx->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);

        if(side && side_size>=10) {

            avctx->internal->skip_samples = AV_RL32(side);

            av_log(avctx, AV_LOG_DEBUG, "skip %d samples due to side data\n",

                   avctx->internal->skip_samples);

        }

        if (avctx->internal->skip_samples && *got_frame_ptr) {

            if(frame->nb_samples <= avctx->internal->skip_samples){

                *got_frame_ptr = 0;

                avctx->internal->skip_samples -= frame->nb_samples;

                av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",

                       avctx->internal->skip_samples);

            } else {

                av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,

                                frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);

                if(avctx->pkt_timebase.num && avctx->sample_rate) {

                    int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,

                                                   (AVRational){1, avctx->sample_rate},

                                                   avctx->pkt_timebase);

                    if(frame->pkt_pts!=AV_NOPTS_VALUE)

                        frame->pkt_pts += diff_ts;

                    if(frame->pkt_dts!=AV_NOPTS_VALUE)

                        frame->pkt_dts += diff_ts;

                    if (av_frame_get_pkt_duration(frame) >= diff_ts)

                        av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);

                } else {

                    av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");

                }

                av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",

                       avctx->internal->skip_samples, frame->nb_samples);

                frame->nb_samples -= avctx->internal->skip_samples;

                avctx->internal->skip_samples = 0;

            }

        }

        avctx->pkt = NULL;

        if (did_split) {

            ff_packet_free_side_data(&tmp);

            if(ret == tmp.size)

                ret = avpkt->size;

        }

        if (ret >= 0 && *got_frame_ptr) {

            if (!avctx->refcounted_frames) {

                avci->to_free = *frame;

                avci->to_free.extended_data = avci->to_free.data;

                memset(frame->buf, 0, sizeof(frame->buf));

                frame->extended_buf    = NULL;

                frame->nb_extended_buf = 0;

            }

        } else if (frame->data[0])

            av_frame_unref(frame);

    }

    /* many decoders assign whole AVFrames, thus overwriting extended_data;

     * make sure it's set correctly; assume decoders that actually use

     * extended_data are doing it correctly */

    if (*got_frame_ptr) {

        planar   = av_sample_fmt_is_planar(frame->format);

        channels = av_frame_get_channels(frame);

        if (!(planar && channels > AV_NUM_DATA_POINTERS))

            frame->extended_data = frame->data;

    } else {

        frame->extended_data = NULL;

    }

    return ret;

}


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

{

    S390CPU *cpu = S390_CPU(dev);

    S390CPUClass *scc = S390_CPU_GET_CLASS(dev);

    cpu_reset(CPU(cpu));

    scc->parent_realize(dev, errp);

}


static void vp56_decode_mb(VP56Context *s, int row, int col, int is_alpha)

{

    AVFrame *frame_current, *frame_ref;

    VP56mb mb_type;

    VP56Frame ref_frame;

    int b, ab, b_max, plane, off;

    if (s->frames[VP56_FRAME_CURRENT]->key_frame)

        mb_type = VP56_MB_INTRA;

    else

        mb_type = vp56_decode_mv(s, row, col);

    ref_frame = ff_vp56_reference_frame[mb_type];

    s->parse_coeff(s);

    vp56_add_predictors_dc(s, ref_frame);

    frame_current = s->frames[VP56_FRAME_CURRENT];

    frame_ref = s->frames[ref_frame];

    if (mb_type != VP56_MB_INTRA && !frame_ref->data[0])

        return;

    ab = 6*is_alpha;

    b_max = 6 - 2*is_alpha;

    switch (mb_type) {

        case VP56_MB_INTRA:

            for (b=0; b<b_max; b++) {

                plane = ff_vp56_b2p[b+ab];

                s->vp3dsp.idct_put(frame_current->data[plane] + s->block_offset[b],

                                s->stride[plane], s->block_coeff[b]);

            }

            break;

        case VP56_MB_INTER_NOVEC_PF:

        case VP56_MB_INTER_NOVEC_GF:

            for (b=0; b<b_max; b++) {

                plane = ff_vp56_b2p[b+ab];

                off = s->block_offset[b];

                s->hdsp.put_pixels_tab[1][0](frame_current->data[plane] + off,

                                             frame_ref->data[plane] + off,

                                             s->stride[plane], 8);

                s->vp3dsp.idct_add(frame_current->data[plane] + off,

                                s->stride[plane], s->block_coeff[b]);

            }

            break;

        case VP56_MB_INTER_DELTA_PF:

        case VP56_MB_INTER_V1_PF:

        case VP56_MB_INTER_V2_PF:

        case VP56_MB_INTER_DELTA_GF:

        case VP56_MB_INTER_4V:

        case VP56_MB_INTER_V1_GF:

        case VP56_MB_INTER_V2_GF:

            for (b=0; b<b_max; b++) {

                int x_off = b==1 || b==3 ? 8 : 0;

                int y_off = b==2 || b==3 ? 8 : 0;

                plane = ff_vp56_b2p[b+ab];

                vp56_mc(s, b, plane, frame_ref->data[plane], s->stride[plane],

                        16*col+x_off, 16*row+y_off);

                s->vp3dsp.idct_add(frame_current->data[plane] + s->block_offset[b],

                                s->stride[plane], s->block_coeff[b]);

            }

            break;

    }

    if (is_alpha) {

        s->block_coeff[4][0] = 0;

        s->block_coeff[5][0] = 0;

    }

}


static int qemu_rbd_create(const char *filename, QemuOpts *opts, Error **errp)

{

    Error *local_err = NULL;

    int64_t bytes = 0;

    int64_t objsize;

    int obj_order = 0;

    const char *pool, *name, *conf, *clientname, *keypairs;

    const char *secretid;

    rados_t cluster;

    rados_ioctx_t io_ctx;

    QDict *options = NULL;

    int ret = 0;

    secretid = qemu_opt_get(opts, "password-secret");

    /* Read out options */

    bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                     BDRV_SECTOR_SIZE);

    objsize = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE, 0);

    if (objsize) {

        if ((objsize - 1) & objsize) {    /* not a power of 2? */

            error_setg(errp, "obj size needs to be power of 2");

            ret = -EINVAL;

            goto exit;

        }

        if (objsize < 4096) {

            error_setg(errp, "obj size too small");

            ret = -EINVAL;

            goto exit;

        }

        obj_order = ctz32(objsize);

    }

    options = qdict_new();

    qemu_rbd_parse_filename(filename, options, &local_err);

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

        goto exit;

    }

    pool       = qdict_get_try_str(options, "pool");

    conf       = qdict_get_try_str(options, "conf");

    clientname = qdict_get_try_str(options, "user");

    name       = qdict_get_try_str(options, "image");

    keypairs   = qdict_get_try_str(options, "=keyvalue-pairs");

    ret = rados_create(&cluster, clientname);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error initializing");

        goto exit;

    }

    /* try default location when conf=NULL, but ignore failure */

    ret = rados_conf_read_file(cluster, conf);

    if (conf && ret < 0) {

        error_setg_errno(errp, -ret, "error reading conf file %s", conf);

        ret = -EIO;

        goto shutdown;

    }

    ret = qemu_rbd_set_keypairs(cluster, keypairs, errp);

    if (ret < 0) {

        ret = -EIO;

        goto shutdown;

    }

    if (qemu_rbd_set_auth(cluster, secretid, errp) < 0) {

        ret = -EIO;

        goto shutdown;

    }

    ret = rados_connect(cluster);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error connecting");

        goto shutdown;

    }

    ret = rados_ioctx_create(cluster, pool, &io_ctx);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error opening pool %s", pool);

        goto shutdown;

    }

    ret = rbd_create(io_ctx, name, bytes, &obj_order);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error rbd create");

    }

    rados_ioctx_destroy(io_ctx);

shutdown:

    rados_shutdown(cluster);

exit:

    QDECREF(options);

    return ret;

}


void av_force_cpu_flags(int arg){

    if (   (arg & ( AV_CPU_FLAG_3DNOW    |

                    AV_CPU_FLAG_3DNOWEXT |

                    AV_CPU_FLAG_MMXEXT   |

                    AV_CPU_FLAG_SSE      |

                    AV_CPU_FLAG_SSE2     |

                    AV_CPU_FLAG_SSE2SLOW |

                    AV_CPU_FLAG_SSE3     |

                    AV_CPU_FLAG_SSE3SLOW |

                    AV_CPU_FLAG_SSSE3    |

                    AV_CPU_FLAG_SSE4     |

                    AV_CPU_FLAG_SSE42    |

                    AV_CPU_FLAG_AVX      |

                    AV_CPU_FLAG_AVXSLOW  |

                    AV_CPU_FLAG_XOP      |

                    AV_CPU_FLAG_FMA3     |

                    AV_CPU_FLAG_FMA4     |

                    AV_CPU_FLAG_AVX2     ))

        && !(arg & AV_CPU_FLAG_MMX)) {

        av_log(NULL, AV_LOG_WARNING, "MMX implied by specified flags\n");

        arg |= AV_CPU_FLAG_MMX;

    }

    flags   = arg;

    checked = arg != -1;

}


static int select_frame(AVFilterContext *ctx, AVFilterBufferRef *picref)

{

    SelectContext *select = ctx->priv;

    AVFilterLink *inlink = ctx->inputs[0];

    double res;

    if (isnan(select->var_values[VAR_START_PTS]))

        select->var_values[VAR_START_PTS] = TS2D(picref->pts);

    if (isnan(select->var_values[VAR_START_T]))

        select->var_values[VAR_START_T] = TS2D(picref->pts) * av_q2d(inlink->time_base);

    select->var_values[VAR_PTS] = TS2D(picref->pts);

    select->var_values[VAR_T  ] = picref->pts * av_q2d(inlink->time_base);

    select->var_values[VAR_POS] = picref->pos == -1 ? NAN : picref->pos;

    select->var_values[VAR_PREV_PTS] = TS2D(picref ->pts);

    select->var_values[VAR_INTERLACE_TYPE] =

        !picref->video->interlaced     ? INTERLACE_TYPE_P :

        picref->video->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;

    select->var_values[VAR_PICT_TYPE] = picref->video->pict_type;

    res = av_expr_eval(select->expr, select->var_values, NULL);

    av_log(inlink->dst, AV_LOG_DEBUG,

           "n:%d pts:%d t:%f pos:%d interlace_type:%c key:%d pict_type:%c "

           "-> select:%f\n",

           (int)select->var_values[VAR_N],

           (int)select->var_values[VAR_PTS],

           select->var_values[VAR_T],

           (int)select->var_values[VAR_POS],

           select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_P ? 'P' :

           select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_T ? 'T' :

           select->var_values[VAR_INTERLACE_TYPE] == INTERLACE_TYPE_B ? 'B' : '?',

           (int)select->var_values[VAR_KEY],

           av_get_picture_type_char(select->var_values[VAR_PICT_TYPE]),

           res);

    select->var_values[VAR_N] += 1.0;

    if (res) {

        select->var_values[VAR_PREV_SELECTED_N]   = select->var_values[VAR_N];

        select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];

        select->var_values[VAR_PREV_SELECTED_T]   = select->var_values[VAR_T];

        select->var_values[VAR_SELECTED_N] += 1.0;

    }

    return res;

}


static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)

{

    MOVMuxContext *mov = s->priv_data;

    int i;

    mov_write_ftyp_tag(pb,s);

    if (mov->mode == MODE_PSP) {

        int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;

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

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

            if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)

                video_streams_nb++;

            else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)

                audio_streams_nb++;

            else

                other_streams_nb++;

            }

        if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {

            av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");

            return AVERROR(EINVAL);

        }

        mov_write_uuidprof_tag(pb, s);

    }

    return 0;

}


static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,

                                                 uint32_t length,

                                                 Error **errp)

{

    QIOChannel *ioc;

    QIOChannelTLS *tioc;

    struct NBDTLSHandshakeData data = { 0 };

    trace_nbd_negotiate_handle_starttls();

    ioc = client->ioc;

    if (length) {

        if (nbd_drop(ioc, length, errp) < 0) {

            return NULL;

        }

        nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,

                                   errp,

                                   "OPT_STARTTLS should not have length");

        return NULL;

    }

    if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,

                               NBD_OPT_STARTTLS, errp) < 0) {

        return NULL;

    }

    tioc = qio_channel_tls_new_server(ioc,

                                      client->tlscreds,

                                      client->tlsaclname,

                                      errp);

    if (!tioc) {

        return NULL;

    }

    qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");

    trace_nbd_negotiate_handle_starttls_handshake();

    data.loop = g_main_loop_new(g_main_context_default(), FALSE);

    qio_channel_tls_handshake(tioc,

                              nbd_tls_handshake,

                              &data,

                              NULL);

    if (!data.complete) {

        g_main_loop_run(data.loop);

    }

    g_main_loop_unref(data.loop);

    if (data.error) {

        object_unref(OBJECT(tioc));

        error_propagate(errp, data.error);

        return NULL;

    }

    return QIO_CHANNEL(tioc);

}


static void vnc_write_u32(VncState *vs, uint32_t value)

{

    uint8_t buf[4];

    buf[0] = (value >> 24) & 0xFF;

    buf[1] = (value >> 16) & 0xFF;

    buf[2] = (value >>  8) & 0xFF;

    buf[3] = value & 0xFF;

    vnc_write(vs, buf, 4);

}


static int tcg_cpu_exec(CPUState *cpu)

{

    int ret;

#ifdef CONFIG_PROFILER

    int64_t ti;

#endif

#ifdef CONFIG_PROFILER

    ti = profile_getclock();

#endif

    if (use_icount) {

        int64_t count;

        int64_t deadline;

        int decr;

        timers_state.qemu_icount -= (cpu->icount_decr.u16.low

                                    + cpu->icount_extra);

        cpu->icount_decr.u16.low = 0;

        cpu->icount_extra = 0;

        deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

        /* Maintain prior (possibly buggy) behaviour where if no deadline

         * was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than

         * INT32_MAX nanoseconds ahead, we still use INT32_MAX

         * nanoseconds.

         */

        if ((deadline < 0) || (deadline > INT32_MAX)) {

            deadline = INT32_MAX;

        }

        count = qemu_icount_round(deadline);

        timers_state.qemu_icount += count;

        decr = (count > 0xffff) ? 0xffff : count;

        count -= decr;

        cpu->icount_decr.u16.low = decr;

        cpu->icount_extra = count;

    }

    ret = cpu_exec(cpu);

#ifdef CONFIG_PROFILER

    tcg_time += profile_getclock() - ti;

#endif

    if (use_icount) {

        /* Fold pending instructions back into the

           instruction counter, and clear the interrupt flag.  */

        timers_state.qemu_icount -= (cpu->icount_decr.u16.low

                        + cpu->icount_extra);

        cpu->icount_decr.u32 = 0;

        cpu->icount_extra = 0;

    }

    return ret;

}