static inline void vc1_pred_mv_intfr(VC1Context *v, int n, int dmv_x, int dmv_y,

                                     int mvn, int r_x, int r_y, uint8_t* is_intra, int dir)

{

    MpegEncContext *s = &v->s;

    int xy, wrap, off = 0;

    int A[2], B[2], C[2];

    int px = 0, py = 0;

    int a_valid = 0, b_valid = 0, c_valid = 0;

    int field_a, field_b, field_c; // 0: same, 1: opposit

    int total_valid, num_samefield, num_oppfield;

    int pos_c, pos_b, n_adj;

    wrap = s->b8_stride;

    xy = s->block_index[n];

    if (s->mb_intra) {

        s->mv[0][n][0] = s->current_picture.motion_val[0][xy][0] = 0;

        s->mv[0][n][1] = s->current_picture.motion_val[0][xy][1] = 0;

        s->current_picture.motion_val[1][xy][0] = 0;

        s->current_picture.motion_val[1][xy][1] = 0;

        if (mvn == 1) { /* duplicate motion data for 1-MV block */

            s->current_picture.motion_val[0][xy + 1][0]        = 0;

            s->current_picture.motion_val[0][xy + 1][1]        = 0;

            s->current_picture.motion_val[0][xy + wrap][0]     = 0;

            s->current_picture.motion_val[0][xy + wrap][1]     = 0;

            s->current_picture.motion_val[0][xy + wrap + 1][0] = 0;

            s->current_picture.motion_val[0][xy + wrap + 1][1] = 0;

            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;

            s->current_picture.motion_val[1][xy + 1][0]        = 0;

            s->current_picture.motion_val[1][xy + 1][1]        = 0;

            s->current_picture.motion_val[1][xy + wrap][0]     = 0;

            s->current_picture.motion_val[1][xy + wrap][1]     = 0;

            s->current_picture.motion_val[1][xy + wrap + 1][0] = 0;

            s->current_picture.motion_val[1][xy + wrap + 1][1] = 0;

        }

        return;

    }

    off = ((n == 0) || (n == 1)) ? 1 : -1;

    /* predict A */

    if (s->mb_x || (n == 1) || (n == 3)) {

        if ((v->blk_mv_type[xy]) // current block (MB) has a field MV

            || (!v->blk_mv_type[xy] && !v->blk_mv_type[xy - 1])) { // or both have frame MV

            A[0] = s->current_picture.motion_val[dir][xy - 1][0];

            A[1] = s->current_picture.motion_val[dir][xy - 1][1];

            a_valid = 1;

        } else { // current block has frame mv and cand. has field MV (so average)

            A[0] = (s->current_picture.motion_val[dir][xy - 1][0]

                    + s->current_picture.motion_val[dir][xy - 1 + off * wrap][0] + 1) >> 1;

            A[1] = (s->current_picture.motion_val[dir][xy - 1][1]

                    + s->current_picture.motion_val[dir][xy - 1 + off * wrap][1] + 1) >> 1;

            a_valid = 1;

        }

        if (!(n & 1) && v->is_intra[s->mb_x - 1]) {

            a_valid = 0;

            A[0] = A[1] = 0;

        }

    } else

        A[0] = A[1] = 0;

    /* Predict B and C */

    B[0] = B[1] = C[0] = C[1] = 0;

    if (n == 0 || n == 1 || v->blk_mv_type[xy]) {

        if (!s->first_slice_line) {

            if (!v->is_intra[s->mb_x - s->mb_stride]) {

                b_valid = 1;

                n_adj   = n | 2;

                pos_b   = s->block_index[n_adj] - 2 * wrap;

                if (v->blk_mv_type[pos_b] && v->blk_mv_type[xy]) {

                    n_adj = (n & 2) | (n & 1);

                }

                B[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap][0];

                B[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap][1];

                if (v->blk_mv_type[pos_b] && !v->blk_mv_type[xy]) {

                    B[0] = (B[0] + s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap][0] + 1) >> 1;

                    B[1] = (B[1] + s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap][1] + 1) >> 1;

                }

            }

            if (s->mb_width > 1) {

                if (!v->is_intra[s->mb_x - s->mb_stride + 1]) {

                    c_valid = 1;

                    n_adj   = 2;

                    pos_c   = s->block_index[2] - 2 * wrap + 2;

                    if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                        n_adj = n & 2;

                    }

                    C[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap + 2][0];

                    C[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap + 2][1];

                    if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                        C[0] = (1 + C[0] + (s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap + 2][0])) >> 1;

                        C[1] = (1 + C[1] + (s->current_picture.motion_val[dir][s->block_index[n_adj ^ 2] - 2 * wrap + 2][1])) >> 1;

                    }

                    if (s->mb_x == s->mb_width - 1) {

                        if (!v->is_intra[s->mb_x - s->mb_stride - 1]) {

                            c_valid = 1;

                            n_adj   = 3;

                            pos_c   = s->block_index[3] - 2 * wrap - 2;

                            if (v->blk_mv_type[pos_c] && v->blk_mv_type[xy]) {

                                n_adj = n | 1;

                            }

                            C[0] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap - 2][0];

                            C[1] = s->current_picture.motion_val[dir][s->block_index[n_adj] - 2 * wrap - 2][1];

                            if (v->blk_mv_type[pos_c] && !v->blk_mv_type[xy]) {

                                C[0] = (1 + C[0] + s->current_picture.motion_val[dir][s->block_index[1] - 2 * wrap - 2][0]) >> 1;

                                C[1] = (1 + C[1] + s->current_picture.motion_val[dir][s->block_index[1] - 2 * wrap - 2][1]) >> 1;

                            }

                        } else

                            c_valid = 0;

                    }

                }

            }

        }

    } else {

        pos_b   = s->block_index[1];

        b_valid = 1;

        B[0]    = s->current_picture.motion_val[dir][pos_b][0];

        B[1]    = s->current_picture.motion_val[dir][pos_b][1];

        pos_c   = s->block_index[0];

        c_valid = 1;

        C[0]    = s->current_picture.motion_val[dir][pos_c][0];

        C[1]    = s->current_picture.motion_val[dir][pos_c][1];

    }

    total_valid = a_valid + b_valid + c_valid;

    // check if predictor A is out of bounds

    if (!s->mb_x && !(n == 1 || n == 3)) {

        A[0] = A[1] = 0;

    }

    // check if predictor B is out of bounds

    if ((s->first_slice_line && v->blk_mv_type[xy]) || (s->first_slice_line && !(n & 2))) {

        B[0] = B[1] = C[0] = C[1] = 0;

    }

    if (!v->blk_mv_type[xy]) {

        if (s->mb_width == 1) {

            px = B[0];

            py = B[1];

        } else {

            if (total_valid >= 2) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (total_valid) {

                if      (a_valid) { px = A[0]; py = A[1]; }

                else if (b_valid) { px = B[0]; py = B[1]; }

                else if (c_valid) { px = C[0]; py = C[1]; }

                else av_assert2(0);

            }

        }

    } else {

        if (a_valid)

            field_a = (A[1] & 4) ? 1 : 0;

        else

            field_a = 0;

        if (b_valid)

            field_b = (B[1] & 4) ? 1 : 0;

        else

            field_b = 0;

        if (c_valid)

            field_c = (C[1] & 4) ? 1 : 0;

        else

            field_c = 0;

        num_oppfield  = field_a + field_b + field_c;

        num_samefield = total_valid - num_oppfield;

        if (total_valid == 3) {

            if ((num_samefield == 3) || (num_oppfield == 3)) {

                px = mid_pred(A[0], B[0], C[0]);

                py = mid_pred(A[1], B[1], C[1]);

            } else if (num_samefield >= num_oppfield) {

                /* take one MV from same field set depending on priority

                the check for B may not be necessary */

                px = !field_a ? A[0] : B[0];

                py = !field_a ? A[1] : B[1];

            } else {

                px =  field_a ? A[0] : B[0];

                py =  field_a ? A[1] : B[1];

            }

        } else if (total_valid == 2) {

            if (num_samefield >= num_oppfield) {

                if (!field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (!field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                } else px = py = 0;

            } else {

                if (field_a && a_valid) {

                    px = A[0];

                    py = A[1];

                } else if (field_b && b_valid) {

                    px = B[0];

                    py = B[1];

                } else if (c_valid) {

                    px = C[0];

                    py = C[1];

                }

            }

        } else if (total_valid == 1) {

            px = (a_valid) ? A[0] : ((b_valid) ? B[0] : C[0]);

            py = (a_valid) ? A[1] : ((b_valid) ? B[1] : C[1]);

        }

    }

    /* store MV using signed modulus of MV range defined in 4.11 */

    s->mv[dir][n][0] = s->current_picture.motion_val[dir][xy][0] = ((px + dmv_x + r_x) & ((r_x << 1) - 1)) - r_x;

    s->mv[dir][n][1] = s->current_picture.motion_val[dir][xy][1] = ((py + dmv_y + r_y) & ((r_y << 1) - 1)) - r_y;

    if (mvn == 1) { /* duplicate motion data for 1-MV block */

        s->current_picture.motion_val[dir][xy +    1    ][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy +    1    ][1] = s->current_picture.motion_val[dir][xy][1];

        s->current_picture.motion_val[dir][xy + wrap    ][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + wrap    ][1] = s->current_picture.motion_val[dir][xy][1];

        s->current_picture.motion_val[dir][xy + wrap + 1][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + wrap + 1][1] = s->current_picture.motion_val[dir][xy][1];

    } else if (mvn == 2) { /* duplicate motion data for 2-Field MV block */

        s->current_picture.motion_val[dir][xy + 1][0] = s->current_picture.motion_val[dir][xy][0];

        s->current_picture.motion_val[dir][xy + 1][1] = s->current_picture.motion_val[dir][xy][1];

        s->mv[dir][n + 1][0] = s->mv[dir][n][0];

        s->mv[dir][n + 1][1] = s->mv[dir][n][1];

    }

}


static void free_buffers(VP8Context *s)

{

    int i;

    if (s->thread_data)

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

            av_freep(&s->thread_data[i].filter_strength);

            av_freep(&s->thread_data[i].edge_emu_buffer);

        }

    av_freep(&s->thread_data);

    av_freep(&s->macroblocks_base);

    av_freep(&s->intra4x4_pred_mode_top);

    av_freep(&s->top_nnz);

    av_freep(&s->top_border);

    s->macroblocks = NULL;

}


static void intel_hda_realize(PCIDevice *pci, Error **errp)

{

    IntelHDAState *d = INTEL_HDA(pci);

    uint8_t *conf = d->pci.config;

    d->name = object_get_typename(OBJECT(d));

    pci_config_set_interrupt_pin(conf, 1);

    /* HDCTL off 0x40 bit 0 selects signaling mode (1-HDA, 0 - Ac97) 18.1.19 */

    conf[0x40] = 0x01;

    memory_region_init_io(&d->mmio, OBJECT(d), &intel_hda_mmio_ops, d,

                          "intel-hda", 0x4000);

    pci_register_bar(&d->pci, 0, 0, &d->mmio);

    if (d->msi != ON_OFF_AUTO_OFF) {

         /* TODO check for errors */

        msi_init(&d->pci, d->old_msi_addr ? 0x50 : 0x60, 1, true, false);

    }

    hda_codec_bus_init(DEVICE(pci), &d->codecs, sizeof(d->codecs),

                       intel_hda_response, intel_hda_xfer);

}


static void vnc_dpy_copy(DisplayChangeListener *dcl,

                         int src_x, int src_y,

                         int dst_x, int dst_y, int w, int h)

{

    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);

    VncState *vs, *vn;

    uint8_t *src_row;

    uint8_t *dst_row;

    int i, x, y, pitch, inc, w_lim, s;

    int cmp_bytes;

    vnc_refresh_server_surface(vd);

    QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {

        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {

            vs->force_update = 1;

            vnc_update_client(vs, 1, true);

            /* vs might be free()ed here */

    /* do bitblit op on the local surface too */

    pitch = vnc_server_fb_stride(vd);

    src_row = vnc_server_fb_ptr(vd, src_x, src_y);

    dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);

    y = dst_y;

    inc = 1;

    if (dst_y > src_y) {

        /* copy backwards */

        src_row += pitch * (h-1);

        dst_row += pitch * (h-1);

        pitch = -pitch;

        y = dst_y + h - 1;

        inc = -1;

    w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));

    if (w_lim < 0) {

        w_lim = w;

    } else {

        w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);

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

        for (x = 0; x <= w_lim;

                x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {

            if (x == w_lim) {

                if ((s = w - w_lim) == 0)

                    break;

            } else if (!x) {

                s = (VNC_DIRTY_PIXELS_PER_BIT -

                    (dst_x % VNC_DIRTY_PIXELS_PER_BIT));

                s = MIN(s, w_lim);

            } else {

                s = VNC_DIRTY_PIXELS_PER_BIT;

            cmp_bytes = s * VNC_SERVER_FB_BYTES;

            if (memcmp(src_row, dst_row, cmp_bytes) == 0)

                continue;

            memmove(dst_row, src_row, cmp_bytes);

            QTAILQ_FOREACH(vs, &vd->clients, next) {

                if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {

                    set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),

                            vs->dirty[y]);

        src_row += pitch - w * VNC_SERVER_FB_BYTES;

        dst_row += pitch - w * VNC_SERVER_FB_BYTES;

        y += inc;

    QTAILQ_FOREACH(vs, &vd->clients, next) {

        if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {

            vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);


static int write_refcount_block_entries(BlockDriverState *bs,
    int64_t refcount_block_offset, int first_index, int last_index)
{
    BDRVQcowState *s = bs->opaque;
    size_t size;
    int ret;
    if (cache_refcount_updates) {
    first_index &= ~(REFCOUNTS_PER_SECTOR - 1);
    last_index = (last_index + REFCOUNTS_PER_SECTOR)
        & ~(REFCOUNTS_PER_SECTOR - 1);
    size = (last_index - first_index) << REFCOUNT_SHIFT;
    BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_UPDATE_PART);
    ret = bdrv_pwrite(bs->file,
        refcount_block_offset + (first_index << REFCOUNT_SHIFT),
        &s->refcount_block_cache[first_index], size);
    if (ret < 0) {
        return ret;


static int qemu_rdma_source_init(RDMAContext *rdma, Error **errp, bool pin_all)

{

    int ret, idx;

    Error *local_err = NULL, **temp = &local_err;

    /*

     * Will be validated against destination's actual capabilities

     * after the connect() completes.

     */

    rdma->pin_all = pin_all;

    ret = qemu_rdma_resolve_host(rdma, temp);

    if (ret) {

        goto err_rdma_source_init;

    }

    ret = qemu_rdma_alloc_pd_cq(rdma);

    if (ret) {

        ERROR(temp, "rdma migration: error allocating pd and cq! Your mlock()"

                    " limits may be too low. Please check $ ulimit -a # and "

                    "search for 'ulimit -l' in the output");

        goto err_rdma_source_init;

    }

    ret = qemu_rdma_alloc_qp(rdma);

    if (ret) {

        ERROR(temp, "rdma migration: error allocating qp!");

        goto err_rdma_source_init;

    }

    ret = qemu_rdma_init_ram_blocks(rdma);

    if (ret) {

        ERROR(temp, "rdma migration: error initializing ram blocks!");

        goto err_rdma_source_init;

    }

    for (idx = 0; idx < RDMA_WRID_MAX; idx++) {

        ret = qemu_rdma_reg_control(rdma, idx);

        if (ret) {

            ERROR(temp, "rdma migration: error registering %d control!",

                                                            idx);

            goto err_rdma_source_init;

        }

    }

    return 0;

err_rdma_source_init:

    error_propagate(errp, local_err);

    qemu_rdma_cleanup(rdma);

    return -1;

}


static int curl_open(BlockDriverState *bs, QDict *options, int flags,
                     Error **errp)
{
    BDRVCURLState *s = bs->opaque;
    CURLState *state = NULL;
    QemuOpts *opts;
    Error *local_err = NULL;
    const char *file;
    double d;
    static int inited = 0;
    if (flags & BDRV_O_RDWR) {
        error_setg(errp, "curl block device does not support writes");
        return -EROFS;
    }
    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out_noclean;
    }
    s->readahead_size = qemu_opt_get_size(opts, CURL_BLOCK_OPT_READAHEAD,
                                          READ_AHEAD_DEFAULT);
    if ((s->readahead_size & 0x1ff) != 0) {
        error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
                   s->readahead_size);
        goto out_noclean;
    }
    file = qemu_opt_get(opts, CURL_BLOCK_OPT_URL);
    if (file == NULL) {
        error_setg(errp, "curl block driver requires an 'url' option");
        goto out_noclean;
    }
    if (!inited) {
        curl_global_init(CURL_GLOBAL_ALL);
        inited = 1;
    }
    DPRINTF("CURL: Opening %s\n", file);
    s->url = g_strdup(file);
    state = curl_init_state(s);
    if (!state)
        goto out_noclean;
    // Get file size
    s->accept_range = false;
    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
    curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
                     curl_header_cb);
    curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
    if (curl_easy_perform(state->curl))
        goto out;
    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);
    if (d)
        s->len = (size_t)d;
    else if(!s->len)
        goto out;
    if ((!strncasecmp(s->url, "http://", strlen("http://"))
        || !strncasecmp(s->url, "https://", strlen("https://")))
        && !s->accept_range) {
        pstrcpy(state->errmsg, CURL_ERROR_SIZE,
                "Server does not support 'range' (byte ranges).");
        goto out;
    }
    DPRINTF("CURL: Size = %zd\n", s->len);
    curl_clean_state(state);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;
    aio_timer_init(bdrv_get_aio_context(bs), &s->timer,
                   QEMU_CLOCK_REALTIME, SCALE_NS,
                   curl_multi_timeout_do, s);
    // Now we know the file exists and its size, so let's
    // initialize the multi interface!
    s->multi = curl_multi_init();
    curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
#ifdef NEED_CURL_TIMER_CALLBACK
    curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
    curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
#endif
    qemu_opts_del(opts);
    return 0;
out:
    error_setg(errp, "CURL: Error opening file: %s", state->errmsg);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;
out_noclean:
    g_free(s->url);
    qemu_opts_del(opts);
    return -EINVAL;
}


static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
    int delay = FFMAX(st->codec->has_b_frames, st->codec->max_b_frames > 0);
    int num, den, frame_size, i;
    av_dlog(s, "compute_pkt_fields2: pts:%s dts:%s cur_dts:%s b:%d size:%d st:%d\n",
            av_ts2str(pkt->pts), av_ts2str(pkt->dts), av_ts2str(st->cur_dts), delay, pkt->size, pkt->stream_index);
    /* duration field */
    if (pkt->duration == 0) {
        ff_compute_frame_duration(&num, &den, st, NULL, pkt);
        if (den && num) {
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
    if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
        pkt->pts = pkt->dts;
    //XXX/FIXME this is a temporary hack until all encoders output pts
    if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
        static int warned;
        if (!warned) {
            av_log(s, AV_LOG_WARNING, "Encoder did not produce proper pts, making some up.\n");
            warned = 1;
        pkt->dts =
//        pkt->pts= st->cur_dts;
            pkt->pts = st->pts.val;
    //calculate dts from pts
    if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
        st->pts_buffer[0] = pkt->pts;
        for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
            st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
        for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
        pkt->dts = st->pts_buffer[0];
    if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
        ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
          st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
        av_log(s, AV_LOG_ERROR,
               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %s >= %s\n",
               st->index, av_ts2str(st->cur_dts), av_ts2str(pkt->dts));
        return AVERROR(EINVAL);
    if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
        av_log(s, AV_LOG_ERROR, "pts (%s) < dts (%s) in stream %d\n",
               av_ts2str(pkt->pts), av_ts2str(pkt->dts), st->index);
        return AVERROR(EINVAL);
    av_dlog(s, "av_write_frame: pts2:%s dts2:%s\n",
            av_ts2str(pkt->pts), av_ts2str(pkt->dts));
    st->cur_dts = pkt->dts;
    st->pts.val = pkt->dts;
    /* update pts */
    switch (st->codec->codec_type) {
    case AVMEDIA_TYPE_AUDIO:
        frame_size = (pkt->flags & AV_PKT_FLAG_UNCODED_FRAME) ?
                     ((AVFrame *)pkt->data)->nb_samples :
                     ff_get_audio_frame_size(st->codec, pkt->size, 1);
        /* HACK/FIXME, we skip the initial 0 size packets as they are most
         * likely equal to the encoder delay, but it would be better if we
         * had the real timestamps from the encoder */
        if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
            frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
        break;
    case AVMEDIA_TYPE_VIDEO:
        frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
        break;
    default:
        break;
    return 0;


int qemu_get_fd(QEMUFile *f)

{

    if (f->ops->get_fd) {

        return f->ops->get_fd(f->opaque);

    }

    return -1;

}


static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
    QDict *options, int flags, BlockDriver *drv, Error **errp)
{
    int ret, open_flags;
    const char *filename;
    const char *node_name = NULL;
    Error *local_err = NULL;
    assert(drv != NULL);
    assert(bs->file == NULL);
    assert(options != NULL && bs->options != options);
    if (file != NULL) {
        filename = file->filename;
    } else {
        filename = qdict_get_try_str(options, "filename");
    if (drv->bdrv_needs_filename && !filename) {
        error_setg(errp, "The '%s' block driver requires a file name",
                   drv->format_name);
        return -EINVAL;
    trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
    node_name = qdict_get_try_str(options, "node-name");
    bdrv_assign_node_name(bs, node_name, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return -EINVAL;
    qdict_del(options, "node-name");
    /* bdrv_open() with directly using a protocol as drv. This layer is already
     * opened, so assign it to bs (while file becomes a closed BlockDriverState)
     * and return immediately. */
    if (file != NULL && drv->bdrv_file_open) {
        bdrv_swap(file, bs);
        return 0;
    bs->open_flags = flags;
    bs->guest_block_size = 512;
    bs->request_alignment = 512;
    bs->zero_beyond_eof = true;
    open_flags = bdrv_open_flags(bs, flags);
    bs->read_only = !(open_flags & BDRV_O_RDWR);
    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
        error_setg(errp,
                   !bs->read_only && bdrv_is_whitelisted(drv, true)
                        ? "Driver '%s' can only be used for read-only devices"
                        : "Driver '%s' is not whitelisted",
                   drv->format_name);
        return -ENOTSUP;
    assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
    if (flags & BDRV_O_COPY_ON_READ) {
        if (!bs->read_only) {
            bdrv_enable_copy_on_read(bs);
        } else {
            error_setg(errp, "Can't use copy-on-read on read-only device");
            return -EINVAL;
    if (filename != NULL) {
        pstrcpy(bs->filename, sizeof(bs->filename), filename);
    } else {
        bs->filename[0] = '\0';
    pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
    bs->drv = drv;
    bs->opaque = g_malloc0(drv->instance_size);
    bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
    /* Open the image, either directly or using a protocol */
    if (drv->bdrv_file_open) {
        assert(file == NULL);
        assert(!drv->bdrv_needs_filename || filename != NULL);
        ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
    } else {
        if (file == NULL) {
            error_setg(errp, "Can't use '%s' as a block driver for the "
                       "protocol level", drv->format_name);
            ret = -EINVAL;
            goto free_and_fail;
        bs->file = file;
        ret = drv->bdrv_open(bs, options, open_flags, &local_err);
    if (ret < 0) {
        if (local_err) {
            error_propagate(errp, local_err);
        } else if (bs->filename[0]) {
            error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
        } else {
            error_setg_errno(errp, -ret, "Could not open image");
        goto free_and_fail;
    ret = refresh_total_sectors(bs, bs->total_sectors);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not refresh total sector count");
        goto free_and_fail;
    bdrv_refresh_limits(bs, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto free_and_fail;
    assert(bdrv_opt_mem_align(bs) != 0);
    assert((bs->request_alignment != 0) || bs->sg);
    return 0;
free_and_fail:
    bs->file = NULL;
    g_free(bs->opaque);
    bs->opaque = NULL;
    bs->drv = NULL;
    return ret;


static int virtio_serial_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIOSerial *s = opaque;

    VirtIOSerialPort *port;

    uint32_t max_nr_ports, nr_active_ports, ports_map;

    unsigned int i;

    if (version_id > 3) {

    /* The virtio device */

    virtio_load(&s->vdev, f);

    if (version_id < 2) {

        return 0;

    /* The config space */

    qemu_get_be16s(f, &s->config.cols);

    qemu_get_be16s(f, &s->config.rows);

    qemu_get_be32s(f, &max_nr_ports);

    if (max_nr_ports > s->config.max_nr_ports) {

        /* Source could have had more ports than us. Fail migration. */

    for (i = 0; i < (max_nr_ports + 31) / 32; i++) {

        qemu_get_be32s(f, &ports_map);

        if (ports_map != s->ports_map[i]) {

            /*

             * Ports active on source and destination don't

             * match. Fail migration.

             */

    qemu_get_be32s(f, &nr_active_ports);

    /* Items in struct VirtIOSerialPort */

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

        uint32_t id;

        bool host_connected;

        id = qemu_get_be32(f);

        port = find_port_by_id(s, id);

        port->guest_connected = qemu_get_byte(f);

        host_connected = qemu_get_byte(f);

        if (host_connected != port->host_connected) {

            /*

             * We have to let the guest know of the host connection

             * status change

             */

            send_control_event(port, VIRTIO_CONSOLE_PORT_OPEN,

                               port->host_connected);

        if (version_id > 2) {

            uint32_t elem_popped;

            qemu_get_be32s(f, &elem_popped);

            if (elem_popped) {

                qemu_get_be32s(f, &port->iov_idx);

                qemu_get_be64s(f, &port->iov_offset);

                qemu_get_buffer(f, (unsigned char *)&port->elem,

                                sizeof(port->elem));

                virtqueue_map_sg(port->elem.in_sg, port->elem.in_addr,

                                 port->elem.in_num, 1);

                virtqueue_map_sg(port->elem.out_sg, port->elem.out_addr,

                                 port->elem.out_num, 1);

                /*

                 *  Port was throttled on source machine.  Let's

                 *  unthrottle it here so data starts flowing again.

                 */

                virtio_serial_throttle_port(port, false);

    return 0;


static int cdg_decode_frame(AVCodecContext *avctx,

                            void *data, int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    int ret;

    uint8_t command, inst;

    uint8_t cdg_data[CDG_DATA_SIZE];

    AVFrame *frame = data;

    CDGraphicsContext *cc = avctx->priv_data;

    if (buf_size < CDG_MINIMUM_PKT_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "buffer too small for decoder\n");

        return AVERROR(EINVAL);

    }

    if (buf_size > CDG_HEADER_SIZE + CDG_DATA_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "buffer too big for decoder\n");

        return AVERROR(EINVAL);

    }

    if ((ret = ff_reget_buffer(avctx, cc->frame)) < 0)

        return ret;

    if (!avctx->frame_number) {

        memset(cc->frame->data[0], 0, cc->frame->linesize[0] * avctx->height);

        memset(cc->frame->data[1], 0, AVPALETTE_SIZE);

    }

    command = bytestream_get_byte(&buf);

    inst    = bytestream_get_byte(&buf);

    inst    &= CDG_MASK;

    buf += 2;  /// skipping 2 unneeded bytes

    if (buf_size > CDG_HEADER_SIZE)

        bytestream_get_buffer(&buf, cdg_data, buf_size - CDG_HEADER_SIZE);

    if ((command & CDG_MASK) == CDG_COMMAND) {

        switch (inst) {

        case CDG_INST_MEMORY_PRESET:

            if (!(cdg_data[1] & 0x0F))

                memset(cc->frame->data[0], cdg_data[0] & 0x0F,

                       cc->frame->linesize[0] * CDG_FULL_HEIGHT);

            break;

        case CDG_INST_LOAD_PAL_LO:

        case CDG_INST_LOAD_PAL_HIGH:

            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for loading palette\n");

                return AVERROR(EINVAL);

            }

            cdg_load_palette(cc, cdg_data, inst == CDG_INST_LOAD_PAL_LO);

            break;

        case CDG_INST_BORDER_PRESET:

            cdg_border_preset(cc, cdg_data);

            break;

        case CDG_INST_TILE_BLOCK_XOR:

        case CDG_INST_TILE_BLOCK:

            if (buf_size - CDG_HEADER_SIZE < CDG_DATA_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for drawing tile\n");

                return AVERROR(EINVAL);

            }

            ret = cdg_tile_block(cc, cdg_data, inst == CDG_INST_TILE_BLOCK_XOR);

            if (ret) {

                av_log(avctx, AV_LOG_ERROR, "tile is out of range\n");

                return ret;

            }

            break;

        case CDG_INST_SCROLL_PRESET:

        case CDG_INST_SCROLL_COPY:

            if (buf_size - CDG_HEADER_SIZE < CDG_MINIMUM_SCROLL_SIZE) {

                av_log(avctx, AV_LOG_ERROR, "buffer too small for scrolling\n");

                return AVERROR(EINVAL);

            }

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

                return ret;

            cdg_scroll(cc, cdg_data, frame, inst == CDG_INST_SCROLL_COPY);

            av_frame_unref(cc->frame);

            ret = av_frame_ref(cc->frame, frame);

            if (ret < 0)

                return ret;

            break;

        default:

            break;

        }

        if (!frame->data[0]) {

            ret = av_frame_ref(frame, cc->frame);

            if (ret < 0)

                return ret;

        }

        *got_frame = 1;

    } else {

        *got_frame = 0;

        buf_size   = 0;

    }

    return buf_size;

}


static int nut_write_header(AVFormatContext *s)

{

    NUTContext *nut = s->priv_data;

    ByteIOContext *bc = &s->pb;

    AVCodecContext *codec;

    int i, j, tmp_time, tmp_flags,tmp_stream, tmp_mul, tmp_size, tmp_fields;

    nut->avf= s;

    nut->stream =

	av_mallocz(sizeof(StreamContext)*s->nb_streams);

    put_buffer(bc, ID_STRING, strlen(ID_STRING));

    put_byte(bc, 0);

    nut->packet_start[2]= url_ftell(bc);

    /* main header */

    put_be64(bc, MAIN_STARTCODE);

    put_packetheader(nut, bc, 120+5*256, 1);

    put_v(bc, 2); /* version */

    put_v(bc, s->nb_streams);

    put_v(bc, MAX_DISTANCE);

    put_v(bc, MAX_SHORT_DISTANCE);

    put_v(bc, nut->rate_num=1);

    put_v(bc, nut->rate_den=2);

    put_v(bc, nut->short_startcode=0x4EFE79);

    build_frame_code(s);

    assert(nut->frame_code['N'].flags == FLAG_INVALID);

    tmp_time= tmp_flags= tmp_stream= tmp_mul= tmp_size= /*tmp_res=*/ INT_MAX;

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

        tmp_fields=0;

        tmp_size= 0;

        if(tmp_time   != nut->frame_code[i].timestamp_delta) tmp_fields=1;

        if(tmp_mul    != nut->frame_code[i].size_mul       ) tmp_fields=2;

        if(tmp_stream != nut->frame_code[i].stream_id_plus1) tmp_fields=3;

        if(tmp_size   != nut->frame_code[i].size_lsb       ) tmp_fields=4;

//        if(tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;

        tmp_time  = nut->frame_code[i].timestamp_delta;

        tmp_flags = nut->frame_code[i].flags;

        tmp_stream= nut->frame_code[i].stream_id_plus1;

        tmp_mul   = nut->frame_code[i].size_mul;

        tmp_size  = nut->frame_code[i].size_lsb;

//        tmp_res   = nut->frame_code[i].res;

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

            if(nut->frame_code[i].timestamp_delta != tmp_time  ) break;

            if(nut->frame_code[i].flags           != tmp_flags ) break;

            if(nut->frame_code[i].stream_id_plus1 != tmp_stream) break;

            if(nut->frame_code[i].size_mul        != tmp_mul   ) break;

            if(nut->frame_code[i].size_lsb        != tmp_size+j) break;

//            if(nut->frame_code[i].res             != tmp_res   ) break;

        }

        if(j != tmp_mul - tmp_size) tmp_fields=6;

        put_v(bc, tmp_flags);

        put_v(bc, tmp_fields);

        if(tmp_fields>0) put_s(bc, tmp_time);

        if(tmp_fields>1) put_v(bc, tmp_mul);

        if(tmp_fields>2) put_v(bc, tmp_stream);

        if(tmp_fields>3) put_v(bc, tmp_size);

        if(tmp_fields>4) put_v(bc, 0 /*tmp_res*/);

        if(tmp_fields>5) put_v(bc, j);

    }

    update_packetheader(nut, bc, 0, 1);

    /* stream headers */

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

    {

	int nom, denom, gcd;

	codec = &s->streams[i]->codec;

	put_be64(bc, STREAM_STARTCODE);

	put_packetheader(nut, bc, 120 + codec->extradata_size, 1);

	put_v(bc, i /*s->streams[i]->index*/);

	put_v(bc, (codec->codec_type == CODEC_TYPE_AUDIO) ? 32 : 0);

	if (codec->codec_tag)

	    put_vb(bc, codec->codec_tag);

	else if (codec->codec_type == CODEC_TYPE_VIDEO)

	{

	    put_vb(bc, codec_get_bmp_tag(codec->codec_id));

	}

	else if (codec->codec_type == CODEC_TYPE_AUDIO)

	{

	    put_vb(bc, codec_get_wav_tag(codec->codec_id));

	}

        else

            put_vb(bc, 0);

	if (codec->codec_type == CODEC_TYPE_VIDEO)

	{

	    nom = codec->time_base.den;

	    denom = codec->time_base.num;

	}

	else

	{

	    nom = codec->sample_rate;

            if(codec->frame_size>0)

                denom= codec->frame_size;

            else

                denom= 1; //unlucky

	}

        gcd= ff_gcd(nom, denom);

        nom   /= gcd;

        denom /= gcd;

        nut->stream[i].rate_num= nom;

        nut->stream[i].rate_den= denom;

        av_set_pts_info(s->streams[i], 60, denom, nom);

	put_v(bc, codec->bit_rate);

	put_vb(bc, 0); /* no language code */

	put_v(bc, nom);

	put_v(bc, denom);

        if(nom / denom < 1000)

	    nut->stream[i].msb_timestamp_shift = 7;

        else

	    nut->stream[i].msb_timestamp_shift = 14;

	put_v(bc, nut->stream[i].msb_timestamp_shift);

        put_v(bc, codec->has_b_frames);

	put_byte(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */

        if(codec->extradata_size){

            put_v(bc, 1);

            put_v(bc, codec->extradata_size);

            put_buffer(bc, codec->extradata, codec->extradata_size);

        }

	put_v(bc, 0); /* end of codec specific headers */

	switch(codec->codec_type)

	{

	    case CODEC_TYPE_AUDIO:

		put_v(bc, codec->sample_rate);

		put_v(bc, 1);

		put_v(bc, codec->channels);

		break;

	    case CODEC_TYPE_VIDEO:

		put_v(bc, codec->width);

		put_v(bc, codec->height);

		put_v(bc, codec->sample_aspect_ratio.num);

		put_v(bc, codec->sample_aspect_ratio.den);

		put_v(bc, 0); /* csp type -- unknown */

		break;

            default:

                break;

	}

        update_packetheader(nut, bc, 0, 1);

    }

    /* info header */

    put_be64(bc, INFO_STARTCODE);

    put_packetheader(nut, bc, 30+strlen(s->author)+strlen(s->title)+

        strlen(s->comment)+strlen(s->copyright)+strlen(LIBAVFORMAT_IDENT), 1);

    if (s->author[0])

    {

        put_v(bc, 9); /* type */

        put_str(bc, s->author);

    }

    if (s->title[0])

    {

        put_v(bc, 10); /* type */

        put_str(bc, s->title);

    }

    if (s->comment[0])

    {

        put_v(bc, 11); /* type */

        put_str(bc, s->comment);

    }

    if (s->copyright[0])

    {

        put_v(bc, 12); /* type */

        put_str(bc, s->copyright);

    }

    /* encoder */

    if(!(s->streams[0]->codec.flags & CODEC_FLAG_BITEXACT)){

        put_v(bc, 13); /* type */

        put_str(bc, LIBAVFORMAT_IDENT);

    }

    put_v(bc, 0); /* eof info */

    update_packetheader(nut, bc, 0, 1);

    put_flush_packet(bc);

    return 0;

}


static inline int IRQ_testbit(IRQ_queue_t *q, int n_IRQ)

{

    return test_bit(q->queue, n_IRQ);

}


static int vmdk_write_compressed(BlockDriverState *bs,

                                 int64_t sector_num,

                                 const uint8_t *buf,

                                 int nb_sectors)

{

    BDRVVmdkState *s = bs->opaque;

    if (s->num_extents == 1 && s->extents[0].compressed) {

        Coroutine *co;

        AioContext *aio_context = bdrv_get_aio_context(bs);

        VmdkWriteCompressedCo data = {

            .bs         = bs,

            .sector_num = sector_num,

            .buf        = buf,

            .nb_sectors = nb_sectors,

            .ret        = -EINPROGRESS,

        };

        co = qemu_coroutine_create(vmdk_co_write_compressed);

        qemu_coroutine_enter(co, &data);

        while (data.ret == -EINPROGRESS) {

            aio_poll(aio_context, true);

        }

        return data.ret;

    } else {

        return -ENOTSUP;

    }

}


static int tight_compress_data(VncState *vs, int stream_id, size_t bytes,

                               int level, int strategy)

{

    z_streamp zstream = &vs->tight.stream[stream_id];

    int previous_out;

    if (bytes < VNC_TIGHT_MIN_TO_COMPRESS) {

        vnc_write(vs, vs->tight.tight.buffer, vs->tight.tight.offset);

        return bytes;

    }

    if (tight_init_stream(vs, stream_id, level, strategy)) {

        return -1;

    }

    /* reserve memory in output buffer */

    buffer_reserve(&vs->tight.zlib, bytes + 64);

    /* set pointers */

    zstream->next_in = vs->tight.tight.buffer;

    zstream->avail_in = vs->tight.tight.offset;

    zstream->next_out = vs->tight.zlib.buffer + vs->tight.zlib.offset;

    zstream->avail_out = vs->tight.zlib.capacity - vs->tight.zlib.offset;

    zstream->data_type = Z_BINARY;

    previous_out = zstream->total_out;

    /* start encoding */

    if (deflate(zstream, Z_SYNC_FLUSH) != Z_OK) {

        fprintf(stderr, "VNC: error during tight compression\n");

        return -1;

    }

    vs->tight.zlib.offset = vs->tight.zlib.capacity - zstream->avail_out;

    bytes = zstream->total_out - previous_out;

    tight_send_compact_size(vs, bytes);

    vnc_write(vs, vs->tight.zlib.buffer, bytes);

    buffer_reset(&vs->tight.zlib);

    return bytes;

}


static void do_tb_flush(CPUState *cpu, run_on_cpu_data tb_flush_count)

{

    tb_lock();

    /* If it is already been done on request of another CPU,

     * just retry.

     */

    if (tcg_ctx.tb_ctx.tb_flush_count != tb_flush_count.host_int) {

        goto done;

    }

#if defined(DEBUG_TB_FLUSH)

    printf("qemu: flush code_size=%ld nb_tbs=%d avg_tb_size=%ld\n",

           (unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer),

           tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.tb_ctx.nb_tbs > 0 ?

           ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)) /

           tcg_ctx.tb_ctx.nb_tbs : 0);

#endif

    if ((unsigned long)(tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer)

        > tcg_ctx.code_gen_buffer_size) {

        cpu_abort(cpu, "Internal error: code buffer overflow\n");

    }

    CPU_FOREACH(cpu) {

        int i;

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

            atomic_set(&cpu->tb_jmp_cache[i], NULL);

        }

    }

    tcg_ctx.tb_ctx.nb_tbs = 0;

    qht_reset_size(&tcg_ctx.tb_ctx.htable, CODE_GEN_HTABLE_SIZE);

    page_flush_tb();

    tcg_ctx.code_gen_ptr = tcg_ctx.code_gen_buffer;

    /* XXX: flush processor icache at this point if cache flush is

       expensive */

    atomic_mb_set(&tcg_ctx.tb_ctx.tb_flush_count,

                  tcg_ctx.tb_ctx.tb_flush_count + 1);

done:

    tb_unlock();

}


int v9fs_co_st_gen(V9fsPDU *pdu, V9fsPath *path, mode_t st_mode,

                   V9fsStatDotl *v9stat)

{

    int err = 0;

    V9fsState *s = pdu->s;

    if (v9fs_request_cancelled(pdu)) {

        return -EINTR;

    if (s->ctx.exops.get_st_gen) {

        v9fs_path_read_lock(s);

        v9fs_co_run_in_worker(

            {

                err = s->ctx.exops.get_st_gen(&s->ctx, path, st_mode,

                                              &v9stat->st_gen);

                if (err < 0) {

                    err = -errno;

            });

        v9fs_path_unlock(s);

    return err;


int avpicture_fill(AVPicture *picture, uint8_t *ptr,

                   enum AVPixelFormat pix_fmt, int width, int height)

{

    int ret;

    if ((ret = av_image_check_size(width, height, 0, NULL)) < 0)

        return ret;

    if ((ret = av_image_fill_linesizes(picture->linesize, pix_fmt, width)) < 0)

        return ret;

    return av_image_fill_pointers(picture->data, pix_fmt,

                                  height, ptr, picture->linesize);

}


static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,

                            const char *node_name, QDict *options,

                            int open_flags, Error **errp)

{

    Error *local_err = NULL;

    int ret;

    bdrv_assign_node_name(bs, node_name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return -EINVAL;

    }

    bs->drv = drv;

    bs->read_only = !(bs->open_flags & BDRV_O_RDWR);

    bs->opaque = g_malloc0(drv->instance_size);

    if (drv->bdrv_file_open) {

        assert(!drv->bdrv_needs_filename || bs->filename[0]);

        ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);

    } else if (drv->bdrv_open) {

        ret = drv->bdrv_open(bs, options, open_flags, &local_err);

    } else {

        ret = 0;

    }

    if (ret < 0) {

        if (local_err) {

            error_propagate(errp, local_err);

        } else if (bs->filename[0]) {

            error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);

        } else {

            error_setg_errno(errp, -ret, "Could not open image");

        }

        goto free_and_fail;

    }

    ret = refresh_total_sectors(bs, bs->total_sectors);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not refresh total sector count");

        goto free_and_fail;

    }

    bdrv_refresh_limits(bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto free_and_fail;

    }

    assert(bdrv_opt_mem_align(bs) != 0);

    assert(bdrv_min_mem_align(bs) != 0);

    assert(is_power_of_2(bs->bl.request_alignment));

    return 0;

free_and_fail:

    /* FIXME Close bs first if already opened*/

    g_free(bs->opaque);

    bs->opaque = NULL;

    bs->drv = NULL;

    return ret;

}


static int set_params(AVFilterContext *ctx, const char *params)
{
    Frei0rContext *frei0r = ctx->priv;
    int i;
    for (i = 0; i < frei0r->plugin_info.num_params; i++) {
        f0r_param_info_t info;
        char *param;
        int ret;
        frei0r->get_param_info(&info, i);
        if (*params) {
            if (!(param = av_get_token(&params, "|")))
                return AVERROR(ENOMEM);
            params++;               /* skip ':' */
            ret = set_param(ctx, info, i, param);
            av_free(param);
            if (ret < 0)
                return ret;
        }
        av_log(ctx, AV_LOG_VERBOSE,
               "idx:%d name:'%s' type:%s explanation:'%s' ",
               i, info.name,
               info.type == F0R_PARAM_BOOL     ? "bool"     :
               info.type == F0R_PARAM_DOUBLE   ? "double"   :
               info.type == F0R_PARAM_COLOR    ? "color"    :
               info.type == F0R_PARAM_POSITION ? "position" :
               info.type == F0R_PARAM_STRING   ? "string"   : "unknown",
               info.explanation);
#ifdef DEBUG
        av_log(ctx, AV_LOG_DEBUG, "value:");
        switch (info.type) {
            void *v;
            double d;
            char s[128];
            f0r_param_color_t col;
            f0r_param_position_t pos;
        case F0R_PARAM_BOOL:
            v = &d;
            frei0r->get_param_value(frei0r->instance, v, i);
            av_log(ctx, AV_LOG_DEBUG, "%s", d >= 0.5 && d <= 1.0 ? "y" : "n");
            break;
        case F0R_PARAM_DOUBLE:
            v = &d;
            frei0r->get_param_value(frei0r->instance, v, i);
            av_log(ctx, AV_LOG_DEBUG, "%f", d);
            break;
        case F0R_PARAM_COLOR:
            v = &col;
            frei0r->get_param_value(frei0r->instance, v, i);
            av_log(ctx, AV_LOG_DEBUG, "%f/%f/%f", col.r, col.g, col.b);
            break;
        case F0R_PARAM_POSITION:
            v = &pos;
            frei0r->get_param_value(frei0r->instance, v, i);
            av_log(ctx, AV_LOG_DEBUG, "%f/%f", pos.x, pos.y);
            break;
        default: /* F0R_PARAM_STRING */
            v = s;
            frei0r->get_param_value(frei0r->instance, v, i);
            av_log(ctx, AV_LOG_DEBUG, "'%s'\n", s);
            break;
        }
#endif
        av_log(ctx, AV_LOG_VERBOSE, "\n");
    }
}


void do_load_fpscr (void)

{

    /* The 32 MSB of the target fpr are undefined.

     * They'll be zero...

     */

    union {

        float64 d;

        struct {

            uint32_t u[2];

        } s;

    } u;

    int i;

#ifdef WORDS_BIGENDIAN

#define WORD0 0

#define WORD1 1

#else

#define WORD0 1

#define WORD1 0

#endif

    u.s.u[WORD0] = 0;

    u.s.u[WORD1] = 0;

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

        u.s.u[WORD1] |= env->fpscr[i] << (4 * i);

    FT0 = u.d;

}


static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,

                                   struct in_addr my_ip)

{

    AVFormatContext *avc;

    AVStream *avs = NULL;

    AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);

    AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);

    int i;

    avc =  avformat_alloc_context();

    if (avc == NULL || !rtp_format) {

        return -1;

    }

    avc->oformat = rtp_format;

    av_dict_set(&avc->metadata, "title",

                entry ? entry->value : "No Title", 0);

    avc->nb_streams = stream->nb_streams;

    if (stream->is_multicast) {

        snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",

                 inet_ntoa(stream->multicast_ip),

                 stream->multicast_port, stream->multicast_ttl);

    } else {

        snprintf(avc->filename, 1024, "rtp://0.0.0.0");

    }

    if (avc->nb_streams >= INT_MAX/sizeof(*avc->streams) ||

        !(avc->streams = av_malloc(avc->nb_streams * sizeof(*avc->streams))))

        goto sdp_done;

    if (avc->nb_streams >= INT_MAX/sizeof(*avs) ||

        !(avs = av_malloc(avc->nb_streams * sizeof(*avs))))

        goto sdp_done;

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

        avc->streams[i] = &avs[i];

        avc->streams[i]->codec = stream->streams[i]->codec;

    }

    *pbuffer = av_mallocz(2048);

    av_sdp_create(&avc, 1, *pbuffer, 2048);

 sdp_done:

    av_free(avc->streams);

    av_dict_free(&avc->metadata);

    av_free(avc);

    av_free(avs);

    return strlen(*pbuffer);

}


static void decode_init_vlc(H264Context *h){

    static int done = 0;

    if (!done) {

        int i;

        done = 1;

        init_vlc(&chroma_dc_coeff_token_vlc, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 4*5,

                 &chroma_dc_coeff_token_len [0], 1, 1,

                 &chroma_dc_coeff_token_bits[0], 1, 1);

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

            init_vlc(&coeff_token_vlc[i], COEFF_TOKEN_VLC_BITS, 4*17,

                     &coeff_token_len [i][0], 1, 1,

                     &coeff_token_bits[i][0], 1, 1);

        }

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

            init_vlc(&chroma_dc_total_zeros_vlc[i], CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 4,

                     &chroma_dc_total_zeros_len [i][0], 1, 1,

                     &chroma_dc_total_zeros_bits[i][0], 1, 1);

        }

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

            init_vlc(&total_zeros_vlc[i], TOTAL_ZEROS_VLC_BITS, 16,

                     &total_zeros_len [i][0], 1, 1,

                     &total_zeros_bits[i][0], 1, 1);

        }

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

            init_vlc(&run_vlc[i], RUN_VLC_BITS, 7,

                     &run_len [i][0], 1, 1,

                     &run_bits[i][0], 1, 1);

        }

        init_vlc(&run7_vlc, RUN7_VLC_BITS, 16,

                 &run_len [6][0], 1, 1,

                 &run_bits[6][0], 1, 1);

    }

}


int av_buffersink_poll_frame(AVFilterContext *ctx)

{

    BufferSinkContext *buf = ctx->priv;

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

    av_assert0(!strcmp(ctx->filter->name, "buffersink") || !strcmp(ctx->filter->name, "abuffersink"));

    return av_fifo_size(buf->fifo)/sizeof(AVFilterBufferRef *) + ff_poll_frame(inlink);

}


int ff_h263_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MpegEncContext *s = avctx->priv_data;

    int ret;

    AVFrame *pict = data;

#ifdef PRINT_FRAME_TIME

uint64_t time= rdtsc();

#endif

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

        if (s->low_delay==0 && s->next_picture_ptr) {

            *pict = s->next_picture_ptr->f;

            s->next_picture_ptr= NULL;

            *data_size = sizeof(AVFrame);

        }

        return 0;

    }

    if(s->flags&CODEC_FLAG_TRUNCATED){

        int next;

        if(CONFIG_MPEG4_DECODER && s->codec_id==CODEC_ID_MPEG4){

            next= ff_mpeg4_find_frame_end(&s->parse_context, buf, buf_size);

        }else if(CONFIG_H263_DECODER && s->codec_id==CODEC_ID_H263){

            next= ff_h263_find_frame_end(&s->parse_context, buf, buf_size);

        }else{

            av_log(s->avctx, AV_LOG_ERROR, "this codec does not support truncated bitstreams\n");

            return -1;

        }

        if( ff_combine_frame(&s->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0 )

            return buf_size;

    }

retry:

    if(s->bitstream_buffer_size && (s->divx_packed || buf_size<20)){ //divx 5.01+/xvid frame reorder

        init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size*8);

    }else

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

    s->bitstream_buffer_size=0;

    if (!s->context_initialized) {

        if (ff_MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix

            return -1;

    }

    /* We need to set current_picture_ptr before reading the header,

     * otherwise we cannot store anyting in there */

    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {

        int i= ff_find_unused_picture(s, 0);

        if (i < 0)

            return i;

        s->current_picture_ptr= &s->picture[i];

    }

    /* let's go :-) */

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version==5) {

        ret= ff_wmv2_decode_picture_header(s);

    } else if (CONFIG_MSMPEG4_DECODER && s->msmpeg4_version) {

        ret = ff_msmpeg4_decode_picture_header(s);

    } else if (CONFIG_MPEG4_DECODER && s->h263_pred) {

        if(s->avctx->extradata_size && s->picture_number==0){

            GetBitContext gb;

            init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);

            ret = ff_mpeg4_decode_picture_header(s, &gb);

        }

        ret = ff_mpeg4_decode_picture_header(s, &s->gb);

    } else if (CONFIG_H263I_DECODER && s->codec_id == CODEC_ID_H263I) {

        ret = ff_intel_h263_decode_picture_header(s);

    } else if (CONFIG_FLV_DECODER && s->h263_flv) {

        ret = ff_flv_decode_picture_header(s);

    } else {

        ret = ff_h263_decode_picture_header(s);

    }

    if(ret==FRAME_SKIPPED) return get_consumed_bytes(s, buf_size);

    /* skip if the header was thrashed */

    if (ret < 0){

        av_log(s->avctx, AV_LOG_ERROR, "header damaged\n");

        return -1;

    }

    avctx->has_b_frames= !s->low_delay;

    if(s->xvid_build==-1 && s->divx_version==-1 && s->lavc_build==-1){

        if(s->stream_codec_tag == AV_RL32("XVID") ||

           s->codec_tag == AV_RL32("XVID") || s->codec_tag == AV_RL32("XVIX") ||

           s->codec_tag == AV_RL32("RMP4") ||

           s->codec_tag == AV_RL32("SIPP")

           )

            s->xvid_build= 0;

#if 0

        if(s->codec_tag == AV_RL32("DIVX") && s->vo_type==0 && s->vol_control_parameters==1

           && s->padding_bug_score > 0 && s->low_delay) // XVID with modified fourcc

            s->xvid_build= 0;

#endif

    }

    if(s->xvid_build==-1 && s->divx_version==-1 && s->lavc_build==-1){

        if(s->codec_tag == AV_RL32("DIVX") && s->vo_type==0 && s->vol_control_parameters==0)

            s->divx_version= 400; //divx 4

    }

    if(s->xvid_build>=0 && s->divx_version>=0){

        s->divx_version=

        s->divx_build= -1;

    }

    if(s->workaround_bugs&FF_BUG_AUTODETECT){

        if(s->codec_tag == AV_RL32("XVIX"))

            s->workaround_bugs|= FF_BUG_XVID_ILACE;

        if(s->codec_tag == AV_RL32("UMP4")){

            s->workaround_bugs|= FF_BUG_UMP4;

        }

        if(s->divx_version>=500 && s->divx_build<1814){

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        }

        if(s->divx_version>502 && s->divx_build<1814){

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA2;

        }

        if(s->xvid_build<=3U)

            s->padding_bug_score= 256*256*256*64;

        if(s->xvid_build<=1U)

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        if(s->xvid_build<=12U)

            s->workaround_bugs|= FF_BUG_EDGE;

        if(s->xvid_build<=32U)

            s->workaround_bugs|= FF_BUG_DC_CLIP;

#define SET_QPEL_FUNC(postfix1, postfix2) \

    s->dsp.put_ ## postfix1 = ff_put_ ## postfix2;\

    s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;\

    s->dsp.avg_ ## postfix1 = ff_avg_ ## postfix2;

        if(s->lavc_build<4653U)

            s->workaround_bugs|= FF_BUG_STD_QPEL;

        if(s->lavc_build<4655U)

            s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;

        if(s->lavc_build<4670U){

            s->workaround_bugs|= FF_BUG_EDGE;

        }

        if(s->lavc_build<=4712U)

            s->workaround_bugs|= FF_BUG_DC_CLIP;

        if(s->divx_version>=0)

            s->workaround_bugs|= FF_BUG_DIRECT_BLOCKSIZE;

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

        if(s->divx_version==501 && s->divx_build==20020416)

            s->padding_bug_score= 256*256*256*64;

        if(s->divx_version<500U){

            s->workaround_bugs|= FF_BUG_EDGE;

        }

        if(s->divx_version>=0)

            s->workaround_bugs|= FF_BUG_HPEL_CHROMA;

#if 0

        if(s->divx_version==500)

            s->padding_bug_score= 256*256*256*64;

        /* very ugly XVID padding bug detection FIXME/XXX solve this differently

         * Let us hope this at least works.

         */

        if(   s->resync_marker==0 && s->data_partitioning==0 && s->divx_version==-1

           && s->codec_id==CODEC_ID_MPEG4 && s->vo_type==0)

            s->workaround_bugs|= FF_BUG_NO_PADDING;

        if(s->lavc_build<4609U) //FIXME not sure about the version num but a 4609 file seems ok

            s->workaround_bugs|= FF_BUG_NO_PADDING;

#endif

    }

    if(s->workaround_bugs& FF_BUG_STD_QPEL){

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 5], qpel16_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 7], qpel16_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 9], qpel16_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 5], qpel8_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 7], qpel8_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 9], qpel8_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)

    }

    if(avctx->debug & FF_DEBUG_BUGS)

        av_log(s->avctx, AV_LOG_DEBUG, "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",

               s->workaround_bugs, s->lavc_build, s->xvid_build, s->divx_version, s->divx_build,

               s->divx_packed ? "p" : "");

#if HAVE_MMX

    if (s->codec_id == CODEC_ID_MPEG4 && s->xvid_build>=0 && avctx->idct_algo == FF_IDCT_AUTO && (av_get_cpu_flags() & AV_CPU_FLAG_MMX)) {

        avctx->idct_algo= FF_IDCT_XVIDMMX;

        avctx->coded_width= 0; // force reinit

//        ff_dsputil_init(&s->dsp, avctx);

        s->picture_number=0;

    }

#endif

        /* After H263 & mpeg4 header decode we have the height, width,*/

        /* and other parameters. So then we could init the picture   */

        /* FIXME: By the way H263 decoder is evolving it should have */

        /* an H263EncContext                                         */

    if (   s->width  != avctx->coded_width

        || s->height != avctx->coded_height) {

        /* H.263 could change picture size any time */

        ParseContext pc= s->parse_context; //FIXME move these demuxng hack to avformat

        s->parse_context.buffer=0;

        ff_MPV_common_end(s);

        s->parse_context= pc;

    }

    if (!s->context_initialized) {

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

        goto retry;

    }

    if((s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P || s->codec_id == CODEC_ID_H263I))

        s->gob_index = ff_h263_get_gob_height(s);

    // for skipping the frame

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    /* skip B-frames if we don't have reference frames */

    if(s->last_picture_ptr==NULL && (s->pict_type==AV_PICTURE_TYPE_B || s->dropable)) return get_consumed_bytes(s, buf_size);

    if(   (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B)

       || (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I)

       ||  avctx->skip_frame >= AVDISCARD_ALL)

        return get_consumed_bytes(s, buf_size);

    if(s->next_p_frame_damaged){

        if(s->pict_type==AV_PICTURE_TYPE_B)

            return get_consumed_bytes(s, buf_size);

        else

            s->next_p_frame_damaged=0;

    }

    if((s->avctx->flags2 & CODEC_FLAG2_FAST) && s->pict_type==AV_PICTURE_TYPE_B){

        s->me.qpel_put= s->dsp.put_2tap_qpel_pixels_tab;

        s->me.qpel_avg= s->dsp.avg_2tap_qpel_pixels_tab;

    }else if((!s->no_rounding) || s->pict_type==AV_PICTURE_TYPE_B){

        s->me.qpel_put= s->dsp.put_qpel_pixels_tab;

        s->me.qpel_avg= s->dsp.avg_qpel_pixels_tab;

    }else{

        s->me.qpel_put= s->dsp.put_no_rnd_qpel_pixels_tab;

        s->me.qpel_avg= s->dsp.avg_qpel_pixels_tab;

    }

    if(ff_MPV_frame_start(s, avctx) < 0)

        return -1;

    if (!s->divx_packed) ff_thread_finish_setup(avctx);

    if (CONFIG_MPEG4_VDPAU_DECODER && (s->avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)) {

        ff_vdpau_mpeg4_decode_picture(s, s->gb.buffer, s->gb.buffer_end - s->gb.buffer);

        goto frame_end;

    }

    if (avctx->hwaccel) {

        if (avctx->hwaccel->start_frame(avctx, s->gb.buffer, s->gb.buffer_end - s->gb.buffer) < 0)

            return -1;

    }

    ff_er_frame_start(s);

    //the second part of the wmv2 header contains the MB skip bits which are stored in current_picture->mb_type

    //which is not available before ff_MPV_frame_start()

    if (CONFIG_WMV2_DECODER && s->msmpeg4_version==5){

        ret = ff_wmv2_decode_secondary_picture_header(s);

        if(ret<0) return ret;

        if(ret==1) goto intrax8_decoded;

    }

    /* decode each macroblock */

    s->mb_x=0;

    s->mb_y=0;

    ret = decode_slice(s);

    while(s->mb_y<s->mb_height){

        if(s->msmpeg4_version){

            if(s->slice_height==0 || s->mb_x!=0 || (s->mb_y%s->slice_height)!=0 || get_bits_count(&s->gb) > s->gb.size_in_bits)

                break;

        }else{

            int prev_x=s->mb_x, prev_y=s->mb_y;

            if(ff_h263_resync(s)<0)

                break;

            if (prev_y * s->mb_width + prev_x < s->mb_y * s->mb_width + s->mb_x)

                s->error_occurred = 1;

        }

        if(s->msmpeg4_version<4 && s->h263_pred)

            ff_mpeg4_clean_buffers(s);

        if (decode_slice(s) < 0) ret = AVERROR_INVALIDDATA;

    }

    if (s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type==AV_PICTURE_TYPE_I)

        if(!CONFIG_MSMPEG4_DECODER || ff_msmpeg4_decode_ext_header(s, buf_size) < 0){

            s->error_status_table[s->mb_num-1]= ER_MB_ERROR;

        }

    assert(s->bitstream_buffer_size==0);

frame_end:

    /* divx 5.01+ bistream reorder stuff */

    if(s->codec_id==CODEC_ID_MPEG4 && s->divx_packed){

        int current_pos= get_bits_count(&s->gb)>>3;

        int startcode_found=0;

        if(buf_size - current_pos > 5){

            int i;

            for(i=current_pos; i<buf_size-3; i++){

                if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1 && buf[i+3]==0xB6){

                    startcode_found=1;

                    break;

                }

            }

        }

        if(s->gb.buffer == s->bitstream_buffer && buf_size>7 && s->xvid_build>=0){ //xvid style

            startcode_found=1;

            current_pos=0;

        }

        if(startcode_found){

            av_fast_malloc(

                &s->bitstream_buffer,

                &s->allocated_bitstream_buffer_size,

                buf_size - current_pos + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->bitstream_buffer)

                return AVERROR(ENOMEM);

            memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos);

            s->bitstream_buffer_size= buf_size - current_pos;

        }

    }

intrax8_decoded:

    ff_er_frame_end(s);

    if (avctx->hwaccel) {

        if (avctx->hwaccel->end_frame(avctx) < 0)

            return -1;

    }

    ff_MPV_frame_end(s);

    assert(s->current_picture.f.pict_type == s->current_picture_ptr->f.pict_type);

    assert(s->current_picture.f.pict_type == s->pict_type);

    if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {

        *pict = s->current_picture_ptr->f;

    } else if (s->last_picture_ptr != NULL) {

        *pict = s->last_picture_ptr->f;

    }

    if(s->last_picture_ptr || s->low_delay){

        *data_size = sizeof(AVFrame);

        ff_print_debug_info(s, pict);

    }

#ifdef PRINT_FRAME_TIME

av_log(avctx, AV_LOG_DEBUG, "%"PRId64"\n", rdtsc()-time);

#endif

    return (ret && (avctx->err_recognition & AV_EF_EXPLODE))?ret:get_consumed_bytes(s, buf_size);

}


static void mmap_release_buffer(AVPacket *pkt)
{
    struct v4l2_buffer buf;
    int res, fd;
    struct buff_data *buf_descriptor = pkt->priv;
    memset(&buf, 0, sizeof(struct v4l2_buffer));
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    buf.index = buf_descriptor->index;
    fd = buf_descriptor->fd;
    av_free(buf_descriptor);
    res = ioctl (fd, VIDIOC_QBUF, &buf);
    if (res < 0) {
        av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF)\n");
    pkt->data = NULL;
    pkt->size = 0;


static int configure_video_filters(FilterGraph *fg)

{

    InputStream  *ist = fg->inputs[0]->ist;

    OutputStream *ost = fg->outputs[0]->ost;

    AVFilterContext *in_filter, *out_filter, *filter;

    AVCodecContext *codec = ost->st->codec;

    AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();

    char *pix_fmts;

    AVRational sample_aspect_ratio;

    char args[255];

    int ret;

    avfilter_graph_free(&fg->graph);

    fg->graph = avfilter_graph_alloc();

    if (!fg->graph)

        return AVERROR(ENOMEM);

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

        sample_aspect_ratio = ist->st->sample_aspect_ratio;

    } else

        sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;

    snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,

             ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,

             sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));

    ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,

                                       avfilter_get_by_name("buffer"),

                                       "src", args, NULL, fg->graph);

    if (ret < 0)

        return ret;

#if FF_API_OLD_VSINK_API

    ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,

                                       avfilter_get_by_name("buffersink"),

                                       "out", NULL, NULL, fg->graph);

#else

    ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,

                                       avfilter_get_by_name("buffersink"),

                                       "out", NULL, buffersink_params, fg->graph);

#endif

    av_freep(&buffersink_params);

    if (ret < 0)

        return ret;

    in_filter  = fg->inputs[0]->filter;

    out_filter = fg->outputs[0]->filter;

    if (codec->width || codec->height) {

        snprintf(args, 255, "%d:%d:flags=0x%X",

                 codec->width,

                 codec->height,

                 (unsigned)ost->sws_flags);

        if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),

                                                NULL, args, NULL, fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(in_filter, 0, filter, 0)) < 0)

            return ret;

        in_filter = filter;

    }

    if ((pix_fmts = choose_pixel_fmts(ost))) {

        if ((ret = avfilter_graph_create_filter(&filter,

                                                avfilter_get_by_name("format"),

                                                "format", pix_fmts, NULL,

                                                fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(filter, 0, out_filter, 0)) < 0)

            return ret;

        out_filter = filter;

        av_freep(&pix_fmts);

    }

    snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);

    fg->graph->scale_sws_opts = av_strdup(args);

    if (ost->avfilter) {

        AVFilterInOut *outputs = avfilter_inout_alloc();

        AVFilterInOut *inputs  = avfilter_inout_alloc();

        outputs->name    = av_strdup("in");

        outputs->filter_ctx = in_filter;

        outputs->pad_idx = 0;

        outputs->next    = NULL;

        inputs->name    = av_strdup("out");

        inputs->filter_ctx = out_filter;

        inputs->pad_idx = 0;

        inputs->next    = NULL;

        if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)

            return ret;

        av_freep(&ost->avfilter);

    } else {

        if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)

            return ret;

    }

    if (ost->keep_pix_fmt)

        avfilter_graph_set_auto_convert(fg->graph,

                                        AVFILTER_AUTO_CONVERT_NONE);

    if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)

        return ret;

    ost->filter = fg->outputs[0];

    return 0;

}


static inline void RET_STOP (DisasContext *ctx)

{

    gen_update_nip(ctx, ctx->nip);

    ctx->exception = EXCP_MTMSR;

}


void qdev_property_add_legacy(DeviceState *dev, Property *prop,

                              Error **errp)

{

    gchar *type;

    type = g_strdup_printf("legacy<%s>", prop->info->name);

    qdev_property_add(dev, prop->name, type,

                      qdev_get_legacy_property,

                      qdev_set_legacy_property,

                      NULL,

                      prop, errp);

    g_free(type);

}


uint64_t helper_fmadd(CPUPPCState *env, uint64_t arg1, uint64_t arg2,

                      uint64_t arg3)

{

    CPU_DoubleU farg1, farg2, farg3;

    farg1.ll = arg1;

    farg2.ll = arg2;

    farg3.ll = arg3;

    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||

                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {

        /* Multiplication of zero by infinity */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);

    } else {

        if (unlikely(float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d) ||

                     float64_is_signaling_nan(farg3.d))) {

            /* sNaN operation */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        /* This is the way the PowerPC specification defines it */

        float128 ft0_128, ft1_128;

        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);

        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);

        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);

        if (unlikely(float128_is_infinity(ft0_128) &&

                     float64_is_infinity(farg3.d) &&

                     float128_is_neg(ft0_128) != float64_is_neg(farg3.d))) {

            /* Magnitude subtraction of infinities */

            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);

        } else {

            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);

            ft0_128 = float128_add(ft0_128, ft1_128, &env->fp_status);

            farg1.d = float128_to_float64(ft0_128, &env->fp_status);

        }

    }

    return farg1.ll;

}


static void tcg_out_andi64(TCGContext *s, TCGReg dst, TCGReg src, uint64_t c)

{

    int mb, me;

    assert(TCG_TARGET_REG_BITS == 64);

    if (mask64_operand(c, &mb, &me)) {

        if (mb == 0) {

            tcg_out_rld(s, RLDICR, dst, src, 0, me);

        } else {

            tcg_out_rld(s, RLDICL, dst, src, 0, mb);

        }

    } else if ((c & 0xffff) == c) {

        tcg_out32(s, ANDI | SAI(src, dst, c));

        return;

    } else if ((c & 0xffff0000) == c) {

        tcg_out32(s, ANDIS | SAI(src, dst, c >> 16));

        return;

    } else {

        tcg_out_movi(s, TCG_TYPE_I64, TCG_REG_R0, c);

        tcg_out32(s, AND | SAB(src, dst, TCG_REG_R0));

    }

}


static void eth_cleanup(NetClientState *nc)

{

    ETRAXFSEthState *eth = qemu_get_nic_opaque(nc);

    /* Disconnect the client.  */

    eth->dma_out->client.push = NULL;

    eth->dma_out->client.opaque = NULL;

    eth->dma_in->client.opaque = NULL;

    eth->dma_in->client.pull = NULL;

        g_free(eth);

}


long do_sigreturn(CPUCRISState *env)

{

	struct target_signal_frame *frame;

	abi_ulong frame_addr;

	target_sigset_t target_set;

	sigset_t set;

	int i;

	frame_addr = env->regs[R_SP];

	/* Make sure the guest isn't playing games.  */

	if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 1))

		goto badframe;

	/* Restore blocked signals */

	if (__get_user(target_set.sig[0], &frame->sc.oldmask))

		goto badframe;

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

		if (__get_user(target_set.sig[i], &frame->extramask[i - 1]))

			goto badframe;

	}

	target_to_host_sigset_internal(&set, &target_set);

	sigprocmask(SIG_SETMASK, &set, NULL);

	restore_sigcontext(&frame->sc, env);

	unlock_user_struct(frame, frame_addr, 0);

	return env->regs[10];

  badframe:

	unlock_user_struct(frame, frame_addr, 0);

	force_sig(TARGET_SIGSEGV);

}


static inline int epoll_events_from_pfd(int pfd_events)

{

    return (pfd_events & G_IO_IN ? EPOLLIN : 0) |

           (pfd_events & G_IO_OUT ? EPOLLOUT : 0) |

           (pfd_events & G_IO_HUP ? EPOLLHUP : 0) |

           (pfd_events & G_IO_ERR ? EPOLLERR : 0);

}


static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov)

{

    int pos, i;

    pos = url_ftell(pb);

    put_be32(pb, 0); /* size placeholder*/

    put_tag(pb, "moov");

    mov->timescale = globalTimescale;

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

        if(mov->tracks[i].entry <= 0) continue;

        if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {

            mov->tracks[i].timescale = mov->tracks[i].enc->frame_rate;

            mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_rate_base;

        }

        else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {

            /* If AMR, track timescale = 8000, AMR_WB = 16000 */

            if(mov->tracks[i].enc->codec_id == CODEC_ID_AMR_NB) {

                mov->tracks[i].sampleDuration = 160;  // Bytes per chunk

                mov->tracks[i].timescale = 8000;

            }

            else {

                mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;

                mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;

            }

        }

        mov->tracks[i].trackDuration =

            mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;

        mov->tracks[i].time = mov->time;

        mov->tracks[i].trackID = i+1;

    }

    mov_write_mvhd_tag(pb, mov);

    //mov_write_iods_tag(pb, mov);

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

        if(mov->tracks[i].entry > 0) {

            mov_write_trak_tag(pb, &(mov->tracks[i]));

        }

    }

    return updateSize(pb, pos);

}


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

{

    MIPSCPSState *s = MIPS_CPS(dev);

    CPUMIPSState *env;

    MIPSCPU *cpu;

    int i;

    Error *err = NULL;

    target_ulong gcr_base;

    bool itu_present = false;

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

        cpu = cpu_mips_init(s->cpu_model);

        if (cpu == NULL) {

            error_setg(errp, "%s: CPU initialization failed\n",  __func__);

            return;

        }

        /* Init internal devices */

        cpu_mips_irq_init_cpu(cpu);

        cpu_mips_clock_init(cpu);

        env = &cpu->env;

        if (cpu_mips_itu_supported(env)) {

            itu_present = true;

            /* Attach ITC Tag to the VP */

            env->itc_tag = mips_itu_get_tag_region(&s->itu);

        }

        qemu_register_reset(main_cpu_reset, cpu);

    }

    cpu = MIPS_CPU(first_cpu);

    env = &cpu->env;

    /* Inter-Thread Communication Unit */

    if (itu_present) {

        object_initialize(&s->itu, sizeof(s->itu), TYPE_MIPS_ITU);

        qdev_set_parent_bus(DEVICE(&s->itu), sysbus_get_default());

        object_property_set_int(OBJECT(&s->itu), 16, "num-fifo", &err);

        object_property_set_int(OBJECT(&s->itu), 16, "num-semaphores", &err);

        object_property_set_bool(OBJECT(&s->itu), true, "realized", &err);

        if (err != NULL) {

            error_propagate(errp, err);

            return;

        }

        memory_region_add_subregion(&s->container, 0,

                           sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->itu), 0));

    }

    /* Cluster Power Controller */

    object_initialize(&s->cpc, sizeof(s->cpc), TYPE_MIPS_CPC);

    qdev_set_parent_bus(DEVICE(&s->cpc), sysbus_get_default());

    object_property_set_int(OBJECT(&s->cpc), s->num_vp, "num-vp", &err);

    object_property_set_int(OBJECT(&s->cpc), 1, "vp-start-running", &err);

    object_property_set_bool(OBJECT(&s->cpc), true, "realized", &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(&s->container, 0,

                            sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->cpc), 0));

    /* Global Interrupt Controller */

    object_initialize(&s->gic, sizeof(s->gic), TYPE_MIPS_GIC);

    qdev_set_parent_bus(DEVICE(&s->gic), sysbus_get_default());

    object_property_set_int(OBJECT(&s->gic), s->num_vp, "num-vp", &err);

    object_property_set_int(OBJECT(&s->gic), 128, "num-irq", &err);

    object_property_set_bool(OBJECT(&s->gic), true, "realized", &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(&s->container, 0,

                            sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->gic), 0));

    /* Global Configuration Registers */

    gcr_base = env->CP0_CMGCRBase << 4;

    object_initialize(&s->gcr, sizeof(s->gcr), TYPE_MIPS_GCR);

    qdev_set_parent_bus(DEVICE(&s->gcr), sysbus_get_default());

    object_property_set_int(OBJECT(&s->gcr), s->num_vp, "num-vp", &err);

    object_property_set_int(OBJECT(&s->gcr), 0x800, "gcr-rev", &err);

    object_property_set_int(OBJECT(&s->gcr), gcr_base, "gcr-base", &err);

    object_property_set_link(OBJECT(&s->gcr), OBJECT(&s->gic.mr), "gic", &err);

    object_property_set_link(OBJECT(&s->gcr), OBJECT(&s->cpc.mr), "cpc", &err);

    object_property_set_bool(OBJECT(&s->gcr), true, "realized", &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

    memory_region_add_subregion(&s->container, gcr_base,

                            sysbus_mmio_get_region(SYS_BUS_DEVICE(&s->gcr), 0));

}


void cpu_loop(CPUM68KState *env)

{

    CPUState *cs = CPU(m68k_env_get_cpu(env));

    int trapnr;

    unsigned int n;

    target_siginfo_t info;

    TaskState *ts = cs->opaque;

    for(;;) {

        cpu_exec_start(cs);

        trapnr = cpu_m68k_exec(cs);

        cpu_exec_end(cs);

        switch(trapnr) {

        case EXCP_ILLEGAL:

            {

                if (ts->sim_syscalls) {

                    uint16_t nr;

                    get_user_u16(nr, env->pc + 2);

                    env->pc += 4;

                    do_m68k_simcall(env, nr);

                } else {

                    goto do_sigill;

                }

            }

            break;

        case EXCP_HALT_INSN:

            /* Semihosing syscall.  */

            env->pc += 4;

            do_m68k_semihosting(env, env->dregs[0]);

            break;

        case EXCP_LINEA:

        case EXCP_LINEF:

        case EXCP_UNSUPPORTED:

        do_sigill:

            info.si_signo = TARGET_SIGILL;

            info.si_errno = 0;

            info.si_code = TARGET_ILL_ILLOPN;

            info._sifields._sigfault._addr = env->pc;

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

            break;

        case EXCP_TRAP0:

            {

                ts->sim_syscalls = 0;

                n = env->dregs[0];

                env->pc += 2;

                env->dregs[0] = do_syscall(env,

                                          n,

                                          env->dregs[1],

                                          env->dregs[2],

                                          env->dregs[3],

                                          env->dregs[4],

                                          env->dregs[5],

                                          env->aregs[0],

                                          0, 0);

            }

            break;

        case EXCP_INTERRUPT:

            /* just indicate that signals should be handled asap */

            break;

        case EXCP_ACCESS:

            {

                info.si_signo = TARGET_SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = env->mmu.ar;

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

            }

            break;

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig(cs, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

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

                  }

            }

            break;

        default:

            fprintf(stderr, "qemu: unhandled CPU exception 0x%x - aborting\n",

                    trapnr);

            cpu_dump_state(cs, stderr, fprintf, 0);

            abort();

        }

        process_pending_signals(env);

    }

}


void usb_attach(USBPort *port, USBDevice *dev)

{

    if (dev != NULL) {

        /* attach */

        if (port->dev) {

            usb_attach(port, NULL);

        }

        dev->port = port;

        port->dev = dev;

        port->ops->attach(port);

        usb_send_msg(dev, USB_MSG_ATTACH);

    } else {

        /* detach */

        dev = port->dev;

        port->ops->detach(port);

        if (dev) {

            usb_send_msg(dev, USB_MSG_DETACH);

            dev->port = NULL;

            port->dev = NULL;

        }

    }

}


static void qerror_set_data(QError *qerr, const char *fmt, va_list *va)

{

    QObject *obj;

    obj = qobject_from_jsonv(fmt, va);

    if (!obj) {

        qerror_abort(qerr, "invalid format '%s'", fmt);

    }

    if (qobject_type(obj) != QTYPE_QDICT) {

        qerror_abort(qerr, "error format is not a QDict '%s'", fmt);

    }

    qerr->error = qobject_to_qdict(obj);

    obj = qdict_get(qerr->error, "class");

    if (!obj) {

        qerror_abort(qerr, "missing 'class' key in '%s'", fmt);

    }

    if (qobject_type(obj) != QTYPE_QSTRING) {

        qerror_abort(qerr, "'class' key value should be a QString");

    }

    obj = qdict_get(qerr->error, "data");

    if (!obj) {

        qerror_abort(qerr, "missing 'data' key in '%s'", fmt);

    }

    if (qobject_type(obj) != QTYPE_QDICT) {

        qerror_abort(qerr, "'data' key value should be a QDICT");

    }

}


udp_emu(struct socket *so, struct mbuf *m)

{

	struct sockaddr_in addr;

        int addrlen = sizeof(addr);

#ifdef EMULATE_TALK

	CTL_MSG_OLD *omsg;

	CTL_MSG *nmsg;

	char buff[sizeof(CTL_MSG)];

	u_char type;

struct talk_request {

	struct talk_request *next;

	struct socket *udp_so;

	struct socket *tcp_so;

} *req;

	static struct talk_request *req_tbl = 0;

#endif

struct cu_header {

	uint16_t	d_family;		// destination family

	uint16_t	d_port;			// destination port

	uint32_t	d_addr;			// destination address

	uint16_t	s_family;		// source family

	uint16_t	s_port;			// source port

	uint32_t	so_addr;		// source address

	uint32_t	seqn;			// sequence number

	uint16_t	message;		// message

	uint16_t	data_type;		// data type

	uint16_t	pkt_len;		// packet length

} *cu_head;

	switch(so->so_emu) {

#ifdef EMULATE_TALK

	 case EMU_TALK:

	 case EMU_NTALK:

		/*

		 * Talk emulation. We always change the ctl_addr to get

		 * some answers from the daemon. When an ANNOUNCE comes,

		 * we send LEAVE_INVITE to the local daemons. Also when a

		 * DELETE comes, we send copies to the local daemons.

		 */

		if (getsockname(so->s, (struct sockaddr *)&addr, &addrlen) < 0)

			return;

#define	IS_OLD	(so->so_emu == EMU_TALK)

#define COPY_MSG(dest, src) { dest->type = src->type; \

			      dest->id_num = src->id_num; \

			      dest->pid = src->pid; \

			      dest->addr = src->addr; \

			      dest->ctl_addr = src->ctl_addr; \

			      memcpy(&dest->l_name, &src->l_name, NAME_SIZE_OLD); \

			      memcpy(&dest->r_name, &src->r_name, NAME_SIZE_OLD); \

	         	      memcpy(&dest->r_tty, &src->r_tty, TTY_SIZE); }

#define OTOSIN(ptr, field) ((struct sockaddr_in *)&ptr->field)

/* old_sockaddr to sockaddr_in */

		if (IS_OLD) {  		/* old talk */

			omsg = mtod(m, CTL_MSG_OLD*);

			nmsg = (CTL_MSG *) buff;

			type = omsg->type;

			OTOSIN(omsg, ctl_addr)->sin_port = addr.sin_port;

			OTOSIN(omsg, ctl_addr)->sin_addr = our_addr;

			strncpy(omsg->l_name, getlogin(), NAME_SIZE_OLD);

		} else {		/* new talk */

			omsg = (CTL_MSG_OLD *) buff;

			nmsg = mtod(m, CTL_MSG *);

			type = nmsg->type;

			OTOSIN(nmsg, ctl_addr)->sin_port = addr.sin_port;

			OTOSIN(nmsg, ctl_addr)->sin_addr = our_addr;

			strncpy(nmsg->l_name, getlogin(), NAME_SIZE_OLD);

		}

		if (type == LOOK_UP)

			return;		/* for LOOK_UP this is enough */

		if (IS_OLD) {		/* make a copy of the message */

			COPY_MSG(nmsg, omsg);

			nmsg->vers = 1;

			nmsg->answer = 0;

		} else

			COPY_MSG(omsg, nmsg);

		/*

		 * If if is an ANNOUNCE message, we go through the

		 * request table to see if a tcp port has already

		 * been redirected for this socket. If not, we solisten()

		 * a new socket and add this entry to the table.

		 * The port number of the tcp socket and our IP

		 * are put to the addr field of the message structures.

		 * Then a LEAVE_INVITE is sent to both local daemon

		 * ports, 517 and 518. This is why we have two copies

		 * of the message, one in old talk and one in new talk

		 * format.

		 */

		if (type == ANNOUNCE) {

			int s;

			u_short temp_port;

			for(req = req_tbl; req; req = req->next)

				if (so == req->udp_so)

					break;  	/* found it */

			if (!req) {	/* no entry for so, create new */

				req = (struct talk_request *)

					malloc(sizeof(struct talk_request));

				req->udp_so = so;

				req->tcp_so = solisten(0,

					OTOSIN(omsg, addr)->sin_addr.s_addr,

					OTOSIN(omsg, addr)->sin_port,

					SS_FACCEPTONCE);

				req->next = req_tbl;

				req_tbl = req;

			}

			/* replace port number in addr field */

			addrlen = sizeof(addr);

			getsockname(req->tcp_so->s,

					(struct sockaddr *) &addr,

					&addrlen);

			OTOSIN(omsg, addr)->sin_port = addr.sin_port;

			OTOSIN(omsg, addr)->sin_addr = our_addr;

			OTOSIN(nmsg, addr)->sin_port = addr.sin_port;

			OTOSIN(nmsg, addr)->sin_addr = our_addr;

			/* send LEAVE_INVITEs */

			temp_port = OTOSIN(omsg, ctl_addr)->sin_port;

			OTOSIN(omsg, ctl_addr)->sin_port = 0;

			OTOSIN(nmsg, ctl_addr)->sin_port = 0;

			omsg->type = nmsg->type = LEAVE_INVITE;

			s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);

			addr.sin_addr = our_addr;

			addr.sin_family = AF_INET;

			addr.sin_port = htons(517);

			sendto(s, (char *)omsg, sizeof(*omsg), 0,

				(struct sockaddr *)&addr, sizeof(addr));

			addr.sin_port = htons(518);

			sendto(s, (char *)nmsg, sizeof(*nmsg), 0,

				(struct sockaddr *) &addr, sizeof(addr));

			closesocket(s) ;

			omsg->type = nmsg->type = ANNOUNCE;

			OTOSIN(omsg, ctl_addr)->sin_port = temp_port;

			OTOSIN(nmsg, ctl_addr)->sin_port = temp_port;

		}

		/*

		 * If it is a DELETE message, we send a copy to the

		 * local daemons. Then we delete the entry corresponding

		 * to our socket from the request table.

		 */

		if (type == DELETE) {

			struct talk_request *temp_req, *req_next;

			int s;

			u_short temp_port;

			temp_port = OTOSIN(omsg, ctl_addr)->sin_port;

			OTOSIN(omsg, ctl_addr)->sin_port = 0;

			OTOSIN(nmsg, ctl_addr)->sin_port = 0;

			s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);

			addr.sin_addr = our_addr;

			addr.sin_family = AF_INET;

			addr.sin_port = htons(517);

			sendto(s, (char *)omsg, sizeof(*omsg), 0,

				(struct sockaddr *)&addr, sizeof(addr));

			addr.sin_port = htons(518);

			sendto(s, (char *)nmsg, sizeof(*nmsg), 0,

				(struct sockaddr *)&addr, sizeof(addr));

			closesocket(s);

			OTOSIN(omsg, ctl_addr)->sin_port = temp_port;

			OTOSIN(nmsg, ctl_addr)->sin_port = temp_port;

			/* delete table entry */

			if (so == req_tbl->udp_so) {

				temp_req = req_tbl;

				req_tbl = req_tbl->next;

				free(temp_req);

			} else {

				temp_req = req_tbl;

				for(req = req_tbl->next; req; req = req_next) {

					req_next = req->next;

					if (so == req->udp_so) {

						temp_req->next = req_next;

						free(req);

						break;

					} else {

						temp_req = req;

					}

				}

			}

		}

		return;

#endif

	case EMU_CUSEEME:

		/*

		 * Cu-SeeMe emulation.

		 * Hopefully the packet is more that 16 bytes long. We don't

		 * do any other tests, just replace the address and port

		 * fields.

		 */

		if (m->m_len >= sizeof (*cu_head)) {

			if (getsockname(so->s, (struct sockaddr *)&addr, &addrlen) < 0)

				return;

			cu_head = mtod(m, struct cu_header *);

			cu_head->s_port = addr.sin_port;

			cu_head->so_addr = our_addr.s_addr;

		}

		return;

	}

}


static ssize_t usbnet_receive(VLANClientState *nc, const uint8_t *buf, size_t size)

{

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

    struct rndis_packet_msg_type *msg;

    if (s->rndis) {

        msg = (struct rndis_packet_msg_type *) s->in_buf;

        if (!s->rndis_state == RNDIS_DATA_INITIALIZED)

            return -1;

        if (size + sizeof(struct rndis_packet_msg_type) > sizeof(s->in_buf))

            return -1;

        memset(msg, 0, sizeof(struct rndis_packet_msg_type));

        msg->MessageType = cpu_to_le32(RNDIS_PACKET_MSG);

        msg->MessageLength = cpu_to_le32(size + sizeof(struct rndis_packet_msg_type));

        msg->DataOffset = cpu_to_le32(sizeof(struct rndis_packet_msg_type) - 8);

        msg->DataLength = cpu_to_le32(size);

        /* msg->OOBDataOffset;

         * msg->OOBDataLength;

         * msg->NumOOBDataElements;

         * msg->PerPacketInfoOffset;

         * msg->PerPacketInfoLength;

         * msg->VcHandle;

         * msg->Reserved;

         */

        memcpy(msg + 1, buf, size);

        s->in_len = size + sizeof(struct rndis_packet_msg_type);

    } else {

        if (size > sizeof(s->in_buf))

            return -1;

        memcpy(s->in_buf, buf, size);

        s->in_len = size;

    }

    s->in_ptr = 0;

    return size;

}


static void mpcore_priv_map_setup(mpcore_priv_state *s)

{

    int i;

    SysBusDevice *gicbusdev = sysbus_from_qdev(s->gic);

    SysBusDevice *busdev = sysbus_from_qdev(s->mptimer);

    memory_region_init(&s->container, "mpcode-priv-container", 0x2000);

    memory_region_init_io(&s->iomem, &mpcore_scu_ops, s, "mpcore-scu", 0x100);

    memory_region_add_subregion(&s->container, 0, &s->iomem);

    /* GIC CPU interfaces: "current CPU" at 0x100, then specific CPUs

     * at 0x200, 0x300...

     */

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

        target_phys_addr_t offset = 0x100 + (i * 0x100);

        memory_region_add_subregion(&s->container, offset,

                                    sysbus_mmio_get_region(gicbusdev, i + 1));

    }

    /* Add the regions for timer and watchdog for "current CPU" and

     * for each specific CPU.

     */

    for (i = 0; i < (s->num_cpu + 1) * 2; i++) {

        /* Timers at 0x600, 0x700, ...; watchdogs at 0x620, 0x720, ... */

        target_phys_addr_t offset = 0x600 + (i >> 1) * 0x100 + (i & 1) * 0x20;

        memory_region_add_subregion(&s->container, offset,

                                    sysbus_mmio_get_region(busdev, i));

    }

    memory_region_add_subregion(&s->container, 0x1000,

                                sysbus_mmio_get_region(gicbusdev, 0));

    /* Wire up the interrupt from each watchdog and timer.

     * For each core the timer is PPI 29 and the watchdog PPI 30.

     */

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

        int ppibase = (s->num_irq - 32) + i * 32;

        sysbus_connect_irq(busdev, i * 2,

                           qdev_get_gpio_in(s->gic, ppibase + 29));

        sysbus_connect_irq(busdev, i * 2 + 1,

                           qdev_get_gpio_in(s->gic, ppibase + 30));

    }

}


static int proxy_readdir_r(FsContext *ctx, V9fsFidOpenState *fs,

                           struct dirent *entry,

                           struct dirent **result)

{

    return readdir_r(fs->dir, entry, result);

}