static int pixlet_decode_frame(AVCodecContext *avctx, void *data,
                               int *got_frame, AVPacket *avpkt)
{
    PixletContext *ctx = avctx->priv_data;
    int i, w, h, width, height, ret, version;
    AVFrame *p = data;
    ThreadFrame frame = { .f = data };
    uint32_t pktsize;
    bytestream2_init(&ctx->gb, avpkt->data, avpkt->size);
    pktsize = bytestream2_get_be32(&ctx->gb);
    if (pktsize <= 44 || pktsize - 4 > bytestream2_get_bytes_left(&ctx->gb)) {
        av_log(avctx, AV_LOG_ERROR, "Invalid packet size %"PRIu32"\n", pktsize);
    }
    version = bytestream2_get_le32(&ctx->gb);
    if (version != 1)
        avpriv_request_sample(avctx, "Version %d", version);
    bytestream2_skip(&ctx->gb, 4);
    if (bytestream2_get_be32(&ctx->gb) != 1)
    bytestream2_skip(&ctx->gb, 4);
    width  = bytestream2_get_be32(&ctx->gb);
    height = bytestream2_get_be32(&ctx->gb);
    w = FFALIGN(width,  1 << (NB_LEVELS + 1));
    h = FFALIGN(height, 1 << (NB_LEVELS + 1));
    ctx->levels = bytestream2_get_be32(&ctx->gb);
    if (ctx->levels != NB_LEVELS)
    ctx->depth = bytestream2_get_be32(&ctx->gb);
    if (ctx->depth < 8 || ctx->depth > 15) {
        avpriv_request_sample(avctx, "Depth %d", ctx->depth);
    }
    ret = ff_set_dimensions(avctx, w, h);
    if (ret < 0)
        return ret;
    avctx->width  = width;
    avctx->height = height;
    if (ctx->w != w || ctx->h != h) {
        free_buffers(avctx);
        ctx->w = w;
        ctx->h = h;
        ret = init_decoder(avctx);
        if (ret < 0) {
            free_buffers(avctx);
            ctx->w = 0;
            ctx->h = 0;
            return ret;
        }
    }
    bytestream2_skip(&ctx->gb, 8);
    p->pict_type = AV_PICTURE_TYPE_I;
    p->key_frame = 1;
    p->color_range = AVCOL_RANGE_JPEG;
    ret = ff_thread_get_buffer(avctx, &frame, 0);
    if (ret < 0)
        return ret;
    for (i = 0; i < 3; i++) {
        ret = decode_plane(avctx, i, avpkt, frame.f);
        if (ret < 0)
            return ret;
        if (avctx->flags & AV_CODEC_FLAG_GRAY)
            break;
    }
    postprocess_luma(frame.f, ctx->w, ctx->h, ctx->depth);
    postprocess_chroma(frame.f, ctx->w >> 1, ctx->h >> 1, ctx->depth);
    *got_frame = 1;
    return pktsize;
}


static void ccw_machine_2_9_class_options(MachineClass *mc)

{

    S390CcwMachineClass *s390mc = S390_MACHINE_CLASS(mc);

    s390mc->gs_allowed = false;

    ccw_machine_2_10_class_options(mc);

    SET_MACHINE_COMPAT(mc, CCW_COMPAT_2_9);

    s390mc->css_migration_enabled = false;

}


static int matroska_read_header(AVFormatContext *s)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    EbmlList *attachements_list = &matroska->attachments;

    MatroskaAttachement *attachements;

    EbmlList *chapters_list = &matroska->chapters;

    MatroskaChapter *chapters;

    MatroskaTrack *tracks;

    uint64_t max_start = 0;

    int64_t pos;

    Ebml ebml = { 0 };

    AVStream *st;

    int i, j, k, res;

    matroska->ctx = s;

    /* First read the EBML header. */

    if (ebml_parse(matroska, ebml_syntax, &ebml)

        || ebml.version > EBML_VERSION       || ebml.max_size > sizeof(uint64_t)

        || ebml.id_length > sizeof(uint32_t) || ebml.doctype_version > 3) {

        av_log(matroska->ctx, AV_LOG_ERROR,

               "EBML header using unsupported features\n"

               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",

               ebml.version, ebml.doctype, ebml.doctype_version);

        ebml_free(ebml_syntax, &ebml);

        return AVERROR_PATCHWELCOME;

    } else if (ebml.doctype_version == 3) {

        av_log(matroska->ctx, AV_LOG_WARNING,

               "EBML header using unsupported features\n"

               "(EBML version %"PRIu64", doctype %s, doc version %"PRIu64")\n",

               ebml.version, ebml.doctype, ebml.doctype_version);

    }

    for (i = 0; i < FF_ARRAY_ELEMS(matroska_doctypes); i++)

        if (!strcmp(ebml.doctype, matroska_doctypes[i]))

            break;

    if (i >= FF_ARRAY_ELEMS(matroska_doctypes)) {

        av_log(s, AV_LOG_WARNING, "Unknown EBML doctype '%s'\n", ebml.doctype);

    }

    ebml_free(ebml_syntax, &ebml);

    /* The next thing is a segment. */

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

    res = ebml_parse(matroska, matroska_segments, matroska);

    // try resyncing until we find a EBML_STOP type element.

    while (res != 1) {

        res = matroska_resync(matroska, pos);

        if (res < 0)

            return res;

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

        res = ebml_parse(matroska, matroska_segment, matroska);

    }

    matroska_execute_seekhead(matroska);

    if (!matroska->time_scale)

        matroska->time_scale = 1000000;

    if (matroska->duration)

        matroska->ctx->duration = matroska->duration * matroska->time_scale

                                  * 1000 / AV_TIME_BASE;

    av_dict_set(&s->metadata, "title", matroska->title, 0);

    if (matroska->date_utc.size == 8)

        matroska_metadata_creation_time(&s->metadata, AV_RB64(matroska->date_utc.data));

    tracks = matroska->tracks.elem;

    for (i=0; i < matroska->tracks.nb_elem; i++) {

        MatroskaTrack *track = &tracks[i];

        enum CodecID codec_id = CODEC_ID_NONE;

        EbmlList *encodings_list = &track->encodings;

        MatroskaTrackEncoding *encodings = encodings_list->elem;

        uint8_t *extradata = NULL;

        int extradata_size = 0;

        int extradata_offset = 0;

        uint32_t fourcc = 0;

        AVIOContext b;

        /* Apply some sanity checks. */

        if (track->type != MATROSKA_TRACK_TYPE_VIDEO &&

            track->type != MATROSKA_TRACK_TYPE_AUDIO &&

            track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {

            av_log(matroska->ctx, AV_LOG_INFO,

                   "Unknown or unsupported track type %"PRIu64"\n",

                   track->type);

            continue;

        }

        if (track->codec_id == NULL)

            continue;

        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {

            if (!track->default_duration)

                track->default_duration = 1000000000/track->video.frame_rate;

            if (!track->video.display_width)

                track->video.display_width = track->video.pixel_width;

            if (!track->video.display_height)

                track->video.display_height = track->video.pixel_height;

            if (track->video.color_space.size == 4)

                fourcc = AV_RL32(track->video.color_space.data);

        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {

            if (!track->audio.out_samplerate)

                track->audio.out_samplerate = track->audio.samplerate;

        }

        if (encodings_list->nb_elem > 1) {

            av_log(matroska->ctx, AV_LOG_ERROR,

                   "Multiple combined encodings not supported");

        } else if (encodings_list->nb_elem == 1) {

            if (encodings[0].type ||

                (encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP &&

#if CONFIG_ZLIB

                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_ZLIB &&

#endif

#if CONFIG_BZLIB

                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_BZLIB &&

#endif

                 encodings[0].compression.algo != MATROSKA_TRACK_ENCODING_COMP_LZO)) {

                encodings[0].scope = 0;

                av_log(matroska->ctx, AV_LOG_ERROR,

                       "Unsupported encoding type");

            } else if (track->codec_priv.size && encodings[0].scope&2) {

                uint8_t *codec_priv = track->codec_priv.data;

                int offset = matroska_decode_buffer(&track->codec_priv.data,

                                                    &track->codec_priv.size,

                                                    track);

                if (offset < 0) {

                    track->codec_priv.data = NULL;

                    track->codec_priv.size = 0;

                    av_log(matroska->ctx, AV_LOG_ERROR,

                           "Failed to decode codec private data\n");

                } else if (offset > 0) {

                    track->codec_priv.data = av_malloc(track->codec_priv.size + offset);

                    memcpy(track->codec_priv.data,

                           encodings[0].compression.settings.data, offset);

                    memcpy(track->codec_priv.data+offset, codec_priv,

                           track->codec_priv.size);

                    track->codec_priv.size += offset;

                }

                if (codec_priv != track->codec_priv.data)

                    av_free(codec_priv);

            }

        }

        for(j=0; ff_mkv_codec_tags[j].id != CODEC_ID_NONE; j++){

            if(!strncmp(ff_mkv_codec_tags[j].str, track->codec_id,

                        strlen(ff_mkv_codec_tags[j].str))){

                codec_id= ff_mkv_codec_tags[j].id;

                break;

            }

        }

        st = track->stream = avformat_new_stream(s, NULL);

        if (st == NULL)

            return AVERROR(ENOMEM);

        if (!strcmp(track->codec_id, "V_MS/VFW/FOURCC")

            && track->codec_priv.size >= 40

            && track->codec_priv.data != NULL) {

            track->ms_compat = 1;

            fourcc = AV_RL32(track->codec_priv.data + 16);

            codec_id = ff_codec_get_id(ff_codec_bmp_tags, fourcc);

            extradata_offset = 40;

        } else if (!strcmp(track->codec_id, "A_MS/ACM")

                   && track->codec_priv.size >= 14

                   && track->codec_priv.data != NULL) {

            int ret;

            ffio_init_context(&b, track->codec_priv.data, track->codec_priv.size,

                          AVIO_FLAG_READ, NULL, NULL, NULL, NULL);

            ret = ff_get_wav_header(&b, st->codec, track->codec_priv.size);

            if (ret < 0)

                return ret;

            codec_id = st->codec->codec_id;

            extradata_offset = FFMIN(track->codec_priv.size, 18);

        } else if (!strcmp(track->codec_id, "V_QUICKTIME")

                   && (track->codec_priv.size >= 86)

                   && (track->codec_priv.data != NULL)) {

            fourcc = AV_RL32(track->codec_priv.data);

            codec_id = ff_codec_get_id(ff_codec_movvideo_tags, fourcc);

        } else if (codec_id == CODEC_ID_PCM_S16BE) {

            switch (track->audio.bitdepth) {

            case  8:  codec_id = CODEC_ID_PCM_U8;     break;

            case 24:  codec_id = CODEC_ID_PCM_S24BE;  break;

            case 32:  codec_id = CODEC_ID_PCM_S32BE;  break;

            }

        } else if (codec_id == CODEC_ID_PCM_S16LE) {

            switch (track->audio.bitdepth) {

            case  8:  codec_id = CODEC_ID_PCM_U8;     break;

            case 24:  codec_id = CODEC_ID_PCM_S24LE;  break;

            case 32:  codec_id = CODEC_ID_PCM_S32LE;  break;

            }

        } else if (codec_id==CODEC_ID_PCM_F32LE && track->audio.bitdepth==64) {

            codec_id = CODEC_ID_PCM_F64LE;

        } else if (codec_id == CODEC_ID_AAC && !track->codec_priv.size) {

            int profile = matroska_aac_profile(track->codec_id);

            int sri = matroska_aac_sri(track->audio.samplerate);

            extradata = av_mallocz(5 + FF_INPUT_BUFFER_PADDING_SIZE);

            if (extradata == NULL)

                return AVERROR(ENOMEM);

            extradata[0] = (profile << 3) | ((sri&0x0E) >> 1);

            extradata[1] = ((sri&0x01) << 7) | (track->audio.channels<<3);

            if (strstr(track->codec_id, "SBR")) {

                sri = matroska_aac_sri(track->audio.out_samplerate);

                extradata[2] = 0x56;

                extradata[3] = 0xE5;

                extradata[4] = 0x80 | (sri<<3);

                extradata_size = 5;

            } else

                extradata_size = 2;

        } else if (codec_id == CODEC_ID_TTA) {

            extradata_size = 30;

            extradata = av_mallocz(extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

            if (extradata == NULL)

                return AVERROR(ENOMEM);

            ffio_init_context(&b, extradata, extradata_size, 1,

                          NULL, NULL, NULL, NULL);

            avio_write(&b, "TTA1", 4);

            avio_wl16(&b, 1);

            avio_wl16(&b, track->audio.channels);

            avio_wl16(&b, track->audio.bitdepth);

            avio_wl32(&b, track->audio.out_samplerate);

            avio_wl32(&b, matroska->ctx->duration * track->audio.out_samplerate);

        } else if (codec_id == CODEC_ID_RV10 || codec_id == CODEC_ID_RV20 ||

                   codec_id == CODEC_ID_RV30 || codec_id == CODEC_ID_RV40) {

            extradata_offset = 26;

        } else if (codec_id == CODEC_ID_RA_144) {

            track->audio.out_samplerate = 8000;

            track->audio.channels = 1;

        } else if (codec_id == CODEC_ID_RA_288 || codec_id == CODEC_ID_COOK ||

                   codec_id == CODEC_ID_ATRAC3 || codec_id == CODEC_ID_SIPR) {

            int flavor;

            ffio_init_context(&b, track->codec_priv.data,track->codec_priv.size,

                          0, NULL, NULL, NULL, NULL);

            avio_skip(&b, 22);

            flavor                       = avio_rb16(&b);

            track->audio.coded_framesize = avio_rb32(&b);

            avio_skip(&b, 12);

            track->audio.sub_packet_h    = avio_rb16(&b);

            track->audio.frame_size      = avio_rb16(&b);

            track->audio.sub_packet_size = avio_rb16(&b);

            track->audio.buf = av_malloc(track->audio.frame_size * track->audio.sub_packet_h);

            if (codec_id == CODEC_ID_RA_288) {

                st->codec->block_align = track->audio.coded_framesize;

                track->codec_priv.size = 0;

            } else {

                if (codec_id == CODEC_ID_SIPR && flavor < 4) {

                    const int sipr_bit_rate[4] = { 6504, 8496, 5000, 16000 };

                    track->audio.sub_packet_size = ff_sipr_subpk_size[flavor];

                    st->codec->bit_rate = sipr_bit_rate[flavor];

                }

                st->codec->block_align = track->audio.sub_packet_size;

                extradata_offset = 78;

            }

        }

        track->codec_priv.size -= extradata_offset;

        if (codec_id == CODEC_ID_NONE)

            av_log(matroska->ctx, AV_LOG_INFO,

                   "Unknown/unsupported CodecID %s.\n", track->codec_id);

        if (track->time_scale < 0.01)

            track->time_scale = 1.0;

        avpriv_set_pts_info(st, 64, matroska->time_scale*track->time_scale, 1000*1000*1000); /* 64 bit pts in ns */

        st->codec->codec_id = codec_id;

        st->start_time = 0;

        if (strcmp(track->language, "und"))

            av_dict_set(&st->metadata, "language", track->language, 0);

        av_dict_set(&st->metadata, "title", track->name, 0);

        if (track->flag_default)

            st->disposition |= AV_DISPOSITION_DEFAULT;

        if (track->flag_forced)

            st->disposition |= AV_DISPOSITION_FORCED;

        if (!st->codec->extradata) {

            if(extradata){

                st->codec->extradata = extradata;

                st->codec->extradata_size = extradata_size;

            } else if(track->codec_priv.data && track->codec_priv.size > 0){

                st->codec->extradata = av_mallocz(track->codec_priv.size +

                                                  FF_INPUT_BUFFER_PADDING_SIZE);

                if(st->codec->extradata == NULL)

                    return AVERROR(ENOMEM);

                st->codec->extradata_size = track->codec_priv.size;

                memcpy(st->codec->extradata,

                       track->codec_priv.data + extradata_offset,

                       track->codec_priv.size);

            }

        }

        if (track->type == MATROSKA_TRACK_TYPE_VIDEO) {

            MatroskaTrackPlane *planes = track->operation.combine_planes.elem;

            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            st->codec->codec_tag  = fourcc;

            st->codec->width  = track->video.pixel_width;

            st->codec->height = track->video.pixel_height;

            av_reduce(&st->sample_aspect_ratio.num,

                      &st->sample_aspect_ratio.den,

                      st->codec->height * track->video.display_width,

                      st->codec-> width * track->video.display_height,

                      255);

            st->need_parsing = AVSTREAM_PARSE_HEADERS;

            if (track->default_duration)

                st->avg_frame_rate = av_d2q(1000000000.0/track->default_duration, INT_MAX);

            /* export stereo mode flag as metadata tag */

            if (track->video.stereo_mode && track->video.stereo_mode < MATROSKA_VIDEO_STEREO_MODE_COUNT)

                av_dict_set(&st->metadata, "stereo_mode", matroska_video_stereo_mode[track->video.stereo_mode], 0);

            /* if we have virtual track, mark the real tracks */

            for (j=0; j < track->operation.combine_planes.nb_elem; j++) {

                char buf[32];

                if (planes[j].type >= MATROSKA_VIDEO_STEREO_PLANE_COUNT)

                    continue;

                snprintf(buf, sizeof(buf), "%s_%d",

                         matroska_video_stereo_plane[planes[j].type], i);

                for (k=0; k < matroska->tracks.nb_elem; k++)

                    if (planes[j].uid == tracks[k].uid) {

                        av_dict_set(&s->streams[k]->metadata,

                                    "stereo_mode", buf, 0);

                        break;

                    }

            }

        } else if (track->type == MATROSKA_TRACK_TYPE_AUDIO) {

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            st->codec->sample_rate = track->audio.out_samplerate;

            st->codec->channels = track->audio.channels;

            if (st->codec->codec_id != CODEC_ID_AAC)

            st->need_parsing = AVSTREAM_PARSE_HEADERS;

        } else if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE) {

            st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

        }

    }

    attachements = attachements_list->elem;

    for (j=0; j<attachements_list->nb_elem; j++) {

        if (!(attachements[j].filename && attachements[j].mime &&

              attachements[j].bin.data && attachements[j].bin.size > 0)) {

            av_log(matroska->ctx, AV_LOG_ERROR, "incomplete attachment\n");

        } else {

            AVStream *st = avformat_new_stream(s, NULL);

            if (st == NULL)

                break;

            av_dict_set(&st->metadata, "filename",attachements[j].filename, 0);

            av_dict_set(&st->metadata, "mimetype", attachements[j].mime, 0);

            st->codec->codec_id = CODEC_ID_NONE;

            st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;

            st->codec->extradata  = av_malloc(attachements[j].bin.size + FF_INPUT_BUFFER_PADDING_SIZE);

            if(st->codec->extradata == NULL)

                break;

            st->codec->extradata_size = attachements[j].bin.size;

            memcpy(st->codec->extradata, attachements[j].bin.data, attachements[j].bin.size);

            for (i=0; ff_mkv_mime_tags[i].id != CODEC_ID_NONE; i++) {

                if (!strncmp(ff_mkv_mime_tags[i].str, attachements[j].mime,

                             strlen(ff_mkv_mime_tags[i].str))) {

                    st->codec->codec_id = ff_mkv_mime_tags[i].id;

                    break;

                }

            }

            attachements[j].stream = st;

        }

    }

    chapters = chapters_list->elem;

    for (i=0; i<chapters_list->nb_elem; i++)

        if (chapters[i].start != AV_NOPTS_VALUE && chapters[i].uid

            && (max_start==0 || chapters[i].start > max_start)) {

            chapters[i].chapter =

            avpriv_new_chapter(s, chapters[i].uid, (AVRational){1, 1000000000},

                           chapters[i].start, chapters[i].end,

                           chapters[i].title);

            av_dict_set(&chapters[i].chapter->metadata,

                             "title", chapters[i].title, 0);

            max_start = chapters[i].start;

        }

    matroska_add_index_entries(matroska);

    matroska_convert_tags(s);

    return 0;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *picref)

{

    AVFilterContext *ctx = inlink->dst;

    SignatureContext *sic = ctx->priv;

    StreamContext *sc = &(sic->streamcontexts[FF_INLINK_IDX(inlink)]);

    FineSignature* fs;

    static const uint8_t pot3[5] = { 3*3*3*3, 3*3*3, 3*3, 3, 1 };

    /* indexes of words : 210,217,219,274,334  44,175,233,270,273  57,70,103,237,269  100,285,295,337,354  101,102,111,275,296

    s2usw = sorted to unsorted wordvec: 44 is at index 5, 57 at index 10...

    */

    static const unsigned int wordvec[25] = {44,57,70,100,101,102,103,111,175,210,217,219,233,237,269,270,273,274,275,285,295,296,334,337,354};

    static const uint8_t      s2usw[25]   = { 5,10,11, 15, 20, 21, 12, 22,  6,  0,  1,  2,  7, 13, 14,  8,  9,  3, 23, 16, 17, 24,  4, 18, 19};

    uint8_t wordt2b[5] = { 0, 0, 0, 0, 0 }; /* word ternary to binary */

    uint64_t intpic[32][32];

    uint64_t rowcount;

    uint8_t *p = picref->data[0];

    int inti, intj;

    int *intjlut;

    uint64_t conflist[DIFFELEM_SIZE];

    int f = 0, g = 0, w = 0;

    int32_t dh1 = 1, dh2 = 1, dw1 = 1, dw2 = 1, a, b;

    int64_t denom;

    int i, j, k, ternary;

    uint64_t blocksum;

    int blocksize;

    int64_t th; /* threshold */

    int64_t sum;

    int64_t precfactor = (sc->divide) ? 65536 : BLOCK_LCM;

    /* initialize fs */

    if (sc->curfinesig) {

        fs = av_mallocz(sizeof(FineSignature));

        if (!fs)

            return AVERROR(ENOMEM);

        sc->curfinesig->next = fs;

        fs->prev = sc->curfinesig;

        sc->curfinesig = fs;

    } else {

        fs = sc->curfinesig = sc->finesiglist;

        sc->curcoarsesig1->first = fs;

    }

    fs->pts = picref->pts;

    fs->index = sc->lastindex++;

    memset(intpic, 0, sizeof(uint64_t)*32*32);

    intjlut = av_malloc_array(inlink->w, sizeof(int));

    if (!intjlut)

        return AVERROR(ENOMEM);

    for (i = 0; i < inlink->w; i++) {

        intjlut[i] = (i*32)/inlink->w;

    }

    for (i = 0; i < inlink->h; i++) {

        inti = (i*32)/inlink->h;

        for (j = 0; j < inlink->w; j++) {

            intj = intjlut[j];

            intpic[inti][intj] += p[j];

        }

        p += picref->linesize[0];

    }

    av_freep(&intjlut);

    /* The following calculates a summed area table (intpic) and brings the numbers

     * in intpic to the same denominator.

     * So you only have to handle the numinator in the following sections.

     */

    dh1 = inlink->h / 32;

    if (inlink->h % 32)

        dh2 = dh1 + 1;

    dw1 = inlink->w / 32;

    if (inlink->w % 32)

        dw2 = dw1 + 1;

    denom = (sc->divide) ? dh1 * dh2 * dw1 * dw2 : 1;

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

        rowcount = 0;

        a = 1;

        if (dh2 > 1) {

            a = ((inlink->h*(i+1))%32 == 0) ? (inlink->h*(i+1))/32 - 1 : (inlink->h*(i+1))/32;

            a -= ((inlink->h*i)%32 == 0) ? (inlink->h*i)/32 - 1 : (inlink->h*i)/32;

            a = (a == dh1)? dh2 : dh1;

        }

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

            b = 1;

            if (dw2 > 1) {

                b = ((inlink->w*(j+1))%32 == 0) ? (inlink->w*(j+1))/32 - 1 : (inlink->w*(j+1))/32;

                b -= ((inlink->w*j)%32 == 0) ? (inlink->w*j)/32 - 1 : (inlink->w*j)/32;

                b = (b == dw1)? dw2 : dw1;

            }

            rowcount += intpic[i][j] * a * b * precfactor / denom;

            if (i > 0) {

                intpic[i][j] = intpic[i-1][j] + rowcount;

            } else {

                intpic[i][j] = rowcount;

            }

        }

    }

    denom = (sc->divide) ? 1 : dh1 * dh2 * dw1 * dw2;

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

        const ElemCat* elemcat = elements[i];

        int64_t* elemsignature;

        uint64_t* sortsignature;

        elemsignature = av_malloc_array(elemcat->elem_count, sizeof(int64_t));

        if (!elemsignature)

            return AVERROR(ENOMEM);

        sortsignature = av_malloc_array(elemcat->elem_count, sizeof(int64_t));

        if (!sortsignature)

            return AVERROR(ENOMEM);

        for (j = 0; j < elemcat->elem_count; j++) {

            blocksum = 0;

            blocksize = 0;

            for (k = 0; k < elemcat->left_count; k++) {

                blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);

                blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);

            }

            sum = blocksum / blocksize;

            if (elemcat->av_elem) {

                sum -= 128 * precfactor * denom;

            } else {

                blocksum = 0;

                blocksize = 0;

                for (; k < elemcat->block_count; k++) {

                    blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);

                    blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);

                }

                sum -= blocksum / blocksize;

                conflist[g++] = FFABS(sum * 8 / (precfactor * denom));

            }

            elemsignature[j] = sum;

            sortsignature[j] = FFABS(sum);

        }

        /* get threshold */

        qsort(sortsignature, elemcat->elem_count, sizeof(uint64_t), (void*) cmp);

        th = sortsignature[(int) (elemcat->elem_count*0.333)];

        /* ternarize */

        for (j = 0; j < elemcat->elem_count; j++) {

            if (elemsignature[j] < -th) {

                ternary = 0;

            } else if (elemsignature[j] <= th) {

                ternary = 1;

            } else {

                ternary = 2;

            }

            fs->framesig[f/5] += ternary * pot3[f%5];

            if (f == wordvec[w]) {

                fs->words[s2usw[w]/5] += ternary * pot3[wordt2b[s2usw[w]/5]++];

                if (w < 24)

                    w++;

            }

            f++;

        }

        av_freep(&elemsignature);

        av_freep(&sortsignature);

    }

    /* confidence */

    qsort(conflist, DIFFELEM_SIZE, sizeof(uint64_t), (void*) cmp);

    fs->confidence = FFMIN(conflist[DIFFELEM_SIZE/2], 255);

    /* coarsesignature */

    if (sc->coarsecount == 0) {

        if (sc->curcoarsesig2) {

            sc->curcoarsesig1 = av_mallocz(sizeof(CoarseSignature));

            if (!sc->curcoarsesig1)

                return AVERROR(ENOMEM);

            sc->curcoarsesig1->first = fs;

            sc->curcoarsesig2->next = sc->curcoarsesig1;

            sc->coarseend = sc->curcoarsesig1;

        }

    }

    if (sc->coarsecount == 45) {

        sc->midcoarse = 1;

        sc->curcoarsesig2 = av_mallocz(sizeof(CoarseSignature));

        if (!sc->curcoarsesig2)

            return AVERROR(ENOMEM);

        sc->curcoarsesig2->first = fs;

        sc->curcoarsesig1->next = sc->curcoarsesig2;

        sc->coarseend = sc->curcoarsesig2;

    }

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

        set_bit(sc->curcoarsesig1->data[i], fs->words[i]);

    }

    /* assuming the actual frame is the last */

    sc->curcoarsesig1->last = fs;

    if (sc->midcoarse) {

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

            set_bit(sc->curcoarsesig2->data[i], fs->words[i]);

        }

        sc->curcoarsesig2->last = fs;

    }

    sc->coarsecount = (sc->coarsecount+1)%90;

    /* debug printing finesignature */

    if (av_log_get_level() == AV_LOG_DEBUG) {

        av_log(ctx, AV_LOG_DEBUG, "input %d, confidence: %d\n", FF_INLINK_IDX(inlink), fs->confidence);

        av_log(ctx, AV_LOG_DEBUG, "words:");

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

            av_log(ctx, AV_LOG_DEBUG, " %d:", fs->words[i] );

            av_log(ctx, AV_LOG_DEBUG, " %d", fs->words[i] / pot3[0] );

            for (j = 1; j < 5; j++)

                av_log(ctx, AV_LOG_DEBUG, ",%d", fs->words[i] % pot3[j-1] / pot3[j] );

            av_log(ctx, AV_LOG_DEBUG, ";");

        }

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

        av_log(ctx, AV_LOG_DEBUG, "framesignature:");

        for (i = 0; i < SIGELEM_SIZE/5; i++) {

            av_log(ctx, AV_LOG_DEBUG, " %d", fs->framesig[i] / pot3[0] );

            for (j = 1; j < 5; j++)

                av_log(ctx, AV_LOG_DEBUG, ",%d", fs->framesig[i] % pot3[j-1] / pot3[j] );

        }

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

    }

    if (FF_INLINK_IDX(inlink) == 0)

        return ff_filter_frame(inlink->dst->outputs[0], picref);

    return 1;

}


static void test_dma_fragmented(void)

{

    AHCIQState *ahci;

    AHCICommand *cmd;

    uint8_t px;

    size_t bufsize = 4096;

    unsigned char *tx = g_malloc(bufsize);

    unsigned char *rx = g_malloc0(bufsize);

    uint64_t ptr;

    ahci = ahci_boot_and_enable(NULL);

    px = ahci_port_select(ahci);

    ahci_port_clear(ahci, px);

    /* create pattern */

    generate_pattern(tx, bufsize, AHCI_SECTOR_SIZE);

    /* Create a DMA buffer in guest memory, and write our pattern to it. */

    ptr = guest_alloc(ahci->parent->alloc, bufsize);

    g_assert(ptr);

    bufwrite(ptr, tx, bufsize);

    cmd = ahci_command_create(CMD_WRITE_DMA);

    ahci_command_adjust(cmd, 0, ptr, bufsize, 32);

    ahci_command_commit(ahci, cmd, px);

    ahci_command_issue(ahci, cmd);

    ahci_command_verify(ahci, cmd);

    g_free(cmd);

    cmd = ahci_command_create(CMD_READ_DMA);

    ahci_command_adjust(cmd, 0, ptr, bufsize, 32);

    ahci_command_commit(ahci, cmd, px);

    ahci_command_issue(ahci, cmd);

    ahci_command_verify(ahci, cmd);

    g_free(cmd);

    /* Read back the guest's receive buffer into local memory */

    bufread(ptr, rx, bufsize);

    guest_free(ahci->parent->alloc, ptr);

    g_assert_cmphex(memcmp(tx, rx, bufsize), ==, 0);

    ahci_shutdown(ahci);

    g_free(rx);

    g_free(tx);

}


static uint32_t pcihotplug_read(void *opaque, uint32_t addr)

{

    uint32_t val = 0;

    struct pci_status *g = opaque;

    switch (addr) {

        case PCI_BASE:

            val = g->up;

            break;

        case PCI_BASE + 4:

            val = g->down;

            break;

        default:

            break;

    }

    PIIX4_DPRINTF("pcihotplug read %x == %x\n", addr, val);

    return val;

}


static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    int64_t size;

    AVIOContext *pb  = s->pb;

    WAVContext    *wav = s->priv_data;

    AVStream *st;

    uint8_t guid[16];

    avio_read(pb, guid, 16);

    if (memcmp(guid, guid_riff, 16))

        return -1;

    if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */

        return -1;

    avio_read(pb, guid, 16);

    if (memcmp(guid, guid_wave, 16)) {

        av_log(s, AV_LOG_ERROR, "could not find wave guid\n");

        return -1;

    }

    size = find_guid(pb, guid_fmt);

    if (size < 0) {

        av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");

        return -1;

    }

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    /* subtract chunk header size - normal wav file doesn't count it */

    ff_get_wav_header(pb, st->codec, size - 24);

    avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);

    st->need_parsing = AVSTREAM_PARSE_FULL;

    av_set_pts_info(st, 64, 1, st->codec->sample_rate);

    size = find_guid(pb, guid_data);

    if (size < 0) {

        av_log(s, AV_LOG_ERROR, "could not find data guid\n");

        return -1;

    }

    wav->data_end = avio_tell(pb) + size - 24;

    wav->w64      = 1;

    return 0;

}


void rgb15tobgr15(const uint8_t *src, uint8_t *dst, long src_size)

{

	long i;

	long num_pixels = src_size >> 1;

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

	{

	    unsigned b,g,r;

	    register uint16_t rgb;

	    rgb = src[2*i];

	    r = rgb&0x1F;

	    g = (rgb&0x3E0)>>5;

	    b = (rgb&0x7C00)>>10;

	    dst[2*i] = (b&0x1F) | ((g&0x1F)<<5) | ((r&0x1F)<<10);

	}

}


int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h)

{

    VncRectEntry *entry = g_malloc0(sizeof(VncRectEntry));

    entry->rect.x = x;

    entry->rect.y = y;

    entry->rect.w = w;

    entry->rect.h = h;

    vnc_lock_queue(queue);

    QLIST_INSERT_HEAD(&job->rectangles, entry, next);

    vnc_unlock_queue(queue);

    return 1;

}


static void uhci_async_complete_packet(USBPacket * packet, void *opaque)

{

    UHCIState *s = opaque;

    UHCI_QH qh;

    UHCI_TD td;

    uint32_t link;

    uint32_t old_td_ctrl;

    uint32_t val;

    uint32_t frame_addr;

    int ret;

    /* Handle async isochronous packet completion */

    frame_addr = s->async_frame_addr;

    if (frame_addr) {

        cpu_physical_memory_read(frame_addr, (uint8_t *)&link, 4);

        le32_to_cpus(&link);

        cpu_physical_memory_read(link & ~0xf, (uint8_t *)&td, sizeof(td));

        le32_to_cpus(&td.link);

        le32_to_cpus(&td.ctrl);

        le32_to_cpus(&td.token);

        le32_to_cpus(&td.buffer);

        old_td_ctrl = td.ctrl;

        ret = uhci_handle_td(s, &td, &s->pending_int_mask, 1);

        /* update the status bits of the TD */

        if (old_td_ctrl != td.ctrl) {

            val = cpu_to_le32(td.ctrl);

            cpu_physical_memory_write((link & ~0xf) + 4,

                                      (const uint8_t *)&val,

                                      sizeof(val));

        }

        if (ret == 2) {

            s->async_frame_addr = frame_addr;

        } else if (ret == 0) {

            /* update qh element link */

            val = cpu_to_le32(td.link);

            cpu_physical_memory_write(frame_addr,

                                      (const uint8_t *)&val,

                                      sizeof(val));

        }

        return;

    }

    link = s->async_qh;

    if (!link) {

        /* This should never happen. It means a TD somehow got removed

           without cancelling the associated async IO request.  */

        return;

    }

    cpu_physical_memory_read(link & ~0xf, (uint8_t *)&qh, sizeof(qh));

    le32_to_cpus(&qh.link);

    le32_to_cpus(&qh.el_link);

    /* Re-process the queue containing the async packet.  */

    while (1) {

        cpu_physical_memory_read(qh.el_link & ~0xf,

                                 (uint8_t *)&td, sizeof(td));

        le32_to_cpus(&td.link);

        le32_to_cpus(&td.ctrl);

        le32_to_cpus(&td.token);

        le32_to_cpus(&td.buffer);

        old_td_ctrl = td.ctrl;

        ret = uhci_handle_td(s, &td, &s->pending_int_mask, 1);

        /* update the status bits of the TD */

        if (old_td_ctrl != td.ctrl) {

            val = cpu_to_le32(td.ctrl);

            cpu_physical_memory_write((qh.el_link & ~0xf) + 4,

                                      (const uint8_t *)&val,

                                      sizeof(val));

        }

        if (ret < 0)

            break; /* interrupted frame */

        if (ret == 2) {

            s->async_qh = link;

            break;

        } else if (ret == 0) {

            /* update qh element link */

            qh.el_link = td.link;

            val = cpu_to_le32(qh.el_link);

            cpu_physical_memory_write((link & ~0xf) + 4,

                                      (const uint8_t *)&val,

                                      sizeof(val));

            if (!(qh.el_link & 4))

                break;

        }

        break;

    }

}


static void tracked_request_end(BdrvTrackedRequest *req)

{

    if (req->serialising) {

        req->bs->serialising_in_flight--;

    }

    QLIST_REMOVE(req, list);

    qemu_co_queue_restart_all(&req->wait_queue);

}


static int adpcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    ADPCMDecodeContext *c = avctx->priv_data;

    ADPCMChannelStatus *cs;

    int n, m, channel, i;

    int block_predictor[2];

    short *samples;

    short *samples_end;

    const uint8_t *src;

    int st; /* stereo */

    /* DK3 ADPCM accounting variables */

    unsigned char last_byte = 0;

    unsigned char nibble;

    int decode_top_nibble_next = 0;

    int diff_channel;

    /* EA ADPCM state variables */

    uint32_t samples_in_chunk;

    int32_t previous_left_sample, previous_right_sample;

    int32_t current_left_sample, current_right_sample;

    int32_t next_left_sample, next_right_sample;

    int32_t coeff1l, coeff2l, coeff1r, coeff2r;

    uint8_t shift_left, shift_right;

    int count1, count2;

    int coeff[2][2], shift[2];//used in EA MAXIS ADPCM

    if (!buf_size)

        return 0;

    //should protect all 4bit ADPCM variants

    //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels

    //

    if(*data_size/4 < buf_size + 8)

        return -1;

    samples = data;

    samples_end= samples + *data_size/2;

    *data_size= 0;

    src = buf;

    st = avctx->channels == 2 ? 1 : 0;

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT:

        n = buf_size - 2*avctx->channels;

        for (channel = 0; channel < avctx->channels; channel++) {

            int16_t predictor;

            int step_index;

            cs = &(c->status[channel]);

            /* (pppppp) (piiiiiii) */

            /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */

            predictor = AV_RB16(src);

            step_index = predictor & 0x7F;

            predictor &= 0xFF80;

            src += 2;

            if (cs->step_index == step_index) {

                int diff = (int)predictor - cs->predictor;

                if (diff < 0)

                    diff = - diff;

                if (diff > 0x7f)

                    goto update;

            } else {

            update:

                cs->step_index = step_index;

                cs->predictor = predictor;

            }

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            samples = (short*)data + channel;

            for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */

                *samples = adpcm_ima_qt_expand_nibble(cs, src[0] & 0x0F, 3);

                samples += avctx->channels;

                *samples = adpcm_ima_qt_expand_nibble(cs, src[0] >> 4  , 3);

                samples += avctx->channels;

                src ++;

            }

        }

        if (st)

            samples--;

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

//        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;

        for(i=0; i<avctx->channels; i++){

            cs = &(c->status[i]);

            cs->predictor = *samples++ = (int16_t)bytestream_get_le16(&src);

            cs->step_index = *src++;

            if (cs->step_index > 88){

                av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);

                cs->step_index = 88;

            }

            if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */

        }

        while(src < buf + buf_size){

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

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);

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

                    *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);

                src++;

            }

            src += 4*st;

        }

        break;

    case CODEC_ID_ADPCM_4XM:

        cs = &(c->status[0]);

        c->status[0].predictor= (int16_t)bytestream_get_le16(&src);

        if(st){

            c->status[1].predictor= (int16_t)bytestream_get_le16(&src);

        }

        c->status[0].step_index= (int16_t)bytestream_get_le16(&src);

        if(st){

            c->status[1].step_index= (int16_t)bytestream_get_le16(&src);

        }

        if (cs->step_index < 0) cs->step_index = 0;

        if (cs->step_index > 88) cs->step_index = 88;

        m= (buf_size - (src - buf))>>st;

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

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);

            if (st)

                *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);

        }

        src += m<<st;

        break;

    case CODEC_ID_ADPCM_MS:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        n = buf_size - 7 * avctx->channels;

        if (n < 0)

            return -1;

        block_predictor[0] = av_clip(*src++, 0, 6);

        block_predictor[1] = 0;

        if (st)

            block_predictor[1] = av_clip(*src++, 0, 6);

        c->status[0].idelta = (int16_t)bytestream_get_le16(&src);

        if (st){

            c->status[1].idelta = (int16_t)bytestream_get_le16(&src);

        }

        c->status[0].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor[0]];

        c->status[0].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor[0]];

        c->status[1].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor[1]];

        c->status[1].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor[1]];

        c->status[0].sample1 = bytestream_get_le16(&src);

        if (st) c->status[1].sample1 = bytestream_get_le16(&src);

        c->status[0].sample2 = bytestream_get_le16(&src);

        if (st) c->status[1].sample2 = bytestream_get_le16(&src);

        *samples++ = c->status[0].sample2;

        if (st) *samples++ = c->status[1].sample2;

        *samples++ = c->status[0].sample1;

        if (st) *samples++ = c->status[1].sample1;

        for(;n>0;n--) {

            *samples++ = adpcm_ms_expand_nibble(&c->status[0 ], src[0] >> 4  );

            *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);

            src ++;

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        c->status[0].predictor  = (int16_t)bytestream_get_le16(&src);

        c->status[0].step_index = *src++;

        src++;

        *samples++ = c->status[0].predictor;

        if (st) {

            c->status[1].predictor  = (int16_t)bytestream_get_le16(&src);

            c->status[1].step_index = *src++;

            src++;

            *samples++ = c->status[1].predictor;

        }

        while (src < buf + buf_size) {

            uint8_t v = *src++;

            *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v >> 4  , 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_DK3:

        if (avctx->block_align != 0 && buf_size > avctx->block_align)

            buf_size = avctx->block_align;

        if(buf_size + 16 > (samples_end - samples)*3/8)

            return -1;

        c->status[0].predictor  = (int16_t)AV_RL16(src + 10);

        c->status[1].predictor  = (int16_t)AV_RL16(src + 12);

        c->status[0].step_index = src[14];

        c->status[1].step_index = src[15];

        /* sign extend the predictors */

        src += 16;

        diff_channel = c->status[1].predictor;

        /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when

         * the buffer is consumed */

        while (1) {

            /* for this algorithm, c->status[0] is the sum channel and

             * c->status[1] is the diff channel */

            /* process the first predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the diff channel predictor */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[1], nibble, 3);

            /* process the first pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

            /* process the second predictor of the sum channel */

            DK3_GET_NEXT_NIBBLE();

            adpcm_ima_expand_nibble(&c->status[0], nibble, 3);

            /* process the second pair of stereo PCM samples */

            diff_channel = (diff_channel + c->status[1].predictor) / 2;

            *samples++ = c->status[0].predictor + c->status[1].predictor;

            *samples++ = c->status[0].predictor - c->status[1].predictor;

        }

        break;

    case CODEC_ID_ADPCM_IMA_ISS:

        c->status[0].predictor  = (int16_t)AV_RL16(src + 0);

        c->status[0].step_index = src[2];

        src += 4;

        if(st) {

            c->status[1].predictor  = (int16_t)AV_RL16(src + 0);

            c->status[1].step_index = src[2];

            src += 4;

        }

        while (src < buf + buf_size) {

            uint8_t v1, v2;

            uint8_t v = *src++;

            /* nibbles are swapped for mono */

            if (st) {

                v1 = v >> 4;

                v2 = v & 0x0F;

            } else {

                v2 = v >> 4;

                v1 = v & 0x0F;

            }

            *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v1, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v2, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_WS:

        while (src < buf + buf_size) {

            uint8_t v = *src++;

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],  v >> 4  , 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_XA:

        while (buf_size >= 128) {

            xa_decode(samples, src, &c->status[0], &c->status[1],

                avctx->channels);

            src += 128;

            samples += 28 * 8;

            buf_size -= 128;

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_EACS:

        samples_in_chunk = bytestream_get_le32(&src) >> (1-st);

        if (samples_in_chunk > buf_size-4-(8<<st)) {

            src += buf_size - 4;

            break;

        }

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

            c->status[i].step_index = bytestream_get_le32(&src);

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

            c->status[i].predictor  = bytestream_get_le32(&src);

        for (; samples_in_chunk; samples_in_chunk--, src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],  *src>>4,   3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st], *src&0x0F, 3);

        }

        break;

    case CODEC_ID_ADPCM_IMA_EA_SEAD:

        for (; src < buf+buf_size; src++) {

            *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[0] >> 4, 6);

            *samples++ = adpcm_ima_expand_nibble(&c->status[st],src[0]&0x0F, 6);

        }

        break;

    case CODEC_ID_ADPCM_EA:

        /* Each EA ADPCM frame has a 12-byte header followed by 30-byte pieces,

           each coding 28 stereo samples. */

        if (buf_size < 12) {

            av_log(avctx, AV_LOG_ERROR, "frame too small\n");

            return AVERROR(EINVAL);

        }

        samples_in_chunk = AV_RL32(src);

        if (samples_in_chunk / 28 > (buf_size - 12) / 30) {

            av_log(avctx, AV_LOG_ERROR, "invalid frame\n");

            return AVERROR(EINVAL);

        }

        src += 4;

        current_left_sample   = (int16_t)bytestream_get_le16(&src);

        previous_left_sample  = (int16_t)bytestream_get_le16(&src);

        current_right_sample  = (int16_t)bytestream_get_le16(&src);

        previous_right_sample = (int16_t)bytestream_get_le16(&src);

        for (count1 = 0; count1 < samples_in_chunk/28;count1++) {

            coeff1l = ea_adpcm_table[ *src >> 4       ];

            coeff2l = ea_adpcm_table[(*src >> 4  ) + 4];

            coeff1r = ea_adpcm_table[*src & 0x0F];

            coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];

            src++;

            shift_left  = (*src >> 4  ) + 8;

            shift_right = (*src & 0x0F) + 8;

            src++;

            for (count2 = 0; count2 < 28; count2++) {

                next_left_sample  = (int32_t)((*src & 0xF0) << 24) >> shift_left;

                next_right_sample = (int32_t)((*src & 0x0F) << 28) >> shift_right;

                src++;

                next_left_sample = (next_left_sample +

                    (current_left_sample * coeff1l) +

                    (previous_left_sample * coeff2l) + 0x80) >> 8;

                next_right_sample = (next_right_sample +

                    (current_right_sample * coeff1r) +

                    (previous_right_sample * coeff2r) + 0x80) >> 8;

                previous_left_sample = current_left_sample;

                current_left_sample = av_clip_int16(next_left_sample);

                previous_right_sample = current_right_sample;

                current_right_sample = av_clip_int16(next_right_sample);

                *samples++ = (unsigned short)current_left_sample;

                *samples++ = (unsigned short)current_right_sample;

            }

        }

        if (src - buf == buf_size - 2)

            src += 2; // Skip terminating 0x0000

        break;

    case CODEC_ID_ADPCM_EA_MAXIS_XA:

        for(channel = 0; channel < avctx->channels; channel++) {

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

                coeff[channel][i] = ea_adpcm_table[(*src >> 4) + 4*i];

            shift[channel] = (*src & 0x0F) + 8;

            src++;

        }

        for (count1 = 0; count1 < (buf_size - avctx->channels) / avctx->channels; count1++) {

            for(i = 4; i >= 0; i-=4) { /* Pairwise samples LL RR (st) or LL LL (mono) */

                for(channel = 0; channel < avctx->channels; channel++) {

                    int32_t sample = (int32_t)(((*(src+channel) >> i) & 0x0F) << 0x1C) >> shift[channel];

                    sample = (sample +

                             c->status[channel].sample1 * coeff[channel][0] +

                             c->status[channel].sample2 * coeff[channel][1] + 0x80) >> 8;

                    c->status[channel].sample2 = c->status[channel].sample1;

                    c->status[channel].sample1 = av_clip_int16(sample);

                    *samples++ = c->status[channel].sample1;

                }

            }

            src+=avctx->channels;

        }

        break;

    case CODEC_ID_ADPCM_EA_R1:

    case CODEC_ID_ADPCM_EA_R2:

    case CODEC_ID_ADPCM_EA_R3: {

        /* channel numbering

           2chan: 0=fl, 1=fr

           4chan: 0=fl, 1=rl, 2=fr, 3=rr

           6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */

        const int big_endian = avctx->codec->id == CODEC_ID_ADPCM_EA_R3;

        int32_t previous_sample, current_sample, next_sample;

        int32_t coeff1, coeff2;

        uint8_t shift;

        unsigned int channel;

        uint16_t *samplesC;

        const uint8_t *srcC;

        const uint8_t *src_end = buf + buf_size;

        samples_in_chunk = (big_endian ? bytestream_get_be32(&src)

                                       : bytestream_get_le32(&src)) / 28;

        if (samples_in_chunk > UINT32_MAX/(28*avctx->channels) ||

            28*samples_in_chunk*avctx->channels > samples_end-samples) {

            src += buf_size - 4;

            break;

        }

        for (channel=0; channel<avctx->channels; channel++) {

            int32_t offset = (big_endian ? bytestream_get_be32(&src)

                                         : bytestream_get_le32(&src))

                           + (avctx->channels-channel-1) * 4;

            if ((offset < 0) || (offset >= src_end - src - 4)) break;

            srcC  = src + offset;

            samplesC = samples + channel;

            if (avctx->codec->id == CODEC_ID_ADPCM_EA_R1) {

                current_sample  = (int16_t)bytestream_get_le16(&srcC);

                previous_sample = (int16_t)bytestream_get_le16(&srcC);

            } else {

                current_sample  = c->status[channel].predictor;

                previous_sample = c->status[channel].prev_sample;

            }

            for (count1=0; count1<samples_in_chunk; count1++) {

                if (*srcC == 0xEE) {  /* only seen in R2 and R3 */

                    srcC++;

                    if (srcC > src_end - 30*2) break;

                    current_sample  = (int16_t)bytestream_get_be16(&srcC);

                    previous_sample = (int16_t)bytestream_get_be16(&srcC);

                    for (count2=0; count2<28; count2++) {

                        *samplesC = (int16_t)bytestream_get_be16(&srcC);

                        samplesC += avctx->channels;

                    }

                } else {

                    coeff1 = ea_adpcm_table[ *srcC>>4     ];

                    coeff2 = ea_adpcm_table[(*srcC>>4) + 4];

                    shift = (*srcC++ & 0x0F) + 8;

                    if (srcC > src_end - 14) break;

                    for (count2=0; count2<28; count2++) {

                        if (count2 & 1)

                            next_sample = (int32_t)((*srcC++ & 0x0F) << 28) >> shift;

                        else

                            next_sample = (int32_t)((*srcC   & 0xF0) << 24) >> shift;

                        next_sample += (current_sample  * coeff1) +

                                       (previous_sample * coeff2);

                        next_sample = av_clip_int16(next_sample >> 8);

                        previous_sample = current_sample;

                        current_sample  = next_sample;

                        *samplesC = current_sample;

                        samplesC += avctx->channels;

                    }

                }

            }

            if (avctx->codec->id != CODEC_ID_ADPCM_EA_R1) {

                c->status[channel].predictor   = current_sample;

                c->status[channel].prev_sample = previous_sample;

            }

        }

        src = src + buf_size - (4 + 4*avctx->channels);

        samples += 28 * samples_in_chunk * avctx->channels;

        break;

    }

    case CODEC_ID_ADPCM_EA_XAS:

        if (samples_end-samples < 32*4*avctx->channels

            || buf_size < (4+15)*4*avctx->channels) {

            src += buf_size;

            break;

        }

        for (channel=0; channel<avctx->channels; channel++) {

            int coeff[2][4], shift[4];

            short *s2, *s = &samples[channel];

            for (n=0; n<4; n++, s+=32*avctx->channels) {

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

                    coeff[i][n] = ea_adpcm_table[(src[0]&0x0F)+4*i];

                shift[n] = (src[2]&0x0F) + 8;

                for (s2=s, i=0; i<2; i++, src+=2, s2+=avctx->channels)

                    s2[0] = (src[0]&0xF0) + (src[1]<<8);

            }

            for (m=2; m<32; m+=2) {

                s = &samples[m*avctx->channels + channel];

                for (n=0; n<4; n++, src++, s+=32*avctx->channels) {

                    for (s2=s, i=0; i<8; i+=4, s2+=avctx->channels) {

                        int level = (int32_t)((*src & (0xF0>>i)) << (24+i)) >> shift[n];

                        int pred  = s2[-1*avctx->channels] * coeff[0][n]

                                  + s2[-2*avctx->channels] * coeff[1][n];

                        s2[0] = av_clip_int16((level + pred + 0x80) >> 8);

                    }

                }

            }

        }

        samples += 32*4*avctx->channels;

        break;

    case CODEC_ID_ADPCM_IMA_AMV:

    case CODEC_ID_ADPCM_IMA_SMJPEG:

        c->status[0].predictor = (int16_t)bytestream_get_le16(&src);

        c->status[0].step_index = bytestream_get_le16(&src);

        if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

            src+=4;

        while (src < buf + buf_size) {

            char hi, lo;

            lo = *src & 0x0F;

            hi = *src >> 4;

            if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)

                FFSWAP(char, hi, lo);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                lo, 3);

            *samples++ = adpcm_ima_expand_nibble(&c->status[0],

                hi, 3);

            src++;

        }

        break;

    case CODEC_ID_ADPCM_CT:

        while (src < buf + buf_size) {

            uint8_t v = *src++;

            *samples++ = adpcm_ct_expand_nibble(&c->status[0 ], v >> 4  );

            *samples++ = adpcm_ct_expand_nibble(&c->status[st], v & 0x0F);

        }

        break;

    case CODEC_ID_ADPCM_SBPRO_4:

    case CODEC_ID_ADPCM_SBPRO_3:

    case CODEC_ID_ADPCM_SBPRO_2:

        if (!c->status[0].step_index) {

            /* the first byte is a raw sample */

            *samples++ = 128 * (*src++ - 0x80);

            if (st)

              *samples++ = 128 * (*src++ - 0x80);

            c->status[0].step_index = 1;

        }

        if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {

            while (src < buf + buf_size) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] >> 4, 4, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x0F, 4, 0);

                src++;

            }

        } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {

            while (src < buf + buf_size && samples + 2 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 5        , 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x07, 3, 0);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    src[0] & 0x03, 2, 0);

                src++;

            }

        } else {

            while (src < buf + buf_size && samples + 3 < samples_end) {

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                     src[0] >> 6        , 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    (src[0] >> 4) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],

                    (src[0] >> 2) & 0x03, 2, 2);

                *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],

                    src[0] & 0x03, 2, 2);

                src++;

            }

        }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        GetBitContext gb;

        const int *table;

        int k0, signmask, nb_bits, count;

        int size = buf_size*8;

        init_get_bits(&gb, buf, size);

        //read bits & initial values

        nb_bits = get_bits(&gb, 2)+2;

        //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);

        table = swf_index_tables[nb_bits-2];

        k0 = 1 << (nb_bits-2);

        signmask = 1 << (nb_bits-1);

        while (get_bits_count(&gb) <= size - 22*avctx->channels) {

            for (i = 0; i < avctx->channels; i++) {

                *samples++ = c->status[i].predictor = get_sbits(&gb, 16);

                c->status[i].step_index = get_bits(&gb, 6);

            }

            for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {

                int i;

                for (i = 0; i < avctx->channels; i++) {

                    // similar to IMA adpcm

                    int delta = get_bits(&gb, nb_bits);

                    int step = ff_adpcm_step_table[c->status[i].step_index];

                    long vpdiff = 0; // vpdiff = (delta+0.5)*step/4

                    int k = k0;

                    do {

                        if (delta & k)

                            vpdiff += step;

                        step >>= 1;

                        k >>= 1;

                    } while(k);

                    vpdiff += step;

                    if (delta & signmask)

                        c->status[i].predictor -= vpdiff;

                    else

                        c->status[i].predictor += vpdiff;

                    c->status[i].step_index += table[delta & (~signmask)];

                    c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);

                    c->status[i].predictor = av_clip_int16(c->status[i].predictor);

                    *samples++ = c->status[i].predictor;

                    if (samples >= samples_end) {

                        av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

                        return -1;

                    }

                }

            }

        }

        src += buf_size;

        break;

    }

    case CODEC_ID_ADPCM_YAMAHA:

        while (src < buf + buf_size) {

            uint8_t v = *src++;

            *samples++ = adpcm_yamaha_expand_nibble(&c->status[0 ], v & 0x0F);

            *samples++ = adpcm_yamaha_expand_nibble(&c->status[st], v >> 4  );

        }

        break;

    case CODEC_ID_ADPCM_THP:

    {

        int table[2][16];

        unsigned int samplecnt;

        int prev[2][2];

        int ch;

        if (buf_size < 80) {

            av_log(avctx, AV_LOG_ERROR, "frame too small\n");

            return -1;

        }

        src+=4;

        samplecnt = bytestream_get_be32(&src);

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

            table[0][i] = (int16_t)bytestream_get_be16(&src);

        /* Initialize the previous sample.  */

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

            prev[0][i] = (int16_t)bytestream_get_be16(&src);

        if (samplecnt >= (samples_end - samples) /  (st + 1)) {

            av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");

            return -1;

        }

        for (ch = 0; ch <= st; ch++) {

            samples = (unsigned short *) data + ch;

            /* Read in every sample for this channel.  */

            for (i = 0; i < samplecnt / 14; i++) {

                int index = (*src >> 4) & 7;

                unsigned int exp = 28 - (*src++ & 15);

                int factor1 = table[ch][index * 2];

                int factor2 = table[ch][index * 2 + 1];

                /* Decode 14 samples.  */

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

                    int32_t sampledat;

                    if(n&1) sampledat=  *src++    <<28;

                    else    sampledat= (*src&0xF0)<<24;

                    sampledat = ((prev[ch][0]*factor1

                                + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);

                    *samples = av_clip_int16(sampledat);

                    prev[ch][1] = prev[ch][0];

                    prev[ch][0] = *samples++;

                    /* In case of stereo, skip one sample, this sample

                       is for the other channel.  */

                    samples += st;

                }

            }

        }

        /* In the previous loop, in case stereo is used, samples is

           increased exactly one time too often.  */

        samples -= st;

        break;

    }

    default:

        return -1;

    }

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

    return src - buf;

}


static int smacker_decode_header_tree(SmackVContext *smk, GetBitContext *gb, int **recodes, int *last, int size)

{

    int res;

    HuffContext huff;

    HuffContext tmp1, tmp2;

    VLC vlc[2] = { { 0 } };

    int escapes[3];

    DBCtx ctx;

    int err = 0;

    if(size >= UINT_MAX>>4){ // (((size + 3) >> 2) + 3) << 2 must not overflow

        av_log(smk->avctx, AV_LOG_ERROR, "size too large\n");

        return AVERROR_INVALIDDATA;

    }

    tmp1.length = 256;

    tmp1.maxlength = 0;

    tmp1.current = 0;

    tmp1.bits = av_mallocz(256 * 4);

    tmp1.lengths = av_mallocz(256 * sizeof(int));

    tmp1.values = av_mallocz(256 * sizeof(int));

    tmp2.length = 256;

    tmp2.maxlength = 0;

    tmp2.current = 0;

    tmp2.bits = av_mallocz(256 * 4);

    tmp2.lengths = av_mallocz(256 * sizeof(int));

    tmp2.values = av_mallocz(256 * sizeof(int));

    if(get_bits1(gb)) {

        smacker_decode_tree(gb, &tmp1, 0, 0);

        skip_bits1(gb);

        if(tmp1.current > 1) {

            res = init_vlc(&vlc[0], SMKTREE_BITS, tmp1.length,

                        tmp1.lengths, sizeof(int), sizeof(int),

                        tmp1.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);

            if(res < 0) {

                av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (!vlc[0].table) {

        av_log(smk->avctx, AV_LOG_ERROR, "Skipping low bytes tree\n");

    }

    if(get_bits1(gb)){

        smacker_decode_tree(gb, &tmp2, 0, 0);

        skip_bits1(gb);

        if(tmp2.current > 1) {

            res = init_vlc(&vlc[1], SMKTREE_BITS, tmp2.length,

                        tmp2.lengths, sizeof(int), sizeof(int),

                        tmp2.bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);

            if(res < 0) {

                av_log(smk->avctx, AV_LOG_ERROR, "Cannot build VLC table\n");

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if (!vlc[1].table) {

        av_log(smk->avctx, AV_LOG_ERROR, "Skipping high bytes tree\n");

    }

    escapes[0]  = get_bits(gb, 16);

    escapes[1]  = get_bits(gb, 16);

    escapes[2]  = get_bits(gb, 16);

    last[0] = last[1] = last[2] = -1;

    ctx.escapes[0] = escapes[0];

    ctx.escapes[1] = escapes[1];

    ctx.escapes[2] = escapes[2];

    ctx.v1 = &vlc[0];

    ctx.v2 = &vlc[1];

    ctx.recode1 = tmp1.values;

    ctx.recode2 = tmp2.values;

    ctx.last = last;

    huff.length = ((size + 3) >> 2) + 3;

    huff.maxlength = 0;

    huff.current = 0;

    huff.values = av_mallocz(huff.length * sizeof(int));

    if (smacker_decode_bigtree(gb, &huff, &ctx) < 0)

        err = -1;

    skip_bits1(gb);

    if(ctx.last[0] == -1) ctx.last[0] = huff.current++;

    if(ctx.last[1] == -1) ctx.last[1] = huff.current++;

    if(ctx.last[2] == -1) ctx.last[2] = huff.current++;

    if(huff.current > huff.length){

        ctx.last[0] = ctx.last[1] = ctx.last[2] = 1;

        av_log(smk->avctx, AV_LOG_ERROR, "bigtree damaged\n");

        return AVERROR_INVALIDDATA;

    }

    *recodes = huff.values;

    if(vlc[0].table)

        ff_free_vlc(&vlc[0]);

    if(vlc[1].table)

        ff_free_vlc(&vlc[1]);

    av_free(tmp1.bits);

    av_free(tmp1.lengths);

    av_free(tmp1.values);

    av_free(tmp2.bits);

    av_free(tmp2.lengths);

    av_free(tmp2.values);

    return err;

}


static int standard_decode_picture_primary_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    int status = 0;

    if (v->finterpflag) v->interpfrm = get_bits(gb, 1);

    skip_bits(gb, 2); //framecnt unused

    if (v->rangered) v->rangeredfrm = get_bits(gb, 1);

    v->s.pict_type = get_bits(gb, 1);

    if (v->s.avctx->max_b_frames)

    {

        if (!v->s.pict_type)

        {

            if (get_bits(gb, 1)) v->s.pict_type = I_TYPE;

            else v->s.pict_type = B_TYPE;

        }

        else v->s.pict_type = P_TYPE;

    }

    else v->s.pict_type++;

    switch (v->s.pict_type)

    {

    case I_TYPE: status = decode_i_picture_header(v); break;

    case P_TYPE: status = decode_p_picture_primary_header(v); break;

    case BI_TYPE:

    case B_TYPE: status = decode_b_picture_primary_header(v); break;

    }

    if (status == FRAME_SKIPED)

    {

      av_log(v->s.avctx, AV_LOG_INFO, "Skipping frame...\n");

      return status;

    }

    return 0;

}


static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream, HTTPContext *c)

{

    FILE* f;

    char line[1024];

    char  cmd[1024];

    FFServerIPAddressACL *acl = NULL;

    int line_num = 0;

    const char *p;

    f = fopen(stream->dynamic_acl, "r");

    if (!f) {

        perror(stream->dynamic_acl);

        return NULL;

    }

    acl = av_mallocz(sizeof(FFServerIPAddressACL));

    /* Build ACL */

    for(;;) {

        if (fgets(line, sizeof(line), f) == NULL)

            break;

        line_num++;

        p = line;

        while (av_isspace(*p))

            p++;

        if (*p == '\0' || *p == '#')

            continue;

        ffserver_get_arg(cmd, sizeof(cmd), &p);

        if (!av_strcasecmp(cmd, "ACL"))

            ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num);

    }

    fclose(f);

    return acl;

}


static int discard_f(BlockBackend *blk, int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, qflag = 0;

    int c, ret;

    int64_t offset, count;

    while ((c = getopt(argc, argv, "Cq")) != -1) {

        switch (c) {

        case 'C':

            Cflag = 1;

            break;

        case 'q':

            qflag = 1;

            break;

        default:

            return qemuio_command_usage(&discard_cmd);

        }

    }

    if (optind != argc - 2) {

        return qemuio_command_usage(&discard_cmd);

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        print_cvtnum_err(offset, argv[optind]);

        return 0;

    }

    optind++;

    count = cvtnum(argv[optind]);

    if (count < 0) {

        print_cvtnum_err(count, argv[optind]);

        return 0;

    } else if (count >> BDRV_SECTOR_BITS > INT_MAX) {

        printf("length cannot exceed %"PRIu64", given %s\n",

               (uint64_t)INT_MAX << BDRV_SECTOR_BITS,

               argv[optind]);

        return 0;

    }

    gettimeofday(&t1, NULL);

    ret = blk_discard(blk, offset >> BDRV_SECTOR_BITS,

                      count >> BDRV_SECTOR_BITS);

    gettimeofday(&t2, NULL);

    if (ret < 0) {

        printf("discard failed: %s\n", strerror(-ret));

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    if (!qflag) {

        t2 = tsub(t2, t1);

        print_report("discard", &t2, offset, count, count, 1, Cflag);

    }

out:

    return 0;

}


void memory_region_set_dirty(MemoryRegion *mr, hwaddr addr,

                             hwaddr size)

{

    assert(mr->terminates);

    cpu_physical_memory_set_dirty_range(mr->ram_addr + addr, size,

                                        memory_region_get_dirty_log_mask(mr));

}


static void vnc_display_print_local_addr(VncDisplay *vd)

{

    SocketAddressLegacy *addr;

    Error *err = NULL;

    if (!vd->nlsock) {

        return;

    }

    addr = qio_channel_socket_get_local_address(vd->lsock[0], &err);

    if (!addr) {

        return;

    }

    if (addr->type != SOCKET_ADDRESS_LEGACY_KIND_INET) {

        qapi_free_SocketAddressLegacy(addr);

        return;

    }

    error_printf_unless_qmp("VNC server running on %s:%s\n",

                            addr->u.inet.data->host,

                            addr->u.inet.data->port);

    qapi_free_SocketAddressLegacy(addr);

}


static int v9fs_synth_lstat(FsContext *fs_ctx,

                            V9fsPath *fs_path, struct stat *stbuf)

{

    V9fsSynthNode *node = *(V9fsSynthNode **)fs_path->data;

    v9fs_synth_fill_statbuf(node, stbuf);

    return 0;

}


static av_cold int qsv_decode_close(AVCodecContext *avctx)
{
    QSVOtherContext *s = avctx->priv_data;
    ff_qsv_decode_close(&s->qsv);
    qsv_clear_buffers(s);
    av_fifo_free(s->packet_fifo);
    return 0;
}


int ff_ass_split_override_codes(const ASSCodesCallbacks *callbacks, void *priv,

                                const char *buf)

{

    const char *text = NULL;

    char new_line[2];

    int text_len = 0;

    while (*buf) {

        if (text && callbacks->text &&

            (sscanf(buf, "\\%1[nN]", new_line) == 1 ||

             !strncmp(buf, "{\\", 2))) {

            callbacks->text(priv, text, text_len);

            text = NULL;

        }

        if (sscanf(buf, "\\%1[nN]", new_line) == 1) {

            if (callbacks->new_line)

                callbacks->new_line(priv, new_line[0] == 'N');

            buf += 2;

        } else if (!strncmp(buf, "{\\", 2)) {

            buf++;

            while (*buf == '\\') {

                char style[2], c[2], sep[2], c_num[2] = "0", tmp[128] = {0};

                unsigned int color = 0xFFFFFFFF;

                int len, size = -1, an = -1, alpha = -1;

                int x1, y1, x2, y2, t1 = -1, t2 = -1;

                if (sscanf(buf, "\\%1[bisu]%1[01\\}]%n", style, c, &len) > 1) {

                    int close = c[0] == '0' ? 1 : c[0] == '1' ? 0 : -1;

                    len += close != -1;

                    if (callbacks->style)

                        callbacks->style(priv, style[0], close);

                } else if (sscanf(buf, "\\c%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\c&H%X&%1[\\}]%n", &color, sep, &len) > 1 ||

                           sscanf(buf, "\\%1[1234]c%1[\\}]%n", c_num, sep, &len) > 1 ||

                           sscanf(buf, "\\%1[1234]c&H%X&%1[\\}]%n", c_num, &color, sep, &len) > 2) {

                    if (callbacks->color)

                        callbacks->color(priv, color, c_num[0] - '0');

                } else if (sscanf(buf, "\\alpha%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\alpha&H%2X&%1[\\}]%n", &alpha, sep, &len) > 1 ||

                           sscanf(buf, "\\%1[1234]a%1[\\}]%n", c_num, sep, &len) > 1 ||

                           sscanf(buf, "\\%1[1234]a&H%2X&%1[\\}]%n", c_num, &alpha, sep, &len) > 2) {

                    if (callbacks->alpha)

                        callbacks->alpha(priv, alpha, c_num[0] - '0');

                } else if (sscanf(buf, "\\fn%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\fn%127[^\\}]%1[\\}]%n", tmp, sep, &len) > 1) {

                    if (callbacks->font_name)

                        callbacks->font_name(priv, tmp[0] ? tmp : NULL);

                } else if (sscanf(buf, "\\fs%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\fs%u%1[\\}]%n", &size, sep, &len) > 1) {

                    if (callbacks->font_size)

                        callbacks->font_size(priv, size);

                } else if (sscanf(buf, "\\a%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\a%2u%1[\\}]%n", &an, sep, &len) > 1 ||

                           sscanf(buf, "\\an%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\an%1u%1[\\}]%n", &an, sep, &len) > 1) {

                    if (an != -1 && buf[2] != 'n')

                        an = (an&3) + (an&4 ? 6 : an&8 ? 3 : 0);

                    if (callbacks->alignment)

                        callbacks->alignment(priv, an);

                } else if (sscanf(buf, "\\r%1[\\}]%n", sep, &len) > 0 ||

                           sscanf(buf, "\\r%127[^\\}]%1[\\}]%n", tmp, sep, &len) > 1) {

                    if (callbacks->cancel_overrides)

                        callbacks->cancel_overrides(priv, tmp);

                } else if (sscanf(buf, "\\move(%d,%d,%d,%d)%1[\\}]%n", &x1, &y1, &x2, &y2, sep, &len) > 4 ||

                           sscanf(buf, "\\move(%d,%d,%d,%d,%d,%d)%1[\\}]%n", &x1, &y1, &x2, &y2, &t1, &t2, sep, &len) > 6) {

                    if (callbacks->move)

                        callbacks->move(priv, x1, y1, x2, y2, t1, t2);

                } else if (sscanf(buf, "\\pos(%d,%d)%1[\\}]%n", &x1, &y1, sep, &len) > 2) {

                    if (callbacks->move)

                        callbacks->move(priv, x1, y1, x1, y1, -1, -1);

                } else if (sscanf(buf, "\\org(%d,%d)%1[\\}]%n", &x1, &y1, sep, &len) > 2) {

                    if (callbacks->origin)

                        callbacks->origin(priv, x1, y1);

                } else {

                    len = strcspn(buf+1, "\\}") + 2;  /* skip unknown code */

                }

                buf += len - 1;

            }

            if (*buf++ != '}')

                return AVERROR_INVALIDDATA;

        } else {

            if (!text) {

                text = buf;

                text_len = 1;

            } else

                text_len++;

            buf++;

        }

    }

    if (text && callbacks->text)

        callbacks->text(priv, text, text_len);

    if (callbacks->end)

        callbacks->end(priv);

    return 0;

}


static void compute_scale_factors(unsigned char scale_code[SBLIMIT],

                                  unsigned char scale_factors[SBLIMIT][3],

                                  int sb_samples[3][12][SBLIMIT],

                                  int sblimit)

{

    int *p, vmax, v, n, i, j, k, code;

    int index, d1, d2;

    unsigned char *sf = &scale_factors[0][0];

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

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

            /* find the max absolute value */

            p = &sb_samples[i][0][j];

            vmax = abs(*p);

            for(k=1;k<12;k++) {

                p += SBLIMIT;

                v = abs(*p);

                if (v > vmax)

                    vmax = v;

            }

            /* compute the scale factor index using log 2 computations */

            if (vmax > 0) {

                n = av_log2(vmax);

                /* n is the position of the MSB of vmax. now

                   use at most 2 compares to find the index */

                index = (21 - n) * 3 - 3;

                if (index >= 0) {

                    while (vmax <= scale_factor_table[index+1])

                        index++;

                } else {

                    index = 0; /* very unlikely case of overflow */

                }

            } else {

                index = 62; /* value 63 is not allowed */

            }

#if 0

            printf("%2d:%d in=%x %x %d\n",

                   j, i, vmax, scale_factor_table[index], index);

#endif

            /* store the scale factor */

            assert(index >=0 && index <= 63);

            sf[i] = index;

        }

        /* compute the transmission factor : look if the scale factors

           are close enough to each other */

        d1 = scale_diff_table[sf[0] - sf[1] + 64];

        d2 = scale_diff_table[sf[1] - sf[2] + 64];

        /* handle the 25 cases */

        switch(d1 * 5 + d2) {

        case 0*5+0:

        case 0*5+4:

        case 3*5+4:

        case 4*5+0:

        case 4*5+4:

            code = 0;

            break;

        case 0*5+1:

        case 0*5+2:

        case 4*5+1:

        case 4*5+2:

            code = 3;

            sf[2] = sf[1];

            break;

        case 0*5+3:

        case 4*5+3:

            code = 3;

            sf[1] = sf[2];

            break;

        case 1*5+0:

        case 1*5+4:

        case 2*5+4:

            code = 1;

            sf[1] = sf[0];

            break;

        case 1*5+1:

        case 1*5+2:

        case 2*5+0:

        case 2*5+1:

        case 2*5+2:

            code = 2;

            sf[1] = sf[2] = sf[0];

            break;

        case 2*5+3:

        case 3*5+3:

            code = 2;

            sf[0] = sf[1] = sf[2];

            break;

        case 3*5+0:

        case 3*5+1:

        case 3*5+2:

            code = 2;

            sf[0] = sf[2] = sf[1];

            break;

        case 1*5+3:

            code = 2;

            if (sf[0] > sf[2])

              sf[0] = sf[2];

            sf[1] = sf[2] = sf[0];

            break;

        default:

            assert(0); //cannot happen

            code = 0;           /* kill warning */

        }

#if 0

        printf("%d: %2d %2d %2d %d %d -> %d\n", j,

               sf[0], sf[1], sf[2], d1, d2, code);

#endif

        scale_code[j] = code;

        sf += 3;

    }

}


static void armv7m_nvic_clear_pending(void *opaque, int irq)

{

    NVICState *s = (NVICState *)opaque;

    VecInfo *vec;

    assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);

    vec = &s->vectors[irq];

    trace_nvic_clear_pending(irq, vec->enabled, vec->prio);

    if (vec->pending) {

        vec->pending = 0;

        nvic_irq_update(s);

    }

}


static void vararg_string(void)

{

    int i;

    struct {

        const char *decoded;

    } test_cases[] = {

        { "hello world" },

        { "the quick brown fox jumped over the fence" },

        {}

    };

    for (i = 0; test_cases[i].decoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_jsonf("%s", test_cases[i].decoded);

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QSTRING);

        str = qobject_to_qstring(obj);

        g_assert(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        QDECREF(str);

    }

}


static int scsi_qdev_exit(DeviceState *qdev)

{

    SCSIDevice *dev = SCSI_DEVICE(qdev);

    if (dev->vmsentry) {

        qemu_del_vm_change_state_handler(dev->vmsentry);

    }

    scsi_device_destroy(dev);

    return 0;

}


static int gen_sub_bitmap(TeletextContext *ctx, AVSubtitleRect *sub_rect, vbi_page *page, int chop_top)

{

    int resx = page->columns * BITMAP_CHAR_WIDTH;

    int resy = (page->rows - chop_top) * BITMAP_CHAR_HEIGHT;

    uint8_t ci, cmax = 0;

    int ret;

    vbi_char *vc = page->text + (chop_top * page->columns);

    vbi_char *vcend = page->text + (page->rows * page->columns);

    for (; vc < vcend; vc++) {

        if (vc->opacity != VBI_TRANSPARENT_SPACE) {

            cmax = VBI_NB_COLORS;

            break;

        }

    }

    if (cmax == 0) {

        av_log(ctx, AV_LOG_DEBUG, "dropping empty page %3x\n", page->pgno);

        sub_rect->type = SUBTITLE_NONE;

        return 0;

    }

    if ((ret = avpicture_alloc(&sub_rect->pict, AV_PIX_FMT_PAL8, resx, resy)) < 0)

        return ret;

    // Yes, we want to allocate the palette on our own because AVSubtitle works this way

    sub_rect->pict.data[1] = NULL;

    vbi_draw_vt_page_region(page, VBI_PIXFMT_PAL8,

                            sub_rect->pict.data[0], sub_rect->pict.linesize[0],

                            0, chop_top, page->columns, page->rows - chop_top,

                            /*reveal*/ 1, /*flash*/ 1);

    fix_transparency(ctx, sub_rect, page, chop_top, cmax, resx, resy);

    sub_rect->x = ctx->x_offset;

    sub_rect->y = ctx->y_offset + chop_top * BITMAP_CHAR_HEIGHT;

    sub_rect->w = resx;

    sub_rect->h = resy;

    sub_rect->nb_colors = (int)cmax + 1;

    sub_rect->pict.data[1] = av_mallocz(AVPALETTE_SIZE);

    if (!sub_rect->pict.data[1]) {

        av_freep(&sub_rect->pict.data[0]);

        return AVERROR(ENOMEM);

    }

    for (ci = 0; ci < cmax; ci++) {

        int r, g, b, a;

        r = VBI_R(page->color_map[ci]);

        g = VBI_G(page->color_map[ci]);

        b = VBI_B(page->color_map[ci]);

        a = VBI_A(page->color_map[ci]);

        ((uint32_t *)sub_rect->pict.data[1])[ci] = RGBA(r, g, b, a);

        av_dlog(ctx, "palette %0x\n", ((uint32_t *)sub_rect->pict.data[1])[ci]);

    }

    ((uint32_t *)sub_rect->pict.data[1])[cmax] = RGBA(0, 0, 0, 0);

    sub_rect->type = SUBTITLE_BITMAP;

    return 0;

}


int opt_default(const char *opt, const char *arg)

{

    const AVOption *oc, *of, *os, *oswr;

    char opt_stripped[128];

    const char *p;

    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class(), *sc, *swr_class;

    if (!(p = strchr(opt, ':')))

        p = opt + strlen(opt);

    av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));

    if ((oc = av_opt_find(&cc, opt_stripped, NULL, 0,

                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||

        ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&

         (oc = av_opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ))))

        av_dict_set(&codec_opts, opt, arg, FLAGS(oc));

    if ((of = av_opt_find(&fc, opt, NULL, 0,

                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)))

        av_dict_set(&format_opts, opt, arg, FLAGS(of));

#if CONFIG_SWSCALE

    sc = sws_get_class();

    if ((os = av_opt_find(&sc, opt, NULL, 0,

                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        // XXX we only support sws_flags, not arbitrary sws options

        int ret = av_opt_set(sws_opts, opt, arg, 0);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);

            return ret;

        }

    }

#endif

    swr_class = swr_get_class();

    if (!oc && !of && !os && (oswr = av_opt_find(&swr_class, opt, NULL, 0,

                          AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        int ret = av_opt_set(swr_opts, opt, arg, 0);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);

            return ret;

        }

    }

    if (oc || of || os || oswr)

        return 0;

    av_log(NULL, AV_LOG_ERROR, "Unrecognized option '%s'\n", opt);

    return AVERROR_OPTION_NOT_FOUND;

}


static void slavio_misc_init(target_phys_addr_t base,

                             target_phys_addr_t aux1_base,

                             target_phys_addr_t aux2_base, qemu_irq irq,

                             qemu_irq fdc_tc)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "slavio_misc");

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    if (base) {

        /* 8 bit registers */

        /* Slavio control */

        sysbus_mmio_map(s, 0, base + MISC_CFG);

        /* Diagnostics */

        sysbus_mmio_map(s, 1, base + MISC_DIAG);

        /* Modem control */

        sysbus_mmio_map(s, 2, base + MISC_MDM);

        /* 16 bit registers */

        /* ss600mp diag LEDs */

        sysbus_mmio_map(s, 3, base + MISC_LEDS);

        /* 32 bit registers */

        /* System control */

        sysbus_mmio_map(s, 4, base + MISC_SYS);

    }

    if (aux1_base) {

        /* AUX 1 (Misc System Functions) */

        sysbus_mmio_map(s, 5, aux1_base);

    }

    if (aux2_base) {

        /* AUX 2 (Software Powerdown Control) */

        sysbus_mmio_map(s, 6, aux2_base);

    }

    sysbus_connect_irq(s, 0, irq);

    sysbus_connect_irq(s, 1, fdc_tc);

    qemu_system_powerdown = qdev_get_gpio_in(dev, 0);

}


int check_tm_pred4x4_mode(int mode, int mb_x, int mb_y)

{

    if (!mb_x) {

        return mb_y ? VERT_VP8_PRED : DC_129_PRED;

    } else {

        return mb_y ? mode : HOR_VP8_PRED;

    }

}


static struct ResampleContext *create(struct ResampleContext *c, int out_rate, int in_rate, int filter_size, int phase_shift, int linear,

        double cutoff, enum AVSampleFormat format, enum SwrFilterType filter_type, double kaiser_beta, double precision, int cheby, int exact_rational){

    soxr_error_t error;

    soxr_datatype_t type =

        format == AV_SAMPLE_FMT_S16P? SOXR_INT16_S :

        format == AV_SAMPLE_FMT_S16 ? SOXR_INT16_I :

        format == AV_SAMPLE_FMT_S32P? SOXR_INT32_S :

        format == AV_SAMPLE_FMT_S32 ? SOXR_INT32_I :

        format == AV_SAMPLE_FMT_FLTP? SOXR_FLOAT32_S :

        format == AV_SAMPLE_FMT_FLT ? SOXR_FLOAT32_I :

        format == AV_SAMPLE_FMT_DBLP? SOXR_FLOAT64_S :

        format == AV_SAMPLE_FMT_DBL ? SOXR_FLOAT64_I : (soxr_datatype_t)-1;

    soxr_io_spec_t io_spec = soxr_io_spec(type, type);

    soxr_quality_spec_t q_spec = soxr_quality_spec((int)((precision-2)/4), (SOXR_HI_PREC_CLOCK|SOXR_ROLLOFF_NONE)*!!cheby);

    q_spec.precision = linear? 0 : precision;

#if !defined SOXR_VERSION /* Deprecated @ March 2013: */

    q_spec.bw_pc = cutoff? FFMAX(FFMIN(cutoff,.995),.8)*100 : q_spec.bw_pc;

#else

    q_spec.passband_end = cutoff? FFMAX(FFMIN(cutoff,.995),.8) : q_spec.passband_end;

#endif

    soxr_delete((soxr_t)c);

    c = (struct ResampleContext *)

        soxr_create(in_rate, out_rate, 0, &error, &io_spec, &q_spec, 0);

    if (!c)

        av_log(NULL, AV_LOG_ERROR, "soxr_create: %s\n", error);

    return c;

}


static void bdrv_put_buffer(void *opaque, const uint8_t *buf,

                            int64_t pos, int size)

{

    QEMUFileBdrv *s = opaque;

    bdrv_pwrite(s->bs, s->base_offset + pos, buf, size);

}


static void qemu_clock_init(QEMUClockType type)

{

    QEMUClock *clock = qemu_clock_ptr(type);

    /* Assert that the clock of type TYPE has not been initialized yet. */

    assert(main_loop_tlg.tl[type] == NULL);

    clock->type = type;

    clock->enabled = (type == QEMU_CLOCK_VIRTUAL ? false : true);

    clock->last = INT64_MIN;

    QLIST_INIT(&clock->timerlists);

    notifier_list_init(&clock->reset_notifiers);

    main_loop_tlg.tl[type] = timerlist_new(type, NULL, NULL);

}


static CharDriverState *qemu_chr_open_pty(QemuOpts *opts)

{

    CharDriverState *chr;

    PtyCharDriver *s;

    struct termios tty;

    int master_fd, slave_fd, len;

#if defined(__OpenBSD__) || defined(__DragonFly__)

    char pty_name[PATH_MAX];

#define q_ptsname(x) pty_name

#else

    char *pty_name = NULL;

#define q_ptsname(x) ptsname(x)

#endif

    if (openpty(&master_fd, &slave_fd, pty_name, NULL, NULL) < 0) {

        return NULL;

    }

    /* Set raw attributes on the pty. */

    tcgetattr(slave_fd, &tty);

    cfmakeraw(&tty);

    tcsetattr(slave_fd, TCSAFLUSH, &tty);

    close(slave_fd);

    chr = g_malloc0(sizeof(CharDriverState));

    len = strlen(q_ptsname(master_fd)) + 5;

    chr->filename = g_malloc(len);

    snprintf(chr->filename, len, "pty:%s", q_ptsname(master_fd));

    qemu_opt_set(opts, "path", q_ptsname(master_fd));

    fprintf(stderr, "char device redirected to %s\n", q_ptsname(master_fd));

    s = g_malloc0(sizeof(PtyCharDriver));

    chr->opaque = s;

    chr->chr_write = pty_chr_write;

    chr->chr_update_read_handler = pty_chr_update_read_handler;

    chr->chr_close = pty_chr_close;

    s->fd = master_fd;

    s->timer = qemu_new_timer_ms(rt_clock, pty_chr_timer, chr);

    return chr;

}


uint32_t HELPER(sigp)(CPUS390XState *env, uint64_t order_code, uint32_t r1,

                      uint64_t cpu_addr)

{

    int cc = SIGP_CC_ORDER_CODE_ACCEPTED;

    HELPER_LOG("%s: %016" PRIx64 " %08x %016" PRIx64 "\n",

               __func__, order_code, r1, cpu_addr);

    /* Remember: Use "R1 or R1 + 1, whichever is the odd-numbered register"

       as parameter (input). Status (output) is always R1. */

    switch (order_code) {

    case SIGP_SET_ARCH:

        /* switch arch */

        break;

    case SIGP_SENSE:

        /* enumerate CPU status */

        if (cpu_addr) {

            /* XXX implement when SMP comes */

            return 3;

        }

        env->regs[r1] &= 0xffffffff00000000ULL;

        cc = 1;

        break;

#if !defined(CONFIG_USER_ONLY)

    case SIGP_RESTART:

        qemu_system_reset_request();

        cpu_loop_exit(CPU(s390_env_get_cpu(env)));

        break;

    case SIGP_STOP:

        qemu_system_shutdown_request();

        cpu_loop_exit(CPU(s390_env_get_cpu(env)));

        break;

#endif

    default:

        /* unknown sigp */

        fprintf(stderr, "XXX unknown sigp: 0x%" PRIx64 "\n", order_code);

        cc = SIGP_CC_NOT_OPERATIONAL;

    }

    return cc;

}


yuv2rgb_1_c_template(SwsContext *c, const uint16_t *buf0,

                     const uint16_t *ubuf0, const uint16_t *ubuf1,

                     const uint16_t *vbuf0, const uint16_t *vbuf1,

                     const uint16_t *abuf0, uint8_t *dest, int dstW,

                     int uvalpha, enum PixelFormat dstFormat,

                     int flags, int y, enum PixelFormat target,

                     int hasAlpha)

{

    int i;

    if (uvalpha < 2048) {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 = buf0[i * 2]     >> 7;

            int Y2 = buf0[i * 2 + 1] >> 7;

            int U  = ubuf1[i]        >> 7;

            int V  = vbuf1[i]        >> 7;

            int A1, A2;

            const void *r =  c->table_rV[V],

                       *g = (c->table_gU[U] + c->table_gV[V]),

                       *b =  c->table_bU[U];

            if (hasAlpha) {

                A1 = abuf0[i * 2    ] >> 7;

                A2 = abuf0[i * 2 + 1] >> 7;

            }

            yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,

                          r, g, b, y, target, hasAlpha);

        }

    } else {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 =  buf0[i * 2]          >> 7;

            int Y2 =  buf0[i * 2 + 1]      >> 7;

            int U  = (ubuf0[i] + ubuf1[i]) >> 8;

            int V  = (vbuf0[i] + vbuf1[i]) >> 8;

            int A1, A2;

            const void *r =  c->table_rV[V],

                       *g = (c->table_gU[U] + c->table_gV[V]),

                       *b =  c->table_bU[U];

            if (hasAlpha) {

                A1 = abuf0[i * 2    ] >> 7;

                A2 = abuf0[i * 2 + 1] >> 7;

            }

            yuv2rgb_write(dest, i, Y1, Y2, U, V, hasAlpha ? A1 : 0, hasAlpha ? A2 : 0,

                          r, g, b, y, target, hasAlpha);

        }

    }

}


static inline int onenand_prog_main(OneNANDState *s, int sec, int secn,

                void *src)

{

    int result = 0;

    if (secn > 0) {

        uint32_t size = (uint32_t)secn * 512;

        const uint8_t *sp = (const uint8_t *)src;

        uint8_t *dp = 0;

        if (s->bdrv_cur) {

            dp = g_malloc(size);

            if (!dp || bdrv_read(s->bdrv_cur, sec, dp, secn) < 0) {

                result = 1;

            }

        } else {

            if (sec + secn > s->secs_cur) {

                result = 1;

            } else {

                dp = (uint8_t *)s->current + (sec << 9);

            }

        }

        if (!result) {

            uint32_t i;

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

                dp[i] &= sp[i];

            }

            if (s->bdrv_cur) {

                result = bdrv_write(s->bdrv_cur, sec, dp, secn) < 0;

            }

        }

        if (dp && s->bdrv_cur) {

            g_free(dp);

        }

    }

    return result;

}


static int nbd_receive_list(QIOChannel *ioc, char **name, Error **errp)

{

    uint64_t magic;

    uint32_t opt;

    uint32_t type;

    uint32_t len;

    uint32_t namelen;

    int error;

    *name = NULL;

    if (read_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {

        error_setg(errp, "failed to read list option magic");

        return -1;

    }

    magic = be64_to_cpu(magic);

    if (magic != NBD_REP_MAGIC) {

        error_setg(errp, "Unexpected option list magic");

        return -1;

    }

    if (read_sync(ioc, &opt, sizeof(opt)) != sizeof(opt)) {

        error_setg(errp, "failed to read list option");

        return -1;

    }

    opt = be32_to_cpu(opt);

    if (opt != NBD_OPT_LIST) {

        error_setg(errp, "Unexpected option type %" PRIx32 " expected %x",

                   opt, NBD_OPT_LIST);

        return -1;

    }

    if (read_sync(ioc, &type, sizeof(type)) != sizeof(type)) {

        error_setg(errp, "failed to read list option type");

        return -1;

    }

    type = be32_to_cpu(type);

    error = nbd_handle_reply_err(ioc, opt, type, errp);

    if (error <= 0) {

        return error;

    }

    if (read_sync(ioc, &len, sizeof(len)) != sizeof(len)) {

        error_setg(errp, "failed to read option length");

        return -1;

    }

    len = be32_to_cpu(len);

    if (type == NBD_REP_ACK) {

        if (len != 0) {

            error_setg(errp, "length too long for option end");

            return -1;

        }

    } else if (type == NBD_REP_SERVER) {

        if (len < sizeof(namelen) || len > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "incorrect option length");

            return -1;

        }

        if (read_sync(ioc, &namelen, sizeof(namelen)) != sizeof(namelen)) {

            error_setg(errp, "failed to read option name length");

            return -1;

        }

        namelen = be32_to_cpu(namelen);

        len -= sizeof(namelen);

        if (len < namelen) {

            error_setg(errp, "incorrect option name length");

            return -1;

        }

        if (namelen > 255) {

            error_setg(errp, "export name length too long %" PRIu32, namelen);

            return -1;

        }

        *name = g_new0(char, namelen + 1);

        if (read_sync(ioc, *name, namelen) != namelen) {

            error_setg(errp, "failed to read export name");

            g_free(*name);

            *name = NULL;

            return -1;

        }

        (*name)[namelen] = '\0';

        len -= namelen;

        if (len) {

            char *buf = g_malloc(len + 1);

            if (read_sync(ioc, buf, len) != len) {

                error_setg(errp, "failed to read export description");

                g_free(*name);

                g_free(buf);

                *name = NULL;

                return -1;

            }

            buf[len] = '\0';

            TRACE("Ignoring export description: %s", buf);

            g_free(buf);

        }

    } else {

        error_setg(errp, "Unexpected reply type %" PRIx32 " expected %x",

                   type, NBD_REP_SERVER);

        return -1;

    }

    return 1;

}