static int pcm_encode_frame(AVCodecContext *avctx,

                            unsigned char *frame, int buf_size, void *data)

{

    int n, sample_size, v;

    const short *samples;

    unsigned char *dst;

    const uint8_t *srcu8;

    const int16_t *samples_int16_t;

    const int32_t *samples_int32_t;

    const int64_t *samples_int64_t;

    const uint16_t *samples_uint16_t;

    const uint32_t *samples_uint32_t;

    sample_size = av_get_bits_per_sample(avctx->codec->id)/8;

    n = buf_size / sample_size;

    samples = data;

    dst = frame;

    if (avctx->sample_fmt!=avctx->codec->sample_fmts[0]) {

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

        return -1;

    }

    switch(avctx->codec->id) {

    case CODEC_ID_PCM_U32LE:

        ENCODE(uint32_t, le32, samples, dst, n, 0, 0x80000000)

        break;

    case CODEC_ID_PCM_U32BE:

        ENCODE(uint32_t, be32, samples, dst, n, 0, 0x80000000)

        break;

    case CODEC_ID_PCM_S24LE:

        ENCODE(int32_t, le24, samples, dst, n, 8, 0)

        break;

    case CODEC_ID_PCM_S24BE:

        ENCODE(int32_t, be24, samples, dst, n, 8, 0)

        break;

    case CODEC_ID_PCM_U24LE:

        ENCODE(uint32_t, le24, samples, dst, n, 8, 0x800000)

        break;

    case CODEC_ID_PCM_U24BE:

        ENCODE(uint32_t, be24, samples, dst, n, 8, 0x800000)

        break;

    case CODEC_ID_PCM_S24DAUD:

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

            uint32_t tmp = av_reverse[(*samples >> 8) & 0xff] +

                           (av_reverse[*samples & 0xff] << 8);

            tmp <<= 4; // sync flags would go here

            bytestream_put_be24(&dst, tmp);

            samples++;

        }

        break;

    case CODEC_ID_PCM_U16LE:

        ENCODE(uint16_t, le16, samples, dst, n, 0, 0x8000)

        break;

    case CODEC_ID_PCM_U16BE:

        ENCODE(uint16_t, be16, samples, dst, n, 0, 0x8000)

        break;

    case CODEC_ID_PCM_S8:

        srcu8= data;

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

            v = *srcu8++;

            *dst++ = v - 128;

        }

        break;

#if HAVE_BIGENDIAN

    case CODEC_ID_PCM_F64LE:

        ENCODE(int64_t, le64, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_S32LE:

    case CODEC_ID_PCM_F32LE:

        ENCODE(int32_t, le32, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_S16LE:

        ENCODE(int16_t, le16, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_F64BE:

    case CODEC_ID_PCM_F32BE:

    case CODEC_ID_PCM_S32BE:

    case CODEC_ID_PCM_S16BE:

#else

    case CODEC_ID_PCM_F64BE:

        ENCODE(int64_t, be64, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_F32BE:

    case CODEC_ID_PCM_S32BE:

        ENCODE(int32_t, be32, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_S16BE:

        ENCODE(int16_t, be16, samples, dst, n, 0, 0)

        break;

    case CODEC_ID_PCM_F64LE:

    case CODEC_ID_PCM_F32LE:

    case CODEC_ID_PCM_S32LE:

    case CODEC_ID_PCM_S16LE:

#endif /* HAVE_BIGENDIAN */

    case CODEC_ID_PCM_U8:

        memcpy(dst, samples, n*sample_size);

        dst += n*sample_size;

        break;

    case CODEC_ID_PCM_ZORK:

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

            v= *samples++ >> 8;

            if(v<0)   v = -v;

            else      v+= 128;

            *dst++ = v;

        }

        break;

    case CODEC_ID_PCM_ALAW:

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

            v = *samples++;

            *dst++ = linear_to_alaw[(v + 32768) >> 2];

        }

        break;

    case CODEC_ID_PCM_MULAW:

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

            v = *samples++;

            *dst++ = linear_to_ulaw[(v + 32768) >> 2];

        }

        break;

    default:

        return -1;

    }

    //avctx->frame_size = (dst - frame) / (sample_size * avctx->channels);

    return dst - frame;

}


static int exif_add_metadata(AVCodecContext *avctx, int count, int type,

                             const char *name, const char *sep,

                             GetByteContext *gb, int le,

                             AVDictionary **metadata)

{

    switch(type) {

    case 0:

        av_log(avctx, AV_LOG_WARNING,

               "Invalid TIFF tag type 0 found for %s with size %d\n",

               name, count);

        return 0;

    case TIFF_DOUBLE   : return ff_tadd_doubles_metadata(count, name, sep, gb, le, metadata);

    case TIFF_SSHORT   : return ff_tadd_shorts_metadata(count, name, sep, gb, le, 1, metadata);

    case TIFF_SHORT    : return ff_tadd_shorts_metadata(count, name, sep, gb, le, 0, metadata);

    case TIFF_SBYTE    : return ff_tadd_bytes_metadata(count, name, sep, gb, le, 1, metadata);

    case TIFF_BYTE     :

    case TIFF_UNDEFINED: return ff_tadd_bytes_metadata(count, name, sep, gb, le, 0, metadata);

    case TIFF_STRING   : return ff_tadd_string_metadata(count, name, gb, le, metadata);

    case TIFF_SRATIONAL:

    case TIFF_RATIONAL : return ff_tadd_rational_metadata(count, name, sep, gb, le, metadata);

    case TIFF_SLONG    :

    case TIFF_LONG     : return ff_tadd_long_metadata(count, name, sep, gb, le, metadata);

    default:

        avpriv_request_sample(avctx, "TIFF tag type (%u)", type);

        return 0;

    };

}


static int mtv_probe(AVProbeData *p)

{

    if(p->buf_size < 3)

        return 0;

    /* Magic is 'AMV' */

    if(*(p->buf) != 'A' || *(p->buf+1) != 'M' || *(p->buf+2) != 'V')

        return 0;

    return AVPROBE_SCORE_MAX;

}


static int vmd_probe(AVProbeData *p)

{

    if (p->buf_size < 2)

        return 0;

    /* check if the first 2 bytes of the file contain the appropriate size

     * of a VMD header chunk */

    if (AV_RL16(&p->buf[0]) != VMD_HEADER_SIZE - 2)

        return 0;

    /* only return half certainty since this check is a bit sketchy */

    return AVPROBE_SCORE_MAX / 2;

}


voc_get_packet(AVFormatContext *s, AVPacket *pkt, AVStream *st, int max_size)

{

    VocDecContext *voc = s->priv_data;

    AVCodecContext *dec = st->codec;

    ByteIOContext *pb = s->pb;

    VocType type;

    int size, tmp_codec;

    int sample_rate = 0;

    int channels = 1;

    while (!voc->remaining_size) {

        type = get_byte(pb);

        if (type == VOC_TYPE_EOF)

            return AVERROR(EIO);

        voc->remaining_size = get_le24(pb);

        if (!voc->remaining_size) {

            if (url_is_streamed(s->pb))

                return AVERROR(EIO);

            voc->remaining_size = url_fsize(pb) - url_ftell(pb);

        }

        max_size -= 4;

        switch (type) {

        case VOC_TYPE_VOICE_DATA:

            dec->sample_rate = 1000000 / (256 - get_byte(pb));

            if (sample_rate)

                dec->sample_rate = sample_rate;

            dec->channels = channels;

            tmp_codec = ff_codec_get_id(ff_voc_codec_tags, get_byte(pb));

            if (dec->codec_id == CODEC_ID_NONE)

                dec->codec_id = tmp_codec;

            else if (dec->codec_id != tmp_codec)

                av_log(s, AV_LOG_WARNING, "Ignoring mid-stream change in audio codec\n");

            dec->bits_per_coded_sample = av_get_bits_per_sample(dec->codec_id);

            voc->remaining_size -= 2;

            max_size -= 2;

            channels = 1;

            break;

        case VOC_TYPE_VOICE_DATA_CONT:

            break;

        case VOC_TYPE_EXTENDED:

            sample_rate = get_le16(pb);

            get_byte(pb);

            channels = get_byte(pb) + 1;

            sample_rate = 256000000 / (channels * (65536 - sample_rate));

            voc->remaining_size = 0;

            max_size -= 4;

            break;

        case VOC_TYPE_NEW_VOICE_DATA:

            dec->sample_rate = get_le32(pb);

            dec->bits_per_coded_sample = get_byte(pb);

            dec->channels = get_byte(pb);

            tmp_codec = ff_codec_get_id(ff_voc_codec_tags, get_le16(pb));

            if (dec->codec_id == CODEC_ID_NONE)

                dec->codec_id = tmp_codec;

            else if (dec->codec_id != tmp_codec)

                av_log(s, AV_LOG_WARNING, "Ignoring mid-stream change in audio codec\n");

            url_fskip(pb, 4);

            voc->remaining_size -= 12;

            max_size -= 12;

            break;

        default:

            url_fskip(pb, voc->remaining_size);

            max_size -= voc->remaining_size;

            voc->remaining_size = 0;

            break;

        }

        if (dec->codec_id == CODEC_ID_NONE) {

            av_log(s, AV_LOG_ERROR, "Invalid codec_id\n");

            if (s->audio_codec_id == CODEC_ID_NONE) return AVERROR(EINVAL);

        }

    }

    dec->bit_rate = dec->sample_rate * dec->bits_per_coded_sample;

    if (max_size <= 0)

        max_size = 2048;

    size = FFMIN(voc->remaining_size, max_size);

    voc->remaining_size -= size;

    return av_get_packet(pb, pkt, size);

}


static inline int mjpeg_decode_dc(MJpegDecodeContext *s, int dc_index)

{

    int code;

    code = get_vlc2(&s->gb, s->vlcs[0][dc_index].table, 9, 2);

    if (code < 0) {

        av_log(s->avctx, AV_LOG_WARNING,

               "mjpeg_decode_dc: bad vlc: %d:%d (%p)\n",

               0, dc_index, &s->vlcs[0][dc_index]);

        return 0xffff;

    }

    if (code)

        return get_xbits(&s->gb, code);

    else

        return 0;

}


static void palmte_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    MemoryRegion *address_space_mem = get_system_memory();

    struct omap_mpu_state_s *mpu;

    int flash_size = 0x00800000;

    int sdram_size = palmte_binfo.ram_size;

    static uint32_t cs0val = 0xffffffff;

    static uint32_t cs1val = 0x0000e1a0;

    static uint32_t cs2val = 0x0000e1a0;

    static uint32_t cs3val = 0xe1a0e1a0;

    int rom_size, rom_loaded = 0;

    MemoryRegion *flash = g_new(MemoryRegion, 1);

    MemoryRegion *cs = g_new(MemoryRegion, 4);

    mpu = omap310_mpu_init(address_space_mem, sdram_size, cpu_model);

    /* External Flash (EMIFS) */

    memory_region_init_ram(flash, NULL, "palmte.flash", flash_size,

                           &error_abort);

    vmstate_register_ram_global(flash);

    memory_region_set_readonly(flash, true);

    memory_region_add_subregion(address_space_mem, OMAP_CS0_BASE, flash);

    memory_region_init_io(&cs[0], NULL, &static_ops, &cs0val, "palmte-cs0",

                          OMAP_CS0_SIZE - flash_size);

    memory_region_add_subregion(address_space_mem, OMAP_CS0_BASE + flash_size,

                                &cs[0]);

    memory_region_init_io(&cs[1], NULL, &static_ops, &cs1val, "palmte-cs1",

                          OMAP_CS1_SIZE);

    memory_region_add_subregion(address_space_mem, OMAP_CS1_BASE, &cs[1]);

    memory_region_init_io(&cs[2], NULL, &static_ops, &cs2val, "palmte-cs2",

                          OMAP_CS2_SIZE);

    memory_region_add_subregion(address_space_mem, OMAP_CS2_BASE, &cs[2]);

    memory_region_init_io(&cs[3], NULL, &static_ops, &cs3val, "palmte-cs3",

                          OMAP_CS3_SIZE);

    memory_region_add_subregion(address_space_mem, OMAP_CS3_BASE, &cs[3]);

    palmte_microwire_setup(mpu);

    qemu_add_kbd_event_handler(palmte_button_event, mpu);

    palmte_gpio_setup(mpu);

    /* Setup initial (reset) machine state */

    if (nb_option_roms) {

        rom_size = get_image_size(option_rom[0].name);

        if (rom_size > flash_size) {

            fprintf(stderr, "%s: ROM image too big (%x > %x)\n",

                            __FUNCTION__, rom_size, flash_size);

            rom_size = 0;

        }

        if (rom_size > 0) {

            rom_size = load_image_targphys(option_rom[0].name, OMAP_CS0_BASE,

                                           flash_size);

            rom_loaded = 1;

        }

        if (rom_size < 0) {

            fprintf(stderr, "%s: error loading '%s'\n",

                            __FUNCTION__, option_rom[0].name);

        }

    }

    if (!rom_loaded && !kernel_filename && !qtest_enabled()) {

        fprintf(stderr, "Kernel or ROM image must be specified\n");

        exit(1);

    }

    /* Load the kernel.  */

    palmte_binfo.kernel_filename = kernel_filename;

    palmte_binfo.kernel_cmdline = kernel_cmdline;

    palmte_binfo.initrd_filename = initrd_filename;

    arm_load_kernel(mpu->cpu, &palmte_binfo);

}


static void aio_signal_handler(int signum)

{

#if !defined(QEMU_IMG) && !defined(QEMU_NBD)

    CPUState *env = cpu_single_env;

    if (env) {

        /* stop the currently executing cpu because a timer occured */

        cpu_interrupt(env, CPU_INTERRUPT_EXIT);

#ifdef USE_KQEMU

        if (env->kqemu_enabled) {

            kqemu_cpu_interrupt(env);

        }

#endif

    }

#endif

}


static int mov_read_mfra(MOVContext *c, AVIOContext *f)

{

    int64_t stream_size = avio_size(f);

    int64_t original_pos = avio_tell(f);

    int64_t seek_ret;

    int32_t mfra_size;

    int ret = -1;

    if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) {

        ret = seek_ret;

        goto fail;

    }

    mfra_size = avio_rb32(f);

    if (mfra_size < 0 || mfra_size > stream_size) {

        av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n");

        goto fail;

    }

    if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) {

        ret = seek_ret;

        goto fail;

    }

    if (avio_rb32(f) != mfra_size) {

        av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n");

        goto fail;

    }

    if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) {

        av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n");

        goto fail;

    }

    ret = 0;

    av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n");

    while (!read_tfra(c, f)) {

        /* Empty */

    }

fail:

    seek_ret = avio_seek(f, original_pos, SEEK_SET);

    if (seek_ret < 0) {

        av_log(c->fc, AV_LOG_ERROR,

               "failed to seek back after looking for mfra\n");

        ret = seek_ret;

    }

    return ret;

}


static int qemu_save_device_state(QEMUFile *f)
{
    SaveStateEntry *se;
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
    cpu_synchronize_all_states();
    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {
        if (se->is_ram) {
            continue;
        }
        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
            continue;
        }
        save_section_header(f, se, QEMU_VM_SECTION_FULL);
        vmstate_save(f, se, NULL);
    }
    qemu_put_byte(f, QEMU_VM_EOF);
    return qemu_file_get_error(f);
}


void PREFIX_h264_chroma_mc8_altivec(uint8_t * dst, uint8_t * src,

                                    int stride, int h, int x, int y) {

  POWERPC_PERF_DECLARE(PREFIX_h264_chroma_mc8_num, 1);

    DECLARE_ALIGNED_16(signed int, ABCD[4]) =

                        {((8 - x) * (8 - y)),

                         ((    x) * (8 - y)),

                         ((8 - x) * (    y)),

                         ((    x) * (    y))};

    register int i;

    vec_u8 fperm;

    const vec_s32 vABCD = vec_ld(0, ABCD);

    const vec_s16 vA = vec_splat((vec_s16)vABCD, 1);

    const vec_s16 vB = vec_splat((vec_s16)vABCD, 3);

    const vec_s16 vC = vec_splat((vec_s16)vABCD, 5);

    const vec_s16 vD = vec_splat((vec_s16)vABCD, 7);

    LOAD_ZERO;

    const vec_s16 v32ss = vec_sl(vec_splat_s16(1),vec_splat_u16(5));

    const vec_u16 v6us = vec_splat_u16(6);

    register int loadSecond = (((unsigned long)src) % 16) <= 7 ? 0 : 1;

    register int reallyBadAlign = (((unsigned long)src) % 16) == 15 ? 1 : 0;

    vec_u8 vsrcAuc, vsrcBuc, vsrcperm0, vsrcperm1;

    vec_u8 vsrc0uc, vsrc1uc;

    vec_s16 vsrc0ssH, vsrc1ssH;

    vec_u8 vsrcCuc, vsrc2uc, vsrc3uc;

    vec_s16 vsrc2ssH, vsrc3ssH, psum;

    vec_u8 vdst, ppsum, vfdst, fsum;

  POWERPC_PERF_START_COUNT(PREFIX_h264_chroma_mc8_num, 1);

    if (((unsigned long)dst) % 16 == 0) {

        fperm = (vec_u8){0x10, 0x11, 0x12, 0x13,

                           0x14, 0x15, 0x16, 0x17,

                           0x08, 0x09, 0x0A, 0x0B,

                           0x0C, 0x0D, 0x0E, 0x0F};

    } else {

        fperm = (vec_u8){0x00, 0x01, 0x02, 0x03,

                           0x04, 0x05, 0x06, 0x07,

                           0x18, 0x19, 0x1A, 0x1B,

                           0x1C, 0x1D, 0x1E, 0x1F};

    }

    vsrcAuc = vec_ld(0, src);

    if (loadSecond)

        vsrcBuc = vec_ld(16, src);

    vsrcperm0 = vec_lvsl(0, src);

    vsrcperm1 = vec_lvsl(1, src);

    vsrc0uc = vec_perm(vsrcAuc, vsrcBuc, vsrcperm0);

    if (reallyBadAlign)

        vsrc1uc = vsrcBuc;

    else

        vsrc1uc = vec_perm(vsrcAuc, vsrcBuc, vsrcperm1);

    vsrc0ssH = (vec_s16)vec_mergeh(zero_u8v,(vec_u8)vsrc0uc);

    vsrc1ssH = (vec_s16)vec_mergeh(zero_u8v,(vec_u8)vsrc1uc);

    if (ABCD[3]) {

        if (!loadSecond) {// -> !reallyBadAlign

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

                vsrcCuc = vec_ld(stride + 0, src);

                vsrc2uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm0);

                vsrc3uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm1);

                CHROMA_MC8_ALTIVEC_CORE

            }

        } else {

            vec_u8 vsrcDuc;

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

                vsrcCuc = vec_ld(stride + 0, src);

                vsrcDuc = vec_ld(stride + 16, src);

                vsrc2uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm0);

                if (reallyBadAlign)

                    vsrc3uc = vsrcDuc;

                else

                    vsrc3uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm1);

                CHROMA_MC8_ALTIVEC_CORE

            }

        }

    } else {

        const vec_s16 vE = vec_add(vB, vC);

        if (ABCD[2]) { // x == 0 B == 0

            if (!loadSecond) {// -> !reallyBadAlign

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

                    vsrcCuc = vec_ld(stride + 0, src);

                    vsrc1uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm0);

                    CHROMA_MC8_ALTIVEC_CORE_SIMPLE

                    vsrc0uc = vsrc1uc;

                }

            } else {

                vec_u8 vsrcDuc;

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

                    vsrcCuc = vec_ld(stride + 0, src);

                    vsrcDuc = vec_ld(stride + 15, src);

                    vsrc1uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm0);

                    CHROMA_MC8_ALTIVEC_CORE_SIMPLE

                    vsrc0uc = vsrc1uc;

                }

            }

        } else { // y == 0 C == 0

            if (!loadSecond) {// -> !reallyBadAlign

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

                    vsrcCuc = vec_ld(0, src);

                    vsrc0uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm0);

                    vsrc1uc = vec_perm(vsrcCuc, vsrcCuc, vsrcperm1);

                    CHROMA_MC8_ALTIVEC_CORE_SIMPLE

                }

            } else {

                vec_u8 vsrcDuc;

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

                    vsrcCuc = vec_ld(0, src);

                    vsrcDuc = vec_ld(15, src);

                    vsrc0uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm0);

                    if (reallyBadAlign)

                        vsrc1uc = vsrcDuc;

                    else

                        vsrc1uc = vec_perm(vsrcCuc, vsrcDuc, vsrcperm1);

                    CHROMA_MC8_ALTIVEC_CORE_SIMPLE

                }

            }

        }

    }

    POWERPC_PERF_STOP_COUNT(PREFIX_h264_chroma_mc8_num, 1);

}


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);

        config->dummy_actx = avcodec_alloc_context3(NULL);

        config->dummy_vctx = avcodec_alloc_context3(NULL);

        if (!config->dummy_vctx || !config->dummy_actx) {

            av_free(stream);

            avcodec_free_context(&config->dummy_vctx);

            avcodec_free_context(&config->dummy_actx);

            return AVERROR(ENOMEM);

        }

        config->dummy_actx->codec_type = AVMEDIA_TYPE_AUDIO;

        config->dummy_vctx->codec_type = AVMEDIA_TYPE_VIDEO;

        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->guessed_audio_codec_id = stream->fmt->audio_codec;

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

        } else {

            config->guessed_audio_codec_id = AV_CODEC_ID_NONE;

            config->guessed_video_codec_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->guessed_audio_codec_id = stream->fmt->audio_codec;

            config->guessed_video_codec_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);

        ffserver_set_codec(config->dummy_actx, arg, config, line_num);

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

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

        ffserver_set_codec(config->dummy_vctx, arg, config, line_num);

    } 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 % 2) || (h % 2))

            WARNING("Image size is not a multiple of 2\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")) {

        int ret;

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

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

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

            ret = ffserver_save_avoption(config->dummy_vctx, arg, arg2, &config->video_opts,

                                         AV_OPT_FLAG_VIDEO_PARAM ,config, line_num);

        else

            ret = ffserver_save_avoption(config->dummy_actx, arg, arg2, &config->audio_opts,

                                         AV_OPT_FLAG_AUDIO_PARAM ,config, line_num);

        if (ret < 0)

            goto nomem;

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

               !av_strcasecmp(cmd, "AVPresetAudio")) {

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

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

            ffserver_opt_preset(arg, config->dummy_vctx, config, line_num);

        else

            ffserver_opt_preset(arg, config->dummy_actx, config, line_num);

    } 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->no_video = 1;

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

        config->no_audio = 1;

    } 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))

            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")) {

            if (config->dummy_actx->codec_id == AV_CODEC_ID_NONE)

                config->dummy_actx->codec_id = config->guessed_audio_codec_id;

            if (!config->no_audio && config->dummy_actx->codec_id != AV_CODEC_ID_NONE) {

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

                ffserver_apply_stream_config(audio_enc, config->audio_conf, &config->audio_opts);

                add_codec(stream, audio_enc);

            }

            if (config->dummy_vctx->codec_id == AV_CODEC_ID_NONE)

                config->dummy_vctx->codec_id = config->guessed_video_codec_id;

            if (!config->no_video && config->dummy_vctx->codec_id != AV_CODEC_ID_NONE) {

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

                ffserver_apply_stream_config(video_enc, config->video_conf, &config->video_opts);

                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);

        avcodec_free_context(&config->dummy_vctx);

        avcodec_free_context(&config->dummy_actx);

        *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);

    avcodec_free_context(&config->dummy_vctx);

    avcodec_free_context(&config->dummy_actx);

    return AVERROR(ENOMEM);

}


static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,

                                               struct sockaddr *addr,

                                               socklen_t len)

{

    struct target_sockaddr *target_saddr;

    if (len == 0) {

        return 0;

    }

    target_saddr = lock_user(VERIFY_WRITE, target_addr, len, 0);

    if (!target_saddr)

        return -TARGET_EFAULT;

    memcpy(target_saddr, addr, len);

    if (len >= offsetof(struct target_sockaddr, sa_family) +

        sizeof(target_saddr->sa_family)) {

        target_saddr->sa_family = tswap16(addr->sa_family);

    }

    if (addr->sa_family == AF_NETLINK && len >= sizeof(struct sockaddr_nl)) {

        struct sockaddr_nl *target_nl = (struct sockaddr_nl *)target_saddr;

        target_nl->nl_pid = tswap32(target_nl->nl_pid);

        target_nl->nl_groups = tswap32(target_nl->nl_groups);

    } else if (addr->sa_family == AF_PACKET) {

        struct sockaddr_ll *target_ll = (struct sockaddr_ll *)target_saddr;

        target_ll->sll_ifindex = tswap32(target_ll->sll_ifindex);

        target_ll->sll_hatype = tswap16(target_ll->sll_hatype);

    } else if (addr->sa_family == AF_INET6 &&

               len >= sizeof(struct target_sockaddr_in6)) {

        struct target_sockaddr_in6 *target_in6 =

               (struct target_sockaddr_in6 *)target_saddr;

        target_in6->sin6_scope_id = tswap16(target_in6->sin6_scope_id);

    }

    unlock_user(target_saddr, target_addr, len);

    return 0;

}


void kvm_set_phys_mem(target_phys_addr_t start_addr,

                      ram_addr_t size,

                      ram_addr_t phys_offset)

{

    KVMState *s = kvm_state;

    ram_addr_t flags = phys_offset & ~TARGET_PAGE_MASK;

    KVMSlot *mem;

    if (start_addr & ~TARGET_PAGE_MASK) {

        fprintf(stderr, "Only page-aligned memory slots supported\n");

        abort();

    }

    /* KVM does not support read-only slots */

    phys_offset &= ~IO_MEM_ROM;

    mem = kvm_lookup_slot(s, start_addr);

    if (mem) {

        if (flags >= IO_MEM_UNASSIGNED) {

            mem->memory_size = 0;

            mem->start_addr = start_addr;

            mem->phys_offset = 0;

            mem->flags = 0;

            kvm_set_user_memory_region(s, mem);

        } else if (start_addr >= mem->start_addr &&

                   (start_addr + size) <= (mem->start_addr +

                                           mem->memory_size)) {

            KVMSlot slot;

            target_phys_addr_t mem_start;

            ram_addr_t mem_size, mem_offset;

            /* Not splitting */

            if ((phys_offset - (start_addr - mem->start_addr)) ==

                mem->phys_offset)

                return;

            /* unregister whole slot */

            memcpy(&slot, mem, sizeof(slot));

            mem->memory_size = 0;

            kvm_set_user_memory_region(s, mem);

            /* register prefix slot */

            mem_start = slot.start_addr;

            mem_size = start_addr - slot.start_addr;

            mem_offset = slot.phys_offset;

            if (mem_size)

                kvm_set_phys_mem(mem_start, mem_size, mem_offset);

            /* register new slot */

            kvm_set_phys_mem(start_addr, size, phys_offset);

            /* register suffix slot */

            mem_start = start_addr + size;

            mem_offset += mem_size + size;

            mem_size = slot.memory_size - mem_size - size;

            if (mem_size)

                kvm_set_phys_mem(mem_start, mem_size, mem_offset);

            return;

        } else {

            printf("Registering overlapping slot\n");

            abort();

        }

    }

    /* KVM does not need to know about this memory */

    if (flags >= IO_MEM_UNASSIGNED)

        return;

    mem = kvm_alloc_slot(s);

    mem->memory_size = size;

    mem->start_addr = start_addr;

    mem->phys_offset = phys_offset;

    mem->flags = 0;

    kvm_set_user_memory_region(s, mem);

    /* FIXME deal with errors */

}


static void vfio_put_device(VFIOPCIDevice *vdev)

{

    g_free(vdev->vbasedev.name);

    if (vdev->msix) {

        g_free(vdev->msix);

        vdev->msix = NULL;

    }

    vfio_put_base_device(&vdev->vbasedev);

}


static void net_init_tap_one(const NetdevTapOptions *tap, NetClientState *peer,

                             const char *model, const char *name,

                             const char *ifname, const char *script,

                             const char *downscript, const char *vhostfdname,

                             int vnet_hdr, int fd, Error **errp)

{

    Error *err = NULL;

    TAPState *s = net_tap_fd_init(peer, model, name, fd, vnet_hdr);

    int vhostfd;

    tap_set_sndbuf(s->fd, tap, &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    if (tap->has_fd || tap->has_fds) {

        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "fd=%d", fd);

    } else if (tap->has_helper) {

        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s",

                 tap->helper);

    } else {

        snprintf(s->nc.info_str, sizeof(s->nc.info_str),

                 "ifname=%s,script=%s,downscript=%s", ifname, script,

                 downscript);

        if (strcmp(downscript, "no") != 0) {

            snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);

            snprintf(s->down_script_arg, sizeof(s->down_script_arg),

                     "%s", ifname);

        }

    }

    if (tap->has_vhost ? tap->vhost :

        vhostfdname || (tap->has_vhostforce && tap->vhostforce)) {

        VhostNetOptions options;

        options.backend_type = VHOST_BACKEND_TYPE_KERNEL;

        options.net_backend = &s->nc;

        options.force = tap->has_vhostforce && tap->vhostforce;

        if (tap->has_vhostfd || tap->has_vhostfds) {

            vhostfd = monitor_fd_param(cur_mon, vhostfdname, &err);

            if (vhostfd == -1) {

                error_propagate(errp, err);

                return;

            }

        } else {

            vhostfd = open("/dev/vhost-net", O_RDWR);

            if (vhostfd < 0) {

                error_setg_errno(errp, errno,

                                 "tap: open vhost char device failed");

                return;

            }

        }

        options.opaque = (void *)(uintptr_t)vhostfd;

        s->vhost_net = vhost_net_init(&options);

        if (!s->vhost_net) {

            error_setg(errp,

                       "vhost-net requested but could not be initialized");

            return;

        }

    } else if (tap->has_vhostfd || tap->has_vhostfds) {

        error_setg(errp, "vhostfd= is not valid without vhost");

    }

}


void qemu_iovec_concat_iov(QEMUIOVector *dst,
                           struct iovec *src_iov, unsigned int src_cnt,
                           size_t soffset, size_t sbytes)
{
    int i;
    size_t done;
    assert(dst->nalloc != -1);
    for (i = 0, done = 0; done < sbytes && i < src_cnt; i++) {
        if (soffset < src_iov[i].iov_len) {
            size_t len = MIN(src_iov[i].iov_len - soffset, sbytes - done);
            qemu_iovec_add(dst, src_iov[i].iov_base + soffset, len);
            done += len;
            soffset = 0;
        } else {
            soffset -= src_iov[i].iov_len;
    assert(soffset == 0); /* offset beyond end of src */


void hmp_dump_guest_memory(Monitor *mon, const QDict *qdict)

{

    Error *errp = NULL;

    int paging = qdict_get_try_bool(qdict, "paging", 0);

    const char *file = qdict_get_str(qdict, "filename");

    bool has_begin = qdict_haskey(qdict, "begin");

    bool has_length = qdict_haskey(qdict, "length");

    int64_t begin = 0;

    int64_t length = 0;

    char *prot;

    if (has_begin) {

        begin = qdict_get_int(qdict, "begin");

    }

    if (has_length) {

        length = qdict_get_int(qdict, "length");

    }

    prot = g_strconcat("file:", file, NULL);

    qmp_dump_guest_memory(paging, prot, has_begin, begin, has_length, length,

                          &errp);

    hmp_handle_error(mon, &errp);

    g_free(prot);

}


static int encode_picture_ls(AVCodecContext *avctx, unsigned char *buf, int buf_size, void *data){

    JpeglsContext * const s = avctx->priv_data;

    AVFrame *pict = data;

    AVFrame * const p= (AVFrame*)&s->picture;

    const int near = avctx->prediction_method;

    PutBitContext pb, pb2;

    GetBitContext gb;

    uint8_t *buf2, *zero, *cur, *last;

    JLSState *state;

    int i, size;

    int comps;

    buf2 = av_malloc(buf_size);

    init_put_bits(&pb, buf, buf_size);

    init_put_bits(&pb2, buf2, buf_size);

    *p = *pict;

    p->pict_type= FF_I_TYPE;

    p->key_frame= 1;

    if(avctx->pix_fmt == PIX_FMT_GRAY8 || avctx->pix_fmt == PIX_FMT_GRAY16)

        comps = 1;

    else

        comps = 3;

    /* write our own JPEG header, can't use mjpeg_picture_header */

    put_marker(&pb, SOI);

    put_marker(&pb, SOF48);

    put_bits(&pb, 16, 8 + comps * 3); // header size depends on components

    put_bits(&pb,  8, (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8); // bpp

    put_bits(&pb, 16, avctx->height);

    put_bits(&pb, 16, avctx->width);

    put_bits(&pb,  8, comps);         // components

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

        put_bits(&pb,  8, i);    // component ID

        put_bits(&pb,  8, 0x11); // subsampling: none

        put_bits(&pb,  8, 0);    // Tiq, used by JPEG-LS ext

    }

    put_marker(&pb, SOS);

    put_bits(&pb, 16, 6 + comps * 2);

    put_bits(&pb,  8, comps);

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

        put_bits(&pb,  8, i);  // component ID

        put_bits(&pb,  8, 0);  // mapping index: none

    }

    put_bits(&pb,  8, near);

    put_bits(&pb,  8, (comps > 1) ? 1 : 0); // interleaving: 0 - plane, 1 - line

    put_bits(&pb,  8, 0); // point transform: none

    state = av_mallocz(sizeof(JLSState));

    /* initialize JPEG-LS state from JPEG parameters */

    state->near = near;

    state->bpp = (avctx->pix_fmt == PIX_FMT_GRAY16) ? 16 : 8;

    reset_ls_coding_parameters(state, 0);

    ls_init_state(state);

    ls_store_lse(state, &pb);

    zero = av_mallocz(p->linesize[0]);

    last = zero;

    cur = p->data[0];

    if(avctx->pix_fmt == PIX_FMT_GRAY8){

        int t = 0;

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

            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0,  8);

            t = last[0];

            last = cur;

            cur += p->linesize[0];

        }

    }else if(avctx->pix_fmt == PIX_FMT_GRAY16){

        int t = 0;

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

            ls_encode_line(state, &pb2, last, cur, t, avctx->width, 1, 0, 16);

            t = *((uint16_t*)last);

            last = cur;

            cur += p->linesize[0];

        }

    }else if(avctx->pix_fmt == PIX_FMT_RGB24){

        int j, width;

        int Rc[3] = {0, 0, 0};

        width = avctx->width * 3;

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

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

                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);

                Rc[j] = last[j];

            }

            last = cur;

            cur += s->picture.linesize[0];

        }

    }else if(avctx->pix_fmt == PIX_FMT_BGR24){

        int j, width;

        int Rc[3] = {0, 0, 0};

        width = avctx->width * 3;

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

            for(j = 2; j >= 0; j--) {

                ls_encode_line(state, &pb2, last + j, cur + j, Rc[j], width, 3, j, 8);

                Rc[j] = last[j];

            }

            last = cur;

            cur += s->picture.linesize[0];

        }

    }

    av_free(zero);

    av_free(state);

    flush_put_bits(&pb2);

    /* do escape coding */

    size = put_bits_count(&pb2) >> 3;

    init_get_bits(&gb, buf2, size);

    while(get_bits_count(&gb) < size * 8){

        int v;

        v = get_bits(&gb, 8);

        put_bits(&pb, 8, v);

        if(v == 0xFF){

            v = get_bits(&gb, 7);

            put_bits(&pb, 8, v);

        }

    }

    align_put_bits(&pb);

    av_free(buf2);

    /* End of image */

    put_marker(&pb, EOI);

    flush_put_bits(&pb);

    emms_c();

    return put_bits_count(&pb) >> 3;

}


void ff_er_add_slice(MpegEncContext *s, int startx, int starty, int endx, int endy, int status){
    const int start_i= clip(startx + starty * s->mb_width    , 0, s->mb_num-1);
    const int end_i  = clip(endx   + endy   * s->mb_width    , 0, s->mb_num);
    const int start_xy= s->mb_index2xy[start_i];
    const int end_xy  = s->mb_index2xy[end_i];
    int mask= -1;
    if(!s->error_resilience) return;
    mask &= ~VP_START;
    if(status & (AC_ERROR|AC_END)){
        mask &= ~(AC_ERROR|AC_END);
        s->error_count -= end_i - start_i + 1;
    if(status & (DC_ERROR|DC_END)){
        mask &= ~(DC_ERROR|DC_END);
        s->error_count -= end_i - start_i + 1;
    if(status & (MV_ERROR|MV_END)){
        mask &= ~(MV_ERROR|MV_END);
        s->error_count -= end_i - start_i + 1;
    if(status & (AC_ERROR|DC_ERROR|MV_ERROR)) s->error_count= INT_MAX;
    if(mask == ~0x7F){
        memset(&s->error_status_table[start_xy], 0, (end_xy - start_xy) * sizeof(uint8_t));
    }else{
        int i;
        for(i=start_xy; i<end_xy; i++){
            s->error_status_table[ i ] &= mask;
    if(end_i == s->mb_num)
        s->error_count= INT_MAX;
    else{
        s->error_status_table[end_xy] &= mask;
        s->error_status_table[end_xy] |= status;
    s->error_status_table[start_xy] |= VP_START;
    if(start_xy > 0 && s->avctx->thread_count <= 1 && s->avctx->skip_top*s->mb_width < start_i){
        int prev_status= s->error_status_table[ s->mb_index2xy[start_i - 1] ];
        prev_status &= ~ VP_START;
        if(prev_status != (MV_END|DC_END|AC_END)) s->error_count= INT_MAX;


static int rtsp_parse_request(HTTPContext *c)

{

    const char *p, *p1, *p2;

    char cmd[32];

    char url[1024];

    char protocol[32];

    char line[1024];

    int len;

    RTSPMessageHeader header1 = { 0 }, *header = &header1;

    c->buffer_ptr[0] = '\0';

    p = c->buffer;

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

    get_word(url, sizeof(url), &p);

    get_word(protocol, sizeof(protocol), &p);

    av_strlcpy(c->method, cmd, sizeof(c->method));

    av_strlcpy(c->url, url, sizeof(c->url));

    av_strlcpy(c->protocol, protocol, sizeof(c->protocol));

    if (avio_open_dyn_buf(&c->pb) < 0) {

        /* XXX: cannot do more */

        c->pb = NULL; /* safety */

        return -1;

    }

    /* check version name */

    if (strcmp(protocol, "RTSP/1.0") != 0) {

        rtsp_reply_error(c, RTSP_STATUS_VERSION);

        goto the_end;

    }

    /* parse each header line */

    /* skip to next line */

    while (*p != '\n' && *p != '\0')

        p++;

    if (*p == '\n')

        p++;

    while (*p != '\0') {

        p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);

        if (!p1)

            break;

        p2 = p1;

        if (p2 > p && p2[-1] == '\r')

            p2--;

        /* skip empty line */

        if (p2 == p)

            break;

        len = p2 - p;

        if (len > sizeof(line) - 1)

            len = sizeof(line) - 1;

        memcpy(line, p, len);

        line[len] = '\0';

        ff_rtsp_parse_line(header, line, NULL, NULL);

        p = p1 + 1;

    }

    /* handle sequence number */

    c->seq = header->seq;

    if (!strcmp(cmd, "DESCRIBE"))

        rtsp_cmd_describe(c, url);

    else if (!strcmp(cmd, "OPTIONS"))

        rtsp_cmd_options(c, url);

    else if (!strcmp(cmd, "SETUP"))

        rtsp_cmd_setup(c, url, header);

    else if (!strcmp(cmd, "PLAY"))

        rtsp_cmd_play(c, url, header);

    else if (!strcmp(cmd, "PAUSE"))

        rtsp_cmd_interrupt(c, url, header, 1);

    else if (!strcmp(cmd, "TEARDOWN"))

        rtsp_cmd_interrupt(c, url, header, 0);

    else

        rtsp_reply_error(c, RTSP_STATUS_METHOD);

 the_end:

    len = avio_close_dyn_buf(c->pb, &c->pb_buffer);

    c->pb = NULL; /* safety */

    if (len < 0) {

        /* XXX: cannot do more */

        return -1;

    }

    c->buffer_ptr = c->pb_buffer;

    c->buffer_end = c->pb_buffer + len;

    c->state = RTSPSTATE_SEND_REPLY;

    return 0;

}


bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)

{

    assert(cookie->type < BDRV_MAX_IOTYPE);

    bs->stats.nr_bytes[cookie->type] += cookie->bytes;

    bs->stats.nr_ops[cookie->type]++;

    bs->stats.total_time_ns[cookie->type] += get_clock() -

                                             cookie->start_time_ns;

}


static void dump_stream_format(AVFormatContext *ic, int i,
                               int index, int is_output)
{
    char buf[256];
    int flags = (is_output ? ic->oformat->flags : ic->iformat->flags);
    AVStream *st = ic->streams[i];
    int g = av_gcd(st->time_base.num, st->time_base.den);
    AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL, 0);
    avcodec_string(buf, sizeof(buf), st->codec, is_output);
    av_log(NULL, AV_LOG_INFO, "    Stream #%d:%d", index, i);
    /* the pid is an important information, so we display it */
    /* XXX: add a generic system */
    if (flags & AVFMT_SHOW_IDS)
        av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
    if (lang)
        av_log(NULL, AV_LOG_INFO, "(%s)", lang->value);
    av_log(NULL, AV_LOG_DEBUG, ", %d, %d/%d", st->codec_info_nb_frames,
           st->time_base.num / g, st->time_base.den / g);
    av_log(NULL, AV_LOG_INFO, ": %s", buf);
    if (st->sample_aspect_ratio.num && // default
        av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)) {
        AVRational display_aspect_ratio;
        av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
                  st->codec->width  * st->sample_aspect_ratio.num,
                  st->codec->height * st->sample_aspect_ratio.den,
                  1024 * 1024);
        av_log(NULL, AV_LOG_INFO, ", SAR %d:%d DAR %d:%d",
               st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
               display_aspect_ratio.num, display_aspect_ratio.den);
    }
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
        if (st->avg_frame_rate.den && st->avg_frame_rate.num)
            print_fps(av_q2d(st->avg_frame_rate), "fps");
#if FF_API_R_FRAME_RATE
        if (st->r_frame_rate.den && st->r_frame_rate.num)
            print_fps(av_q2d(st->r_frame_rate), "tbr");
#endif
        if (st->time_base.den && st->time_base.num)
            print_fps(1 / av_q2d(st->time_base), "tbn");
        if (st->codec->time_base.den && st->codec->time_base.num)
            print_fps(1 / av_q2d(st->codec->time_base), "tbc");
    }
    if (st->disposition & AV_DISPOSITION_DEFAULT)
        av_log(NULL, AV_LOG_INFO, " (default)");
    if (st->disposition & AV_DISPOSITION_DUB)
        av_log(NULL, AV_LOG_INFO, " (dub)");
    if (st->disposition & AV_DISPOSITION_ORIGINAL)
        av_log(NULL, AV_LOG_INFO, " (original)");
    if (st->disposition & AV_DISPOSITION_COMMENT)
        av_log(NULL, AV_LOG_INFO, " (comment)");
    if (st->disposition & AV_DISPOSITION_LYRICS)
        av_log(NULL, AV_LOG_INFO, " (lyrics)");
    if (st->disposition & AV_DISPOSITION_KARAOKE)
        av_log(NULL, AV_LOG_INFO, " (karaoke)");
    if (st->disposition & AV_DISPOSITION_FORCED)
        av_log(NULL, AV_LOG_INFO, " (forced)");
    if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
        av_log(NULL, AV_LOG_INFO, " (hearing impaired)");
    if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
        av_log(NULL, AV_LOG_INFO, " (visual impaired)");
    if (st->disposition & AV_DISPOSITION_CLEAN_EFFECTS)
        av_log(NULL, AV_LOG_INFO, " (clean effects)");
    av_log(NULL, AV_LOG_INFO, "\n");
    dump_metadata(NULL, st->metadata, "    ");
    dump_sidedata(NULL, st, "    ");
}


int rom_load_all(void)

{

    target_phys_addr_t addr = 0;

    int memtype;

    Rom *rom;

    QTAILQ_FOREACH(rom, &roms, next) {

        if (addr < rom->min)

            addr = rom->min;

        if (rom->max) {

            /* load address range */

            if (rom->align) {

                addr += (rom->align-1);

                addr &= ~(rom->align-1);

            }

            if (addr + rom->romsize > rom->max) {

                fprintf(stderr, "rom: out of memory (rom %s, "

                        "addr 0x" TARGET_FMT_plx

                        ", size 0x%zx, max 0x" TARGET_FMT_plx ")\n",

                        rom->name, addr, rom->romsize, rom->max);

                return -1;

            }

        } else {

            /* fixed address requested */

            if (addr != rom->min) {

                fprintf(stderr, "rom: requested regions overlap "

                        "(rom %s. free=0x" TARGET_FMT_plx

                        ", addr=0x" TARGET_FMT_plx ")\n",

                        rom->name, addr, rom->min);

                return -1;

            }

        }

        rom->addr = addr;

        addr += rom->romsize;

        memtype = cpu_get_physical_page_desc(rom->addr) & (3 << IO_MEM_SHIFT);

        if (memtype == IO_MEM_ROM)

            rom->isrom = 1;

    }

    qemu_register_reset(rom_reset, NULL);

    roms_loaded = 1;

    return 0;

}


static uint32_t vmsvga_value_read(void *opaque, uint32_t address)

{

    uint32_t caps;

    struct vmsvga_state_s *s = opaque;

    DisplaySurface *surface = qemu_console_surface(s->vga.con);

    uint32_t ret;

    switch (s->index) {

    case SVGA_REG_ID:

        ret = s->svgaid;

        break;

    case SVGA_REG_ENABLE:

        ret = s->enable;

        break;

    case SVGA_REG_WIDTH:

        ret = surface_width(surface);

        break;

    case SVGA_REG_HEIGHT:

        ret = surface_height(surface);

        break;

    case SVGA_REG_MAX_WIDTH:

        ret = SVGA_MAX_WIDTH;

        break;

    case SVGA_REG_MAX_HEIGHT:

        ret = SVGA_MAX_HEIGHT;

        break;

    case SVGA_REG_DEPTH:

        ret = s->depth;

        break;

    case SVGA_REG_BITS_PER_PIXEL:

        ret = (s->depth + 7) & ~7;

        break;

    case SVGA_REG_PSEUDOCOLOR:

        ret = 0x0;

        break;

    case SVGA_REG_RED_MASK:

        ret = surface->pf.rmask;

        break;

    case SVGA_REG_GREEN_MASK:

        ret = surface->pf.gmask;

        break;

    case SVGA_REG_BLUE_MASK:

        ret = surface->pf.bmask;

        break;

    case SVGA_REG_BYTES_PER_LINE:

        ret = s->bypp * s->new_width;

        break;

    case SVGA_REG_FB_START: {

        struct pci_vmsvga_state_s *pci_vmsvga

            = container_of(s, struct pci_vmsvga_state_s, chip);

        ret = pci_get_bar_addr(&pci_vmsvga->card, 1);

        break;

    }

    case SVGA_REG_FB_OFFSET:

        ret = 0x0;

        break;

    case SVGA_REG_VRAM_SIZE:

        ret = s->vga.vram_size; /* No physical VRAM besides the framebuffer */

        break;

    case SVGA_REG_FB_SIZE:

        ret = s->vga.vram_size;

        break;

    case SVGA_REG_CAPABILITIES:

        caps = SVGA_CAP_NONE;

#ifdef HW_RECT_ACCEL

        caps |= SVGA_CAP_RECT_COPY;

#endif

#ifdef HW_FILL_ACCEL

        caps |= SVGA_CAP_RECT_FILL;

#endif

#ifdef HW_MOUSE_ACCEL

        if (dpy_cursor_define_supported(s->vga.con)) {

            caps |= SVGA_CAP_CURSOR | SVGA_CAP_CURSOR_BYPASS_2 |

                    SVGA_CAP_CURSOR_BYPASS;

        }

#endif

        ret = caps;

        break;

    case SVGA_REG_MEM_START: {

        struct pci_vmsvga_state_s *pci_vmsvga

            = container_of(s, struct pci_vmsvga_state_s, chip);

        ret = pci_get_bar_addr(&pci_vmsvga->card, 2);

        break;

    }

    case SVGA_REG_MEM_SIZE:

        ret = s->fifo_size;

        break;

    case SVGA_REG_CONFIG_DONE:

        ret = s->config;

        break;

    case SVGA_REG_SYNC:

    case SVGA_REG_BUSY:

        ret = s->syncing;

        break;

    case SVGA_REG_GUEST_ID:

        ret = s->guest;

        break;

    case SVGA_REG_CURSOR_ID:

        ret = s->cursor.id;

        break;

    case SVGA_REG_CURSOR_X:

        ret = s->cursor.x;

        break;

    case SVGA_REG_CURSOR_Y:

        ret = s->cursor.x;

        break;

    case SVGA_REG_CURSOR_ON:

        ret = s->cursor.on;

        break;

    case SVGA_REG_HOST_BITS_PER_PIXEL:

        ret = (s->depth + 7) & ~7;

        break;

    case SVGA_REG_SCRATCH_SIZE:

        ret = s->scratch_size;

        break;

    case SVGA_REG_MEM_REGS:

    case SVGA_REG_NUM_DISPLAYS:

    case SVGA_REG_PITCHLOCK:

    case SVGA_PALETTE_BASE ... SVGA_PALETTE_END:

        ret = 0;

        break;

    default:

        if (s->index >= SVGA_SCRATCH_BASE &&

            s->index < SVGA_SCRATCH_BASE + s->scratch_size) {

            ret = s->scratch[s->index - SVGA_SCRATCH_BASE];

            break;

        }

        printf("%s: Bad register %02x\n", __func__, s->index);

        ret = 0;

        break;

    }

    if (s->index >= SVGA_SCRATCH_BASE) {

        trace_vmware_scratch_read(s->index, ret);

    } else if (s->index >= SVGA_PALETTE_BASE) {

        trace_vmware_palette_read(s->index, ret);

    } else {

        trace_vmware_value_read(s->index, ret);

    }

    return ret;

}


static uint32_t pxa2xx_gpio_read(void *opaque, target_phys_addr_t offset)
{
    struct pxa2xx_gpio_info_s *s = (struct pxa2xx_gpio_info_s *) opaque;
    uint32_t ret;
    int bank;
    offset -= s->base;
    if (offset >= 0x200)
        return 0;
    bank = pxa2xx_gpio_regs[offset].bank;
    switch (pxa2xx_gpio_regs[offset].reg) {
    case GPDR:		/* GPIO Pin-Direction registers */
        return s->dir[bank];
    case GRER:		/* GPIO Rising-Edge Detect Enable registers */
        return s->rising[bank];
    case GFER:		/* GPIO Falling-Edge Detect Enable registers */
        return s->falling[bank];
    case GAFR_L:	/* GPIO Alternate Function registers */
        return s->gafr[bank * 2];
    case GAFR_U:	/* GPIO Alternate Function registers */
        return s->gafr[bank * 2 + 1];
    case GPLR:		/* GPIO Pin-Level registers */
        ret = (s->olevel[bank] & s->dir[bank]) |
                (s->ilevel[bank] & ~s->dir[bank]);
        if (s->read_notify)
            s->read_notify(s->opaque);
        return ret;
    case GEDR:		/* GPIO Edge Detect Status registers */
        return s->status[bank];
    default:
        cpu_abort(cpu_single_env,
                "%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);
    }
    return 0;
}


void rgb24tobgr32(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	unsigned i;

	for(i=0; 3*i<src_size; i++)

	{

		dst[4*i + 0] = src[3*i + 2];

		dst[4*i + 1] = src[3*i + 1];

		dst[4*i + 2] = src[3*i + 0];

		dst[4*i + 3] = 0;

	}

}


int qcrypto_init(Error **errp)

{

#ifdef CONFIG_GNUTLS

    int ret;

    ret = gnutls_global_init();

    if (ret < 0) {

        error_setg(errp,

                   "Unable to initialize GNUTLS library: %s",

                   gnutls_strerror(ret));

        return -1;

    }

#ifdef DEBUG_GNUTLS

    gnutls_global_set_log_level(10);

    gnutls_global_set_log_function(qcrypto_gnutls_log);

#endif

#endif

#ifdef CONFIG_GCRYPT

    if (!gcry_check_version(GCRYPT_VERSION)) {

        error_setg(errp, "Unable to initialize gcrypt");

        return -1;

    }

#ifdef QCRYPTO_INIT_GCRYPT_THREADS

    gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);

#endif /* QCRYPTO_INIT_GCRYPT_THREADS */

    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

#endif

    return 0;

}


libAVFilter_QueryVendorInfo(libAVFilter *this, wchar_t **info)

{

    dshowdebug("libAVFilter_QueryVendorInfo(%p)\n", this);

    if (!info)

        return E_POINTER;

    *info = wcsdup(L"libAV");

    return S_OK;

}


static int compute_mb_distortion(CinepakEncContext *s, AVPicture *a, AVPicture *b)

{

    int x, y, p, d, ret = 0;

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

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

            d = a->data[0][x + y*a->linesize[0]] - b->data[0][x + y*b->linesize[0]];

            ret += d*d;

        }

    }

    if(s->pix_fmt == AV_PIX_FMT_YUV420P) {

        for(p = 1; p <= 2; p++) {

            for(y = 0; y < MB_SIZE/2; y++) {

                for(x = 0; x < MB_SIZE/2; x++) {

                    d = a->data[p][x + y*a->linesize[p]] - b->data[p][x + y*b->linesize[p]];

                    ret += d*d;

                }

            }

        }

    }

    return ret;

}


static VirtIOSerialBus *virtser_bus_new(DeviceState *dev)

{

    VirtIOSerialBus *bus;

    bus = FROM_QBUS(VirtIOSerialBus, qbus_create(&virtser_bus_info, dev, NULL));

    bus->qbus.allow_hotplug = 1;

    return bus;

}


static int vp8_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata,

                                    int jobnr, int threadnr)

{

    VP8Context *s = avctx->priv_data;

    VP8ThreadData *td = &s->thread_data[jobnr];

    VP8ThreadData *next_td = NULL, *prev_td = NULL;

    VP8Frame *curframe = s->curframe;

    int mb_y, num_jobs = s->num_jobs;

    td->thread_nr = threadnr;

    for (mb_y = jobnr; mb_y < s->mb_height; mb_y += num_jobs) {

        if (mb_y >= s->mb_height)

            break;

        td->thread_mb_pos = mb_y << 16;

        vp8_decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr);

        if (s->deblock_filter)

            vp8_filter_mb_row(avctx, tdata, jobnr, threadnr);

        update_pos(td, mb_y, INT_MAX & 0xFFFF);

        s->mv_min.y -= 64;

        s->mv_max.y -= 64;

        if (avctx->active_thread_type == FF_THREAD_FRAME)

            ff_thread_report_progress(&curframe->tf, mb_y, 0);

    }

    return 0;

}


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

{

	long i;

	for(i=0; 3*i<src_size; i++)

	{

		#ifdef WORDS_BIGENDIAN

			/* RGB24 (= R,G,B) -> BGR32 (= A,R,G,B) */

			dst[4*i + 0] = 0;

			dst[4*i + 1] = src[3*i + 0];

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

			dst[4*i + 3] = src[3*i + 2];

		#else

			dst[4*i + 0] = src[3*i + 2];

			dst[4*i + 1] = src[3*i + 1];

			dst[4*i + 2] = src[3*i + 0];

			dst[4*i + 3] = 0;

		#endif

	}

}


static int ea_read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    EaDemuxContext *ea = s->priv_data;

    ByteIOContext *pb = s->pb;

    int ret = 0;

    int packet_read = 0;

    unsigned int chunk_type, chunk_size;

    int key = 0;

    int av_uninit(num_samples);

    while (!packet_read) {

        chunk_type = get_le32(pb);

        chunk_size = (ea->big_endian ? get_be32(pb) : get_le32(pb)) - 8;

        switch (chunk_type) {

        /* audio data */

        case ISNh_TAG:

            /* header chunk also contains data; skip over the header portion*/

            url_fskip(pb, 32);

            chunk_size -= 32;

        case ISNd_TAG:

        case SCDl_TAG:

        case SNDC_TAG:

        case SDEN_TAG:

            if (!ea->audio_codec) {

                url_fskip(pb, chunk_size);

                break;

            } else if (ea->audio_codec == CODEC_ID_PCM_S16LE_PLANAR ||

                       ea->audio_codec == CODEC_ID_MP3) {

                num_samples = get_le32(pb);

                url_fskip(pb, 8);

                chunk_size -= 12;

            }

            ret = av_get_packet(pb, pkt, chunk_size);

            if (ret != chunk_size)

                ret = AVERROR(EIO);

            else {

                    pkt->stream_index = ea->audio_stream_index;

                    pkt->pts = 90000;

                    pkt->pts *= ea->audio_frame_counter;

                    pkt->pts /= ea->sample_rate;

                    switch (ea->audio_codec) {

                    case CODEC_ID_ADPCM_EA:

                    /* 2 samples/byte, 1 or 2 samples per frame depending

                     * on stereo; chunk also has 12-byte header */

                    ea->audio_frame_counter += ((chunk_size - 12) * 2) /

                        ea->num_channels;

                        break;

                    case CODEC_ID_PCM_S16LE_PLANAR:

                    case CODEC_ID_MP3:

                        ea->audio_frame_counter += num_samples;

                        break;

                    default:

                        ea->audio_frame_counter += chunk_size /

                            (ea->bytes * ea->num_channels);

                    }

            }

            packet_read = 1;

            break;

        /* ending tag */

        case 0:

        case ISNe_TAG:

        case SCEl_TAG:

        case SEND_TAG:

        case SEEN_TAG:

            ret = AVERROR(EIO);

            packet_read = 1;

            break;

        case MVIh_TAG:

        case kVGT_TAG:

        case pQGT_TAG:

        case TGQs_TAG:

            key = PKT_FLAG_KEY;

        case MVIf_TAG:

        case fVGT_TAG:

            url_fseek(pb, -8, SEEK_CUR);     // include chunk preamble

            chunk_size += 8;

            goto get_video_packet;

        case mTCD_TAG:

            url_fseek(pb, 8, SEEK_CUR);  // skip ea dct header

            chunk_size -= 8;

            goto get_video_packet;

        case MV0K_TAG:

        case MPCh_TAG:

        case pIQT_TAG:

            key = PKT_FLAG_KEY;

        case MV0F_TAG:

get_video_packet:

            ret = av_get_packet(pb, pkt, chunk_size);

            if (ret != chunk_size)

                ret = AVERROR_IO;

            else {

                pkt->stream_index = ea->video_stream_index;

                pkt->flags |= key;

            }

            packet_read = 1;

            break;

        default:

            url_fseek(pb, chunk_size, SEEK_CUR);

            break;

        }

    }

    return ret;

}


static void decode_interframe_v4a(AVCodecContext *avctx, uint8_t *src,

                                  uint32_t size)

{

    Hnm4VideoContext *hnm = avctx->priv_data;

    GetByteContext gb;

    uint32_t writeoffset = 0, offset;

    uint8_t tag, count, previous, delta;

    bytestream2_init(&gb, src, size);

    while (bytestream2_tell(&gb) < size) {

        count = bytestream2_peek_byte(&gb) & 0x3F;

        if (count == 0) {

            tag = bytestream2_get_byte(&gb) & 0xC0;

            tag = tag >> 6;

            if (tag == 0) {

                writeoffset += bytestream2_get_byte(&gb);

            } else if (tag == 1) {

                if (writeoffset + hnm->width >= hnm->width * hnm->height) {

                    av_log(avctx, AV_LOG_ERROR, "writeoffset out of bounds\n");

                    break;

                }

                hnm->current[writeoffset]              = bytestream2_get_byte(&gb);

                hnm->current[writeoffset + hnm->width] = bytestream2_get_byte(&gb);

                writeoffset++;

            } else if (tag == 2) {

                writeoffset += hnm->width;

            } else if (tag == 3) {

                break;

            }

            if (writeoffset > hnm->width * hnm->height) {

                av_log(avctx, AV_LOG_ERROR, "writeoffset out of bounds\n");

                break;

            }

        } else {

            delta    = bytestream2_peek_byte(&gb) & 0x80;

            previous = bytestream2_peek_byte(&gb) & 0x40;

            bytestream2_skip(&gb, 1);

            offset  = writeoffset;

            offset += bytestream2_get_le16(&gb);

            if (delta)

                offset -= 0x10000;

            if (offset + hnm->width + count >= hnm->width * hnm->height) {

                av_log(avctx, AV_LOG_ERROR, "Attempting to read out of bounds\n");

                break;

            } else if (writeoffset + hnm->width + count >= hnm->width * hnm->height) {

                av_log(avctx, AV_LOG_ERROR, "Attempting to write out of bounds\n");

                break;

            }

            if (previous) {

                while (count > 0) {

                    hnm->current[writeoffset]              = hnm->previous[offset];

                    hnm->current[writeoffset + hnm->width] = hnm->previous[offset + hnm->width];

                    writeoffset++;

                    offset++;

                    count--;

                }

            } else {

                while (count > 0) {

                    hnm->current[writeoffset]              = hnm->current[offset];

                    hnm->current[writeoffset + hnm->width] = hnm->current[offset + hnm->width];

                    writeoffset++;

                    offset++;

                    count--;

                }

            }

        }

    }

}


static void roqvideo_decode_frame(RoqContext *ri)

{

    unsigned int chunk_id = 0, chunk_arg = 0;

    unsigned long chunk_size = 0;

    int i, j, k, nv1, nv2, vqflg = 0, vqflg_pos = -1;

    int vqid, bpos, xpos, ypos, xp, yp, x, y, mx, my;

    int frame_stats[2][4] = {{0},{0}};

    roq_qcell *qcell;

    const unsigned char *buf = ri->buf;

    const unsigned char *buf_end = ri->buf + ri->size;

    while (buf < buf_end) {

        chunk_id = bytestream_get_le16(&buf);

        chunk_size = bytestream_get_le32(&buf);

        chunk_arg = bytestream_get_le16(&buf);

        if(chunk_id == RoQ_QUAD_VQ)

            break;

        if(chunk_id == RoQ_QUAD_CODEBOOK) {

            if((nv1 = chunk_arg >> 8) == 0)

                nv1 = 256;

            if((nv2 = chunk_arg & 0xff) == 0 && nv1 * 6 < chunk_size)

                nv2 = 256;

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

                ri->cb2x2[i].y[0] = *buf++;

                ri->cb2x2[i].y[1] = *buf++;

                ri->cb2x2[i].y[2] = *buf++;

                ri->cb2x2[i].y[3] = *buf++;

                ri->cb2x2[i].u = *buf++;

                ri->cb2x2[i].v = *buf++;

            }

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

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

                    ri->cb4x4[i].idx[j] = *buf++;

        }

    }

    bpos = xpos = ypos = 0;

    if (chunk_size > buf_end - buf) {

        av_log(ri->avctx, AV_LOG_ERROR, "Chunk does not fit in input buffer\n");

        chunk_size = buf_end - buf;

    }

    while(bpos < chunk_size) {

        for (yp = ypos; yp < ypos + 16; yp += 8)

            for (xp = xpos; xp < xpos + 16; xp += 8) {

                if (bpos >= chunk_size) {

                    av_log(ri->avctx, AV_LOG_ERROR, "Input buffer too small\n");

                    return;

                }

                if (vqflg_pos < 0) {

                    vqflg = buf[bpos++]; vqflg |= (buf[bpos++] << 8);

                    vqflg_pos = 7;

                }

                vqid = (vqflg >> (vqflg_pos * 2)) & 0x3;

                frame_stats[0][vqid]++;

                vqflg_pos--;

                switch(vqid) {

                case RoQ_ID_MOT:

                    break;

                case RoQ_ID_FCC:

                    mx = 8 - (buf[bpos] >> 4) - ((signed char) (chunk_arg >> 8));

                    my = 8 - (buf[bpos++] & 0xf) - ((signed char) chunk_arg);

                    ff_apply_motion_8x8(ri, xp, yp, mx, my);

                    break;

                case RoQ_ID_SLD:

                    qcell = ri->cb4x4 + buf[bpos++];

                    ff_apply_vector_4x4(ri, xp, yp, ri->cb2x2 + qcell->idx[0]);

                    ff_apply_vector_4x4(ri, xp+4, yp, ri->cb2x2 + qcell->idx[1]);

                    ff_apply_vector_4x4(ri, xp, yp+4, ri->cb2x2 + qcell->idx[2]);

                    ff_apply_vector_4x4(ri, xp+4, yp+4, ri->cb2x2 + qcell->idx[3]);

                    break;

                case RoQ_ID_CCC:

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

                        x = xp; y = yp;

                        if(k & 0x01) x += 4;

                        if(k & 0x02) y += 4;

                        if (bpos >= chunk_size) {

                            av_log(ri->avctx, AV_LOG_ERROR, "Input buffer too small\n");

                            return;

                        }

                        if (vqflg_pos < 0) {

                            vqflg = buf[bpos++];

                            vqflg |= (buf[bpos++] << 8);

                            vqflg_pos = 7;

                        }

                        vqid = (vqflg >> (vqflg_pos * 2)) & 0x3;

                        frame_stats[1][vqid]++;

                        vqflg_pos--;

                        switch(vqid) {

                        case RoQ_ID_MOT:

                            break;

                        case RoQ_ID_FCC:

                            mx = 8 - (buf[bpos] >> 4) - ((signed char) (chunk_arg >> 8));

                            my = 8 - (buf[bpos++] & 0xf) - ((signed char) chunk_arg);

                            ff_apply_motion_4x4(ri, x, y, mx, my);

                            break;

                        case RoQ_ID_SLD:

                            qcell = ri->cb4x4 + buf[bpos++];

                            ff_apply_vector_2x2(ri, x, y, ri->cb2x2 + qcell->idx[0]);

                            ff_apply_vector_2x2(ri, x+2, y, ri->cb2x2 + qcell->idx[1]);

                            ff_apply_vector_2x2(ri, x, y+2, ri->cb2x2 + qcell->idx[2]);

                            ff_apply_vector_2x2(ri, x+2, y+2, ri->cb2x2 + qcell->idx[3]);

                            break;

                        case RoQ_ID_CCC:

                            ff_apply_vector_2x2(ri, x, y, ri->cb2x2 + buf[bpos]);

                            ff_apply_vector_2x2(ri, x+2, y, ri->cb2x2 + buf[bpos+1]);

                            ff_apply_vector_2x2(ri, x, y+2, ri->cb2x2 + buf[bpos+2]);

                            ff_apply_vector_2x2(ri, x+2, y+2, ri->cb2x2 + buf[bpos+3]);

                            bpos += 4;

                            break;

                        }

                    }

                    break;

                default:

                    av_log(ri->avctx, AV_LOG_ERROR, "Unknown vq code: %d\n", vqid);

            }

        }

        xpos += 16;

        if (xpos >= ri->width) {

            xpos -= ri->width;

            ypos += 16;

        }

        if(ypos >= ri->height)

            break;

    }

}


static void build_udp_url(char *buf, int buf_size,

                          const char *hostname, int port,

                          int local_port, int ttl)

{

    snprintf(buf, buf_size, "udp://%s:%d", hostname, port);

    if (local_port >= 0)

        url_add_option(buf, buf_size, "localport=%d", local_port);

    if (ttl >= 0)

        url_add_option(buf, buf_size, "ttl=%d", ttl);

}


static av_cold int wavpack_encode_init(AVCodecContext *avctx)

{

    WavPackEncodeContext *s = avctx->priv_data;

    s->avctx = avctx;

    if (!avctx->frame_size) {

        int block_samples;

        if (!(avctx->sample_rate & 1))

            block_samples = avctx->sample_rate / 2;

        else

            block_samples = avctx->sample_rate;

        while (block_samples * avctx->channels > 150000)

            block_samples /= 2;

        while (block_samples * avctx->channels < 40000)

            block_samples *= 2;

        avctx->frame_size = block_samples;

    } else if (avctx->frame_size && (avctx->frame_size < 128 ||

                              avctx->frame_size > WV_MAX_SAMPLES)) {

        av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n", avctx->frame_size);

        return AVERROR(EINVAL);

    }

    if (avctx->compression_level != FF_COMPRESSION_DEFAULT) {

        if (avctx->compression_level >= 3) {

            s->decorr_filter = 3;

            s->num_passes = 9;

            if      (avctx->compression_level >= 8) {

                s->num_branches = 4;

                s->extra_flags = EXTRA_TRY_DELTAS|EXTRA_ADJUST_DELTAS|EXTRA_SORT_FIRST|EXTRA_SORT_LAST|EXTRA_BRANCHES;

            } else if (avctx->compression_level >= 7) {

                s->num_branches = 3;

                s->extra_flags = EXTRA_TRY_DELTAS|EXTRA_ADJUST_DELTAS|EXTRA_SORT_FIRST|EXTRA_BRANCHES;

            } else if (avctx->compression_level >= 6) {

                s->num_branches = 2;

                s->extra_flags = EXTRA_TRY_DELTAS|EXTRA_ADJUST_DELTAS|EXTRA_SORT_FIRST|EXTRA_BRANCHES;

            } else if (avctx->compression_level >= 5) {

                s->num_branches = 1;

                s->extra_flags = EXTRA_TRY_DELTAS|EXTRA_ADJUST_DELTAS|EXTRA_SORT_FIRST|EXTRA_BRANCHES;

            } else if (avctx->compression_level >= 4) {

                s->num_branches = 1;

                s->extra_flags = EXTRA_TRY_DELTAS|EXTRA_ADJUST_DELTAS|EXTRA_BRANCHES;

            }

        } else if (avctx->compression_level == 2) {

            s->decorr_filter = 2;

            s->num_passes = 4;

        } else if (avctx->compression_level == 1) {

            s->decorr_filter = 1;

            s->num_passes = 2;

        } else if (avctx->compression_level < 1) {

            s->decorr_filter = 0;

            s->num_passes = 0;

        }

    }

    s->num_decorrs = decorr_filter_sizes[s->decorr_filter];

    s->decorr_specs = decorr_filters[s->decorr_filter];

    s->delta_decay = 2.0;

    return 0;

}


static int sub2video_prepare(InputStream *ist)

{

    AVFormatContext *avf = input_files[ist->file_index]->ctx;

    int i, w, h;

    /* Compute the size of the canvas for the subtitles stream.

       If the subtitles codec has set a size, use it. Otherwise use the

       maximum dimensions of the video streams in the same file. */

    w = ist->dec_ctx->width;

    h = ist->dec_ctx->height;

    if (!(w && h)) {

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

            if (avf->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

                w = FFMAX(w, avf->streams[i]->codec->width);

                h = FFMAX(h, avf->streams[i]->codec->height);

            }

        }

        if (!(w && h)) {

            w = FFMAX(w, 720);

            h = FFMAX(h, 576);

        }

        av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);

    }

    ist->sub2video.w = ist->dec_ctx->width  = ist->resample_width  = w;

    ist->sub2video.h = ist->dec_ctx->height = ist->resample_height = h;

    /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the

       palettes for all rectangles are identical or compatible */

    ist->resample_pix_fmt = ist->dec_ctx->pix_fmt = AV_PIX_FMT_RGB32;

    ist->sub2video.frame = av_frame_alloc();

    if (!ist->sub2video.frame)

        return AVERROR(ENOMEM);

    ist->sub2video.last_pts = INT64_MIN;

    return 0;

}


static int arm946_prbs_read(CPUARMState *env, const ARMCPRegInfo *ri,

                            uint64_t *value)

{

    if (ri->crm > 8) {

        return EXCP_UDEF;

    }

    *value = env->cp15.c6_region[ri->crm];

    return 0;

}


static int compat_read(AVFilterContext *ctx, AVFilterBufferRef **pbuf, int nb_samples)

{

    AVFilterBufferRef *buf;

    AVFrame *frame;

    int ret;

    if (!pbuf)

        return ff_poll_frame(ctx->inputs[0]);

    frame = av_frame_alloc();

    if (!frame)

        return AVERROR(ENOMEM);

    if (!nb_samples)

        ret = av_buffersink_get_frame(ctx, frame);

    else

        ret = av_buffersink_get_samples(ctx, frame, nb_samples);

    if (ret < 0)

        goto fail;

    if (ctx->inputs[0]->type == AVMEDIA_TYPE_VIDEO) {

        buf = avfilter_get_video_buffer_ref_from_arrays(frame->data, frame->linesize,

                                                        AV_PERM_READ,

                                                        frame->width, frame->height,

                                                        frame->format);

    } else {

        buf = avfilter_get_audio_buffer_ref_from_arrays(frame->extended_data,

                                                        frame->linesize[0], AV_PERM_READ,

                                                        frame->nb_samples,

                                                        frame->format,

                                                        frame->channel_layout);

    }

    if (!buf) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    avfilter_copy_frame_props(buf, frame);

    buf->buf->priv = frame;

    buf->buf->free = compat_free_buffer;

    *pbuf = buf;

    return 0;

fail:

    av_frame_free(&frame);

    return ret;

}


int cpu_ppc_register (CPUPPCState *env, ppc_def_t *def)

{

    env->msr_mask = def->msr_mask;

    env->mmu_model = def->mmu_model;

    env->excp_model = def->excp_model;

    env->bus_model = def->bus_model;

    env->bfd_mach = def->bfd_mach;

    if (create_ppc_opcodes(env, def) < 0)

        return -1;

    init_ppc_proc(env, def);

#if defined(PPC_DUMP_CPU)

    {

        const unsigned char *mmu_model, *excp_model, *bus_model;

        switch (env->mmu_model) {

        case POWERPC_MMU_32B:

            mmu_model = "PowerPC 32";

            break;

        case POWERPC_MMU_601:

            mmu_model = "PowerPC 601";

            break;

        case POWERPC_MMU_SOFT_6xx:

            mmu_model = "PowerPC 6xx/7xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_74xx:

            mmu_model = "PowerPC 74xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_4xx:

            mmu_model = "PowerPC 4xx with software driven TLBs";

            break;

        case POWERPC_MMU_SOFT_4xx_Z:

            mmu_model = "PowerPC 4xx with software driven TLBs "

                "and zones protections";

            break;

        case POWERPC_MMU_REAL_4xx:

            mmu_model = "PowerPC 4xx real mode only";

            break;

        case POWERPC_MMU_BOOKE:

            mmu_model = "PowerPC BookE";

            break;

        case POWERPC_MMU_BOOKE_FSL:

            mmu_model = "PowerPC BookE FSL";

            break;

#if defined (TARGET_PPC64)

        case POWERPC_MMU_64B:

            mmu_model = "PowerPC 64";

            break;

        case POWERPC_MMU_64BRIDGE:

            mmu_model = "PowerPC 64 bridge";

            break;

#endif

        default:

            mmu_model = "Unknown or invalid";

            break;

        }

        switch (env->excp_model) {

        case POWERPC_EXCP_STD:

            excp_model = "PowerPC";

            break;

        case POWERPC_EXCP_40x:

            excp_model = "PowerPC 40x";

            break;

        case POWERPC_EXCP_601:

            excp_model = "PowerPC 601";

            break;

        case POWERPC_EXCP_602:

            excp_model = "PowerPC 602";

            break;

        case POWERPC_EXCP_603:

            excp_model = "PowerPC 603";

            break;

        case POWERPC_EXCP_603E:

            excp_model = "PowerPC 603e";

            break;

        case POWERPC_EXCP_604:

            excp_model = "PowerPC 604";

            break;

        case POWERPC_EXCP_7x0:

            excp_model = "PowerPC 740/750";

            break;

        case POWERPC_EXCP_7x5:

            excp_model = "PowerPC 745/755";

            break;

        case POWERPC_EXCP_74xx:

            excp_model = "PowerPC 74xx";

            break;

        case POWERPC_EXCP_BOOKE:

            excp_model = "PowerPC BookE";

            break;

#if defined (TARGET_PPC64)

        case POWERPC_EXCP_970:

            excp_model = "PowerPC 970";

            break;

#endif

        default:

            excp_model = "Unknown or invalid";

            break;

        }

        switch (env->bus_model) {

        case PPC_FLAGS_INPUT_6xx:

            bus_model = "PowerPC 6xx";

            break;

        case PPC_FLAGS_INPUT_BookE:

            bus_model = "PowerPC BookE";

            break;

        case PPC_FLAGS_INPUT_405:

            bus_model = "PowerPC 405";

            break;

        case PPC_FLAGS_INPUT_401:

            bus_model = "PowerPC 401/403";

            break;

#if defined (TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

            bus_model = "PowerPC 970";

            break;

#endif

        default:

            bus_model = "Unknown or invalid";

            break;

        }

        printf("PowerPC %-12s : PVR %08x MSR %016" PRIx64 "\n"

               "    MMU model        : %s\n",

               def->name, def->pvr, def->msr_mask, mmu_model);

        if (env->tlb != NULL) {

            printf("                       %d %s TLB in %d ways\n",

                   env->nb_tlb, env->id_tlbs ? "splitted" : "merged",

                   env->nb_ways);

        }

        printf("    Exceptions model : %s\n"

               "    Bus model        : %s\n",

               excp_model, bus_model);

    }

    dump_ppc_insns(env);

    dump_ppc_sprs(env);

    fflush(stdout);

#endif

    return 0;

}


static uint64_t unin_data_read(void *opaque, hwaddr addr,

                               unsigned len)

{

    UNINState *s = opaque;

    PCIHostState *phb = PCI_HOST_BRIDGE(s);

    uint32_t val;

    val = pci_data_read(phb->bus,

                        unin_get_config_reg(phb->config_reg, addr),

                        len);

    UNIN_DPRINTF("read addr %" TARGET_FMT_plx " len %d val %x\n",

                 addr, len, val);

    return val;

}


static void pc_fw_cfg_guest_info(PcGuestInfo *guest_info)

{

    PcRomPciInfo *info;

    if (!guest_info->has_pci_info || !guest_info->fw_cfg) {

        return;

    }

    info = g_malloc(sizeof *info);

    info->w32_min = cpu_to_le64(guest_info->pci_info.w32.begin);

    info->w32_max = cpu_to_le64(guest_info->pci_info.w32.end);

    info->w64_min = cpu_to_le64(guest_info->pci_info.w64.begin);

    info->w64_max = cpu_to_le64(guest_info->pci_info.w64.end);

    /* Pass PCI hole info to guest via a side channel.

     * Required so guest PCI enumeration does the right thing. */

    fw_cfg_add_file(guest_info->fw_cfg, "etc/pci-info", info, sizeof *info);

}


static void set_sel_time(IPMIBmcSim *ibs,

                         uint8_t *cmd, unsigned int cmd_len,

                         uint8_t *rsp, unsigned int *rsp_len,

                         unsigned int max_rsp_len)

{

    uint32_t val;

    struct ipmi_time now;

    IPMI_CHECK_CMD_LEN(6);

    val = cmd[2] | (cmd[3] << 8) | (cmd[4] << 16) | (cmd[5] << 24);

    ipmi_gettime(&now);

    ibs->sel.time_offset = now.tv_sec - ((long) val);

}


static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,

                                    int i)

{

    VRingMemoryRegionCaches *caches = atomic_rcu_read(&vq->vring.caches);

    hwaddr pa = offsetof(VRingUsed, ring[i]);

    virtio_tswap32s(vq->vdev, &uelem->id);

    virtio_tswap32s(vq->vdev, &uelem->len);

    address_space_write_cached(&caches->used, pa, uelem, sizeof(VRingUsedElem));

    address_space_cache_invalidate(&caches->used, pa, sizeof(VRingUsedElem));

}


static void integratorcm_init(int memsz, uint32_t flash_offset)

{

    int iomemtype;

    integratorcm_state *s;

    s = (integratorcm_state *)qemu_mallocz(sizeof(integratorcm_state));

    s->cm_osc = 0x01000048;

    /* ??? What should the high bits of this value be?  */

    s->cm_auxosc = 0x0007feff;

    s->cm_sdram = 0x00011122;

    if (memsz >= 256) {

        integrator_spd[31] = 64;

        s->cm_sdram |= 0x10;

    } else if (memsz >= 128) {

        integrator_spd[31] = 32;

        s->cm_sdram |= 0x0c;

    } else if (memsz >= 64) {

        integrator_spd[31] = 16;

        s->cm_sdram |= 0x08;

    } else if (memsz >= 32) {

        integrator_spd[31] = 4;

        s->cm_sdram |= 0x04;

    } else {

        integrator_spd[31] = 2;

    }

    memcpy(integrator_spd + 73, "QEMU-MEMORY", 11);

    s->cm_init = 0x00000112;

    s->flash_offset = flash_offset;

    iomemtype = cpu_register_io_memory(0, integratorcm_readfn,

                                       integratorcm_writefn, s);

    cpu_register_physical_memory(0x10000000, 0x007fffff, iomemtype);

    integratorcm_do_remap(s, 1);

    /* ??? Save/restore.  */

}


static int mlib_YUV2ARGB420_32(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    assert(srcStride[1] == srcStride[2]);

    mlib_VideoColorYUV2ARGB420(dst[0]+srcSliceY*dstStride[0], src[0], src[1], src[2], c->dstW,

			     srcSliceH, dstStride[0], srcStride[0], srcStride[1]);

    return srcSliceH;

}


int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
                      AVPacket *avpkt, int is_vp7)
{
    VP8Context *s = avctx->priv_data;
    int ret, i, referenced, num_jobs;
    enum AVDiscard skip_thresh;
    VP8Frame *av_uninit(curframe), *prev_frame;
    if (is_vp7)
        ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);
    else
        ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size);
    if (ret < 0)
        goto err;
    prev_frame = s->framep[VP56_FRAME_CURRENT];
    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||
                 s->update_altref == VP56_FRAME_CURRENT;
    skip_thresh = !referenced ? AVDISCARD_NONREF
                              : !s->keyframe ? AVDISCARD_NONKEY
                                             : AVDISCARD_ALL;
    if (avctx->skip_frame >= skip_thresh) {
        s->invisible = 1;
        memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
        goto skip_decode;
    }
    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;
    // release no longer referenced frames
    for (i = 0; i < 5; i++)
        if (s->frames[i].tf.f->data[0] &&
            &s->frames[i] != prev_frame &&
            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&
            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN]   &&
            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])
            vp8_release_frame(s, &s->frames[i]);
    curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s);
    if (!s->colorspace)
        avctx->colorspace = AVCOL_SPC_BT470BG;
    if (s->fullrange)
        avctx->color_range = AVCOL_RANGE_JPEG;
    else
        avctx->color_range = AVCOL_RANGE_MPEG;
    /* Given that arithmetic probabilities are updated every frame, it's quite
     * likely that the values we have on a random interframe are complete
     * junk if we didn't start decode on a keyframe. So just don't display
     * anything rather than junk. */
    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||
                         !s->framep[VP56_FRAME_GOLDEN]   ||
                         !s->framep[VP56_FRAME_GOLDEN2])) {
        av_log(avctx, AV_LOG_WARNING,
               "Discarding interframe without a prior keyframe!\n");
        ret = AVERROR_INVALIDDATA;
        goto err;
    }
    curframe->tf.f->key_frame = s->keyframe;
    curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
                                            : AV_PICTURE_TYPE_P;
    if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0)
        goto err;
    // check if golden and altref are swapped
    if (s->update_altref != VP56_FRAME_NONE)
        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];
    else
        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];
    if (s->update_golden != VP56_FRAME_NONE)
        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];
    else
        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];
    if (s->update_last)
        s->next_framep[VP56_FRAME_PREVIOUS] = curframe;
    else
        s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];
    s->next_framep[VP56_FRAME_CURRENT] = curframe;
    if (avctx->codec->update_thread_context)
        ff_thread_finish_setup(avctx);
    s->linesize   = curframe->tf.f->linesize[0];
    s->uvlinesize = curframe->tf.f->linesize[1];
    memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));
    /* Zero macroblock structures for top/top-left prediction
     * from outside the frame. */
    if (!s->mb_layout)
        memset(s->macroblocks + s->mb_height * 2 - 1, 0,
               (s->mb_width + 1) * sizeof(*s->macroblocks));
    if (!s->mb_layout && s->keyframe)
        memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);
    memset(s->ref_count, 0, sizeof(s->ref_count));
    if (s->mb_layout == 1) {
        // Make sure the previous frame has read its segmentation map,
        // if we re-use the same map.
        if (prev_frame && s->segmentation.enabled &&
            !s->segmentation.update_map)
            ff_thread_await_progress(&prev_frame->tf, 1, 0);
        if (is_vp7)
            vp7_decode_mv_mb_modes(avctx, curframe, prev_frame);
        else
            vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);
    }
    if (avctx->active_thread_type == FF_THREAD_FRAME)
        num_jobs = 1;
    else
        num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);
    s->num_jobs   = num_jobs;
    s->curframe   = curframe;
    s->prev_frame = prev_frame;
    s->mv_bounds.mv_min.y   = -MARGIN;
    s->mv_bounds.mv_max.y   = ((s->mb_height - 1) << 6) + MARGIN;
    for (i = 0; i < MAX_THREADS; i++) {
        VP8ThreadData *td = &s->thread_data[i];
        atomic_init(&td->thread_mb_pos, 0);
        atomic_init(&td->wait_mb_pos, INT_MAX);
    }
    if (is_vp7)
        avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,
                        num_jobs);
    else
        avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL,
                        num_jobs);
    ff_thread_report_progress(&curframe->tf, INT_MAX, 0);
    memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);
skip_decode:
    // if future frames don't use the updated probabilities,
    // reset them to the values we saved
    if (!s->update_probabilities)
        s->prob[0] = s->prob[1];
    if (!s->invisible) {
        if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)
            return ret;
        *got_frame = 1;
    }
    return avpkt->size;
err:
    memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);
    return ret;
}