static int dxv_decompress_dxt1(AVCodecContext *avctx)

{

    DXVContext *ctx = avctx->priv_data;

    GetByteContext *gbc = &ctx->gbc;

    uint32_t value, prev, op;

    int idx = 0, state = 0;

    int pos = 2;

    /* Copy the first two elements */

    AV_WL32(ctx->tex_data, bytestream2_get_le32(gbc));

    AV_WL32(ctx->tex_data + 4, bytestream2_get_le32(gbc));

    /* Process input until the whole texture has been filled */

    while (pos < ctx->tex_size / 4) {

        CHECKPOINT(2);

        /* Copy two elements from a previous offset or from the input buffer */

        if (op) {

            prev = AV_RL32(ctx->tex_data + 4 * (pos - idx));

            AV_WL32(ctx->tex_data + 4 * pos, prev);

            pos++;

            prev = AV_RL32(ctx->tex_data + 4 * (pos - idx));

            AV_WL32(ctx->tex_data + 4 * pos, prev);

            pos++;

        } else {

            CHECKPOINT(2);

            if (op)

                prev = AV_RL32(ctx->tex_data + 4 * (pos - idx));

            else

                prev = bytestream2_get_le32(gbc);

            AV_WL32(ctx->tex_data + 4 * pos, prev);

            pos++;

            CHECKPOINT(2);

            if (op)

                prev = AV_RL32(ctx->tex_data + 4 * (pos - idx));

            else

                prev = bytestream2_get_le32(gbc);

            AV_WL32(ctx->tex_data + 4 * pos, prev);

            pos++;

        }

    }

    return 0;

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *data_size,

                        AVPacket *avpkt)

{

    JvContext *s           = avctx->priv_data;

    const uint8_t *buf     = avpkt->data;

    const uint8_t *buf_end = buf + avpkt->size;

    int video_size, video_type, i, j;

    video_size = AV_RL32(buf);

    video_type = buf[4];

    buf += 5;

    if (video_size) {

        if (video_size < 0 || video_size > avpkt->size - 5) {

            av_log(avctx, AV_LOG_ERROR, "video size %d invalid\n", video_size);

            return AVERROR_INVALIDDATA;

        }

        if (avctx->reget_buffer(avctx, &s->frame) < 0) {

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

            return -1;

        }

        if (video_type == 0 || video_type == 1) {

            GetBitContext gb;

            init_get_bits(&gb, buf, 8 * video_size);

            for (j = 0; j < avctx->height; j += 8)

                for (i = 0; i < avctx->width; i += 8)

                    decode8x8(&gb, s->frame.data[0] + j*s->frame.linesize[0] + i,

                              s->frame.linesize[0], &s->dsp);

            buf += video_size;

        } else if (video_type == 2) {

            if (buf + 1 <= buf_end) {

                int v = *buf++;

                for (j = 0; j < avctx->height; j++)

                    memset(s->frame.data[0] + j*s->frame.linesize[0], v, avctx->width);

            }

        } else {

            av_log(avctx, AV_LOG_WARNING, "unsupported frame type %i\n", video_type);

            return AVERROR_INVALIDDATA;

        }

    }

    if (buf_end - buf >= AVPALETTE_COUNT * 3) {

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

            uint32_t pal = AV_RB24(buf);

            s->palette[i] = 0xFF << 24 | pal << 2 | ((pal >> 4) & 0x30303);

            buf += 3;

        }

        s->palette_has_changed = 1;

    }

    if (video_size) {

        s->frame.key_frame           = 1;

        s->frame.pict_type           = AV_PICTURE_TYPE_I;

        s->frame.palette_has_changed = s->palette_has_changed;

        s->palette_has_changed       = 0;

        memcpy(s->frame.data[1], s->palette, AVPALETTE_SIZE);

        *data_size      = sizeof(AVFrame);

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

    }

    return avpkt->size;

}


static av_cold int asv_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static void megasas_reset_frames(MegasasState *s)

{

    PCIDevice *pcid = PCI_DEVICE(s);

    int i;

    MegasasCmd *cmd;

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

        cmd = &s->frames[i];

        if (cmd->pa) {

            pci_dma_unmap(pcid, cmd->frame, cmd->pa_size, 0, 0);

            cmd->frame = NULL;

            cmd->pa = 0;

        }

    }

}


void aio_set_fd_handler(AioContext *ctx,

                        int fd,

                        bool is_external,

                        IOHandler *io_read,

                        IOHandler *io_write,

                        void *opaque)

{

    AioHandler *node;

    bool is_new = false;

    node = find_aio_handler(ctx, fd);

    /* Are we deleting the fd handler? */

    if (!io_read && !io_write) {

        if (node) {

            g_source_remove_poll(&ctx->source, &node->pfd);

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

            if (ctx->walking_handlers) {

                node->deleted = 1;

                node->pfd.revents = 0;

            } else {

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

                 * deleted because deleted nodes are only cleaned up after

                 * releasing the walking_handlers lock.

                 */

                QLIST_REMOVE(node, node);

                g_free(node);

            }

        }

    } else {

        if (node == NULL) {

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

            node = g_new0(AioHandler, 1);

            node->pfd.fd = fd;

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

            g_source_add_poll(&ctx->source, &node->pfd);

            is_new = true;

        }

        /* Update handler with latest information */

        node->io_read = io_read;

        node->io_write = io_write;

        node->opaque = opaque;

        node->is_external = is_external;

        node->pfd.events = (io_read ? G_IO_IN | G_IO_HUP | G_IO_ERR : 0);

        node->pfd.events |= (io_write ? G_IO_OUT | G_IO_ERR : 0);

    }

    aio_epoll_update(ctx, node, is_new);

    aio_notify(ctx);

}


unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)

{

    size_t pos = hbi->pos;

    const HBitmap *hb = hbi->hb;

    unsigned i = HBITMAP_LEVELS - 1;

    unsigned long cur;

    do {

        cur = hbi->cur[--i];

        pos >>= BITS_PER_LEVEL;

    } while (cur == 0);

    /* Check for end of iteration.  We always use fewer than BITS_PER_LONG

     * bits in the level 0 bitmap; thus we can repurpose the most significant

     * bit as a sentinel.  The sentinel is set in hbitmap_alloc and ensures

     * that the above loop ends even without an explicit check on i.

     */

    if (i == 0 && cur == (1UL << (BITS_PER_LONG - 1))) {

        return 0;

    }

    for (; i < HBITMAP_LEVELS - 1; i++) {

        /* Shift back pos to the left, matching the right shifts above.

         * The index of this word's least significant set bit provides

         * the low-order bits.

         */

        pos = (pos << BITS_PER_LEVEL) + ffsl(cur) - 1;

        hbi->cur[i] = cur & (cur - 1);

        /* Set up next level for iteration.  */

        cur = hb->levels[i + 1][pos];

    }

    hbi->pos = pos;

    trace_hbitmap_iter_skip_words(hbi->hb, hbi, pos, cur);

    assert(cur);

    return cur;

}


static int intel_hda_exit(PCIDevice *pci)

{

    IntelHDAState *d = DO_UPCAST(IntelHDAState, pci, pci);

    if (d->msi) {

        msi_uninit(&d->pci);

    }

    cpu_unregister_io_memory(d->mmio_addr);

    return 0;

}


static int compand_nodelay(AVFilterContext *ctx, AVFrame *frame)

{

    CompandContext *s = ctx->priv;

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

    const int channels = inlink->channels;

    const int nb_samples = frame->nb_samples;

    AVFrame *out_frame;

    int chan, i;

    if (av_frame_is_writable(frame)) {

        out_frame = frame;

    } else {

        out_frame = ff_get_audio_buffer(inlink, nb_samples);

        if (!out_frame)

            return AVERROR(ENOMEM);

        av_frame_copy_props(out_frame, frame);

    }

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

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

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

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

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

            update_volume(cp, fabs(src[i]));

            dst[i] = av_clipd(src[i] * get_volume(s, cp->volume), -1, 1);

        }

    }

    if (frame != out_frame)

        av_frame_free(&frame);

    return ff_filter_frame(ctx->outputs[0], out_frame);

}


static void pfpu_start(MilkymistPFPUState *s)

{

    int x, y;

    int i;

    for (y = 0; y <= s->regs[R_VMESHLAST]; y++) {

        for (x = 0; x <= s->regs[R_HMESHLAST]; x++) {

            D_EXEC(qemu_log("\nprocessing x=%d y=%d\n", x, y));

            /* set current position */

            s->gp_regs[GPR_X] = x;

            s->gp_regs[GPR_Y] = y;

            /* run microcode on this position */

            i = 0;

            while (pfpu_decode_insn(s)) {

                /* decode at most MICROCODE_WORDS instructions */

                if (i++ >= MICROCODE_WORDS) {

                    error_report("milkymist_pfpu: too many instructions "

                            "executed in microcode. No VECTOUT?");

                    break;

                }

            }

            /* reset pc for next run */

            s->regs[R_PC] = 0;

        }

    }

    s->regs[R_VERTICES] = x * y;

    trace_milkymist_pfpu_pulse_irq();

    qemu_irq_pulse(s->irq);

}


av_cold void ff_vp9dsp_init(VP9DSPContext *dsp, int bpp)

{

    if (bpp == 8) {

        ff_vp9dsp_init_8(dsp);

    } else if (bpp == 10) {

        ff_vp9dsp_init_10(dsp);

    } else {

        av_assert0(bpp == 12);

        ff_vp9dsp_init_12(dsp);

    }

    if (ARCH_X86) ff_vp9dsp_init_x86(dsp, bpp);

    if (ARCH_MIPS) ff_vp9dsp_init_mips(dsp, bpp);

}


static int mov_read_mdhd(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    print_atom("mdhd", atom);

    get_byte(pb); /* version */

    get_byte(pb); get_byte(pb);

    get_byte(pb); /* flags */

    get_be32(pb); /* creation time */

    get_be32(pb); /* modification time */

    c->streams[c->total_streams]->time_scale = get_be32(pb);

#ifdef DEBUG

    printf("track[%i].time_scale = %i\n", c->fc->nb_streams-1, c->streams[c->total_streams]->time_scale); /* time scale */

#endif

    get_be32(pb); /* duration */

    get_be16(pb); /* language */

    get_be16(pb); /* quality */

    return 0;

}


static int svq1_encode_plane(SVQ1Context *s, int plane, unsigned char *src_plane, unsigned char *ref_plane, unsigned char *decoded_plane,

    int width, int height, int src_stride, int stride)

{

    int x, y;

    int i;

    int block_width, block_height;

    int level;

    int threshold[6];

    const int lambda= (s->picture.quality*s->picture.quality) >> (2*FF_LAMBDA_SHIFT);

    /* figure out the acceptable level thresholds in advance */

    threshold[5] = QUALITY_THRESHOLD;

    for (level = 4; level >= 0; level--)

        threshold[level] = threshold[level + 1] * THRESHOLD_MULTIPLIER;

    block_width = (width + 15) / 16;

    block_height = (height + 15) / 16;

    if(s->picture.pict_type == FF_P_TYPE){

        s->m.avctx= s->avctx;

        s->m.current_picture_ptr= &s->m.current_picture;

        s->m.last_picture_ptr   = &s->m.last_picture;

        s->m.last_picture.data[0]= ref_plane;

        s->m.linesize=

        s->m.last_picture.linesize[0]=

        s->m.new_picture.linesize[0]=

        s->m.current_picture.linesize[0]= stride;

        s->m.width= width;

        s->m.height= height;

        s->m.mb_width= block_width;

        s->m.mb_height= block_height;

        s->m.mb_stride= s->m.mb_width+1;

        s->m.b8_stride= 2*s->m.mb_width+1;

        s->m.f_code=1;

        s->m.pict_type= s->picture.pict_type;

        s->m.me_method= s->avctx->me_method;

        s->m.me.scene_change_score=0;

        s->m.flags= s->avctx->flags;

//        s->m.out_format = FMT_H263;

//        s->m.unrestricted_mv= 1;

        s->m.lambda= s->picture.quality;

        s->m.qscale= (s->m.lambda*139 + FF_LAMBDA_SCALE*64) >> (FF_LAMBDA_SHIFT + 7);

        s->m.lambda2= (s->m.lambda*s->m.lambda + FF_LAMBDA_SCALE/2) >> FF_LAMBDA_SHIFT;

        if(!s->motion_val8[plane]){

            s->motion_val8 [plane]= av_mallocz((s->m.b8_stride*block_height*2 + 2)*2*sizeof(int16_t));

            s->motion_val16[plane]= av_mallocz((s->m.mb_stride*(block_height + 2) + 1)*2*sizeof(int16_t));

        }

        s->m.mb_type= s->mb_type;

        //dummies, to avoid segfaults

        s->m.current_picture.mb_mean=   (uint8_t *)s->dummy;

        s->m.current_picture.mb_var=    (uint16_t*)s->dummy;

        s->m.current_picture.mc_mb_var= (uint16_t*)s->dummy;

        s->m.current_picture.mb_type= s->dummy;

        s->m.current_picture.motion_val[0]= s->motion_val8[plane] + 2;

        s->m.p_mv_table= s->motion_val16[plane] + s->m.mb_stride + 1;

        s->m.dsp= s->dsp; //move

        ff_init_me(&s->m);

        s->m.me.dia_size= s->avctx->dia_size;

        s->m.first_slice_line=1;

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

            uint8_t src[stride*16];

            s->m.new_picture.data[0]= src - y*16*stride; //ugly

            s->m.mb_y= y;

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

                memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);

                for(x=width; x<16*block_width; x++)

                    src[i*stride+x]= src[i*stride+x-1];

            }

            for(; i<16 && i + 16*y<16*block_height; i++)

                memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);

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

                s->m.mb_x= x;

                ff_init_block_index(&s->m);

                ff_update_block_index(&s->m);

                ff_estimate_p_frame_motion(&s->m, x, y);

            }

            s->m.first_slice_line=0;

        }

        ff_fix_long_p_mvs(&s->m);

        ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code, CANDIDATE_MB_TYPE_INTER, 0);

    }

    s->m.first_slice_line=1;

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

        uint8_t src[stride*16];

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

            memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);

            for(x=width; x<16*block_width; x++)

                src[i*stride+x]= src[i*stride+x-1];

        }

        for(; i<16 && i + 16*y<16*block_height; i++)

            memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);

        s->m.mb_y= y;

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

            uint8_t reorder_buffer[3][6][7*32];

            int count[3][6];

            int offset = y * 16 * stride + x * 16;

            uint8_t *decoded= decoded_plane + offset;

            uint8_t *ref= ref_plane + offset;

            int score[4]={0,0,0,0}, best;

            uint8_t *temp = s->scratchbuf;

            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < 3000){ //FIXME check size

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

                return -1;

            }

            s->m.mb_x= x;

            ff_init_block_index(&s->m);

            ff_update_block_index(&s->m);

            if(s->picture.pict_type == FF_I_TYPE || (s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTRA)){

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

                    init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i], 7*32);

                }

                if(s->picture.pict_type == FF_P_TYPE){

                    const uint8_t *vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_INTRA];

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    score[0]= vlc[1]*lambda;

                }

                score[0]+= encode_block(s, src+16*x, NULL, temp, stride, 5, 64, lambda, 1);

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

                    count[0][i]= put_bits_count(&s->reorder_pb[i]);

                    flush_put_bits(&s->reorder_pb[i]);

                }

            }else

                score[0]= INT_MAX;

            best=0;

            if(s->picture.pict_type == FF_P_TYPE){

                const uint8_t *vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_INTER];

                int mx, my, pred_x, pred_y, dxy;

                int16_t *motion_ptr;

                motion_ptr= h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);

                if(s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTER){

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

                        init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i], 7*32);

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    s->m.pb= s->reorder_pb[5];

                    mx= motion_ptr[0];

                    my= motion_ptr[1];

                    assert(mx>=-32 && mx<=31);

                    assert(my>=-32 && my<=31);

                    assert(pred_x>=-32 && pred_x<=31);

                    assert(pred_y>=-32 && pred_y<=31);

                    ff_h263_encode_motion(&s->m, mx - pred_x, 1);

                    ff_h263_encode_motion(&s->m, my - pred_y, 1);

                    s->reorder_pb[5]= s->m.pb;

                    score[1] += lambda*put_bits_count(&s->reorder_pb[5]);

                    dxy= (mx&1) + 2*(my&1);

                    s->dsp.put_pixels_tab[0][dxy](temp+16, ref + (mx>>1) + stride*(my>>1), stride, 16);

                    score[1]+= encode_block(s, src+16*x, temp+16, decoded, stride, 5, 64, lambda, 0);

                    best= score[1] <= score[0];

                    vlc= ff_svq1_block_type_vlc[SVQ1_BLOCK_SKIP];

                    score[2]= s->dsp.sse[0](NULL, src+16*x, ref, stride, 16);

                    score[2]+= vlc[1]*lambda;

                    if(score[2] < score[best] && mx==0 && my==0){

                        best=2;

                        s->dsp.put_pixels_tab[0][0](decoded, ref, stride, 16);

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

                            count[2][i]=0;

                        }

                        put_bits(&s->pb, vlc[1], vlc[0]);

                    }

                }

                if(best==1){

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

                        count[1][i]= put_bits_count(&s->reorder_pb[i]);

                        flush_put_bits(&s->reorder_pb[i]);

                    }

                }else{

                    motion_ptr[0                 ] = motion_ptr[1                 ]=

                    motion_ptr[2                 ] = motion_ptr[3                 ]=

                    motion_ptr[0+2*s->m.b8_stride] = motion_ptr[1+2*s->m.b8_stride]=

                    motion_ptr[2+2*s->m.b8_stride] = motion_ptr[3+2*s->m.b8_stride]=0;

                }

            }

            s->rd_total += score[best];

            for(i=5; i>=0; i--){

                ff_copy_bits(&s->pb, reorder_buffer[best][i], count[best][i]);

            }

            if(best==0){

                s->dsp.put_pixels_tab[0][0](decoded, temp, stride, 16);

            }

        }

        s->m.first_slice_line=0;

    }

    return 0;

}


static int commit_direntries(BDRVVVFATState* s,

	int dir_index, int parent_mapping_index)

{

    direntry_t* direntry = array_get(&(s->directory), dir_index);

    uint32_t first_cluster = dir_index == 0 ? 0 : begin_of_direntry(direntry);

    mapping_t* mapping = find_mapping_for_cluster(s, first_cluster);

    int factor = 0x10 * s->sectors_per_cluster;

    int old_cluster_count, new_cluster_count;

    int current_dir_index = mapping->info.dir.first_dir_index;

    int first_dir_index = current_dir_index;

    int ret, i;

    uint32_t c;

DLOG(fprintf(stderr, "commit_direntries for %s, parent_mapping_index %d\n", mapping->path, parent_mapping_index));

    assert(direntry);

    assert(mapping);

    assert(mapping->begin == first_cluster);

    assert(mapping->info.dir.first_dir_index < s->directory.next);

    assert(mapping->mode & MODE_DIRECTORY);

    assert(dir_index == 0 || is_directory(direntry));

    mapping->info.dir.parent_mapping_index = parent_mapping_index;

    if (first_cluster == 0) {

	old_cluster_count = new_cluster_count =

	    s->last_cluster_of_root_directory;

    } else {

	for (old_cluster_count = 0, c = first_cluster; !fat_eof(s, c);

		c = fat_get(s, c))

	    old_cluster_count++;

	for (new_cluster_count = 0, c = first_cluster; !fat_eof(s, c);

		c = modified_fat_get(s, c))

	    new_cluster_count++;

    }

    if (new_cluster_count > old_cluster_count) {

	if (insert_direntries(s,

		current_dir_index + factor * old_cluster_count,

		factor * (new_cluster_count - old_cluster_count)) == NULL)

	    return -1;

    } else if (new_cluster_count < old_cluster_count)

	remove_direntries(s,

		current_dir_index + factor * new_cluster_count,

		factor * (old_cluster_count - new_cluster_count));

    for (c = first_cluster; !fat_eof(s, c); c = modified_fat_get(s, c)) {

	void* direntry = array_get(&(s->directory), current_dir_index);

	int ret = vvfat_read(s->bs, cluster2sector(s, c), direntry,

		s->sectors_per_cluster);

	if (ret)

	    return ret;

	assert(!strncmp(s->directory.pointer, "QEMU", 4));

	current_dir_index += factor;

    }

    ret = commit_mappings(s, first_cluster, dir_index);

    if (ret)

	return ret;

    /* recurse */

    for (i = 0; i < factor * new_cluster_count; i++) {

	direntry = array_get(&(s->directory), first_dir_index + i);

	if (is_directory(direntry) && !is_dot(direntry)) {

	    mapping = find_mapping_for_cluster(s, first_cluster);

	    assert(mapping->mode & MODE_DIRECTORY);

	    ret = commit_direntries(s, first_dir_index + i,

		array_index(&(s->mapping), mapping));

	    if (ret)

		return ret;

	}

    }

    return 0;

}


void vfio_put_group(VFIOGroup *group)

{

    if (!QLIST_EMPTY(&group->device_list)) {

        return;

    }

    vfio_kvm_device_del_group(group);

    vfio_disconnect_container(group);

    QLIST_REMOVE(group, next);

    trace_vfio_put_group(group->fd);

    close(group->fd);

    g_free(group);

    if (QLIST_EMPTY(&vfio_group_list)) {

        qemu_unregister_reset(vfio_reset_handler, NULL);

    }

}


void qemu_chr_info(Monitor *mon)

{

    CharDriverState *chr;

    TAILQ_FOREACH(chr, &chardevs, next) {

        monitor_printf(mon, "%s: filename=%s\n", chr->label, chr->filename);

    }

}


void lm32_debug_excp_handler(CPUState *cs)

{

    LM32CPU *cpu = LM32_CPU(cs);

    CPULM32State *env = &cpu->env;

    CPUBreakpoint *bp;

    if (cs->watchpoint_hit) {

        if (cs->watchpoint_hit->flags & BP_CPU) {

            cs->watchpoint_hit = NULL;

            if (check_watchpoints(env)) {

                raise_exception(env, EXCP_WATCHPOINT);

            } else {

                cpu_resume_from_signal(cs, NULL);

            }

        }

    } else {

        QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

            if (bp->pc == env->pc) {

                if (bp->flags & BP_CPU) {

                    raise_exception(env, EXCP_BREAKPOINT);

                }

                break;

            }

        }

    }

}


int qemu_get_byte(QEMUFile *f)

{

    if (f->is_write)

        abort();

    if (f->buf_index >= f->buf_size) {

        qemu_fill_buffer(f);

        if (f->buf_index >= f->buf_size)

            return 0;

    }

    return f->buf[f->buf_index++];

}


static void parse_error(JSONParserContext *ctxt, QObject *token, const char *msg, ...)

{

    fprintf(stderr, "parse error: %s\n", msg);

}


void gtod_save(QEMUFile *f, void *opaque)

{

    uint64_t tod_low;

    uint8_t tod_high;

    int r;

    r = s390_get_clock(&tod_high, &tod_low);

    if (r) {

        fprintf(stderr, "WARNING: Unable to get guest clock for migration. "

                        "Error code %d. Guest clock will not be migrated "

                        "which could cause the guest to hang.\n", r);

        qemu_put_byte(f, S390_TOD_CLOCK_VALUE_MISSING);

        return;

    }

    qemu_put_byte(f, S390_TOD_CLOCK_VALUE_PRESENT);

    qemu_put_byte(f, tod_high);

    qemu_put_be64(f, tod_low);

}


void kvm_arch_update_guest_debug(CPUState *env, struct kvm_guest_debug *dbg)

{

    const uint8_t type_code[] = {

        [GDB_BREAKPOINT_HW] = 0x0,

        [GDB_WATCHPOINT_WRITE] = 0x1,

        [GDB_WATCHPOINT_ACCESS] = 0x3

    };

    const uint8_t len_code[] = {

        [1] = 0x0, [2] = 0x1, [4] = 0x3, [8] = 0x2

    };

    int n;

    if (kvm_sw_breakpoints_active(env))

        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP;

    if (nb_hw_breakpoint > 0) {

        dbg->control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;

        dbg->arch.debugreg[7] = 0x0600;

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

            dbg->arch.debugreg[n] = hw_breakpoint[n].addr;

            dbg->arch.debugreg[7] |= (2 << (n * 2)) |

                (type_code[hw_breakpoint[n].type] << (16 + n*4)) |

                ((uint32_t)len_code[hw_breakpoint[n].len] << (18 + n*4));

        }

    }

    /* Legal xcr0 for loading */

    env->xcr0 = 1;

}


SocketAddress *socket_local_address(int fd, Error **errp)

{

    struct sockaddr_storage ss;

    socklen_t sslen = sizeof(ss);

    if (getsockname(fd, (struct sockaddr *)&ss, &sslen) < 0) {

        error_setg_errno(errp, errno, "%s",

                         "Unable to query local socket address");

        return NULL;

    }

    return socket_sockaddr_to_address(&ss, sslen, errp);

}


static void eeprom_generate(eeprom24c0x_t *eeprom, ram_addr_t ram_size)

{

    enum { SDR = 0x4, DDR2 = 0x8 } type;

    uint8_t *spd = eeprom->contents;

    uint8_t nbanks = 0;

    uint16_t density = 0;

    int i;

    /* work in terms of MB */

    ram_size >>= 20;

    while ((ram_size >= 4) && (nbanks <= 2)) {

        int sz_log2 = MIN(31 - clz32(ram_size), 14);

        nbanks++;

        density |= 1 << (sz_log2 - 2);

        ram_size -= 1 << sz_log2;

    }

    /* split to 2 banks if possible */

    if ((nbanks == 1) && (density > 1)) {

        nbanks++;

        density >>= 1;

    }

    if (density & 0xff00) {

        density = (density & 0xe0) | ((density >> 8) & 0x1f);

        type = DDR2;

    } else if (!(density & 0x1f)) {

        type = DDR2;

    } else {

        type = SDR;

    }

    if (ram_size) {

        fprintf(stderr, "Warning: SPD cannot represent final %dMB"

                " of SDRAM\n", (int)ram_size);

    }

    /* fill in SPD memory information */

    spd[2] = type;

    spd[5] = nbanks;

    spd[31] = density;

    /* checksum */

    spd[63] = 0;

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

        spd[63] += spd[i];

    }

}


static int virtio_blk_init_pci(PCIDevice *pci_dev)

{

    VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);

    VirtIODevice *vdev;

    if (proxy->class_code != PCI_CLASS_STORAGE_SCSI &&

        proxy->class_code != PCI_CLASS_STORAGE_OTHER)

        proxy->class_code = PCI_CLASS_STORAGE_SCSI;

    if (!proxy->block.dinfo) {

        error_report("virtio-blk-pci: drive property not set");

        return -1;

    }

    vdev = virtio_blk_init(&pci_dev->qdev, &proxy->block);

    vdev->nvectors = proxy->nvectors;

    virtio_init_pci(proxy, vdev,

                    PCI_VENDOR_ID_REDHAT_QUMRANET,

                    PCI_DEVICE_ID_VIRTIO_BLOCK,

                    proxy->class_code, 0x00);

    /* make the actual value visible */

    proxy->nvectors = vdev->nvectors;

    return 0;

}


void s390_io_interrupt(S390CPU *cpu, uint16_t subchannel_id,

                       uint16_t subchannel_nr, uint32_t io_int_parm,

                       uint32_t io_int_word)

{

    if (kvm_enabled()) {

        kvm_s390_io_interrupt(cpu, subchannel_id, subchannel_nr, io_int_parm,

                              io_int_word);

    } else {

        cpu_inject_io(cpu, subchannel_id, subchannel_nr, io_int_parm,

                      io_int_word);

    }

}


static void pci_bridge_region_del(PCIBridge *br, PCIBridgeWindows *w)

{

    PCIDevice *pd = PCI_DEVICE(br);

    PCIBus *parent = pd->bus;

    memory_region_del_subregion(parent->address_space_io, &w->alias_io);

    memory_region_del_subregion(parent->address_space_mem, &w->alias_mem);

    memory_region_del_subregion(parent->address_space_mem, &w->alias_pref_mem);

    pci_unregister_vga(pd);

}


void bt_l2cap_psm_register(struct bt_l2cap_device_s *dev, int psm, int min_mtu,

                int (*new_channel)(struct bt_l2cap_device_s *dev,

                        struct bt_l2cap_conn_params_s *params))

{

    struct bt_l2cap_psm_s *new_psm = l2cap_psm(dev, psm);

    if (new_psm) {

        fprintf(stderr, "%s: PSM %04x already registered for device `%s'.\n",

                        __FUNCTION__, psm, dev->device.lmp_name);

        exit(-1);

    }

    new_psm = g_malloc0(sizeof(*new_psm));

    new_psm->psm = psm;

    new_psm->min_mtu = min_mtu;

    new_psm->new_channel = new_channel;

    new_psm->next = dev->first_psm;

    dev->first_psm = new_psm;

}


static int check_pow_970 (CPUPPCState *env)

{

    if (env->spr[SPR_HID0] & 0x00600000)

        return 1;

    return 0;

}


void do_info_usernet(Monitor *mon)

{

    SlirpState *s;

    TAILQ_FOREACH(s, &slirp_stacks, entry) {

        monitor_printf(mon, "VLAN %d (%s):\n", s->vc->vlan->id, s->vc->name);

        slirp_connection_info(s->slirp, mon);

    }

}


static inline void RENAME(rgb16to32)(const uint8_t *src, uint8_t *dst, long src_size)

{

    const uint16_t *end;

#if COMPILE_TEMPLATE_MMX

    const uint16_t *mm_end;

#endif

    uint8_t *d = dst;

    const uint16_t *s = (const uint16_t*)src;

    end = s + src_size/2;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(PREFETCH"    %0"::"m"(*s):"memory");

    __asm__ volatile("pxor    %%mm7,%%mm7    \n\t":::"memory");

    __asm__ volatile("pcmpeqd %%mm6,%%mm6    \n\t":::"memory");

    mm_end = end - 3;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

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

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

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

            "pand          %2, %%mm0    \n\t"

            "pand          %3, %%mm1    \n\t"

            "pand          %4, %%mm2    \n\t"

            "psllq         $3, %%mm0    \n\t"

            "psrlq         $3, %%mm1    \n\t"

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

            PACK_RGB32

            :"=m"(*d)

            :"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r)

            :"memory");

        d += 16;

        s += 4;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

#endif

    while (s < end) {

        register uint16_t bgr;

        bgr = *s++;

#if HAVE_BIGENDIAN

        *d++ = 255;

        *d++ = (bgr&0xF800)>>8;

        *d++ = (bgr&0x7E0)>>3;

        *d++ = (bgr&0x1F)<<3;

#else

        *d++ = (bgr&0x1F)<<3;

        *d++ = (bgr&0x7E0)>>3;

        *d++ = (bgr&0xF800)>>8;

        *d++ = 255;

#endif

    }

}


int ff_xvmc_field_start(MpegEncContext*s, AVCodecContext *avctx)

{

    struct xvmc_pixfmt_render *last, *next, *render = (struct xvmc_pixfmt_render*)s->current_picture.data[2];

    const int mb_block_count = 4 + (1 << s->chroma_format);

    assert(avctx);

    if (!render || render->magic_id != AV_XVMC_RENDER_MAGIC ||

        !render->data_blocks || !render->mv_blocks){

        av_log(avctx, AV_LOG_ERROR,

               "Render token doesn't look as expected.\n");

        return -1; // make sure that this is a render packet

    }

    render->picture_structure = s->picture_structure;

    render->flags             = s->first_field ? 0 : XVMC_SECOND_FIELD;

    if (render->filled_mv_blocks_num) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface contains %i unprocessed blocks.\n",

               render->filled_mv_blocks_num);

        return -1;

    }

    if (render->total_number_of_mv_blocks   < 1 ||

        render->total_number_of_data_blocks < mb_block_count) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface doesn't provide enough block structures to work with.\n");

        return -1;

    }

    if (render->total_number_of_mv_blocks   < 1 ||

        render->total_number_of_data_blocks < mb_block_count) {

        av_log(avctx, AV_LOG_ERROR,

               "Rendering surface doesn't provide enough block structures to work with.\n");

        return -1;

    }

    render->p_future_surface = NULL;

    render->p_past_surface   = NULL;

    switch(s->pict_type) {

        case  FF_I_TYPE:

            return 0; // no prediction from other frames

        case  FF_B_TYPE:

            next = (struct xvmc_pixfmt_render*)s->next_picture.data[2];

            if (!next)

                return -1;

            if (next->magic_id != AV_XVMC_RENDER_MAGIC)

                return -1;

            render->p_future_surface = next->p_surface;

            // no return here, going to set forward prediction

        case  FF_P_TYPE:

            last = (struct xvmc_pixfmt_render*)s->last_picture.data[2];

            if (!last)

                last = render; // predict second field from the first

            if (last->magic_id != AV_XVMC_RENDER_MAGIC)

                return -1;

            render->p_past_surface = last->p_surface;

            return 0;

    }

return -1;

}


int64_t url_fseek(ByteIOContext *s, int64_t offset, int whence)

{

    int64_t offset1;

    int64_t pos;

    int force = whence & AVSEEK_FORCE;

    whence &= ~AVSEEK_FORCE;

    if(!s)

        return AVERROR(EINVAL);

    pos = s->pos - (s->write_flag ? 0 : (s->buf_end - s->buffer));

    if (whence != SEEK_CUR && whence != SEEK_SET)

        return AVERROR(EINVAL);

    if (whence == SEEK_CUR) {

        offset1 = pos + (s->buf_ptr - s->buffer);

        if (offset == 0)

            return offset1;

        offset += offset1;

    }

    offset1 = offset - pos;

    if (!s->must_flush &&

        offset1 >= 0 && offset1 <= (s->buf_end - s->buffer)) {

        /* can do the seek inside the buffer */

        s->buf_ptr = s->buffer + offset1;

    } else if(s->is_streamed && !s->write_flag && offset1 >= 0 &&

              (whence != SEEK_END || force)) {

        while(s->pos < offset && !s->eof_reached)

            fill_buffer(s);

        if (s->eof_reached)

            return AVERROR_EOF;

        s->buf_ptr = s->buf_end + offset - s->pos;

    } else {

        int64_t res = AVERROR(EPIPE);

#if CONFIG_MUXERS || CONFIG_NETWORK

        if (s->write_flag) {

            flush_buffer(s);

            s->must_flush = 1;

        }

#endif /* CONFIG_MUXERS || CONFIG_NETWORK */

        if (!s->seek || (res = s->seek(s->opaque, offset, SEEK_SET)) < 0)

            return res;

        if (!s->write_flag)

            s->buf_end = s->buffer;

        s->buf_ptr = s->buffer;

        s->pos = offset;

    }

    s->eof_reached = 0;

    return offset;

}


int ff_listen_connect(int fd, const struct sockaddr *addr,

                      socklen_t addrlen, int timeout, URLContext *h)

{

    struct pollfd p = {fd, POLLOUT, 0};

    int ret;

    socklen_t optlen;

    ff_socket_nonblock(fd, 1);

    while ((ret = connect(fd, addr, addrlen))) {

        ret = ff_neterrno();

        switch (ret) {

        case AVERROR(EINTR):

            if (ff_check_interrupt(&h->interrupt_callback))

                return AVERROR_EXIT;

            continue;

        case AVERROR(EINPROGRESS):

        case AVERROR(EAGAIN):

            while (timeout--) {

                if (ff_check_interrupt(&h->interrupt_callback))

                    return AVERROR_EXIT;

                ret = poll(&p, 1, 100);

                if (ret > 0)

                    break;

            }

            if (ret <= 0)

                return AVERROR(ETIMEDOUT);

            optlen = sizeof(ret);

            if (getsockopt (fd, SOL_SOCKET, SO_ERROR, &ret, &optlen))

                ret = AVUNERROR(ff_neterrno());

            if (ret != 0) {

                char errbuf[100];

                ret = AVERROR(ret);

                av_strerror(ret, errbuf, sizeof(errbuf));

                av_log(h, AV_LOG_ERROR,

                       "Connection to %s failed: %s\n",

                       h->filename, errbuf);

            }

        default:

            return ret;

        }

    }

    return ret;

}


static int get_uint32_equal(QEMUFile *f, void *pv, size_t size)

{

    uint32_t *v = pv;

    uint32_t v2;

    qemu_get_be32s(f, &v2);

    if (*v == v2) {

        return 0;

    }

    return -EINVAL;

}


int socket_dgram(SocketAddress *remote, SocketAddress *local, Error **errp)

{

    QemuOpts *opts;

    int fd;

    opts = qemu_opts_create_nofail(&socket_optslist);

    switch (remote->kind) {

    case SOCKET_ADDRESS_KIND_INET:

        qemu_opt_set(opts, "host", remote->inet->host);

        qemu_opt_set(opts, "port", remote->inet->port);

        if (local) {

            qemu_opt_set(opts, "localaddr", local->inet->host);

            qemu_opt_set(opts, "localport", local->inet->port);

        }

        fd = inet_dgram_opts(opts, errp);

        break;

    default:

        error_setg(errp, "socket type unsupported for datagram");

        return -1;

    }

    qemu_opts_del(opts);

    return fd;

}


static void cpu_common_initfn(Object *obj)

{

    CPUState *cpu = CPU(obj);

    CPUClass *cc = CPU_GET_CLASS(obj);

    cpu->cpu_index = UNASSIGNED_CPU_INDEX;

    cpu->gdb_num_regs = cpu->gdb_num_g_regs = cc->gdb_num_core_regs;

    /* *-user doesn't have configurable SMP topology */

    /* the default value is changed by qemu_init_vcpu() for softmmu */

    cpu->nr_cores = 1;

    cpu->nr_threads = 1;

    qemu_mutex_init(&cpu->work_mutex);

    QTAILQ_INIT(&cpu->breakpoints);

    QTAILQ_INIT(&cpu->watchpoints);

    cpu->trace_dstate = bitmap_new(trace_get_vcpu_event_count());

    cpu_exec_initfn(cpu);

}


static void read_sbr_single_channel_element(AACContext *ac,

                                            SpectralBandReplication *sbr,

                                            GetBitContext *gb)

{

    if (get_bits1(gb)) // bs_data_extra

        skip_bits(gb, 4); // bs_reserved

    read_sbr_grid(ac, sbr, gb, &sbr->data[0]);

    read_sbr_dtdf(sbr, gb, &sbr->data[0]);

    read_sbr_invf(sbr, gb, &sbr->data[0]);

    read_sbr_envelope(sbr, gb, &sbr->data[0], 0);

    read_sbr_noise(sbr, gb, &sbr->data[0], 0);

    if ((sbr->data[0].bs_add_harmonic_flag = get_bits1(gb)))

        get_bits1_vector(gb, sbr->data[0].bs_add_harmonic, sbr->n[1]);

}


static int GLZWDecode(GifState * s, uint8_t * buf, int len)

{

    int l, c, code, oc, fc;

    uint8_t *sp;

    if (s->end_code < 0)

        return 0;

    l = len;

    sp = s->sp;

    oc = s->oc;

    fc = s->fc;

    while (sp > s->stack) {

        *buf++ = *(--sp);

        if ((--l) == 0)

            goto the_end;

    }

    for (;;) {

        c = GetCode(s);

        if (c == s->end_code) {

            s->end_code = -1;

            break;

        } else if (c == s->clear_code) {

            s->cursize = s->codesize + 1;

            s->curmask = mask[s->cursize];

            s->slot = s->newcodes;

            s->top_slot = 1 << s->cursize;

            while ((c = GetCode(s)) == s->clear_code);

            if (c == s->end_code) {

                s->end_code = -1;

                break;

            }

            /* test error */

            if (c >= s->slot)

                c = 0;

            fc = oc = c;

            *buf++ = c;

            if ((--l) == 0)

                break;

        } else {

            code = c;

            if (code >= s->slot) {

                *sp++ = fc;

                code = oc;

            }

            while (code >= s->newcodes) {

                *sp++ = s->suffix[code];

                code = s->prefix[code];

            }

            *sp++ = code;

            if (s->slot < s->top_slot) {

                s->suffix[s->slot] = fc = code;

                s->prefix[s->slot++] = oc;

                oc = c;

            }

            if (s->slot >= s->top_slot) {

                if (s->cursize < MAXBITS) {

                    s->top_slot <<= 1;

                    s->curmask = mask[++s->cursize];

                }

            }

            while (sp > s->stack) {

                *buf++ = *(--sp);

                if ((--l) == 0)

                    goto the_end;

            }

        }

    }

  the_end:

    s->sp = sp;

    s->oc = oc;

    s->fc = fc;

    return len - l;

}


bool throttle_is_valid(ThrottleConfig *cfg, Error **errp)
{
    int i;
    bool bps_flag, ops_flag;
    bool bps_max_flag, ops_max_flag;
    bps_flag = cfg->buckets[THROTTLE_BPS_TOTAL].avg &&
               (cfg->buckets[THROTTLE_BPS_READ].avg ||
                cfg->buckets[THROTTLE_BPS_WRITE].avg);
    ops_flag = cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
               (cfg->buckets[THROTTLE_OPS_READ].avg ||
                cfg->buckets[THROTTLE_OPS_WRITE].avg);
    bps_max_flag = cfg->buckets[THROTTLE_BPS_TOTAL].max &&
                  (cfg->buckets[THROTTLE_BPS_READ].max  ||
                   cfg->buckets[THROTTLE_BPS_WRITE].max);
    ops_max_flag = cfg->buckets[THROTTLE_OPS_TOTAL].max &&
                   (cfg->buckets[THROTTLE_OPS_READ].max ||
                   cfg->buckets[THROTTLE_OPS_WRITE].max);
    if (bps_flag || ops_flag || bps_max_flag || ops_max_flag) {
        error_setg(errp, "bps/iops/max total values and read/write values"
                   " cannot be used at the same time");
    if (cfg->op_size &&
        !cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
        !cfg->buckets[THROTTLE_OPS_READ].avg &&
        !cfg->buckets[THROTTLE_OPS_WRITE].avg) {
        error_setg(errp, "iops size requires an iops value to be set");
    for (i = 0; i < BUCKETS_COUNT; i++) {
        LeakyBucket *bkt = &cfg->buckets[i];
        if (bkt->avg > THROTTLE_VALUE_MAX || bkt->max > THROTTLE_VALUE_MAX) {
            error_setg(errp, "bps/iops/max values must be within [0, %lld]",
                       THROTTLE_VALUE_MAX);
        if (!bkt->burst_length) {
            error_setg(errp, "the burst length cannot be 0");
        if (bkt->burst_length > 1 && !bkt->max) {
            error_setg(errp, "burst length set without burst rate");
        if (bkt->max && !bkt->avg) {
            error_setg(errp, "bps_max/iops_max require corresponding"
                       " bps/iops values");
        if (bkt->max && bkt->max < bkt->avg) {
            error_setg(errp, "bps_max/iops_max cannot be lower than bps/iops");
    return true;


static void put_ebml_uint(ByteIOContext *pb, unsigned int elementid, uint64_t val)

{

    int i, bytes = 1;

    while (val >> bytes*8 && bytes < 8) bytes++;

    put_ebml_id(pb, elementid);

    put_ebml_num(pb, bytes, 0);

    for (i = bytes - 1; i >= 0; i--)

        put_byte(pb, val >> i*8);

}


PCIBus *pci_grackle_init(uint32_t base, qemu_irq *pic)

{

    DeviceState *dev;

    SysBusDevice *s;

    GrackleState *d;

    dev = qdev_create(NULL, "grackle");

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    d = FROM_SYSBUS(GrackleState, s);

    d->host_state.bus = pci_register_bus(&d->busdev.qdev, "pci",

                                         pci_grackle_set_irq,

                                         pci_grackle_map_irq,

                                         pic, 0, 4);

    pci_create_simple(d->host_state.bus, 0, "grackle");

    sysbus_mmio_map(s, 0, base);

    sysbus_mmio_map(s, 1, base + 0x00200000);

    return d->host_state.bus;

}


static void xan_unpack(unsigned char *dest, const unsigned char *src, int dest_len)

{

    unsigned char opcode;

    int size;

    unsigned char *dest_end = dest + dest_len;

    while (dest < dest_end) {

        opcode = *src++;

        if (opcode < 0xe0) {

            int size2, back;

            if ( (opcode & 0x80) == 0 ) {

                size = opcode & 3;

                back  = ((opcode & 0x60) << 3) + *src++ + 1;

                size2 = ((opcode & 0x1c) >> 2) + 3;

            } else if ( (opcode & 0x40) == 0 ) {

                size = *src >> 6;

                back  = (bytestream_get_be16(&src) & 0x3fff) + 1;

                size2 = (opcode & 0x3f) + 4;

            } else {

                size = opcode & 3;

                back  = ((opcode & 0x10) << 12) + bytestream_get_be16(&src) + 1;

                size2 = ((opcode & 0x0c) <<  6) + *src++ + 5;

                if (size + size2 > dest_end - dest)

                    return;

            }

            memcpy(dest, src, size);  dest += size;  src += size;

            av_memcpy_backptr(dest, back, size2);

            dest += size2;

        } else {

            int finish = opcode >= 0xfc;

            size = finish ? opcode & 3 : ((opcode & 0x1f) << 2) + 4;

            memcpy(dest, src, size);  dest += size;  src += size;

            if (finish)

                return;

        }

    }

}


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

                            int *got_frame_ptr, AVPacket *avpkt)

{

    int buf_size        = avpkt->size;

    ADXContext *c       = avctx->priv_data;

    int16_t *samples;

    const uint8_t *buf  = avpkt->data;

    int num_blocks, ch, ret;

    if (c->eof) {

        *got_frame_ptr = 0;

        return buf_size;

    }

    if (!c->header_parsed && buf_size >= 2 && AV_RB16(buf) == 0x8000) {

        int header_size;

        if ((ret = avpriv_adx_decode_header(avctx, buf, buf_size, &header_size,

                                            c->coeff)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "error parsing ADX header\n");

            return AVERROR_INVALIDDATA;

        }

        c->channels      = avctx->channels;

        c->header_parsed = 1;

        if (buf_size < header_size)

            return AVERROR_INVALIDDATA;

        buf      += header_size;

        buf_size -= header_size;

    }

    if (!c->header_parsed)

        return AVERROR_INVALIDDATA;

    /* calculate number of blocks in the packet */

    num_blocks = buf_size / (BLOCK_SIZE * c->channels);

    /* if the packet is not an even multiple of BLOCK_SIZE, check for an EOF

       packet */

    if (!num_blocks || buf_size % (BLOCK_SIZE * avctx->channels)) {

        if (buf_size >= 4 && (AV_RB16(buf) & 0x8000)) {

            c->eof = 1;

            *got_frame_ptr = 0;

            return avpkt->size;

        }

        return AVERROR_INVALIDDATA;

    }

    /* get output buffer */

    c->frame.nb_samples = num_blocks * BLOCK_SAMPLES;

    if ((ret = avctx->get_buffer(avctx, &c->frame)) < 0) {

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

        return ret;

    }

    samples = (int16_t *)c->frame.data[0];

    while (num_blocks--) {

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

            if (adx_decode(c, samples + ch, buf, ch)) {

                c->eof = 1;

                buf = avpkt->data + avpkt->size;

                break;

            }

            buf_size -= BLOCK_SIZE;

            buf      += BLOCK_SIZE;

        }

        samples += BLOCK_SAMPLES * c->channels;

    }

    *got_frame_ptr   = 1;

    *(AVFrame *)data = c->frame;

    return buf - avpkt->data;

}


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

{

	int i;

        assert(src1==src2);

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

	{

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

		int dl= (d0&0x03E07C1F);

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

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

		int d= dh2 + dl;

		int b= d&0x7F;

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

		int g= d>>21;

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

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

	}

}


static int matroska_parse_cluster_incremental(MatroskaDemuxContext *matroska)

{

    EbmlList *blocks_list;

    MatroskaBlock *blocks;

    int i, res;

    res = ebml_parse(matroska,

                     matroska_cluster_incremental_parsing,

                     &matroska->current_cluster);

    if (res == 1) {

        /* New Cluster */

        if (matroska->current_cluster_pos)

            ebml_level_end(matroska);

        ebml_free(matroska_cluster, &matroska->current_cluster);

        memset(&matroska->current_cluster, 0, sizeof(MatroskaCluster));

        matroska->current_cluster_num_blocks = 0;

        matroska->current_cluster_pos = avio_tell(matroska->ctx->pb);

        matroska->prev_pkt = NULL;

        /* sizeof the ID which was already read */

        if (matroska->current_id)

            matroska->current_cluster_pos -= 4;

        res = ebml_parse(matroska,

                         matroska_clusters_incremental,

                         &matroska->current_cluster);

        /* Try parsing the block again. */

        if (res == 1)

            res = ebml_parse(matroska,

                             matroska_cluster_incremental_parsing,

                             &matroska->current_cluster);

    }

    if (!res &&

        matroska->current_cluster_num_blocks <

            matroska->current_cluster.blocks.nb_elem) {

        blocks_list = &matroska->current_cluster.blocks;

        blocks = blocks_list->elem;

        matroska->current_cluster_num_blocks = blocks_list->nb_elem;

        i = blocks_list->nb_elem - 1;

        if (blocks[i].bin.size > 0 && blocks[i].bin.data) {

            int is_keyframe = blocks[i].non_simple ? !blocks[i].reference : -1;

            uint8_t* additional = blocks[i].additional.size > 0 ?

                                    blocks[i].additional.data : NULL;

            if (!blocks[i].non_simple)

                blocks[i].duration = 0;

            res = matroska_parse_block(matroska,

                                       blocks[i].bin.data, blocks[i].bin.size,

                                       blocks[i].bin.pos,

                                       matroska->current_cluster.timecode,

                                       blocks[i].duration, is_keyframe,

                                       additional, blocks[i].additional_id,

                                       blocks[i].additional.size,

                                       matroska->current_cluster_pos);

        }

    }

    if (res < 0)  matroska->done = 1;

    return res;

}


static int cache_read(URLContext *h, unsigned char *buf, int size)

{

    Context *c= h->priv_data;

    CacheEntry *entry, *next[2] = {NULL, NULL};

    int r;

    entry = av_tree_find(c->root, &c->logical_pos, cmp, (void**)next);

    if (!entry)

        entry = next[0];

    if (entry) {

        int64_t in_block_pos = c->logical_pos - entry->logical_pos;

        av_assert0(entry->logical_pos <= c->logical_pos);

        if (in_block_pos < entry->size) {

            int64_t physical_target = entry->physical_pos + in_block_pos;

            if (c->cache_pos != physical_target) {

                r = lseek(c->fd, physical_target, SEEK_SET);

            } else

                r = c->cache_pos;

            if (r >= 0) {

                c->cache_pos = r;

                r = read(c->fd, buf, FFMIN(size, entry->size - in_block_pos));

            }

            if (r > 0) {

                c->cache_pos += r;

                c->logical_pos += r;

                c->cache_hit ++;

                return r;

            }

        }

    }

    // Cache miss or some kind of fault with the cache

    if (c->logical_pos != c->inner_pos) {

        r = ffurl_seek(c->inner, c->logical_pos, SEEK_SET);

        if (r<0) {

            av_log(h, AV_LOG_ERROR, "Failed to perform internal seek\n");

            return r;

        }

        c->inner_pos = r;

    }

    r = ffurl_read(c->inner, buf, size);

    if (r == 0 && size>0) {

        c->is_true_eof = 1;

        av_assert0(c->end >= c->logical_pos);

    }

    if (r<=0)

        return r;

    c->inner_pos += r;

    c->cache_miss ++;

    add_entry(h, buf, r);

    c->logical_pos += r;

    c->end = FFMAX(c->end, c->logical_pos);

    return r;

}


const AVOption *av_opt_find(void *obj, const char *name, const char *unit,

                            int opt_flags, int search_flags)

{

    AVClass *c = *(AVClass**)obj;

    const AVOption *o = NULL;

    if (c->opt_find && search_flags & AV_OPT_SEARCH_CHILDREN &&

        (o = c->opt_find(obj, name, unit, opt_flags, search_flags)))

        return o;

    while (o = av_next_option(obj, o)) {

        if (!strcmp(o->name, name) && (!unit || (o->unit && !strcmp(o->unit, unit))) &&

            (o->flags & opt_flags) == opt_flags)

            return o;

    }

    return NULL;

}


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

                             int *got_frame, AVPacket *avpkt)

{

    VCR1Context *const a      = avctx->priv_data;

    AVFrame *const p          = data;

    const uint8_t *bytestream = avpkt->data;

    const uint8_t *bytestream_end = bytestream + avpkt->size;

    int i, x, y, ret;

    if(avpkt->size < 16 + avctx->height + avctx->width*avctx->height*5/8){

        av_log(avctx, AV_LOG_ERROR, "Insufficient input data.\n");

        return AVERROR(EINVAL);

    }

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)

        return ret;

    p->pict_type = AV_PICTURE_TYPE_I;

    p->key_frame = 1;

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

        a->delta[i] = *bytestream++;

        bytestream++;

    }

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

        int offset;

        uint8_t *luma = &p->data[0][y * p->linesize[0]];

        if ((y & 3) == 0) {

            uint8_t *cb = &p->data[1][(y >> 2) * p->linesize[1]];

            uint8_t *cr = &p->data[2][(y >> 2) * p->linesize[2]];

            av_assert0 (bytestream_end - bytestream >= 4 + avctx->width);

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

                a->offset[i] = *bytestream++;

            offset = a->offset[0] - a->delta[bytestream[2] & 0xF];

            for (x = 0; x < avctx->width; x += 4) {

                luma[0]     = offset += a->delta[bytestream[2] & 0xF];

                luma[1]     = offset += a->delta[bytestream[2] >>  4];

                luma[2]     = offset += a->delta[bytestream[0] & 0xF];

                luma[3]     = offset += a->delta[bytestream[0] >>  4];

                luma       += 4;

                *cb++       = bytestream[3];

                *cr++       = bytestream[1];

                bytestream += 4;

            }

        } else {

            av_assert0 (bytestream_end - bytestream >= avctx->width / 2);

            offset = a->offset[y & 3] - a->delta[bytestream[2] & 0xF];

            for (x = 0; x < avctx->width; x += 8) {

                luma[0]     = offset += a->delta[bytestream[2] & 0xF];

                luma[1]     = offset += a->delta[bytestream[2] >>  4];

                luma[2]     = offset += a->delta[bytestream[3] & 0xF];

                luma[3]     = offset += a->delta[bytestream[3] >>  4];

                luma[4]     = offset += a->delta[bytestream[0] & 0xF];

                luma[5]     = offset += a->delta[bytestream[0] >>  4];

                luma[6]     = offset += a->delta[bytestream[1] & 0xF];

                luma[7]     = offset += a->delta[bytestream[1] >>  4];

                luma       += 8;

                bytestream += 4;

            }

        }

    }

    *got_frame = 1;

    return bytestream - avpkt->data;

}


static void fill_slice_long(AVCodecContext *avctx, DXVA_Slice_H264_Long *slice,

                            unsigned position, unsigned size)

{

    const H264Context *h = avctx->priv_data;

    struct dxva_context *ctx = avctx->hwaccel_context;

    unsigned list;

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

    slice->BSNALunitDataLocation = position;

    slice->SliceBytesInBuffer    = size;

    slice->wBadSliceChopping     = 0;

    slice->first_mb_in_slice     = (h->mb_y >> FIELD_OR_MBAFF_PICTURE(h)) * h->mb_width + h->mb_x;

    slice->NumMbsForSlice        = 0; /* XXX it is set once we have all slices */

    slice->BitOffsetToSliceData  = get_bits_count(&h->gb);

    slice->slice_type            = ff_h264_get_slice_type(h);

    if (h->slice_type_fixed)

        slice->slice_type += 5;

    slice->luma_log2_weight_denom       = h->luma_log2_weight_denom;

    slice->chroma_log2_weight_denom     = h->chroma_log2_weight_denom;

    if (h->list_count > 0)

        slice->num_ref_idx_l0_active_minus1 = h->ref_count[0] - 1;

    if (h->list_count > 1)

        slice->num_ref_idx_l1_active_minus1 = h->ref_count[1] - 1;

    slice->slice_alpha_c0_offset_div2   = h->slice_alpha_c0_offset / 2;

    slice->slice_beta_offset_div2       = h->slice_beta_offset     / 2;

    slice->Reserved8Bits                = 0;

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

        unsigned i;

        for (i = 0; i < FF_ARRAY_ELEMS(slice->RefPicList[list]); i++) {

            if (list < h->list_count && i < h->ref_count[list]) {

                const Picture *r = &h->ref_list[list][i];

                unsigned plane;

                fill_picture_entry(&slice->RefPicList[list][i],

                                   ff_dxva2_get_surface_index(ctx, r),

                                   r->reference == PICT_BOTTOM_FIELD);

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

                    int w, o;

                    if (plane == 0 && h->luma_weight_flag[list]) {

                        w = h->luma_weight[i][list][0];

                        o = h->luma_weight[i][list][1];

                    } else if (plane >= 1 && h->chroma_weight_flag[list]) {

                        w = h->chroma_weight[i][list][plane-1][0];

                        o = h->chroma_weight[i][list][plane-1][1];

                    } else {

                        w = 1 << (plane == 0 ? h->luma_log2_weight_denom :

                                               h->chroma_log2_weight_denom);

                        o = 0;

                    }

                    slice->Weights[list][i][plane][0] = w;

                    slice->Weights[list][i][plane][1] = o;

                }

            } else {

                unsigned plane;

                slice->RefPicList[list][i].bPicEntry = 0xff;

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

                    slice->Weights[list][i][plane][0] = 0;

                    slice->Weights[list][i][plane][1] = 0;

                }

            }

        }

    }

    slice->slice_qs_delta    = 0; /* XXX not implemented by FFmpeg */

    slice->slice_qp_delta    = h->qscale - h->pps.init_qp;

    slice->redundant_pic_cnt = h->redundant_pic_count;

    if (h->slice_type == AV_PICTURE_TYPE_B)

        slice->direct_spatial_mv_pred_flag = h->direct_spatial_mv_pred;

    slice->cabac_init_idc = h->pps.cabac ? h->cabac_init_idc : 0;

    if (h->deblocking_filter < 2)

        slice->disable_deblocking_filter_idc = 1 - h->deblocking_filter;

    else

        slice->disable_deblocking_filter_idc = h->deblocking_filter;

    slice->slice_id = h->current_slice - 1;

}


static char* mpjpeg_get_boundary(AVIOContext* pb)

{

    uint8_t *mime_type = NULL;

    const char *start;

    const char *end;

    uint8_t *res = NULL;

    int     len;

    /* get MIME type, and skip to the first parameter */

    av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type);

    start = mime_type;

    while (start != NULL && *start != '\0') {

        start = strchr(start, ';');

        if (start)

            start = start+1;

        while (av_isspace(*start))

            start++;

        if (!av_stristart(start, "boundary=", &start)) {

            end = strchr(start, ';');

            if (end)

                len = end - start - 1;

            else

                len = strlen(start);

            res = av_strndup(start, len);

            break;

        }

    }

    av_freep(&mime_type);

    return res;

}


static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)

{

    AVPacket pkt1, *pkt = &pkt1;

    AVStream *st;

    int read_size, i, ret;

    int64_t end_time;

    int64_t filesize, offset, duration;

    int retry = 0;

    /* flush packet queue */

    flush_packet_queue(ic);

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

        st = ic->streams[i];

        if (st->start_time == AV_NOPTS_VALUE &&

            st->first_dts == AV_NOPTS_VALUE &&

            st->codec->codec_type != AVMEDIA_TYPE_UNKNOWN)

            av_log(st->codec, AV_LOG_WARNING,

                   "start time for stream %d is not set in estimate_timings_from_pts\n", i);

        if (st->parser) {

            av_parser_close(st->parser);

            st->parser = NULL;

        }

    }

    /* estimate the end time (duration) */

    /* XXX: may need to support wrapping */

    filesize = ic->pb ? avio_size(ic->pb) : 0;

    end_time = AV_NOPTS_VALUE;

    do {

        offset = filesize - (DURATION_MAX_READ_SIZE << retry);

        if (offset < 0)

            offset = 0;

        avio_seek(ic->pb, offset, SEEK_SET);

        read_size = 0;

        for (;;) {

            if (read_size >= DURATION_MAX_READ_SIZE << (FFMAX(retry - 1, 0)))

                break;

            do {

                ret = ff_read_packet(ic, pkt);

            } while (ret == AVERROR(EAGAIN));

            if (ret != 0)

                break;

            read_size += pkt->size;

            st         = ic->streams[pkt->stream_index];

            if (pkt->pts != AV_NOPTS_VALUE &&

                (st->start_time != AV_NOPTS_VALUE ||

                 st->first_dts  != AV_NOPTS_VALUE)) {

                duration = end_time = pkt->pts + pkt->duration;

                if (st->start_time != AV_NOPTS_VALUE)

                    duration -= st->start_time;

                else

                    duration -= st->first_dts;

                if (duration > 0) {

                    if (st->duration == AV_NOPTS_VALUE || st->info->last_duration<= 0 ||

                        (st->duration < duration && FFABS(duration - st->info->last_duration) < 60LL*st->time_base.den / st->time_base.num))

                        st->duration = duration;

                    st->info->last_duration = duration;

                }

            }

            av_free_packet(pkt);

        }

    } while (end_time == AV_NOPTS_VALUE &&

             filesize > (DURATION_MAX_READ_SIZE << retry) &&

             ++retry <= DURATION_MAX_RETRY);

    /* warn about audio/video streams which duration could not be estimated */

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

        st = ic->streams[i];

        if (st->duration == AV_NOPTS_VALUE) {

            switch (st->codec->codec_type) {

            case AVMEDIA_TYPE_VIDEO:

            case AVMEDIA_TYPE_AUDIO:

                if (st->start_time != AV_NOPTS_VALUE || st->first_dts  != AV_NOPTS_VALUE) {

                    av_log(ic, AV_LOG_DEBUG, "stream %d : no PTS found at end of file, duration not set\n", i);

                } else

                    av_log(ic, AV_LOG_DEBUG, "stream %d : no TS found at start of file, duration not set\n", i);

            }

        }

    }

    fill_all_stream_timings(ic);

    avio_seek(ic->pb, old_offset, SEEK_SET);

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

        int j;

        st              = ic->streams[i];

        st->cur_dts     = st->first_dts;

        st->last_IP_pts = AV_NOPTS_VALUE;

        st->last_dts_for_order_check = AV_NOPTS_VALUE;

        for (j = 0; j < MAX_REORDER_DELAY + 1; j++)

            st->pts_buffer[j] = AV_NOPTS_VALUE;

    }

}


int init_put_byte(ByteIOContext *s,

                  unsigned char *buffer,

                  int buffer_size,

                  int write_flag,

                  void *opaque,

                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),

                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),

                  int64_t (*seek)(void *opaque, int64_t offset, int whence))

{

    s->buffer = buffer;

    s->buffer_size = buffer_size;

    s->buf_ptr = buffer;

    url_resetbuf(s, write_flag ? URL_WRONLY : URL_RDONLY);

    s->opaque = opaque;

    s->write_packet = write_packet;

    s->read_packet = read_packet;

    s->seek = seek;

    s->pos = 0;

    s->must_flush = 0;

    s->eof_reached = 0;

    s->error = 0;

    s->is_streamed = 0;

    s->max_packet_size = 0;

    s->update_checksum= NULL;

    if(!read_packet && !write_flag){

        s->pos = buffer_size;

        s->buf_end = s->buffer + buffer_size;

    }

    s->read_pause = NULL;

    s->read_seek  = NULL;

    return 0;

}


static void vc1_decode_skip_blocks(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    if (!v->s.last_picture.f.data[0])

        return;

    ff_er_add_slice(&s->er, 0, s->start_mb_y, s->mb_width - 1, s->end_mb_y - 1, ER_MB_END);

    s->first_slice_line = 1;

    for (s->mb_y = s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {

        s->mb_x = 0;

        init_block_index(v);

        ff_update_block_index(s);

        memcpy(s->dest[0], s->last_picture.f.data[0] + s->mb_y * 16 * s->linesize,   s->linesize   * 16);

        memcpy(s->dest[1], s->last_picture.f.data[1] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);

        memcpy(s->dest[2], s->last_picture.f.data[2] + s->mb_y *  8 * s->uvlinesize, s->uvlinesize *  8);

        ff_mpeg_draw_horiz_band(s, s->mb_y * 16, 16);

        s->first_slice_line = 0;

    }

    s->pict_type = AV_PICTURE_TYPE_P;

}


static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,

                                     const float *coefs, const FFPsyWindowInfo *wi)

{

    AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;

    AacPsyChannel *pch  = &pctx->ch[channel];

    int start = 0;

    int i, w, g;

    float desired_bits, desired_pe, delta_pe, reduction, spread_en[128] = {0};

    float a = 0.0f, active_lines = 0.0f, norm_fac = 0.0f;

    float pe = pctx->chan_bitrate > 32000 ? 0.0f : FFMAX(50.0f, 100.0f - pctx->chan_bitrate * 100.0f / 32000.0f);

    const int      num_bands   = ctx->num_bands[wi->num_windows == 8];

    const uint8_t *band_sizes  = ctx->bands[wi->num_windows == 8];

    AacPsyCoeffs  *coeffs      = pctx->psy_coef[wi->num_windows == 8];

    const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;

    //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"

    for (w = 0; w < wi->num_windows*16; w += 16) {

        for (g = 0; g < num_bands; g++) {

            AacPsyBand *band = &pch->band[w+g];

            float form_factor = 0.0f;

            band->energy = 0.0f;

            for (i = 0; i < band_sizes[g]; i++) {

                band->energy += coefs[start+i] * coefs[start+i];

                form_factor  += sqrtf(fabs(coefs[start+i]));

            }

            band->thr      = band->energy * 0.001258925f;

            band->nz_lines = form_factor / powf(band->energy / band_sizes[g], 0.25f);

            start += band_sizes[g];

        }

    }

    //modify thresholds and energies - spread, threshold in quiet, pre-echo control

    for (w = 0; w < wi->num_windows*16; w += 16) {

        AacPsyBand *bands = &pch->band[w];

        //5.4.2.3 "Spreading" & 5.4.3 "Spreaded Energy Calculation"

        spread_en[0] = bands[0].energy;

        for (g = 1; g < num_bands; g++) {

            bands[g].thr   = FFMAX(bands[g].thr,    bands[g-1].thr * coeffs[g].spread_hi[0]);

            spread_en[w+g] = FFMAX(bands[g].energy, spread_en[w+g-1] * coeffs[g].spread_hi[1]);

        }

        for (g = num_bands - 2; g >= 0; g--) {

            bands[g].thr   = FFMAX(bands[g].thr,   bands[g+1].thr * coeffs[g].spread_low[0]);

            spread_en[w+g] = FFMAX(spread_en[w+g], spread_en[w+g+1] * coeffs[g].spread_low[1]);

        }

        //5.4.2.4 "Threshold in quiet"

        for (g = 0; g < num_bands; g++) {

            AacPsyBand *band = &bands[g];

            band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);

            //5.4.2.5 "Pre-echo control"

            if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))

                band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,

                                  PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));

            /* 5.6.1.3.1 "Prepatory steps of the perceptual entropy calculation" */

            pe += calc_pe_3gpp(band);

            a  += band->pe_const;

            active_lines += band->active_lines;

            /* 5.6.1.3.3 "Selection of the bands for avoidance of holes" */

            if (spread_en[w+g] * avoid_hole_thr > band->energy || coeffs[g].min_snr > 1.0f)

                band->avoid_holes = PSY_3GPP_AH_NONE;

            else

                band->avoid_holes = PSY_3GPP_AH_INACTIVE;

        }

    }

    /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */

    ctx->ch[channel].entropy = pe;

    desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);

    desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);

    /* NOTE: PE correction is kept simple. During initial testing it had very

     *       little effect on the final bitrate. Probably a good idea to come

     *       back and do more testing later.

     */

    if (ctx->bitres.bits > 0)

        desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),

                               0.85f, 1.15f);

    pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);

    if (desired_pe < pe) {

        /* 5.6.1.3.4 "First Estimation of the reduction value" */

        for (w = 0; w < wi->num_windows*16; w += 16) {

            reduction = calc_reduction_3gpp(a, desired_pe, pe, active_lines);

            pe = 0.0f;

            a  = 0.0f;

            active_lines = 0.0f;

            for (g = 0; g < num_bands; g++) {

                AacPsyBand *band = &pch->band[w+g];

                band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);

                /* recalculate PE */

                pe += calc_pe_3gpp(band);

                a  += band->pe_const;

                active_lines += band->active_lines;

            }

        }

        /* 5.6.1.3.5 "Second Estimation of the reduction value" */

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

            float pe_no_ah = 0.0f, desired_pe_no_ah;

            active_lines = a = 0.0f;

            for (w = 0; w < wi->num_windows*16; w += 16) {

                for (g = 0; g < num_bands; g++) {

                    AacPsyBand *band = &pch->band[w+g];

                    if (band->avoid_holes != PSY_3GPP_AH_ACTIVE) {

                        pe_no_ah += band->pe;

                        a        += band->pe_const;

                        active_lines += band->active_lines;

                    }

                }

            }

            desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);

            if (active_lines > 0.0f)

                reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);

            pe = 0.0f;

            for (w = 0; w < wi->num_windows*16; w += 16) {

                for (g = 0; g < num_bands; g++) {

                    AacPsyBand *band = &pch->band[w+g];

                    if (active_lines > 0.0f)

                        band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);

                    pe += calc_pe_3gpp(band);

                    band->norm_fac = band->active_lines / band->thr;

                    norm_fac += band->norm_fac;

                }

            }

            delta_pe = desired_pe - pe;

            if (fabs(delta_pe) > 0.05f * desired_pe)

                break;

        }

        if (pe < 1.15f * desired_pe) {

            /* 6.6.1.3.6 "Final threshold modification by linearization" */

            norm_fac = 1.0f / norm_fac;

            for (w = 0; w < wi->num_windows*16; w += 16) {

                for (g = 0; g < num_bands; g++) {

                    AacPsyBand *band = &pch->band[w+g];

                    if (band->active_lines > 0.5f) {

                        float delta_sfb_pe = band->norm_fac * norm_fac * delta_pe;

                        float thr = band->thr;

                        thr *= powf(2.0f, delta_sfb_pe / band->active_lines);

                        if (thr > coeffs[g].min_snr * band->energy && band->avoid_holes == PSY_3GPP_AH_INACTIVE)

                            thr = FFMAX(band->thr, coeffs[g].min_snr * band->energy);

                        band->thr = thr;

                    }

                }

            }

        } else {

            /* 5.6.1.3.7 "Further perceptual entropy reduction" */

            g = num_bands;

            while (pe > desired_pe && g--) {

                for (w = 0; w < wi->num_windows*16; w+= 16) {

                    AacPsyBand *band = &pch->band[w+g];

                    if (band->avoid_holes != PSY_3GPP_AH_NONE && coeffs[g].min_snr < PSY_SNR_1DB) {

                        coeffs[g].min_snr = PSY_SNR_1DB;

                        band->thr = band->energy * PSY_SNR_1DB;

                        pe += band->active_lines * 1.5f - band->pe;

                    }

                }

            }

            /* TODO: allow more holes (unused without mid/side) */

        }

    }

    for (w = 0; w < wi->num_windows*16; w += 16) {

        for (g = 0; g < num_bands; g++) {

            AacPsyBand *band     = &pch->band[w+g];

            FFPsyBand  *psy_band = &ctx->ch[channel].psy_bands[w+g];

            psy_band->threshold = band->thr;

            psy_band->energy    = band->energy;

        }

    }

    memcpy(pch->prev_band, pch->band, sizeof(pch->band));

}


decode_coeffs_b_generic(VP56RangeCoder *c, int16_t *coef, int n_coeffs,

                        int is_tx32x32, int is8bitsperpixel, int bpp, unsigned (*cnt)[6][3],

                        unsigned (*eob)[6][2], uint8_t (*p)[6][11],

                        int nnz, const int16_t *scan, const int16_t (*nb)[2],

                        const int16_t *band_counts, const int16_t *qmul)

{

    int i = 0, band = 0, band_left = band_counts[band];

    uint8_t *tp = p[0][nnz];

    uint8_t cache[1024];

    do {

        int val, rc;

        val = vp56_rac_get_prob_branchy(c, tp[0]); // eob

        eob[band][nnz][val]++;

        if (!val)

            break;

skip_eob:

        if (!vp56_rac_get_prob_branchy(c, tp[1])) { // zero

            cnt[band][nnz][0]++;

            if (!--band_left)

                band_left = band_counts[++band];

            cache[scan[i]] = 0;

            nnz            = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;

            tp             = p[band][nnz];

            if (++i == n_coeffs)

                break;  //invalid input; blocks should end with EOB

            goto skip_eob;

        }

        rc = scan[i];

        if (!vp56_rac_get_prob_branchy(c, tp[2])) { // one

            cnt[band][nnz][1]++;

            val       = 1;

            cache[rc] = 1;

        } else {

            // fill in p[3-10] (model fill) - only once per frame for each pos

            if (!tp[3])

                memcpy(&tp[3], ff_vp9_model_pareto8[tp[2]], 8);

            cnt[band][nnz][2]++;

            if (!vp56_rac_get_prob_branchy(c, tp[3])) { // 2, 3, 4

                if (!vp56_rac_get_prob_branchy(c, tp[4])) {

                    cache[rc] = val = 2;

                } else {

                    val       = 3 + vp56_rac_get_prob(c, tp[5]);

                    cache[rc] = 3;

                }

            } else if (!vp56_rac_get_prob_branchy(c, tp[6])) { // cat1/2

                cache[rc] = 4;

                if (!vp56_rac_get_prob_branchy(c, tp[7])) {

                    val  =  vp56_rac_get_prob(c, 159) + 5;

                } else {

                    val  = (vp56_rac_get_prob(c, 165) << 1) + 7;

                    val +=  vp56_rac_get_prob(c, 145);

                }

            } else { // cat 3-6

                cache[rc] = 5;

                if (!vp56_rac_get_prob_branchy(c, tp[8])) {

                    if (!vp56_rac_get_prob_branchy(c, tp[9])) {

                        val  = 11 + (vp56_rac_get_prob(c, 173) << 2);

                        val +=      (vp56_rac_get_prob(c, 148) << 1);

                        val +=       vp56_rac_get_prob(c, 140);

                    } else {

                        val  = 19 + (vp56_rac_get_prob(c, 176) << 3);

                        val +=      (vp56_rac_get_prob(c, 155) << 2);

                        val +=      (vp56_rac_get_prob(c, 140) << 1);

                        val +=       vp56_rac_get_prob(c, 135);

                    }

                } else if (!vp56_rac_get_prob_branchy(c, tp[10])) {

                    val  = (vp56_rac_get_prob(c, 180) << 4) + 35;

                    val += (vp56_rac_get_prob(c, 157) << 3);

                    val += (vp56_rac_get_prob(c, 141) << 2);

                    val += (vp56_rac_get_prob(c, 134) << 1);

                    val +=  vp56_rac_get_prob(c, 130);

                } else {

                    val = 67;

                    if (!is8bitsperpixel) {

                        if (bpp == 12) {

                            val += vp56_rac_get_prob(c, 255) << 17;

                            val += vp56_rac_get_prob(c, 255) << 16;

                        }

                        val +=  (vp56_rac_get_prob(c, 255) << 15);

                        val +=  (vp56_rac_get_prob(c, 255) << 14);

                    }

                    val += (vp56_rac_get_prob(c, 254) << 13);

                    val += (vp56_rac_get_prob(c, 254) << 12);

                    val += (vp56_rac_get_prob(c, 254) << 11);

                    val += (vp56_rac_get_prob(c, 252) << 10);

                    val += (vp56_rac_get_prob(c, 249) << 9);

                    val += (vp56_rac_get_prob(c, 243) << 8);

                    val += (vp56_rac_get_prob(c, 230) << 7);

                    val += (vp56_rac_get_prob(c, 196) << 6);

                    val += (vp56_rac_get_prob(c, 177) << 5);

                    val += (vp56_rac_get_prob(c, 153) << 4);

                    val += (vp56_rac_get_prob(c, 140) << 3);

                    val += (vp56_rac_get_prob(c, 133) << 2);

                    val += (vp56_rac_get_prob(c, 130) << 1);

                    val +=  vp56_rac_get_prob(c, 129);

                }

            }

        }

#define STORE_COEF(c, i, v) do { \

    if (is8bitsperpixel) { \

        c[i] = v; \

    } else { \

        AV_WN32A(&c[i * 2], v); \

    } \

} while (0)

        if (!--band_left)

            band_left = band_counts[++band];

        if (is_tx32x32)

            STORE_COEF(coef, rc, ((vp8_rac_get(c) ? -val : val) * qmul[!!i]) / 2);

        else

            STORE_COEF(coef, rc, (vp8_rac_get(c) ? -val : val) * qmul[!!i]);

        nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;

        tp = p[band][nnz];

    } while (++i < n_coeffs);

    return i;

}


static void set_pci_devfn(Object *obj, Visitor *v, void *opaque,

                          const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);

    unsigned int slot, fn, n;

    Error *local_err = NULL;

    char *str = (char *)"";

    if (dev->state != DEV_STATE_CREATED) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

    visit_type_str(v, &str, name, &local_err);

    if (local_err) {

        error_free(local_err);

        return set_int32(obj, v, opaque, name, errp);

    }

    if (sscanf(str, "%x.%x%n", &slot, &fn, &n) != 2) {

        fn = 0;

        if (sscanf(str, "%x%n", &slot, &n) != 1) {

            goto invalid;

        }

    }

    if (str[n] != '\0' || fn > 7 || slot > 31) {

        goto invalid;

    }

    *ptr = slot << 3 | fn;

    return;

invalid:

    error_set_from_qdev_prop_error(errp, EINVAL, dev, prop, str);

}


static void error_callback_bh(void *opaque)

{

    Coroutine *co = opaque;

    qemu_coroutine_enter(co);

}


void *colo_process_incoming_thread(void *opaque)

{

    MigrationIncomingState *mis = opaque;

    QEMUFile *fb = NULL;

    QIOChannelBuffer *bioc = NULL; /* Cache incoming device state */

    uint64_t total_size;

    uint64_t value;

    Error *local_err = NULL;

    migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,

                      MIGRATION_STATUS_COLO);

    failover_init_state();

    mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);

    if (!mis->to_src_file) {

        error_report("COLO incoming thread: Open QEMUFile to_src_file failed");

        goto out;

    }

    /*

     * Note: the communication between Primary side and Secondary side

     * should be sequential, we set the fd to unblocked in migration incoming

     * coroutine, and here we are in the COLO incoming thread, so it is ok to

     * set the fd back to blocked.

     */

    qemu_file_set_blocking(mis->from_src_file, true);

    bioc = qio_channel_buffer_new(COLO_BUFFER_BASE_SIZE);

    fb = qemu_fopen_channel_input(QIO_CHANNEL(bioc));

    object_unref(OBJECT(bioc));

    colo_send_message(mis->to_src_file, COLO_MESSAGE_CHECKPOINT_READY,

                      &local_err);

    if (local_err) {

        goto out;

    }

    while (mis->state == MIGRATION_STATUS_COLO) {

        int request;

        colo_wait_handle_message(mis->from_src_file, &request, &local_err);

        if (local_err) {

            goto out;

        }

        assert(request);

        if (failover_get_state() != FAILOVER_STATUS_NONE) {

            error_report("failover request");

            goto out;

        }

        /* FIXME: This is unnecessary for periodic checkpoint mode */

        colo_send_message(mis->to_src_file, COLO_MESSAGE_CHECKPOINT_REPLY,

                     &local_err);

        if (local_err) {

            goto out;

        }

        colo_receive_check_message(mis->from_src_file,

                           COLO_MESSAGE_VMSTATE_SEND, &local_err);

        if (local_err) {

            goto out;

        }

        value = colo_receive_message_value(mis->from_src_file,

                                 COLO_MESSAGE_VMSTATE_SIZE, &local_err);

        if (local_err) {

            goto out;

        }

        /*

         * Read VM device state data into channel buffer,

         * It's better to re-use the memory allocated.

         * Here we need to handle the channel buffer directly.

         */

        if (value > bioc->capacity) {

            bioc->capacity = value;

            bioc->data = g_realloc(bioc->data, bioc->capacity);

        }

        total_size = qemu_get_buffer(mis->from_src_file, bioc->data, value);

        if (total_size != value) {

            error_report("Got %" PRIu64 " VMState data, less than expected"

                        " %" PRIu64, total_size, value);

            goto out;

        }

        bioc->usage = total_size;

        qio_channel_io_seek(QIO_CHANNEL(bioc), 0, 0, NULL);

        colo_send_message(mis->to_src_file, COLO_MESSAGE_VMSTATE_RECEIVED,

                     &local_err);

        if (local_err) {

            goto out;

        }

        qemu_mutex_lock_iothread();

        qemu_system_reset(VMRESET_SILENT);

        if (qemu_loadvm_state(fb) < 0) {

            error_report("COLO: loadvm failed");

            qemu_mutex_unlock_iothread();

            goto out;

        }

        qemu_mutex_unlock_iothread();

        colo_send_message(mis->to_src_file, COLO_MESSAGE_VMSTATE_LOADED,

                     &local_err);

        if (local_err) {

            goto out;

        }

    }

out:

    /* Throw the unreported error message after exited from loop */

    if (local_err) {

        error_report_err(local_err);

    }

    if (fb) {

        qemu_fclose(fb);

    }

    if (mis->to_src_file) {

        qemu_fclose(mis->to_src_file);

    }

    migration_incoming_exit_colo();

    return NULL;

}


static int get_uint8(QEMUFile *f, void *pv, size_t size)

{

    uint8_t *v = pv;

    qemu_get_8s(f, v);

    return 0;

}


static uint64_t virtio_pci_config_read(void *opaque, hwaddr addr,

                                       unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    uint32_t config = VIRTIO_PCI_CONFIG(&proxy->pci_dev);

    uint64_t val = 0;

    if (addr < config) {

        return virtio_ioport_read(proxy, addr);

    }

    addr -= config;

    switch (size) {

    case 1:

        val = virtio_config_readb(vdev, addr);

        break;

    case 2:

        val = virtio_config_readw(vdev, addr);

        if (virtio_is_big_endian()) {

            val = bswap16(val);

        }

        break;

    case 4:

        val = virtio_config_readl(vdev, addr);

        if (virtio_is_big_endian()) {

            val = bswap32(val);

        }

        break;

    }

    return val;

}


int net_init_socket(QemuOpts *opts, const char *name, VLANState *vlan)

{

    if (qemu_opt_get(opts, "fd")) {

        int fd;

        if (qemu_opt_get(opts, "listen") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("listen=, connect=, mcast= and localaddr= is invalid with fd=");

            return -1;

        }

        fd = net_handle_fd_param(cur_mon, qemu_opt_get(opts, "fd"));

        if (fd == -1) {

            return -1;

        }

        if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "listen")) {

        const char *listen;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("fd=, connect=, mcast= and localaddr= is invalid with listen=");

            return -1;

        }

        listen = qemu_opt_get(opts, "listen");

        if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "connect")) {

        const char *connect;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "listen") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("fd=, listen=, mcast= and localaddr= is invalid with connect=");

            return -1;

        }

        connect = qemu_opt_get(opts, "connect");

        if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "mcast")) {

        const char *mcast, *localaddr;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "listen")) {

            error_report("fd=, connect= and listen= is invalid with mcast=");

            return -1;

        }

        mcast = qemu_opt_get(opts, "mcast");

        localaddr = qemu_opt_get(opts, "localaddr");

        if (net_socket_mcast_init(vlan, "socket", name, mcast, localaddr) == -1) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "udp")) {

        const char *udp, *localaddr;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "listen") ||

            qemu_opt_get(opts, "mcast")) {

            error_report("fd=, connect=, listen="

                         " and mcast= is invalid with udp=");

            return -1;

        }

        udp = qemu_opt_get(opts, "udp");

        localaddr = qemu_opt_get(opts, "localaddr");

        if (localaddr == NULL) {

                error_report("localaddr= is mandatory with udp=");

                return -1;

        }

        if (net_socket_udp_init(vlan, "udp", name, udp, localaddr) == -1) {

            return -1;

        }

    } else {

        error_report("-socket requires fd=, listen=,"

                     " connect=, mcast= or udp=");

        return -1;

    }

    return 0;

}


static int dvvideo_decode_frame(AVCodecContext *avctx,

                                 void *data, int *got_frame,

                                 AVPacket *avpkt)

{

    uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DVVideoContext *s = avctx->priv_data;

    const uint8_t* vsc_pack;

    int apt, is16_9, ret;

    const DVprofile *sys;

    sys = avpriv_dv_frame_profile2(avctx, s->sys, buf, buf_size);

    if (!sys || buf_size < sys->frame_size) {

        av_log(avctx, AV_LOG_ERROR, "could not find dv frame profile\n");

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

    }

    if (sys != s->sys) {

        ret = ff_dv_init_dynamic_tables(s, sys);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error initializing the work tables.\n");

            return ret;

        }

        s->sys = sys;

    }

    s->frame            = data;

    s->frame->key_frame = 1;

    s->frame->pict_type = AV_PICTURE_TYPE_I;

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

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

    ret = ff_set_dimensions(avctx, s->sys->width, s->sys->height);

    if (ret < 0)

        return ret;

    /* Determine the codec's sample_aspect ratio from the packet */

    vsc_pack = buf + 80*5 + 48 + 5;

    if ( *vsc_pack == dv_video_control ) {

        apt = buf[4] & 0x07;

        is16_9 = (vsc_pack && ((vsc_pack[2] & 0x07) == 0x02 || (!apt && (vsc_pack[2] & 0x07) == 0x07)));

        ff_set_sar(avctx, s->sys->sar[is16_9]);

    }

    if ((ret = ff_get_buffer(avctx, s->frame, 0)) < 0)

        return ret;

    s->frame->interlaced_frame = 1;

    s->frame->top_field_first  = 0;

    /* Determine the codec's field order from the packet */

    if ( *vsc_pack == dv_video_control ) {

        s->frame->top_field_first = !(vsc_pack[3] & 0x40);

    }

    s->buf = buf;

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

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

    emms_c();

    /* return image */

    *got_frame = 1;

    return s->sys->frame_size;

}


static int theora_decode_header(AVCodecContext *avctx, GetBitContext gb)

{

    Vp3DecodeContext *s = avctx->priv_data;

    s->theora = get_bits_long(&gb, 24);

    av_log(avctx, AV_LOG_INFO, "Theora bitstream version %X\n", s->theora);

    /* 3.2.0 aka alpha3 has the same frame orientation as original vp3 */

    /* but previous versions have the image flipped relative to vp3 */

    if (s->theora < 0x030200)

    {

        s->flipped_image = 1;

        av_log(avctx, AV_LOG_DEBUG, "Old (<alpha3) Theora bitstream, flipped image\n");

    }

    s->width = get_bits(&gb, 16) << 4;

    s->height = get_bits(&gb, 16) << 4;

    if(avcodec_check_dimensions(avctx, s->width, s->height)){

        av_log(avctx, AV_LOG_ERROR, "Invalid dimensions (%dx%d)\n", s->width, s->height);

        s->width= s->height= 0;

        return -1;

    }

    if (s->theora >= 0x030400)

    {

        skip_bits(&gb, 32); /* total number of superblocks in a frame */

        // fixme, the next field is 36bits long

        skip_bits(&gb, 32); /* total number of blocks in a frame */

        skip_bits(&gb, 4); /* total number of blocks in a frame */

        skip_bits(&gb, 32); /* total number of macroblocks in a frame */

        skip_bits(&gb, 24); /* frame width */

        skip_bits(&gb, 24); /* frame height */

    }

    else

    {

        skip_bits(&gb, 24); /* frame width */

        skip_bits(&gb, 24); /* frame height */

    }

    skip_bits(&gb, 8); /* offset x */

    skip_bits(&gb, 8); /* offset y */

    skip_bits(&gb, 32); /* fps numerator */

    skip_bits(&gb, 32); /* fps denumerator */

    skip_bits(&gb, 24); /* aspect numerator */

    skip_bits(&gb, 24); /* aspect denumerator */

    if (s->theora < 0x030200)

        skip_bits(&gb, 5); /* keyframe frequency force */

    skip_bits(&gb, 8); /* colorspace */

    if (s->theora >= 0x030400)

        skip_bits(&gb, 2); /* pixel format: 420,res,422,444 */

    skip_bits(&gb, 24); /* bitrate */

    skip_bits(&gb, 6); /* quality hint */

    if (s->theora >= 0x030200)

    {

        skip_bits(&gb, 5); /* keyframe frequency force */

        if (s->theora < 0x030400)

            skip_bits(&gb, 5); /* spare bits */

    }

//    align_get_bits(&gb);

    avctx->width = s->width;

    avctx->height = s->height;

    return 0;

}


static av_cold int init_buffers(SANMVideoContext *ctx)

{

    av_fast_padded_malloc(&ctx->frm0, &ctx->frm0_size, ctx->buf_size);

    av_fast_padded_malloc(&ctx->frm1, &ctx->frm1_size, ctx->buf_size);

    av_fast_padded_malloc(&ctx->frm2, &ctx->frm2_size, ctx->buf_size);

    if (!ctx->version)

        av_fast_padded_malloc(&ctx->stored_frame,

                              &ctx->stored_frame_size, ctx->buf_size);

    if (!ctx->frm0 || !ctx->frm1 || !ctx->frm2 ||

        (!ctx->stored_frame && !ctx->version)) {

        destroy_buffers(ctx);

        return AVERROR(ENOMEM);

    }

    return 0;

}


int unix_listen_opts(QemuOpts *opts)

{

    struct sockaddr_un un;

    const char *path = qemu_opt_get(opts, "path");

    int sock, fd;

    sock = socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        perror("socket(unix)");

        return -1;

    }

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

    un.sun_family = AF_UNIX;

    if (path && strlen(path)) {

        snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);

    } else {

        char *tmpdir = getenv("TMPDIR");

        snprintf(un.sun_path, sizeof(un.sun_path), "%s/qemu-socket-XXXXXX",

                 tmpdir ? tmpdir : "/tmp");

        /*

         * This dummy fd usage silences the mktemp() unsecure warning.

         * Using mkstemp() doesn't make things more secure here

         * though.  bind() complains about existing files, so we have

         * to unlink first and thus re-open the race window.  The

         * worst case possible is bind() failing, i.e. a DoS attack.

         */

        fd = mkstemp(un.sun_path); close(fd);

        qemu_opt_set(opts, "path", un.sun_path);

    }

    unlink(un.sun_path);

    if (bind(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

        fprintf(stderr, "bind(unix:%s): %s\n", un.sun_path, strerror(errno));

        goto err;

    }

    if (listen(sock, 1) < 0) {

        fprintf(stderr, "listen(unix:%s): %s\n", un.sun_path, strerror(errno));

        goto err;

    }

    if (sockets_debug)

        fprintf(stderr, "bind(unix:%s): OK\n", un.sun_path);

    return sock;

err:

    closesocket(sock);

    return -1;

}


static void bus_add_child(BusState *bus, DeviceState *child)

{

    char name[32];

    BusChild *kid = g_malloc0(sizeof(*kid));

    if (qdev_hotplug) {

        assert(bus->allow_hotplug);

    }

    kid->index = bus->max_index++;

    kid->child = child;

    object_ref(OBJECT(kid->child));

    QTAILQ_INSERT_HEAD(&bus->children, kid, sibling);

    /* This transfers ownership of kid->child to the property.  */

    snprintf(name, sizeof(name), "child[%d]", kid->index);

    object_property_add_link(OBJECT(bus), name,

                             object_get_typename(OBJECT(child)),

                             (Object **)&kid->child,

                             NULL);

}