static bool vtd_process_inv_desc(IntelIOMMUState *s)

{

    VTDInvDesc inv_desc;

    uint8_t desc_type;

    VTD_DPRINTF(INV, "iq head %"PRIu16, s->iq_head);

    if (!vtd_get_inv_desc(s->iq, s->iq_head, &inv_desc)) {

        s->iq_last_desc_type = VTD_INV_DESC_NONE;

        return false;

    }

    desc_type = inv_desc.lo & VTD_INV_DESC_TYPE;

    /* FIXME: should update at first or at last? */

    s->iq_last_desc_type = desc_type;

    switch (desc_type) {

    case VTD_INV_DESC_CC:

        VTD_DPRINTF(INV, "Context-cache Invalidate Descriptor hi 0x%"PRIx64

                    " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);

        if (!vtd_process_context_cache_desc(s, &inv_desc)) {

            return false;

        }

        break;

    case VTD_INV_DESC_IOTLB:

        VTD_DPRINTF(INV, "IOTLB Invalidate Descriptor hi 0x%"PRIx64

                    " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);

        if (!vtd_process_iotlb_desc(s, &inv_desc)) {

            return false;

        }

        break;

    case VTD_INV_DESC_WAIT:

        VTD_DPRINTF(INV, "Invalidation Wait Descriptor hi 0x%"PRIx64

                    " lo 0x%"PRIx64, inv_desc.hi, inv_desc.lo);

        if (!vtd_process_wait_desc(s, &inv_desc)) {

            return false;

        }

        break;

    case VTD_INV_DESC_IEC:

        VTD_DPRINTF(INV, "Interrupt Entry Cache Invalidation "

                    "not implemented yet");

        /*

         * Since currently we do not cache interrupt entries, we can

         * just mark this descriptor as "good" and move on.

         */

        break;

    default:

        VTD_DPRINTF(GENERAL, "error: unkonw Invalidation Descriptor type "

                    "hi 0x%"PRIx64 " lo 0x%"PRIx64 " type %"PRIu8,

                    inv_desc.hi, inv_desc.lo, desc_type);

        return false;

    }

    s->iq_head++;

    if (s->iq_head == s->iq_size) {

        s->iq_head = 0;

    }

    return true;

}


static bool cmd_read_pio(IDEState *s, uint8_t cmd)

{

    bool lba48 = (cmd == WIN_READ_EXT);

    if (s->drive_kind == IDE_CD) {

        ide_set_signature(s); /* odd, but ATA4 8.27.5.2 requires it */

        ide_abort_command(s);

        return true;

    }

    if (!s->bs) {

        ide_abort_command(s);

        return true;

    }

    ide_cmd_lba48_transform(s, lba48);

    s->req_nb_sectors = 1;

    ide_sector_read(s);

    return false;

}


void os_setup_post(void)

{

    int fd = 0;

    if (daemonize) {

        uint8_t status = 0;

        ssize_t len;

        do {

            len = write(daemon_pipe, &status, 1);

        } while (len < 0 && errno == EINTR);

        if (len != 1) {

            exit(1);

        }

        if (chdir("/")) {

            perror("not able to chdir to /");

            exit(1);

        }

        TFR(fd = qemu_open("/dev/null", O_RDWR));

        if (fd == -1) {

            exit(1);

        }

    }

    change_root();

    change_process_uid();

    if (daemonize) {

        dup2(fd, 0);

        dup2(fd, 1);

        dup2(fd, 2);

        close(fd);

    }

}


int qcow2_check_metadata_overlap(BlockDriverState *bs, int chk, int64_t offset,

                                 int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int i, j;

    if (!size) {

        return 0;

    }

    if (chk & QCOW2_OL_MAIN_HEADER) {

        if (offset < s->cluster_size) {

            return QCOW2_OL_MAIN_HEADER;

        }

    }

    /* align range to test to cluster boundaries */

    size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);

    offset = start_of_cluster(s, offset);

    if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {

        if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {

            return QCOW2_OL_ACTIVE_L1;

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {

        if (overlaps_with(s->refcount_table_offset,

            s->refcount_table_size * sizeof(uint64_t))) {

            return QCOW2_OL_REFCOUNT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {

        if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {

            return QCOW2_OL_SNAPSHOT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {

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

            if (s->snapshots[i].l1_size &&

                overlaps_with(s->snapshots[i].l1_table_offset,

                s->snapshots[i].l1_size * sizeof(uint64_t))) {

                return QCOW2_OL_INACTIVE_L1;

            }

        }

    }

    if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {

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

            if ((s->l1_table[i] & L1E_OFFSET_MASK) &&

                overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_ACTIVE_L2;

            }

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {

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

            if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&

                overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_REFCOUNT_BLOCK;

            }

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {

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

            uint64_t l1_ofs = s->snapshots[i].l1_table_offset;

            uint32_t l1_sz  = s->snapshots[i].l1_size;

            uint64_t *l1 = g_malloc(l1_sz * sizeof(uint64_t));

            int ret;

            ret = bdrv_read(bs->file, l1_ofs / BDRV_SECTOR_SIZE, (uint8_t *)l1,

                            l1_sz * sizeof(uint64_t) / BDRV_SECTOR_SIZE);

            if (ret < 0) {

                g_free(l1);

                return ret;

            }

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

                if ((l1[j] & L1E_OFFSET_MASK) &&

                    overlaps_with(l1[j] & L1E_OFFSET_MASK, s->cluster_size)) {

                    g_free(l1);

                    return QCOW2_OL_INACTIVE_L2;

                }

            }

            g_free(l1);

        }

    }

    return 0;

}


static int cpu_x86_find_by_name(X86CPU *cpu, x86_def_t *x86_cpu_def,

                                const char *name)

{

    x86_def_t *def;

    int i;

    if (name == NULL) {

        return -1;

    }

    if (kvm_enabled() && strcmp(name, "host") == 0) {

        kvm_cpu_fill_host(x86_cpu_def);

        object_property_set_bool(OBJECT(cpu), true, "pmu", &error_abort);

        return 0;

    }

    for (i = 0; i < ARRAY_SIZE(builtin_x86_defs); i++) {

        def = &builtin_x86_defs[i];

        if (strcmp(name, def->name) == 0) {

            memcpy(x86_cpu_def, def, sizeof(*def));

            /* sysenter isn't supported in compatibility mode on AMD,

             * syscall isn't supported in compatibility mode on Intel.

             * Normally we advertise the actual CPU vendor, but you can

             * override this using the 'vendor' property if you want to use

             * KVM's sysenter/syscall emulation in compatibility mode and

             * when doing cross vendor migration

             */

            if (kvm_enabled()) {

                uint32_t  ebx = 0, ecx = 0, edx = 0;

                host_cpuid(0, 0, NULL, &ebx, &ecx, &edx);

                x86_cpu_vendor_words2str(x86_cpu_def->vendor, ebx, edx, ecx);

            }

            return 0;

        }

    }

    return -1;

}


static void put_pixels_y2_mmx(UINT8 *block, const UINT8 *pixels, int line_size, int h)

{

#if 0

  UINT8 *p;

  const UINT8 *pix;

  p = block;

  pix = pixels;

  MOVQ_ZERO(mm7);

  MOVQ_WONE(mm4);

  JUMPALIGN();

  do {

    __asm __volatile(

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

	"movq	%2, %%mm1\n\t"

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

	"movq	%%mm1, %%mm3\n\t"

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

	"punpcklbw %%mm7, %%mm1\n\t"

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

	"punpckhbw %%mm7, %%mm3\n\t"

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

	"paddusw %%mm3, %%mm2\n\t"

	"paddusw %%mm4, %%mm0\n\t"

	"paddusw %%mm4, %%mm2\n\t"

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

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

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

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

	:"=m"(*p)

	:"m"(*pix),

	 "m"(*(pix+line_size))

	:"memory");

   pix += line_size;

   p += line_size;

  } while (--h);

#else

  __asm __volatile(

  	MOVQ_BFE(%%mm7)

	"lea (%3, %3), %%eax	\n\t"

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

	".balign 8     		\n\t"

	"1:			\n\t"

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

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

	PAVG_MMX(%%mm1, %%mm0)

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

	PAVG_MMX(%%mm2, %%mm1)

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

	"addl %%eax, %1		\n\t"

	"addl %%eax, %2		\n\t"

#ifdef LONG_UNROLL

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

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

	PAVG_MMX(%%mm1, %%mm2)

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

	PAVG_MMX(%%mm0, %%mm1)

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

	"addl %%eax, %1		\n\t"

	"addl %%eax, %2		\n\t"

	"subl $4, %0		\n\t"

#else

	"subl $2, %0		\n\t"

#endif

	"jnz 1b			\n\t"

	:"+g"(h), "+S"(pixels), "+D"(block)

	:"r"(line_size)

	:"eax", "memory");

#endif

}


static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)

{

    PtyCharDriver *s = chr->opaque;

    if (!s->connected) {

        /* guest sends data, check for (re-)connect */

        pty_chr_update_read_handler(chr);

        return 0;

    }

    return io_channel_send(s->fd, buf, len);

}


static void gen_rlwimi(DisasContext *ctx)

{

    uint32_t mb, me, sh;

    mb = MB(ctx->opcode);

    me = ME(ctx->opcode);

    sh = SH(ctx->opcode);

    if (likely(sh == (31-me) && mb <= me)) {

        tcg_gen_deposit_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rA(ctx->opcode)],

                           cpu_gpr[rS(ctx->opcode)], sh, me - mb + 1);

    } else {

        target_ulong mask;

        TCGv t1;

        TCGv t0 = tcg_temp_new();

#if defined(TARGET_PPC64)

        tcg_gen_deposit_i64(t0, cpu_gpr[rS(ctx->opcode)],

            cpu_gpr[rS(ctx->opcode)], 32, 32);

        tcg_gen_rotli_i64(t0, t0, sh);

#else

        tcg_gen_rotli_i32(t0, cpu_gpr[rS(ctx->opcode)], sh);

#endif

#if defined(TARGET_PPC64)

        mb += 32;

        me += 32;

#endif

        mask = MASK(mb, me);

        t1 = tcg_temp_new();

        tcg_gen_andi_tl(t0, t0, mask);

        tcg_gen_andi_tl(t1, cpu_gpr[rA(ctx->opcode)], ~mask);

        tcg_gen_or_tl(cpu_gpr[rA(ctx->opcode)], t0, t1);

        tcg_temp_free(t0);

        tcg_temp_free(t1);

    }

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static int av_seek_frame_generic(AVFormatContext *s,

                                 int stream_index, int64_t timestamp)

{

    int index;

    AVStream *st;

    AVIndexEntry *ie;

    if (!s->index_built) {

        if (is_raw_stream(s)) {

            av_build_index_raw(s);

        } else {

            return -1;

        }

        s->index_built = 1;

    }

    if (stream_index < 0)

        stream_index = 0;

    st = s->streams[stream_index];

    index = index_search_timestamp(st->index_entries, st->nb_index_entries,

                                   timestamp);

    if (index < 0)

        return -1;

    /* now we have found the index, we can seek */

    ie = &st->index_entries[index];

    av_read_frame_flush(s);

    url_fseek(&s->pb, ie->pos, SEEK_SET);

    st->cur_dts = ie->timestamp;

    return 0;

}


static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid)

{

    MXFIndexTableSegment *segment = arg;

    switch(tag) {

    case 0x3F05:

        segment->edit_unit_byte_count = avio_rb32(pb);

        av_dlog(NULL, "EditUnitByteCount %d\n", segment->edit_unit_byte_count);

        break;

    case 0x3F06:

        segment->index_sid = avio_rb32(pb);

        av_dlog(NULL, "IndexSID %d\n", segment->index_sid);

        break;

    case 0x3F07:

        segment->body_sid = avio_rb32(pb);

        av_dlog(NULL, "BodySID %d\n", segment->body_sid);

        break;

    case 0x3F08:

        segment->slice_count = avio_r8(pb);

        av_dlog(NULL, "SliceCount %d\n", segment->slice_count);

        break;

    case 0x3F09:

        av_dlog(NULL, "DeltaEntryArray found\n");

        return mxf_read_delta_entry_array(pb, segment);

    case 0x3F0A:

        av_dlog(NULL, "IndexEntryArray found\n");

        return mxf_read_index_entry_array(pb, segment);

    case 0x3F0B:

        segment->index_edit_rate.num = avio_rb32(pb);

        segment->index_edit_rate.den = avio_rb32(pb);

        av_dlog(NULL, "IndexEditRate %d/%d\n", segment->index_edit_rate.num,

                segment->index_edit_rate.den);

        break;

    case 0x3F0C:

        segment->index_start_position = avio_rb64(pb);

        av_dlog(NULL, "IndexStartPosition %"PRId64"\n", segment->index_start_position);

        break;

    case 0x3F0D:

        segment->index_duration = avio_rb64(pb);

        av_dlog(NULL, "IndexDuration %"PRId64"\n", segment->index_duration);

        break;

    }

    return 0;

}


static ssize_t test_block_write_func(QCryptoBlock *block,

                                     void *opaque,

                                     size_t offset,

                                     const uint8_t *buf,

                                     size_t buflen,

                                     Error **errp)

{

    Buffer *header = opaque;

    g_assert_cmpint(buflen + offset, <=, header->capacity);

    memcpy(header->buffer + offset, buf, buflen);

    header->offset = offset + buflen;

    return buflen;

}


static ssize_t block_crypto_read_func(QCryptoBlock *block,

                                      size_t offset,

                                      uint8_t *buf,

                                      size_t buflen,

                                      Error **errp,

                                      void *opaque)

{

    BlockDriverState *bs = opaque;

    ssize_t ret;

    ret = bdrv_pread(bs->file, offset, buf, buflen);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not read encryption header");

        return ret;

    }

    return ret;

}


static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

    char compressor_name[32] = { 0 };

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

    avio_wl32(pb, track->tag); // store it byteswapped

    avio_wb32(pb, 0); /* Reserved */

    avio_wb16(pb, 0); /* Reserved */

    avio_wb16(pb, 1); /* Data-reference index */

    avio_wb16(pb, 0); /* Codec stream version */

    avio_wb16(pb, 0); /* Codec stream revision (=0) */

    if (track->mode == MODE_MOV) {

        ffio_wfourcc(pb, "FFMP"); /* Vendor */

        if (track->enc->codec_id == AV_CODEC_ID_RAWVIDEO) {

            avio_wb32(pb, 0); /* Temporal Quality */

            avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/

        } else {

            avio_wb32(pb, 0x200); /* Temporal Quality = normal */

            avio_wb32(pb, 0x200); /* Spatial Quality = normal */

        }

    } else {

        avio_wb32(pb, 0); /* Reserved */

        avio_wb32(pb, 0); /* Reserved */

        avio_wb32(pb, 0); /* Reserved */

    }

    avio_wb16(pb, track->enc->width); /* Video width */

    avio_wb16(pb, track->height); /* Video height */

    avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */

    avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */

    avio_wb32(pb, 0); /* Data size (= 0) */

    avio_wb16(pb, 1); /* Frame count (= 1) */

    /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */

    find_compressor(compressor_name, 32, track);

    avio_w8(pb, strlen(compressor_name));

    avio_write(pb, compressor_name, 31);

    if (track->mode == MODE_MOV && track->enc->bits_per_coded_sample)

        avio_wb16(pb, track->enc->bits_per_coded_sample);

    else

        avio_wb16(pb, 0x18); /* Reserved */

    avio_wb16(pb, 0xffff); /* Reserved */

    if (track->tag == MKTAG('m','p','4','v'))

        mov_write_esds_tag(pb, track);

    else if (track->enc->codec_id == AV_CODEC_ID_H263)

        mov_write_d263_tag(pb);

    else if (track->enc->codec_id == AV_CODEC_ID_AVUI ||

            track->enc->codec_id == AV_CODEC_ID_SVQ3) {

        mov_write_extradata_tag(pb, track);

        avio_wb32(pb, 0);

    } else if (track->enc->codec_id == AV_CODEC_ID_DNXHD)

        mov_write_avid_tag(pb, track);

    else if (track->enc->codec_id == AV_CODEC_ID_HEVC)

        mov_write_hvcc_tag(pb, track);

    else if (track->enc->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {

        mov_write_avcc_tag(pb, track);

        if (track->mode == MODE_IPOD)

            mov_write_uuid_tag_ipod(pb);

    } else if (track->enc->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)

        mov_write_dvc1_tag(pb, track);

    else if (track->enc->codec_id == AV_CODEC_ID_VP6F ||

             track->enc->codec_id == AV_CODEC_ID_VP6A) {

        /* Don't write any potential extradata here - the cropping

         * is signalled via the normal width/height fields. */

    } else if (track->enc->codec_id == AV_CODEC_ID_R10K) {

        if (track->enc->codec_tag == MKTAG('R','1','0','k'))

            mov_write_dpxe_tag(pb, track);

    } else if (track->vos_len > 0)

        mov_write_glbl_tag(pb, track);

    if (track->enc->codec_id != AV_CODEC_ID_H264 &&

        track->enc->codec_id != AV_CODEC_ID_MPEG4 &&

        track->enc->codec_id != AV_CODEC_ID_DNXHD)

        if (track->enc->field_order != AV_FIELD_UNKNOWN)

            mov_write_fiel_tag(pb, track);

    if (mov->flags & FF_MOV_FLAG_WRITE_COLR)

        mov_write_colr_tag(pb, track);

    if (track->enc->sample_aspect_ratio.den && track->enc->sample_aspect_ratio.num &&

        track->enc->sample_aspect_ratio.den != track->enc->sample_aspect_ratio.num) {

        mov_write_pasp_tag(pb, track);

    }

    return update_size(pb, pos);

}


int load_multiboot(FWCfgState *fw_cfg,
                   FILE *f,
                   const char *kernel_filename,
                   const char *initrd_filename,
                   const char *kernel_cmdline,
                   int kernel_file_size,
                   uint8_t *header)
{
    int i, is_multiboot = 0;
    uint32_t flags = 0;
    uint32_t mh_entry_addr;
    uint32_t mh_load_addr;
    uint32_t mb_kernel_size;
    MultibootState mbs;
    uint8_t bootinfo[MBI_SIZE];
    uint8_t *mb_bootinfo_data;
    uint32_t cmdline_len;
    /* Ok, let's see if it is a multiboot image.
       The header is 12x32bit long, so the latest entry may be 8192 - 48. */
    for (i = 0; i < (8192 - 48); i += 4) {
        if (ldl_p(header+i) == 0x1BADB002) {
            uint32_t checksum = ldl_p(header+i+8);
            flags = ldl_p(header+i+4);
            checksum += flags;
            checksum += (uint32_t)0x1BADB002;
            if (!checksum) {
                is_multiboot = 1;
                break;
    if (!is_multiboot)
        return 0; /* no multiboot */
    mb_debug("qemu: I believe we found a multiboot image!\n");
    memset(bootinfo, 0, sizeof(bootinfo));
    memset(&mbs, 0, sizeof(mbs));
    if (flags & 0x00000004) { /* MULTIBOOT_HEADER_HAS_VBE */
        fprintf(stderr, "qemu: multiboot knows VBE. we don't.\n");
    if (!(flags & 0x00010000)) { /* MULTIBOOT_HEADER_HAS_ADDR */
        uint64_t elf_entry;
        uint64_t elf_low, elf_high;
        int kernel_size;
        fclose(f);
        if (((struct elf64_hdr*)header)->e_machine == EM_X86_64) {
            fprintf(stderr, "Cannot load x86-64 image, give a 32bit one.\n");
        kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry,
                               &elf_low, &elf_high, 0, I386_ELF_MACHINE,
                               0, 0);
        if (kernel_size < 0) {
            fprintf(stderr, "Error while loading elf kernel\n");
        mh_load_addr = elf_low;
        mb_kernel_size = elf_high - elf_low;
        mh_entry_addr = elf_entry;
        mbs.mb_buf = g_malloc(mb_kernel_size);
        if (rom_copy(mbs.mb_buf, mh_load_addr, mb_kernel_size) != mb_kernel_size) {
            fprintf(stderr, "Error while fetching elf kernel from rom\n");
        mb_debug("qemu: loading multiboot-elf kernel (%#x bytes) with entry %#zx\n",
                  mb_kernel_size, (size_t)mh_entry_addr);
    } else {
        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_ADDR. */
        uint32_t mh_header_addr = ldl_p(header+i+12);
        uint32_t mh_load_end_addr = ldl_p(header+i+20);
        uint32_t mh_bss_end_addr = ldl_p(header+i+24);
        mh_load_addr = ldl_p(header+i+16);
        uint32_t mb_kernel_text_offset = i - (mh_header_addr - mh_load_addr);
        uint32_t mb_load_size = 0;
        mh_entry_addr = ldl_p(header+i+28);
        if (mh_load_end_addr) {
            mb_kernel_size = mh_bss_end_addr - mh_load_addr;
            mb_load_size = mh_load_end_addr - mh_load_addr;
        } else {
            mb_kernel_size = kernel_file_size - mb_kernel_text_offset;
            mb_load_size = mb_kernel_size;
        /* Valid if mh_flags sets MULTIBOOT_HEADER_HAS_VBE.
        uint32_t mh_mode_type = ldl_p(header+i+32);
        uint32_t mh_width = ldl_p(header+i+36);
        uint32_t mh_height = ldl_p(header+i+40);
        uint32_t mh_depth = ldl_p(header+i+44); */
        mb_debug("multiboot: mh_header_addr = %#x\n", mh_header_addr);
        mb_debug("multiboot: mh_load_addr = %#x\n", mh_load_addr);
        mb_debug("multiboot: mh_load_end_addr = %#x\n", mh_load_end_addr);
        mb_debug("multiboot: mh_bss_end_addr = %#x\n", mh_bss_end_addr);
        mb_debug("qemu: loading multiboot kernel (%#x bytes) at %#x\n",
                 mb_load_size, mh_load_addr);
        mbs.mb_buf = g_malloc(mb_kernel_size);
        fseek(f, mb_kernel_text_offset, SEEK_SET);
        if (fread(mbs.mb_buf, 1, mb_load_size, f) != mb_load_size) {
            fprintf(stderr, "fread() failed\n");
        memset(mbs.mb_buf + mb_load_size, 0, mb_kernel_size - mb_load_size);
        fclose(f);
    mbs.mb_buf_phys = mh_load_addr;
    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_kernel_size);
    mbs.offset_mbinfo = mbs.mb_buf_size;
    /* Calculate space for cmdlines, bootloader name, and mb_mods */
    cmdline_len = strlen(kernel_filename) + 1;
    cmdline_len += strlen(kernel_cmdline) + 1;
    if (initrd_filename) {
        const char *r = initrd_filename;
        cmdline_len += strlen(r) + 1;
        mbs.mb_mods_avail = 1;
        while (*(r = get_opt_value(NULL, 0, r))) {
           mbs.mb_mods_avail++;
           r++;
    mbs.mb_buf_size += cmdline_len;
    mbs.mb_buf_size += MB_MOD_SIZE * mbs.mb_mods_avail;
    mbs.mb_buf_size += strlen(bootloader_name) + 1;
    mbs.mb_buf_size = TARGET_PAGE_ALIGN(mbs.mb_buf_size);
    /* enlarge mb_buf to hold cmdlines, bootloader, mb-info structs */
    mbs.mb_buf            = g_realloc(mbs.mb_buf, mbs.mb_buf_size);
    mbs.offset_cmdlines   = mbs.offset_mbinfo + mbs.mb_mods_avail * MB_MOD_SIZE;
    mbs.offset_bootloader = mbs.offset_cmdlines + cmdline_len;
    if (initrd_filename) {
        const char *next_initrd;
        char not_last, tmpbuf[strlen(initrd_filename) + 1];
        mbs.offset_mods = mbs.mb_buf_size;
        do {
            char *next_space;
            int mb_mod_length;
            uint32_t offs = mbs.mb_buf_size;
            next_initrd = get_opt_value(tmpbuf, sizeof(tmpbuf), initrd_filename);
            not_last = *next_initrd;
            /* if a space comes after the module filename, treat everything
               after that as parameters */
            hwaddr c = mb_add_cmdline(&mbs, tmpbuf);
            if ((next_space = strchr(tmpbuf, ' ')))
                *next_space = '\0';
            mb_debug("multiboot loading module: %s\n", tmpbuf);
            mb_mod_length = get_image_size(tmpbuf);
            if (mb_mod_length < 0) {
                fprintf(stderr, "Failed to open file '%s'\n", tmpbuf);
            mbs.mb_buf_size = TARGET_PAGE_ALIGN(mb_mod_length + mbs.mb_buf_size);
            mbs.mb_buf = g_realloc(mbs.mb_buf, mbs.mb_buf_size);
            load_image(tmpbuf, (unsigned char *)mbs.mb_buf + offs);
            mb_add_mod(&mbs, mbs.mb_buf_phys + offs,
                       mbs.mb_buf_phys + offs + mb_mod_length, c);
            mb_debug("mod_start: %p\nmod_end:   %p\n  cmdline: "TARGET_FMT_plx"\n",
                     (char *)mbs.mb_buf + offs,
                     (char *)mbs.mb_buf + offs + mb_mod_length, c);
            initrd_filename = next_initrd+1;
        } while (not_last);
    /* Commandline support */
    char kcmdline[strlen(kernel_filename) + strlen(kernel_cmdline) + 2];
    snprintf(kcmdline, sizeof(kcmdline), "%s %s",
             kernel_filename, kernel_cmdline);
    stl_p(bootinfo + MBI_CMDLINE, mb_add_cmdline(&mbs, kcmdline));
    stl_p(bootinfo + MBI_BOOTLOADER, mb_add_bootloader(&mbs, bootloader_name));
    stl_p(bootinfo + MBI_MODS_ADDR,  mbs.mb_buf_phys + mbs.offset_mbinfo);
    stl_p(bootinfo + MBI_MODS_COUNT, mbs.mb_mods_count); /* mods_count */
    /* the kernel is where we want it to be now */
    stl_p(bootinfo + MBI_FLAGS, MULTIBOOT_FLAGS_MEMORY
                                | MULTIBOOT_FLAGS_BOOT_DEVICE
                                | MULTIBOOT_FLAGS_CMDLINE
                                | MULTIBOOT_FLAGS_MODULES
                                | MULTIBOOT_FLAGS_MMAP
                                | MULTIBOOT_FLAGS_BOOTLOADER);
    stl_p(bootinfo + MBI_BOOT_DEVICE, 0x8000ffff); /* XXX: use the -boot switch? */
    stl_p(bootinfo + MBI_MMAP_ADDR,   ADDR_E820_MAP);
    mb_debug("multiboot: mh_entry_addr = %#x\n", mh_entry_addr);
    mb_debug("           mb_buf_phys   = "TARGET_FMT_plx"\n", mbs.mb_buf_phys);
    mb_debug("           mod_start     = "TARGET_FMT_plx"\n", mbs.mb_buf_phys + mbs.offset_mods);
    mb_debug("           mb_mods_count = %d\n", mbs.mb_mods_count);
    /* save bootinfo off the stack */
    mb_bootinfo_data = g_memdup(bootinfo, sizeof(bootinfo));
    /* Pass variables to option rom */
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ENTRY, mh_entry_addr);
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, mh_load_addr);
    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, mbs.mb_buf_size);
    fw_cfg_add_bytes(fw_cfg, FW_CFG_KERNEL_DATA,
                     mbs.mb_buf, mbs.mb_buf_size);
    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, ADDR_MBI);
    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, sizeof(bootinfo));
    fw_cfg_add_bytes(fw_cfg, FW_CFG_INITRD_DATA, mb_bootinfo_data,
                     sizeof(bootinfo));
    option_rom[nb_option_roms].name = "multiboot.bin";
    option_rom[nb_option_roms].bootindex = 0;
    nb_option_roms++;
    return 1; /* yes, we are multiboot */


static void lm32_cpu_reset(CPUState *s)

{

    LM32CPU *cpu = LM32_CPU(s);

    LM32CPUClass *lcc = LM32_CPU_GET_CLASS(cpu);

    CPULM32State *env = &cpu->env;

    if (qemu_loglevel_mask(CPU_LOG_RESET)) {

        qemu_log("CPU Reset (CPU %d)\n", s->cpu_index);

        log_cpu_state(env, 0);

    }

    lcc->parent_reset(s);

    tlb_flush(env, 1);

    /* reset cpu state */

    memset(env, 0, offsetof(CPULM32State, breakpoints));

}


static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { return 0; }


D(float, sse)

D(float, avx)

D(int16, mmx)

D(int16, sse2)

av_cold int swri_rematrix_init_x86(struct SwrContext *s){

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    int nb_in  = av_get_channel_layout_nb_channels(s->in_ch_layout);

    int nb_out = av_get_channel_layout_nb_channels(s->out_ch_layout);

    int num    = nb_in * nb_out;

    int i,j;

    s->mix_1_1_simd = NULL;

    s->mix_2_1_simd = NULL;

    if (s->midbuf.fmt == AV_SAMPLE_FMT_S16P){

        if(EXTERNAL_MMX(mm_flags)) {

            s->mix_1_1_simd = ff_mix_1_1_a_int16_mmx;

            s->mix_2_1_simd = ff_mix_2_1_a_int16_mmx;

        }

        if(EXTERNAL_SSE2(mm_flags)) {

            s->mix_1_1_simd = ff_mix_1_1_a_int16_sse2;

            s->mix_2_1_simd = ff_mix_2_1_a_int16_sse2;

        }

        s->native_simd_matrix = av_mallocz_array(num,  2 * sizeof(int16_t));

        s->native_simd_one    = av_mallocz(2 * sizeof(int16_t));

        if (!s->native_simd_matrix || !s->native_simd_one)

            return AVERROR(ENOMEM);

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

            int sh = 0;

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

                sh = FFMAX(sh, FFABS(((int*)s->native_matrix)[i * nb_in + j]));

            sh = FFMAX(av_log2(sh) - 14, 0);

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

                ((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)+1] = 15 - sh;

                ((int16_t*)s->native_simd_matrix)[2*(i * nb_in + j)] =

                    ((((int*)s->native_matrix)[i * nb_in + j]) + (1<<sh>>1)) >> sh;

            }

        }

        ((int16_t*)s->native_simd_one)[1] = 14;

        ((int16_t*)s->native_simd_one)[0] = 16384;

    } else if(s->midbuf.fmt == AV_SAMPLE_FMT_FLTP){

        if(EXTERNAL_SSE(mm_flags)) {

            s->mix_1_1_simd = ff_mix_1_1_a_float_sse;

            s->mix_2_1_simd = ff_mix_2_1_a_float_sse;

        }

        if(EXTERNAL_AVX(mm_flags)) {

            s->mix_1_1_simd = ff_mix_1_1_a_float_avx;

            s->mix_2_1_simd = ff_mix_2_1_a_float_avx;

        }

        s->native_simd_matrix = av_mallocz_array(num, sizeof(float));

        s->native_simd_one = av_mallocz(sizeof(float));

        if (!s->native_simd_matrix || !s->native_simd_one)

            return AVERROR(ENOMEM);

        memcpy(s->native_simd_matrix, s->native_matrix, num * sizeof(float));

        memcpy(s->native_simd_one, s->native_one, sizeof(float));

    }

#endif

    return 0;

}


static int av_transcode(AVFormatContext **output_files,

                        int nb_output_files,

                        AVFormatContext **input_files,

                        int nb_input_files,

                        AVStreamMap *stream_maps, int nb_stream_maps)

{

    int ret = 0, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;

    AVFormatContext *is, *os;

    AVCodecContext *codec, *icodec;

    AVOutputStream *ost, **ost_table = NULL;

    AVInputStream *ist, **ist_table = NULL;

    AVInputFile *file_table;

    char error[1024];

    int key;

    int want_sdp = 1;

    uint8_t no_packet[MAX_FILES]={0};

    int no_packet_count=0;

    file_table= av_mallocz(nb_input_files * sizeof(AVInputFile));

    if (!file_table)

        goto fail;

    /* input stream init */

    j = 0;

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

        is = input_files[i];

        file_table[i].ist_index = j;

        file_table[i].nb_streams = is->nb_streams;

        j += is->nb_streams;

    }

    nb_istreams = j;

    ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));

    if (!ist_table)

        goto fail;

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

        ist = av_mallocz(sizeof(AVInputStream));

        if (!ist)

            goto fail;

        ist_table[i] = ist;

    }

    j = 0;

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

        is = input_files[i];

        for(k=0;k<is->nb_streams;k++) {

            ist = ist_table[j++];

            ist->st = is->streams[k];

            ist->file_index = i;

            ist->index = k;

            ist->discard = 1; /* the stream is discarded by default

                                 (changed later) */

            if (rate_emu) {

                ist->start = av_gettime();

            }

        }

    }

    /* output stream init */

    nb_ostreams = 0;

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

        os = output_files[i];

        if (!os->nb_streams) {

            dump_format(output_files[i], i, output_files[i]->filename, 1);

            fprintf(stderr, "Output file #%d does not contain any stream\n", i);

            av_exit(1);

        }

        nb_ostreams += os->nb_streams;

    }

    if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {

        fprintf(stderr, "Number of stream maps must match number of output streams\n");

        av_exit(1);

    }

    /* Sanity check the mapping args -- do the input files & streams exist? */

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

        int fi = stream_maps[i].file_index;

        int si = stream_maps[i].stream_index;

        if (fi < 0 || fi > nb_input_files - 1 ||

            si < 0 || si > file_table[fi].nb_streams - 1) {

            fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);

            av_exit(1);

        }

        fi = stream_maps[i].sync_file_index;

        si = stream_maps[i].sync_stream_index;

        if (fi < 0 || fi > nb_input_files - 1 ||

            si < 0 || si > file_table[fi].nb_streams - 1) {

            fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);

            av_exit(1);

        }

    }

    ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);

    if (!ost_table)

        goto fail;

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

        ost = av_mallocz(sizeof(AVOutputStream));

        if (!ost)

            goto fail;

        ost_table[i] = ost;

    }

    n = 0;

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

        os = output_files[k];

        for(i=0;i<os->nb_streams;i++,n++) {

            int found;

            ost = ost_table[n];

            ost->file_index = k;

            ost->index = i;

            ost->st = os->streams[i];

            if (nb_stream_maps > 0) {

                ost->source_index = file_table[stream_maps[n].file_index].ist_index +

                    stream_maps[n].stream_index;

                /* Sanity check that the stream types match */

                if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {

                    int i= ost->file_index;

                    dump_format(output_files[i], i, output_files[i]->filename, 1);

                    fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",

                        stream_maps[n].file_index, stream_maps[n].stream_index,

                        ost->file_index, ost->index);

                    av_exit(1);

                }

            } else {

                int best_nb_frames=-1;

                    /* get corresponding input stream index : we select the first one with the right type */

                    found = 0;

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

                        int skip=0;

                        ist = ist_table[j];

                        if(opt_programid){

                            int pi,si;

                            AVFormatContext *f= input_files[ ist->file_index ];

                            skip=1;

                            for(pi=0; pi<f->nb_programs; pi++){

                                AVProgram *p= f->programs[pi];

                                if(p->id == opt_programid)

                                    for(si=0; si<p->nb_stream_indexes; si++){

                                        if(f->streams[ p->stream_index[si] ] == ist->st)

                                            skip=0;

                                    }

                            }

                        }

                        if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&

                            ist->st->codec->codec_type == ost->st->codec->codec_type) {

                            if(best_nb_frames < ist->st->codec_info_nb_frames){

                                best_nb_frames= ist->st->codec_info_nb_frames;

                                ost->source_index = j;

                                found = 1;

                            }

                        }

                    }

                if (!found) {

                    if(! opt_programid) {

                        /* try again and reuse existing stream */

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

                            ist = ist_table[j];

                            if (   ist->st->codec->codec_type == ost->st->codec->codec_type

                                && ist->st->discard != AVDISCARD_ALL) {

                                ost->source_index = j;

                                found = 1;

                            }

                        }

                    }

                    if (!found) {

                        int i= ost->file_index;

                        dump_format(output_files[i], i, output_files[i]->filename, 1);

                        fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",

                                ost->file_index, ost->index);

                        av_exit(1);

                    }

                }

            }

            ist = ist_table[ost->source_index];

            ist->discard = 0;

            ost->sync_ist = (nb_stream_maps > 0) ?

                ist_table[file_table[stream_maps[n].sync_file_index].ist_index +

                         stream_maps[n].sync_stream_index] : ist;

        }

    }

    /* for each output stream, we compute the right encoding parameters */

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

        AVMetadataTag *t = NULL;

        ost = ost_table[i];

        os = output_files[ost->file_index];

        ist = ist_table[ost->source_index];

        codec = ost->st->codec;

        icodec = ist->st->codec;

        while ((t = av_metadata_get(ist->st->metadata, "", t, AV_METADATA_IGNORE_SUFFIX))) {

            av_metadata_set2(&ost->st->metadata, t->key, t->value, AV_METADATA_DONT_OVERWRITE);

        }

        ost->st->disposition = ist->st->disposition;

        codec->bits_per_raw_sample= icodec->bits_per_raw_sample;

        codec->chroma_sample_location = icodec->chroma_sample_location;

        if (ost->st->stream_copy) {

            /* if stream_copy is selected, no need to decode or encode */

            codec->codec_id = icodec->codec_id;

            codec->codec_type = icodec->codec_type;

            if(!codec->codec_tag){

                if(   !os->oformat->codec_tag

                   || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id

                   || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)

                    codec->codec_tag = icodec->codec_tag;

            }

            codec->bit_rate = icodec->bit_rate;

            codec->extradata= icodec->extradata;

            codec->extradata_size= icodec->extradata_size;

            if(av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/1000){

                codec->time_base = icodec->time_base;

                codec->time_base.num *= icodec->ticks_per_frame;

            }else

                codec->time_base = ist->st->time_base;

            switch(codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                if(audio_volume != 256) {

                    fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");

                    av_exit(1);

                }

                codec->channel_layout = icodec->channel_layout;

                codec->sample_rate = icodec->sample_rate;

                codec->channels = icodec->channels;

                codec->frame_size = icodec->frame_size;

                codec->block_align= icodec->block_align;

                if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)

                    codec->block_align= 0;

                if(codec->codec_id == CODEC_ID_AC3)

                    codec->block_align= 0;

                break;

            case AVMEDIA_TYPE_VIDEO:

                codec->pix_fmt = icodec->pix_fmt;

                codec->width = icodec->width;

                codec->height = icodec->height;

                codec->has_b_frames = icodec->has_b_frames;

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                codec->width = icodec->width;

                codec->height = icodec->height;

                break;

            default:

                abort();

            }

        } else {

            switch(codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                ost->fifo= av_fifo_alloc(1024);

                if(!ost->fifo)

                    goto fail;

                ost->reformat_pair = MAKE_SFMT_PAIR(SAMPLE_FMT_NONE,SAMPLE_FMT_NONE);

                ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;

                icodec->request_channels = codec->channels;

                ist->decoding_needed = 1;

                ost->encoding_needed = 1;

                break;

            case AVMEDIA_TYPE_VIDEO:

                if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {

                    fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");

                    av_exit(1);

                }

                ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);

                ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);

                ost->video_resample = ((codec->width != icodec->width -

                                (frame_leftBand + frame_rightBand) +

                                (frame_padleft + frame_padright)) ||

                        (codec->height != icodec->height -

                                (frame_topBand  + frame_bottomBand) +

                                (frame_padtop + frame_padbottom)) ||

                        (codec->pix_fmt != icodec->pix_fmt));

                if (ost->video_crop) {

                    ost->topBand    = ost->original_topBand    = frame_topBand;

                    ost->bottomBand = ost->original_bottomBand = frame_bottomBand;

                    ost->leftBand   = ost->original_leftBand   = frame_leftBand;

                    ost->rightBand  = ost->original_rightBand  = frame_rightBand;

                }

                if (ost->video_pad) {

                    ost->padtop = frame_padtop;

                    ost->padleft = frame_padleft;

                    ost->padbottom = frame_padbottom;

                    ost->padright = frame_padright;

                    if (!ost->video_resample) {

                        avcodec_get_frame_defaults(&ost->pict_tmp);

                        if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,

                                         codec->width, codec->height))

                            goto fail;

                    }

                }

                if (ost->video_resample) {

                    avcodec_get_frame_defaults(&ost->pict_tmp);

                    if(avpicture_alloc((AVPicture*)&ost->pict_tmp, codec->pix_fmt,

                                         codec->width, codec->height)) {

                        fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");

                        av_exit(1);

                    }

                    sws_flags = av_get_int(sws_opts, "sws_flags", NULL);

                    ost->img_resample_ctx = sws_getContext(

                            icodec->width - (frame_leftBand + frame_rightBand),

                            icodec->height - (frame_topBand + frame_bottomBand),

                            icodec->pix_fmt,

                            codec->width - (frame_padleft + frame_padright),

                            codec->height - (frame_padtop + frame_padbottom),

                            codec->pix_fmt,

                            sws_flags, NULL, NULL, NULL);

                    if (ost->img_resample_ctx == NULL) {

                        fprintf(stderr, "Cannot get resampling context\n");

                        av_exit(1);

                    }

#if !CONFIG_AVFILTER

                    ost->original_height = icodec->height;

                    ost->original_width  = icodec->width;

#endif

                    codec->bits_per_raw_sample= 0;

                }

                ost->resample_height = icodec->height - (frame_topBand  + frame_bottomBand);

                ost->resample_width  = icodec->width  - (frame_leftBand + frame_rightBand);

                ost->resample_pix_fmt= icodec->pix_fmt;

                ost->encoding_needed = 1;

                ist->decoding_needed = 1;

#if CONFIG_AVFILTER

                if (configure_filters(ist, ost)) {

                    fprintf(stderr, "Error opening filters!\n");

                    exit(1);

                }

#endif

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                ost->encoding_needed = 1;

                ist->decoding_needed = 1;

                break;

            default:

                abort();

                break;

            }

            /* two pass mode */

            if (ost->encoding_needed &&

                (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {

                char logfilename[1024];

                FILE *f;

                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",

                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,

                         i);

                if (codec->flags & CODEC_FLAG_PASS1) {

                    f = fopen(logfilename, "w");

                    if (!f) {

                        fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));

                        av_exit(1);

                    }

                    ost->logfile = f;

                } else {

                    char  *logbuffer;

                    size_t logbuffer_size;

                    if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {

                        fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);

                        av_exit(1);

                    }

                    codec->stats_in = logbuffer;

                }

            }

        }

        if(codec->codec_type == AVMEDIA_TYPE_VIDEO){

            int size= codec->width * codec->height;

            bit_buffer_size= FFMAX(bit_buffer_size, 6*size + 200);

        }

    }

    if (!bit_buffer)

        bit_buffer = av_malloc(bit_buffer_size);

    if (!bit_buffer) {

        fprintf(stderr, "Cannot allocate %d bytes output buffer\n",

                bit_buffer_size);

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    /* open each encoder */

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

        ost = ost_table[i];

        if (ost->encoding_needed) {

            AVCodec *codec = output_codecs[i];

            if (!codec)

                codec = avcodec_find_encoder(ost->st->codec->codec_id);

            if (!codec) {

                snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",

                         ost->st->codec->codec_id, ost->file_index, ost->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            if (avcodec_open(ost->st->codec, codec) < 0) {

                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",

                        ost->file_index, ost->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            extra_size += ost->st->codec->extradata_size;

        }

    }

    /* open each decoder */

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

        ist = ist_table[i];

        if (ist->decoding_needed) {

            AVCodec *codec = input_codecs[i];

            if (!codec)

                codec = avcodec_find_decoder(ist->st->codec->codec_id);

            if (!codec) {

                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",

                        ist->st->codec->codec_id, ist->file_index, ist->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            if (avcodec_open(ist->st->codec, codec) < 0) {

                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",

                        ist->file_index, ist->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;

        }

    }

    /* init pts */

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

        AVStream *st;

        ist = ist_table[i];

        st= ist->st;

        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;

        ist->next_pts = AV_NOPTS_VALUE;

        ist->is_start = 1;

    }

    /* set meta data information from input file if required */

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

        AVFormatContext *out_file;

        AVFormatContext *in_file;

        AVMetadataTag *mtag;

        int out_file_index = meta_data_maps[i].out_file;

        int in_file_index = meta_data_maps[i].in_file;

        if (out_file_index < 0 || out_file_index >= nb_output_files) {

            snprintf(error, sizeof(error), "Invalid output file index %d map_meta_data(%d,%d)",

                     out_file_index, out_file_index, in_file_index);

            ret = AVERROR(EINVAL);

            goto dump_format;

        }

        if (in_file_index < 0 || in_file_index >= nb_input_files) {

            snprintf(error, sizeof(error), "Invalid input file index %d map_meta_data(%d,%d)",

                     in_file_index, out_file_index, in_file_index);

            ret = AVERROR(EINVAL);

            goto dump_format;

        }

        out_file = output_files[out_file_index];

        in_file = input_files[in_file_index];

        mtag=NULL;

        while((mtag=av_metadata_get(in_file->metadata, "", mtag, AV_METADATA_IGNORE_SUFFIX)))

            av_metadata_set2(&out_file->metadata, mtag->key, mtag->value, AV_METADATA_DONT_OVERWRITE);

        av_metadata_conv(out_file, out_file->oformat->metadata_conv,

                                    in_file->iformat->metadata_conv);

    }

    /* copy chapters from the first input file that has them*/

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

        if (!input_files[i]->nb_chapters)

            continue;

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

            if ((ret = copy_chapters(i, j)) < 0)

                goto dump_format;

    }

    /* open files and write file headers */

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

        os = output_files[i];

        if (av_write_header(os) < 0) {

            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);

            ret = AVERROR(EINVAL);

            goto dump_format;

        }

        if (strcmp(output_files[i]->oformat->name, "rtp")) {

            want_sdp = 0;

        }

    }

 dump_format:

    /* dump the file output parameters - cannot be done before in case

       of stream copy */

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

        dump_format(output_files[i], i, output_files[i]->filename, 1);

    }

    /* dump the stream mapping */

    if (verbose >= 0) {

        fprintf(stderr, "Stream mapping:\n");

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

            ost = ost_table[i];

            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",

                    ist_table[ost->source_index]->file_index,

                    ist_table[ost->source_index]->index,

                    ost->file_index,

                    ost->index);

            if (ost->sync_ist != ist_table[ost->source_index])

                fprintf(stderr, " [sync #%d.%d]",

                        ost->sync_ist->file_index,

                        ost->sync_ist->index);

            fprintf(stderr, "\n");

        }

    }

    if (ret) {

        fprintf(stderr, "%s\n", error);

        goto fail;

    }

    if (want_sdp) {

        print_sdp(output_files, nb_output_files);

    }

    if (!using_stdin && verbose >= 0) {

        fprintf(stderr, "Press [q] to stop encoding\n");

        url_set_interrupt_cb(decode_interrupt_cb);

    }

    term_init();

    timer_start = av_gettime();

    for(; received_sigterm == 0;) {

        int file_index, ist_index;

        AVPacket pkt;

        double ipts_min;

        double opts_min;

    redo:

        ipts_min= 1e100;

        opts_min= 1e100;

        /* if 'q' pressed, exits */

        if (!using_stdin) {

            if (q_pressed)

                break;

            /* read_key() returns 0 on EOF */

            key = read_key();

            if (key == 'q')

                break;

        }

        /* select the stream that we must read now by looking at the

           smallest output pts */

        file_index = -1;

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

            double ipts, opts;

            ost = ost_table[i];

            os = output_files[ost->file_index];

            ist = ist_table[ost->source_index];

            if(ist->is_past_recording_time || no_packet[ist->file_index])

                continue;

                opts = ost->st->pts.val * av_q2d(ost->st->time_base);

            ipts = (double)ist->pts;

            if (!file_table[ist->file_index].eof_reached){

                if(ipts < ipts_min) {

                    ipts_min = ipts;

                    if(input_sync ) file_index = ist->file_index;

                }

                if(opts < opts_min) {

                    opts_min = opts;

                    if(!input_sync) file_index = ist->file_index;

                }

            }

            if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){

                file_index= -1;

                break;

            }

        }

        /* if none, if is finished */

        if (file_index < 0) {

            if(no_packet_count){

                no_packet_count=0;

                memset(no_packet, 0, sizeof(no_packet));

                usleep(10000);

                continue;

            }

            break;

        }

        /* finish if limit size exhausted */

        if (limit_filesize != 0 && limit_filesize < url_ftell(output_files[0]->pb))

            break;

        /* read a frame from it and output it in the fifo */

        is = input_files[file_index];

        ret= av_read_frame(is, &pkt);

        if(ret == AVERROR(EAGAIN)){

            no_packet[file_index]=1;

            no_packet_count++;

            continue;

        }

        if (ret < 0) {

            file_table[file_index].eof_reached = 1;

            if (opt_shortest)

                break;

            else

                continue;

        }

        no_packet_count=0;

        memset(no_packet, 0, sizeof(no_packet));

        if (do_pkt_dump) {

            av_pkt_dump_log(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump);

        }

        /* the following test is needed in case new streams appear

           dynamically in stream : we ignore them */

        if (pkt.stream_index >= file_table[file_index].nb_streams)

            goto discard_packet;

        ist_index = file_table[file_index].ist_index + pkt.stream_index;

        ist = ist_table[ist_index];

        if (ist->discard)

            goto discard_packet;

        if (pkt.dts != AV_NOPTS_VALUE)

            pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);

        if (pkt.pts != AV_NOPTS_VALUE)

            pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);

        if(input_files_ts_scale[file_index][pkt.stream_index]){

            if(pkt.pts != AV_NOPTS_VALUE)

                pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];

            if(pkt.dts != AV_NOPTS_VALUE)

                pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];

        }

//        fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);

        if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE

            && (is->iformat->flags & AVFMT_TS_DISCONT)) {

            int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);

            int64_t delta= pkt_dts - ist->next_pts;

            if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){

                input_files_ts_offset[ist->file_index]-= delta;

                if (verbose > 2)

                    fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);

                pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

                if(pkt.pts != AV_NOPTS_VALUE)

                    pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

            }

        }

        /* finish if recording time exhausted */

        if (recording_time != INT64_MAX &&

            av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000}) >= 0) {

            ist->is_past_recording_time = 1;

            goto discard_packet;

        }

        //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);

        if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {

            if (verbose >= 0)

                fprintf(stderr, "Error while decoding stream #%d.%d\n",

                        ist->file_index, ist->index);

            if (exit_on_error)

                av_exit(1);

            av_free_packet(&pkt);

            goto redo;

        }

    discard_packet:

        av_free_packet(&pkt);

        /* dump report by using the output first video and audio streams */

        print_report(output_files, ost_table, nb_ostreams, 0);

    }

    /* at the end of stream, we must flush the decoder buffers */

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

        ist = ist_table[i];

        if (ist->decoding_needed) {

            output_packet(ist, i, ost_table, nb_ostreams, NULL);

        }

    }

    term_exit();

    /* write the trailer if needed and close file */

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

        os = output_files[i];

        av_write_trailer(os);

    }

    /* dump report by using the first video and audio streams */

    print_report(output_files, ost_table, nb_ostreams, 1);

    /* close each encoder */

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

        ost = ost_table[i];

        if (ost->encoding_needed) {

            av_freep(&ost->st->codec->stats_in);

            avcodec_close(ost->st->codec);

        }

    }

    /* close each decoder */

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

        ist = ist_table[i];

        if (ist->decoding_needed) {

            avcodec_close(ist->st->codec);

        }

    }

#if CONFIG_AVFILTER

    if (filt_graph_all) {

        avfilter_graph_destroy(filt_graph_all);

        av_freep(&filt_graph_all);

    }

#endif

    /* finished ! */

    ret = 0;

 fail:

    av_freep(&bit_buffer);

    av_free(file_table);

    if (ist_table) {

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

            ist = ist_table[i];

            av_free(ist);

        }

        av_free(ist_table);

    }

    if (ost_table) {

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

            ost = ost_table[i];

            if (ost) {

                if (ost->logfile) {

                    fclose(ost->logfile);

                    ost->logfile = NULL;

                }

                av_fifo_free(ost->fifo); /* works even if fifo is not

                                             initialized but set to zero */

                av_free(ost->pict_tmp.data[0]);

                if (ost->video_resample)

                    sws_freeContext(ost->img_resample_ctx);

                if (ost->resample)

                    audio_resample_close(ost->resample);

                if (ost->reformat_ctx)

                    av_audio_convert_free(ost->reformat_ctx);

                av_free(ost);

            }

        }

        av_free(ost_table);

    }

    return ret;

}


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

{

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

    int size= pkt->size;

    uint8_t *buf= pkt->data;

    MpegTSWriteStream *ts_st = st->priv_data;

    int len, max_payload_size;

    const uint8_t *access_unit_index = NULL;

    if (st->codec->codec_type == CODEC_TYPE_SUBTITLE) {

        /* for subtitle, a single PES packet must be generated */

        mpegts_write_pes(s, st, buf, size, pkt->pts, AV_NOPTS_VALUE);

        return 0;

    }

    if (st->codec->codec_id == CODEC_ID_DIRAC) {

        /* for Dirac, a single PES packet must be generated */

        mpegts_write_pes(s, st, buf, size, pkt->pts, pkt->dts);

        return 0;

    }

    max_payload_size = DEFAULT_PES_PAYLOAD_SIZE;

    if (st->codec->codec_id == CODEC_ID_MPEG2VIDEO ||

        st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {

        const uint8_t *p = pkt->data;

        const uint8_t *end = pkt->data+pkt->size;

        uint32_t state = -1;

        while (p < end) {

            p = ff_find_start_code(p, end, &state);

            if (state == PICTURE_START_CODE) {

                access_unit_index = p - 4;

                break;

            }

        }

    } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {

        access_unit_index = pkt->data;

    }

    if (!access_unit_index) {

        av_log(s, AV_LOG_ERROR, "error, could not find access unit start\n");

        return -1;

    }

    while (size > 0) {

        len = max_payload_size - ts_st->payload_index;

        if (len > size)

            len = size;

        memcpy(ts_st->payload + ts_st->payload_index, buf, len);

        buf += len;

        size -= len;

        ts_st->payload_index += len;

        if (access_unit_index && access_unit_index < buf &&

            ts_st->payload_pts == AV_NOPTS_VALUE &&

            ts_st->payload_dts == AV_NOPTS_VALUE) {

            ts_st->payload_dts = pkt->dts;

            ts_st->payload_pts = pkt->pts;

        }

        if (ts_st->payload_index >= max_payload_size) {

            mpegts_write_pes(s, st, ts_st->payload, ts_st->payload_index,

                             ts_st->payload_pts, ts_st->payload_dts);

            ts_st->payload_pts = AV_NOPTS_VALUE;

            ts_st->payload_dts = AV_NOPTS_VALUE;

            ts_st->payload_index = 0;

            access_unit_index = NULL; // unset access unit to avoid setting pts/dts again

        }

    }

    return 0;

}


static inline void RENAME(yuv2packedX)(SwsContext *c, const int16_t *lumFilter, const int16_t **lumSrc, int lumFilterSize,

                                       const int16_t *chrFilter, const int16_t **chrSrc, int chrFilterSize,

                                       const int16_t **alpSrc, uint8_t *dest, int dstW, int dstY)

{

#if COMPILE_TEMPLATE_MMX

    x86_reg dummy=0;

    if(!(c->flags & SWS_BITEXACT)) {

        if (c->flags & SWS_ACCURATE_RND) {

            switch(c->dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    YSCALEYUV2PACKEDX_ACCURATE

                    YSCALEYUV2RGBX

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

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

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

                    YSCALEYUV2PACKEDX_ACCURATE_YA(ALP_MMX_FILTER_OFFSET)

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

                    "psraw                        $3, %%mm1         \n\t"

                    "psraw                        $3, %%mm7         \n\t"

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

                    WRITEBGR32(%4, %5, %%REGa, %%mm3, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm2, %%mm6)

                    YSCALEYUV2PACKEDX_END

                } else {

                    YSCALEYUV2PACKEDX_ACCURATE

                    YSCALEYUV2RGBX

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

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                }

                return;

            case PIX_FMT_BGR24:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"\n\t" //FIXME optimize

                "add %4, %%"REG_c"                        \n\t"

                WRITEBGR24(%%REGc, %5, %%REGa)

                :: "r" (&c->redDither),

                "m" (dummy), "m" (dummy), "m" (dummy),

                "r" (dest), "m" (dstW)

                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S

                );

                return;

            case PIX_FMT_RGB555:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"

                "paddusb "RED_DITHER"(%0), %%mm5\n\t"

#endif

                WRITERGB15(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_RGB565:

                YSCALEYUV2PACKEDX_ACCURATE

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2\n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4\n\t"

                "paddusb "RED_DITHER"(%0), %%mm5\n\t"

#endif

                WRITERGB16(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_YUYV422:

                YSCALEYUV2PACKEDX_ACCURATE

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

                "psraw $3, %%mm3    \n\t"

                "psraw $3, %%mm4    \n\t"

                "psraw $3, %%mm1    \n\t"

                "psraw $3, %%mm7    \n\t"

                WRITEYUY2(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            }

        } else {

            switch(c->dstFormat) {

            case PIX_FMT_RGB32:

                if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf) {

                    YSCALEYUV2PACKEDX

                    YSCALEYUV2RGBX

                    YSCALEYUV2PACKEDX_YA(ALP_MMX_FILTER_OFFSET, %%mm0, %%mm3, %%mm6, %%mm1, %%mm7)

                    "psraw                        $3, %%mm1         \n\t"

                    "psraw                        $3, %%mm7         \n\t"

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

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm1, %%mm0, %%mm7, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                } else {

                    YSCALEYUV2PACKEDX

                    YSCALEYUV2RGBX

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

                    WRITEBGR32(%4, %5, %%REGa, %%mm2, %%mm4, %%mm5, %%mm7, %%mm0, %%mm1, %%mm3, %%mm6)

                    YSCALEYUV2PACKEDX_END

                }

                return;

            case PIX_FMT_BGR24:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor                    %%mm7, %%mm7       \n\t"

                "lea (%%"REG_a", %%"REG_a", 2), %%"REG_c"   \n\t" //FIXME optimize

                "add                        %4, %%"REG_c"   \n\t"

                WRITEBGR24(%%REGc, %5, %%REGa)

                :: "r" (&c->redDither),

                "m" (dummy), "m" (dummy), "m" (dummy),

                "r" (dest),  "m" (dstW)

                : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S

                );

                return;

            case PIX_FMT_RGB555:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"

                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"

#endif

                WRITERGB15(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_RGB565:

                YSCALEYUV2PACKEDX

                YSCALEYUV2RGBX

                "pxor %%mm7, %%mm7 \n\t"

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

                "paddusb "BLUE_DITHER"(%0), %%mm2  \n\t"

                "paddusb "GREEN_DITHER"(%0), %%mm4  \n\t"

                "paddusb "RED_DITHER"(%0), %%mm5  \n\t"

#endif

                WRITERGB16(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            case PIX_FMT_YUYV422:

                YSCALEYUV2PACKEDX

                /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

                "psraw $3, %%mm3    \n\t"

                "psraw $3, %%mm4    \n\t"

                "psraw $3, %%mm1    \n\t"

                "psraw $3, %%mm7    \n\t"

                WRITEYUY2(%4, %5, %%REGa)

                YSCALEYUV2PACKEDX_END

                return;

            }

        }

    }

#endif /* COMPILE_TEMPLATE_MMX */

#if COMPILE_TEMPLATE_ALTIVEC

    /* The following list of supported dstFormat values should

       match what's found in the body of ff_yuv2packedX_altivec() */

    if (!(c->flags & SWS_BITEXACT) && !c->alpPixBuf &&

         (c->dstFormat==PIX_FMT_ABGR  || c->dstFormat==PIX_FMT_BGRA  ||

          c->dstFormat==PIX_FMT_BGR24 || c->dstFormat==PIX_FMT_RGB24 ||

          c->dstFormat==PIX_FMT_RGBA  || c->dstFormat==PIX_FMT_ARGB))

            ff_yuv2packedX_altivec(c, lumFilter, lumSrc, lumFilterSize,

                                   chrFilter, chrSrc, chrFilterSize,

                                   dest, dstW, dstY);

    else

#endif

        yuv2packedXinC(c, lumFilter, lumSrc, lumFilterSize,

                       chrFilter, chrSrc, chrFilterSize,

                       alpSrc, dest, dstW, dstY);

}


static av_cold int frei0r_init(AVFilterContext *ctx,

                               const char *dl_name, int type)

{

    Frei0rContext *frei0r = ctx->priv;

    f0r_init_f            f0r_init;

    f0r_get_plugin_info_f f0r_get_plugin_info;

    f0r_plugin_info_t *pi;

    char *path;

    int ret = 0;

    /* see: http://frei0r.dyne.org/codedoc/html/group__pluglocations.html */

    if ((path = av_strdup(getenv("FREI0R_PATH")))) {

#ifdef _WIN32

        const char *separator = ";";

#else

        const char *separator = ":";

#endif

        char *p, *ptr = NULL;

        for (p = path; p = av_strtok(p, separator, &ptr); p = NULL) {

            /* add additional trailing slash in case it is missing */

            char *p1 = av_asprintf("%s/", p);

            if (!p1) {

                av_free(path);

                return AVERROR(ENOMEM);

            }

            ret = load_path(ctx, &frei0r->dl_handle, p1, dl_name);

            av_free(p1);

            if (ret < 0) {

                av_free(path);

                return ret;

            }

            if (frei0r->dl_handle)

                break;

        }

        av_free(path);

    }

    if (!frei0r->dl_handle && (path = getenv("HOME"))) {

        char *prefix = av_asprintf("%s/.frei0r-1/lib/", path);

        if (!prefix)

            return AVERROR(ENOMEM);

        ret = load_path(ctx, &frei0r->dl_handle, prefix, dl_name);

        av_free(prefix);

        if (ret < 0)

            return ret;

    }

    if (!frei0r->dl_handle) {

        ret = load_path(ctx, &frei0r->dl_handle, "/usr/local/lib/frei0r-1/", dl_name);

        if (ret < 0)

            return ret;

    }

    if (!frei0r->dl_handle) {

        ret = load_path(ctx, &frei0r->dl_handle, "/usr/lib/frei0r-1/", dl_name);

        if (ret < 0)

            return ret;

    }

    if (!frei0r->dl_handle) {

        av_log(ctx, AV_LOG_ERROR, "Could not find module '%s'\n", dl_name);

        return AVERROR(EINVAL);

    }

    if (!(f0r_init                = load_sym(ctx, "f0r_init"           )) ||

        !(f0r_get_plugin_info     = load_sym(ctx, "f0r_get_plugin_info")) ||

        !(frei0r->get_param_info  = load_sym(ctx, "f0r_get_param_info" )) ||

        !(frei0r->get_param_value = load_sym(ctx, "f0r_get_param_value")) ||

        !(frei0r->set_param_value = load_sym(ctx, "f0r_set_param_value")) ||

        !(frei0r->update          = load_sym(ctx, "f0r_update"         )) ||

        !(frei0r->construct       = load_sym(ctx, "f0r_construct"      )) ||

        !(frei0r->destruct        = load_sym(ctx, "f0r_destruct"       )) ||

        !(frei0r->deinit          = load_sym(ctx, "f0r_deinit"         )))

        return AVERROR(EINVAL);

    if (f0r_init() < 0) {

        av_log(ctx, AV_LOG_ERROR, "Could not init the frei0r module\n");

        return AVERROR(EINVAL);

    }

    f0r_get_plugin_info(&frei0r->plugin_info);

    pi = &frei0r->plugin_info;

    if (pi->plugin_type != type) {

        av_log(ctx, AV_LOG_ERROR,

               "Invalid type '%s' for the plugin\n",

               pi->plugin_type == F0R_PLUGIN_TYPE_FILTER ? "filter" :

               pi->plugin_type == F0R_PLUGIN_TYPE_SOURCE ? "source" :

               pi->plugin_type == F0R_PLUGIN_TYPE_MIXER2 ? "mixer2" :

               pi->plugin_type == F0R_PLUGIN_TYPE_MIXER3 ? "mixer3" : "unknown");

        return AVERROR(EINVAL);

    }

    av_log(ctx, AV_LOG_VERBOSE,

           "name:%s author:'%s' explanation:'%s' color_model:%s "

           "frei0r_version:%d version:%d.%d num_params:%d\n",

           pi->name, pi->author, pi->explanation,

           pi->color_model == F0R_COLOR_MODEL_BGRA8888 ? "bgra8888" :

           pi->color_model == F0R_COLOR_MODEL_RGBA8888 ? "rgba8888" :

           pi->color_model == F0R_COLOR_MODEL_PACKED32 ? "packed32" : "unknown",

           pi->frei0r_version, pi->major_version, pi->minor_version, pi->num_params);

    return 0;

}


uint32_t HELPER(tprot)(CPUS390XState *env, uint64_t a1, uint64_t a2)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    /*

     * TODO: we currently don't handle all access protection types

     * (including access-list and key-controlled) as well as AR mode.

     */

    if (!s390_cpu_virt_mem_check_write(cpu, a1, 0, 1)) {

        /* Fetching permitted; storing permitted */

        return 0;

    }

    switch (env->int_pgm_code) {

    case PGM_PROTECTION:

        /* Fetching permitted; storing not permitted */

        cs->exception_index = 0;

        return 1;

    case PGM_ADDRESSING:

        /* Fetching not permitted; storing not permitted */

        cs->exception_index = 0;

        return 2;

    case PGM_ASCE_TYPE:

    case PGM_REG_FIRST_TRANS:

    case PGM_REG_SEC_TRANS:

    case PGM_REG_THIRD_TRANS:

    case PGM_SEGMENT_TRANS:

    case PGM_PAGE_TRANS:

    case PGM_ALET_SPEC:

    case PGM_ALEN_SPEC:

    case PGM_ALE_SEQ:

    case PGM_ASTE_VALID:

    case PGM_ASTE_SEQ:

    case PGM_EXT_AUTH:

        /* Translation not available */

        cs->exception_index = 0;

        return 3;

    }

    /* any other exception is forwarded to the guest */

    s390_cpu_virt_mem_handle_exc(cpu, GETPC());

    return 0;

}


static int adb_kbd_poll(ADBDevice *d, uint8_t *obuf)

{

    KBDState *s = ADB_KEYBOARD(d);

    int keycode;

    int olen;

    olen = 0;

    if (s->count == 0) {

        return 0;

    }

    keycode = s->data[s->rptr];

    s->rptr++;

    if (s->rptr == sizeof(s->data)) {

        s->rptr = 0;

    }

    s->count--;

    /*

     * The power key is the only two byte value key, so it is a special case.

     * Since 0x7f is not a used keycode for ADB we overload it to indicate the

     * power button when we're storing keycodes in our internal buffer, and

     * expand it out to two bytes when we send to the guest.

     */

    if (keycode == 0x7f) {

        obuf[0] = 0x7f;

        obuf[1] = 0x7f;

        olen = 2;

    } else {

        obuf[0] = keycode;

        /* NOTE: the power key key-up is the two byte sequence 0xff 0xff;

         * otherwise we could in theory send a second keycode in the second

         * byte, but choose not to bother.

         */

        obuf[1] = 0xff;

        olen = 2;

    }

    return olen;

}


static inline int wv_unpack_stereo(WavpackFrameContext *s, GetBitContext *gb,

                                   void *dst_l, void *dst_r, const int type)

{

    int i, j, count = 0;

    int last, t;

    int A, B, L, L2, R, R2;

    int pos                 = s->pos;

    uint32_t crc            = s->sc.crc;

    uint32_t crc_extra_bits = s->extra_sc.crc;

    int16_t *dst16_l        = dst_l;

    int16_t *dst16_r        = dst_r;

    int32_t *dst32_l        = dst_l;

    int32_t *dst32_r        = dst_r;

    float *dstfl_l          = dst_l;

    float *dstfl_r          = dst_r;

    s->one = s->zero = s->zeroes = 0;

    do {

        L = wv_get_value(s, gb, 0, &last);

        if (last)

            break;

        R = wv_get_value(s, gb, 1, &last);

        if (last)

            break;

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

            t = s->decorr[i].value;

            if (t > 0) {

                if (t > 8) {

                    if (t & 1) {

                        A = 2U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1];

                        B = 2U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1];

                    } else {

                        A = (int)(3U * s->decorr[i].samplesA[0] - s->decorr[i].samplesA[1]) >> 1;

                        B = (int)(3U * s->decorr[i].samplesB[0] - s->decorr[i].samplesB[1]) >> 1;

                    }

                    s->decorr[i].samplesA[1] = s->decorr[i].samplesA[0];

                    s->decorr[i].samplesB[1] = s->decorr[i].samplesB[0];

                    j                        = 0;

                } else {

                    A = s->decorr[i].samplesA[pos];

                    B = s->decorr[i].samplesB[pos];

                    j = (pos + t) & 7;

                }

                if (type != AV_SAMPLE_FMT_S16P) {

                    L2 = L + ((s->decorr[i].weightA * (int64_t)A + 512) >> 10);

                    R2 = R + ((s->decorr[i].weightB * (int64_t)B + 512) >> 10);

                } else {

                    L2 = L + ((int)(s->decorr[i].weightA * (unsigned)A + 512) >> 10);

                    R2 = R + ((int)(s->decorr[i].weightB * (unsigned)B + 512) >> 10);

                }

                if (A && L)

                    s->decorr[i].weightA -= ((((L ^ A) >> 30) & 2) - 1) * s->decorr[i].delta;

                if (B && R)

                    s->decorr[i].weightB -= ((((R ^ B) >> 30) & 2) - 1) * s->decorr[i].delta;

                s->decorr[i].samplesA[j] = L = L2;

                s->decorr[i].samplesB[j] = R = R2;

            } else if (t == -1) {

                if (type != AV_SAMPLE_FMT_S16P)

                    L2 = L + ((s->decorr[i].weightA * (int64_t)s->decorr[i].samplesA[0] + 512) >> 10);

                else

                    L2 = L + ((int)(s->decorr[i].weightA * (unsigned)s->decorr[i].samplesA[0] + 512) >> 10);

                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, s->decorr[i].samplesA[0], L);

                L = L2;

                if (type != AV_SAMPLE_FMT_S16P)

                    R2 = R + ((s->decorr[i].weightB * (int64_t)L2 + 512) >> 10);

                else

                    R2 = R + ((int)(s->decorr[i].weightB * (unsigned)L2 + 512) >> 10);

                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, L2, R);

                R                        = R2;

                s->decorr[i].samplesA[0] = R;

            } else {

                if (type != AV_SAMPLE_FMT_S16P)

                    R2 = R + ((s->decorr[i].weightB * (int64_t)s->decorr[i].samplesB[0] + 512) >> 10);

                else

                    R2 = R + ((int)(s->decorr[i].weightB * (unsigned)s->decorr[i].samplesB[0] + 512) >> 10);

                UPDATE_WEIGHT_CLIP(s->decorr[i].weightB, s->decorr[i].delta, s->decorr[i].samplesB[0], R);

                R = R2;

                if (t == -3) {

                    R2                       = s->decorr[i].samplesA[0];

                    s->decorr[i].samplesA[0] = R;

                }

                if (type != AV_SAMPLE_FMT_S16P)

                    L2 = L + ((s->decorr[i].weightA * (int64_t)R2 + 512) >> 10);

                else

                    L2 = L + ((int)(s->decorr[i].weightA * (unsigned)R2 + 512) >> 10);

                UPDATE_WEIGHT_CLIP(s->decorr[i].weightA, s->decorr[i].delta, R2, L);

                L                        = L2;

                s->decorr[i].samplesB[0] = L;

            }

        }

        if (type == AV_SAMPLE_FMT_S16P) {

            if (FFABS(L) + (unsigned)FFABS(R) > (1<<19)) {

                av_log(s->avctx, AV_LOG_ERROR, "sample %d %d too large\n", L, R);

                return AVERROR_INVALIDDATA;

            }

        }

        pos = (pos + 1) & 7;

        if (s->joint)

            L += (unsigned)(R -= (unsigned)(L >> 1));

        crc = (crc * 3 + L) * 3 + R;

        if (type == AV_SAMPLE_FMT_FLTP) {

            *dstfl_l++ = wv_get_value_float(s, &crc_extra_bits, L);

            *dstfl_r++ = wv_get_value_float(s, &crc_extra_bits, R);

        } else if (type == AV_SAMPLE_FMT_S32P) {

            *dst32_l++ = wv_get_value_integer(s, &crc_extra_bits, L);

            *dst32_r++ = wv_get_value_integer(s, &crc_extra_bits, R);

        } else {

            *dst16_l++ = wv_get_value_integer(s, &crc_extra_bits, L);

            *dst16_r++ = wv_get_value_integer(s, &crc_extra_bits, R);

        }

        count++;

    } while (!last && count < s->samples);

    wv_reset_saved_context(s);

    if (last && count < s->samples) {

        int size = av_get_bytes_per_sample(type);

        memset((uint8_t*)dst_l + count*size, 0, (s->samples-count)*size);

        memset((uint8_t*)dst_r + count*size, 0, (s->samples-count)*size);

    }

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

        wv_check_crc(s, crc, crc_extra_bits))

        return AVERROR_INVALIDDATA;

    return 0;

}


static void qxl_create_guest_primary(PCIQXLDevice *qxl, int loadvm,

                                     qxl_async_io async)

{

    QXLDevSurfaceCreate surface;

    QXLSurfaceCreate *sc = &qxl->guest_primary.surface;

    int size;

    int requested_height = le32_to_cpu(sc->height);

    int requested_stride = le32_to_cpu(sc->stride);

    size = abs(requested_stride) * requested_height;

    if (size > qxl->vgamem_size) {

        qxl_set_guest_bug(qxl, "%s: requested primary larger then framebuffer"

                               " size", __func__);

        return;

    }

    if (qxl->mode == QXL_MODE_NATIVE) {

        qxl_set_guest_bug(qxl, "%s: nop since already in QXL_MODE_NATIVE",

                      __func__);

    }

    qxl_exit_vga_mode(qxl);

    surface.format     = le32_to_cpu(sc->format);

    surface.height     = le32_to_cpu(sc->height);

    surface.mem        = le64_to_cpu(sc->mem);

    surface.position   = le32_to_cpu(sc->position);

    surface.stride     = le32_to_cpu(sc->stride);

    surface.width      = le32_to_cpu(sc->width);

    surface.type       = le32_to_cpu(sc->type);

    surface.flags      = le32_to_cpu(sc->flags);

    trace_qxl_create_guest_primary(qxl->id, sc->width, sc->height, sc->mem,

                                   sc->format, sc->position);

    trace_qxl_create_guest_primary_rest(qxl->id, sc->stride, sc->type,

                                        sc->flags);

    if ((surface.stride & 0x3) != 0) {

        qxl_set_guest_bug(qxl, "primary surface stride = %d %% 4 != 0",

                          surface.stride);

        return;

    }

    surface.mouse_mode = true;

    surface.group_id   = MEMSLOT_GROUP_GUEST;

    if (loadvm) {

        surface.flags |= QXL_SURF_FLAG_KEEP_DATA;

    }

    qxl->mode = QXL_MODE_NATIVE;

    qxl->cmdflags = 0;

    qemu_spice_create_primary_surface(&qxl->ssd, 0, &surface, async);

    if (async == QXL_SYNC) {

        qxl_create_guest_primary_complete(qxl);

    }

}


static inline int signed_shift(int i, int shift) {

    if (shift > 0)

        return i << shift;

    return i >> -shift;

}


static void pmsav7_write(CPUARMState *env, const ARMCPRegInfo *ri,

                         uint64_t value)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    uint32_t *u32p = *(uint32_t **)raw_ptr(env, ri);

    if (!u32p) {

        return;

    }

    u32p += env->pmsav7.rnr;

    tlb_flush(CPU(cpu)); /* Mappings may have changed - purge! */

    *u32p = value;

}


void qemu_opts_del(QemuOpts *opts)

{

    QemuOpt *opt;

    for (;;) {

        opt = TAILQ_FIRST(&opts->head);

        if (opt == NULL)

            break;

        qemu_opt_del(opt);

    }

    TAILQ_REMOVE(&opts->list->head, opts, next);

    qemu_free(opts);

}


static int raw_pwrite(BlockDriverState *bs, int64_t offset,

                      const uint8_t *buf, int count)

{

    BDRVRawState *s = bs->opaque;

    int size, ret, shift, sum;

    sum = 0;

    if (s->aligned_buf != NULL) {

        if (offset & 0x1ff) {

            /* align offset on a 512 bytes boundary */

            shift = offset & 0x1ff;

            ret = raw_pread_aligned(bs, offset - shift, s->aligned_buf, 512);

            if (ret < 0)

                return ret;

            size = 512 - shift;

            if (size > count)

                size = count;

            memcpy(s->aligned_buf + shift, buf, size);

            ret = raw_pwrite_aligned(bs, offset - shift, s->aligned_buf, 512);

            if (ret < 0)

                return ret;

            buf += size;

            offset += size;

            count -= size;

            sum += size;

            if (count == 0)

                return sum;

        }

        if (count & 0x1ff || (uintptr_t) buf & 0x1ff) {

            while ((size = (count & ~0x1ff)) != 0) {

                if (size > ALIGNED_BUFFER_SIZE)

                    size = ALIGNED_BUFFER_SIZE;

                memcpy(s->aligned_buf, buf, size);

                ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, size);

                if (ret < 0)

                    return ret;

                buf += ret;

                offset += ret;

                count -= ret;

                sum += ret;

            }

            /* here, count < 512 because (count & ~0x1ff) == 0 */

            if (count) {

                ret = raw_pread_aligned(bs, offset, s->aligned_buf, 512);

                if (ret < 0)

                    return ret;

                 memcpy(s->aligned_buf, buf, count);

                 ret = raw_pwrite_aligned(bs, offset, s->aligned_buf, 512);

                 if (ret < 0)

                     return ret;

                 if (count < ret)

                     ret = count;

                 sum += ret;

            }

            return sum;

        }

    }

    return raw_pwrite_aligned(bs, offset, buf, count) + sum;

}


void acpi_pcihp_device_unplug_cb(HotplugHandler *hotplug_dev, AcpiPciHpState *s,

                                 DeviceState *dev, Error **errp)

{

    PCIDevice *pdev = PCI_DEVICE(dev);

    int slot = PCI_SLOT(pdev->devfn);

    int bsel = acpi_pcihp_get_bsel(pdev->bus);

    if (bsel < 0) {

        error_setg(errp, "Unsupported bus. Bus doesn't have property '"

                   ACPI_PCIHP_PROP_BSEL "' set");

        return;

    }

    s->acpi_pcihp_pci_status[bsel].down |= (1U << slot);

    acpi_send_event(DEVICE(hotplug_dev), ACPI_PCI_HOTPLUG_STATUS);

}


int bdrv_debug_resume(BlockDriverState *bs, const char *tag)

{

    while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {

        bs = bs->file;

    }

    if (bs && bs->drv && bs->drv->bdrv_debug_resume) {

        return bs->drv->bdrv_debug_resume(bs, tag);

    }

    return -ENOTSUP;

}


static int r3d_read_redv(AVFormatContext *s, AVPacket *pkt, Atom *atom)

{

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

    int tmp, tmp2;

    uint64_t pos = url_ftell(s->pb);

    unsigned dts;

    dts = get_be32(s->pb);

    tmp = get_be32(s->pb);

    dprintf(s, "frame num %d\n", tmp);

    tmp  = get_byte(s->pb); // major version

    tmp2 = get_byte(s->pb); // minor version

    dprintf(s, "version %d.%d\n", tmp, tmp2);

    tmp = get_be16(s->pb); // unknown

    dprintf(s, "unknown %d\n", tmp);

    if (tmp > 4) {

        tmp = get_be16(s->pb); // unknown

        dprintf(s, "unknown %d\n", tmp);

        tmp = get_be16(s->pb); // unknown

        dprintf(s, "unknown %d\n", tmp);

        tmp = get_be32(s->pb);

        dprintf(s, "width %d\n", tmp);

        tmp = get_be32(s->pb);

        dprintf(s, "height %d\n", tmp);

        tmp = get_be32(s->pb);

        dprintf(s, "metadata len %d\n", tmp);

    }

    tmp = atom->size - 8 - (url_ftell(s->pb) - pos);

    if (tmp < 0)

        return -1;

    if (av_get_packet(s->pb, pkt, tmp) != tmp) {

        av_log(s, AV_LOG_ERROR, "error reading video packet\n");

        return -1;

    }

    pkt->stream_index = 0;

    pkt->dts = dts;

    if (st->codec->time_base.den)

        pkt->duration = (uint64_t)st->time_base.den*

            st->codec->time_base.num/st->codec->time_base.den;

    dprintf(s, "pkt dts %lld duration %d\n", pkt->dts, pkt->duration);

    return 0;

}


static uint64_t mpc8544_guts_read(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    uint32_t value = 0;

    CPUPPCState *env = cpu_single_env;

    addr &= MPC8544_GUTS_MMIO_SIZE - 1;

    switch (addr) {

    case MPC8544_GUTS_ADDR_PVR:

        value = env->spr[SPR_PVR];

        break;

    case MPC8544_GUTS_ADDR_SVR:

        value = env->spr[SPR_E500_SVR];

        break;

    default:

        fprintf(stderr, "guts: Unknown register read: %x\n", (int)addr);

        break;

    }

    return value;

}


int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)

{

    /* Do not set read_only if copy_on_read is enabled */

    if (bs->copy_on_read && read_only) {

        error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",

                   bdrv_get_device_or_node_name(bs));

        return -EINVAL;

    }

    /* Do not clear read_only if it is prohibited */

    if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR)) {

        error_setg(errp, "Node '%s' is read only",

                   bdrv_get_device_or_node_name(bs));

        return -EPERM;

    }

    bs->read_only = read_only;

    return 0;

}


int qemu_savevm_state_begin(Monitor *mon, QEMUFile *f, int blk_enable,

                            int shared)

{

    SaveStateEntry *se;

    int ret;

    QTAILQ_FOREACH(se, &savevm_handlers, entry) {

        if(se->set_params == NULL) {

            continue;

	}

	se->set_params(blk_enable, shared, se->opaque);

    }

    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);

    qemu_put_be32(f, QEMU_VM_FILE_VERSION);

    QTAILQ_FOREACH(se, &savevm_handlers, entry) {

        int len;

        if (se->save_live_state == NULL)

            continue;

        /* Section type */

        qemu_put_byte(f, QEMU_VM_SECTION_START);

        qemu_put_be32(f, se->section_id);

        /* ID string */

        len = strlen(se->idstr);

        qemu_put_byte(f, len);

        qemu_put_buffer(f, (uint8_t *)se->idstr, len);

        qemu_put_be32(f, se->instance_id);

        qemu_put_be32(f, se->version_id);

        ret = se->save_live_state(mon, f, QEMU_VM_SECTION_START, se->opaque);

        if (ret < 0) {

            qemu_savevm_state_cancel(mon, f);

            return ret;

        }

    }

    ret = qemu_file_get_error(f);

    if (ret != 0) {

        qemu_savevm_state_cancel(mon, f);

    }

    return ret;

}


static void gen_conditional_jump(DisasContext * ctx,

				 target_ulong ift, target_ulong ifnott)

{

    int l1;

    TCGv sr;

    l1 = gen_new_label();

    sr = tcg_temp_new();

    tcg_gen_andi_i32(sr, cpu_sr, SR_T);

    tcg_gen_brcondi_i32(TCG_COND_NE, sr, 0, l1);

    gen_goto_tb(ctx, 0, ifnott);

    gen_set_label(l1);

    gen_goto_tb(ctx, 1, ift);

}


static int wav_write_trailer(AVFormatContext *s)

{

    AVIOContext *pb  = s->pb;

    WAVMuxContext    *wav = s->priv_data;

    int64_t file_size, data_size;

    int64_t number_of_samples = 0;

    int rf64 = 0;

    avio_flush(pb);

    if (s->pb->seekable) {

        if (wav->write_peak != 2) {

            ff_end_tag(pb, wav->data);

            avio_flush(pb);

        }

        if (wav->write_peak && wav->peak_output) {

            peak_write_chunk(s);

            avio_flush(pb);

        }

        /* update file size */

        file_size = avio_tell(pb);

        data_size = file_size - wav->data;

        if (wav->rf64 == RF64_ALWAYS || (wav->rf64 == RF64_AUTO && file_size - 8 > UINT32_MAX)) {

            rf64 = 1;

        } else {

            avio_seek(pb, 4, SEEK_SET);

            avio_wl32(pb, (uint32_t)(file_size - 8));

            avio_seek(pb, file_size, SEEK_SET);

            avio_flush(pb);

        }

        number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,

                                       s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,

                                       s->streams[0]->time_base.den);

        if(s->streams[0]->codec->codec_tag != 0x01) {

            /* Update num_samps in fact chunk */

            avio_seek(pb, wav->fact_pos, SEEK_SET);

            if (rf64 || (wav->rf64 == RF64_AUTO && number_of_samples > UINT32_MAX)) {

                rf64 = 1;

                avio_wl32(pb, -1);

            } else {

                avio_wl32(pb, number_of_samples);

                avio_seek(pb, file_size, SEEK_SET);

                avio_flush(pb);

            }

        }

        if (rf64) {

            /* overwrite RIFF with RF64 */

            avio_seek(pb, 0, SEEK_SET);

            ffio_wfourcc(pb, "RF64");

            avio_wl32(pb, -1);

            /* write ds64 chunk (overwrite JUNK if rf64 == RF64_AUTO) */

            avio_seek(pb, wav->ds64 - 8, SEEK_SET);

            ffio_wfourcc(pb, "ds64");

            avio_wl32(pb, 28);                  /* ds64 chunk size */

            avio_wl64(pb, file_size - 8);       /* RF64 chunk size */

            avio_wl64(pb, data_size);           /* data chunk size */

            avio_wl64(pb, number_of_samples);   /* fact chunk number of samples */

            avio_wl32(pb, 0);                   /* number of table entries for non-'data' chunks */

            /* write -1 in data chunk size */

            avio_seek(pb, wav->data - 4, SEEK_SET);

            avio_wl32(pb, -1);

            avio_seek(pb, file_size, SEEK_SET);

            avio_flush(pb);

        }

    }

    if (wav->write_peak)

        peak_free_buffers(s);

    return 0;

}