static int ffserver_parse_config_stream(FFServerConfig *config, const char *cmd, const char **p,

                                        int line_num, FFServerStream **pstream)

{

    char arg[1024], arg2[1024];

    FFServerStream *stream;

    int val;

    av_assert0(pstream);

    stream = *pstream;

    if (!av_strcasecmp(cmd, "<Stream")) {

        char *q;

        FFServerStream *s;

        stream = av_mallocz(sizeof(FFServerStream));

        if (!stream)

            return AVERROR(ENOMEM);

        ffserver_get_arg(stream->filename, sizeof(stream->filename), p);

        q = strrchr(stream->filename, '>');

        if (q)

            *q = '\0';

        for (s = config->first_stream; s; s = s->next) {

            if (!strcmp(stream->filename, s->filename))

                ERROR("Stream '%s' already registered\n", s->filename);

        }

        stream->fmt = ffserver_guess_format(NULL, stream->filename, NULL);

        if (stream->fmt) {

            config->audio_id = stream->fmt->audio_codec;

            config->video_id = stream->fmt->video_codec;

        } else {

            config->audio_id = AV_CODEC_ID_NONE;

            config->video_id = AV_CODEC_ID_NONE;

        }

        *pstream = stream;

        return 0;

    }

    av_assert0(stream);

    if (!av_strcasecmp(cmd, "Feed")) {

        FFServerStream *sfeed;

        ffserver_get_arg(arg, sizeof(arg), p);

        sfeed = config->first_feed;

        while (sfeed) {

            if (!strcmp(sfeed->filename, arg))

                break;

            sfeed = sfeed->next_feed;

        }

        if (!sfeed)

            ERROR("Feed with name '%s' for stream '%s' is not defined\n", arg, stream->filename);

        else

            stream->feed = sfeed;

    } else if (!av_strcasecmp(cmd, "Format")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (!strcmp(arg, "status")) {

            stream->stream_type = STREAM_TYPE_STATUS;

            stream->fmt = NULL;

        } else {

            stream->stream_type = STREAM_TYPE_LIVE;

            /* JPEG cannot be used here, so use single frame MJPEG */

            if (!strcmp(arg, "jpeg"))

                strcpy(arg, "mjpeg");

            stream->fmt = ffserver_guess_format(arg, NULL, NULL);

            if (!stream->fmt)

                ERROR("Unknown Format: %s\n", arg);

        }

        if (stream->fmt) {

            config->audio_id = stream->fmt->audio_codec;

            config->video_id = stream->fmt->video_codec;

        }

    } else if (!av_strcasecmp(cmd, "InputFormat")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->ifmt = av_find_input_format(arg);

        if (!stream->ifmt)

            ERROR("Unknown input format: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "FaviconURL")) {

        if (stream->stream_type == STREAM_TYPE_STATUS)

            ffserver_get_arg(stream->feed_filename, sizeof(stream->feed_filename), p);

        else

            ERROR("FaviconURL only permitted for status streams\n");

    } else if (!av_strcasecmp(cmd, "Author")    ||

               !av_strcasecmp(cmd, "Comment")   ||

               !av_strcasecmp(cmd, "Copyright") ||

               !av_strcasecmp(cmd, "Title")) {

        char key[32];

        int i;

        ffserver_get_arg(arg, sizeof(arg), p);

        for (i = 0; i < strlen(cmd); i++)

            key[i] = av_tolower(cmd[i]);

        key[i] = 0;

        WARNING("'%s' option in configuration file is deprecated, "

                "use 'Metadata %s VALUE' instead\n", cmd, key);

        if (av_dict_set(&stream->metadata, key, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Metadata")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_get_arg(arg2, sizeof(arg2), p);

        if (av_dict_set(&stream->metadata, arg, arg2, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Preroll")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->prebuffer = atof(arg) * 1000;

    } else if (!av_strcasecmp(cmd, "StartSendOnKey")) {

        stream->send_on_key = 1;

    } else if (!av_strcasecmp(cmd, "AudioCodec")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        config->audio_id = opt_codec(arg, AVMEDIA_TYPE_AUDIO);

        if (config->audio_id == AV_CODEC_ID_NONE)

            ERROR("Unknown AudioCodec: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "VideoCodec")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        config->video_id = opt_codec(arg, AVMEDIA_TYPE_VIDEO);

        if (config->video_id == AV_CODEC_ID_NONE)

            ERROR("Unknown VideoCodec: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "MaxTime")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        stream->max_time = atof(arg) * 1000;

    } else if (!av_strcasecmp(cmd, "AudioBitRate")) {

        float f;

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(&f, arg, 1000, 0, FLT_MAX, config, line_num, "Invalid %s: %s\n", cmd, arg);

        if (av_dict_set_int(&config->audio_conf, cmd, lrintf(f), 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AudioChannels")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 8, config, line_num, "Invalid %s: %s, valid range is 1-8.", cmd, arg);

        if (av_dict_set(&config->audio_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AudioSampleRate")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 0, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->audio_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRateRange")) {

        int minrate, maxrate;

        ffserver_get_arg(arg, sizeof(arg), p);

        if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {

            if (av_dict_set_int(&config->video_conf, "VideoBitRateRangeMin", minrate, 0) < 0 ||

                av_dict_set_int(&config->video_conf, "VideoBitRateRangeMax", maxrate, 0) < 0)

                goto nomem;

        } else

            ERROR("Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n", arg);

    } else if (!av_strcasecmp(cmd, "Debug")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Strict")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBufferSize")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 8*1024, 0, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRateTolerance")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 1000, INT_MIN, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoBitRate")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 1000, 0, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

           goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoSize")) {

        int ret, w, h;

        ffserver_get_arg(arg, sizeof(arg), p);

        ret = av_parse_video_size(&w, &h, arg);

        if (ret < 0)

            ERROR("Invalid video size '%s'\n", arg);

        else if ((w % 16) || (h % 16))

            ERROR("Image size must be a multiple of 16\n");

        if (av_dict_set_int(&config->video_conf, "VideoSizeWidth", w, 0) < 0 ||

            av_dict_set_int(&config->video_conf, "VideoSizeHeight", h, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoFrameRate")) {

        AVRational frame_rate;

        ffserver_get_arg(arg, sizeof(arg), p);

        if (av_parse_video_rate(&frame_rate, arg) < 0) {

            ERROR("Incorrect frame rate: %s\n", arg);

        } else {

            if (av_dict_set_int(&config->video_conf, "VideoFrameRateNum", frame_rate.num, 0) < 0 ||

                av_dict_set_int(&config->video_conf, "VideoFrameRateDen", frame_rate.den, 0) < 0)

                goto nomem;

        }

    } else if (!av_strcasecmp(cmd, "PixelFormat")) {

        enum AVPixelFormat pix_fmt;

        ffserver_get_arg(arg, sizeof(arg), p);

        pix_fmt = av_get_pix_fmt(arg);

        if (pix_fmt == AV_PIX_FMT_NONE)

            ERROR("Unknown pixel format: %s\n", arg);

        if (av_dict_set_int(&config->video_conf, cmd, pix_fmt, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoGopSize")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, INT_MIN, INT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoIntraOnly")) {

        if (av_dict_set(&config->video_conf, cmd, "1", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoHighQuality")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Video4MotionVector")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AVOptionVideo") ||

               !av_strcasecmp(cmd, "AVOptionAudio")) {

        AVDictionary **dict;

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_get_arg(arg2, sizeof(arg2), p);

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

            dict = &config->video_opts;

        else

            dict = &config->audio_opts;

        if (av_dict_set(dict, arg, arg2, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "AVPresetVideo") ||

               !av_strcasecmp(cmd, "AVPresetAudio")) {

        char **preset = NULL;

        ffserver_get_arg(arg, sizeof(arg), p);

        if (!av_strcasecmp(cmd, "AVPresetVideo")) {

            preset = &config->video_preset;

            ffserver_opt_preset(arg, NULL, 0, NULL, &config->video_id);

        } else {

            preset = &config->audio_preset;

            ffserver_opt_preset(arg, NULL, 0, &config->audio_id, NULL);

        }

        *preset = av_strdup(arg);

        if (!preset)

            return AVERROR(ENOMEM);

    } else if (!av_strcasecmp(cmd, "VideoTag")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (strlen(arg) == 4) {

            if (av_dict_set(&config->video_conf, "VideoTag", "arg", 0) < 0)

                goto nomem;

        }

    } else if (!av_strcasecmp(cmd, "BitExact")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "DctFastint")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "IdctSimple")) {

        if (av_dict_set(&config->video_conf, cmd, "", 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "Qscale")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQDiff")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num, "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQMax")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num, "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "VideoQMin")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(NULL, arg, 0, 1, 31, config, line_num, "%s out of range\n", cmd);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "LumiMask")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(NULL, arg, 0, -FLT_MAX, FLT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "DarkMask")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_float_param(NULL, arg, 0, -FLT_MAX, FLT_MAX, config, line_num, "Invalid %s: %s", cmd, arg);

        if (av_dict_set(&config->video_conf, cmd, arg, 0) < 0)

            goto nomem;

    } else if (!av_strcasecmp(cmd, "NoVideo")) {

        config->video_id = AV_CODEC_ID_NONE;

    } else if (!av_strcasecmp(cmd, "NoAudio")) {

        config->audio_id = AV_CODEC_ID_NONE;

    } else if (!av_strcasecmp(cmd, "ACL")) {

        ffserver_parse_acl_row(stream, NULL, NULL, *p, config->filename, line_num);

    } else if (!av_strcasecmp(cmd, "DynamicACL")) {

        ffserver_get_arg(stream->dynamic_acl, sizeof(stream->dynamic_acl), p);

    } else if (!av_strcasecmp(cmd, "RTSPOption")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        av_freep(&stream->rtsp_option);

        stream->rtsp_option = av_strdup(arg);

    } else if (!av_strcasecmp(cmd, "MulticastAddress")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        if (resolve_host(&stream->multicast_ip, arg) != 0)

            ERROR("Invalid host/IP address: %s\n", arg);

        stream->is_multicast = 1;

        stream->loop = 1; /* default is looping */

    } else if (!av_strcasecmp(cmd, "MulticastPort")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(&val, arg, 0, 1, 65535, config, line_num, "Invalid MulticastPort: %s\n", arg);

        stream->multicast_port = val;

    } else if (!av_strcasecmp(cmd, "MulticastTTL")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        ffserver_set_int_param(&val, arg, 0, INT_MIN, INT_MAX, config, line_num, "Invalid MulticastTTL: %s\n", arg);

        stream->multicast_ttl = val;

    } else if (!av_strcasecmp(cmd, "NoLoop")) {

        stream->loop = 0;

    } else if (!av_strcasecmp(cmd, "</Stream>")) {

        if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {

            if (config->audio_id != AV_CODEC_ID_NONE) {

                AVCodecContext *audio_enc = avcodec_alloc_context3(avcodec_find_encoder(config->audio_id));

                if (config->audio_preset &&

                    ffserver_opt_preset(arg, audio_enc, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_ENCODING_PARAM,

                                        NULL, NULL) < 0)

                    ERROR("Could not apply preset '%s'\n", arg);

                if (ffserver_apply_stream_config(audio_enc, config->audio_conf, &config->audio_opts) < 0)

                    config->errors++;

                add_codec(stream, audio_enc);

            }

            if (config->video_id != AV_CODEC_ID_NONE) {

                AVCodecContext *video_enc = avcodec_alloc_context3(avcodec_find_encoder(config->video_id));

                if (config->video_preset &&

                    ffserver_opt_preset(arg, video_enc, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_ENCODING_PARAM,

                                        NULL, NULL) < 0)

                    ERROR("Could not apply preset '%s'\n", arg);

                if (ffserver_apply_stream_config(video_enc, config->video_conf, &config->video_opts) < 0)

                    config->errors++;

                add_codec(stream, video_enc);

            }

        }

        av_dict_free(&config->video_opts);

        av_dict_free(&config->video_conf);

        av_dict_free(&config->audio_opts);

        av_dict_free(&config->audio_conf);

        av_freep(&config->video_preset);

        av_freep(&config->audio_preset);

        *pstream = NULL;

    } else if (!av_strcasecmp(cmd, "File") || !av_strcasecmp(cmd, "ReadOnlyFile")) {

        ffserver_get_arg(stream->feed_filename, sizeof(stream->feed_filename), p);

    } else {

        ERROR("Invalid entry '%s' inside <Stream></Stream>\n", cmd);

    }

    return 0;

  nomem:

    av_log(NULL, AV_LOG_ERROR, "Out of memory. Aborting.\n");

    av_dict_free(&config->video_opts);

    av_dict_free(&config->video_conf);

    av_dict_free(&config->audio_opts);

    av_dict_free(&config->audio_conf);

    av_freep(&config->video_preset);

    av_freep(&config->audio_preset);

    return AVERROR(ENOMEM);

}


static uint64_t omap_uwire_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (offset) {

    case 0x00:	/* RDR */

        s->control &= ~(1 << 15);			/* RDRB */

        return s->rxbuf;

    case 0x04:	/* CSR */

        return s->control;

    case 0x08:	/* SR1 */

        return s->setup[0];

    case 0x0c:	/* SR2 */

        return s->setup[1];

    case 0x10:	/* SR3 */

        return s->setup[2];

    case 0x14:	/* SR4 */

        return s->setup[3];

    case 0x18:	/* SR5 */

        return s->setup[4];

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr)

{

    sPAPRTCETable *tcet = container_of(iommu, sPAPRTCETable, iommu);

    uint64_t tce;

#ifdef DEBUG_TCE

    fprintf(stderr, "spapr_tce_translate liobn=0x%" PRIx32 " addr=0x"

            DMA_ADDR_FMT "\n", tcet->liobn, addr);

#endif

    if (tcet->bypass) {

        return (IOMMUTLBEntry) {

            .target_as = &address_space_memory,

            .iova = 0,

            .translated_addr = 0,

            .addr_mask = ~(hwaddr)0,

            .perm = IOMMU_RW,

        };

    }

    /* Check if we are in bound */

    if (addr >= tcet->window_size) {

#ifdef DEBUG_TCE

        fprintf(stderr, "spapr_tce_translate out of bounds\n");

#endif

        return (IOMMUTLBEntry) { .perm = IOMMU_NONE };

    }

    tce = tcet->table[addr >> SPAPR_TCE_PAGE_SHIFT].tce;

#ifdef DEBUG_TCE

    fprintf(stderr, " ->  *paddr=0x%llx, *len=0x%llx\n",

            (tce & ~SPAPR_TCE_PAGE_MASK), SPAPR_TCE_PAGE_MASK + 1);

#endif

    return (IOMMUTLBEntry) {

        .target_as = &address_space_memory,

        .iova = addr & ~SPAPR_TCE_PAGE_MASK,

        .translated_addr = tce & ~SPAPR_TCE_PAGE_MASK,

        .addr_mask = SPAPR_TCE_PAGE_MASK,

        .perm = tce,

    };

}


static int write_payload_3270(EmulatedCcw3270Device *dev, uint8_t cmd)

{

    Terminal3270 *t = TERMINAL_3270(dev);

    int retval = 0;

    int count = ccw_dstream_avail(get_cds(t));

    assert(count <= (OUTPUT_BUFFER_SIZE - 3) / 2);

    if (!t->handshake_done) {

        if (!(t->outv[0] == IAC && t->outv[1] != IAC)) {

            /*

             * Before having finished 3270 negotiation,

             * sending outbound data except protocol options is prohibited.

             */

            return 0;

        }

    }

    if (!qemu_chr_fe_backend_connected(&t->chr)) {

        /* We just say we consumed all data if there's no backend. */

        return count;

    }

    t->outv[0] = cmd;

    ccw_dstream_read_buf(get_cds(t), &t->outv[1], count);

    t->out_len = count + 1;

    t->out_len = insert_IAC_escape_char(t->outv, t->out_len);

    t->outv[t->out_len++] = IAC;

    t->outv[t->out_len++] = IAC_EOR;

    retval = qemu_chr_fe_write_all(&t->chr, t->outv, t->out_len);

    return (retval <= 0) ? 0 : (retval - 3);

}


static void qmp_output_start_struct(Visitor *v, const char *name, void **obj,

                                    size_t unused, Error **errp)

{

    QmpOutputVisitor *qov = to_qov(v);

    QDict *dict = qdict_new();

    qmp_output_add(qov, name, dict);

    qmp_output_push(qov, dict, obj);

}


static int xen_pt_word_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                                 uint16_t *val, uint16_t dev_value,

                                 uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint16_t writable_mask = 0;

    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    /* create value for writing to I/O device register */

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;

}


static void monitor_fdset_cleanup(MonFdset *mon_fdset)

{

    MonFdsetFd *mon_fdset_fd;

    MonFdsetFd *mon_fdset_fd_next;

    QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {

        if (mon_fdset_fd->removed ||

                (QLIST_EMPTY(&mon_fdset->dup_fds) && mon_refcount == 0)) {

            close(mon_fdset_fd->fd);

            g_free(mon_fdset_fd->opaque);

            QLIST_REMOVE(mon_fdset_fd, next);

            g_free(mon_fdset_fd);

        }

    }

    if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {

        QLIST_REMOVE(mon_fdset, next);

        g_free(mon_fdset);

    }

}


static int joint_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer1,

                         float *mlt_buffer2)

{

    int i, j, ret;

    int decouple_tab[SUBBAND_SIZE];

    float *decode_buffer = q->decode_buffer_0;

    int idx, cpl_tmp;

    float f1, f2;

    const float *cplscale;

    memset(decouple_tab, 0, sizeof(decouple_tab));

    memset(decode_buffer, 0, sizeof(q->decode_buffer_0));

    /* Make sure the buffers are zeroed out. */

    memset(mlt_buffer1, 0, 1024 * sizeof(*mlt_buffer1));

    memset(mlt_buffer2, 0, 1024 * sizeof(*mlt_buffer2));

    decouple_info(q, p, decouple_tab);

    if ((ret = mono_decode(q, p, decode_buffer)) < 0)

        return ret;

    /* The two channels are stored interleaved in decode_buffer. */

    for (i = 0; i < p->js_subband_start; i++) {

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

            mlt_buffer1[i * 20 + j] = decode_buffer[i * 40 + j];

            mlt_buffer2[i * 20 + j] = decode_buffer[i * 40 + 20 + j];

        }

    }

    /* When we reach js_subband_start (the higher frequencies)

       the coefficients are stored in a coupling scheme. */

    idx = (1 << p->js_vlc_bits) - 1;

    for (i = p->js_subband_start; i < p->subbands; i++) {

        cpl_tmp = cplband[i];

        idx -= decouple_tab[cpl_tmp];

        cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table

        f1 = cplscale[decouple_tab[cpl_tmp]];

        f2 = cplscale[idx - 1];

        q->decouple(q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);

        idx = (1 << p->js_vlc_bits) - 1;

    }

    return 0;

}


static av_cold int a64multi_encode_init(AVCodecContext *avctx)

{

    A64Context *c = avctx->priv_data;

    int a;

    av_lfg_init(&c->randctx, 1);

    if (avctx->global_quality < 1) {

        c->mc_lifetime = 4;

    } else {

        c->mc_lifetime = avctx->global_quality /= FF_QP2LAMBDA;

    }

    av_log(avctx, AV_LOG_INFO, "charset lifetime set to %d frame(s)\n", c->mc_lifetime);

    c->mc_frame_counter = 0;

    c->mc_use_5col      = avctx->codec->id == AV_CODEC_ID_A64_MULTI5;

    c->mc_pal_size      = 4 + c->mc_use_5col;

    /* precalc luma values for later use */

    for (a = 0; a < c->mc_pal_size; a++) {

        c->mc_luma_vals[a]=a64_palette[mc_colors[a]][0] * 0.30 +

                           a64_palette[mc_colors[a]][1] * 0.59 +

                           a64_palette[mc_colors[a]][2] * 0.11;

    }

    if (!(c->mc_meta_charset = av_malloc(32000 * c->mc_lifetime * sizeof(int))) ||

       !(c->mc_best_cb       = av_malloc(CHARSET_CHARS * 32 * sizeof(int)))     ||

       !(c->mc_charmap       = av_mallocz(1000 * c->mc_lifetime * sizeof(int))) ||

       !(c->mc_colram        = av_mallocz(CHARSET_CHARS * sizeof(uint8_t)))     ||

       !(c->mc_charset       = av_malloc(0x800 * (INTERLACED+1) * sizeof(uint8_t)))) {

        av_log(avctx, AV_LOG_ERROR, "Failed to allocate buffer memory.\n");

        return AVERROR(ENOMEM);

    }

    /* set up extradata */

    if (!(avctx->extradata = av_mallocz(8 * 4 + FF_INPUT_BUFFER_PADDING_SIZE))) {

        av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory for extradata.\n");

        return AVERROR(ENOMEM);

    }

    avctx->extradata_size = 8 * 4;

    AV_WB32(avctx->extradata, c->mc_lifetime);

    AV_WB32(avctx->extradata + 16, INTERLACED);

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame) {

        a64multi_close_encoder(avctx);

        return AVERROR(ENOMEM);

    }

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    avctx->coded_frame->key_frame = 1;

    if (!avctx->codec_tag)

         avctx->codec_tag = AV_RL32("a64m");

    c->next_pts = AV_NOPTS_VALUE;

    return 0;

}


static void calc_scales(DCAEncContext *c)

{

    int band, ch;

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

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

            c->scale_factor[band][ch] = calc_one_scale(c->peak_cb[band][ch],

                                                       c->abits[band][ch],

                                                       &c->quant[band][ch]);

    if (c->lfe_channel)

        c->lfe_scale_factor = calc_one_scale(c->lfe_peak_cb, 11, &c->lfe_quant);

}


static void rtc_update_timer(void *opaque)

{

    RTCState *s = opaque;

    int32_t irqs = REG_C_UF;

    int32_t new_irqs;

    assert((s->cmos_data[RTC_REG_A] & 0x60) != 0x60);

    /* UIP might have been latched, update time and clear it.  */

    rtc_update_time(s);

    s->cmos_data[RTC_REG_A] &= ~REG_A_UIP;

    if (check_alarm(s)) {

        irqs |= REG_C_AF;

        if (s->cmos_data[RTC_REG_B] & REG_B_AIE) {

            qemu_system_wakeup_request(QEMU_WAKEUP_REASON_RTC);

        }

    }

    new_irqs = irqs & ~s->cmos_data[RTC_REG_C];

    s->cmos_data[RTC_REG_C] |= irqs;

    if ((new_irqs & s->cmos_data[RTC_REG_B]) != 0) {

        s->cmos_data[RTC_REG_C] |= REG_C_IRQF;

        qemu_irq_raise(s->irq);

    }

    check_update_timer(s);

}


static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,

                            int is_user, hwaddr *phys_ptr,

                            int *prot, target_ulong *page_size)

{

    CPUState *cs = ENV_GET_CPU(env);

    int code;

    uint32_t table;

    uint32_t desc;

    uint32_t xn;

    uint32_t pxn = 0;

    int type;

    int ap;

    int domain = 0;

    int domain_prot;

    hwaddr phys_addr;

    /* Pagetable walk.  */

    /* Lookup l1 descriptor.  */

    table = get_level1_table_address(env, address);

    desc = ldl_phys(cs->as, table);

    type = (desc & 3);

    if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {

        /* Section translation fault, or attempt to use the encoding

         * which is Reserved on implementations without PXN.

         */

        code = 5;

        goto do_fault;

    }

    if ((type == 1) || !(desc & (1 << 18))) {

        /* Page or Section.  */

        domain = (desc >> 5) & 0x0f;

    }

    domain_prot = (env->cp15.c3 >> (domain * 2)) & 3;

    if (domain_prot == 0 || domain_prot == 2) {

        if (type != 1) {

            code = 9; /* Section domain fault.  */

        } else {

            code = 11; /* Page domain fault.  */

        }

        goto do_fault;

    }

    if (type != 1) {

        if (desc & (1 << 18)) {

            /* Supersection.  */

            phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);

            *page_size = 0x1000000;

        } else {

            /* Section.  */

            phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);

            *page_size = 0x100000;

        }

        ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);

        xn = desc & (1 << 4);

        pxn = desc & 1;

        code = 13;

    } else {

        if (arm_feature(env, ARM_FEATURE_PXN)) {

            pxn = (desc >> 2) & 1;

        }

        /* Lookup l2 entry.  */

        table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);

        desc = ldl_phys(cs->as, table);

        ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);

        switch (desc & 3) {

        case 0: /* Page translation fault.  */

            code = 7;

            goto do_fault;

        case 1: /* 64k page.  */

            phys_addr = (desc & 0xffff0000) | (address & 0xffff);

            xn = desc & (1 << 15);

            *page_size = 0x10000;

            break;

        case 2: case 3: /* 4k page.  */

            phys_addr = (desc & 0xfffff000) | (address & 0xfff);

            xn = desc & 1;

            *page_size = 0x1000;

            break;

        default:

            /* Never happens, but compiler isn't smart enough to tell.  */

            abort();

        }

        code = 15;

    }

    if (domain_prot == 3) {

        *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

    } else {

        if (pxn && !is_user) {

            xn = 1;

        }

        if (xn && access_type == 2)

            goto do_fault;

        /* The simplified model uses AP[0] as an access control bit.  */

        if ((env->cp15.c1_sys & (1 << 29)) && (ap & 1) == 0) {

            /* Access flag fault.  */

            code = (code == 15) ? 6 : 3;

            goto do_fault;

        }

        *prot = check_ap(env, ap, domain_prot, access_type, is_user);

        if (!*prot) {

            /* Access permission fault.  */

            goto do_fault;

        }

        if (!xn) {

            *prot |= PAGE_EXEC;

        }

    }

    *phys_ptr = phys_addr;

    return 0;

do_fault:

    return code | (domain << 4);

}


void nvdimm_build_acpi(GArray *table_offsets, GArray *table_data,

                       BIOSLinker *linker, GArray *dsm_dma_arrea)

{

    GSList *device_list;

    /* no NVDIMM device is plugged. */

    device_list = nvdimm_get_plugged_device_list();

    if (!device_list) {

        return;

    }

    nvdimm_build_nfit(device_list, table_offsets, table_data, linker);

    nvdimm_build_ssdt(device_list, table_offsets, table_data, linker,

                      dsm_dma_arrea);

    g_slist_free(device_list);

}


void spapr_core_release(DeviceState *dev)

{

    MachineState *ms = MACHINE(qdev_get_hotplug_handler(dev));

    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(ms);

    CPUCore *cc = CPU_CORE(dev);

    CPUArchId *core_slot = spapr_find_cpu_slot(ms, cc->core_id, NULL);

    if (smc->pre_2_10_has_unused_icps) {

        sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev));

        sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc));

        size_t size = object_type_get_instance_size(scc->cpu_type);

        int i;

        for (i = 0; i < cc->nr_threads; i++) {

            CPUState *cs = CPU(sc->threads + i * size);

            pre_2_10_vmstate_register_dummy_icp(cs->cpu_index);

        }

    }

    assert(core_slot);

    core_slot->cpu = NULL;

    object_unparent(OBJECT(dev));

}


static int parse_playlist(HLSContext *c, const char *url,

                          struct variant *var, AVIOContext *in)

{

    int ret = 0, is_segment = 0, is_variant = 0, bandwidth = 0;

    int64_t duration = 0;

    enum KeyType key_type = KEY_NONE;

    uint8_t iv[16] = "";

    int has_iv = 0;

    char key[MAX_URL_SIZE] = "";

    char line[1024];

    const char *ptr;

    int close_in = 0;

    if (!in) {

        AVDictionary *opts = NULL;

        close_in = 1;

        /* Some HLS servers don't like being sent the range header */

        av_dict_set(&opts, "seekable", "0", 0);

        // broker prior HTTP options that should be consistent across requests

        av_dict_set(&opts, "user-agent", c->user_agent, 0);

        av_dict_set(&opts, "cookies", c->cookies, 0);

        ret = avio_open2(&in, url, AVIO_FLAG_READ,

                         c->interrupt_callback, &opts);

        av_dict_free(&opts);

        if (ret < 0)

            return ret;

    }

    read_chomp_line(in, line, sizeof(line));

    if (strcmp(line, "#EXTM3U")) {

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    if (var) {

        free_segment_list(var);

        var->finished = 0;

    }

    while (!url_feof(in)) {

        read_chomp_line(in, line, sizeof(line));

        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {

            struct variant_info info = {{0}};

            is_variant = 1;

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,

                               &info);

            bandwidth = atoi(info.bandwidth);

        } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {

            struct key_info info = {{0}};

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,

                               &info);

            key_type = KEY_NONE;

            has_iv = 0;

            if (!strcmp(info.method, "AES-128"))

                key_type = KEY_AES_128;

            if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {

                ff_hex_to_data(iv, info.iv + 2);

                has_iv = 1;

            }

            av_strlcpy(key, info.uri, sizeof(key));

        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {

            if (!var) {

                var = new_variant(c, 0, url, NULL);

                if (!var) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

            var->target_duration = atoi(ptr) * AV_TIME_BASE;

        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {

            if (!var) {

                var = new_variant(c, 0, url, NULL);

                if (!var) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

            var->start_seq_no = atoi(ptr);

        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {

            if (var)

                var->finished = 1;

        } else if (av_strstart(line, "#EXTINF:", &ptr)) {

            is_segment = 1;

            duration   = atof(ptr) * AV_TIME_BASE;

        } else if (av_strstart(line, "#", NULL)) {

            continue;

        } else if (line[0]) {

            if (is_variant) {

                if (!new_variant(c, bandwidth, line, url)) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                is_variant = 0;

                bandwidth  = 0;

            }

            if (is_segment) {

                struct segment *seg;

                if (!var) {

                    var = new_variant(c, 0, url, NULL);

                    if (!var) {

                        ret = AVERROR(ENOMEM);

                        goto fail;

                    }

                }

                seg = av_malloc(sizeof(struct segment));

                if (!seg) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                seg->duration = duration;

                seg->key_type = key_type;

                if (has_iv) {

                    memcpy(seg->iv, iv, sizeof(iv));

                } else {

                    int seq = var->start_seq_no + var->n_segments;

                    memset(seg->iv, 0, sizeof(seg->iv));

                    AV_WB32(seg->iv + 12, seq);

                }

                ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);

                ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);

                dynarray_add(&var->segments, &var->n_segments, seg);

                is_segment = 0;

            }

        }

    }

    if (var)

        var->last_load_time = av_gettime();

fail:

    if (close_in)

        avio_close(in);

    return ret;

}


static void intra_predict_vert_16x16_msa(uint8_t *src, uint8_t *dst,

                                         int32_t dst_stride)

{

    uint32_t row;

    v16u8 src0;

    src0 = LD_UB(src);

    for (row = 16; row--;) {

        ST_UB(src0, dst);

        dst += dst_stride;

    }

}


static inline void mcdc(uint16_t *dst, uint16_t *src, int log2w, int h, int stride, int scale, int dc){

   int i;

   dc*= 0x10001;

   switch(log2w){

   case 0:

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

            dst[0] = scale*src[0] + dc;

            if(scale) src += stride;

            dst += stride;

        }

        break;

    case 1:

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

            LE_CENTRIC_MUL(dst, src, scale, dc);

            if(scale) src += stride;

            dst += stride;

        }

        break;

    case 2:

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

            LE_CENTRIC_MUL(dst,     src,     scale, dc);

            LE_CENTRIC_MUL(dst + 2, src + 2, scale, dc);

            if(scale) src += stride;

            dst += stride;

        }

        break;

    case 3:

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

            LE_CENTRIC_MUL(dst,     src,     scale, dc);

            LE_CENTRIC_MUL(dst + 2, src + 2, scale, dc);

            LE_CENTRIC_MUL(dst + 4, src + 4, scale, dc);

            LE_CENTRIC_MUL(dst + 6, src + 6, scale, dc);

            if(scale) src += stride;

            dst += stride;

        }

        break;

    default: assert(0);

    }

}


static void init_vlcs(void)

{

    static int done = 0;

    if (!done) {

        done = 1;

        init_vlc(&dc_lum_vlc, DC_VLC_BITS, 12,

                 vlc_dc_lum_bits, 1, 1,

                 vlc_dc_lum_code, 2, 2);

        init_vlc(&dc_chroma_vlc,  DC_VLC_BITS, 12,

                 vlc_dc_chroma_bits, 1, 1,

                 vlc_dc_chroma_code, 2, 2);

        init_vlc(&mv_vlc, MV_VLC_BITS, 17,

                 &mbMotionVectorTable[0][1], 2, 1,

                 &mbMotionVectorTable[0][0], 2, 1);

        init_vlc(&mbincr_vlc, MBINCR_VLC_BITS, 36,

                 &mbAddrIncrTable[0][1], 2, 1,

                 &mbAddrIncrTable[0][0], 2, 1);

        init_vlc(&mb_pat_vlc, MB_PAT_VLC_BITS, 64,

                 &mbPatTable[0][1], 2, 1,

                 &mbPatTable[0][0], 2, 1);

        init_vlc(&mb_ptype_vlc, MB_PTYPE_VLC_BITS, 7,

                 &table_mb_ptype[0][1], 2, 1,

                 &table_mb_ptype[0][0], 2, 1);

        init_vlc(&mb_btype_vlc, MB_BTYPE_VLC_BITS, 11,

                 &table_mb_btype[0][1], 2, 1,

                 &table_mb_btype[0][0], 2, 1);

        init_rl(&rl_mpeg1);

        init_rl(&rl_mpeg2);

        init_2d_vlc_rl(&rl_mpeg1);

        init_2d_vlc_rl(&rl_mpeg2);

    }

}


static void test_parse_invalid_path_subprocess(void)

{

    qemu_set_log_filename("/tmp/qemu-%d%d.log");

}


static void scsi_cancel_io(SCSIDevice *d, uint32_t tag)

{

    DPRINTF("scsi_cancel_io 0x%x\n", tag);

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, d);

    SCSIGenericReq *r;

    DPRINTF("Cancel tag=0x%x\n", tag);

    r = scsi_find_request(s, tag);

    if (r) {

        if (r->req.aiocb)

            bdrv_aio_cancel(r->req.aiocb);

        r->req.aiocb = NULL;

        scsi_req_dequeue(&r->req);

    }

}


static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)

{

    #define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL + CONFIG_HEVC_D3D11VA_HWACCEL + CONFIG_HEVC_VAAPI_HWACCEL + CONFIG_HEVC_VDPAU_HWACCEL)

    enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmt = pix_fmts;

    switch (sps->pix_fmt) {

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUVJ420P:

#if CONFIG_HEVC_DXVA2_HWACCEL

        *fmt++ = AV_PIX_FMT_DXVA2_VLD;

#endif

#if CONFIG_HEVC_D3D11VA_HWACCEL

        *fmt++ = AV_PIX_FMT_D3D11VA_VLD;

#endif

#if CONFIG_HEVC_VAAPI_HWACCEL

        *fmt++ = AV_PIX_FMT_VAAPI;

#endif

#if CONFIG_HEVC_VDPAU_HWACCEL

        *fmt++ = AV_PIX_FMT_VDPAU;

#endif

        break;

    case AV_PIX_FMT_YUV420P10:

#if CONFIG_HEVC_DXVA2_HWACCEL

        *fmt++ = AV_PIX_FMT_DXVA2_VLD;

#endif

#if CONFIG_HEVC_D3D11VA_HWACCEL

        *fmt++ = AV_PIX_FMT_D3D11VA_VLD;

#endif

#if CONFIG_HEVC_VAAPI_HWACCEL

        *fmt++ = AV_PIX_FMT_VAAPI;

#endif

        break;

    }

    *fmt++ = sps->pix_fmt;

    *fmt = AV_PIX_FMT_NONE;

    return ff_thread_get_format(s->avctx, pix_fmts);

}


av_cold void ff_fft_init_x86(FFTContext *s)

{

    int cpu_flags = av_get_cpu_flags();

#if ARCH_X86_32

    if (EXTERNAL_AMD3DNOW(cpu_flags)) {

        /* 3DNow! for K6-2/3 */

        s->imdct_calc = ff_imdct_calc_3dnow;

        s->imdct_half = ff_imdct_half_3dnow;

        s->fft_calc   = ff_fft_calc_3dnow;

    }

    if (EXTERNAL_AMD3DNOWEXT(cpu_flags)) {

        /* 3DNowEx for K7 */

        s->imdct_calc = ff_imdct_calc_3dnowext;

        s->imdct_half = ff_imdct_half_3dnowext;

        s->fft_calc   = ff_fft_calc_3dnowext;

    }

#endif

    if (EXTERNAL_SSE(cpu_flags)) {

        /* SSE for P3/P4/K8 */

        s->imdct_calc  = ff_imdct_calc_sse;

        s->imdct_half  = ff_imdct_half_sse;

        s->fft_permute = ff_fft_permute_sse;

        s->fft_calc    = ff_fft_calc_sse;

        s->fft_permutation = FF_FFT_PERM_SWAP_LSBS;

    }

    if (EXTERNAL_AVX(cpu_flags) && s->nbits >= 5) {

        /* AVX for SB */

        s->imdct_half      = ff_imdct_half_avx;

        s->fft_calc        = ff_fft_calc_avx;

        s->fft_permutation = FF_FFT_PERM_AVX;

    }

}


static void rtl8139_io_writew(void *opaque, uint8_t addr, uint32_t val)

{

    RTL8139State *s = opaque;

    addr &= 0xfe;

    switch (addr)

    {

        case IntrMask:

            rtl8139_IntrMask_write(s, val);

            break;

        case IntrStatus:

            rtl8139_IntrStatus_write(s, val);

            break;

        case MultiIntr:

            rtl8139_MultiIntr_write(s, val);

            break;

        case RxBufPtr:

            rtl8139_RxBufPtr_write(s, val);

            break;

        case BasicModeCtrl:

            rtl8139_BasicModeCtrl_write(s, val);

            break;

        case BasicModeStatus:

            rtl8139_BasicModeStatus_write(s, val);

            break;

        case NWayAdvert:

            DPRINTF("NWayAdvert write(w) val=0x%04x\n", val);

            s->NWayAdvert = val;

            break;

        case NWayLPAR:

            DPRINTF("forbidden NWayLPAR write(w) val=0x%04x\n", val);

            break;

        case NWayExpansion:

            DPRINTF("NWayExpansion write(w) val=0x%04x\n", val);

            s->NWayExpansion = val;

            break;

        case CpCmd:

            rtl8139_CpCmd_write(s, val);

            break;

        case IntrMitigate:

            rtl8139_IntrMitigate_write(s, val);

            break;

        default:

            DPRINTF("ioport write(w) addr=0x%x val=0x%04x via write(b)\n",

                addr, val);

            rtl8139_io_writeb(opaque, addr, val & 0xff);

            rtl8139_io_writeb(opaque, addr + 1, (val >> 8) & 0xff);

            break;

    }

}


static int pci_device_hot_remove(Monitor *mon, const char *pci_addr)

{

    PCIBus *root = pci_find_primary_bus();

    PCIDevice *d;

    int bus;

    unsigned slot;

    Error *local_err = NULL;

    if (!root) {

        monitor_printf(mon, "no primary PCI bus (if there are multiple"

                       " PCI roots, you must use device_del instead)");

        return -1;

    }

    if (pci_read_devaddr(mon, pci_addr, &bus, &slot)) {

        return -1;

    }

    d = pci_find_device(root, bus, PCI_DEVFN(slot, 0));

    if (!d) {

        monitor_printf(mon, "slot %d empty\n", slot);

        return -1;

    }

    qdev_unplug(&d->qdev, &local_err);

    if (local_err) {

        monitor_printf(mon, "%s\n", error_get_pretty(local_err));

        error_free(local_err);

        return -1;

    }

    return 0;

}


qcrypto_tls_creds_x509_load(QCryptoTLSCredsX509 *creds,
                            Error **errp)
{
    char *cacert = NULL, *cacrl = NULL, *cert = NULL,
        *key = NULL, *dhparams = NULL;
    int ret;
    int rv = -1;
    trace_qcrypto_tls_creds_x509_load(creds,
            creds->parent_obj.dir ? creds->parent_obj.dir : "<nodir>");
    if (creds->parent_obj.endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
        if (qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_CA_CERT,
                                       true, &cacert, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_CA_CRL,
                                       false, &cacrl, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_SERVER_CERT,
                                       true, &cert, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_SERVER_KEY,
                                       true, &key, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_DH_PARAMS,
                                       false, &dhparams, errp) < 0) {
    } else {
        if (qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_CA_CERT,
                                       true, &cacert, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_CLIENT_CERT,
                                       false, &cert, errp) < 0 ||
            qcrypto_tls_creds_get_path(&creds->parent_obj,
                                       QCRYPTO_TLS_CREDS_X509_CLIENT_KEY,
                                       false, &key, errp) < 0) {
    ret = gnutls_certificate_allocate_credentials(&creds->data);
    if (ret < 0) {
        error_setg(errp, "Cannot allocate credentials: '%s'",
                   gnutls_strerror(ret));
    ret = gnutls_certificate_set_x509_trust_file(creds->data,
                                                 cacert,
                                                 GNUTLS_X509_FMT_PEM);
    if (ret < 0) {
        error_setg(errp, "Cannot load CA certificate '%s': %s",
                   cacert, gnutls_strerror(ret));
    if (cert != NULL && key != NULL) {
        ret = gnutls_certificate_set_x509_key_file(creds->data,
                                                   cert, key,
                                                   GNUTLS_X509_FMT_PEM);
        if (ret < 0) {
            error_setg(errp, "Cannot load certificate '%s' & key '%s': %s",
                       cert, key, gnutls_strerror(ret));
    if (cacrl != NULL) {
        ret = gnutls_certificate_set_x509_crl_file(creds->data,
                                                   cacrl,
                                                   GNUTLS_X509_FMT_PEM);
        if (ret < 0) {
            error_setg(errp, "Cannot load CRL '%s': %s",
                       cacrl, gnutls_strerror(ret));
    if (creds->parent_obj.endpoint == QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
        if (qcrypto_tls_creds_get_dh_params_file(&creds->parent_obj, dhparams,
                                                 &creds->parent_obj.dh_params,
                                                 errp) < 0) {
        gnutls_certificate_set_dh_params(creds->data,
                                         creds->parent_obj.dh_params);
    rv = 0;
 cleanup:
    g_free(cacert);
    g_free(cacrl);
    g_free(cert);
    g_free(key);
    g_free(dhparams);
    return rv;


static void set_next_tick(rc4030State *s)

{

    qemu_irq_lower(s->timer_irq);

    uint32_t hz;

    hz = 1000 / (s->itr + 1);

    qemu_mod_timer(s->periodic_timer, qemu_get_clock(vm_clock) + ticks_per_sec / hz);

}


static void print_samplesref(AVFilterBufferRef *samplesref)

{

    const AVFilterBufferRefAudioProps *props = samplesref->audio;

    const int n = props->nb_samples * av_get_channel_layout_nb_channels(props->channel_layout);

    const uint16_t *p     = (uint16_t*)samplesref->data[0];

    const uint16_t *p_end = p + n;

    while (p < p_end) {

        fputc(*p    & 0xff, stdout);

        fputc(*p>>8 & 0xff, stdout);

        p++;

    }

    fflush(stdout);

}


static void test_media_insert(void)

{

    uint8_t dir;

    /* Insert media in drive. DSKCHK should not be reset until a step pulse

     * is sent. */

    qmp_discard_response("{'execute':'change', 'arguments':{"

                         " 'device':'floppy0', 'target': '%s' }}",

                         test_image);

    qmp_discard_response(""); /* ignore event

                                 (FIXME open -> open transition?!) */

    qmp_discard_response(""); /* ignore event */

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_set(dir, DSKCHG);

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_set(dir, DSKCHG);

    send_seek(0);

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_set(dir, DSKCHG);

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_set(dir, DSKCHG);

    /* Step to next track should clear DSKCHG bit. */

    send_seek(1);

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_clear(dir, DSKCHG);

    dir = inb(FLOPPY_BASE + reg_dir);

    assert_bit_clear(dir, DSKCHG);

}


void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)

{

    int64_t bitmap_size;

    if (enable) {

        if (bs->dirty_tracking == 0) {

            int64_t i;

            uint8_t test;

            bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);

            bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK;

            bitmap_size++;

            bs->dirty_bitmap = qemu_mallocz(bitmap_size);

            bs->dirty_tracking = enable;

            for(i = 0; i < bitmap_size; i++) test = bs->dirty_bitmap[i];

        }

    } else {

        if (bs->dirty_tracking != 0) {

            qemu_free(bs->dirty_bitmap);

            bs->dirty_tracking = enable;

        }

    }

}


static void quorum_aio_finalize(QuorumAIOCB *acb)

{

    BDRVQuorumState *s = acb->common.bs->opaque;

    int i, ret = 0;

    if (acb->vote_ret) {

        ret = acb->vote_ret;

    }

    acb->common.cb(acb->common.opaque, ret);

    if (acb->is_read) {

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

            qemu_vfree(acb->qcrs[i].buf);

            qemu_iovec_destroy(&acb->qcrs[i].qiov);

        }

    }

    g_free(acb->qcrs);

    qemu_aio_release(acb);

}


static int h261_decode_gob_header(H261Context *h){

    unsigned int val;

    MpegEncContext * const s = &h->s;

    /* Check for GOB Start Code */

    val = show_bits(&s->gb, 15);

    if(val)

        return -1;

    /* We have a GBSC */

    skip_bits(&s->gb, 16);

    h->gob_number = get_bits(&s->gb, 4); /* GN */

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

    /* GEI */

    while (get_bits1(&s->gb) != 0) {

        skip_bits(&s->gb, 8);

    }

    if(s->qscale==0)

        return -1;

    // For the first transmitted macroblock in a GOB, MBA is the absolute address. For

    // subsequent macroblocks, MBA is the difference between the absolute addresses of

    // the macroblock and the last transmitted macroblock.

    h->current_mba = 0;

    h->mba_diff = 0;

    return 0;

}


static int vhost_user_set_u64(struct vhost_dev *dev, int request, uint64_t u64)

{

    VhostUserMsg msg = {

        .request = request,

        .flags = VHOST_USER_VERSION,

        .u64 = u64,

        .size = sizeof(m.u64),

    };

    vhost_user_write(dev, &msg, NULL, 0);

    return 0;

}


static int read_rle_sgi(uint8_t *out_buf, SgiState *s)

{

    uint8_t *dest_row;

    unsigned int len = s->height * s->depth * 4;

    GetByteContext g_table = s->g;

    unsigned int y, z;

    unsigned int start_offset;

    /* size of  RLE offset and length tables */

    if (len * 2  > bytestream2_get_bytes_left(&s->g)) {

        return AVERROR_INVALIDDATA;

    }

    for (z = 0; z < s->depth; z++) {

        dest_row = out_buf;

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

            dest_row -= s->linesize;

            start_offset = bytestream2_get_be32(&g_table);

            bytestream2_seek(&s->g, start_offset, SEEK_SET);

            if (expand_rle_row(s, dest_row + z, dest_row + FFABS(s->linesize),

                               s->depth) != s->width) {

                return AVERROR_INVALIDDATA;

            }

        }

    }

    return 0;

}


static inline void RENAME(uyvyToY)(uint8_t *dst, const uint8_t *src, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "mov                  %0, %%"REG_a"         \n\t"

        "1:                                         \n\t"

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

        "movq 8(%1, %%"REG_a",2), %%mm1             \n\t"

        "psrlw                $8, %%mm0             \n\t"

        "psrlw                $8, %%mm1             \n\t"

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

        "movq              %%mm0, (%2, %%"REG_a")   \n\t"

        "add                  $8, %%"REG_a"         \n\t"

        " js                  1b                    \n\t"

        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)

        : "%"REG_a

    );

#else

    int i;

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

        dst[i]= src[2*i+1];

#endif

}


static inline void RENAME(yv12toyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

                                      long width, long height,

                                      long lumStride, long chromStride, long dstStride)

{

    //FIXME interpolate chroma

    RENAME(yuvPlanartoyuy2)(ysrc, usrc, vsrc, dst, width, height, lumStride, chromStride, dstStride, 2);

}


static av_always_inline void filter_common(uint8_t *p, ptrdiff_t stride, int is4tap)

{

    LOAD_PIXELS

    int a, f1, f2;

    const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    a = 3*(q0 - p0);

    if (is4tap)

        a += clip_int8(p1 - q1);

    a = clip_int8(a);

    // We deviate from the spec here with c(a+3) >> 3

    // since that's what libvpx does.

    f1 = FFMIN(a+4, 127) >> 3;

    f2 = FFMIN(a+3, 127) >> 3;

    // Despite what the spec says, we do need to clamp here to

    // be bitexact with libvpx.

    p[-1*stride] = cm[p0 + f2];

    p[ 0*stride] = cm[q0 - f1];

    // only used for _inner on blocks without high edge variance

    if (!is4tap) {

        a = (f1+1)>>1;

        p[-2*stride] = cm[p1 + a];

        p[ 1*stride] = cm[q1 - a];

    }

}


static int theora_decode_init(AVCodecContext *avctx)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    int ptype;

    uint8_t *p= avctx->extradata;

    int op_bytes, i;

    s->theora = 1;

    if (!avctx->extradata_size)

    {

        av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");

        return -1;

    }

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

    op_bytes = *(p++)<<8;

    op_bytes += *(p++);

    init_get_bits(&gb, p, op_bytes);

    p += op_bytes;

    ptype = get_bits(&gb, 8);

    debug_vp3("Theora headerpacket type: %x\n", ptype);

     if (!(ptype & 0x80))

     {

        av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");

        return -1;

     }

    // FIXME: check for this aswell

    skip_bits(&gb, 6*8); /* "theora" */

    switch(ptype)

    {

        case 0x80:

            theora_decode_header(avctx, gb);

                break;

        case 0x81:

// FIXME: is this needed? it breaks sometimes

//            theora_decode_comments(avctx, gb);

            break;

        case 0x82:

            theora_decode_tables(avctx, gb);

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unknown Theora config packet: %d\n", ptype&~0x80);

            break;

    }

  }

    vp3_decode_init(avctx);

    return 0;

}


static av_cold int pcm_encode_init(AVCodecContext *avctx)

{

    avctx->frame_size = 0;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_PCM_ALAW:

        pcm_alaw_tableinit();

        break;

    case AV_CODEC_ID_PCM_MULAW:

        pcm_ulaw_tableinit();

        break;

    default:

        break;

    }

    avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);

    avctx->block_align           = avctx->channels * avctx->bits_per_coded_sample / 8;

    avctx->bit_rate              = avctx->block_align * avctx->sample_rate * 8;

    avctx->coded_frame           = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


static void write_packet(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)

{

    AVStream *st = ost->st;

    int ret;

    /*

     * Audio encoders may split the packets --  #frames in != #packets out.

     * But there is no reordering, so we can limit the number of output packets

     * by simply dropping them here.

     * Counting encoded video frames needs to be done separately because of

     * reordering, see do_video_out()

     */

    if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {

        if (ost->frame_number >= ost->max_frames) {

            av_packet_unref(pkt);

            return;

        }

        ost->frame_number++;

    }

    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

        uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,

                                              NULL);

        ost->quality = sd ? *(int *)sd : -1;

        if (ost->frame_rate.num) {

            pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),

                                         ost->st->time_base);

        }

    }

    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&

        ost->last_mux_dts != AV_NOPTS_VALUE &&

        pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {

        av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "

               "%d:%d; previous: %"PRId64", current: %"PRId64"; ",

               ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);

        if (exit_on_error) {

            av_log(NULL, AV_LOG_FATAL, "aborting.\n");

            exit_program(1);

        }

        av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "

               "in incorrect timestamps in the output file.\n",

               ost->last_mux_dts + 1);

        pkt->dts = ost->last_mux_dts + 1;

        if (pkt->pts != AV_NOPTS_VALUE)

            pkt->pts = FFMAX(pkt->pts, pkt->dts);

    }

    ost->last_mux_dts = pkt->dts;

    ost->data_size += pkt->size;

    ost->packets_written++;

    pkt->stream_index = ost->index;

    ret = av_interleaved_write_frame(s, pkt);

    if (ret < 0) {

        print_error("av_interleaved_write_frame()", ret);

        exit_program(1);

    }

}


void MPV_decode_mb_internal(MpegEncContext *s, DCTELEM block[12][64],

                            int lowres_flag, int is_mpeg12)

{

    int mb_x, mb_y;

    const int mb_xy = s->mb_y * s->mb_stride + s->mb_x;

#if CONFIG_MPEG_XVMC_DECODER

    if(s->avctx->xvmc_acceleration){

        ff_xvmc_decode_mb(s);//xvmc uses pblocks

        return;

    }

#endif

    mb_x = s->mb_x;

    mb_y = s->mb_y;

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

       /* save DCT coefficients */

       int i,j;

       DCTELEM *dct = &s->current_picture.dct_coeff[mb_xy*64*6];

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

           for(j=0; j<64; j++)

               *dct++ = block[i][s->dsp.idct_permutation[j]];

    }

    s->current_picture.qscale_table[mb_xy]= s->qscale;

    /* update DC predictors for P macroblocks */

    if (!s->mb_intra) {

        if (!is_mpeg12 && (s->h263_pred || s->h263_aic)) {

            if(s->mbintra_table[mb_xy])

                ff_clean_intra_table_entries(s);

        } else {

            s->last_dc[0] =

            s->last_dc[1] =

            s->last_dc[2] = 128 << s->intra_dc_precision;

        }

    }

    else if (!is_mpeg12 && (s->h263_pred || s->h263_aic))

        s->mbintra_table[mb_xy]=1;

    if ((s->flags&CODEC_FLAG_PSNR) || !(s->encoding && (s->intra_only || s->pict_type==FF_B_TYPE) && s->avctx->mb_decision != FF_MB_DECISION_RD)) { //FIXME precalc

        uint8_t *dest_y, *dest_cb, *dest_cr;

        int dct_linesize, dct_offset;

        op_pixels_func (*op_pix)[4];

        qpel_mc_func (*op_qpix)[16];

        const int linesize= s->current_picture.linesize[0]; //not s->linesize as this would be wrong for field pics

        const int uvlinesize= s->current_picture.linesize[1];

        const int readable= s->pict_type != FF_B_TYPE || s->encoding || s->avctx->draw_horiz_band || lowres_flag;

        const int block_size= lowres_flag ? 8>>s->avctx->lowres : 8;

        /* avoid copy if macroblock skipped in last frame too */

        /* skip only during decoding as we might trash the buffers during encoding a bit */

        if(!s->encoding){

            uint8_t *mbskip_ptr = &s->mbskip_table[mb_xy];

            const int age= s->current_picture.age;

            assert(age);

            if (s->mb_skipped) {

                s->mb_skipped= 0;

                assert(s->pict_type!=FF_I_TYPE);

                (*mbskip_ptr) ++; /* indicate that this time we skipped it */

                if(*mbskip_ptr >99) *mbskip_ptr= 99;

                /* if previous was skipped too, then nothing to do !  */

                if (*mbskip_ptr >= age && s->current_picture.reference){

                    return;

                }

            } else if(!s->current_picture.reference){

                (*mbskip_ptr) ++; /* increase counter so the age can be compared cleanly */

                if(*mbskip_ptr >99) *mbskip_ptr= 99;

            } else{

                *mbskip_ptr = 0; /* not skipped */

            }

        }

        dct_linesize = linesize << s->interlaced_dct;

        dct_offset =(s->interlaced_dct)? linesize : linesize*block_size;

        if(readable){

            dest_y=  s->dest[0];

            dest_cb= s->dest[1];

            dest_cr= s->dest[2];

        }else{

            dest_y = s->b_scratchpad;

            dest_cb= s->b_scratchpad+16*linesize;

            dest_cr= s->b_scratchpad+32*linesize;

        }

        if (!s->mb_intra) {

            /* motion handling */

            /* decoding or more than one mb_type (MC was already done otherwise) */

            if(!s->encoding){

                if(lowres_flag){

                    h264_chroma_mc_func *op_pix = s->dsp.put_h264_chroma_pixels_tab;

                    if (s->mv_dir & MV_DIR_FORWARD) {

                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix);

                        op_pix = s->dsp.avg_h264_chroma_pixels_tab;

                    }

                    if (s->mv_dir & MV_DIR_BACKWARD) {

                        MPV_motion_lowres(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix);

                    }

                }else{

                    op_qpix= s->me.qpel_put;

                    if ((!s->no_rounding) || s->pict_type==FF_B_TYPE){

                        op_pix = s->dsp.put_pixels_tab;

                    }else{

                        op_pix = s->dsp.put_no_rnd_pixels_tab;

                    }

                    if (s->mv_dir & MV_DIR_FORWARD) {

                        MPV_motion(s, dest_y, dest_cb, dest_cr, 0, s->last_picture.data, op_pix, op_qpix);

                        op_pix = s->dsp.avg_pixels_tab;

                        op_qpix= s->me.qpel_avg;

                    }

                    if (s->mv_dir & MV_DIR_BACKWARD) {

                        MPV_motion(s, dest_y, dest_cb, dest_cr, 1, s->next_picture.data, op_pix, op_qpix);

                    }

                }

            }

            /* skip dequant / idct if we are really late ;) */

            if(s->hurry_up>1) goto skip_idct;

            if(s->avctx->skip_idct){

                if(  (s->avctx->skip_idct >= AVDISCARD_NONREF && s->pict_type == FF_B_TYPE)

                   ||(s->avctx->skip_idct >= AVDISCARD_NONKEY && s->pict_type != FF_I_TYPE)

                   || s->avctx->skip_idct >= AVDISCARD_ALL)

                    goto skip_idct;

            }

            /* add dct residue */

            if(s->encoding || !(   s->h263_msmpeg4 || s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO

                                || (s->codec_id==CODEC_ID_MPEG4 && !s->mpeg_quant))){

                add_dequant_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                add_dequant_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                add_dequant_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                add_dequant_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    if (s->chroma_y_shift){

                        add_dequant_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_linesize >>= 1;

                        dct_offset >>=1;

                        add_dequant_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        add_dequant_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            } else if(is_mpeg12 || (s->codec_id != CODEC_ID_WMV2)){

                add_dct(s, block[0], 0, dest_y                          , dct_linesize);

                add_dct(s, block[1], 1, dest_y              + block_size, dct_linesize);

                add_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize);

                add_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize);

                if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){//Chroma420

                        add_dct(s, block[4], 4, dest_cb, uvlinesize);

                        add_dct(s, block[5], 5, dest_cr, uvlinesize);

                    }else{

                        //chroma422

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;

                        add_dct(s, block[4], 4, dest_cb, dct_linesize);

                        add_dct(s, block[5], 5, dest_cr, dct_linesize);

                        add_dct(s, block[6], 6, dest_cb+dct_offset, dct_linesize);

                        add_dct(s, block[7], 7, dest_cr+dct_offset, dct_linesize);

                        if(!s->chroma_x_shift){//Chroma444

                            add_dct(s, block[8], 8, dest_cb+8, dct_linesize);

                            add_dct(s, block[9], 9, dest_cr+8, dct_linesize);

                            add_dct(s, block[10], 10, dest_cb+8+dct_offset, dct_linesize);

                            add_dct(s, block[11], 11, dest_cr+8+dct_offset, dct_linesize);

                        }

                    }

                }//fi gray

            }

            else if (CONFIG_WMV2) {

                ff_wmv2_add_mb(s, block, dest_y, dest_cb, dest_cr);

            }

        } else {

            /* dct only in intra block */

            if(s->encoding || !(s->codec_id==CODEC_ID_MPEG1VIDEO || s->codec_id==CODEC_ID_MPEG2VIDEO)){

                put_dct(s, block[0], 0, dest_y                          , dct_linesize, s->qscale);

                put_dct(s, block[1], 1, dest_y              + block_size, dct_linesize, s->qscale);

                put_dct(s, block[2], 2, dest_y + dct_offset             , dct_linesize, s->qscale);

                put_dct(s, block[3], 3, dest_y + dct_offset + block_size, dct_linesize, s->qscale);

                if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){

                        put_dct(s, block[4], 4, dest_cb, uvlinesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr, uvlinesize, s->chroma_qscale);

                    }else{

                        dct_offset >>=1;

                        dct_linesize >>=1;

                        put_dct(s, block[4], 4, dest_cb,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[5], 5, dest_cr,              dct_linesize, s->chroma_qscale);

                        put_dct(s, block[6], 6, dest_cb + dct_offset, dct_linesize, s->chroma_qscale);

                        put_dct(s, block[7], 7, dest_cr + dct_offset, dct_linesize, s->chroma_qscale);

                    }

                }

            }else{

                s->dsp.idct_put(dest_y                          , dct_linesize, block[0]);

                s->dsp.idct_put(dest_y              + block_size, dct_linesize, block[1]);

                s->dsp.idct_put(dest_y + dct_offset             , dct_linesize, block[2]);

                s->dsp.idct_put(dest_y + dct_offset + block_size, dct_linesize, block[3]);

                if(!CONFIG_GRAY || !(s->flags&CODEC_FLAG_GRAY)){

                    if(s->chroma_y_shift){

                        s->dsp.idct_put(dest_cb, uvlinesize, block[4]);

                        s->dsp.idct_put(dest_cr, uvlinesize, block[5]);

                    }else{

                        dct_linesize = uvlinesize << s->interlaced_dct;

                        dct_offset =(s->interlaced_dct)? uvlinesize : uvlinesize*8;

                        s->dsp.idct_put(dest_cb,              dct_linesize, block[4]);

                        s->dsp.idct_put(dest_cr,              dct_linesize, block[5]);

                        s->dsp.idct_put(dest_cb + dct_offset, dct_linesize, block[6]);

                        s->dsp.idct_put(dest_cr + dct_offset, dct_linesize, block[7]);

                        if(!s->chroma_x_shift){//Chroma444

                            s->dsp.idct_put(dest_cb + 8,              dct_linesize, block[8]);

                            s->dsp.idct_put(dest_cr + 8,              dct_linesize, block[9]);

                            s->dsp.idct_put(dest_cb + 8 + dct_offset, dct_linesize, block[10]);

                            s->dsp.idct_put(dest_cr + 8 + dct_offset, dct_linesize, block[11]);

                        }

                    }

                }//gray

            }

        }

skip_idct:

        if(!readable){

            s->dsp.put_pixels_tab[0][0](s->dest[0], dest_y ,   linesize,16);

            s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[1], dest_cb, uvlinesize,16 >> s->chroma_y_shift);

            s->dsp.put_pixels_tab[s->chroma_x_shift][0](s->dest[2], dest_cr, uvlinesize,16 >> s->chroma_y_shift);

        }

    }

}


void ff_aac_apply_tns(SingleChannelElement *sce)

{

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

    float *coef = sce->pcoeffs;

    TemporalNoiseShaping *tns = &sce->tns;

    int w, filt, m, i;

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

    float *lpc, tmp[TNS_MAX_ORDER+1];

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

        bottom = sce->ics.num_swb;

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

            top    = bottom;

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

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

            lpc    = tns->coef[w][filt];

            if (!order)

                continue;

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

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

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

                continue;

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

                inc = -1;

                start = end - 1;

            } else {

                inc = 1;

            }

            start += w * 128;

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

                // ar filter

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

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

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

            } else {

                // ma filter

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

                    tmp[0] = coef[start];

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

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

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

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

                }

            }

        }

    }

}


void qcow2_free_clusters(BlockDriverState *bs,

                          int64_t offset, int64_t size)

{

    int ret;

    BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_FREE);

    ret = update_refcount(bs, offset, size, -1);

    if (ret < 0) {

        fprintf(stderr, "qcow2_free_clusters failed: %s\n", strerror(-ret));

        abort();

    }

}


static void do_video_stats(AVOutputStream *ost,

                         AVInputStream *ist,

                         int frame_size)

{

    static FILE *fvstats=NULL;

    static INT64 total_size = 0;

    struct tm *today;

    time_t today2;

    char filename[40];

    AVCodecContext *enc;

    int frame_number;

    INT64 ti;

    double ti1, bitrate, avg_bitrate;

    if (!fvstats) {

        today2 = time(NULL);

        today = localtime(&today2);

        sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,

                                               today->tm_min,

                                               today->tm_sec);

        fvstats = fopen(filename,"w");

        if (!fvstats) {

            perror("fopen");

            exit(1);

        }

    }

    ti = MAXINT64;

    enc = &ost->st->codec;

    total_size += frame_size;

    if (enc->codec_type == CODEC_TYPE_VIDEO) {

        frame_number = ist->frame_number;

        fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);

        if (do_psnr)

            fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);

        fprintf(fvstats,"f_size= %6d ", frame_size);

        /* compute min pts value */

        if (!ist->discard && ist->pts < ti) {

            ti = ist->pts;

        }

        ti1 = (double)ti / 1000000.0;

        if (ti1 < 0.01)

            ti1 = 0.01;

        bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;

        avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;

        fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",

            (double)total_size / 1024, ti1, bitrate, avg_bitrate);

        fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");

    }

}


static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)

{

    int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);

    if (action == BLOCK_ERR_IGNORE) {

        bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);

        return 0;

    }

    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)

            || action == BLOCK_ERR_STOP_ANY) {

        type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;

        r->status |= SCSI_REQ_STATUS_RETRY | type;

        bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);

        vm_stop(VMSTOP_DISKFULL);

    } else {

        if (type == SCSI_REQ_STATUS_RETRY_READ) {

            scsi_req_data(&r->req, 0);

        }

        scsi_command_complete(r, CHECK_CONDITION,

                HARDWARE_ERROR);

        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);

    }

    return 1;

}


static gboolean qio_channel_websock_handshake_io(QIOChannel *ioc,

                                                 GIOCondition condition,

                                                 gpointer user_data)

{

    QIOTask *task = user_data;

    QIOChannelWebsock *wioc = QIO_CHANNEL_WEBSOCK(

        qio_task_get_source(task));

    Error *err = NULL;

    int ret;

    ret = qio_channel_websock_handshake_read(wioc, &err);

    if (ret < 0) {

        trace_qio_channel_websock_handshake_fail(ioc);

        qio_task_abort(task, err);

        error_free(err);

        return FALSE;

    }

    if (ret == 0) {

        trace_qio_channel_websock_handshake_pending(ioc, G_IO_IN);

        /* need more data still */

        return TRUE;

    }

    object_ref(OBJECT(task));

    trace_qio_channel_websock_handshake_reply(ioc);

    qio_channel_add_watch(

        wioc->master,

        G_IO_OUT,

        qio_channel_websock_handshake_send,

        task,

        (GDestroyNotify)object_unref);

    return FALSE;

}


static int find_debugfs(char *debugfs)

{

    char type[100];

    FILE *fp;

    fp = fopen("/proc/mounts", "r");

    if (fp == NULL) {

        return 0;

    }

    while (fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n",

                  debugfs, type) == 2) {

        if (strcmp(type, "debugfs") == 0) {

            break;

        }

    }

    fclose(fp);

    if (strcmp(type, "debugfs") != 0) {

        return 0;

    }

    return 1;

}


void qemu_input_event_send(QemuConsole *src, InputEvent *evt)

{

    QemuInputHandlerState *s;

    if (!runstate_is_running() && !runstate_check(RUN_STATE_SUSPENDED)) {

    qemu_input_event_trace(src, evt);

    /* pre processing */

    if (graphic_rotate && (evt->kind == INPUT_EVENT_KIND_ABS)) {

            qemu_input_transform_abs_rotate(evt);

    /* send event */

    s = qemu_input_find_handler(1 << evt->kind);

    s->handler->event(s->dev, src, evt);

    s->events++;


static int qemu_chr_fe_write_buffer(CharDriverState *s, const uint8_t *buf, int len, int *offset)

{

    int res = 0;

    *offset = 0;

    qemu_mutex_lock(&s->chr_write_lock);

    while (*offset < len) {

        do {

            res = s->chr_write(s, buf + *offset, len - *offset);

            if (res == -1 && errno == EAGAIN) {

                g_usleep(100);

            }

        } while (res == -1 && errno == EAGAIN);

        if (res <= 0) {

            break;

        }

        *offset += res;

    }

    if (*offset > 0) {

        qemu_chr_fe_write_log(s, buf, *offset);

    }

    qemu_mutex_unlock(&s->chr_write_lock);

    return res;

}


VLANClientState *qdev_get_vlan_client(DeviceState *dev,

                                      NetCanReceive *can_receive,

                                      NetReceive *receive,

                                      NetReceiveIOV *receive_iov,

                                      NetCleanup *cleanup,

                                      void *opaque)

{

    NICInfo *nd = dev->nd;

    assert(nd);

    return qemu_new_vlan_client(nd->vlan, nd->model, nd->name, can_receive,

                                receive, receive_iov, cleanup, opaque);

}


static int send_sub_rect_nojpeg(VncState *vs, int x, int y, int w, int h,

                                int bg, int fg, int colors, VncPalette *palette)

{

    int ret;

    if (colors == 0) {

        if (tight_detect_smooth_image(vs, w, h)) {

            ret = send_gradient_rect(vs, x, y, w, h);

            ret = send_full_color_rect(vs, x, y, w, h);

        }

    } else if (colors == 1) {

        ret = send_solid_rect(vs);

    } else if (colors == 2) {

        ret = send_mono_rect(vs, x, y, w, h, bg, fg);

    } else if (colors <= 256) {

        ret = send_palette_rect(vs, x, y, w, h, palette);

    }

    return ret;

}


static int guess_disk_lchs(IDEState *s,

                           int *pcylinders, int *pheads, int *psectors)

{

    uint8_t *buf;

    int ret, i, heads, sectors, cylinders;

    struct partition *p;

    uint32_t nr_sects;

    buf = qemu_memalign(512, 512);

    if (buf == NULL)

        return -1;

    ret = bdrv_read(s->bs, 0, buf, 1);

    if (ret < 0) {

        qemu_free(buf);

        return -1;

    }

    /* test msdos magic */

    if (buf[510] != 0x55 || buf[511] != 0xaa) {

        qemu_free(buf);

        return -1;

    }

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

        p = ((struct partition *)(buf + 0x1be)) + i;

        nr_sects = le32_to_cpu(p->nr_sects);

        if (nr_sects && p->end_head) {

            /* We make the assumption that the partition terminates on

               a cylinder boundary */

            heads = p->end_head + 1;

            sectors = p->end_sector & 63;

            if (sectors == 0)

                continue;

            cylinders = s->nb_sectors / (heads * sectors);

            if (cylinders < 1 || cylinders > 16383)

                continue;

            *pheads = heads;

            *psectors = sectors;

            *pcylinders = cylinders;

#if 0

            printf("guessed geometry: LCHS=%d %d %d\n",

                   cylinders, heads, sectors);

#endif

            qemu_free(buf);

            return 0;

        }

    }

    qemu_free(buf);

    return -1;

}


USBDevice *usb_host_device_open(USBBus *bus, const char *devname)

{

    struct USBAutoFilter filter;

    USBDevice *dev;

    char *p;

    dev = usb_create(bus, "usb-host");

    if (strstr(devname, "auto:")) {

        if (parse_filter(devname, &filter) < 0) {

            goto fail;

        }

    } else {

        p = strchr(devname, '.');

        if (p) {

            filter.bus_num    = strtoul(devname, NULL, 0);

            filter.addr       = strtoul(p + 1, NULL, 0);

            filter.vendor_id  = 0;

            filter.product_id = 0;

        } else {

            p = strchr(devname, ':');

            if (p) {

                filter.bus_num    = 0;

                filter.addr       = 0;

                filter.vendor_id  = strtoul(devname, NULL, 16);

                filter.product_id = strtoul(p + 1, NULL, 16);

            } else {

                goto fail;

            }

        }

    }

    qdev_prop_set_uint32(&dev->qdev, "hostbus",   filter.bus_num);

    qdev_prop_set_uint32(&dev->qdev, "hostaddr",  filter.addr);

    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);

    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);

    qdev_init_nofail(&dev->qdev);

    return dev;

fail:

    object_unparent(OBJECT(dev));

    return NULL;

}


static void xlnx_dp_set_dpdma(Object *obj, const char *name, Object *val,

                              Error **errp)

{

    XlnxDPState *s = XLNX_DP(obj);

    if (s->console) {

        DisplaySurface *surface = qemu_console_surface(s->console);

        XlnxDPDMAState *dma = XLNX_DPDMA(val);

        xlnx_dpdma_set_host_data_location(dma, DP_GRAPHIC_DMA_CHANNEL,

                                          surface_data(surface));

    }

}


static int ff_interleave_new_audio_packet(AVFormatContext *s, AVPacket *pkt,

                                   int stream_index, int flush)

{

    AVStream *st = s->streams[stream_index];

    AudioInterleaveContext *aic = st->priv_data;

    int size = FFMIN(av_fifo_size(aic->fifo), *aic->samples * aic->sample_size);

    if (!size || (!flush && size == av_fifo_size(aic->fifo)))

        return 0;

    av_new_packet(pkt, size);

    av_fifo_generic_read(aic->fifo, pkt->data, size, NULL);

    pkt->dts = pkt->pts = aic->dts;

    pkt->duration = av_rescale_q(*aic->samples, st->time_base, aic->time_base);

    pkt->stream_index = stream_index;

    aic->dts += pkt->duration;

    aic->samples++;

    if (!*aic->samples)

        aic->samples = aic->samples_per_frame;

    return size;

}


static int alloc_tables(H264Context *h){

    MpegEncContext * const s = &h->s;

    const int big_mb_num= s->mb_stride * (s->mb_height+1);

    int x,y;

    CHECKED_ALLOCZ(h->intra4x4_pred_mode, big_mb_num * 8  * sizeof(uint8_t))

    CHECKED_ALLOCZ(h->non_zero_count    , big_mb_num * 16 * sizeof(uint8_t))

    CHECKED_ALLOCZ(h->slice_table_base  , (big_mb_num+s->mb_stride) * sizeof(*h->slice_table_base))

    CHECKED_ALLOCZ(h->cbp_table, big_mb_num * sizeof(uint16_t))

    CHECKED_ALLOCZ(h->chroma_pred_mode_table, big_mb_num * sizeof(uint8_t))

    CHECKED_ALLOCZ(h->mvd_table[0], 32*big_mb_num * sizeof(uint16_t));

    CHECKED_ALLOCZ(h->mvd_table[1], 32*big_mb_num * sizeof(uint16_t));

    CHECKED_ALLOCZ(h->direct_table, 32*big_mb_num * sizeof(uint8_t));

    memset(h->slice_table_base, -1, (big_mb_num+s->mb_stride)  * sizeof(*h->slice_table_base));

    h->slice_table= h->slice_table_base + s->mb_stride*2 + 1;

    CHECKED_ALLOCZ(h->mb2b_xy  , big_mb_num * sizeof(uint32_t));

    CHECKED_ALLOCZ(h->mb2b8_xy , big_mb_num * sizeof(uint32_t));

    for(y=0; y<s->mb_height; y++){

        for(x=0; x<s->mb_width; x++){

            const int mb_xy= x + y*s->mb_stride;

            const int b_xy = 4*x + 4*y*h->b_stride;

            const int b8_xy= 2*x + 2*y*h->b8_stride;

            h->mb2b_xy [mb_xy]= b_xy;

            h->mb2b8_xy[mb_xy]= b8_xy;

        }

    }

    s->obmc_scratchpad = NULL;

    if(!h->dequant4_coeff[0])

        init_dequant_tables(h);

    return 0;

fail:

    free_tables(h);

    return -1;

}


static int decode_nal_sei_frame_packing_arrangement(HEVCContext *s)

{

    GetBitContext *gb = &s->HEVClc->gb;

    get_ue_golomb(gb);                  // frame_packing_arrangement_id

    s->sei_frame_packing_present = !get_bits1(gb);

    if (s->sei_frame_packing_present) {

        s->frame_packing_arrangement_type = get_bits(gb, 7);

        s->quincunx_subsampling           = get_bits1(gb);

        s->content_interpretation_type    = get_bits(gb, 6);

        // the following skips spatial_flipping_flag frame0_flipped_flag

        // field_views_flag current_frame_is_frame0_flag

        // frame0_self_contained_flag frame1_self_contained_flag

        skip_bits(gb, 6);

        if (!s->quincunx_subsampling && s->frame_packing_arrangement_type != 5)

            skip_bits(gb, 16);  // frame[01]_grid_position_[xy]

        skip_bits(gb, 8);       // frame_packing_arrangement_reserved_byte

        skip_bits1(gb);         // frame_packing_arrangement_persistance_flag

    }

    skip_bits1(gb);             // upsampled_aspect_ratio_flag

    return 0;

}


static int decode_frame_header(ProresContext *ctx, const uint8_t *buf,

                               const int data_size, AVCodecContext *avctx)

{

    int hdr_size, width, height, flags;

    int version;

    const uint8_t *ptr;

    hdr_size = AV_RB16(buf);

    av_dlog(avctx, "header size %d\n", hdr_size);

    if (hdr_size > data_size) {

        av_log(avctx, AV_LOG_ERROR, "error, wrong header size\n");

        return AVERROR_INVALIDDATA;

    }

    version = AV_RB16(buf + 2);

    av_dlog(avctx, "%.4s version %d\n", buf+4, version);

    if (version > 1) {

        av_log(avctx, AV_LOG_ERROR, "unsupported version: %d\n", version);

        return AVERROR_PATCHWELCOME;

    }

    width  = AV_RB16(buf + 8);

    height = AV_RB16(buf + 10);

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

        av_log(avctx, AV_LOG_ERROR, "picture resolution change: %dx%d -> %dx%d\n",

               avctx->width, avctx->height, width, height);

        return AVERROR_PATCHWELCOME;

    }

    ctx->frame_type = (buf[12] >> 2) & 3;

    ctx->alpha_info = buf[17] & 0xf;

    if (ctx->alpha_info > 2) {

        av_log(avctx, AV_LOG_ERROR, "Invalid alpha mode %d\n", ctx->alpha_info);

        return AVERROR_INVALIDDATA;

    }

    if (avctx->skip_alpha) ctx->alpha_info = 0;

    av_dlog(avctx, "frame type %d\n", ctx->frame_type);

    if (ctx->frame_type == 0) {

        ctx->scan = ctx->progressive_scan; // permuted

    } else {

        ctx->scan = ctx->interlaced_scan; // permuted

        ctx->frame->interlaced_frame = 1;

        ctx->frame->top_field_first = ctx->frame_type == 1;

    }

    if (ctx->alpha_info) {

        avctx->pix_fmt = (buf[12] & 0xC0) == 0xC0 ? AV_PIX_FMT_YUVA444P10 : AV_PIX_FMT_YUVA422P10;

    } else {

        avctx->pix_fmt = (buf[12] & 0xC0) == 0xC0 ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV422P10;

    }

    ptr   = buf + 20;

    flags = buf[19];

    av_dlog(avctx, "flags %x\n", flags);

    if (flags & 2) {

        if(buf + data_size - ptr < 64) {

            av_log(avctx, AV_LOG_ERROR, "Header truncated\n");

            return AVERROR_INVALIDDATA;

        }

        permute(ctx->qmat_luma, ctx->prodsp.idct_permutation, ptr);

        ptr += 64;

    } else {

        memset(ctx->qmat_luma, 4, 64);

    }

    if (flags & 1) {

        if(buf + data_size - ptr < 64) {

            av_log(avctx, AV_LOG_ERROR, "Header truncated\n");

            return AVERROR_INVALIDDATA;

        }

        permute(ctx->qmat_chroma, ctx->prodsp.idct_permutation, ptr);

    } else {

        memset(ctx->qmat_chroma, 4, 64);

    }

    return hdr_size;

}


static int svq1_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             UINT8 *buf, int buf_size)

{

  MpegEncContext *s=avctx->priv_data;

  uint8_t      *current, *previous;

  int		result, i, x, y, width, height;

  AVFrame *pict = data;

  /* initialize bit buffer */

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

  /* decode frame header */

  s->f_code = get_bits (&s->gb, 22);

  if ((s->f_code & ~0x70) || !(s->f_code & 0x60))

    return -1;

  /* swap some header bytes (why?) */

  if (s->f_code != 0x20) {

    uint32_t *src = (uint32_t *) (buf + 4);

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

      src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];

    }

  }

  result = svq1_decode_frame_header (&s->gb, s);

  if (result != 0)

  {

#ifdef DEBUG_SVQ1

    printf("Error in svq1_decode_frame_header %i\n",result);

#endif

    return result;

  }

  //FIXME this avoids some confusion for "B frames" without 2 references

  //this should be removed after libavcodec can handle more flaxible picture types & ordering

  if(s->pict_type==B_TYPE && s->last_picture.data[0]==NULL) return buf_size;

  if(avctx->hurry_up && s->pict_type==B_TYPE) return buf_size;

  if(MPV_frame_start(s, avctx) < 0)

      return -1;

  /* decode y, u and v components */

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

    int linesize;

    if (i == 0) {

      width  = (s->width+15)&~15;

      height = (s->height+15)&~15;

      linesize= s->linesize;

    } else {

      if(s->flags&CODEC_FLAG_GRAY) break;

      width  = (s->width/4+15)&~15;

      height = (s->height/4+15)&~15;

      linesize= s->uvlinesize;

    }

    current  = s->current_picture.data[i];

    if(s->pict_type==B_TYPE){

        previous = s->next_picture.data[i];

    }else{

        previous = s->last_picture.data[i];

    }

    if (s->pict_type == I_TYPE) {

      /* keyframe */

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

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

	  result = svq1_decode_block_intra (&s->gb, &current[x], linesize);

	  if (result != 0)

	  {

#ifdef DEBUG_SVQ1

	    printf("Error in svq1_decode_block %i (keyframe)\n",result);

#endif

	    return result;

	  }

	}

	current += 16*linesize;

      }

    } else {

      svq1_pmv_t pmv[width/8+3];

      /* delta frame */

      memset (pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv_t));

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

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

	  result = svq1_decode_delta_block (s, &s->gb, &current[x], previous,

					    linesize, pmv, x, y);

	  if (result != 0)

	  {

#ifdef DEBUG_SVQ1

    printf("Error in svq1_decode_delta_block %i\n",result);

#endif

	    return result;

	  }

	}

	pmv[0].x =

	pmv[0].y = 0;

	current += 16*linesize;

      }

    }

  }

  *pict = *(AVFrame*)&s->current_picture;

  MPV_frame_end(s);

  *data_size=sizeof(AVFrame);

  return buf_size;

}


static int decode_blocks(SnowContext *s){

    int x, y;

    int w= s->b_width;

    int h= s->b_height;

    int res;

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

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

            if ((res = decode_q_branch(s, 0, x, y)) < 0)

                return res;

        }

    }

    return 0;

}


static int s390x_write_all_elf64_notes(const char *note_name,

                                       WriteCoreDumpFunction f,

                                       S390CPU *cpu, int id,

                                       void *opaque)

{

    Note note;

    const NoteFuncDesc *nf;

    int note_size;

    int ret = -1;

    for (nf = note_func; nf->note_contents_func; nf++) {

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

        note.hdr.n_namesz = cpu_to_be32(sizeof(note.name));

        note.hdr.n_descsz = cpu_to_be32(nf->contents_size);

        strncpy(note.name, note_name, sizeof(note.name));

        (*nf->note_contents_func)(&note, cpu);

        note_size = sizeof(note) - sizeof(note.contents) + nf->contents_size;

        ret = f(&note, note_size, opaque);

        if (ret < 0) {

            return -1;

        }

    }

    return 0;

}


static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval)

{

    GetByteContext *gb = &s->gb;

    RangeCoder *rc = &s->rc;

    unsigned totfr = pixel->total_freq;

    unsigned value, x = 0, cumfr = 0, cnt_x = 0;

    int i, j, ret, c, cnt_c;

    if ((ret = s->get_freq(rc, totfr, &value)) < 0)

        return ret;

    while (x < 16) {

        cnt_x = pixel->lookup[x];

        if (value >= cumfr + cnt_x)

            cumfr += cnt_x;

        else

            break;

        x++;

    c = x * 16;

    cnt_c = 0;

    while (c < 256) {

        cnt_c = pixel->freq[c];

        if (value >= cumfr + cnt_c)

            cumfr += cnt_c;

        else

            break;

        c++;

    if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)

        return ret;

    pixel->freq[c] = cnt_c + step;

    pixel->lookup[x] = cnt_x + step;

    totfr += step;

    if (totfr > BOT) {

        totfr = 0;

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

            unsigned nc = (pixel->freq[i] >> 1) + 1;

            pixel->freq[i] = nc;

            totfr += nc;

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

            unsigned sum = 0;

            unsigned i16_17 = i << 4;

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

                sum += pixel->freq[i16_17 + j];

            pixel->lookup[i] = sum;

    pixel->total_freq = totfr;

    *rval = c & s->cbits;

    return 0;


void slirp_select_fill(int *pnfds, fd_set *readfds,

                       fd_set *writefds, fd_set *xfds)

{

}


int tcp_socket_incoming(const char *address, uint16_t port)

{

    char address_and_port[128];

    Error *local_err = NULL;

    combine_addr(address_and_port, 128, address, port);

    int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);

    if (local_err != NULL) {

        qerror_report_err(local_err);

        error_free(local_err);

    }

    return fd;

}


static void paio_cancel(BlockDriverAIOCB *blockacb)

{

    struct qemu_paiocb *acb = (struct qemu_paiocb *)blockacb;

    int active = 0;

    mutex_lock(&lock);

    if (!acb->active) {

        TAILQ_REMOVE(&request_list, acb, node);

        acb->ret = -ECANCELED;

    } else if (acb->ret == -EINPROGRESS) {

        active = 1;

    }

    mutex_unlock(&lock);

    if (active) {

        /* fail safe: if the aio could not be canceled, we wait for

           it */

        while (qemu_paio_error(acb) == EINPROGRESS)

            ;

    }

    paio_remove(acb);

}