static void pcie_aer_update_log(PCIDevice *dev, const PCIEAERErr *err)

{

    uint8_t *aer_cap = dev->config + dev->exp.aer_cap;

    uint8_t first_bit = ffs(err->status) - 1;

    uint32_t errcap = pci_get_long(aer_cap + PCI_ERR_CAP);

    int i;

    assert(err->status);

    assert(!(err->status & (err->status - 1)));

    errcap &= ~(PCI_ERR_CAP_FEP_MASK | PCI_ERR_CAP_TLP);

    errcap |= PCI_ERR_CAP_FEP(first_bit);

    if (err->flags & PCIE_AER_ERR_HEADER_VALID) {

        for (i = 0; i < ARRAY_SIZE(err->header); ++i) {

            /* 7.10.8 Header Log Register */

            uint8_t *header_log =

                aer_cap + PCI_ERR_HEADER_LOG + i * sizeof err->header[0];

            stl_be_p(header_log, err->header[i]);

        }

    } else {

        assert(!(err->flags & PCIE_AER_ERR_TLP_PREFIX_PRESENT));

        memset(aer_cap + PCI_ERR_HEADER_LOG, 0, PCI_ERR_HEADER_LOG_SIZE);

    }

    if ((err->flags & PCIE_AER_ERR_TLP_PREFIX_PRESENT) &&

        (pci_get_long(dev->config + dev->exp.exp_cap + PCI_EXP_DEVCAP2) &

         PCI_EXP_DEVCAP2_EETLPP)) {

        for (i = 0; i < ARRAY_SIZE(err->prefix); ++i) {

            /* 7.10.12 tlp prefix log register */

            uint8_t *prefix_log =

                aer_cap + PCI_ERR_TLP_PREFIX_LOG + i * sizeof err->prefix[0];

            stl_be_p(prefix_log, err->prefix[i]);

        }

        errcap |= PCI_ERR_CAP_TLP;

    } else {

        memset(aer_cap + PCI_ERR_TLP_PREFIX_LOG, 0,

               PCI_ERR_TLP_PREFIX_LOG_SIZE);

    }

    pci_set_long(aer_cap + PCI_ERR_CAP, errcap);

}


static int hdev_create(const char *filename, QEMUOptionParameter *options)

{

    int fd;

    int ret = 0;

    struct stat stat_buf;

    int64_t total_size = 0;

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, "size")) {

            total_size = options->value.n / 512;

        }

        options++;

    }

    fd = open(filename, O_WRONLY | O_BINARY);

    if (fd < 0)

        return -EIO;

    if (fstat(fd, &stat_buf) < 0)

        ret = -EIO;

    else if (!S_ISBLK(stat_buf.st_mode))

        ret = -EIO;

    else if (lseek(fd, 0, SEEK_END) < total_size * 512)

        ret = -ENOSPC;

    close(fd);

    return ret;

}


void net_rx_pkt_set_protocols(struct NetRxPkt *pkt, const void *data,

                              size_t len)

{

    assert(pkt);

    eth_get_protocols(data, len, &pkt->isip4, &pkt->isip6,

        &pkt->isudp, &pkt->istcp);

}


static int decode_frame(AVCodecContext *avctx,

                        void *data,

                        int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

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

    int buf_size       = avpkt->size;

    DPXContext *const s = avctx->priv_data;

    AVFrame *picture  = data;

    AVFrame *const p = &s->picture;

    uint8_t *ptr;

    int magic_num, offset, endian;

    int x, y;

    int w, h, stride, bits_per_color, descriptor, elements, target_packet_size, source_packet_size;

    unsigned int rgbBuffer;

    if (avpkt->size <= 1634) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small for DPX header\n");

        return AVERROR_INVALIDDATA;

    }

    magic_num = AV_RB32(buf);

    buf += 4;

    /* Check if the files "magic number" is "SDPX" which means it uses

     * big-endian or XPDS which is for little-endian files */

    if (magic_num == AV_RL32("SDPX")) {

        endian = 0;

    } else if (magic_num == AV_RB32("SDPX")) {

        endian = 1;

    } else {

        av_log(avctx, AV_LOG_ERROR, "DPX marker not found\n");

        return -1;

    }

    offset = read32(&buf, endian);

    if (avpkt->size <= offset) {

        av_log(avctx, AV_LOG_ERROR, "Invalid data start offset\n");

        return AVERROR_INVALIDDATA;

    }

    // Need to end in 0x304 offset from start of file

    buf = avpkt->data + 0x304;

    w = read32(&buf, endian);

    h = read32(&buf, endian);

    // Need to end in 0x320 to read the descriptor

    buf += 20;

    descriptor = buf[0];

    // Need to end in 0x323 to read the bits per color

    buf += 3;

    avctx->bits_per_raw_sample =

    bits_per_color = buf[0];

    buf += 825;

    avctx->sample_aspect_ratio.num = read32(&buf, endian);

    avctx->sample_aspect_ratio.den = read32(&buf, endian);

    if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0)

        av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,

                   avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den,

                  0x10000);

    else

        avctx->sample_aspect_ratio = (AVRational){ 0, 0 };

    switch (descriptor) {

        case 51: // RGBA

            elements = 4;

            break;

        case 50: // RGB

            elements = 3;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported descriptor %d\n", descriptor);

            return -1;

    }

    switch (bits_per_color) {

        case 8:

            if (elements == 4) {

                avctx->pix_fmt = PIX_FMT_RGBA;

            } else {

                avctx->pix_fmt = PIX_FMT_RGB24;

            }

            source_packet_size = elements;

            target_packet_size = elements;

            break;

        case 10:

            avctx->pix_fmt = PIX_FMT_RGB48;

            target_packet_size = 6;

            source_packet_size = 4;

            break;

        case 12:

        case 16:

            if (endian) {

                avctx->pix_fmt = elements == 4 ? PIX_FMT_RGBA64BE : PIX_FMT_RGB48BE;

            } else {

                avctx->pix_fmt = elements == 4 ? PIX_FMT_RGBA64LE : PIX_FMT_RGB48LE;

            }

            target_packet_size =

            source_packet_size = elements * 2;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported color depth : %d\n", bits_per_color);

            return -1;

    }

    if (s->picture.data[0])

        avctx->release_buffer(avctx, &s->picture);

    if (av_image_check_size(w, h, 0, avctx))

        return -1;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    if (avctx->get_buffer(avctx, p) < 0) {

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

        return -1;

    }

    // Move pointer to offset from start of file

    buf =  avpkt->data + offset;

    ptr    = p->data[0];

    stride = p->linesize[0];

    if (source_packet_size*avctx->width*avctx->height > buf_end - buf) {

        av_log(avctx, AV_LOG_ERROR, "Overread buffer. Invalid header?\n");

        return -1;

    }

    switch (bits_per_color) {

        case 10:

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

               uint16_t *dst = (uint16_t*)ptr;

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

                   rgbBuffer = read32(&buf, endian);

                   // Read out the 10-bit colors and convert to 16-bit

                   *dst++ = make_16bit(rgbBuffer >> 16);

                   *dst++ = make_16bit(rgbBuffer >>  6);

                   *dst++ = make_16bit(rgbBuffer <<  4);

               }

               ptr += stride;

            }

            break;

        case 8:

        case 12: // Treat 12-bit as 16-bit

        case 16:

            if (source_packet_size == target_packet_size) {

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

                    memcpy(ptr, buf, target_packet_size*avctx->width);

                    ptr += stride;

                    buf += source_packet_size*avctx->width;

                }

            } else {

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

                    uint8_t *dst = ptr;

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

                        memcpy(dst, buf, target_packet_size);

                        dst += target_packet_size;

                        buf += source_packet_size;

                    }

                    ptr += stride;

                }

            }

            break;

    }

    *picture   = s->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


static int hls_write_trailer(struct AVFormatContext *s)

{

    HLSContext *hls = s->priv_data;

    AVFormatContext *oc = hls->avf;

    av_write_trailer(oc);

    avio_closep(&oc->pb);

    avformat_free_context(oc);

    av_free(hls->basename);

    append_entry(hls, hls->duration);

    hls_window(s, 1);

    free_entries(hls);

    return 0;

}


static int g726_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    G726Context *c = avctx->priv_data;

    int16_t *samples = data;

    GetBitContext gb;

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

    while (get_bits_count(&gb) + c->code_size <= buf_size*8)

        *samples++ = g726_decode(c, get_bits(&gb, c->code_size));

    if(buf_size*8 != get_bits_count(&gb))

        av_log(avctx, AV_LOG_ERROR, "Frame invalidly split, missing parser?\n");

    *data_size = (uint8_t*)samples - (uint8_t*)data;

    return buf_size;

}


static inline void downmix_mono_to_stereo(float *samples)

{

    int i;

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

        samples[i + 256] = samples[i];

}


dshow_cycle_devices(AVFormatContext *avctx, ICreateDevEnum *devenum,

                    enum dshowDeviceType devtype, enum dshowSourceFilterType sourcetype, IBaseFilter **pfilter)

{

    struct dshow_ctx *ctx = avctx->priv_data;

    IBaseFilter *device_filter = NULL;

    IEnumMoniker *classenum = NULL;

    IMoniker *m = NULL;

    const char *device_name = ctx->device_name[devtype];

    int skip = (devtype == VideoDevice) ? ctx->video_device_number

                                        : ctx->audio_device_number;

    int r;

    const GUID *device_guid[2] = { &CLSID_VideoInputDeviceCategory,

                                   &CLSID_AudioInputDeviceCategory };

    const char *devtypename = (devtype == VideoDevice) ? "video" : "audio only";

    const char *sourcetypename = (sourcetype == VideoSourceDevice) ? "video" : "audio";

    r = ICreateDevEnum_CreateClassEnumerator(devenum, device_guid[sourcetype],

                                             (IEnumMoniker **) &classenum, 0);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not enumerate %s devices (or none found).\n",

               devtypename);

        return AVERROR(EIO);

    }

    while (!device_filter && IEnumMoniker_Next(classenum, 1, &m, NULL) == S_OK) {

        IPropertyBag *bag = NULL;

        char *friendly_name = NULL;

        char *unique_name = NULL;

        VARIANT var;

        IBindCtx *bind_ctx = NULL;

        LPOLESTR olestr = NULL;

        LPMALLOC co_malloc = NULL;

        int i;

        r = CoGetMalloc(1, &co_malloc);

        if (r = S_OK)

            goto fail1;

        r = CreateBindCtx(0, &bind_ctx);

        if (r != S_OK)

            goto fail1;

        /* GetDisplayname works for both video and audio, DevicePath doesn't */

        r = IMoniker_GetDisplayName(m, bind_ctx, NULL, &olestr);

        if (r != S_OK)

            goto fail1;

        unique_name = dup_wchar_to_utf8(olestr);

        /* replace ':' with '_' since we use : to delineate between sources */

        for (i = 0; i < strlen(unique_name); i++) {

            if (unique_name[i] == ':')

                unique_name[i] = '_';

        }

        r = IMoniker_BindToStorage(m, 0, 0, &IID_IPropertyBag, (void *) &bag);

        if (r != S_OK)

            goto fail1;

        var.vt = VT_BSTR;

        r = IPropertyBag_Read(bag, L"FriendlyName", &var, NULL);

        if (r != S_OK)

            goto fail1;

        friendly_name = dup_wchar_to_utf8(var.bstrVal);

        if (pfilter) {

            if (strcmp(device_name, friendly_name) && strcmp(device_name, unique_name))

                goto fail1;

            if (!skip--) {

                r = IMoniker_BindToObject(m, 0, 0, &IID_IBaseFilter, (void *) &device_filter);

                if (r != S_OK) {

                    av_log(avctx, AV_LOG_ERROR, "Unable to BindToObject for %s\n", device_name);

                    goto fail1;

                }

            }

        } else {

            av_log(avctx, AV_LOG_INFO, " \"%s\"\n", friendly_name);

            av_log(avctx, AV_LOG_INFO, "    Alternative name \"%s\"\n", unique_name);

        }

fail1:

        if (olestr && co_malloc)

            IMalloc_Free(co_malloc, olestr);

        if (bind_ctx)

            IBindCtx_Release(bind_ctx);

        av_free(friendly_name);

        av_free(unique_name);

        if (bag)

            IPropertyBag_Release(bag);

        IMoniker_Release(m);

    }

    IEnumMoniker_Release(classenum);

    if (pfilter) {

        if (!device_filter) {

            av_log(avctx, AV_LOG_ERROR, "Could not find %s device with name [%s] among source devices of type %s.\n",

                   devtypename, device_name, sourcetypename);

            return AVERROR(EIO);

        }

        *pfilter = device_filter;

    }

    return 0;

}


static void rgb24_to_yuvj444p(AVPicture *dst, AVPicture *src,

                              int width, int height)

{

    int src_wrap, x, y;

    int r, g, b;

    uint8_t *lum, *cb, *cr;

    const uint8_t *p;

    lum = dst->data[0];

    cb = dst->data[1];

    cr = dst->data[2];

    src_wrap = src->linesize[0] - width * BPP;

    p = src->data[0];

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

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

            RGB_IN(r, g, b, p);

            lum[0] = RGB_TO_Y(r, g, b);

            cb[0] = RGB_TO_U(r, g, b, 0);

            cr[0] = RGB_TO_V(r, g, b, 0);

            cb++;

            cr++;

            lum++;

        }

        p += src_wrap;

        lum += dst->linesize[0] - width;

        cb += dst->linesize[1] - width;

        cr += dst->linesize[2] - width;

    }

}


static int vf_open(vf_instance_t *vf, char *args){

    vf->config=config;

    vf->put_image=put_image;

    vf->get_image=get_image;

    vf->query_format=query_format;

    vf->uninit=uninit;

    vf->control= control;

    vf->priv=malloc(sizeof(struct vf_priv_s));

    memset(vf->priv, 0, sizeof(struct vf_priv_s));

    if (args) sscanf(args, "%d:%d", &vf->priv->qp, &vf->priv->mode);

    if(vf->priv->qp < 0)

        vf->priv->qp = 0;

    init_thres2();

    switch(vf->priv->mode){

        case 0: requantize= hardthresh_c; break;

        case 1: requantize= softthresh_c; break;

        default:

        case 2: requantize= mediumthresh_c; break;

    }

#if HAVE_MMX

    if(ff_gCpuCaps.hasMMX){

        dctB= dctB_mmx;

    }

#endif

#if 0

    if(ff_gCpuCaps.hasMMX){

        switch(vf->priv->mode){

            case 0: requantize= hardthresh_mmx; break;

            case 1: requantize= softthresh_mmx; break;

        }

    }

#endif

    return 1;

}


static void ff_id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags, ID3v2ExtraMeta **extra_meta)

{

    int isv34, tlen, unsync;

    char tag[5];

    int64_t next, end = avio_tell(s->pb) + len;

    int taghdrlen;

    const char *reason = NULL;

    AVIOContext pb;

    AVIOContext *pbx;

    unsigned char *buffer = NULL;

    int buffer_size = 0;

    void (*extra_func)(AVFormatContext*, AVIOContext*, int, char*, ID3v2ExtraMeta**) = NULL;

    switch (version) {

    case 2:

        if (flags & 0x40) {

            reason = "compression";

            goto error;

        }

        isv34 = 0;

        taghdrlen = 6;

        break;

    case 3:

    case 4:

        isv34 = 1;

        taghdrlen = 10;

        break;

    default:

        reason = "version";

        goto error;

    }

    unsync = flags & 0x80;

    if (isv34 && flags & 0x40) /* Extended header present, just skip over it */

        avio_skip(s->pb, get_size(s->pb, 4));

    while (len >= taghdrlen) {

        unsigned int tflags = 0;

        int tunsync = 0;

        if (isv34) {

            avio_read(s->pb, tag, 4);

            tag[4] = 0;

            if(version==3){

                tlen = avio_rb32(s->pb);

            }else

                tlen = get_size(s->pb, 4);

            tflags = avio_rb16(s->pb);

            tunsync = tflags & ID3v2_FLAG_UNSYNCH;

        } else {

            avio_read(s->pb, tag, 3);

            tag[3] = 0;

            tlen = avio_rb24(s->pb);

        }

        if (tlen <= 0 || tlen > len - taghdrlen) {

            av_log(s, AV_LOG_WARNING, "Invalid size in frame %s, skipping the rest of tag.\n", tag);

            break;

        }

        len -= taghdrlen + tlen;

        next = avio_tell(s->pb) + tlen;

        if (tflags & ID3v2_FLAG_DATALEN) {

            avio_rb32(s->pb);

            tlen -= 4;

        }

        if (tflags & (ID3v2_FLAG_ENCRYPTION | ID3v2_FLAG_COMPRESSION)) {

            av_log(s, AV_LOG_WARNING, "Skipping encrypted/compressed ID3v2 frame %s.\n", tag);

            avio_skip(s->pb, tlen);

        /* check for text tag or supported special meta tag */

        } else if (tag[0] == 'T' || (extra_meta && (extra_func = get_extra_meta_func(tag, isv34)->read))) {

            if (unsync || tunsync) {

                int i, j;

                av_fast_malloc(&buffer, &buffer_size, tlen);

                if (!buffer) {

                    av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);

                    goto seek;

                }

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

                    buffer[j] = avio_r8(s->pb);

                    if (j > 0 && !buffer[j] && buffer[j - 1] == 0xff) {

                        /* Unsynchronised byte, skip it */

                        j--;

                    }

                }

                ffio_init_context(&pb, buffer, j, 0, NULL, NULL, NULL, NULL);

                tlen = j;

                pbx = &pb; // read from sync buffer

            } else {

                pbx = s->pb; // read straight from input

            }

            if (tag[0] == 'T')

                /* parse text tag */

                read_ttag(s, pbx, tlen, tag);

            else

                /* parse special meta tag */

                extra_func(s, pbx, tlen, tag, extra_meta);

        }

        else if (!tag[0]) {

            if (tag[1])

                av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding");

            avio_skip(s->pb, tlen);

            break;

        }

        /* Skip to end of tag */

seek:

        avio_seek(s->pb, next, SEEK_SET);

    }

    if (version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */

        end += 10;

  error:

    if (reason)

        av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);

    avio_seek(s->pb, end, SEEK_SET);

    av_free(buffer);

    return;

}


static int eval_refl(int *refl, const int16_t *coefs, RA144Context *ractx)

{

    int b, c, i;

    unsigned int u;

    int buffer1[10];

    int buffer2[10];

    int *bp1 = buffer1;

    int *bp2 = buffer2;

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

        buffer2[i] = coefs[i];

    refl[9] = bp2[9];

    if ((unsigned) bp2[9] + 0x1000 > 0x1fff) {

        av_log(ractx, AV_LOG_ERROR, "Overflow. Broken sample?\n");

        return 1;

    }

    for (c=8; c >= 0; c--) {

        b = 0x1000-((bp2[c+1] * bp2[c+1]) >> 12);

        if (!b)

            b = -2;

        for (u=0; u<=c; u++)

            bp1[u] = ((bp2[u] - ((refl[c+1] * bp2[c-u]) >> 12)) * (0x1000000 / b)) >> 12;

        refl[c] = bp1[c];

        if ((unsigned) bp1[c] + 0x1000 > 0x1fff)

            return 1;

        FFSWAP(int *, bp1, bp2);

    }

    return 0;

}


static char *sdp_media_attributes(char *buff, int size, AVCodecContext *c, int payload_type)

{

    char *config = NULL;

    switch (c->codec_id) {

        case CODEC_ID_MPEG4:

            if (c->flags & CODEC_FLAG_GLOBAL_HEADER) {

                config = extradata2config(c->extradata, c->extradata_size);

            }

            av_strlcatf(buff, size, "a=rtpmap:%d MP4V-ES/90000\r\n"

                                    "a=fmtp:%d profile-level-id=1%s\r\n",

                                     payload_type,

                                     payload_type, config ? config : "");

            break;

        case CODEC_ID_AAC:

            if (c->flags & CODEC_FLAG_GLOBAL_HEADER) {

                config = extradata2config(c->extradata, c->extradata_size);

            } else {

                /* FIXME: maybe we can forge config information based on the

                 *        codec parameters...

                 */

                av_log(NULL, AV_LOG_ERROR, "AAC with no global headers is currently not supported\n");

                return NULL;

            }

            if (config == NULL) {

                return NULL;

            }

            av_strlcatf(buff, size, "a=rtpmap:%d MPEG4-GENERIC/%d/%d\r\n"

                                    "a=fmtp:%d profile-level-id=1;"

                                    "mode=AAC-hbr;sizelength=13;indexlength=3;"

                                    "indexdeltalength=3%s\r\n",

                                     payload_type, c->sample_rate, c->channels,

                                     payload_type, config);

            break;

        default:

            /* Nothing special to do, here... */

            break;

    }

    av_free(config);

    return buff;

}


static int mpegvideo_parse(AVCodecParserContext *s,

                           AVCodecContext *avctx,

                           const uint8_t **poutbuf, int *poutbuf_size,

                           const uint8_t *buf, int buf_size)

{

    ParseContext1 *pc1 = s->priv_data;

    ParseContext *pc= &pc1->pc;

    int next;

    if(s->flags & PARSER_FLAG_COMPLETE_FRAMES){

        next= buf_size;

    }else{

        next= ff_mpeg1_find_frame_end(pc, buf, buf_size);

        if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {

            *poutbuf = NULL;

            *poutbuf_size = 0;

            return buf_size;

        }

    }

    /* we have a full frame : we just parse the first few MPEG headers

       to have the full timing information. The time take by this

       function should be negligible for uncorrupted streams */

    mpegvideo_extract_headers(s, avctx, buf, buf_size);

#if 0

    printf("pict_type=%d frame_rate=%0.3f repeat_pict=%d\n",

           s->pict_type, (double)avctx->time_base.den / avctx->time_base.num, s->repeat_pict);

#endif

    *poutbuf = buf;

    *poutbuf_size = buf_size;

    return next;

}


int ff_h264_execute_ref_pic_marking(H264Context *h, MMCO *mmco, int mmco_count)

{

    int i, av_uninit(j);

    int current_ref_assigned = 0, err = 0;

    H264Picture *av_uninit(pic);

    if ((h->avctx->debug & FF_DEBUG_MMCO) && mmco_count == 0)

        av_log(h->avctx, AV_LOG_DEBUG, "no mmco here\n");

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

        int av_uninit(structure), av_uninit(frame_num);

        if (h->avctx->debug & FF_DEBUG_MMCO)

            av_log(h->avctx, AV_LOG_DEBUG, "mmco:%d %d %d\n", h->mmco[i].opcode,

                   h->mmco[i].short_pic_num, h->mmco[i].long_arg);

        if (mmco[i].opcode == MMCO_SHORT2UNUSED ||

            mmco[i].opcode == MMCO_SHORT2LONG) {

            frame_num = pic_num_extract(h, mmco[i].short_pic_num, &structure);

            pic       = find_short(h, frame_num, &j);

            if (!pic) {

                if (mmco[i].opcode != MMCO_SHORT2LONG ||

                    !h->long_ref[mmco[i].long_arg]    ||

                    h->long_ref[mmco[i].long_arg]->frame_num != frame_num) {

                    av_log(h->avctx, AV_LOG_ERROR, "mmco: unref short failure\n");

                    err = AVERROR_INVALIDDATA;

                }

                continue;

            }

        }

        switch (mmco[i].opcode) {

        case MMCO_SHORT2UNUSED:

            if (h->avctx->debug & FF_DEBUG_MMCO)

                av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref short %d count %d\n",

                       h->mmco[i].short_pic_num, h->short_ref_count);

            remove_short(h, frame_num, structure ^ PICT_FRAME);

            break;

        case MMCO_SHORT2LONG:

                if (h->long_ref[mmco[i].long_arg] != pic)

                    remove_long(h, mmco[i].long_arg, 0);

                remove_short_at_index(h, j);

                h->long_ref[ mmco[i].long_arg ] = pic;

                if (h->long_ref[mmco[i].long_arg]) {

                    h->long_ref[mmco[i].long_arg]->long_ref = 1;

                    h->long_ref_count++;

                }

            break;

        case MMCO_LONG2UNUSED:

            j   = pic_num_extract(h, mmco[i].long_arg, &structure);

            pic = h->long_ref[j];

            if (pic) {

                remove_long(h, j, structure ^ PICT_FRAME);

            } else if (h->avctx->debug & FF_DEBUG_MMCO)

                av_log(h->avctx, AV_LOG_DEBUG, "mmco: unref long failure\n");

            break;

        case MMCO_LONG:

                    // Comment below left from previous code as it is an interresting note.

                    /* First field in pair is in short term list or

                     * at a different long term index.

                     * This is not allowed; see 7.4.3.3, notes 2 and 3.

                     * Report the problem and keep the pair where it is,

                     * and mark this field valid.

                     */

            if (h->short_ref[0] == h->cur_pic_ptr)

                remove_short_at_index(h, 0);

            /* make sure the current picture is not already assigned as a long ref */

            if (h->cur_pic_ptr->long_ref) {

                for (j = 0; j < FF_ARRAY_ELEMS(h->long_ref); j++) {

                    if (h->long_ref[j] == h->cur_pic_ptr)

                        remove_long(h, j, 0);

                }

            }

            if (h->long_ref[mmco[i].long_arg] != h->cur_pic_ptr) {

                remove_long(h, mmco[i].long_arg, 0);

                h->long_ref[mmco[i].long_arg]           = h->cur_pic_ptr;

                h->long_ref[mmco[i].long_arg]->long_ref = 1;

                h->long_ref_count++;

            }

            h->cur_pic_ptr->reference |= h->picture_structure;

            current_ref_assigned = 1;

            break;

        case MMCO_SET_MAX_LONG:

            assert(mmco[i].long_arg <= 16);

            // just remove the long term which index is greater than new max

            for (j = mmco[i].long_arg; j < 16; j++) {

                remove_long(h, j, 0);

            }

            break;

        case MMCO_RESET:

            while (h->short_ref_count) {

                remove_short(h, h->short_ref[0]->frame_num, 0);

            }

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

                remove_long(h, j, 0);

            }

            h->frame_num  = h->cur_pic_ptr->frame_num = 0;

            h->mmco_reset = 1;

            h->cur_pic_ptr->mmco_reset = 1;

            break;

        default: assert(0);

        }

    }

    if (!current_ref_assigned) {

        /* Second field of complementary field pair; the first field of

         * which is already referenced. If short referenced, it

         * should be first entry in short_ref. If not, it must exist

         * in long_ref; trying to put it on the short list here is an

         * error in the encoded bit stream (ref: 7.4.3.3, NOTE 2 and 3).

         */

        if (h->short_ref_count && h->short_ref[0] == h->cur_pic_ptr) {

            /* Just mark the second field valid */

            h->cur_pic_ptr->reference = PICT_FRAME;

        } else if (h->cur_pic_ptr->long_ref) {

            av_log(h->avctx, AV_LOG_ERROR, "illegal short term reference "

                                           "assignment for second field "

                                           "in complementary field pair "

                                           "(first field is long term)\n");

            err = AVERROR_INVALIDDATA;

        } else {

            pic = remove_short(h, h->cur_pic_ptr->frame_num, 0);

            if (pic) {

                av_log(h->avctx, AV_LOG_ERROR, "illegal short term buffer state detected\n");

                err = AVERROR_INVALIDDATA;

            }

            if (h->short_ref_count)

                memmove(&h->short_ref[1], &h->short_ref[0],

                        h->short_ref_count * sizeof(H264Picture*));

            h->short_ref[0] = h->cur_pic_ptr;

            h->short_ref_count++;

            h->cur_pic_ptr->reference |= h->picture_structure;

        }

    }

    if (h->long_ref_count + h->short_ref_count -

        (h->short_ref[0] == h->cur_pic_ptr) > h->sps.ref_frame_count) {

        /* We have too many reference frames, probably due to corrupted

         * stream. Need to discard one frame. Prevents overrun of the

         * short_ref and long_ref buffers.

         */

        av_log(h->avctx, AV_LOG_ERROR,

               "number of reference frames (%d+%d) exceeds max (%d; probably "

               "corrupt input), discarding one\n",

               h->long_ref_count, h->short_ref_count, h->sps.ref_frame_count);

        err = AVERROR_INVALIDDATA;

        if (h->long_ref_count && !h->short_ref_count) {

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

                if (h->long_ref[i])

                    break;

            assert(i < 16);

            remove_long(h, i, 0);

        } else {

            pic = h->short_ref[h->short_ref_count - 1];

            remove_short(h, pic->frame_num, 0);

        }

    }

    print_short_term(h);

    print_long_term(h);

    return (h->avctx->err_recognition & AV_EF_EXPLODE) ? err : 0;

}


static int libschroedinger_encode_close(AVCodecContext *avctx)

{

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    /* Close the encoder. */

    schro_encoder_free(p_schro_params->encoder);

    /* Free data in the output frame queue. */

    ff_schro_queue_free(&p_schro_params->enc_frame_queue,

                        libschroedinger_free_frame);

    /* Free the encoder buffer. */

    if (p_schro_params->enc_buf_size)

        av_freep(&p_schro_params->enc_buf);

    /* Free the video format structure. */

    av_freep(&p_schro_params->format);

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static void apply_window_mp3(float *in, float *win, int *unused, float *out,

                             int incr)

{

    LOCAL_ALIGNED_16(float, suma, [17]);

    LOCAL_ALIGNED_16(float, sumb, [17]);

    LOCAL_ALIGNED_16(float, sumc, [17]);

    LOCAL_ALIGNED_16(float, sumd, [17]);

    float sum;

    /* copy to avoid wrap */

    memcpy(in + 512, in, 32 * sizeof(*in));

    apply_window(in + 16, win     , win + 512, suma, sumc, 16);

    apply_window(in + 32, win + 48, win + 640, sumb, sumd, 16);

    SUM8(MACS, suma[0], win + 32, in + 48);

    sumc[ 0] = 0;

    sumb[16] = 0;

    sumd[16] = 0;

#define SUMS(suma, sumb, sumc, sumd, out1, out2)               \

            "movups " #sumd "(%4),       %%xmm0          \n\t" \

            "shufps         $0x1b,       %%xmm0, %%xmm0  \n\t" \

            "subps  " #suma "(%1),       %%xmm0          \n\t" \

            "movaps        %%xmm0," #out1 "(%0)          \n\t" \

\

            "movups " #sumc "(%3),       %%xmm0          \n\t" \

            "shufps         $0x1b,       %%xmm0, %%xmm0  \n\t" \

            "addps  " #sumb "(%2),       %%xmm0          \n\t" \

            "movaps        %%xmm0," #out2 "(%0)          \n\t"

    if (incr == 1) {

        __asm__ volatile(

            SUMS( 0, 48,  4, 52,  0, 112)

            SUMS(16, 32, 20, 36, 16,  96)

            SUMS(32, 16, 36, 20, 32,  80)

            SUMS(48,  0, 52,  4, 48,  64)

            :"+&r"(out)

            :"r"(&suma[0]), "r"(&sumb[0]), "r"(&sumc[0]), "r"(&sumd[0])

            :"memory"

            );

        out += 16*incr;

    } else {

        int j;

        float *out2 = out + 32 * incr;

        out[0  ]  = -suma[   0];

        out += incr;

        out2 -= incr;

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

            *out  = -suma[   j] + sumd[16-j];

            *out2 =  sumb[16-j] + sumc[   j];

            out  += incr;

            out2 -= incr;

        }

    }

    sum = 0;

    SUM8(MLSS, sum, win + 16 + 32, in + 32);

    *out = sum;

}


static int mp_user_removexattr(FsContext *ctx,

                               const char *path, const char *name)

{

    char buffer[PATH_MAX];

    if (strncmp(name, "user.virtfs.", 12) == 0) {

        /*

         * Don't allow fetch of user.virtfs namesapce

         * in case of mapped security

         */

        errno = EACCES;

        return -1;

    }

    return lremovexattr(rpath(ctx, path, buffer), name);

}


static void sdhci_data_transfer(SDHCIState *s)

{

    SDHCIClass *k = SDHCI_GET_CLASS(s);

    if (s->trnmod & SDHC_TRNS_DMA) {

        switch (SDHC_DMA_TYPE(s->hostctl)) {

        case SDHC_CTRL_SDMA:

            if ((s->trnmod & SDHC_TRNS_MULTI) &&

                    (!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || s->blkcnt == 0)) {

                break;

            }

            if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {

                k->do_sdma_single(s);

            } else {

                k->do_sdma_multi(s);

            }

            break;

        case SDHC_CTRL_ADMA1_32:

            if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {

                ERRPRINT("ADMA1 not supported\n");

                break;

            }

            k->do_adma(s);

            break;

        case SDHC_CTRL_ADMA2_32:

            if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {

                ERRPRINT("ADMA2 not supported\n");

                break;

            }

            k->do_adma(s);

            break;

        case SDHC_CTRL_ADMA2_64:

            if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||

                    !(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {

                ERRPRINT("64 bit ADMA not supported\n");

                break;

            }

            k->do_adma(s);

            break;

        default:

            ERRPRINT("Unsupported DMA type\n");

            break;

        }

    } else {

        if ((s->trnmod & SDHC_TRNS_READ) && sd_data_ready(s->card)) {

            s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |

                    SDHC_DAT_LINE_ACTIVE;

            SDHCI_GET_CLASS(s)->read_block_from_card(s);

        } else {

            s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |

                    SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;

            SDHCI_GET_CLASS(s)->write_block_to_card(s);

        }

    }

}


static void disas_cc(DisasContext *s, uint32_t insn)

{

    unsigned int sf, op, y, cond, rn, nzcv, is_imm;

    int label_continue = -1;

    TCGv_i64 tcg_tmp, tcg_y, tcg_rn;

    if (!extract32(insn, 29, 1)) {

        unallocated_encoding(s);

        return;

    }

    if (insn & (1 << 10 | 1 << 4)) {

        unallocated_encoding(s);

        return;

    }

    sf = extract32(insn, 31, 1);

    op = extract32(insn, 30, 1);

    is_imm = extract32(insn, 11, 1);

    y = extract32(insn, 16, 5); /* y = rm (reg) or imm5 (imm) */

    cond = extract32(insn, 12, 4);

    rn = extract32(insn, 5, 5);

    nzcv = extract32(insn, 0, 4);

    if (cond < 0x0e) { /* not always */

        int label_match = gen_new_label();

        label_continue = gen_new_label();

        arm_gen_test_cc(cond, label_match);

        /* nomatch: */

        tcg_tmp = tcg_temp_new_i64();

        tcg_gen_movi_i64(tcg_tmp, nzcv << 28);

        gen_set_nzcv(tcg_tmp);

        tcg_temp_free_i64(tcg_tmp);

        tcg_gen_br(label_continue);

        gen_set_label(label_match);

    }

    /* match, or condition is always */

    if (is_imm) {

        tcg_y = new_tmp_a64(s);

        tcg_gen_movi_i64(tcg_y, y);

    } else {

        tcg_y = cpu_reg(s, y);

    }

    tcg_rn = cpu_reg(s, rn);

    tcg_tmp = tcg_temp_new_i64();

    if (op) {

        gen_sub_CC(sf, tcg_tmp, tcg_rn, tcg_y);

    } else {

        gen_add_CC(sf, tcg_tmp, tcg_rn, tcg_y);

    }

    tcg_temp_free_i64(tcg_tmp);

    if (cond < 0x0e) { /* continue */

        gen_set_label(label_continue);

    }

}


static void xenfb_handle_events(struct XenFB *xenfb)

{

    uint32_t prod, cons, out_cons;

    struct xenfb_page *page = xenfb->c.page;

    prod = page->out_prod;

    out_cons = page->out_cons;

    if (prod - out_cons >= XENFB_OUT_RING_LEN) {

        return;

    }

    xen_rmb();		/* ensure we see ring contents up to prod */

    for (cons = out_cons; cons != prod; cons++) {

	union xenfb_out_event *event = &XENFB_OUT_RING_REF(page, cons);

        uint8_t type = event->type;

	int x, y, w, h;

	switch (type) {

	case XENFB_TYPE_UPDATE:

	    if (xenfb->up_count == UP_QUEUE)

		xenfb->up_fullscreen = 1;

	    if (xenfb->up_fullscreen)

		break;

	    x = MAX(event->update.x, 0);

	    y = MAX(event->update.y, 0);

	    w = MIN(event->update.width, xenfb->width - x);

	    h = MIN(event->update.height, xenfb->height - y);

	    if (w < 0 || h < 0) {

                xen_be_printf(&xenfb->c.xendev, 1, "bogus update ignored\n");

		break;

	    }

	    if (x != event->update.x ||

                y != event->update.y ||

		w != event->update.width ||

		h != event->update.height) {

                xen_be_printf(&xenfb->c.xendev, 1, "bogus update clipped\n");

	    }

	    if (w == xenfb->width && h > xenfb->height / 2) {

		/* scroll detector: updated more than 50% of the lines,

		 * don't bother keeping track of the rectangles then */

		xenfb->up_fullscreen = 1;

	    } else {

		xenfb->up_rects[xenfb->up_count].x = x;

		xenfb->up_rects[xenfb->up_count].y = y;

		xenfb->up_rects[xenfb->up_count].w = w;

		xenfb->up_rects[xenfb->up_count].h = h;

		xenfb->up_count++;

	    }

	    break;

#ifdef XENFB_TYPE_RESIZE

	case XENFB_TYPE_RESIZE:

	    if (xenfb_configure_fb(xenfb, xenfb->fb_len,

				   event->resize.width,

				   event->resize.height,

				   event->resize.depth,

				   xenfb->fb_len,

				   event->resize.offset,

				   event->resize.stride) < 0)

		break;

	    xenfb_invalidate(xenfb);

	    break;

#endif

	}

    }

    xen_mb();		/* ensure we're done with ring contents */

    page->out_cons = cons;

}


static always_inline void gen_ext_l(void (*tcg_gen_ext_i64)(TCGv t0, TCGv t1),

                                    int ra, int rb, int rc,

                                    int islit, uint8_t lit)

{

    if (unlikely(rc == 31))

        return;

    if (ra != 31) {

        if (islit) {

                tcg_gen_shri_i64(cpu_ir[rc], cpu_ir[ra], (lit & 7) * 8);

        } else {

            TCGv tmp = tcg_temp_new(TCG_TYPE_I64);

            tcg_gen_andi_i64(tmp, cpu_ir[rb], 7);

            tcg_gen_shli_i64(tmp, tmp, 3);

            tcg_gen_shr_i64(cpu_ir[rc], cpu_ir[ra], tmp);

            tcg_temp_free(tmp);

        }

        if (tcg_gen_ext_i64)

            tcg_gen_ext_i64(cpu_ir[rc], cpu_ir[rc]);

    } else

        tcg_gen_movi_i64(cpu_ir[rc], 0);

}


eth_calc_pseudo_hdr_csum(struct ip_header *iphdr, uint16_t csl)

{

    struct ip_pseudo_header ipph;

    ipph.ip_src = iphdr->ip_src;

    ipph.ip_dst = iphdr->ip_dst;

    ipph.ip_payload = cpu_to_be16(csl);

    ipph.ip_proto = iphdr->ip_p;

    ipph.zeros = 0;

    return net_checksum_add(sizeof(ipph), (uint8_t *) &ipph);

}


static int ftp_auth(FTPContext *s, char *auth)

{

    const char *user = NULL, *pass = NULL;

    char *end = NULL, buf[CONTROL_BUFFER_SIZE];

    int err;

    av_assert2(auth);

    user = av_strtok(auth, ":", &end);

    pass = av_strtok(end, ":", &end);

    if (user) {

        snprintf(buf, sizeof(buf), "USER %s\r\n", user);

        if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)

            return err;

        ftp_status(s, &err, NULL, NULL, NULL, -1);

        if (err == 3) {

            if (pass) {

                snprintf(buf, sizeof(buf), "PASS %s\r\n", pass);

                if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)

                    return err;

                ftp_status(s, &err, NULL, NULL, NULL, -1);

            } else

                return AVERROR(EACCES);

        }

        if (err != 2) {

            return AVERROR(EACCES);

        }

    } else {

        const char* command = "USER anonymous\r\n";

        if ((err = ffurl_write(s->conn_control, command, strlen(command))) < 0)

            return err;

        ftp_status(s, &err, NULL, NULL, NULL, -1);

        if (err == 3) {

            if (s->anonymous_password) {

                snprintf(buf, sizeof(buf), "PASS %s\r\n", s->anonymous_password);

            } else

                snprintf(buf, sizeof(buf), "PASS nopassword\r\n");

            if ((err = ffurl_write(s->conn_control, buf, strlen(buf))) < 0)

                return err;

            ftp_status(s, &err, NULL, NULL, NULL, -1);

        }

        if (err != 2) {

            return AVERROR(EACCES);

        }

    }

    return 0;

}


static void omap_l4_io_writew(void *opaque, target_phys_addr_t addr,

                uint32_t value)

{

    unsigned int i = (addr - OMAP2_L4_BASE) >> TARGET_PAGE_BITS;

    return omap_l4_io_writew_fn[i](omap_l4_io_opaque[i], addr, value);

}


static void pl050_write(void *opaque, hwaddr offset,

                        uint64_t value, unsigned size)

{

    pl050_state *s = (pl050_state *)opaque;

    switch (offset >> 2) {

    case 0: /* KMICR */

        s->cr = value;

        pl050_update(s, s->pending);

        /* ??? Need to implement the enable/disable bit.  */

        break;

    case 2: /* KMIDATA */

        /* ??? This should toggle the TX interrupt line.  */

        /* ??? This means kbd/mouse can block each other.  */

        if (s->is_mouse) {

            ps2_write_mouse(s->dev, value);

        } else {

            ps2_write_keyboard(s->dev, value);

        }

        break;

    case 3: /* KMICLKDIV */

        s->clk = value;

        return;

    default:

        hw_error("pl050_write: Bad offset %x\n", (int)offset);

    }

}


static int eject_device(Monitor *mon, BlockDriverState *bs, int force)

{

    if (!bdrv_is_removable(bs)) {

        qerror_report(QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));

        return -1;

    }

    if (!force && bdrv_dev_is_medium_locked(bs)) {

        qerror_report(QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));

        return -1;

    }

    bdrv_close(bs);

    return 0;

}


static int load_dtb(target_phys_addr_t addr, const struct arm_boot_info *binfo)

{

#ifdef CONFIG_FDT

    uint32_t *mem_reg_property;

    uint32_t mem_reg_propsize;

    void *fdt = NULL;

    char *filename;

    int size, rc;

    uint32_t acells, scells, hival;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, binfo->dtb_filename);

    if (!filename) {

        fprintf(stderr, "Couldn't open dtb file %s\n", binfo->dtb_filename);

        return -1;

    }

    fdt = load_device_tree(filename, &size);

    if (!fdt) {

        fprintf(stderr, "Couldn't open dtb file %s\n", filename);

        g_free(filename);

        return -1;

    }

    g_free(filename);

    acells = qemu_devtree_getprop_cell(fdt, "/", "#address-cells");

    scells = qemu_devtree_getprop_cell(fdt, "/", "#size-cells");

    if (acells == 0 || scells == 0) {

        fprintf(stderr, "dtb file invalid (#address-cells or #size-cells 0)\n");

        return -1;

    }

    mem_reg_propsize = acells + scells;

    mem_reg_property = g_new0(uint32_t, mem_reg_propsize);

    mem_reg_property[acells - 1] = cpu_to_be32(binfo->loader_start);

    hival = cpu_to_be32(binfo->loader_start >> 32);

    if (acells > 1) {

        mem_reg_property[acells - 2] = hival;

    } else if (hival != 0) {

        fprintf(stderr, "qemu: dtb file not compatible with "

                "RAM start address > 4GB\n");

        exit(1);

    }

    mem_reg_property[acells + scells - 1] = cpu_to_be32(binfo->ram_size);

    hival = cpu_to_be32(binfo->ram_size >> 32);

    if (scells > 1) {

        mem_reg_property[acells + scells - 2] = hival;

    } else if (hival != 0) {

        fprintf(stderr, "qemu: dtb file not compatible with "

                "RAM size > 4GB\n");

        exit(1);

    }

    rc = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,

                              mem_reg_propsize * sizeof(uint32_t));

    if (rc < 0) {

        fprintf(stderr, "couldn't set /memory/reg\n");

    }

    if (binfo->kernel_cmdline && *binfo->kernel_cmdline) {

        rc = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",

                                          binfo->kernel_cmdline);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/bootargs\n");

        }

    }

    if (binfo->initrd_size) {

        rc = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                binfo->loader_start + INITRD_LOAD_ADDR);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

        }

        rc = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                    binfo->loader_start + INITRD_LOAD_ADDR +

                    binfo->initrd_size);

        if (rc < 0) {

            fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

        }

    }

    cpu_physical_memory_write(addr, fdt, size);

    return 0;

#else

    fprintf(stderr, "Device tree requested, "

                "but qemu was compiled without fdt support\n");

    return -1;

#endif

}


static void flush_compressed_data(QEMUFile *f)

{

    int idx, len, thread_count;

    if (!migrate_use_compression()) {

        return;

    }

    thread_count = migrate_compress_threads();

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

        if (!comp_param[idx].done) {

            qemu_mutex_lock(comp_done_lock);

            while (!comp_param[idx].done && !quit_comp_thread) {

                qemu_cond_wait(comp_done_cond, comp_done_lock);

            }

            qemu_mutex_unlock(comp_done_lock);

        }

        if (!quit_comp_thread) {

            len = qemu_put_qemu_file(f, comp_param[idx].file);

            bytes_transferred += len;

        }

    }

}


sPAPRDRConnector *spapr_dr_connector_new(Object *owner,

                                         sPAPRDRConnectorType type,

                                         uint32_t id)

{

    sPAPRDRConnector *drc =

        SPAPR_DR_CONNECTOR(object_new(TYPE_SPAPR_DR_CONNECTOR));

    g_assert(type);

    drc->type = type;

    drc->id = id;

    drc->owner = owner;

    object_property_add_child(owner, "dr-connector[*]", OBJECT(drc), NULL);

    object_property_set_bool(OBJECT(drc), true, "realized", NULL);

    /* human-readable name for a DRC to encode into the DT

     * description. this is mainly only used within a guest in place

     * of the unique DRC index.

     *

     * in the case of VIO/PCI devices, it corresponds to a

     * "location code" that maps a logical device/function (DRC index)

     * to a physical (or virtual in the case of VIO) location in the

     * system by chaining together the "location label" for each

     * encapsulating component.

     *

     * since this is more to do with diagnosing physical hardware

     * issues than guest compatibility, we choose location codes/DRC

     * names that adhere to the documented format, but avoid encoding

     * the entire topology information into the label/code, instead

     * just using the location codes based on the labels for the

     * endpoints (VIO/PCI adaptor connectors), which is basically

     * just "C" followed by an integer ID.

     *

     * DRC names as documented by PAPR+ v2.7, 13.5.2.4

     * location codes as documented by PAPR+ v2.7, 12.3.1.5

     */

    switch (drc->type) {

    case SPAPR_DR_CONNECTOR_TYPE_CPU:

        drc->name = g_strdup_printf("CPU %d", id);

        break;

    case SPAPR_DR_CONNECTOR_TYPE_PHB:

        drc->name = g_strdup_printf("PHB %d", id);

        break;

    case SPAPR_DR_CONNECTOR_TYPE_VIO:

    case SPAPR_DR_CONNECTOR_TYPE_PCI:

        drc->name = g_strdup_printf("C%d", id);

        break;

    case SPAPR_DR_CONNECTOR_TYPE_LMB:

        drc->name = g_strdup_printf("LMB %d", id);

        break;

    default:

        g_assert(false);

    }

    /* PCI slot always start in a USABLE state, and stay there */

    if (drc->type == SPAPR_DR_CONNECTOR_TYPE_PCI) {

        drc->allocation_state = SPAPR_DR_ALLOCATION_STATE_USABLE;

    }

    return drc;

}


int bdrv_snapshot_create(BlockDriverState *bs,

                         QEMUSnapshotInfo *sn_info)

{

    BlockDriver *drv = bs->drv;

    if (!drv)

        return -ENOMEDIUM;

    if (drv->bdrv_snapshot_create)

        return drv->bdrv_snapshot_create(bs, sn_info);

    if (bs->file)

        return bdrv_snapshot_create(bs->file, sn_info);

    return -ENOTSUP;

}


static char *tcg_get_arg_str_idx(TCGContext *s, char *buf,

                                 int buf_size, int idx)

{

    assert(idx >= 0 && idx < s->nb_temps);

    return tcg_get_arg_str_ptr(s, buf, buf_size, &s->temps[idx]);

}


static inline int mpeg4_is_resync(MpegEncContext *s){

    const int bits_count= get_bits_count(&s->gb);

    if(s->workaround_bugs&FF_BUG_NO_PADDING){

        return 0;

    }

    if(bits_count + 8 >= s->gb.size*8){

        int v= show_bits(&s->gb, 8);

        v|= 0x7F >> (7-(bits_count&7));

        if(v==0x7F)

            return 1;

    }else{

        if(show_bits(&s->gb, 16) == ff_mpeg4_resync_prefix[bits_count&7]){

            int len;

            GetBitContext gb= s->gb;

            skip_bits(&s->gb, 1);

            align_get_bits(&s->gb);

            for(len=0; len<32; len++){

                if(get_bits1(&s->gb)) break;

            }

            s->gb= gb;

            if(len>=ff_mpeg4_get_video_packet_prefix_length(s))

                return 1;

        }

    }

    return 0;

}


ssize_t v9fs_list_xattr(FsContext *ctx, const char *path,

                        void *value, size_t vsize)

{

    ssize_t size = 0;

    char *buffer;

    void *ovalue = value;

    XattrOperations *xops;

    char *orig_value, *orig_value_start;

    ssize_t xattr_len, parsed_len = 0, attr_len;

    /* Get the actual len */

    buffer = rpath(ctx, path);

    xattr_len = llistxattr(buffer, value, 0);

    if (xattr_len <= 0) {

        g_free(buffer);

        return xattr_len;

    }

    /* Now fetch the xattr and find the actual size */

    orig_value = g_malloc(xattr_len);

    xattr_len = llistxattr(buffer, orig_value, xattr_len);

    g_free(buffer);

    /* store the orig pointer */

    orig_value_start = orig_value;

    while (xattr_len > parsed_len) {

        xops = get_xattr_operations(ctx->xops, orig_value);

        if (!xops) {

            goto next_entry;

        }

        if (!value) {

            size += xops->listxattr(ctx, path, orig_value, value, vsize);

        } else {

            size = xops->listxattr(ctx, path, orig_value, value, vsize);

            if (size < 0) {

                goto err_out;

            }

            value += size;

            vsize -= size;

        }

next_entry:

        /* Got the next entry */

        attr_len = strlen(orig_value) + 1;

        parsed_len += attr_len;

        orig_value += attr_len;

    }

    if (value) {

        size = value - ovalue;

    }

err_out:

    g_free(orig_value_start);

    return size;

}


static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,

                              AVFormatContext *s)

{

    int pos = url_ftell(pb);

    int i;

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

    put_tag(pb, "udta");

    /* iTunes meta data */

    mov_write_meta_tag(pb, mov, s);

    /* Requirements */

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

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

        if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||

            mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {

            int pos = url_ftell(pb);

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

            put_tag(pb, "\251req");

            put_be16(pb, sizeof("QuickTime 6.0 or greater") - 1);

            put_be16(pb, 0);

            put_buffer(pb, "QuickTime 6.0 or greater",

                       sizeof("QuickTime 6.0 or greater") - 1);

            updateSize(pb, pos);

            break;

        }

    }

    /* Encoder */

    if(!(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))

    {

        int pos = url_ftell(pb);

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

        put_tag(pb, "\251enc");

        put_be16(pb, sizeof(LIBAVFORMAT_IDENT) - 1); /* string length */

        put_be16(pb, 0);

        put_buffer(pb, LIBAVFORMAT_IDENT, sizeof(LIBAVFORMAT_IDENT) - 1);

        updateSize(pb, pos);

    }

    if( s->title[0] )

    {

        int pos = url_ftell(pb);

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

        put_tag(pb, "\251nam");

        put_be16(pb, strlen(s->title)); /* string length */

        put_be16(pb, 0);

        put_buffer(pb, s->title, strlen(s->title));

        updateSize(pb, pos);

    }

    if( s->author[0] )

    {

        int pos = url_ftell(pb);

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

        put_tag(pb, /*"\251aut"*/ "\251day" );

        put_be16(pb, strlen(s->author)); /* string length */

        put_be16(pb, 0);

        put_buffer(pb, s->author, strlen(s->author));

        updateSize(pb, pos);

    }

    if( s->comment[0] )

    {

        int pos = url_ftell(pb);

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

        put_tag(pb, "\251des");

        put_be16(pb, strlen(s->comment)); /* string length */

        put_be16(pb, 0);

        put_buffer(pb, s->comment, strlen(s->comment));

        updateSize(pb, pos);

    }

    return updateSize(pb, pos);

}


static void bochs_bios_write(void *opaque, uint32_t addr, uint32_t val)

{

    static const char shutdown_str[8] = "Shutdown";

    static int shutdown_index = 0;

    switch(addr) {

        /* Bochs BIOS messages */

    case 0x400:

    case 0x401:

        /* used to be panic, now unused */

        break;

    case 0x402:

    case 0x403:

#ifdef DEBUG_BIOS

        fprintf(stderr, "%c", val);

#endif

        break;

    case 0x8900:

        /* same as Bochs power off */

        if (val == shutdown_str[shutdown_index]) {

            shutdown_index++;

            if (shutdown_index == 8) {

                shutdown_index = 0;

                qemu_system_shutdown_request();

            }

        } else {

            shutdown_index = 0;

        }

        break;

        /* LGPL'ed VGA BIOS messages */

    case 0x501:

    case 0x502:

        fprintf(stderr, "VGA BIOS panic, line %d\n", val);

        exit(1);

    case 0x500:

    case 0x503:

#ifdef DEBUG_BIOS

        fprintf(stderr, "%c", val);

#endif

        break;

    }

}


void error_propagate(Error **dst_err, Error *local_err)

{

    if (dst_err) {

        *dst_err = local_err;

    } else if (local_err) {

        error_free(local_err);

    }

}


static int macio_newworld_initfn(PCIDevice *d)

{

    MacIOState *s = MACIO(d);

    NewWorldMacIOState *ns = NEWWORLD_MACIO(d);

    SysBusDevice *sysbus_dev;

    MemoryRegion *timer_memory = g_new(MemoryRegion, 1);

    int i;

    int cur_irq = 0;

    int ret = macio_common_initfn(d);

    if (ret < 0) {

        return ret;

    }

    sysbus_dev = SYS_BUS_DEVICE(&s->cuda);

    sysbus_connect_irq(sysbus_dev, 0, ns->irqs[cur_irq++]);

    if (s->pic_mem) {

        /* OpenPIC */

        memory_region_add_subregion(&s->bar, 0x40000, s->pic_mem);

    }

    /* IDE buses */

    for (i = 0; i < ARRAY_SIZE(ns->ide); i++) {

        qemu_irq irq0 = ns->irqs[cur_irq++];

        qemu_irq irq1 = ns->irqs[cur_irq++];

        ret = macio_initfn_ide(s, &ns->ide[i], irq0, irq1, 0x16 + (i * 4));

        if (ret < 0) {

            return ret;

        }

    }

    /* Timer */

    memory_region_init_io(timer_memory, OBJECT(s), &timer_ops, NULL, "timer",

                          0x1000);

    memory_region_add_subregion(&s->bar, 0x15000, timer_memory);

    return 0;

}


static void cpu_openrisc_load_kernel(ram_addr_t ram_size,

                                     const char *kernel_filename,

                                     OpenRISCCPU *cpu)

{

    long kernel_size;

    uint64_t elf_entry;

    hwaddr entry;

    if (kernel_filename && !qtest_enabled()) {

        kernel_size = load_elf(kernel_filename, NULL, NULL,

                               &elf_entry, NULL, NULL, 1, ELF_MACHINE, 1);

        entry = elf_entry;

        if (kernel_size < 0) {

            kernel_size = load_uimage(kernel_filename,

                                      &entry, NULL, NULL);

        }

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename,

                                              KERNEL_LOAD_ADDR,

                                              ram_size - KERNEL_LOAD_ADDR);

            entry = KERNEL_LOAD_ADDR;

        }

        if (kernel_size < 0) {

            fprintf(stderr, "QEMU: couldn't load the kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

    }

    cpu->env.pc = entry;

}


void qmp_migrate(const char *uri, bool has_blk, bool blk,

                 bool has_inc, bool inc, bool has_detach, bool detach,

                 Error **errp)

{

    Error *local_err = NULL;

    MigrationState *s = migrate_get_current();

    MigrationParams params;

    const char *p;

    params.blk = has_blk && blk;

    params.shared = has_inc && inc;

    if (migration_is_setup_or_active(s->state) ||

        s->state == MIGRATION_STATUS_CANCELLING) {

        error_setg(errp, QERR_MIGRATION_ACTIVE);

        return;

    }

    if (runstate_check(RUN_STATE_INMIGRATE)) {

        error_setg(errp, "Guest is waiting for an incoming migration");

        return;

    }

    if (qemu_savevm_state_blocked(errp)) {

        return;

    }

    if (migration_blockers) {

        *errp = error_copy(migration_blockers->data);

        return;

    }

    s = migrate_init(&params);

    if (strstart(uri, "tcp:", &p)) {

        tcp_start_outgoing_migration(s, p, &local_err);

#ifdef CONFIG_RDMA

    } else if (strstart(uri, "rdma:", &p)) {

        rdma_start_outgoing_migration(s, p, &local_err);

#endif

#if !defined(WIN32)

    } else if (strstart(uri, "exec:", &p)) {

        exec_start_outgoing_migration(s, p, &local_err);

    } else if (strstart(uri, "unix:", &p)) {

        unix_start_outgoing_migration(s, p, &local_err);

    } else if (strstart(uri, "fd:", &p)) {

        fd_start_outgoing_migration(s, p, &local_err);

#endif

    } else {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",

                   "a valid migration protocol");

        migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,

                          MIGRATION_STATUS_FAILED);

        return;

    }

    if (local_err) {

        migrate_fd_error(s);

        error_propagate(errp, local_err);

        return;

    }

}


static void avc_luma_hv_qrt_and_aver_dst_16x16_msa(const uint8_t *src_x,

                                                   const uint8_t *src_y,

                                                   int32_t src_stride,

                                                   uint8_t *dst,

                                                   int32_t dst_stride)

{

    uint32_t multiple8_cnt;

    for (multiple8_cnt = 2; multiple8_cnt--;) {

        avc_luma_hv_qrt_and_aver_dst_8x8_msa(src_x, src_y, src_stride,

                                             dst, dst_stride);

        src_x += 8;

        src_y += 8;

        dst += 8;

    }

    src_x += (8 * src_stride) - 16;

    src_y += (8 * src_stride) - 16;

    dst += (8 * dst_stride) - 16;

    for (multiple8_cnt = 2; multiple8_cnt--;) {

        avc_luma_hv_qrt_and_aver_dst_8x8_msa(src_x, src_y, src_stride,

                                             dst, dst_stride);

        src_x += 8;

        src_y += 8;

        dst += 8;

    }

}


uint32_t net_checksum_add(int len, uint8_t *buf)

{

    uint32_t sum = 0;

    int i;

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

	if (i & 1)

	    sum += (uint32_t)buf[i];

	else

	    sum += (uint32_t)buf[i] << 8;

    }

    return sum;

}


static uint32_t hpet_ram_readl(void *opaque, target_phys_addr_t addr)

{

    HPETState *s = opaque;

    uint64_t cur_tick, index;

    DPRINTF("qemu: Enter hpet_ram_readl at %" PRIx64 "\n", addr);

    index = addr;

    /*address range of all TN regs*/

    if (index >= 0x100 && index <= 0x3ff) {

        uint8_t timer_id = (addr - 0x100) / 0x20;

        HPETTimer *timer = &s->timer[timer_id];

        if (timer_id > s->num_timers) {

            DPRINTF("qemu: timer id out of range\n");

            return 0;

        }

        switch ((addr - 0x100) % 0x20) {

        case HPET_TN_CFG:

            return timer->config;

        case HPET_TN_CFG + 4: // Interrupt capabilities

            return timer->config >> 32;

        case HPET_TN_CMP: // comparator register

            return timer->cmp;

        case HPET_TN_CMP + 4:

            return timer->cmp >> 32;

        case HPET_TN_ROUTE:

            return timer->fsb;

        case HPET_TN_ROUTE + 4:

            return timer->fsb >> 32;

        default:

            DPRINTF("qemu: invalid hpet_ram_readl\n");

            break;

        }

    } else {

        switch (index) {

        case HPET_ID:

            return s->capability;

        case HPET_PERIOD:

            return s->capability >> 32;

        case HPET_CFG:

            return s->config;

        case HPET_CFG + 4:

            DPRINTF("qemu: invalid HPET_CFG + 4 hpet_ram_readl \n");

            return 0;

        case HPET_COUNTER:

            if (hpet_enabled(s)) {

                cur_tick = hpet_get_ticks(s);

            } else {

                cur_tick = s->hpet_counter;

            }

            DPRINTF("qemu: reading counter  = %" PRIx64 "\n", cur_tick);

            return cur_tick;

        case HPET_COUNTER + 4:

            if (hpet_enabled(s)) {

                cur_tick = hpet_get_ticks(s);

            } else {

                cur_tick = s->hpet_counter;

            }

            DPRINTF("qemu: reading counter + 4  = %" PRIx64 "\n", cur_tick);

            return cur_tick >> 32;

        case HPET_STATUS:

            return s->isr;

        default:

            DPRINTF("qemu: invalid hpet_ram_readl\n");

            break;

        }

    }

    return 0;

}


static void gen_jump(DisasContext *dc, uint32_t imm, uint32_t reg, uint32_t op0)

{

    target_ulong tmp_pc;

    /* N26, 26bits imm */

    tmp_pc = sign_extend((imm<<2), 26) + dc->pc;

    switch (op0) {

    case 0x00:     /* l.j */

        tcg_gen_movi_tl(jmp_pc, tmp_pc);

        break;

    case 0x01:     /* l.jal */

        tcg_gen_movi_tl(cpu_R[9], (dc->pc + 8));

        tcg_gen_movi_tl(jmp_pc, tmp_pc);

        break;

    case 0x03:     /* l.bnf */

    case 0x04:     /* l.bf  */

        {

            int lab = gen_new_label();

            TCGv sr_f = tcg_temp_new();

            tcg_gen_movi_tl(jmp_pc, dc->pc+8);

            tcg_gen_andi_tl(sr_f, cpu_sr, SR_F);

            tcg_gen_brcondi_i32(op0 == 0x03 ? TCG_COND_EQ : TCG_COND_NE,

                                sr_f, SR_F, lab);

            tcg_gen_movi_tl(jmp_pc, tmp_pc);

            gen_set_label(lab);

            tcg_temp_free(sr_f);

        }

        break;

    case 0x11:     /* l.jr */

        tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);

        break;

    case 0x12:     /* l.jalr */

        tcg_gen_movi_tl(cpu_R[9], (dc->pc + 8));

        tcg_gen_mov_tl(jmp_pc, cpu_R[reg]);

        break;

    default:

        gen_illegal_exception(dc);

        break;

    }

    dc->delayed_branch = 2;

    dc->tb_flags |= D_FLAG;

    gen_sync_flags(dc);

}


static int net_init_nic(const NetClientOptions *opts, const char *name,

                        NetClientState *peer, Error **errp)

{

    int idx;

    NICInfo *nd;

    const NetLegacyNicOptions *nic;

    assert(opts->type == NET_CLIENT_OPTIONS_KIND_NIC);

    nic = opts->u.nic;

    idx = nic_get_free_idx();

    if (idx == -1 || nb_nics >= MAX_NICS) {

        error_setg(errp, "too many NICs");

        return -1;

    }

    nd = &nd_table[idx];

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

    if (nic->has_netdev) {

        nd->netdev = qemu_find_netdev(nic->netdev);

        if (!nd->netdev) {

            error_setg(errp, "netdev '%s' not found", nic->netdev);

            return -1;

        }

    } else {

        assert(peer);

        nd->netdev = peer;

    }

    nd->name = g_strdup(name);

    if (nic->has_model) {

        nd->model = g_strdup(nic->model);

    }

    if (nic->has_addr) {

        nd->devaddr = g_strdup(nic->addr);

    }

    if (nic->has_macaddr &&

        net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {

        error_setg(errp, "invalid syntax for ethernet address");

        return -1;

    }

    if (nic->has_macaddr &&

        is_multicast_ether_addr(nd->macaddr.a)) {

        error_setg(errp,

                   "NIC cannot have multicast MAC address (odd 1st byte)");

        return -1;

    }

    qemu_macaddr_default_if_unset(&nd->macaddr);

    if (nic->has_vectors) {

        if (nic->vectors > 0x7ffffff) {

            error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);

            return -1;

        }

        nd->nvectors = nic->vectors;

    } else {

        nd->nvectors = DEV_NVECTORS_UNSPECIFIED;

    }

    nd->used = 1;

    nb_nics++;

    return idx;

}


static int dxtory_decode_v2_410(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    GetByteContext gb;

    GetBitContext  gb2;

    int nslices, slice, slice_height, ref_slice_height;

    int cur_y, next_y;

    uint32_t off, slice_size;

    uint8_t *Y, *U, *V;

    int ret;

    bytestream2_init(&gb, src, src_size);

    nslices = bytestream2_get_le16(&gb);

    off = FFALIGN(nslices * 4 + 2, 16);

    if (src_size < off) {

        av_log(avctx, AV_LOG_ERROR, "no slice data\n");

        return AVERROR_INVALIDDATA;

    }

    if (!nslices || avctx->height % nslices) {

        avpriv_request_sample(avctx, "%d slices for %dx%d", nslices,

                              avctx->width, avctx->height);

        return AVERROR_PATCHWELCOME;

    }

    ref_slice_height = avctx->height / nslices;

    if ((avctx->width & 3) || (avctx->height & 3)) {

        avpriv_request_sample(avctx, "Frame dimensions %dx%d",

                              avctx->width, avctx->height);

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV410P;

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

        return ret;

    Y = pic->data[0];

    U = pic->data[1];

    V = pic->data[2];

    cur_y  = 0;

    next_y = ref_slice_height;

    for (slice = 0; slice < nslices; slice++) {

        slice_size   = bytestream2_get_le32(&gb);

        slice_height = (next_y & ~3) - (cur_y & ~3);

        if (slice_size > src_size - off) {

            av_log(avctx, AV_LOG_ERROR,

                   "invalid slice size %"PRIu32" (only %"PRIu32" bytes left)\n",

                   slice_size, src_size - off);

            return AVERROR_INVALIDDATA;

        }

        if (slice_size <= 16) {

            av_log(avctx, AV_LOG_ERROR, "invalid slice size %"PRIu32"\n", slice_size);

            return AVERROR_INVALIDDATA;

        }

        if (AV_RL32(src + off) != slice_size - 16) {

            av_log(avctx, AV_LOG_ERROR,

                   "Slice sizes mismatch: got %"PRIu32" instead of %"PRIu32"\n",

                   AV_RL32(src + off), slice_size - 16);

        }

        init_get_bits(&gb2, src + off + 16, (slice_size - 16) * 8);

        dx2_decode_slice_410(&gb2, avctx->width, slice_height, Y, U, V,

                             pic->linesize[0], pic->linesize[1],

                             pic->linesize[2]);

        Y += pic->linesize[0] *  slice_height;

        U += pic->linesize[1] * (slice_height >> 2);

        V += pic->linesize[2] * (slice_height >> 2);

        off += slice_size;

        cur_y   = next_y;

        next_y += ref_slice_height;

    }

    return 0;

}


int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)

{

    struct kvm_irq_routing_entry kroute;

    if (!kvm_irqchip_in_kernel()) {

        return -ENOSYS;

    }

    kroute.gsi = virq;

    kroute.type = KVM_IRQ_ROUTING_MSI;

    kroute.flags = 0;

    kroute.u.msi.address_lo = (uint32_t)msg.address;

    kroute.u.msi.address_hi = msg.address >> 32;

    kroute.u.msi.data = msg.data;

    return kvm_update_routing_entry(s, &kroute);

}


type_init(pflash_cfi01_register_types)

pflash_t *pflash_cfi01_register(hwaddr base,

                                DeviceState *qdev, const char *name,

                                hwaddr size,

                                BlockDriverState *bs,

                                uint32_t sector_len, int nb_blocs,

                                int bank_width, uint16_t id0, uint16_t id1,

                                uint16_t id2, uint16_t id3, int be)

{

    DeviceState *dev = qdev_create(NULL, TYPE_CFI_PFLASH01);

    if (bs && qdev_prop_set_drive(dev, "drive", bs)) {

        abort();

    }

    qdev_prop_set_uint32(dev, "num-blocks", nb_blocs);

    qdev_prop_set_uint64(dev, "sector-length", sector_len);

    qdev_prop_set_uint8(dev, "width", bank_width);

    qdev_prop_set_uint8(dev, "big-endian", !!be);

    qdev_prop_set_uint16(dev, "id0", id0);

    qdev_prop_set_uint16(dev, "id1", id1);

    qdev_prop_set_uint16(dev, "id2", id2);

    qdev_prop_set_uint16(dev, "id3", id3);

    qdev_prop_set_string(dev, "name", name);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, base);

    return CFI_PFLASH01(dev);

}


static void vnc_write_u16(VncState *vs, uint16_t value)

{

    uint8_t buf[2];

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

    buf[1] = value & 0xFF;

    vnc_write(vs, buf, 2);

}


type_init(assign_register_types)

static void assigned_dev_load_option_rom(AssignedDevice *dev)

{

    int size = 0;

    pci_assign_dev_load_option_rom(&dev->dev, OBJECT(dev), &size,

                                   dev->host.domain, dev->host.bus,

                                   dev->host.slot, dev->host.function);

    if (!size) {

        error_report("pci-assign: Invalid ROM.");

    }

}


static void ide_issue_trim_cb(void *opaque, int ret)

{

    TrimAIOCB *iocb = opaque;

    if (ret >= 0) {

        while (iocb->j < iocb->qiov->niov) {

            int j = iocb->j;

            while (++iocb->i < iocb->qiov->iov[j].iov_len / 8) {

                int i = iocb->i;

                uint64_t *buffer = iocb->qiov->iov[j].iov_base;

                /* 6-byte LBA + 2-byte range per entry */

                uint64_t entry = le64_to_cpu(buffer[i]);

                uint64_t sector = entry & 0x0000ffffffffffffULL;

                uint16_t count = entry >> 48;

                if (count == 0) {

                    continue;

                }

                /* Got an entry! Submit and exit.  */

                iocb->aiocb = blk_aio_pdiscard(iocb->blk,

                                               sector << BDRV_SECTOR_BITS,

                                               count << BDRV_SECTOR_BITS,

                                               ide_issue_trim_cb, opaque);

                return;

            }

            iocb->j++;

            iocb->i = -1;

        }

    } else {

        iocb->ret = ret;

    }

    iocb->aiocb = NULL;

    if (iocb->bh) {

        qemu_bh_schedule(iocb->bh);

    }

}


static void usbredir_device_disconnect(void *priv)

{

    USBRedirDevice *dev = priv;

    int i;

    /* Stop any pending attaches */

    qemu_del_timer(dev->attach_timer);

    if (dev->dev.attached) {

        usb_device_detach(&dev->dev);

        /*

         * Delay next usb device attach to give the guest a chance to see

         * see the detach / attach in case of quick close / open succession

         */

        dev->next_attach_time = qemu_get_clock_ms(vm_clock) + 200;

    }

    /* Reset state so that the next dev connected starts with a clean slate */

    usbredir_cleanup_device_queues(dev);

    memset(dev->endpoint, 0, sizeof(dev->endpoint));

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

        QTAILQ_INIT(&dev->endpoint[i].bufpq);

    }

    usb_ep_init(&dev->dev);

    dev->interface_info.interface_count = 0;

}


static void pm_write_config(PCIDevice *d,

                            uint32_t address, uint32_t val, int len)

{

    DPRINTF("pm_write_config  address 0x%x  val 0x%x len 0x%x \n",

           address, val, len);

    pci_default_write_config(d, address, val, len);

}


static int rv20_decode_picture_header(MpegEncContext *s)

{

    int seq, mb_pos, i;

    i= get_bits(&s->gb, 2);

    switch(i){

    case 0: s->pict_type= I_TYPE; break;

    case 1: s->pict_type= I_TYPE; break; //hmm ...

    case 2: s->pict_type= P_TYPE; break;

    case 3: s->pict_type= B_TYPE; break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, "unknown frame type\n");

        return -1;

    }

    if (get_bits(&s->gb, 1)){

        av_log(s->avctx, AV_LOG_ERROR, "unknown bit set\n");

        return -1;

    }

    s->qscale = get_bits(&s->gb, 5);

    if(s->qscale==0){

        av_log(s->avctx, AV_LOG_ERROR, "error, qscale:0\n");

        return -1;

    }

    if(s->avctx->sub_id == 0x20200002)

        seq= get_bits(&s->gb, 16);

    else

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

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

        if(s->mb_width*s->mb_height < ff_mba_max[i]) break;

    }

    mb_pos= get_bits(&s->gb, ff_mba_length[i]);

    s->mb_x= mb_pos % s->mb_width;

    s->mb_y= mb_pos / s->mb_width;

    s->no_rounding= get_bits1(&s->gb);

    s->f_code = 1;

    s->unrestricted_mv = 1;

    s->h263_aic= s->pict_type == I_TYPE;

//    s->alt_inter_vlc=1;

//    s->obmc=1;

//    s->umvplus=1;

//    s->modified_quant=1;

    if(s->avctx->debug & FF_DEBUG_PICT_INFO){

            av_log(s->avctx, AV_LOG_INFO, "num:%5d x:%2d y:%2d type:%d qscale:%2d rnd:%d\n",

                   seq, s->mb_x, s->mb_y, s->pict_type, s->qscale, s->no_rounding);

    }

    if (s->pict_type == B_TYPE){

        av_log(s->avctx, AV_LOG_ERROR, "b frame not supported\n");

        return -1;

    }

    return s->mb_width*s->mb_height - mb_pos;

}


static void test_visitor_in_union_flat(TestInputVisitorData *data,

                                       const void *unused)

{

    Visitor *v;

    Error *err = NULL;

    UserDefFlatUnion *tmp;

    UserDefUnionBase *base;

    v = visitor_input_test_init(data,

                                "{ 'enum1': 'value1', "

                                "'integer': 41, "

                                "'string': 'str', "

                                "'boolean': true }");

    visit_type_UserDefFlatUnion(v, &tmp, NULL, &err);

    g_assert(err == NULL);

    g_assert_cmpint(tmp->enum1, ==, ENUM_ONE_VALUE1);

    g_assert_cmpstr(tmp->string, ==, "str");

    g_assert_cmpint(tmp->integer, ==, 41);

    g_assert_cmpint(tmp->u.value1->boolean, ==, true);

    base = qapi_UserDefFlatUnion_base(tmp);

    g_assert(&base->enum1 == &tmp->enum1);

    qapi_free_UserDefFlatUnion(tmp);

}


static void s390_pcihost_hot_unplug(HotplugHandler *hotplug_dev,

                                    DeviceState *dev, Error **errp)

{

    PCIDevice *pci_dev = NULL;

    PCIBus *bus;

    int32_t devfn;

    S390PCIBusDevice *pbdev = NULL;

    S390pciState *s = s390_get_phb();

    if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_BRIDGE)) {

        error_setg(errp, "PCI bridge hot unplug currently not supported");

        return;

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {

        pci_dev = PCI_DEVICE(dev);

        QTAILQ_FOREACH(pbdev, &s->zpci_devs, link) {

            if (pbdev->pdev == pci_dev) {

                break;

            }

        }

        assert(pbdev != NULL);

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_S390_PCI_DEVICE)) {

        pbdev = S390_PCI_DEVICE(dev);

        pci_dev = pbdev->pdev;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

        goto out;

    case ZPCI_FS_STANDBY:

        break;

    default:

        s390_pci_generate_plug_event(HP_EVENT_DECONFIGURE_REQUEST,

                                     pbdev->fh, pbdev->fid);

        pbdev->release_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                            s390_pcihost_timer_cb,

                                            pbdev);

        timer_mod(pbdev->release_timer,

                  qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + HOT_UNPLUG_TIMEOUT);

        return;

    }

    if (pbdev->release_timer && timer_pending(pbdev->release_timer)) {

        timer_del(pbdev->release_timer);

        timer_free(pbdev->release_timer);

        pbdev->release_timer = NULL;

    }

    s390_pci_generate_plug_event(HP_EVENT_STANDBY_TO_RESERVED,

                                 pbdev->fh, pbdev->fid);

    bus = pci_dev->bus;

    devfn = pci_dev->devfn;

    object_unparent(OBJECT(pci_dev));

    s390_pci_msix_free(pbdev);

    s390_pci_iommu_free(s, bus, devfn);

    pbdev->pdev = NULL;

    pbdev->state = ZPCI_FS_RESERVED;

out:

    pbdev->fid = 0;

    QTAILQ_REMOVE(&s->zpci_devs, pbdev, link);

    g_hash_table_remove(s->zpci_table, &pbdev->idx);

    object_unparent(OBJECT(pbdev));

}


static int parse_presentation_segment(AVCodecContext *avctx,

                                      const uint8_t *buf, int buf_size,

                                      int64_t pts)

{

    PGSSubContext *ctx = avctx->priv_data;

    int i, state, ret;

    // Video descriptor

    int w = bytestream_get_be16(&buf);

    int h = bytestream_get_be16(&buf);

    uint16_t object_index;

    ctx->presentation.pts = pts;

    av_dlog(avctx, "Video Dimensions %dx%d\n",

            w, h);

    ret = ff_set_dimensions(avctx, w, h);

    if (ret < 0)

        return ret;

    /* Skip 1 bytes of unknown, frame rate */

    buf++;

    // Composition descriptor

    ctx->presentation.id_number = bytestream_get_be16(&buf);

    /*

     * state is a 2 bit field that defines pgs epoch boundaries

     * 00 - Normal, previously defined objects and palettes are still valid

     * 01 - Acquisition point, previous objects and palettes can be released

     * 10 - Epoch start, previous objects and palettes can be released

     * 11 - Epoch continue, previous objects and palettes can be released

     *

     * reserved 6 bits discarded

     */

    state = bytestream_get_byte(&buf) >> 6;

    if (state != 0) {

        flush_cache(avctx);

    }

    /*

     * skip palette_update_flag (0x80),

     */

    buf += 1;

    ctx->presentation.palette_id = bytestream_get_byte(&buf);

    ctx->presentation.object_count = bytestream_get_byte(&buf);

    if (ctx->presentation.object_count > MAX_OBJECT_REFS) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid number of presentation objects %d\n",

               ctx->presentation.object_count);

        ctx->presentation.object_count = 2;

        if (avctx->err_recognition & AV_EF_EXPLODE) {

            return AVERROR_INVALIDDATA;

        }

    }

    for (i = 0; i < ctx->presentation.object_count; i++)

    {

        if (buf_end - buf < 8) {

            av_log(avctx, AV_LOG_ERROR, "Insufficent space for object\n");

            ctx->presentation.object_count = i;

            return AVERROR_INVALIDDATA;

        }

        ctx->presentation.objects[i].id = bytestream_get_be16(&buf);

        ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);

        ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);

        ctx->presentation.objects[i].x = bytestream_get_be16(&buf);

        ctx->presentation.objects[i].y = bytestream_get_be16(&buf);

        // If cropping

        if (ctx->presentation.objects[i].composition_flag & 0x80) {

            ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);

            ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);

            ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);

            ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);

        }

        av_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",

                ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);

        if (ctx->presentation.objects[i].x > avctx->width ||

            ctx->presentation.objects[i].y > avctx->height) {

            av_log(avctx, AV_LOG_ERROR, "Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\n",

                   ctx->presentation.objects[i].x,

                   ctx->presentation.objects[i].y,

                    avctx->width, avctx->height);

            ctx->presentation.objects[i].x = 0;

            ctx->presentation.objects[i].y = 0;

            if (avctx->err_recognition & AV_EF_EXPLODE) {

                return AVERROR_INVALIDDATA;

            }

        }

    }

    return 0;

}


static int crypto_close(URLContext *h)

{

    CryptoContext *c = h->priv_data;

    if (c->hd)

        ffurl_close(c->hd);

    av_freep(&c->aes);

    av_freep(&c->key);

    av_freep(&c->iv);

    return 0;

}


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

                              int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    int swap_buf_size  = buf_size - MIMIC_HEADER_SIZE;

    MimicContext *ctx  = avctx->priv_data;

    GetByteContext gb;

    int is_pframe;

    int width, height;

    int quality, num_coeffs;

    int res;

    if (buf_size <= MIMIC_HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "insufficient data\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_init(&gb, buf, MIMIC_HEADER_SIZE);

    bytestream2_skip(&gb, 2); /* some constant (always 256) */

    quality    = bytestream2_get_le16u(&gb);

    width      = bytestream2_get_le16u(&gb);

    height     = bytestream2_get_le16u(&gb);

    bytestream2_skip(&gb, 4); /* some constant */

    is_pframe  = bytestream2_get_le32u(&gb);

    num_coeffs = bytestream2_get_byteu(&gb);

    bytestream2_skip(&gb, 3); /* some constant */

    if (!ctx->avctx) {

        int i;

        if (!(width == 160 && height == 120) &&

            !(width == 320 && height == 240)) {

            av_log(avctx, AV_LOG_ERROR, "invalid width/height!\n");

            return AVERROR_INVALIDDATA;

        }

        ctx->avctx     = avctx;

        avctx->width   = width;

        avctx->height  = height;

        avctx->pix_fmt = AV_PIX_FMT_YUV420P;

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

            ctx->num_vblocks[i] = AV_CEIL_RSHIFT(height,   3 + !!i);

            ctx->num_hblocks[i] =                width >> (3 + !!i);

        }

    } else if (width != ctx->avctx->width || height != ctx->avctx->height) {

        avpriv_request_sample(avctx, "Resolution changing");

        return AVERROR_PATCHWELCOME;

    }

    if (is_pframe && !ctx->frames[ctx->prev_index].f->data[0]) {

        av_log(avctx, AV_LOG_ERROR, "decoding must start with keyframe\n");

        return AVERROR_INVALIDDATA;

    }

    ff_thread_release_buffer(avctx, &ctx->frames[ctx->cur_index]);

    ctx->frames[ctx->cur_index].f->pict_type = is_pframe ? AV_PICTURE_TYPE_P :

                                                           AV_PICTURE_TYPE_I;

    if ((res = ff_thread_get_buffer(avctx, &ctx->frames[ctx->cur_index],

                                    AV_GET_BUFFER_FLAG_REF)) < 0) {

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

        return res;

    }

    ctx->next_prev_index = ctx->cur_index;

    ctx->next_cur_index  = (ctx->cur_index - 1) & 15;

    ff_thread_finish_setup(avctx);

    av_fast_padded_malloc(&ctx->swap_buf, &ctx->swap_buf_size, swap_buf_size);

    if (!ctx->swap_buf)

        return AVERROR(ENOMEM);

    ctx->bbdsp.bswap_buf(ctx->swap_buf,

                         (const uint32_t *) (buf + MIMIC_HEADER_SIZE),

                         swap_buf_size >> 2);

    init_get_bits(&ctx->gb, ctx->swap_buf, swap_buf_size << 3);

    res = decode(ctx, quality, num_coeffs, !is_pframe);

    ff_thread_report_progress(&ctx->frames[ctx->cur_index], INT_MAX, 0);

    if (res < 0) {

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

            ff_thread_release_buffer(avctx, &ctx->frames[ctx->cur_index]);

        return res;

    }

    if ((res = av_frame_ref(data, ctx->frames[ctx->cur_index].f)) < 0)

        return res;

    *got_frame      = 1;

    flip_swap_frame(data);

    ctx->prev_index = ctx->next_prev_index;

    ctx->cur_index  = ctx->next_cur_index;

    /* Only release frames that aren't used for backreferences anymore */

    ff_thread_release_buffer(avctx, &ctx->frames[ctx->cur_index]);

    return buf_size;

}


static void vmgenid_set_guid_auto_test(void)

{

    const char *cmd;

    QemuUUID measured;

    cmd = "-machine accel=tcg -device vmgenid,id=testvgid," "guid=auto";

    qtest_start(cmd);

    read_guid_from_memory(&measured);

    /* Just check that the GUID is non-null */

    g_assert(!qemu_uuid_is_null(&measured));

    qtest_quit(global_qtest);

}


static TCGv gen_lea_indexed(CPUM68KState *env, DisasContext *s, TCGv base)
{
    uint32_t offset;
    uint16_t ext;
    TCGv add;
    TCGv tmp;
    uint32_t bd, od;
    offset = s->pc;
    ext = cpu_lduw_code(env, s->pc);
    s->pc += 2;
    if ((ext & 0x800) == 0 && !m68k_feature(s->env, M68K_FEATURE_WORD_INDEX))
        return NULL_QREG;
    if (ext & 0x100) {
        /* full extension word format */
        if (!m68k_feature(s->env, M68K_FEATURE_EXT_FULL))
            return NULL_QREG;
        if ((ext & 0x30) > 0x10) {
            /* base displacement */
            if ((ext & 0x30) == 0x20) {
                bd = (int16_t)cpu_lduw_code(env, s->pc);
                s->pc += 2;
            } else {
                bd = read_im32(env, s);
        } else {
            bd = 0;
        tmp = tcg_temp_new();
        if ((ext & 0x44) == 0) {
            /* pre-index */
            add = gen_addr_index(ext, tmp);
        } else {
            add = NULL_QREG;
        if ((ext & 0x80) == 0) {
            /* base not suppressed */
            if (IS_NULL_QREG(base)) {
                base = tcg_const_i32(offset + bd);
                bd = 0;
            if (!IS_NULL_QREG(add)) {
                tcg_gen_add_i32(tmp, add, base);
                add = tmp;
            } else {
                add = base;
        if (!IS_NULL_QREG(add)) {
            if (bd != 0) {
                tcg_gen_addi_i32(tmp, add, bd);
                add = tmp;
        } else {
            add = tcg_const_i32(bd);
        if ((ext & 3) != 0) {
            /* memory indirect */
            base = gen_load(s, OS_LONG, add, 0);
            if ((ext & 0x44) == 4) {
                add = gen_addr_index(ext, tmp);
                tcg_gen_add_i32(tmp, add, base);
                add = tmp;
            } else {
                add = base;
            if ((ext & 3) > 1) {
                /* outer displacement */
                if ((ext & 3) == 2) {
                    od = (int16_t)cpu_lduw_code(env, s->pc);
                    s->pc += 2;
                } else {
                    od = read_im32(env, s);
            } else {
                od = 0;
            if (od != 0) {
                tcg_gen_addi_i32(tmp, add, od);
                add = tmp;
    } else {
        /* brief extension word format */
        tmp = tcg_temp_new();
        add = gen_addr_index(ext, tmp);
        if (!IS_NULL_QREG(base)) {
            tcg_gen_add_i32(tmp, add, base);
            if ((int8_t)ext)
                tcg_gen_addi_i32(tmp, tmp, (int8_t)ext);
        } else {
            tcg_gen_addi_i32(tmp, add, offset + (int8_t)ext);
        add = tmp;
    return add;


int swr_convert_frame(SwrContext *s,

                      AVFrame *out, const AVFrame *in)

{

    int ret, setup = 0;

    if (!swr_is_initialized(s)) {

        if ((ret = swr_config_frame(s, out, in)) < 0)

            return ret;

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

            return ret;

        setup = 1;

    } else {

        // return as is or reconfigure for input changes?

        if ((ret = config_changed(s, out, in)))

            return ret;

    }

    if (out) {

        if (!out->linesize[0]) {

            out->nb_samples =   swr_get_delay(s, s->out_sample_rate)

                              + in->nb_samples*(int64_t)s->out_sample_rate / s->in_sample_rate

                              + 3;

            if ((ret = av_frame_get_buffer(out, 0)) < 0) {

                if (setup)

                    swr_close(s);

                return ret;

            }

        } else {

            if (!out->nb_samples)

                out->nb_samples = available_samples(out);

        }

    }

    return convert_frame(s, out, in);

}


av_cold static int fbdev_read_header(AVFormatContext *avctx,

                                     AVFormatParameters *ap)

{

    FBDevContext *fbdev = avctx->priv_data;

    AVStream *st = NULL;

    enum PixelFormat pix_fmt;

    int ret, flags = O_RDONLY;

    ret = av_parse_video_rate(&fbdev->framerate_q, fbdev->framerate);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Couldn't parse framerate.\n");

        return ret;

    }

#if FF_API_FORMAT_PARAMETERS

    if (ap->time_base.num)

        fbdev->framerate_q = (AVRational){ap->time_base.den, ap->time_base.num};

#endif

    if (!(st = av_new_stream(avctx, 0)))

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in microseconds */

    /* NONBLOCK is ignored by the fbdev driver, only set for consistency */

    if (avctx->flags & AVFMT_FLAG_NONBLOCK)

        flags |= O_NONBLOCK;

    if ((fbdev->fd = open(avctx->filename, flags)) == -1) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "Could not open framebuffer device '%s': %s\n",

               avctx->filename, strerror(ret));

        return ret;

    }

    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "FBIOGET_VSCREENINFO: %s\n", strerror(errno));

        goto fail;

    }

    if (ioctl(fbdev->fd, FBIOGET_FSCREENINFO, &fbdev->fixinfo) < 0) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "FBIOGET_FSCREENINFO: %s\n", strerror(errno));

        goto fail;

    }

    pix_fmt = get_pixfmt_from_fb_varinfo(&fbdev->varinfo);

    if (pix_fmt == PIX_FMT_NONE) {

        ret = AVERROR(EINVAL);

        av_log(avctx, AV_LOG_ERROR,

               "Framebuffer pixel format not supported.\n");

        goto fail;

    }

    fbdev->width           = fbdev->varinfo.xres;

    fbdev->heigth          = fbdev->varinfo.yres;

    fbdev->bytes_per_pixel = (fbdev->varinfo.bits_per_pixel + 7) >> 3;

    fbdev->frame_linesize  = fbdev->width * fbdev->bytes_per_pixel;

    fbdev->frame_size      = fbdev->frame_linesize * fbdev->heigth;

    fbdev->time_frame      = AV_NOPTS_VALUE;

    fbdev->data = mmap(NULL, fbdev->fixinfo.smem_len, PROT_READ, MAP_SHARED, fbdev->fd, 0);

    if (fbdev->data == MAP_FAILED) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR, "Error in mmap(): %s\n", strerror(errno));

        goto fail;

    }

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id   = CODEC_ID_RAWVIDEO;

    st->codec->width      = fbdev->width;

    st->codec->height     = fbdev->heigth;

    st->codec->pix_fmt    = pix_fmt;

    st->codec->time_base  = (AVRational){fbdev->framerate_q.den, fbdev->framerate_q.num};

    st->codec->bit_rate   =

        fbdev->width * fbdev->heigth * fbdev->bytes_per_pixel * av_q2d(fbdev->framerate_q) * 8;

    av_log(avctx, AV_LOG_INFO,

           "w:%d h:%d bpp:%d pixfmt:%s fps:%d/%d bit_rate:%d\n",

           fbdev->width, fbdev->heigth, fbdev->varinfo.bits_per_pixel,

           av_pix_fmt_descriptors[pix_fmt].name,

           fbdev->framerate_q.num, fbdev->framerate_q.den,

           st->codec->bit_rate);

    return 0;

fail:

    close(fbdev->fd);

    return ret;

}


static abi_long target_to_host_data_route(struct nlmsghdr *nlh)

{

    struct ifinfomsg *ifi;

    struct ifaddrmsg *ifa;

    struct rtmsg *rtm;

    switch (nlh->nlmsg_type) {

    case RTM_GETLINK:

        break;

    case RTM_NEWLINK:

    case RTM_DELLINK:

        ifi = NLMSG_DATA(nlh);

        ifi->ifi_type = tswap16(ifi->ifi_type);

        ifi->ifi_index = tswap32(ifi->ifi_index);

        ifi->ifi_flags = tswap32(ifi->ifi_flags);

        ifi->ifi_change = tswap32(ifi->ifi_change);

        target_to_host_link_rtattr(IFLA_RTA(ifi), nlh->nlmsg_len -

                                   NLMSG_LENGTH(sizeof(*ifi)));

        break;

    case RTM_GETADDR:

    case RTM_NEWADDR:

    case RTM_DELADDR:

        ifa = NLMSG_DATA(nlh);

        ifa->ifa_index = tswap32(ifa->ifa_index);

        target_to_host_addr_rtattr(IFA_RTA(ifa), nlh->nlmsg_len -

                                   NLMSG_LENGTH(sizeof(*ifa)));

        break;

    case RTM_GETROUTE:

        break;

    case RTM_NEWROUTE:

    case RTM_DELROUTE:

        rtm = NLMSG_DATA(nlh);

        rtm->rtm_flags = tswap32(rtm->rtm_flags);

        target_to_host_route_rtattr(RTM_RTA(rtm), nlh->nlmsg_len -

                                    NLMSG_LENGTH(sizeof(*rtm)));

        break;

    default:

        return -TARGET_EOPNOTSUPP;

    }

    return 0;

}


static int parse_channel_expressions(AVFilterContext *ctx,

                                     int expected_nb_channels)

{

    EvalContext *eval = ctx->priv;

    char *args1 = av_strdup(eval->exprs);

    char *expr, *last_expr, *buf;

    double (* const *func1)(void *, double) = NULL;

    const char * const *func1_names = NULL;

    int i, ret = 0;

    if (!args1)

        return AVERROR(ENOMEM);

    if (!eval->exprs) {

        av_log(ctx, AV_LOG_ERROR, "Channels expressions list is empty\n");

        return AVERROR(EINVAL);

    }

    if (!strcmp(ctx->filter->name, "aeval")) {

        func1 = aeval_func1;

        func1_names = aeval_func1_names;

    }

#define ADD_EXPRESSION(expr_) do {                                      \

        if (!av_dynarray2_add((void **)&eval->expr, &eval->nb_channels, \

                              sizeof(*eval->expr), NULL)) {             \

            ret = AVERROR(ENOMEM);                                      \

            goto end;                                                   \

        }                                                               \

        eval->expr[eval->nb_channels-1] = NULL;                         \

        ret = av_expr_parse(&eval->expr[eval->nb_channels - 1], expr_,  \

                            var_names, func1_names, func1,              \

                            NULL, NULL, 0, ctx);                        \

        if (ret < 0)                                                    \

            goto end;                                                   \

    } while (0)

    /* reset expressions */

    for (i = 0; i < eval->nb_channels; i++) {

        av_expr_free(eval->expr[i]);

        eval->expr[i] = NULL;

    }

    av_freep(&eval->expr);

    eval->nb_channels = 0;

    buf = args1;

    while (expr = av_strtok(buf, "|", &buf)) {

        ADD_EXPRESSION(expr);

        last_expr = expr;

    }

    if (expected_nb_channels > eval->nb_channels)

        for (i = eval->nb_channels; i < expected_nb_channels; i++)

            ADD_EXPRESSION(last_expr);

    if (expected_nb_channels > 0 && eval->nb_channels != expected_nb_channels) {

        av_log(ctx, AV_LOG_ERROR,

               "Mismatch between the specified number of channel expressions '%d' "

               "and the number of expected output channels '%d' for the specified channel layout\n",

               eval->nb_channels, expected_nb_channels);

        ret = AVERROR(EINVAL);

        goto end;

    }

end:

    av_free(args1);

    return ret;

}


static int sdp_probe(AVProbeData *p1)

{

    const char *p = p1->buf, *p_end = p1->buf + p1->buf_size;

    /* we look for a line beginning "c=IN IP" */

    while (p < p_end && *p != '\0') {

        if (p + sizeof("c=IN IP") - 1 < p_end &&

            av_strstart(p, "c=IN IP", NULL))

            return AVPROBE_SCORE_EXTENSION;

        while (p < p_end - 1 && *p != '\n') p++;

        if (++p >= p_end)

            break;

        if (*p == '\r')

            p++;

    }

    return 0;

}


int avcodec_decode_audio(AVCodecContext *avctx, int16_t *samples,

                         int *frame_size_ptr,

                         uint8_t *buf, int buf_size)

{

    int ret;

    *frame_size_ptr= 0;

    ret = avctx->codec->decode(avctx, samples, frame_size_ptr,

                               buf, buf_size);

    avctx->frame_number++;

    return ret;

}