static ssize_t qio_channel_command_readv(QIOChannel *ioc,

                                         const struct iovec *iov,

                                         size_t niov,

                                         int **fds,

                                         size_t *nfds,

                                         Error **errp)

{

    QIOChannelCommand *cioc = QIO_CHANNEL_COMMAND(ioc);

    ssize_t ret;

 retry:

    ret = readv(cioc->readfd, iov, niov);

    if (ret < 0) {

        if (errno == EAGAIN ||

            errno == EWOULDBLOCK) {

            return QIO_CHANNEL_ERR_BLOCK;

        }

        if (errno == EINTR) {

            goto retry;

        }

        error_setg_errno(errp, errno,

                         "Unable to read from command");

        return -1;

    }

    return ret;

}


vnc_display_setup_auth(VncDisplay *vs,

                       bool password,

                       bool sasl,

                       bool websocket,

                       Error **errp)

{

    /*

     * We have a choice of 3 authentication options

     *

     *   1. none

     *   2. vnc

     *   3. sasl

     *

     * The channel can be run in 2 modes

     *

     *   1. clear

     *   2. tls

     *

     * And TLS can use 2 types of credentials

     *

     *   1. anon

     *   2. x509

     *

     * We thus have 9 possible logical combinations

     *

     *   1. clear + none

     *   2. clear + vnc

     *   3. clear + sasl

     *   4. tls + anon + none

     *   5. tls + anon + vnc

     *   6. tls + anon + sasl

     *   7. tls + x509 + none

     *   8. tls + x509 + vnc

     *   9. tls + x509 + sasl

     *

     * These need to be mapped into the VNC auth schemes

     * in an appropriate manner. In regular VNC, all the

     * TLS options get mapped into VNC_AUTH_VENCRYPT

     * sub-auth types.

     *

     * In websockets, the https:// protocol already provides

     * TLS support, so there is no need to make use of the

     * VeNCrypt extension. Furthermore, websockets browser

     * clients could not use VeNCrypt even if they wanted to,

     * as they cannot control when the TLS handshake takes

     * place. Thus there is no option but to rely on https://,

     * meaning combinations 4->6 and 7->9 will be mapped to

     * VNC auth schemes in the same way as combos 1->3.

     *

     * Regardless of fact that we have a different mapping to

     * VNC auth mechs for plain VNC vs websockets VNC, the end

     * result has the same security characteristics.

     */

    if (password) {

        if (vs->tlscreds) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 password auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;

            } else if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS password auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vs->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with password auth\n");

            vs->auth = VNC_AUTH_VNC;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_VNC;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    } else if (sasl) {

        if (vs->tlscreds) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;

            } else if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vs->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with SASL auth\n");

            vs->auth = VNC_AUTH_SASL;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_SASL;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    } else {

        if (vs->tlscreds) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                    TYPE_QCRYPTO_TLS_CREDS_X509)) {

                VNC_DEBUG("Initializing VNC server with x509 no auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;

            } else if (object_dynamic_cast(OBJECT(vs->tlscreds),

                                           TYPE_QCRYPTO_TLS_CREDS_ANON)) {

                VNC_DEBUG("Initializing VNC server with TLS no auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;

            } else {

                error_setg(errp,

                           "Unsupported TLS cred type %s",

                           object_get_typename(OBJECT(vs->tlscreds)));

                return -1;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with no auth\n");

            vs->auth = VNC_AUTH_NONE;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_NONE;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    }

    return 0;

}


void bdrv_flush(BlockDriverState *bs)
{
    if (bs->drv && bs->drv->bdrv_flush)
        bs->drv->bdrv_flush(bs);


void block_job_cancel_sync(BlockJob *job)

{

    BlockDriverState *bs = job->bs;

    assert(bs->job == job);

    block_job_cancel(job);

    while (bs->job != NULL && bs->job->busy) {

        qemu_aio_wait();

    }

}


static int read_header(ShortenContext *s)

{

    int i, ret;

    int maxnlpc = 0;

    /* shorten signature */

    if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {

        av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");

        return -1;

    }

    s->lpcqoffset = 0;

    s->blocksize = DEFAULT_BLOCK_SIZE;

    s->nmean = -1;

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

    s->internal_ftype = get_uint(s, TYPESIZE);

    s->channels = get_uint(s, CHANSIZE);

    if (s->channels > MAX_CHANNELS) {

        av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);

        return -1;

    }

    s->avctx->channels = s->channels;

    /* get blocksize if version > 0 */

    if (s->version > 0) {

        int skip_bytes, blocksize;

        blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));

        if (!blocksize || blocksize > MAX_BLOCKSIZE) {

            av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",

                   blocksize);

            return AVERROR(EINVAL);

        }

        s->blocksize = blocksize;

        maxnlpc = get_uint(s, LPCQSIZE);

        s->nmean = get_uint(s, 0);

        skip_bytes = get_uint(s, NSKIPSIZE);

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

            skip_bits(&s->gb, 8);

        }

    }

    s->nwrap = FFMAX(NWRAP, maxnlpc);

    if ((ret = allocate_buffers(s)) < 0)

        return ret;

    if ((ret = init_offset(s)) < 0)

        return ret;

    if (s->version > 1)

        s->lpcqoffset = V2LPCQOFFSET;

    if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {

        av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");

        return -1;

    }

    s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);

    if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);

        return -1;

    }

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

        s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);

    if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)

        return -1;

    s->cur_chan = 0;

    s->bitshift = 0;

    s->got_header = 1;

    return 0;

}


void parse_options(void *optctx, int argc, char **argv, const OptionDef *options,

                   void (*parse_arg_function)(void *, const char*))

{

    const char *opt;

    int optindex, handleoptions = 1, ret;

    /* perform system-dependent conversions for arguments list */

    prepare_app_arguments(&argc, &argv);

    /* parse options */

    optindex = 1;

    while (optindex < argc) {

        opt = argv[optindex++];

        if (handleoptions && opt[0] == '-' && opt[1] != '\0') {

            if (opt[1] == '-' && opt[2] == '\0') {

                handleoptions = 0;

                continue;

            }

            opt++;

            if ((ret = parse_option(optctx, opt, argv[optindex], options)) < 0)

                exit(1);

            optindex += ret;

        } else {

            if (parse_arg_function)

                parse_arg_function(optctx, opt);

        }

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    X86IOMMUClass *x86_class = X86_IOMMU_CLASS(klass);

    dc->reset = vtd_reset;

    dc->vmsd = &vtd_vmstate;

    dc->props = vtd_properties;

    dc->hotpluggable = false;

    x86_class->realize = vtd_realize;

    x86_class->int_remap = vtd_int_remap;

}


static void audio_capture(void *opaque, void *buf, int size)

{

    VncState *vs = opaque;

    vnc_lock_output(vs);

    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);

    vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);

    vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);

    vnc_write_u32(vs, size);

    vnc_write(vs, buf, size);

    vnc_unlock_output(vs);

    vnc_flush(vs);

}


void ff_aac_search_for_ltp(AACEncContext *s, SingleChannelElement *sce,

                           int common_window)

{

    int w, g, w2, i, start = 0, count = 0;

    int saved_bits = -(15 + FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB));

    float *C34 = &s->scoefs[128*0], *PCD = &s->scoefs[128*1];

    float *PCD34 = &s->scoefs[128*2];

    const int max_ltp = FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB);

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE ||

        !sce->ics.ltp.lag)

        return;

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        start = 0;

        for (g = 0;  g < sce->ics.num_swb; g++) {

            int bits1 = 0, bits2 = 0;

            float dist1 = 0.0f, dist2 = 0.0f;

            if (w*16+g > max_ltp) {

                start += sce->ics.swb_sizes[g];

                continue;

            }

            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                int bits_tmp1, bits_tmp2;

                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];

                for (i = 0; i < sce->ics.swb_sizes[g]; i++)

                    PCD[i] = sce->coeffs[start+(w+w2)*128+i] - sce->lcoeffs[start+(w+w2)*128+i];

                abs_pow34_v(C34,  &sce->coeffs[start+(w+w2)*128],  sce->ics.swb_sizes[g]);

                abs_pow34_v(PCD34, PCD, sce->ics.swb_sizes[g]);

                dist1 += quantize_band_cost(s, &sce->coeffs[start+(w+w2)*128], C34, sce->ics.swb_sizes[g],

                                            sce->sf_idx[(w+w2)*16+g], sce->band_type[(w+w2)*16+g],

                                            s->lambda/band->threshold, INFINITY, &bits_tmp1, NULL, 0);

                dist2 += quantize_band_cost(s, PCD, PCD34, sce->ics.swb_sizes[g],

                                            sce->sf_idx[(w+w2)*16+g],

                                            sce->band_type[(w+w2)*16+g],

                                            s->lambda/band->threshold, INFINITY, &bits_tmp2, NULL, 0);

                bits1 += bits_tmp1;

                bits2 += bits_tmp2;

            }

            if (dist2 < dist1 && bits2 < bits1) {

                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)

                    for (i = 0; i < sce->ics.swb_sizes[g]; i++)

                        sce->coeffs[start+(w+w2)*128+i] -= sce->lcoeffs[start+(w+w2)*128+i];

                sce->ics.ltp.used[w*16+g] = 1;

                saved_bits += bits1 - bits2;

                count++;

            }

            start += sce->ics.swb_sizes[g];

        }

    }

    sce->ics.ltp.present = !!count && (saved_bits >= 0);

    sce->ics.predictor_present = !!sce->ics.ltp.present;

    /* Reset any marked sfbs */

    if (!sce->ics.ltp.present && !!count) {

        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

            start = 0;

            for (g = 0;  g < sce->ics.num_swb; g++) {

                if (sce->ics.ltp.used[w*16+g]) {

                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                        for (i = 0; i < sce->ics.swb_sizes[g]; i++) {

                            sce->coeffs[start+(w+w2)*128+i] += sce->lcoeffs[start+(w+w2)*128+i];

                        }

                    }

                }

                start += sce->ics.swb_sizes[g];

            }

        }

    }

}


void av_opencl_buffer_release(cl_mem *cl_buf)

{

    cl_int status = 0;

    if (!cl_buf)

        return;

    status = clReleaseMemObject(*cl_buf);

    if (status != CL_SUCCESS) {

        av_log(&openclutils, AV_LOG_ERROR, "Could not release OpenCL buffer: %s\n", opencl_errstr(status));

    }

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

}


int inet_connect_opts(QemuOpts *opts, bool *in_progress, Error **errp)

{

    struct addrinfo ai,*res,*e;

    const char *addr;

    const char *port;

    char uaddr[INET6_ADDRSTRLEN+1];

    char uport[33];

    int sock,rc;

    bool block;

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

    ai.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;

    ai.ai_family = PF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    if (in_progress) {

        *in_progress = false;

    }

    addr = qemu_opt_get(opts, "host");

    port = qemu_opt_get(opts, "port");

    block = qemu_opt_get_bool(opts, "block", 0);

    if (addr == NULL || port == NULL) {

        fprintf(stderr, "inet_connect: host and/or port not specified\n");

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

        return -1;

    }

    if (qemu_opt_get_bool(opts, "ipv4", 0))

        ai.ai_family = PF_INET;

    if (qemu_opt_get_bool(opts, "ipv6", 0))

        ai.ai_family = PF_INET6;

    /* lookup */

    if (0 != (rc = getaddrinfo(addr, port, &ai, &res))) {

        fprintf(stderr,"getaddrinfo(%s,%s): %s\n", addr, port,

                gai_strerror(rc));

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

	return -1;

    }

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

        if (getnameinfo((struct sockaddr*)e->ai_addr,e->ai_addrlen,

                            uaddr,INET6_ADDRSTRLEN,uport,32,

                            NI_NUMERICHOST | NI_NUMERICSERV) != 0) {

            fprintf(stderr,"%s: getnameinfo: oops\n", __FUNCTION__);

            continue;

        }

        sock = qemu_socket(e->ai_family, e->ai_socktype, e->ai_protocol);

        if (sock < 0) {

            fprintf(stderr,"%s: socket(%s): %s\n", __FUNCTION__,

            inet_strfamily(e->ai_family), strerror(errno));

            continue;

        }

        setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(void*)&on,sizeof(on));

        if (!block) {

            socket_set_nonblock(sock);

        }

        /* connect to peer */

        do {

            rc = 0;

            if (connect(sock, e->ai_addr, e->ai_addrlen) < 0) {

                rc = -socket_error();

            }

        } while (rc == -EINTR);

  #ifdef _WIN32

        if (!block && (rc == -EINPROGRESS || rc == -EWOULDBLOCK

                       || rc == -WSAEALREADY)) {

  #else

        if (!block && (rc == -EINPROGRESS)) {

  #endif

            if (in_progress) {

                *in_progress = true;

            }

            error_set(errp, QERR_SOCKET_CONNECT_IN_PROGRESS);

        } else if (rc < 0) {

            if (NULL == e->ai_next)

                fprintf(stderr, "%s: connect(%s,%s,%s,%s): %s\n", __FUNCTION__,

                        inet_strfamily(e->ai_family),

                        e->ai_canonname, uaddr, uport, strerror(errno));

            closesocket(sock);

            continue;

        }

        freeaddrinfo(res);

        return sock;

    }

    error_set(errp, QERR_SOCKET_CONNECT_FAILED);

    freeaddrinfo(res);

    return -1;

}


int ff_rv34_decode_frame(AVCodecContext *avctx,

                            void *data, int *got_picture_ptr,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    RV34DecContext *r = avctx->priv_data;

    MpegEncContext *s = &r->s;

    AVFrame *pict = data;

    SliceInfo si;

    int i, ret;

    int slice_count;

    const uint8_t *slices_hdr = NULL;

    int last = 0;

    /* no supplementary picture */

    if (buf_size == 0) {

        /* special case for last picture */

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

            if ((ret = av_frame_ref(pict, &s->next_picture_ptr->f)) < 0)

                return ret;

            s->next_picture_ptr = NULL;

            *got_picture_ptr = 1;

        }

        return 0;

    }

    if(!avctx->slice_count){

        slice_count = (*buf++) + 1;

        slices_hdr = buf + 4;

        buf += 8 * slice_count;

        buf_size -= 1 + 8 * slice_count;

    }else

        slice_count = avctx->slice_count;

    //parse first slice header to check whether this frame can be decoded

    if(get_slice_offset(avctx, slices_hdr, 0) < 0 ||

       get_slice_offset(avctx, slices_hdr, 0) > buf_size){

        av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, 0), (buf_size-get_slice_offset(avctx, slices_hdr, 0))*8);

    if(r->parse_slice_header(r, &r->s.gb, &si) < 0 || si.start){

        av_log(avctx, AV_LOG_ERROR, "First slice header is incorrect\n");

        return AVERROR_INVALIDDATA;

    }

    if ((!s->last_picture_ptr || !s->last_picture_ptr->f.data[0]) &&

        si.type == AV_PICTURE_TYPE_B) {

        av_log(avctx, AV_LOG_ERROR, "Invalid decoder state: B-frame without "

               "reference data.\n");

        return AVERROR_INVALIDDATA;

    }

    if(   (avctx->skip_frame >= AVDISCARD_NONREF && si.type==AV_PICTURE_TYPE_B)

       || (avctx->skip_frame >= AVDISCARD_NONKEY && si.type!=AV_PICTURE_TYPE_I)

       ||  avctx->skip_frame >= AVDISCARD_ALL)

        return avpkt->size;

    /* first slice */

    if (si.start == 0) {

        if (s->mb_num_left > 0) {

            av_log(avctx, AV_LOG_ERROR, "New frame but still %d MB left.",

                   s->mb_num_left);

            ff_er_frame_end(&s->er);

            ff_MPV_frame_end(s);

        }

        if (s->width != si.width || s->height != si.height) {

            int err;

            av_log(s->avctx, AV_LOG_WARNING, "Changing dimensions to %dx%d\n",

                   si.width, si.height);

            s->width  = si.width;

            s->height = si.height;

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

            if (err < 0)

                return err;

            if ((err = ff_MPV_common_frame_size_change(s)) < 0)

                return err;

            if ((err = rv34_decoder_realloc(r)) < 0)

                return err;

        }

        s->pict_type = si.type ? si.type : AV_PICTURE_TYPE_I;

        if (ff_MPV_frame_start(s, s->avctx) < 0)

            return -1;

        ff_mpeg_er_frame_start(s);

        if (!r->tmp_b_block_base) {

            int i;

            r->tmp_b_block_base = av_malloc(s->linesize * 48);

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

                r->tmp_b_block_y[i] = r->tmp_b_block_base

                                      + i * 16 * s->linesize;

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

                r->tmp_b_block_uv[i] = r->tmp_b_block_base + 32 * s->linesize

                                       + (i >> 1) * 8 * s->uvlinesize

                                       + (i &  1) * 16;

        }

        r->cur_pts = si.pts;

        if (s->pict_type != AV_PICTURE_TYPE_B) {

            r->last_pts = r->next_pts;

            r->next_pts = r->cur_pts;

        } else {

            int refdist = GET_PTS_DIFF(r->next_pts, r->last_pts);

            int dist0   = GET_PTS_DIFF(r->cur_pts,  r->last_pts);

            int dist1   = GET_PTS_DIFF(r->next_pts, r->cur_pts);

            if(!refdist){

                r->mv_weight1 = r->mv_weight2 = r->weight1 = r->weight2 = 8192;

                r->scaled_weight = 0;

            }else{

                r->mv_weight1 = (dist0 << 14) / refdist;

                r->mv_weight2 = (dist1 << 14) / refdist;

                if((r->mv_weight1|r->mv_weight2) & 511){

                    r->weight1 = r->mv_weight1;

                    r->weight2 = r->mv_weight2;

                    r->scaled_weight = 0;

                }else{

                    r->weight1 = r->mv_weight1 >> 9;

                    r->weight2 = r->mv_weight2 >> 9;

                    r->scaled_weight = 1;

                }

            }

        }

        s->mb_x = s->mb_y = 0;

        ff_thread_finish_setup(s->avctx);

    } else if (HAVE_THREADS &&

               (s->avctx->active_thread_type & FF_THREAD_FRAME)) {

        av_log(s->avctx, AV_LOG_ERROR, "Decoder needs full frames in frame "

               "multithreading mode (start MB is %d).\n", si.start);

        return AVERROR_INVALIDDATA;

    }

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

        int offset = get_slice_offset(avctx, slices_hdr, i);

        int size;

        if(i+1 == slice_count)

            size = buf_size - offset;

        else

            size = get_slice_offset(avctx, slices_hdr, i+1) - offset;

        if(offset < 0 || offset > buf_size){

            av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");

            break;

        }

        r->si.end = s->mb_width * s->mb_height;

        s->mb_num_left = r->s.mb_x + r->s.mb_y*r->s.mb_width - r->si.start;

        if(i+1 < slice_count){

            if (get_slice_offset(avctx, slices_hdr, i+1) < 0 ||

                get_slice_offset(avctx, slices_hdr, i+1) > buf_size) {

                av_log(avctx, AV_LOG_ERROR, "Slice offset is invalid\n");

                break;

            }

            init_get_bits(&s->gb, buf+get_slice_offset(avctx, slices_hdr, i+1), (buf_size-get_slice_offset(avctx, slices_hdr, i+1))*8);

            if(r->parse_slice_header(r, &r->s.gb, &si) < 0){

                if(i+2 < slice_count)

                    size = get_slice_offset(avctx, slices_hdr, i+2) - offset;

                else

                    size = buf_size - offset;

            }else

                r->si.end = si.start;

        }

        if (size < 0 || size > buf_size - offset) {

            av_log(avctx, AV_LOG_ERROR, "Slice size is invalid\n");

            break;

        }

        last = rv34_decode_slice(r, r->si.end, buf + offset, size);

        if(last)

            break;

    }

    if (s->current_picture_ptr) {

        if (last) {

            if(r->loop_filter)

                r->loop_filter(r, s->mb_height - 1);

            ret = finish_frame(avctx, pict);

            if (ret < 0)

                return ret;

            *got_picture_ptr = ret;

        } else if (HAVE_THREADS &&

                   (s->avctx->active_thread_type & FF_THREAD_FRAME)) {

            av_log(avctx, AV_LOG_INFO, "marking unfished frame as finished\n");

            /* always mark the current frame as finished, frame-mt supports

             * only complete frames */

            ff_er_frame_end(&s->er);

            ff_MPV_frame_end(s);

            s->mb_num_left = 0;

            ff_thread_report_progress(&s->current_picture_ptr->tf, INT_MAX, 0);

            return AVERROR_INVALIDDATA;

        }

    }

    return avpkt->size;

}


static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)

{

    int i, ret = 1;

    char filename[1000];

    const char *base[3] = { getenv("AVCONV_DATADIR"),

                            getenv("HOME"),

                            AVCONV_DATADIR,

                            };

    for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {

        if (!base[i])

            continue;

        if (codec_name) {

            snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],

                     i != 1 ? "" : "/.avconv", codec_name, preset_name);

            ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);

        }

        if (ret) {

            snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],

                     i != 1 ? "" : "/.avconv", preset_name);

            ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);

        }

    }

    return ret;

}


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

{

    int maxTrackID = 1, i;

    int64_t maxTrackLenTemp, maxTrackLen = 0;

    int version;

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

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

            maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);

            if(maxTrackLen < maxTrackLenTemp)

                maxTrackLen = maxTrackLenTemp;

            if(maxTrackID < mov->tracks[i].trackID)

                maxTrackID = mov->tracks[i].trackID;

        }

    }

    version = maxTrackLen < UINT32_MAX ? 0 : 1;

    (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */

    put_tag(pb, "mvhd");

    put_byte(pb, version);

    put_be24(pb, 0); /* flags */

    if (version == 1) {

        put_be64(pb, mov->time);

        put_be64(pb, mov->time);

    } else {

        put_be32(pb, mov->time); /* creation time */

        put_be32(pb, mov->time); /* modification time */

    }

    put_be32(pb, mov->timescale); /* timescale */

    (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */

    put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */

    put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */

    put_be16(pb, 0); /* reserved */

    put_be32(pb, 0); /* reserved */

    put_be32(pb, 0); /* reserved */

    /* Matrix structure */

    put_be32(pb, 0x00010000); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x00010000); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x40000000); /* reserved */

    put_be32(pb, 0); /* reserved (preview time) */

    put_be32(pb, 0); /* reserved (preview duration) */

    put_be32(pb, 0); /* reserved (poster time) */

    put_be32(pb, 0); /* reserved (selection time) */

    put_be32(pb, 0); /* reserved (selection duration) */

    put_be32(pb, 0); /* reserved (current time) */

    put_be32(pb, maxTrackID+1); /* Next track id */

    return 0x6c;

}


static void apply_tns(float coef[1024], TemporalNoiseShaping *tns,

                      IndividualChannelStream *ics, int decode)

{

    const int mmm = FFMIN(ics->tns_max_bands, ics->max_sfb);

    int w, filt, m, i;

    int bottom, top, order, start, end, size, inc;

    float lpc[TNS_MAX_ORDER];

    float tmp[TNS_MAX_ORDER];

    for (w = 0; w < ics->num_windows; w++) {

        bottom = ics->num_swb;

        for (filt = 0; filt < tns->n_filt[w]; filt++) {

            top    = bottom;

            bottom = FFMAX(0, top - tns->length[w][filt]);

            order  = tns->order[w][filt];

            if (order == 0)

                continue;

            // tns_decode_coef

            compute_lpc_coefs(tns->coef[w][filt], order, lpc, 0, 0, 0);

            start = ics->swb_offset[FFMIN(bottom, mmm)];

            end   = ics->swb_offset[FFMIN(   top, mmm)];

            if ((size = end - start) <= 0)

                continue;

            if (tns->direction[w][filt]) {

                inc = -1;

                start = end - 1;

            } else {

                inc = 1;

            }

            start += w * 128;

            if (decode) {

                // ar filter

                for (m = 0; m < size; m++, start += inc)

                    for (i = 1; i <= FFMIN(m, order); i++)

                        coef[start] -= coef[start - i * inc] * lpc[i - 1];

            } else {

                // ma filter

                for (m = 0; m < size; m++, start += inc) {

                    tmp[0] = coef[start];

                    for (i = 1; i <= FFMIN(m, order); i++)

                        coef[start] += tmp[i] * lpc[i - 1];

                    for (i = order; i > 0; i--)

                        tmp[i] = tmp[i - 1];

                }

            }

        }

    }

}


static int g2m_init_buffers(G2MContext *c)

{

    int aligned_height;

    if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {

        c->framebuf_stride = FFALIGN(c->width * 3, 16);

        aligned_height     = FFALIGN(c->height,    16);

        av_free(c->framebuf);

        c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);

        if (!c->framebuf)

            return AVERROR(ENOMEM);

    }

    if (!c->synth_tile || !c->jpeg_tile ||

        c->old_tile_w < c->tile_width ||

        c->old_tile_h < c->tile_height) {

        c->tile_stride = FFALIGN(c->tile_width * 3, 16);

        aligned_height = FFALIGN(c->tile_height,    16);

        av_free(c->synth_tile);

        av_free(c->jpeg_tile);

        av_free(c->kempf_buf);

        av_free(c->kempf_flags);

        c->synth_tile  = av_mallocz(c->tile_stride      * aligned_height);

        c->jpeg_tile   = av_mallocz(c->tile_stride      * aligned_height);

        c->kempf_buf   = av_mallocz((c->tile_width + 1) * aligned_height

                                    + FF_INPUT_BUFFER_PADDING_SIZE);

        c->kempf_flags = av_mallocz( c->tile_width      * aligned_height);

        if (!c->synth_tile || !c->jpeg_tile ||

            !c->kempf_buf || !c->kempf_flags)

            return AVERROR(ENOMEM);

    }

    return 0;

}


static uint32_t rtl8139_io_readb(void *opaque, uint8_t addr)

{

    RTL8139State *s = opaque;

    int ret;

    addr &= 0xff;

    switch (addr)

    {

        case MAC0 ... MAC0+5:

            ret = s->phys[addr - MAC0];

            break;

        case MAC0+6 ... MAC0+7:

            ret = 0;

            break;

        case MAR0 ... MAR0+7:

            ret = s->mult[addr - MAR0];

            break;

        case ChipCmd:

            ret = rtl8139_ChipCmd_read(s);

            break;

        case Cfg9346:

            ret = rtl8139_Cfg9346_read(s);

            break;

        case Config0:

            ret = rtl8139_Config0_read(s);

            break;

        case Config1:

            ret = rtl8139_Config1_read(s);

            break;

        case Config3:

            ret = rtl8139_Config3_read(s);

            break;

        case Config4:

            ret = rtl8139_Config4_read(s);

            break;

        case Config5:

            ret = rtl8139_Config5_read(s);

            break;

        case MediaStatus:

            ret = 0xd0;

            DPRINTF("MediaStatus read 0x%x\n", ret);

            break;

        case HltClk:

            ret = s->clock_enabled;

            DPRINTF("HltClk read 0x%x\n", ret);

            break;

        case PCIRevisionID:

            ret = RTL8139_PCI_REVID;

            DPRINTF("PCI Revision ID read 0x%x\n", ret);

            break;

        case TxThresh:

            ret = s->TxThresh;

            DPRINTF("C+ TxThresh read(b) val=0x%02x\n", ret);

            break;

        case 0x43: /* Part of TxConfig register. Windows driver tries to read it */

            ret = s->TxConfig >> 24;

            DPRINTF("RTL8139C TxConfig at 0x43 read(b) val=0x%02x\n", ret);

            break;

        default:

            DPRINTF("not implemented read(b) addr=0x%x\n", addr);

            ret = 0;

            break;

    }

    return ret;

}


int ff_mpv_common_frame_size_change(MpegEncContext *s)

{

    int i, err = 0;

    if (!s->context_initialized)

        return AVERROR(EINVAL);

    if (s->slice_context_count > 1) {

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

            free_duplicate_context(s->thread_context[i]);

        }

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

            av_freep(&s->thread_context[i]);

        }

    } else

        free_duplicate_context(s);

    free_context_frame(s);

    if (s->picture)

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

                s->picture[i].needs_realloc = 1;

        }

    s->last_picture_ptr         =

    s->next_picture_ptr         =

    s->current_picture_ptr      = NULL;

    // init

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else

        s->mb_height = (s->height + 15) / 16;

    if ((s->width || s->height) &&

        (err = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)

        goto fail;

    if ((err = init_context_frame(s)))

        goto fail;

    s->thread_context[0]   = s;

    if (s->width && s->height) {

        int nb_slices = s->slice_context_count;

        if (nb_slices > 1) {

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

                s->thread_context[i] = av_malloc(sizeof(MpegEncContext));

                memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

            }

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

                if ((err = init_duplicate_context(s->thread_context[i])) < 0)

                    goto fail;

                    s->thread_context[i]->start_mb_y =

                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;

                    s->thread_context[i]->end_mb_y   =

                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;

            }

        } else {

            err = init_duplicate_context(s);

            if (err < 0)

                goto fail;

            s->start_mb_y = 0;

            s->end_mb_y   = s->mb_height;

        }

        s->slice_context_count = nb_slices;

    }

    return 0;

 fail:

    ff_mpv_common_end(s);

    return err;

}


void ff_snow_horizontal_compose97i_mmx(DWTELEM *b, int width){

    const int w2= (width+1)>>1;

    DWTELEM temp[width >> 1];

    const int w_l= (width>>1);

    const int w_r= w2 - 1;

    int i;

    { // Lift 0

        DWTELEM * const ref = b + w2 - 1;

        i = 1;

        b[0] = b[0] - ((W_DM * 2 * ref[1]+W_DO)>>W_DS);

        asm volatile(

            "pcmpeqd    %%mm7, %%mm7         \n\t"

            "pslld        $31, %%mm7         \n\t"

            "psrld        $29, %%mm7         \n\t"

           ::);

        for(; i<w_l-3; i+=4){

            asm volatile(

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

                "movq    8(%1), %%mm6        \n\t"

                "paddd   4(%1), %%mm2        \n\t"

                "paddd  12(%1), %%mm6        \n\t"

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

                "movq    %%mm6, %%mm4        \n\t"

                "paddd   %%mm2, %%mm2        \n\t"

                "paddd   %%mm6, %%mm6        \n\t"

                "paddd   %%mm0, %%mm2        \n\t"

                "paddd   %%mm4, %%mm6        \n\t"

                "paddd   %%mm7, %%mm2        \n\t"

                "paddd   %%mm7, %%mm6        \n\t"

                "psrad      $3, %%mm2        \n\t"

                "psrad      $3, %%mm6        \n\t"

                "movq     (%0), %%mm0        \n\t"

                "movq    8(%0), %%mm4        \n\t"

                "psubd   %%mm2, %%mm0        \n\t"

                "psubd   %%mm6, %%mm4        \n\t"

                "movq    %%mm0, (%0)         \n\t"

                "movq    %%mm4, 8(%0)        \n\t"

                :: "r"(&b[i]), "r"(&ref[i])

                 : "memory"

               );

        }

        snow_horizontal_compose_lift_lead_out(i, b, b, ref, width, w_l, 0, W_DM, W_DO, W_DS);

    }

    { // Lift 1

        DWTELEM * const dst = b+w2;

        i = 0;

        for(; i<w_r-3; i+=4){

            asm volatile(

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

                "movq    8(%1), %%mm6        \n\t"

                "paddd   4(%1), %%mm2        \n\t"

                "paddd  12(%1), %%mm6        \n\t"

                "movq     (%0), %%mm0        \n\t"

                "movq    8(%0), %%mm4        \n\t"

                "psubd   %%mm2, %%mm0        \n\t"

                "psubd   %%mm6, %%mm4        \n\t"

                "movq    %%mm0, (%0)         \n\t"

                "movq    %%mm4, 8(%0)        \n\t"

                :: "r"(&dst[i]), "r"(&b[i])

                 : "memory"

               );

        }

        snow_horizontal_compose_lift_lead_out(i, dst, dst, b, width, w_r, 1, W_CM, W_CO, W_CS);

    }

    { // Lift 2

        DWTELEM * const ref = b+w2 - 1;

        i = 1;

        b[0] = b[0] + (((2 * ref[1] + W_BO) + 4 * b[0]) >> W_BS);

        asm volatile(

            "pslld          $1, %%mm7        \n\t"

           ::);

        for(; i<w_l-3; i+=4){

            asm volatile(

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

                "movq    8(%1), %%mm4        \n\t"

                "paddd   4(%1), %%mm0        \n\t"

                "paddd  12(%1), %%mm4        \n\t"

                "paddd   %%mm7, %%mm0        \n\t"

                "paddd   %%mm7, %%mm4        \n\t"

                "psrad      $2, %%mm0        \n\t"

                "psrad      $2, %%mm4        \n\t"

                "movq     (%0), %%mm1        \n\t"

                "movq    8(%0), %%mm5        \n\t"

                "paddd   %%mm1, %%mm0        \n\t"

                "paddd   %%mm5, %%mm4        \n\t"

                "psrad      $2, %%mm0        \n\t"

                "psrad      $2, %%mm4        \n\t"

                "paddd   %%mm1, %%mm0        \n\t"

                "paddd   %%mm5, %%mm4        \n\t"

                "movq    %%mm0, (%0)         \n\t"

                "movq    %%mm4, 8(%0)        \n\t"

                :: "r"(&b[i]), "r"(&ref[i])

                 : "memory"

               );

        }

        snow_horizontal_compose_liftS_lead_out(i, b, b, ref, width, w_l);

    }

    { // Lift 3

        DWTELEM * const src = b+w2;

        i = 0;

        for(; i<w_r-3; i+=4){

            asm volatile(

                "movq    4(%1), %%mm2        \n\t"

                "movq   12(%1), %%mm6        \n\t"

                "paddd    (%1), %%mm2        \n\t"

                "paddd   8(%1), %%mm6        \n\t"

                "movq     (%0), %%mm0        \n\t"

                "movq    8(%0), %%mm4        \n\t"

                "paddd   %%mm2, %%mm0        \n\t"

                "paddd   %%mm6, %%mm4        \n\t"

                "psrad      $1, %%mm2        \n\t"

                "psrad      $1, %%mm6        \n\t"

                "paddd   %%mm0, %%mm2        \n\t"

                "paddd   %%mm4, %%mm6        \n\t"

                "movq    %%mm2, (%2)         \n\t"

                "movq    %%mm6, 8(%2)        \n\t"

                :: "r"(&src[i]), "r"(&b[i]), "r"(&temp[i])

                 : "memory"

               );

        }

        snow_horizontal_compose_lift_lead_out(i, temp, src, b, width, w_r, 1, -W_AM, W_AO+1, W_AS);

    }

    {

        snow_interleave_line_header(&i, width, b, temp);

        for (; (i & 0xE) != 0xE; i-=2){

            b[i+1] = temp[i>>1];

            b[i] = b[i>>1];

        }

        for (i-=14; i>=0; i-=16){

            asm volatile(

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

                "movq       8(%1), %%mm2       \n\t"

                "movq      16(%1), %%mm4       \n\t"

                "movq      24(%1), %%mm6       \n\t"

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

                "movq       8(%1), %%mm3       \n\t"

                "movq      16(%1), %%mm5       \n\t"

                "movq      24(%1), %%mm7       \n\t"

                "punpckldq   (%2), %%mm0       \n\t"

                "punpckldq  8(%2), %%mm2       \n\t"

                "punpckldq 16(%2), %%mm4       \n\t"

                "punpckldq 24(%2), %%mm6       \n\t"

                "movq       %%mm0, (%0)        \n\t"

                "movq       %%mm2, 16(%0)      \n\t"

                "movq       %%mm4, 32(%0)      \n\t"

                "movq       %%mm6, 48(%0)      \n\t"

                "punpckhdq   (%2), %%mm1       \n\t"

                "punpckhdq  8(%2), %%mm3       \n\t"

                "punpckhdq 16(%2), %%mm5       \n\t"

                "punpckhdq 24(%2), %%mm7       \n\t"

                "movq       %%mm1, 8(%0)       \n\t"

                "movq       %%mm3, 24(%0)      \n\t"

                "movq       %%mm5, 40(%0)      \n\t"

                "movq       %%mm7, 56(%0)      \n\t"

                :: "r"(&b[i]), "r"(&b[i>>1]), "r"(&temp[i>>1])

                 : "memory"

               );

        }

    }

}


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

{

    OMAContext *oc = s->priv_data;

    int packet_size = s->streams[0]->codec->block_align;

    int ret = av_get_packet(s->pb, pkt, packet_size);

    if (ret <= 0)

        return AVERROR(EIO);

    pkt->stream_index = 0;

    if (oc->encrypted) {

        /* previous unencrypted block saved in IV for

         * the next packet (CBC mode) */

        av_des_crypt(&oc->av_des, pkt->data, pkt->data,

                     (packet_size >> 3), oc->iv, 1);

    }

    return ret;

}


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

{

    RTSPState *rt = s->priv_data;

    int ret, len;

    uint8_t buf[10 * RTP_MAX_PACKET_LENGTH];

    RTSPStream *rtsp_st;

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

    if (rt->cur_transport_priv) {

        if (rt->transport == RTSP_TRANSPORT_RDT)

            ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);

        else

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

        if (ret == 0) {

            rt->cur_transport_priv = NULL;

            return 0;

        } else if (ret == 1) {

            return 0;

        } else {

            rt->cur_transport_priv = NULL;

        }

    }

    /* read next RTP packet */

 redo:

    switch(rt->lower_transport) {

    default:

#if CONFIG_RTSP_DEMUXER

    case RTSP_LOWER_TRANSPORT_TCP:

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

        break;

#endif

    case RTSP_LOWER_TRANSPORT_UDP:

    case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:

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

        if (len >=0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)

            rtp_check_and_send_back_rr(rtsp_st->transport_priv, len);

        break;

    }

    if (len < 0)

        return len;

    if (len == 0)

        return AVERROR_EOF;

    if (rt->transport == RTSP_TRANSPORT_RDT)

        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, buf, len);

    else

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

    if (ret < 0)

        goto redo;

    if (ret == 1) {

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

        rt->cur_transport_priv = rtsp_st->transport_priv;

    }

    return ret;

}


rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)

{

    RTSPState *rt = s->priv_data;

    AVStream *st = NULL;

    /* open the RTP context */

    if (rtsp_st->stream_index >= 0)

        st = s->streams[rtsp_st->stream_index];

    if (!st)

        s->ctx_flags |= AVFMTCTX_NOHEADER;

    if (rt->transport == RTSP_TRANSPORT_RDT)

        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,

                                            rtsp_st->dynamic_protocol_context,

                                            rtsp_st->dynamic_handler);

    else

        rtsp_st->transport_priv = rtp_parse_open(s, st, rtsp_st->rtp_handle,

                                         rtsp_st->sdp_payload_type,

                                         &rtsp_st->rtp_payload_data);

    if (!rtsp_st->transport_priv) {

         return AVERROR(ENOMEM);

    } else if (rt->transport != RTSP_TRANSPORT_RDT) {

        if(rtsp_st->dynamic_handler) {

            rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,

                                           rtsp_st->dynamic_protocol_context,

                                           rtsp_st->dynamic_handler);

        }

    }

    return 0;

}


void net_tx_pkt_update_ip_checksums(struct NetTxPkt *pkt)

{

    uint16_t csum;

    uint32_t ph_raw_csum;

    assert(pkt);

    uint8_t gso_type = pkt->virt_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN;

    struct ip_header *ip_hdr;

    if (VIRTIO_NET_HDR_GSO_TCPV4 != gso_type &&

        VIRTIO_NET_HDR_GSO_UDP != gso_type) {

        return;

    }

    ip_hdr = pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_base;

    if (pkt->payload_len + pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len >

        ETH_MAX_IP_DGRAM_LEN) {

        return;

    }

    ip_hdr->ip_len = cpu_to_be16(pkt->payload_len +

        pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len);

    /* Calculate IP header checksum                    */

    ip_hdr->ip_sum = 0;

    csum = net_raw_checksum((uint8_t *)ip_hdr,

        pkt->vec[NET_TX_PKT_L3HDR_FRAG].iov_len);

    ip_hdr->ip_sum = cpu_to_be16(csum);

    /* Calculate IP pseudo header checksum             */

    ph_raw_csum = eth_calc_pseudo_hdr_csum(ip_hdr, pkt->payload_len);

    csum = cpu_to_be16(~net_checksum_finish(ph_raw_csum));

    iov_from_buf(&pkt->vec[NET_TX_PKT_PL_START_FRAG], pkt->payload_frags,

                 pkt->virt_hdr.csum_offset, &csum, sizeof(csum));

}


void ff_print_debug_info2(AVCodecContext *avctx, AVFrame *pict, uint8_t *mbskip_table,

                         uint32_t *mbtype_table, int8_t *qscale_table, int16_t (*motion_val[2])[2],

                         int *low_delay,

                         int mb_width, int mb_height, int mb_stride, int quarter_sample)

{

    if ((avctx->flags2 & AV_CODEC_FLAG2_EXPORT_MVS) && mbtype_table && motion_val[0]) {

        const int shift = 1 + quarter_sample;

        const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;

        const int mv_stride      = (mb_width << mv_sample_log2) +

                                   (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);

        int mb_x, mb_y, mbcount = 0;

        /* size is width * height * 2 * 4 where 2 is for directions and 4 is

         * for the maximum number of MB (4 MB in case of IS_8x8) */

        AVMotionVector *mvs = av_malloc_array(mb_width * mb_height, 2 * 4 * sizeof(AVMotionVector));

        if (!mvs)

            return;

        for (mb_y = 0; mb_y < mb_height; mb_y++) {

            for (mb_x = 0; mb_x < mb_width; mb_x++) {

                int i, direction, mb_type = mbtype_table[mb_x + mb_y * mb_stride];

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

                    if (!USES_LIST(mb_type, direction))

                        continue;

                    if (IS_8X8(mb_type)) {

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

                            int sx = mb_x * 16 + 4 + 8 * (i & 1);

                            int sy = mb_y * 16 + 4 + 8 * (i >> 1);

                            int xy = (mb_x * 2 + (i & 1) +

                                      (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);

                            int mx = (motion_val[direction][xy][0] >> shift) + sx;

                            int my = (motion_val[direction][xy][1] >> shift) + sy;

                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx, my, direction);

                        }

                    } else if (IS_16X8(mb_type)) {

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

                            int sx = mb_x * 16 + 8;

                            int sy = mb_y * 16 + 4 + 8 * i;

                            int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);

                            int mx = (motion_val[direction][xy][0] >> shift);

                            int my = (motion_val[direction][xy][1] >> shift);

                            if (IS_INTERLACED(mb_type))

                                my *= 2;

                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx + sx, my + sy, direction);

                        }

                    } else if (IS_8X16(mb_type)) {

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

                            int sx = mb_x * 16 + 4 + 8 * i;

                            int sy = mb_y * 16 + 8;

                            int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);

                            int mx = motion_val[direction][xy][0] >> shift;

                            int my = motion_val[direction][xy][1] >> shift;

                            if (IS_INTERLACED(mb_type))

                                my *= 2;

                            mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx + sx, my + sy, direction);

                        }

                    } else {

                          int sx = mb_x * 16 + 8;

                          int sy = mb_y * 16 + 8;

                          int xy = (mb_x + mb_y * mv_stride) << mv_sample_log2;

                          int mx = (motion_val[direction][xy][0]>>shift) + sx;

                          int my = (motion_val[direction][xy][1]>>shift) + sy;

                          mbcount += add_mb(mvs + mbcount, mb_type, sx, sy, mx, my, direction);

                    }

                }

            }

        }

        if (mbcount) {

            AVFrameSideData *sd;

            av_log(avctx, AV_LOG_DEBUG, "Adding %d MVs info to frame %d\n", mbcount, avctx->frame_number);

            sd = av_frame_new_side_data(pict, AV_FRAME_DATA_MOTION_VECTORS, mbcount * sizeof(AVMotionVector));

            if (!sd) {

                av_freep(&mvs);

                return;

            }

            memcpy(sd->data, mvs, mbcount * sizeof(AVMotionVector));

        }

        av_freep(&mvs);

    }

    /* TODO: export all the following to make them accessible for users (and filters) */

    if (avctx->hwaccel || !mbtype_table

#if FF_API_CAP_VDPAU

        || (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)

#endif

        )

        return;

    if (avctx->debug & (FF_DEBUG_SKIP | FF_DEBUG_QP | FF_DEBUG_MB_TYPE)) {

        int x,y;

        av_log(avctx, AV_LOG_DEBUG, "New frame, type: %c\n",

               av_get_picture_type_char(pict->pict_type));

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

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

                if (avctx->debug & FF_DEBUG_SKIP) {

                    int count = mbskip_table ? mbskip_table[x + y * mb_stride] : 0;

                    if (count > 9)

                        count = 9;

                    av_log(avctx, AV_LOG_DEBUG, "%1d", count);

                }

                if (avctx->debug & FF_DEBUG_QP) {

                    av_log(avctx, AV_LOG_DEBUG, "%2d",

                           qscale_table[x + y * mb_stride]);

                }

                if (avctx->debug & FF_DEBUG_MB_TYPE) {

                    int mb_type = mbtype_table[x + y * mb_stride];

                    // Type & MV direction

                    if (IS_PCM(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "P");

                    else if (IS_INTRA(mb_type) && IS_ACPRED(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "A");

                    else if (IS_INTRA4x4(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "i");

                    else if (IS_INTRA16x16(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "I");

                    else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "d");

                    else if (IS_DIRECT(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "D");

                    else if (IS_GMC(mb_type) && IS_SKIP(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "g");

                    else if (IS_GMC(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "G");

                    else if (IS_SKIP(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "S");

                    else if (!USES_LIST(mb_type, 1))

                        av_log(avctx, AV_LOG_DEBUG, ">");

                    else if (!USES_LIST(mb_type, 0))

                        av_log(avctx, AV_LOG_DEBUG, "<");

                    else {

                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));

                        av_log(avctx, AV_LOG_DEBUG, "X");

                    }

                    // segmentation

                    if (IS_8X8(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "+");

                    else if (IS_16X8(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "-");

                    else if (IS_8X16(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "|");

                    else if (IS_INTRA(mb_type) || IS_16X16(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, " ");

                    else

                        av_log(avctx, AV_LOG_DEBUG, "?");

                    if (IS_INTERLACED(mb_type))

                        av_log(avctx, AV_LOG_DEBUG, "=");

                    else

                        av_log(avctx, AV_LOG_DEBUG, " ");

                }

            }

            av_log(avctx, AV_LOG_DEBUG, "\n");

        }

    }

    if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) ||

        (avctx->debug_mv)) {

        int mb_y;

        int i;

        int h_chroma_shift, v_chroma_shift, block_height;

#if FF_API_VISMV

        const int shift = 1 + quarter_sample;

        uint8_t *ptr;

        const int width          = avctx->width;

        const int height         = avctx->height;

#endif

        const int mv_sample_log2 = avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_SVQ3 ? 2 : 1;

        const int mv_stride      = (mb_width << mv_sample_log2) +

                                   (avctx->codec->id == AV_CODEC_ID_H264 ? 0 : 1);

        *low_delay = 0; // needed to see the vectors without trashing the buffers

        avcodec_get_chroma_sub_sample(avctx->pix_fmt, &h_chroma_shift, &v_chroma_shift);

        av_frame_make_writable(pict);

        pict->opaque = NULL;

#if FF_API_VISMV

        ptr          = pict->data[0];

#endif

        block_height = 16 >> v_chroma_shift;

        for (mb_y = 0; mb_y < mb_height; mb_y++) {

            int mb_x;

            for (mb_x = 0; mb_x < mb_width; mb_x++) {

                const int mb_index = mb_x + mb_y * mb_stride;

#if FF_API_VISMV

                if ((avctx->debug_mv) && motion_val[0]) {

                    int type;

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

                        int direction = 0;

                        switch (type) {

                        case 0:

                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_P_FOR)) ||

                                (pict->pict_type!= AV_PICTURE_TYPE_P))

                                continue;

                            direction = 0;

                            break;

                        case 1:

                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_FOR)) ||

                                (pict->pict_type!= AV_PICTURE_TYPE_B))

                                continue;

                            direction = 0;

                            break;

                        case 2:

                            if ((!(avctx->debug_mv & FF_DEBUG_VIS_MV_B_BACK)) ||

                                (pict->pict_type!= AV_PICTURE_TYPE_B))

                                continue;

                            direction = 1;

                            break;

                        }

                        if (!USES_LIST(mbtype_table[mb_index], direction))

                            continue;

                        if (IS_8X8(mbtype_table[mb_index])) {

                            int i;

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

                                int sx = mb_x * 16 + 4 + 8 * (i & 1);

                                int sy = mb_y * 16 + 4 + 8 * (i >> 1);

                                int xy = (mb_x * 2 + (i & 1) +

                                          (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);

                                int mx = (motion_val[direction][xy][0] >> shift) + sx;

                                int my = (motion_val[direction][xy][1] >> shift) + sy;

                                draw_arrow(ptr, sx, sy, mx, my, width,

                                           height, pict->linesize[0], 100, 0, direction);

                            }

                        } else if (IS_16X8(mbtype_table[mb_index])) {

                            int i;

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

                                int sx = mb_x * 16 + 8;

                                int sy = mb_y * 16 + 4 + 8 * i;

                                int xy = (mb_x * 2 + (mb_y * 2 + i) * mv_stride) << (mv_sample_log2 - 1);

                                int mx = (motion_val[direction][xy][0] >> shift);

                                int my = (motion_val[direction][xy][1] >> shift);

                                if (IS_INTERLACED(mbtype_table[mb_index]))

                                    my *= 2;

                                draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,

                                           height, pict->linesize[0], 100, 0, direction);

                            }

                        } else if (IS_8X16(mbtype_table[mb_index])) {

                            int i;

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

                                int sx = mb_x * 16 + 4 + 8 * i;

                                int sy = mb_y * 16 + 8;

                                int xy = (mb_x * 2 + i + mb_y * 2 * mv_stride) << (mv_sample_log2 - 1);

                                int mx = motion_val[direction][xy][0] >> shift;

                                int my = motion_val[direction][xy][1] >> shift;

                                if (IS_INTERLACED(mbtype_table[mb_index]))

                                    my *= 2;

                                draw_arrow(ptr, sx, sy, mx + sx, my + sy, width,

                                           height, pict->linesize[0], 100, 0, direction);

                            }

                        } else {

                              int sx= mb_x * 16 + 8;

                              int sy= mb_y * 16 + 8;

                              int xy= (mb_x + mb_y * mv_stride) << mv_sample_log2;

                              int mx= (motion_val[direction][xy][0]>>shift) + sx;

                              int my= (motion_val[direction][xy][1]>>shift) + sy;

                              draw_arrow(ptr, sx, sy, mx, my, width, height, pict->linesize[0], 100, 0, direction);

                        }

                    }

                }

#endif

                if ((avctx->debug & FF_DEBUG_VIS_QP)) {

                    uint64_t c = (qscale_table[mb_index] * 128 / 31) *

                                 0x0101010101010101ULL;

                    int y;

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

                        *(uint64_t *)(pict->data[1] + 8 * mb_x +

                                      (block_height * mb_y + y) *

                                      pict->linesize[1]) = c;

                        *(uint64_t *)(pict->data[2] + 8 * mb_x +

                                      (block_height * mb_y + y) *

                                      pict->linesize[2]) = c;

                    }

                }

                if ((avctx->debug & FF_DEBUG_VIS_MB_TYPE) &&

                    motion_val[0]) {

                    int mb_type = mbtype_table[mb_index];

                    uint64_t u,v;

                    int y;

#define COLOR(theta, r) \

    u = (int)(128 + r * cos(theta * 3.141592 / 180)); \

    v = (int)(128 + r * sin(theta * 3.141592 / 180));

                    u = v = 128;

                    if (IS_PCM(mb_type)) {

                        COLOR(120, 48)

                    } else if ((IS_INTRA(mb_type) && IS_ACPRED(mb_type)) ||

                               IS_INTRA16x16(mb_type)) {

                        COLOR(30, 48)

                    } else if (IS_INTRA4x4(mb_type)) {

                        COLOR(90, 48)

                    } else if (IS_DIRECT(mb_type) && IS_SKIP(mb_type)) {

                        // COLOR(120, 48)

                    } else if (IS_DIRECT(mb_type)) {

                        COLOR(150, 48)

                    } else if (IS_GMC(mb_type) && IS_SKIP(mb_type)) {

                        COLOR(170, 48)

                    } else if (IS_GMC(mb_type)) {

                        COLOR(190, 48)

                    } else if (IS_SKIP(mb_type)) {

                        // COLOR(180, 48)

                    } else if (!USES_LIST(mb_type, 1)) {

                        COLOR(240, 48)

                    } else if (!USES_LIST(mb_type, 0)) {

                        COLOR(0, 48)

                    } else {

                        av_assert2(USES_LIST(mb_type, 0) && USES_LIST(mb_type, 1));

                        COLOR(300,48)

                    }

                    u *= 0x0101010101010101ULL;

                    v *= 0x0101010101010101ULL;

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

                        *(uint64_t *)(pict->data[1] + 8 * mb_x +

                                      (block_height * mb_y + y) * pict->linesize[1]) = u;

                        *(uint64_t *)(pict->data[2] + 8 * mb_x +

                                      (block_height * mb_y + y) * pict->linesize[2]) = v;

                    }

                    // segmentation

                    if (IS_8X8(mb_type) || IS_16X8(mb_type)) {

                        *(uint64_t *)(pict->data[0] + 16 * mb_x + 0 +

                                      (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;

                        *(uint64_t *)(pict->data[0] + 16 * mb_x + 8 +

                                      (16 * mb_y + 8) * pict->linesize[0]) ^= 0x8080808080808080ULL;

                    }

                    if (IS_8X8(mb_type) || IS_8X16(mb_type)) {

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

                            pict->data[0][16 * mb_x + 8 + (16 * mb_y + y) *

                                          pict->linesize[0]] ^= 0x80;

                    }

                    if (IS_8X8(mb_type) && mv_sample_log2 >= 2) {

                        int dm = 1 << (mv_sample_log2 - 2);

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

                            int sx = mb_x * 16 + 8 * (i & 1);

                            int sy = mb_y * 16 + 8 * (i >> 1);

                            int xy = (mb_x * 2 + (i & 1) +

                                     (mb_y * 2 + (i >> 1)) * mv_stride) << (mv_sample_log2 - 1);

                            // FIXME bidir

                            int32_t *mv = (int32_t *) &motion_val[0][xy];

                            if (mv[0] != mv[dm] ||

                                mv[dm * mv_stride] != mv[dm * (mv_stride + 1)])

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

                                    pict->data[0][sx + 4 + (sy + y) * pict->linesize[0]] ^= 0x80;

                            if (mv[0] != mv[dm * mv_stride] || mv[dm] != mv[dm * (mv_stride + 1)])

                                *(uint64_t *)(pict->data[0] + sx + (sy + 4) *

                                              pict->linesize[0]) ^= 0x8080808080808080ULL;

                        }

                    }

                    if (IS_INTERLACED(mb_type) &&

                        avctx->codec->id == AV_CODEC_ID_H264) {

                        // hmm

                    }

                }

                if (mbskip_table)

                    mbskip_table[mb_index] = 0;

            }

        }

    }

}


static void alloc_picture(void *opaque)

{

    VideoState *is = opaque;

    VideoPicture *vp;

    vp = &is->pictq[is->pictq_windex];

    if (vp->bmp)

        SDL_FreeYUVOverlay(vp->bmp);

#if CONFIG_AVFILTER

    if (vp->picref)

        avfilter_unref_buffer(vp->picref);

    vp->picref = NULL;

    vp->width   = is->out_video_filter->inputs[0]->w;

    vp->height  = is->out_video_filter->inputs[0]->h;

    vp->pix_fmt = is->out_video_filter->inputs[0]->format;

#else

    vp->width   = is->video_st->codec->width;

    vp->height  = is->video_st->codec->height;

    vp->pix_fmt = is->video_st->codec->pix_fmt;

#endif

    vp->bmp = SDL_CreateYUVOverlay(vp->width, vp->height,

                                   SDL_YV12_OVERLAY,

                                   screen);

    SDL_LockMutex(is->pictq_mutex);

    vp->allocated = 1;

    SDL_CondSignal(is->pictq_cond);

    SDL_UnlockMutex(is->pictq_mutex);


int css_create_css_image(uint8_t cssid, bool default_image)

{

    trace_css_new_image(cssid, default_image ? "(default)" : "");

    if (cssid > MAX_CSSID) {

        return -EINVAL;

    }

    if (channel_subsys.css[cssid]) {

        return -EBUSY;

    }

    channel_subsys.css[cssid] = g_malloc0(sizeof(CssImage));

    if (default_image) {

        channel_subsys.default_cssid = cssid;

    }

    return 0;

}


static int decode_nal_unit(HEVCContext *s, const HEVCNAL *nal)

{

    HEVCLocalContext *lc = &s->HEVClc;

    GetBitContext *gb    = &lc->gb;

    int ctb_addr_ts, ret;

    ret = init_get_bits8(gb, nal->data, nal->size);

    if (ret < 0)

        return ret;

    ret = hls_nal_unit(s);

    if (ret < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid NAL unit %d, skipping.\n",

               s->nal_unit_type);

        goto fail;

    } else if (!ret)

        return 0;

    switch (s->nal_unit_type) {

    case NAL_VPS:

        ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps);

        if (ret < 0)

            goto fail;

        break;

    case NAL_SPS:

        ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps,

                                     s->apply_defdispwin);

        if (ret < 0)

            goto fail;

        break;

    case NAL_PPS:

        ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps);

        if (ret < 0)

            goto fail;

        break;

    case NAL_SEI_PREFIX:

    case NAL_SEI_SUFFIX:

        ret = ff_hevc_decode_nal_sei(s);

        if (ret < 0)

            goto fail;

        break;

    case NAL_TRAIL_R:

    case NAL_TRAIL_N:

    case NAL_TSA_N:

    case NAL_TSA_R:

    case NAL_STSA_N:

    case NAL_STSA_R:

    case NAL_BLA_W_LP:

    case NAL_BLA_W_RADL:

    case NAL_BLA_N_LP:

    case NAL_IDR_W_RADL:

    case NAL_IDR_N_LP:

    case NAL_CRA_NUT:

    case NAL_RADL_N:

    case NAL_RADL_R:

    case NAL_RASL_N:

    case NAL_RASL_R:

        ret = hls_slice_header(s);

        if (ret < 0)

            return ret;

        if (s->max_ra == INT_MAX) {

            if (s->nal_unit_type == NAL_CRA_NUT || IS_BLA(s)) {

                s->max_ra = s->poc;

            } else {

                if (IS_IDR(s))

                    s->max_ra = INT_MIN;

            }

        }

        if ((s->nal_unit_type == NAL_RASL_R || s->nal_unit_type == NAL_RASL_N) &&

            s->poc <= s->max_ra) {

            s->is_decoded = 0;

            break;

        } else {

            if (s->nal_unit_type == NAL_RASL_R && s->poc > s->max_ra)

                s->max_ra = INT_MIN;

        }

        if (s->sh.first_slice_in_pic_flag) {

            ret = hevc_frame_start(s);

            if (ret < 0)

                return ret;

        } else if (!s->ref) {

            av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n");

            goto fail;

        }

        if (s->nal_unit_type != s->first_nal_type) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Non-matching NAL types of the VCL NALUs: %d %d\n",

                   s->first_nal_type, s->nal_unit_type);

            return AVERROR_INVALIDDATA;

        }

        if (!s->sh.dependent_slice_segment_flag &&

            s->sh.slice_type != I_SLICE) {

            ret = ff_hevc_slice_rpl(s);

            if (ret < 0) {

                av_log(s->avctx, AV_LOG_WARNING,

                       "Error constructing the reference lists for the current slice.\n");

                goto fail;

            }

        }

        if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) {

            ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0);

            if (ret < 0)

                goto fail;

        }

        if (s->avctx->hwaccel) {

            ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size);

            if (ret < 0)

                goto fail;

        } else {

            ctb_addr_ts = hls_slice_data(s);

            if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) {

                s->is_decoded = 1;

                if ((s->ps.pps->transquant_bypass_enable_flag ||

                     (s->ps.sps->pcm.loop_filter_disable_flag && s->ps.sps->pcm_enabled_flag)) &&

                    s->ps.sps->sao_enabled)

                    restore_tqb_pixels(s);

            }

            if (ctb_addr_ts < 0) {

                ret = ctb_addr_ts;

                goto fail;

            }

        }

        break;

    case NAL_EOS_NUT:

    case NAL_EOB_NUT:

        s->seq_decode = (s->seq_decode + 1) & 0xff;

        s->max_ra     = INT_MAX;

        break;

    case NAL_AUD:

    case NAL_FD_NUT:

        break;

    default:

        av_log(s->avctx, AV_LOG_INFO,

               "Skipping NAL unit %d\n", s->nal_unit_type);

    }

    return 0;

fail:

    if (s->avctx->err_recognition & AV_EF_EXPLODE)

        return ret;

    return 0;

}


static void pxa2xx_pic_save(QEMUFile *f, void *opaque)

{

    PXA2xxPICState *s = (PXA2xxPICState *) opaque;

    int i;

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

        qemu_put_be32s(f, &s->int_enabled[i]);

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

        qemu_put_be32s(f, &s->int_pending[i]);

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

        qemu_put_be32s(f, &s->is_fiq[i]);

    qemu_put_be32s(f, &s->int_idle);

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

        qemu_put_be32s(f, &s->priority[i]);

}


static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,

                               struct iovec *iov, int offset)

{

    int rc, ret;

    qemu_co_mutex_lock(&s->send_mutex);

    s->send_coroutine = qemu_coroutine_self();

    qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, nbd_restart_write,

                            nbd_have_request, NULL, s);

    rc = nbd_send_request(s->sock, request);

    if (rc >= 0 && iov) {

        ret = qemu_co_sendv(s->sock, iov, request->len, offset);

        if (ret != request->len) {

            errno = -EIO;

            rc = -1;

        }

    }

    qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,

                            nbd_have_request, NULL, s);

    s->send_coroutine = NULL;

    qemu_co_mutex_unlock(&s->send_mutex);

    return rc;

}


void replay_save_input_event(InputEvent *evt)

{

    InputKeyEvent *key;

    InputBtnEvent *btn;

    InputMoveEvent *move;

    replay_put_dword(evt->type);

    switch (evt->type) {

    case INPUT_EVENT_KIND_KEY:

        key = evt->u.key;

        replay_put_dword(key->key->type);

        switch (key->key->type) {

        case KEY_VALUE_KIND_NUMBER:

            replay_put_qword(key->key->u.number);

            replay_put_byte(key->down);

            break;

        case KEY_VALUE_KIND_QCODE:

            replay_put_dword(key->key->u.qcode);

            replay_put_byte(key->down);

            break;

        case KEY_VALUE_KIND__MAX:

            /* keep gcc happy */

            break;

        }

        break;

    case INPUT_EVENT_KIND_BTN:

        btn = evt->u.btn;

        replay_put_dword(btn->button);

        replay_put_byte(btn->down);

        break;

    case INPUT_EVENT_KIND_REL:

        move = evt->u.rel;

        replay_put_dword(move->axis);

        replay_put_qword(move->value);

        break;

    case INPUT_EVENT_KIND_ABS:

        move = evt->u.abs;

        replay_put_dword(move->axis);

        replay_put_qword(move->value);

        break;

    case INPUT_EVENT_KIND__MAX:

        /* keep gcc happy */

        break;

    }

}


static void internal_snapshot_prepare(BlkActionState *common,

                                      Error **errp)

{

    Error *local_err = NULL;

    const char *device;

    const char *name;

    BlockBackend *blk;

    BlockDriverState *bs;

    QEMUSnapshotInfo old_sn, *sn;

    bool ret;

    qemu_timeval tv;

    BlockdevSnapshotInternal *internal;

    InternalSnapshotState *state;

    int ret1;

    g_assert(common->action->type ==

             TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);

    internal = common->action->u.blockdev_snapshot_internal_sync.data;

    state = DO_UPCAST(InternalSnapshotState, common, common);

    /* 1. parse input */

    device = internal->device;

    name = internal->name;

    /* 2. check for validation */

    if (action_check_completion_mode(common, errp) < 0) {

        return;

    }

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", device);

        return;

    }

    /* AioContext is released in .clean() */

    state->aio_context = blk_get_aio_context(blk);

    aio_context_acquire(state->aio_context);

    if (!blk_is_available(blk)) {

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    bs = blk_bs(blk);

    state->bs = bs;

    bdrv_drained_begin(bs);

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {

        return;

    }

    if (bdrv_is_read_only(bs)) {

        error_setg(errp, "Device '%s' is read only", device);

        return;

    }

    if (!bdrv_can_snapshot(bs)) {

        error_setg(errp, "Block format '%s' used by device '%s' "

                   "does not support internal snapshots",

                   bs->drv->format_name, device);

        return;

    }

    if (!strlen(name)) {

        error_setg(errp, "Name is empty");

        return;

    }

    /* check whether a snapshot with name exist */

    ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,

                                            &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    } else if (ret) {

        error_setg(errp,

                   "Snapshot with name '%s' already exists on device '%s'",

                   name, device);

        return;

    }

    /* 3. take the snapshot */

    sn = &state->sn;

    pstrcpy(sn->name, sizeof(sn->name), name);

    qemu_gettimeofday(&tv);

    sn->date_sec = tv.tv_sec;

    sn->date_nsec = tv.tv_usec * 1000;

    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    ret1 = bdrv_snapshot_create(bs, sn);

    if (ret1 < 0) {

        error_setg_errno(errp, -ret1,

                         "Failed to create snapshot '%s' on device '%s'",

                         name, device);

        return;

    }

    /* 4. succeed, mark a snapshot is created */

    state->created = true;

}


void qdev_set_parent_bus(DeviceState *dev, BusState *bus)

{

    Property *prop;

    if (qdev_hotplug) {

        assert(bus->allow_hotplug);

    }

    dev->parent_bus = bus;

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

    qdev_prop_set_defaults(dev, dev->parent_bus->info->props);

    for (prop = qdev_get_bus_info(dev)->props; prop && prop->name; prop++) {

        qdev_property_add_legacy(dev, prop, NULL);

        qdev_property_add_static(dev, prop, NULL);

    }

}


int object_property_get_enum(Object *obj, const char *name,

                             const char *typename, Error **errp)

{

    Error *err = NULL;

    StringOutputVisitor *sov;

    Visitor *v;

    char *str;

    int ret;

    ObjectProperty *prop = object_property_find(obj, name, errp);

    EnumProperty *enumprop;

    if (prop == NULL) {

        return 0;

    }

    if (!g_str_equal(prop->type, typename)) {

        error_setg(errp, "Property %s on %s is not '%s' enum type",

                   name, object_class_get_name(

                       object_get_class(obj)), typename);

        return 0;

    }

    enumprop = prop->opaque;

    sov = string_output_visitor_new(false);

    object_property_get(obj, string_output_get_visitor(sov), name, &err);

    if (err) {

        error_propagate(errp, err);

        string_output_visitor_cleanup(sov);

        return 0;

    }

    str = string_output_get_string(sov);

    string_output_visitor_cleanup(sov);

    v = string_input_visitor_new(str);

    visit_type_enum(v, name, &ret, enumprop->strings, errp);

    g_free(str);

    visit_free(v);

    return ret;

}


static uint64_t omap_sti_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    struct omap_sti_s *s = (struct omap_sti_s *) opaque;

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* STI_REVISION */

        return 0x10;

    case 0x10:	/* STI_SYSCONFIG */

        return s->sysconfig;

    case 0x14:	/* STI_SYSSTATUS / STI_RX_STATUS / XTI_SYSSTATUS */

        return 0x00;

    case 0x18:	/* STI_IRQSTATUS */

        return s->irqst;

    case 0x1c:	/* STI_IRQSETEN / STI_IRQCLREN */

        return s->irqen;

    case 0x24:	/* STI_ER / STI_DR / XTI_TRACESELECT */

    case 0x28:	/* STI_RX_DR / XTI_RXDATA */

        /* TODO */

        return 0;

    case 0x2c:	/* STI_CLK_CTRL / XTI_SCLKCRTL */

        return s->clkcontrol;

    case 0x30:	/* STI_SERIAL_CFG / XTI_SCONFIG */

        return s->serial_config;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,

                        fd_set *xfds)

{

    int nfds = -1;

    int i;

    for (i = 0; i < pollfds->len; i++) {

        GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);

        int fd = pfd->fd;

        int events = pfd->events;

        if (events & G_IO_IN) {

            FD_SET(fd, rfds);

            nfds = MAX(nfds, fd);

        }

        if (events & G_IO_OUT) {

            FD_SET(fd, wfds);

            nfds = MAX(nfds, fd);

        }

        if (events & G_IO_PRI) {

            FD_SET(fd, xfds);

            nfds = MAX(nfds, fd);

        }

    }

    return nfds;

}


void qemu_bh_schedule_idle(QEMUBH *bh)

{

    if (bh->scheduled)

        return;

    bh->scheduled = 1;

    bh->idle = 1;

}


void stl_phys(target_phys_addr_t addr, uint32_t val)

{

    stl_phys_internal(addr, val, DEVICE_NATIVE_ENDIAN);

}


build_madt(GArray *table_data, GArray *linker, PCMachineState *pcms,

           AcpiCpuInfo *cpu)

{

    int madt_start = table_data->len;

    AcpiMultipleApicTable *madt;

    AcpiMadtIoApic *io_apic;

    AcpiMadtIntsrcovr *intsrcovr;

    AcpiMadtLocalNmi *local_nmi;

    int i;

    madt = acpi_data_push(table_data, sizeof *madt);

    madt->local_apic_address = cpu_to_le32(APIC_DEFAULT_ADDRESS);

    madt->flags = cpu_to_le32(1);

    for (i = 0; i < pcms->apic_id_limit; i++) {

        AcpiMadtProcessorApic *apic = acpi_data_push(table_data, sizeof *apic);

        apic->type = ACPI_APIC_PROCESSOR;

        apic->length = sizeof(*apic);

        apic->processor_id = i;

        apic->local_apic_id = i;

        if (test_bit(i, cpu->found_cpus)) {

            apic->flags = cpu_to_le32(1);

        } else {

            apic->flags = cpu_to_le32(0);

        }

    }

    io_apic = acpi_data_push(table_data, sizeof *io_apic);

    io_apic->type = ACPI_APIC_IO;

    io_apic->length = sizeof(*io_apic);

#define ACPI_BUILD_IOAPIC_ID 0x0

    io_apic->io_apic_id = ACPI_BUILD_IOAPIC_ID;

    io_apic->address = cpu_to_le32(IO_APIC_DEFAULT_ADDRESS);

    io_apic->interrupt = cpu_to_le32(0);

    if (pcms->apic_xrupt_override) {

        intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);

        intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;

        intsrcovr->length = sizeof(*intsrcovr);

        intsrcovr->source = 0;

        intsrcovr->gsi    = cpu_to_le32(2);

        intsrcovr->flags  = cpu_to_le16(0); /* conforms to bus specifications */

    }

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

#define ACPI_BUILD_PCI_IRQS ((1<<5) | (1<<9) | (1<<10) | (1<<11))

        if (!(ACPI_BUILD_PCI_IRQS & (1 << i))) {

            /* No need for a INT source override structure. */

            continue;

        }

        intsrcovr = acpi_data_push(table_data, sizeof *intsrcovr);

        intsrcovr->type   = ACPI_APIC_XRUPT_OVERRIDE;

        intsrcovr->length = sizeof(*intsrcovr);

        intsrcovr->source = i;

        intsrcovr->gsi    = cpu_to_le32(i);

        intsrcovr->flags  = cpu_to_le16(0xd); /* active high, level triggered */

    }

    local_nmi = acpi_data_push(table_data, sizeof *local_nmi);

    local_nmi->type         = ACPI_APIC_LOCAL_NMI;

    local_nmi->length       = sizeof(*local_nmi);

    local_nmi->processor_id = 0xff; /* all processors */

    local_nmi->flags        = cpu_to_le16(0);

    local_nmi->lint         = 1; /* ACPI_LINT1 */

    build_header(linker, table_data,

                 (void *)(table_data->data + madt_start), "APIC",

                 table_data->len - madt_start, 1, NULL, NULL);

}


static inline int vc1_i_pred_dc(MpegEncContext *s, int overlap, int pq, int n,

                              int16_t **dc_val_ptr, int *dir_ptr)

{

    int a, b, c, wrap, pred, scale;

    int16_t *dc_val;

    static const uint16_t dcpred[32] = {

    -1, 1024,  512,  341,  256,  205,  171,  146,  128,

         114,  102,   93,   85,   79,   73,   68,   64,

          60,   57,   54,   51,   49,   47,   45,   43,

          41,   39,   38,   37,   35,   34,   33

    };

    /* find prediction - wmv3_dc_scale always used here in fact */

    if (n < 4)     scale = s->y_dc_scale;

    else           scale = s->c_dc_scale;

    wrap = s->block_wrap[n];

    dc_val= s->dc_val[0] + s->block_index[n];

    /* B A

     * C X

     */

    c = dc_val[ - 1];

    b = dc_val[ - 1 - wrap];

    a = dc_val[ - wrap];

    if (pq < 9 || !overlap)

    {

        /* Set outer values */

        if (!s->mb_y && (n!=2 && n!=3)) b=a=dcpred[scale];

        if (s->mb_x == 0 && (n!=1 && n!=3)) b=c=dcpred[scale];

    }

    else

    {

        /* Set outer values */

        if (!s->mb_y && (n!=2 && n!=3)) b=a=0;

        if (s->mb_x == 0 && (n!=1 && n!=3)) b=c=0;

    }

    if (abs(a - b) <= abs(b - c)) {

        pred = c;

        *dir_ptr = 1;//left

    } else {

        pred = a;

        *dir_ptr = 0;//top

    }

    /* update predictor */

    *dc_val_ptr = &dc_val[0];

    return pred;

}


static void multiwrite_user_cb(MultiwriteCB *mcb)

{

    int i;

    for (i = 0; i < mcb->num_callbacks; i++) {

        mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);

        if (mcb->callbacks[i].free_qiov) {

            qemu_iovec_destroy(mcb->callbacks[i].free_qiov);

        }

        g_free(mcb->callbacks[i].free_qiov);

    }

}


char *get_boot_devices_list(uint32_t *size)

{

    FWBootEntry *i;

    uint32_t total = 0;

    char *list = NULL;

    QTAILQ_FOREACH(i, &fw_boot_order, link) {

        char *devpath = NULL, *bootpath;

        int len;

        if (i->dev) {

            devpath = qdev_get_fw_dev_path(i->dev);

            assert(devpath);

        }

        if (i->suffix && devpath) {

            bootpath = qemu_malloc(strlen(devpath) + strlen(i->suffix) + 1);

            sprintf(bootpath, "%s%s", devpath, i->suffix);

            qemu_free(devpath);

        } else if (devpath) {

            bootpath = devpath;

        } else {

            bootpath = strdup(i->suffix);

            assert(bootpath);

        }

        if (total) {

            list[total-1] = '\n';

        }

        len = strlen(bootpath) + 1;

        list = qemu_realloc(list, total + len);

        memcpy(&list[total], bootpath, len);

        total += len;

        qemu_free(bootpath);

    }

    *size = total;

    return list;

}


void rgb24toyv12_c(const uint8_t *src, uint8_t *ydst, uint8_t *udst,

                   uint8_t *vdst, int width, int height, int lumStride,

                   int chromStride, int srcStride)

{

    int y;

    const int chromWidth = width >> 1;

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

        int i;

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

            unsigned int b = src[6 * i + 0];

            unsigned int g = src[6 * i + 1];

            unsigned int r = src[6 * i + 2];

            unsigned int Y = ((RY * r + GY * g + BY * b) >> RGB2YUV_SHIFT) +  16;

            unsigned int V = ((RV * r + GV * g + BV * b) >> RGB2YUV_SHIFT) + 128;

            unsigned int U = ((RU * r + GU * g + BU * b) >> RGB2YUV_SHIFT) + 128;

            udst[i]     = U;

            vdst[i]     = V;

            ydst[2 * i] = Y;

            b = src[6 * i + 3];

            g = src[6 * i + 4];

            r = src[6 * i + 5];

            Y = ((RY * r + GY * g + BY * b) >> RGB2YUV_SHIFT) + 16;

            ydst[2 * i + 1] = Y;

        }

        ydst += lumStride;

        src  += srcStride;

        if (y+1 == height)

            break;

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

            unsigned int b = src[6 * i + 0];

            unsigned int g = src[6 * i + 1];

            unsigned int r = src[6 * i + 2];

            unsigned int Y = ((RY * r + GY * g + BY * b) >> RGB2YUV_SHIFT) + 16;

            ydst[2 * i] = Y;

            b = src[6 * i + 3];

            g = src[6 * i + 4];

            r = src[6 * i + 5];

            Y = ((RY * r + GY * g + BY * b) >> RGB2YUV_SHIFT) + 16;

            ydst[2 * i + 1] = Y;

        }

        udst += chromStride;

        vdst += chromStride;

        ydst += lumStride;

        src  += srcStride;

    }

}


static void framebuffer_update_request(VncState *vs, int incremental,

                                       int x_position, int y_position,

                                       int w, int h)

{

    int i;

    const size_t width = surface_width(vs->vd->ds) / VNC_DIRTY_PIXELS_PER_BIT;

    const size_t height = surface_height(vs->vd->ds);

    if (y_position > height) {

        y_position = height;

    }

    if (y_position + h >= height) {

        h = height - y_position;

    }

    vs->need_update = 1;

    if (!incremental) {

        vs->force_update = 1;

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

            bitmap_set(vs->dirty[y_position + i], 0, width);

            bitmap_clear(vs->dirty[y_position + i], width,

                         VNC_DIRTY_BITS - width);

        }

    }

}


static void sdp_parse_fmtp_config(AVCodecContext *codec, char *attr, char *value)

{

    switch (codec->codec_id) {

        case CODEC_ID_MPEG4:

        case CODEC_ID_AAC:

            if (!strcmp(attr, "config")) {

                /* decode the hexa encoded parameter */

                int len = hex_to_data(NULL, value);

                codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!codec->extradata)

                    return;

                codec->extradata_size = len;

                hex_to_data(codec->extradata, value);

            }

            break;

        default:

            break;

    }

    return;

}


static int tpm_passthrough_unix_write(int fd, const uint8_t *buf, uint32_t len)

{

    int ret, remain;

    remain = len;

    while (len > 0) {

        ret = write(fd, buf, remain);

        if (ret < 0) {

            if (errno != EINTR && errno != EAGAIN) {

                return -1;

            }

        } else if (ret == 0) {

            break;

        } else {

            buf += ret;

            remain -= ret;

        }

    }

    return len - remain;

}


static int mp3_header_decompress(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args,

                     uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size, int keyframe){

    uint32_t header;

    int sample_rate= avctx->sample_rate;

    int sample_rate_index=0;

    int lsf, mpeg25, bitrate_index, frame_size;

    header = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];

    if(ff_mpa_check_header(header) >= 0){

        *poutbuf= (uint8_t *) buf;

        *poutbuf_size= buf_size;

        return 0;

    }

    header= 0xFFE00000 | ((4-3)<<17) | (1<<16); //FIXME simplify

    lsf     = sample_rate < (24000+32000)/2;

    mpeg25  = sample_rate < (12000+16000)/2;

    header |= (!mpeg25)<<20;

    header |= (!lsf   )<<19;

    if(sample_rate<<(lsf+mpeg25) < (44100+32000)/2)

        sample_rate_index |= 2;

    else if(sample_rate<<(lsf+mpeg25) > (44100+48000)/2)

        sample_rate_index |= 1;

    header |= sample_rate_index<<10;

    sample_rate= mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25); //in case sample rate is a little off

    for(bitrate_index=2; bitrate_index<30; bitrate_index++){

        frame_size = mpa_bitrate_tab[lsf][2][bitrate_index>>1];

        frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);

        if(frame_size == buf_size + 4)

            break;

    }

    if(bitrate_index == 30){

        av_log(avctx, AV_LOG_ERROR, "couldnt find bitrate_index\n");

        return -1;

    }

    header |= (bitrate_index&1)<<9;

    header |= (bitrate_index>>1)<<12;

    header |= (avctx->channels==1 ? MPA_MONO : MPA_JSTEREO)<<6;

    *poutbuf_size= buf_size + 4;

    *poutbuf= av_malloc(buf_size + 4 + FF_INPUT_BUFFER_PADDING_SIZE);

    memcpy(*poutbuf + 4, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    if(avctx->channels==2){

        if(lsf){

            FFSWAP(int, (*poutbuf)[5], (*poutbuf)[6]);

            header |= ((*poutbuf)[5] & 0xC0)>>2;

        }else{

            header |= (*poutbuf)[5] & 0x30;

        }

    }

    (*poutbuf)[0]= header>>24;

    (*poutbuf)[1]= header>>16;

    (*poutbuf)[2]= header>> 8;

    (*poutbuf)[3]= header    ;

    return 1;

}


static struct iovec *lock_iovec(int type, abi_ulong target_addr,

                                int count, int copy)

{

    struct target_iovec *target_vec;

    struct iovec *vec;

    abi_ulong total_len, max_len;

    int i;

    int err = 0;

    bool bad_address = false;

    if (count == 0) {

        errno = 0;

        return NULL;

    if (count < 0 || count > IOV_MAX) {

        errno = EINVAL;

        return NULL;

    vec = calloc(count, sizeof(struct iovec));

    if (vec == NULL) {

        errno = ENOMEM;

        return NULL;

    target_vec = lock_user(VERIFY_READ, target_addr,

                           count * sizeof(struct target_iovec), 1);

    if (target_vec == NULL) {

        err = EFAULT;

        goto fail2;

    /* ??? If host page size > target page size, this will result in a

       value larger than what we can actually support.  */

    max_len = 0x7fffffff & TARGET_PAGE_MASK;

    total_len = 0;

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

        abi_ulong base = tswapal(target_vec[i].iov_base);

        abi_long len = tswapal(target_vec[i].iov_len);

        if (len < 0) {

            err = EINVAL;

            goto fail;

        } else if (len == 0) {

            /* Zero length pointer is ignored.  */

            vec[i].iov_base = 0;

        } else {

            vec[i].iov_base = lock_user(type, base, len, copy);

            /* If the first buffer pointer is bad, this is a fault.  But

             * subsequent bad buffers will result in a partial write; this

             * is realized by filling the vector with null pointers and

             * zero lengths. */

            if (!vec[i].iov_base) {

                if (i == 0) {

                    err = EFAULT;

                    goto fail;

                } else {

                    bad_address = true;

            if (bad_address) {

                len = 0;

            if (len > max_len - total_len) {

                len = max_len - total_len;

        vec[i].iov_len = len;

        total_len += len;

    unlock_user(target_vec, target_addr, 0);

    return vec;

 fail:

    unlock_user(target_vec, target_addr, 0);

 fail2:

    free(vec);

    errno = err;

    return NULL;


static void cris_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    CRISCPU *cpu = CRIS_CPU(obj);

    CRISCPUClass *ccc = CRIS_CPU_GET_CLASS(obj);

    CPUCRISState *env = &cpu->env;

    static bool tcg_initialized;

    cs->env_ptr = env;

    cpu_exec_init(cs, &error_abort);

    env->pregs[PR_VR] = ccc->vr;

#ifndef CONFIG_USER_ONLY

    /* IRQ and NMI lines.  */

    qdev_init_gpio_in(DEVICE(cpu), cris_cpu_set_irq, 2);

#endif

    if (tcg_enabled() && !tcg_initialized) {

        tcg_initialized = true;

        if (env->pregs[PR_VR] < 32) {

            cris_initialize_crisv10_tcg();

        } else {

            cris_initialize_tcg();

        }

    }

}


static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,

                   uint8_t *properties)

{

    Jpeg2000CodingStyle tmp;

    int compno;

    if (s->buf_end - s->buf < 5)

        return AVERROR(EINVAL);

    tmp.log2_prec_width  =

    tmp.log2_prec_height = 15;

    tmp.csty = bytestream_get_byte(&s->buf);

    // get progression order

    tmp.prog_order = bytestream_get_byte(&s->buf);

    tmp.nlayers = bytestream_get_be16(&s->buf);

    tmp.mct     = bytestream_get_byte(&s->buf); // multiple component transformation

    get_cox(s, &tmp);

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

        if (!(properties[compno] & HAD_COC))

            memcpy(c + compno, &tmp, sizeof(tmp));

    return 0;

}


static int32_t scalarproduct_and_madd_int16_c(int16_t *v1, const int16_t *v2,

                                              const int16_t *v3,

                                              int order, int mul)

{

    int res = 0;

    while (order--) {

        res   += *v1 * *v2++;

        *v1++ += mul * *v3++;

    }

    return res;

}


void exec_start_incoming_migration(const char *command, Error **errp)

{

    QEMUFile *f;

    DPRINTF("Attempting to start an incoming migration\n");

    f = qemu_popen_cmd(command, "r");

    if(f == NULL) {

        error_setg_errno(errp, errno, "failed to popen the migration source");

        return;

    }

    qemu_set_fd_handler2(qemu_get_fd(f), NULL,

			 exec_accept_incoming_migration, NULL, f);

}


static void io_mem_init(void)

{

    cpu_register_io_memory(IO_MEM_ROM >> IO_MEM_SHIFT, error_mem_read, unassigned_mem_write, NULL);

    cpu_register_io_memory(IO_MEM_UNASSIGNED >> IO_MEM_SHIFT, unassigned_mem_read, unassigned_mem_write, NULL);

    cpu_register_io_memory(IO_MEM_NOTDIRTY >> IO_MEM_SHIFT, error_mem_read, notdirty_mem_write, NULL);

    io_mem_nb = 5;

    /* alloc dirty bits array */

    phys_ram_dirty = qemu_vmalloc(phys_ram_size >> TARGET_PAGE_BITS);

    memset(phys_ram_dirty, 0xff, phys_ram_size >> TARGET_PAGE_BITS);

}