void mips_malta_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    char *filename;

    pflash_t *fl;

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios, *bios_copy = g_new(MemoryRegion, 1);

    target_long bios_size = FLASH_SIZE;

    int64_t kernel_entry;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    MIPSCPU *cpu;

    CPUMIPSState *env;

    qemu_irq *isa_irq;

    qemu_irq *cpu_exit_irq;

    int piix4_devfn;

    i2c_bus *smbus;

    int i;

    DriveInfo *dinfo;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    int fl_idx = 0;

    int fl_sectors = bios_size >> 16;

    int be;

    DeviceState *dev = qdev_create(NULL, TYPE_MIPS_MALTA);

    MaltaState *s = MIPS_MALTA(dev);

    qdev_init_nofail(dev);

    /* Make sure the first 3 serial ports are associated with a device. */

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

        if (!serial_hds[i]) {

            char label[32];

            snprintf(label, sizeof(label), "serial%d", i);

            serial_hds[i] = qemu_chr_new(label, "null", NULL);

        }

    }

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "20Kc";

#else

        cpu_model = "24Kf";

#endif

    }

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

        cpu = cpu_mips_init(cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        /* Init internal devices */

        cpu_mips_irq_init_cpu(env);

        cpu_mips_clock_init(env);

        qemu_register_reset(main_cpu_reset, cpu);

    }

    cpu = MIPS_CPU(first_cpu);

    env = &cpu->env;

    /* allocate RAM */

    if (ram_size > (256 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    memory_region_init_ram(ram, NULL, "mips_malta.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(system_memory, 0, ram);

    /* generate SPD EEPROM data */

    eeprom_generate(&eeprom, ram_size);

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    /* FPGA */

    /* The CBUS UART is attached to the MIPS CPU INT2 pin, ie interrupt 4 */

    malta_fpga_init(system_memory, FPGA_ADDRESS, env->irq[4], serial_hds[2]);

    /* Load firmware in flash / BIOS. */

    dinfo = drive_get(IF_PFLASH, 0, fl_idx);

#ifdef DEBUG_BOARD_INIT

    if (dinfo) {

        printf("Register parallel flash %d size " TARGET_FMT_lx " at "

               "addr %08llx '%s' %x\n",

               fl_idx, bios_size, FLASH_ADDRESS,

               bdrv_get_device_name(dinfo->bdrv), fl_sectors);

    }

#endif

    fl = pflash_cfi01_register(FLASH_ADDRESS, NULL, "mips_malta.bios",

                               BIOS_SIZE, dinfo ? dinfo->bdrv : NULL,

                               65536, fl_sectors,

                               4, 0x0000, 0x0000, 0x0000, 0x0000, be);

    bios = pflash_cfi01_get_memory(fl);

    fl_idx++;

    if (kernel_filename) {

        /* Write a small bootloader to the flash location. */

        loaderparams.ram_size = ram_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        kernel_entry = load_kernel();

        write_bootloader(env, memory_region_get_ram_ptr(bios), kernel_entry);

    } else {

        /* Load firmware from flash. */

        if (!dinfo) {

            /* Load a BIOS image. */

            if (bios_name == NULL) {

                bios_name = BIOS_FILENAME;

            }

            filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

            if (filename) {

                bios_size = load_image_targphys(filename, FLASH_ADDRESS,

                                                BIOS_SIZE);

                g_free(filename);

            } else {

                bios_size = -1;

            }

            if ((bios_size < 0 || bios_size > BIOS_SIZE) && !kernel_filename) {

                fprintf(stderr,

                        "qemu: Warning, could not load MIPS bios '%s', and no -kernel argument was specified\n",

                        bios_name);

            }

        }

        /* In little endian mode the 32bit words in the bios are swapped,

           a neat trick which allows bi-endian firmware. */

#ifndef TARGET_WORDS_BIGENDIAN

        {

            uint32_t *end, *addr = rom_ptr(FLASH_ADDRESS);

            if (!addr) {

                addr = memory_region_get_ram_ptr(bios);

            }

            end = (void *)addr + MIN(bios_size, 0x3e0000);

            while (addr < end) {

                bswap32s(addr);

                addr++;

            }

        }

#endif

    }

    /*

     * Map the BIOS at a 2nd physical location, as on the real board.

     * Copy it so that we can patch in the MIPS revision, which cannot be

     * handled by an overlapping region as the resulting ROM code subpage

     * regions are not executable.

     */

    memory_region_init_ram(bios_copy, NULL, "bios.1fc", BIOS_SIZE);

    if (!rom_copy(memory_region_get_ram_ptr(bios_copy),

                  FLASH_ADDRESS, bios_size)) {

        memcpy(memory_region_get_ram_ptr(bios_copy),

               memory_region_get_ram_ptr(bios), bios_size);

    }

    memory_region_set_readonly(bios_copy, true);

    memory_region_add_subregion(system_memory, RESET_ADDRESS, bios_copy);

    /* Board ID = 0x420 (Malta Board with CoreLV) */

    stl_p(memory_region_get_ram_ptr(bios_copy) + 0x10, 0x00000420);

    /* Init internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /*

     * We have a circular dependency problem: pci_bus depends on isa_irq,

     * isa_irq is provided by i8259, i8259 depends on ISA, ISA depends

     * on piix4, and piix4 depends on pci_bus.  To stop the cycle we have

     * qemu_irq_proxy() adds an extra bit of indirection, allowing us

     * to resolve the isa_irq -> i8259 dependency after i8259 is initialized.

     */

    isa_irq = qemu_irq_proxy(&s->i8259, 16);

    /* Northbridge */

    pci_bus = gt64120_register(isa_irq);

    /* Southbridge */

    ide_drive_get(hd, MAX_IDE_BUS);

    piix4_devfn = piix4_init(pci_bus, &isa_bus, 80);

    /* Interrupt controller */

    /* The 8259 is attached to the MIPS CPU INT0 pin, ie interrupt 2 */

    s->i8259 = i8259_init(isa_bus, env->irq[2]);

    isa_bus_irqs(isa_bus, s->i8259);

    pci_piix4_ide_init(pci_bus, hd, piix4_devfn + 1);

    pci_create_simple(pci_bus, piix4_devfn + 2, "piix4-usb-uhci");

    smbus = piix4_pm_init(pci_bus, piix4_devfn + 3, 0x1100,

                          isa_get_irq(NULL, 9), NULL, 0, NULL);

    /* TODO: Populate SPD eeprom data.  */

    smbus_eeprom_init(smbus, 8, NULL, 0);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

    /* Super I/O */

    isa_create_simple(isa_bus, "i8042");

    rtc_init(isa_bus, 2000, NULL);

    serial_isa_init(isa_bus, 0, serial_hds[0]);

    serial_isa_init(isa_bus, 1, serial_hds[1]);

    if (parallel_hds[0])

        parallel_init(isa_bus, 0, parallel_hds[0]);

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(isa_bus, fd);

    /* Network card */

    network_init(pci_bus);

    /* Optional PCI video card */

    pci_vga_init(pci_bus);

}


static void test_pci_enable(void)

{

    AHCIQState *ahci;

    ahci = ahci_boot();

    ahci_pci_enable(ahci);

    ahci_shutdown(ahci);

}


static int fill_psinfo(struct target_elf_prpsinfo *psinfo, const TaskState *ts)

{

    char *filename, *base_filename;

    unsigned int i, len;

    (void) memset(psinfo, 0, sizeof (*psinfo));

    len = ts->info->arg_end - ts->info->arg_start;

    if (len >= ELF_PRARGSZ)

        len = ELF_PRARGSZ - 1;

    if (copy_from_user(&psinfo->pr_psargs, ts->info->arg_start, len))

        return -EFAULT;

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

        if (psinfo->pr_psargs[i] == 0)

            psinfo->pr_psargs[i] = ' ';

    psinfo->pr_psargs[len] = 0;

    psinfo->pr_pid = getpid();

    psinfo->pr_ppid = getppid();

    psinfo->pr_pgrp = getpgrp();

    psinfo->pr_sid = getsid(0);

    psinfo->pr_uid = getuid();

    psinfo->pr_gid = getgid();

    filename = strdup(ts->bprm->filename);

    base_filename = strdup(basename(filename));

    (void) strncpy(psinfo->pr_fname, base_filename,

                   sizeof(psinfo->pr_fname));

    free(base_filename);

    free(filename);

#ifdef BSWAP_NEEDED

    bswap_psinfo(psinfo);

#endif

    return (0);

}


static void do_exit(void)

{

    if (cur_stream) {

        stream_close(cur_stream);

        cur_stream = NULL;

    }

    uninit_opts();

#if CONFIG_AVFILTER

    avfilter_uninit();

#endif

    avformat_network_deinit();

    if (show_status)

        printf("\n");

    SDL_Quit();

    av_log(NULL, AV_LOG_QUIET, "");

    exit(0);

}


static TileExcp decode_y0(DisasContext *dc, tilegx_bundle_bits bundle)

{

    unsigned opc = get_Opcode_Y0(bundle);

    unsigned ext = get_RRROpcodeExtension_Y0(bundle);

    unsigned dest = get_Dest_Y0(bundle);

    unsigned srca = get_SrcA_Y0(bundle);

    unsigned srcb;

    int imm;

    switch (opc) {

    case RRR_1_OPCODE_Y0:

        if (ext == UNARY_RRR_1_OPCODE_Y0) {

            ext = get_UnaryOpcodeExtension_Y0(bundle);

            return gen_rr_opcode(dc, OE(opc, ext, Y0), dest, srca);

        }

        /* fallthru */

    case RRR_0_OPCODE_Y0:

    case RRR_2_OPCODE_Y0:

    case RRR_3_OPCODE_Y0:

    case RRR_4_OPCODE_Y0:

    case RRR_5_OPCODE_Y0:

    case RRR_6_OPCODE_Y0:

    case RRR_7_OPCODE_Y0:

    case RRR_8_OPCODE_Y0:

    case RRR_9_OPCODE_Y0:

        srcb = get_SrcB_Y0(bundle);

        return gen_rrr_opcode(dc, OE(opc, ext, Y0), dest, srca, srcb);

    case SHIFT_OPCODE_Y0:

        ext = get_ShiftOpcodeExtension_Y0(bundle);

        imm = get_ShAmt_Y0(bundle);

        return gen_rri_opcode(dc, OE(opc, ext, Y0), dest, srca, imm);

    case ADDI_OPCODE_Y0:

    case ADDXI_OPCODE_Y0:

    case ANDI_OPCODE_Y0:

    case CMPEQI_OPCODE_Y0:

    case CMPLTSI_OPCODE_Y0:

        imm = (int8_t)get_Imm8_Y0(bundle);

        return gen_rri_opcode(dc, OE(opc, 0, Y0), dest, srca, imm);

    default:

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    }

}


void ioinst_handle_schm(S390CPU *cpu, uint64_t reg1, uint64_t reg2,

                        uint32_t ipb)

{

    uint8_t mbk;

    int update;

    int dct;

    CPUS390XState *env = &cpu->env;

    trace_ioinst("schm");

    if (SCHM_REG1_RES(reg1)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return;

    }

    mbk = SCHM_REG1_MBK(reg1);

    update = SCHM_REG1_UPD(reg1);

    dct = SCHM_REG1_DCT(reg1);

    if (update && (reg2 & 0x000000000000001f)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return;

    }

    css_do_schm(mbk, update, dct, update ? reg2 : 0);

}


QPCIBus *qpci_init_spapr(QGuestAllocator *alloc)

{

    QPCIBusSPAPR *ret;

    ret = g_malloc(sizeof(*ret));

    ret->alloc = alloc;

    ret->bus.io_readb = qpci_spapr_io_readb;

    ret->bus.io_readw = qpci_spapr_io_readw;

    ret->bus.io_readl = qpci_spapr_io_readl;

    ret->bus.io_writeb = qpci_spapr_io_writeb;

    ret->bus.io_writew = qpci_spapr_io_writew;

    ret->bus.io_writel = qpci_spapr_io_writel;

    ret->bus.config_readb = qpci_spapr_config_readb;

    ret->bus.config_readw = qpci_spapr_config_readw;

    ret->bus.config_readl = qpci_spapr_config_readl;

    ret->bus.config_writeb = qpci_spapr_config_writeb;

    ret->bus.config_writew = qpci_spapr_config_writew;

    ret->bus.config_writel = qpci_spapr_config_writel;

    ret->bus.iomap = qpci_spapr_iomap;

    ret->bus.iounmap = qpci_spapr_iounmap;

    /* FIXME: We assume the default location of the PHB for now.

     * Ideally we'd parse the device tree deposited in the guest to

     * get the window locations */

    ret->buid = 0x800000020000000ULL;

    ret->pio_cpu_base = SPAPR_PCI_WINDOW_BASE + SPAPR_PCI_IO_WIN_OFF;

    ret->pio.pci_base = 0;

    ret->pio.size = SPAPR_PCI_IO_WIN_SIZE;

    ret->mmio_cpu_base = SPAPR_PCI_WINDOW_BASE + SPAPR_PCI_MMIO_WIN_OFF;

    ret->mmio.pci_base = SPAPR_PCI_MEM_WIN_BUS_OFFSET;

    ret->mmio.size = SPAPR_PCI_MMIO_WIN_SIZE;

    ret->pci_hole_start = 0xC0000000;

    ret->pci_hole_size =

        ret->mmio.pci_base + ret->mmio.size - ret->pci_hole_start;

    ret->pci_hole_alloc = 0;

    ret->pci_iohole_start = 0xc000;

    ret->pci_iohole_size =

        ret->pio.pci_base + ret->pio.size - ret->pci_iohole_start;

    ret->pci_iohole_alloc = 0;

    return &ret->bus;

}


static void icount_warp_rt(void *opaque)

{

    if (vm_clock_warp_start == -1) {

        return;

    }

    if (runstate_is_running()) {

        int64_t clock = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

        int64_t warp_delta = clock - vm_clock_warp_start;

        if (use_icount == 1) {

            qemu_icount_bias += warp_delta;

        } else {

            /*

             * In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too

             * far ahead of real time.

             */

            int64_t cur_time = cpu_get_clock();

            int64_t cur_icount = cpu_get_icount();

            int64_t delta = cur_time - cur_icount;

            qemu_icount_bias += MIN(warp_delta, delta);

        }

        if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL)) {

            qemu_clock_notify(QEMU_CLOCK_VIRTUAL);

        }

    }

    vm_clock_warp_start = -1;

}


static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,

                               int flags, int send)

{

    abi_long ret, len;

    struct target_msghdr *msgp;

    struct msghdr msg;

    int count;

    struct iovec *vec;

    abi_ulong target_vec;

    /* FIXME */

    if (!lock_user_struct(send ? VERIFY_READ : VERIFY_WRITE,

                          msgp,

                          target_msg,

                          send ? 1 : 0))

        return -TARGET_EFAULT;

    if (msgp->msg_name) {

        msg.msg_namelen = tswap32(msgp->msg_namelen);

        msg.msg_name = alloca(msg.msg_namelen);

        ret = target_to_host_sockaddr(msg.msg_name, tswapal(msgp->msg_name),

                                msg.msg_namelen);

        if (ret) {

            unlock_user_struct(msgp, target_msg, send ? 0 : 1);

            return ret;

        }

    } else {

        msg.msg_name = NULL;

        msg.msg_namelen = 0;

    }

    msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);

    msg.msg_control = alloca(msg.msg_controllen);

    msg.msg_flags = tswap32(msgp->msg_flags);

    count = tswapal(msgp->msg_iovlen);

    vec = alloca(count * sizeof(struct iovec));

    target_vec = tswapal(msgp->msg_iov);

    lock_iovec(send ? VERIFY_READ : VERIFY_WRITE, vec, target_vec, count, send);

    msg.msg_iovlen = count;

    msg.msg_iov = vec;

    if (send) {

        ret = target_to_host_cmsg(&msg, msgp);

        if (ret == 0)

            ret = get_errno(sendmsg(fd, &msg, flags));

    } else {

        ret = get_errno(recvmsg(fd, &msg, flags));

        if (!is_error(ret)) {

            len = ret;

            ret = host_to_target_cmsg(msgp, &msg);

            if (!is_error(ret)) {

                msgp->msg_namelen = tswap32(msg.msg_namelen);

                if (msg.msg_name != NULL) {

                    ret = host_to_target_sockaddr(tswapal(msgp->msg_name),

                                    msg.msg_name, msg.msg_namelen);

                    if (ret) {

                        goto out;

                    }

                }

                ret = len;

            }

        }

    }

out:

    unlock_iovec(vec, target_vec, count, !send);

    unlock_user_struct(msgp, target_msg, send ? 0 : 1);

    return ret;

}


void av_image_copy_plane(uint8_t       *dst, int dst_linesize,

                         const uint8_t *src, int src_linesize,

                         int bytewidth, int height)

{

    if (!dst || !src)

        return;

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

        memcpy(dst, src, bytewidth);

        dst += dst_linesize;

        src += src_linesize;

    }

}


static int latm_decode_frame(AVCodecContext *avctx, void *out,

                             int *got_frame_ptr, AVPacket *avpkt)

{

    struct LATMContext *latmctx = avctx->priv_data;

    int                 muxlength, err;

    GetBitContext       gb;

    if ((err = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)

        return err;

    // check for LOAS sync word

    if (get_bits(&gb, 11) != LOAS_SYNC_WORD)

        return AVERROR_INVALIDDATA;

    muxlength = get_bits(&gb, 13) + 3;

    // not enough data, the parser should have sorted this out

    if (muxlength > avpkt->size)

        return AVERROR_INVALIDDATA;

    if ((err = read_audio_mux_element(latmctx, &gb)) < 0)

        return err;

    if (!latmctx->initialized) {

        if (!avctx->extradata) {

            *got_frame_ptr = 0;

            return avpkt->size;

        } else {

            push_output_configuration(&latmctx->aac_ctx);

            if ((err = decode_audio_specific_config(

                    &latmctx->aac_ctx, avctx, &latmctx->aac_ctx.oc[1].m4ac,

                    avctx->extradata, avctx->extradata_size*8, 1)) < 0) {

                pop_output_configuration(&latmctx->aac_ctx);

                return err;

            }

            latmctx->initialized = 1;

        }

    }

    if (show_bits(&gb, 12) == 0xfff) {

        av_log(latmctx->aac_ctx.avctx, AV_LOG_ERROR,

               "ADTS header detected, probably as result of configuration "

               "misparsing\n");

        return AVERROR_INVALIDDATA;

    }

    switch (latmctx->aac_ctx.oc[1].m4ac.object_type) {

    case AOT_ER_AAC_LC:

    case AOT_ER_AAC_LTP:

    case AOT_ER_AAC_LD:

    case AOT_ER_AAC_ELD:

        err = aac_decode_er_frame(avctx, out, got_frame_ptr, &gb);

        break;

    default:

        err = aac_decode_frame_int(avctx, out, got_frame_ptr, &gb, avpkt);

    }

    if (err < 0)

        return err;

    return muxlength;

}


static int ioreq_runio_qemu_aio(struct ioreq *ioreq)

{

    struct XenBlkDev *blkdev = ioreq->blkdev;

    if (ioreq->req.nr_segments && ioreq_map(ioreq) == -1)

	goto err;

    ioreq->aio_inflight++;

    if (ioreq->presync)

	bdrv_flush(blkdev->bs); /* FIXME: aio_flush() ??? */

    switch (ioreq->req.operation) {

    case BLKIF_OP_READ:

        ioreq->aio_inflight++;

        bdrv_aio_readv(blkdev->bs, ioreq->start / BLOCK_SIZE,

                       &ioreq->v, ioreq->v.size / BLOCK_SIZE,

                       qemu_aio_complete, ioreq);

	break;

    case BLKIF_OP_WRITE:

    case BLKIF_OP_WRITE_BARRIER:

        ioreq->aio_inflight++;

        if (!ioreq->req.nr_segments)

            break;

        bdrv_aio_writev(blkdev->bs, ioreq->start / BLOCK_SIZE,

                        &ioreq->v, ioreq->v.size / BLOCK_SIZE,

                        qemu_aio_complete, ioreq);

	break;

    default:

	/* unknown operation (shouldn't happen -- parse catches this) */

	goto err;

    }

    if (ioreq->postsync)

	bdrv_flush(blkdev->bs); /* FIXME: aio_flush() ??? */

    qemu_aio_complete(ioreq, 0);

    return 0;

err:

    ioreq->status = BLKIF_RSP_ERROR;

    return -1;

}


int attribute_align_arg avcodec_encode_video(AVCodecContext *avctx, uint8_t *buf, int buf_size,

                                             const AVFrame *pict)

{

    AVPacket pkt;

    int ret, got_packet = 0;

    if (buf_size < FF_MIN_BUFFER_SIZE) {

        av_log(avctx, AV_LOG_ERROR, "buffer smaller than minimum size\n");

        return -1;

    }

    av_init_packet(&pkt);

    pkt.data = buf;

    pkt.size = buf_size;

    ret = avcodec_encode_video2(avctx, &pkt, pict, &got_packet);

    if (!ret && got_packet && avctx->coded_frame) {

        avctx->coded_frame->pts       = pkt.pts;

        avctx->coded_frame->key_frame = !!(pkt.flags & AV_PKT_FLAG_KEY);

    }

    /* free any side data since we cannot return it */

    if (pkt.side_data_elems > 0) {

        int i;

        for (i = 0; i < pkt.side_data_elems; i++)

            av_free(pkt.side_data[i].data);

        av_freep(&pkt.side_data);

        pkt.side_data_elems = 0;

    }

    return ret ? ret : pkt.size;

}


static void spapr_pci_pre_save(void *opaque)

{

    sPAPRPHBState *sphb = opaque;

    GHashTableIter iter;

    gpointer key, value;

    int i;

    g_free(sphb->msi_devs);

    sphb->msi_devs = NULL;

    sphb->msi_devs_num = g_hash_table_size(sphb->msi);

    if (!sphb->msi_devs_num) {

        return;

    }

    sphb->msi_devs = g_malloc(sphb->msi_devs_num * sizeof(spapr_pci_msi_mig));

    g_hash_table_iter_init(&iter, sphb->msi);

    for (i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) {

        sphb->msi_devs[i].key = *(uint32_t *) key;

        sphb->msi_devs[i].value = *(spapr_pci_msi *) value;

    }

    if (sphb->pre_2_8_migration) {

        sphb->mig_liobn = sphb->dma_liobn[0];

        sphb->mig_mem_win_addr = sphb->mem_win_addr;

        sphb->mig_mem_win_size = sphb->mem_win_size;

        sphb->mig_io_win_addr = sphb->io_win_addr;

        sphb->mig_io_win_size = sphb->io_win_size;

        if ((sphb->mem64_win_size != 0)

            && (sphb->mem64_win_addr

                == (sphb->mem_win_addr + sphb->mem_win_size))) {

            sphb->mig_mem_win_size += sphb->mem64_win_size;

        }

    }

}


static void print_report(AVFormatContext **output_files,

                         AVOutputStream **ost_table, int nb_ostreams,

                         int is_last_report)

{

    char buf[1024];

    AVOutputStream *ost;

    AVFormatContext *oc, *os;

    int64_t total_size;

    AVCodecContext *enc;

    int frame_number, vid, i;

    double bitrate, ti1, pts;

    static int64_t last_time = -1;

    static int qp_histogram[52];

    if (!is_last_report) {

        int64_t cur_time;

        /* display the report every 0.5 seconds */

        cur_time = av_gettime();

        if (last_time == -1) {

            last_time = cur_time;

            return;

        }

        if ((cur_time - last_time) < 500000)

            return;

        last_time = cur_time;

    }

    oc = output_files[0];

    total_size = url_fsize(oc->pb);

    if(total_size<0) // FIXME improve url_fsize() so it works with non seekable output too

        total_size= url_ftell(oc->pb);

    buf[0] = '\0';

    ti1 = 1e10;

    vid = 0;

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

        ost = ost_table[i];

        os = output_files[ost->file_index];

        enc = ost->st->codec;

        if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",

                    enc->coded_frame->quality/(float)FF_QP2LAMBDA);

        }

        if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {

            float t = (av_gettime()-timer_start) / 1000000.0;

            frame_number = ost->frame_number;

            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",

                     frame_number, (t>1)?(int)(frame_number/t+0.5) : 0,

                     enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);

            if(is_last_report)

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");

            if(qp_hist && enc->coded_frame){

                int j;

                int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);

                if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))

                    qp_histogram[qp]++;

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

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));

            }

            if (enc->flags&CODEC_FLAG_PSNR){

                int j;

                double error, error_sum=0;

                double scale, scale_sum=0;

                char type[3]= {'Y','U','V'};

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");

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

                    if(is_last_report){

                        error= enc->error[j];

                        scale= enc->width*enc->height*255.0*255.0*frame_number;

                    }else{

                        error= enc->coded_frame->error[j];

                        scale= enc->width*enc->height*255.0*255.0;

                    }

                    if(j) scale/=4;

                    error_sum += error;

                    scale_sum += scale;

                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));

                }

                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));

            }

            vid = 1;

        }

        /* compute min output value */

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

        if ((pts < ti1) && (pts > 0))

            ti1 = pts;

    }

    if (ti1 < 0.01)

        ti1 = 0.01;

    if (verbose || is_last_report) {

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

        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),

            "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",

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

        if (verbose > 1)

          snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",

                  nb_frames_dup, nb_frames_drop);

        if (verbose >= 0)

            fprintf(stderr, "%s    \r", buf);

        fflush(stderr);

    }

    if (is_last_report && verbose >= 0){

        int64_t raw= audio_size + video_size + extra_size;

        fprintf(stderr, "\n");

        fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",

                video_size/1024.0,

                audio_size/1024.0,

                extra_size/1024.0,

                100.0*(total_size - raw)/raw

        );

    }

}


static void decode_opc(DisasContext * ctx)

{

    uint32_t old_flags = ctx->envflags;

    _decode_opc(ctx);

    if (old_flags & DELAY_SLOT_MASK) {

        /* go out of the delay slot */

        ctx->envflags &= ~DELAY_SLOT_MASK;

        tcg_gen_movi_i32(cpu_flags, ctx->envflags);

        ctx->bstate = BS_BRANCH;

        if (old_flags & DELAY_SLOT_CONDITIONAL) {

	    gen_delayed_conditional_jump(ctx);

        } else if (old_flags & DELAY_SLOT) {

            gen_jump(ctx);

	}

    }

}


grlib_apbuart_writel(void *opaque, target_phys_addr_t addr, uint32_t value)

{

    UART          *uart = opaque;

    unsigned char  c    = 0;

    addr &= 0xff;

    /* Unit registers */

    switch (addr) {

    case DATA_OFFSET:

        c = value & 0xFF;

        qemu_chr_write(uart->chr, &c, 1);

        return;

    case STATUS_OFFSET:

        /* Read Only */

        return;

    case CONTROL_OFFSET:

        /* Not supported */

        return;

    case SCALER_OFFSET:

        /* Not supported */

        return;

    default:

        break;

    }

    trace_grlib_apbuart_unknown_register("write", addr);

}


static void vhost_set_memory(MemoryListener *listener,

                             MemoryRegionSection *section,

                             bool add)

{

    struct vhost_dev *dev = container_of(listener, struct vhost_dev,

                                         memory_listener);

    hwaddr start_addr = section->offset_within_address_space;

    ram_addr_t size = int128_get64(section->size);

    bool log_dirty =

        memory_region_get_dirty_log_mask(section->mr) & ~(1 << DIRTY_MEMORY_MIGRATION);

    int s = offsetof(struct vhost_memory, regions) +

        (dev->mem->nregions + 1) * sizeof dev->mem->regions[0];

    void *ram;

    dev->mem = g_realloc(dev->mem, s);

    if (log_dirty) {

        add = false;

    }

    assert(size);

    /* Optimize no-change case. At least cirrus_vga does this a lot at this time. */

    ram = memory_region_get_ram_ptr(section->mr) + section->offset_within_region;

    if (add) {

        if (!vhost_dev_cmp_memory(dev, start_addr, size, (uintptr_t)ram)) {

            /* Region exists with same address. Nothing to do. */

            return;

        }

    } else {

        if (!vhost_dev_find_reg(dev, start_addr, size)) {

            /* Removing region that we don't access. Nothing to do. */

            return;

        }

    }

    vhost_dev_unassign_memory(dev, start_addr, size);

    if (add) {

        /* Add given mapping, merging adjacent regions if any */

        vhost_dev_assign_memory(dev, start_addr, size, (uintptr_t)ram);

    } else {

        /* Remove old mapping for this memory, if any. */

        vhost_dev_unassign_memory(dev, start_addr, size);

    }

    dev->mem_changed_start_addr = MIN(dev->mem_changed_start_addr, start_addr);

    dev->mem_changed_end_addr = MAX(dev->mem_changed_end_addr, start_addr + size - 1);

    dev->memory_changed = true;

}


void do_tw (int flags)

{

    if (!likely(!((Ts0 < Ts1 && (flags & 0x10)) ||

                  (Ts0 > Ts1 && (flags & 0x08)) ||

                  (Ts0 == Ts1 && (flags & 0x04)) ||

                  (T0 < T1 && (flags & 0x02)) ||

                  (T0 > T1 && (flags & 0x01)))))

        do_raise_exception_err(EXCP_PROGRAM, EXCP_TRAP);

}


static int mss2_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    MSS2Context *ctx = avctx->priv_data;

    MSS12Context *c  = &ctx->c;

    AVFrame *frame   = data;

    GetBitContext gb;

    GetByteContext gB;

    ArithCoder acoder;

    int keyframe, has_wmv9, has_mv, is_rle, is_555, ret;

    Rectangle wmv9rects[MAX_WMV9_RECTANGLES], *r;

    int used_rects = 0, i, implicit_rect = 0, av_uninit(wmv9_mask);

    if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)

        return ret;

    if (keyframe = get_bits1(&gb))

        skip_bits(&gb, 7);

    has_wmv9 = get_bits1(&gb);

    has_mv   = keyframe ? 0 : get_bits1(&gb);

    is_rle   = get_bits1(&gb);

    is_555   = is_rle && get_bits1(&gb);

    if (c->slice_split > 0)

        ctx->split_position = c->slice_split;

    else if (c->slice_split < 0) {

        if (get_bits1(&gb)) {

            if (get_bits1(&gb)) {

                if (get_bits1(&gb))

                    ctx->split_position = get_bits(&gb, 16);

                else

                    ctx->split_position = get_bits(&gb, 12);

            } else

                ctx->split_position = get_bits(&gb, 8) << 4;

        } else {

            if (keyframe)

                ctx->split_position = avctx->height / 2;

        }

    } else

        ctx->split_position = avctx->height;

    if (c->slice_split && (ctx->split_position < 1 - is_555 ||

                           ctx->split_position > avctx->height - 1))

        return AVERROR_INVALIDDATA;

    align_get_bits(&gb);

    buf      += get_bits_count(&gb) >> 3;

    buf_size -= get_bits_count(&gb) >> 3;

    if (buf_size < 1)

        return AVERROR_INVALIDDATA;

    if (is_555 && (has_wmv9 || has_mv || c->slice_split && ctx->split_position))

        return AVERROR_INVALIDDATA;

    avctx->pix_fmt = is_555 ? AV_PIX_FMT_RGB555 : AV_PIX_FMT_RGB24;

    if (ctx->last_pic->format != avctx->pix_fmt)

        av_frame_unref(ctx->last_pic);

    if (has_wmv9) {

        bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);

        arith2_init(&acoder, &gB);

        implicit_rect = !arith2_get_bit(&acoder);

        while (arith2_get_bit(&acoder)) {

            if (used_rects == MAX_WMV9_RECTANGLES)

                return AVERROR_INVALIDDATA;

            r = &wmv9rects[used_rects];

            if (!used_rects)

                r->x = arith2_get_number(&acoder, avctx->width);

            else

                r->x = arith2_get_number(&acoder, avctx->width -

                                         wmv9rects[used_rects - 1].x) +

                       wmv9rects[used_rects - 1].x;

            r->y = arith2_get_number(&acoder, avctx->height);

            r->w = arith2_get_number(&acoder, avctx->width  - r->x) + 1;

            r->h = arith2_get_number(&acoder, avctx->height - r->y) + 1;

            used_rects++;

        }

        if (implicit_rect && used_rects) {

            av_log(avctx, AV_LOG_ERROR, "implicit_rect && used_rects > 0\n");

            return AVERROR_INVALIDDATA;

        }

        if (implicit_rect) {

            wmv9rects[0].x = 0;

            wmv9rects[0].y = 0;

            wmv9rects[0].w = avctx->width;

            wmv9rects[0].h = avctx->height;

            used_rects = 1;

        }

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

            if (!implicit_rect && arith2_get_bit(&acoder)) {

                av_log(avctx, AV_LOG_ERROR, "Unexpected grandchildren\n");

                return AVERROR_INVALIDDATA;

            }

            if (!i) {

                wmv9_mask = arith2_get_bit(&acoder) - 1;

                if (!wmv9_mask)

                    wmv9_mask = arith2_get_number(&acoder, 256);

            }

            wmv9rects[i].coded = arith2_get_number(&acoder, 2);

        }

        buf      += arith2_get_consumed_bytes(&acoder);

        buf_size -= arith2_get_consumed_bytes(&acoder);

        if (buf_size < 1)

            return AVERROR_INVALIDDATA;

    }

    c->mvX = c->mvY = 0;

    if (keyframe && !is_555) {

        if ((i = decode_pal_v2(c, buf, buf_size)) < 0)

            return AVERROR_INVALIDDATA;

        buf      += i;

        buf_size -= i;

    } else if (has_mv) {

        buf      += 4;

        buf_size -= 4;

        if (buf_size < 1)

            return AVERROR_INVALIDDATA;

        c->mvX = AV_RB16(buf - 4) - avctx->width;

        c->mvY = AV_RB16(buf - 2) - avctx->height;

    }

    if (c->mvX < 0 || c->mvY < 0) {

        FFSWAP(uint8_t *, c->pal_pic, c->last_pal_pic);

        if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)

            return ret;

        if (ctx->last_pic->data[0]) {

            av_assert0(frame->linesize[0] == ctx->last_pic->linesize[0]);

            c->last_rgb_pic = ctx->last_pic->data[0] +

                              ctx->last_pic->linesize[0] * (avctx->height - 1);

        } else {

            av_log(avctx, AV_LOG_ERROR, "Missing keyframe\n");

            return AVERROR_INVALIDDATA;

        }

    } else {

        if ((ret = ff_reget_buffer(avctx, ctx->last_pic)) < 0)

            return ret;

        if ((ret = av_frame_ref(frame, ctx->last_pic)) < 0)

            return ret;

        c->last_rgb_pic = NULL;

    }

    c->rgb_pic    = frame->data[0] +

                    frame->linesize[0] * (avctx->height - 1);

    c->rgb_stride = -frame->linesize[0];

    frame->key_frame = keyframe;

    frame->pict_type = keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;

    if (is_555) {

        bytestream2_init(&gB, buf, buf_size);

        if (decode_555(&gB, (uint16_t *)c->rgb_pic, c->rgb_stride >> 1,

                       keyframe, avctx->width, avctx->height))

            return AVERROR_INVALIDDATA;

        buf_size -= bytestream2_tell(&gB);

    } else {

        if (keyframe) {

            c->corrupted = 0;

            ff_mss12_slicecontext_reset(&ctx->sc[0]);

            if (c->slice_split)

                ff_mss12_slicecontext_reset(&ctx->sc[1]);

        }

        if (is_rle) {

            if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)

                return ret;

            if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,

                                 c->rgb_pic, c->rgb_stride, c->pal, keyframe,

                                 ctx->split_position, 0,

                                 avctx->width, avctx->height))

                return ret;

            align_get_bits(&gb);

            if (c->slice_split)

                if (ret = decode_rle(&gb, c->pal_pic, c->pal_stride,

                                     c->rgb_pic, c->rgb_stride, c->pal, keyframe,

                                     ctx->split_position, 1,

                                     avctx->width, avctx->height))

                    return ret;

            align_get_bits(&gb);

            buf      += get_bits_count(&gb) >> 3;

            buf_size -= get_bits_count(&gb) >> 3;

        } else if (!implicit_rect || wmv9_mask != -1) {

            if (c->corrupted)

                return AVERROR_INVALIDDATA;

            bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);

            arith2_init(&acoder, &gB);

            c->keyframe = keyframe;

            if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[0], &acoder, 0, 0,

                                                    avctx->width,

                                                    ctx->split_position))

                return AVERROR_INVALIDDATA;

            buf      += arith2_get_consumed_bytes(&acoder);

            buf_size -= arith2_get_consumed_bytes(&acoder);

            if (c->slice_split) {

                if (buf_size < 1)

                    return AVERROR_INVALIDDATA;

                bytestream2_init(&gB, buf, buf_size + ARITH2_PADDING);

                arith2_init(&acoder, &gB);

                if (c->corrupted = ff_mss12_decode_rect(&ctx->sc[1], &acoder, 0,

                                                        ctx->split_position,

                                                        avctx->width,

                                                        avctx->height - ctx->split_position))

                    return AVERROR_INVALIDDATA;

                buf      += arith2_get_consumed_bytes(&acoder);

                buf_size -= arith2_get_consumed_bytes(&acoder);

            }

        } else

            memset(c->pal_pic, 0, c->pal_stride * avctx->height);

    }

    if (has_wmv9) {

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

            int x = wmv9rects[i].x;

            int y = wmv9rects[i].y;

            int w = wmv9rects[i].w;

            int h = wmv9rects[i].h;

            if (wmv9rects[i].coded) {

                int WMV9codedFrameSize;

                if (buf_size < 4 || !(WMV9codedFrameSize = AV_RL24(buf)))

                    return AVERROR_INVALIDDATA;

                if (ret = decode_wmv9(avctx, buf + 3, buf_size - 3,

                                      x, y, w, h, wmv9_mask))

                    return ret;

                buf      += WMV9codedFrameSize + 3;

                buf_size -= WMV9codedFrameSize + 3;

            } else {

                uint8_t *dst = c->rgb_pic + y * c->rgb_stride + x * 3;

                if (wmv9_mask != -1) {

                    ctx->dsp.mss2_gray_fill_masked(dst, c->rgb_stride,

                                                   wmv9_mask,

                                                   c->pal_pic + y * c->pal_stride + x,

                                                   c->pal_stride,

                                                   w, h);

                } else {

                    do {

                        memset(dst, 0x80, w * 3);

                        dst += c->rgb_stride;

                    } while (--h);

                }

            }

        }

    }

    if (buf_size)

        av_log(avctx, AV_LOG_WARNING, "buffer not fully consumed\n");

    if (c->mvX < 0 || c->mvY < 0) {

        av_frame_unref(ctx->last_pic);

        ret = av_frame_ref(ctx->last_pic, frame);

        if (ret < 0)

            return ret;

    }

    *got_frame       = 1;

    return avpkt->size;

}


static int output_packet(InputStream *ist, int ist_index,

                         OutputStream *ost_table, int nb_ostreams,

                         const AVPacket *pkt)

{

    AVFormatContext *os;

    OutputStream *ost;

    int ret, i;

    int got_output;

    void *buffer_to_free = NULL;

    static unsigned int samples_size= 0;

    AVSubtitle subtitle, *subtitle_to_free;

    int64_t pkt_pts = AV_NOPTS_VALUE;

#if CONFIG_AVFILTER

    int frame_available;

#endif

    float quality;

    AVPacket avpkt;

    int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);

    if(ist->next_pts == AV_NOPTS_VALUE)

        ist->next_pts= ist->pts;

    if (pkt == NULL) {

        /* EOF handling */

        av_init_packet(&avpkt);

        avpkt.data = NULL;

        avpkt.size = 0;

        goto handle_eof;

    } else {

        avpkt = *pkt;

    }

    if(pkt->dts != AV_NOPTS_VALUE)

        ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);

    if(pkt->pts != AV_NOPTS_VALUE)

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

    //while we have more to decode or while the decoder did output something on EOF

    while (avpkt.size > 0 || (!pkt && got_output)) {

        uint8_t *data_buf, *decoded_data_buf;

        int data_size, decoded_data_size;

        AVFrame *decoded_frame, *filtered_frame;

    handle_eof:

        ist->pts= ist->next_pts;

        if(avpkt.size && avpkt.size != pkt->size)

            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,

                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);

            ist->showed_multi_packet_warning=1;

        /* decode the packet if needed */

        decoded_frame    = filtered_frame = NULL;

        decoded_data_buf = NULL; /* fail safe */

        decoded_data_size= 0;

        data_buf  = avpkt.data;

        data_size = avpkt.size;

        subtitle_to_free = NULL;

        if (ist->decoding_needed) {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:{

                if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {

                    samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);

                    av_free(samples);

                    samples= av_malloc(samples_size);

                }

                decoded_data_size= samples_size;

                    /* XXX: could avoid copy if PCM 16 bits with same

                       endianness as CPU */

                ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,

                                            &avpkt);

                if (ret < 0)

                    return ret;

                avpkt.data += ret;

                avpkt.size -= ret;

                data_size   = ret;

                got_output  = decoded_data_size > 0;

                /* Some bug in mpeg audio decoder gives */

                /* decoded_data_size < 0, it seems they are overflows */

                if (!got_output) {

                    /* no audio frame */

                    continue;

                }

                decoded_data_buf = (uint8_t *)samples;

                ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /

                    (ist->st->codec->sample_rate * ist->st->codec->channels);

                break;}

            case AVMEDIA_TYPE_VIDEO:

                    decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;

                    if (!(decoded_frame = avcodec_alloc_frame()))

                        return AVERROR(ENOMEM);

                    avpkt.pts = pkt_pts;

                    avpkt.dts = ist->pts;

                    pkt_pts = AV_NOPTS_VALUE;

                    ret = avcodec_decode_video2(ist->st->codec,

                                                decoded_frame, &got_output, &avpkt);

                    quality = same_quant ? decoded_frame->quality : 0;

                    if (ret < 0)

                        goto fail;

                    if (!got_output) {

                        /* no picture yet */

                        av_freep(&decoded_frame);

                        goto discard_packet;

                    }

                    ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;

                    if (ist->st->codec->time_base.num != 0) {

                        int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                        ist->next_pts += ((int64_t)AV_TIME_BASE *

                                          ist->st->codec->time_base.num * ticks) /

                            ist->st->codec->time_base.den;

                    }

                    avpkt.size = 0;

                    buffer_to_free = NULL;

                    pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);

                    break;

            case AVMEDIA_TYPE_SUBTITLE:

                ret = avcodec_decode_subtitle2(ist->st->codec,

                                               &subtitle, &got_output, &avpkt);

                if (ret < 0)

                    return ret;

                if (!got_output) {

                    goto discard_packet;

                }

                subtitle_to_free = &subtitle;

                avpkt.size = 0;

                break;

            default:

                return -1;

            }

        } else {

            switch(ist->st->codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /

                    ist->st->codec->sample_rate;

                break;

            case AVMEDIA_TYPE_VIDEO:

                if (ist->st->codec->time_base.num != 0) {

                    int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;

                    ist->next_pts += ((int64_t)AV_TIME_BASE *

                                      ist->st->codec->time_base.num * ticks) /

                        ist->st->codec->time_base.den;

                }

                break;

            }

            avpkt.size = 0;

        }

#if CONFIG_AVFILTER

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

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

            OutputFile *of = &output_files[ost_table[i].file_index];

            if (of->start_time == 0 || ist->pts >= of->start_time) {

                ost = &ost_table[i];

                if (ost->input_video_filter && ost->source_index == ist_index) {

                if (!decoded_frame->sample_aspect_ratio.num)

                    decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;

                decoded_frame->pts = ist->pts;

                av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);

                }

            }

        }

#endif

        // preprocess audio (volume)

        if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (audio_volume != 256) {

                short *volp;

                volp = samples;

                for(i=0;i<(decoded_data_size / sizeof(short));i++) {

                    int v = ((*volp) * audio_volume + 128) >> 8;

                    *volp++ = av_clip_int16(v);

                }

            }

        }

        /* frame rate emulation */

        if (input_files[ist->file_index].rate_emu) {

            int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);

            int64_t now = av_gettime() - ist->start;

            if (pts > now)

                usleep(pts - now);

        }

        /* if output time reached then transcode raw format,

           encode packets and output them */

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

            OutputFile *of = &output_files[ost_table[i].file_index];

            int frame_size;

            ost = &ost_table[i];

            if (ost->source_index != ist_index)

                continue;

            if (of->start_time && ist->pts < of->start_time)

                continue;

            if (of->recording_time != INT64_MAX &&

                av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,

                              (AVRational){1, 1000000}) >= 0) {

                ost->is_past_recording_time = 1;

                continue;

            }

#if CONFIG_AVFILTER

            frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||

                !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);

            while (frame_available) {

                if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter) {

                    AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;

                    if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)

                        goto cont;

                    if (!filtered_frame && !(filtered_frame = avcodec_alloc_frame())) {

                        ret = AVERROR(ENOMEM);

                        goto fail;

                    }

                    *filtered_frame= *decoded_frame; //for me_threshold

                    if (ost->picref) {

                        avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);

                        ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);

                    }

                }

#else

                filtered_frame = decoded_frame;

#endif

                os = output_files[ost->file_index].ctx;

                /* set the input output pts pairs */

                //ost->sync_ipts = (double)(ist->pts + input_files[ist->file_index].ts_offset - start_time)/ AV_TIME_BASE;

                if (ost->encoding_needed) {

                    av_assert0(ist->decoding_needed);

                    switch(ost->st->codec->codec_type) {

                    case AVMEDIA_TYPE_AUDIO:

                        do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);

                        break;

                    case AVMEDIA_TYPE_VIDEO:

#if CONFIG_AVFILTER

                        if (ost->picref->video && !ost->frame_aspect_ratio)

                            ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;

#endif

                        do_video_out(os, ost, ist, filtered_frame, &frame_size,

                                     same_quant ? quality : ost->st->codec->global_quality);

                        if (vstats_filename && frame_size)

                            do_video_stats(os, ost, frame_size);

                        break;

                    case AVMEDIA_TYPE_SUBTITLE:

                        do_subtitle_out(os, ost, ist, &subtitle,

                                        pkt->pts);

                        break;

                    default:

                        abort();

                    }

                } else {

                    AVPicture pict;

                    AVPacket opkt;

                    int64_t ost_tb_start_time= av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);

                    av_init_packet(&opkt);

                    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)

#if !CONFIG_AVFILTER

                        continue;

#else

                        goto cont;

#endif

                    /* no reencoding needed : output the packet directly */

                    /* force the input stream PTS */

                    if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                        audio_size += data_size;

                    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

                        video_size += data_size;

                        ost->sync_opts++;

                    }

                    opkt.stream_index= ost->index;

                    if(pkt->pts != AV_NOPTS_VALUE)

                        opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;

                    else

                        opkt.pts= AV_NOPTS_VALUE;

                    if (pkt->dts == AV_NOPTS_VALUE)

                        opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);

                    else

                        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);

                    opkt.dts -= ost_tb_start_time;

                    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);

                    opkt.flags= pkt->flags;

                    //FIXME remove the following 2 lines they shall be replaced by the bitstream filters

                    if(   ost->st->codec->codec_id != CODEC_ID_H264

                       && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO

                       && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO

                       ) {

                        if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))

                            opkt.destruct= av_destruct_packet;

                    } else {

                        opkt.data = data_buf;

                        opkt.size = data_size;

                    }

                    if (os->oformat->flags & AVFMT_RAWPICTURE) {

                        /* store AVPicture in AVPacket, as expected by the output format */

                        avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);

                        opkt.data = (uint8_t *)&pict;

                        opkt.size = sizeof(AVPicture);

                        opkt.flags |= AV_PKT_FLAG_KEY;

                    }

                    write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);

                    ost->st->codec->frame_number++;

                    ost->frame_number++;

                    av_free_packet(&opkt);

                }

#if CONFIG_AVFILTER

                cont:

                frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&

                                   ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);

                avfilter_unref_buffer(ost->picref);

            }

            av_freep(&filtered_frame);

#endif

        }

fail:

        av_free(buffer_to_free);

        /* XXX: allocate the subtitles in the codec ? */

        if (subtitle_to_free) {

            avsubtitle_free(subtitle_to_free);

            subtitle_to_free = NULL;

        }

        av_freep(&decoded_frame);

        if (ret < 0)

            return ret;

    }

 discard_packet:

    return 0;

}


void wdt_i6300esb_init(void)

{

    watchdog_add_model(&model);

}


static int decode_frame(AVCodecContext * avctx,

			void *data, int *data_size,

			UINT8 * buf, int buf_size)

{

    MPADecodeContext *s = avctx->priv_data;

    UINT32 header;

    UINT8 *buf_ptr;

    int len, out_size;

    short *out_samples = data;

    *data_size = 0;

    buf_ptr = buf;

    while (buf_size > 0) {

	len = s->inbuf_ptr - s->inbuf;

	if (s->frame_size == 0) {

            /* special case for next header for first frame in free

               format case (XXX: find a simpler method) */

            if (s->free_format_next_header != 0) {

                s->inbuf[0] = s->free_format_next_header >> 24;

                s->inbuf[1] = s->free_format_next_header >> 16;

                s->inbuf[2] = s->free_format_next_header >> 8;

                s->inbuf[3] = s->free_format_next_header;

                s->inbuf_ptr = s->inbuf + 4;

                s->free_format_next_header = 0;

                goto got_header;

            }

	    /* no header seen : find one. We need at least HEADER_SIZE

               bytes to parse it */

	    len = HEADER_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

	    else if (len > 0) {

	    memcpy(s->inbuf_ptr, buf_ptr, len);

	    buf_ptr += len;

	    buf_size -= len;

		s->inbuf_ptr += len;

	    }

	    if ((s->inbuf_ptr - s->inbuf) >= HEADER_SIZE) {

            got_header:

		header = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

		    (s->inbuf[2] << 8) | s->inbuf[3];

		if (check_header(header) < 0) {

		    /* no sync found : move by one byte (inefficient, but simple!) */

		    memcpy(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf);

		    s->inbuf_ptr--;

                    dprintf("skip %x\n", header);

                    /* reset free format frame size to give a chance

                       to get a new bitrate */

                    s->free_format_frame_size = 0;

		} else {

		    if (decode_header(s, header) == 1) {

                        /* free format: compute frame size */

                        s->frame_size = -1;

			memcpy(s->inbuf, s->inbuf + 1, s->inbuf_ptr - s->inbuf);

			s->inbuf_ptr--;

                    } else {

                        /* update codec info */

                        avctx->sample_rate = s->sample_rate;

                        avctx->channels = s->nb_channels;

                        avctx->bit_rate = s->bit_rate;

                    }

		}

	    }

        } else if (s->frame_size == -1) {

            /* free format : find next sync to compute frame size */

	    len = MPA_MAX_CODED_FRAME_SIZE - len;

	    if (len > buf_size)

		len = buf_size;

            if (len == 0) {

                /* frame too long: resync */

                s->frame_size = 0;

            } else {

                UINT8 *p, *pend;

                UINT32 header1;

                int padding;

                memcpy(s->inbuf_ptr, buf_ptr, len);

                /* check for header */

                p = s->inbuf_ptr - 3;

                pend = s->inbuf_ptr + len - 4;

                while (p <= pend) {

                    header = (p[0] << 24) | (p[1] << 16) |

                        (p[2] << 8) | p[3];

                    header1 = (s->inbuf[0] << 24) | (s->inbuf[1] << 16) |

                        (s->inbuf[2] << 8) | s->inbuf[3];

                    /* check with high probability that we have a

                       valid header */

                    if ((header & SAME_HEADER_MASK) ==

                        (header1 & SAME_HEADER_MASK)) {

                        /* header found: update pointers */

                        len = (p + 4) - s->inbuf_ptr;

                        buf_ptr += len;

                        buf_size -= len;

                        s->inbuf_ptr = p;

                        /* compute frame size */

                        s->free_format_next_header = header;

                        s->free_format_frame_size = s->inbuf_ptr - s->inbuf;

                        padding = (header1 >> 9) & 1;

                        if (s->layer == 1)

                            s->free_format_frame_size -= padding * 4;

                        else

                            s->free_format_frame_size -= padding;

                        dprintf("free frame size=%d padding=%d\n",

                                s->free_format_frame_size, padding);

                        decode_header(s, header1);

                        goto next_data;

                    }

                    p++;

                }

                /* not found: simply increase pointers */

                buf_ptr += len;

                s->inbuf_ptr += len;

                buf_size -= len;

            }

	} else if (len < s->frame_size) {

            if (s->frame_size > MPA_MAX_CODED_FRAME_SIZE)

                s->frame_size = MPA_MAX_CODED_FRAME_SIZE;

	    len = s->frame_size - len;

	    if (len > buf_size)

		len = buf_size;

	    else if (len > 0)

	    {

	    memcpy(s->inbuf_ptr, buf_ptr, len);

	    buf_ptr += len;

	    s->inbuf_ptr += len;

	    buf_size -= len;

	    }

	} else {

            out_size = mp_decode_frame(s, out_samples);

	    s->inbuf_ptr = s->inbuf;

	    s->frame_size = 0;

	    *data_size = out_size;

	    break;

	}

    next_data:

    }

    return buf_ptr - buf;

}


static int mpegps_read_seek(AVFormatContext *s,

                            int stream_index, int64_t timestamp)

{

    int64_t pos_min, pos_max, pos;

    int64_t dts_min, dts_max, dts;

    timestamp = (timestamp * 90000) / AV_TIME_BASE;

#ifdef DEBUG_SEEK

    printf("read_seek: %d %0.3f\n", stream_index, timestamp / 90000.0);

#endif

    /* XXX: find stream_index by looking at the first PES packet found */

    if (stream_index < 0) {

        stream_index = find_stream_index(s);

        if (stream_index < 0)

            return -1;

    }

    pos_min = 0;

    dts_min = mpegps_read_dts(s, stream_index, &pos_min, 1);

    if (dts_min == AV_NOPTS_VALUE) {

        /* we can reach this case only if no PTS are present in

           the whole stream */

        return -1;

    }

    pos_max = url_filesize(url_fileno(&s->pb)) - 1;

    dts_max = mpegps_read_dts(s, stream_index, &pos_max, 0);

    while (pos_min <= pos_max) {

#ifdef DEBUG_SEEK

        printf("pos_min=0x%llx pos_max=0x%llx dts_min=%0.3f dts_max=%0.3f\n",

               pos_min, pos_max,

               dts_min / 90000.0, dts_max / 90000.0);

#endif

        if (timestamp <= dts_min) {

            pos = pos_min;

            goto found;

        } else if (timestamp >= dts_max) {

            pos = pos_max;

            goto found;

        } else {

            /* interpolate position (better than dichotomy) */

            pos = (int64_t)((double)(pos_max - pos_min) *

                            (double)(timestamp - dts_min) /

                            (double)(dts_max - dts_min)) + pos_min;

        }

#ifdef DEBUG_SEEK

        printf("pos=0x%llx\n", pos);

#endif

        /* read the next timestamp */

        dts = mpegps_read_dts(s, stream_index, &pos, 1);

        /* check if we are lucky */

        if (dts == AV_NOPTS_VALUE) {

            /* should never happen */

            pos = pos_min;

            goto found;

        } else if (timestamp == dts) {

            goto found;

        } else if (timestamp < dts) {

            pos_max = pos;

            dts_max = mpegps_read_dts(s, stream_index, &pos_max, 0);

            if (dts_max == AV_NOPTS_VALUE) {

                /* should never happen */

                break;

            } else if (timestamp >= dts_max) {

                pos = pos_max;

                goto found;

            }

        } else {

            pos_min = pos + 1;

            dts_min = mpegps_read_dts(s, stream_index, &pos_min, 1);

            if (dts_min == AV_NOPTS_VALUE) {

                /* should never happen */

                goto found;

            } else if (timestamp <= dts_min) {

                goto found;

            }

        }

    }

    pos = pos_min;

 found:

#ifdef DEBUG_SEEK

    pos_min = pos;

    dts_min = mpegps_read_dts(s, stream_index, &pos_min, 1);

    pos_min++;

    dts_max = mpegps_read_dts(s, stream_index, &pos_min, 1);

    printf("pos=0x%llx %0.3f<=%0.3f<=%0.3f\n",

           pos, dts_min / 90000.0, timestamp / 90000.0, dts_max / 90000.0);

#endif

    /* do the seek */

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

    return 0;

}


static void dxva2_uninit(AVCodecContext *s)

{

    InputStream  *ist = s->opaque;

    DXVA2Context *ctx = ist->hwaccel_ctx;

    ist->hwaccel_uninit        = NULL;

    ist->hwaccel_get_buffer    = NULL;

    ist->hwaccel_retrieve_data = NULL;

    if (ctx->decoder_service)

        IDirectXVideoDecoderService_Release(ctx->decoder_service);

    av_buffer_unref(&ctx->hw_frames_ctx);

    av_buffer_unref(&ctx->hw_device_ctx);

    av_frame_free(&ctx->tmp_frame);

    av_freep(&ist->hwaccel_ctx);

    av_freep(&s->hwaccel_context);

}


static av_cold int xvid_encode_close(AVCodecContext *avctx)

{

    struct xvid_context *x = avctx->priv_data;

    if (x->encoder_handle) {

        xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);

        x->encoder_handle = NULL;

    }

    av_frame_free(&avctx->coded_frame);

    av_freep(&avctx->extradata);

    if (x->twopassbuffer) {

        av_free(x->twopassbuffer);

        av_free(x->old_twopassbuffer);

    }

    av_free(x->twopassfile);

    av_free(x->intra_matrix);

    av_free(x->inter_matrix);

    return 0;

}


static void single_quote_string(void)

{

    int i;

    struct {

        const char *encoded;

        const char *decoded;

    } test_cases[] = {

        { "'hello world'", "hello world" },

        { "'the quick brown fox \\' jumped over the fence'",

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

        {}

    };

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

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded, NULL);

        str = qobject_to_qstring(obj);

        g_assert(str);

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

        QDECREF(str);

    }

}


static void calculate_code_lengths(uint8_t *lengths, uint32_t *counts)

{

    uint32_t nr_nodes, nr_heap, node1, node2;

    int      i, j;

    int32_t  k;

    /* Heap and node entries start from 1 */

    uint32_t weights[512];

    uint32_t heap[512];

    int32_t  parents[512];

    /* Set initial weights */

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

        weights[i + 1] = (counts[i] ? counts[i] : 1) << 8;

    nr_nodes = 256;

    nr_heap  = 0;

    heap[0]    = 0;

    weights[0] = 0;

    parents[0] = -2;

    /* Create initial nodes */

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

        parents[i] = -1;

        heap[++nr_heap] = i;

        up_heap(nr_heap, heap, weights);

    }

    /* Build the tree */

    while (nr_heap > 1) {

        node1   = heap[1];

        heap[1] = heap[nr_heap--];

        down_heap(nr_heap, heap, weights);

        node2   = heap[1];

        heap[1] = heap[nr_heap--];

        down_heap(nr_heap, heap, weights);

        nr_nodes++;

        parents[node1]    = parents[node2] = nr_nodes;

        weights[nr_nodes] = add_weights(weights[node1], weights[node2]);

        parents[nr_nodes] = -1;

        heap[++nr_heap] = nr_nodes;

        up_heap(nr_heap, heap, weights);

    }

    /* Generate lengths */

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

        j = 0;

        k = i;

        while (parents[k] >= 0) {

            k = parents[k];

            j++;

        }

        lengths[i - 1] = j;

    }

}


static int oma_read_seek(struct AVFormatContext *s,

                         int stream_index, int64_t timestamp, int flags)

{

    OMAContext *oc = s->priv_data;

    int err = ff_pcm_read_seek(s, stream_index, timestamp, flags);

    if (!oc->encrypted)

        return err;

    /* readjust IV for CBC */

    if (err || avio_tell(s->pb) < oc->content_start)

        goto wipe;

    if ((err = avio_seek(s->pb, -8, SEEK_CUR)) < 0)

        goto wipe;

    if ((err = avio_read(s->pb, oc->iv, 8)) < 8) {

        if (err >= 0)

            err = AVERROR_EOF;

        goto wipe;

    }

    return 0;

wipe:

    memset(oc->iv, 0, 8);

    return err;

}


int pci_piix3_xen_ide_unplug(DeviceState *dev)

{

    PCIIDEState *pci_ide;

    DriveInfo *di;

    int i = 0;

    pci_ide = PCI_IDE(dev);

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

        di = drive_get_by_index(IF_IDE, i);

        if (di != NULL && !di->media_cd) {

            BlockBackend *blk = blk_by_legacy_dinfo(di);

            DeviceState *ds = blk_get_attached_dev(blk);

            if (ds) {

                blk_detach_dev(blk, ds);

            }

            pci_ide->bus[di->bus].ifs[di->unit].blk = NULL;

            blk_unref(blk);

        }

    }

    qdev_reset_all(DEVICE(dev));

    return 0;

}


int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)

{

    const AVCodec *orig_codec = dest->codec;

    uint8_t *orig_priv_data = dest->priv_data;

    if (avcodec_is_open(dest)) { // check that the dest context is uninitialized

        av_log(dest, AV_LOG_ERROR,

               "Tried to copy AVCodecContext %p into already-initialized %p\n",

               src, dest);

        return AVERROR(EINVAL);

    }

    copy_context_reset(dest);

    memcpy(dest, src, sizeof(*dest));

    av_opt_copy(dest, src);

    dest->priv_data       = orig_priv_data;

    dest->codec           = orig_codec;

    if (orig_priv_data && src->codec && src->codec->priv_class &&

        dest->codec && dest->codec->priv_class)

        av_opt_copy(orig_priv_data, src->priv_data);

    /* set values specific to opened codecs back to their default state */

    dest->slice_offset    = NULL;

    dest->hwaccel         = NULL;

    dest->internal        = NULL;

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    dest->coded_frame     = NULL;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    /* reallocate values that should be allocated separately */

    dest->extradata       = NULL;

    dest->intra_matrix    = NULL;

    dest->inter_matrix    = NULL;

    dest->rc_override     = NULL;

    dest->subtitle_header = NULL;

    dest->hw_frames_ctx   = NULL;

#define alloc_and_copy_or_fail(obj, size, pad) \

    if (src->obj && size > 0) { \

        dest->obj = av_malloc(size + pad); \

        if (!dest->obj) \

            goto fail; \

        memcpy(dest->obj, src->obj, size); \

        if (pad) \

            memset(((uint8_t *) dest->obj) + size, 0, pad); \

    }

    alloc_and_copy_or_fail(extradata,    src->extradata_size,

                           AV_INPUT_BUFFER_PADDING_SIZE);

    dest->extradata_size  = src->extradata_size;

    alloc_and_copy_or_fail(intra_matrix, 64 * sizeof(int16_t), 0);

    alloc_and_copy_or_fail(inter_matrix, 64 * sizeof(int16_t), 0);

    alloc_and_copy_or_fail(rc_override,  src->rc_override_count * sizeof(*src->rc_override), 0);

    alloc_and_copy_or_fail(subtitle_header, src->subtitle_header_size, 1);

    av_assert0(dest->subtitle_header_size == src->subtitle_header_size);

#undef alloc_and_copy_or_fail

    if (src->hw_frames_ctx) {

        dest->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);

        if (!dest->hw_frames_ctx)

            goto fail;

    }

    return 0;

fail:

    copy_context_reset(dest);

    return AVERROR(ENOMEM);

}


static int ftp_open(URLContext *h, const char *url, int flags)

{

    char proto[10], path[MAX_URL_SIZE];

    int err;

    FTPContext *s = h->priv_data;

    av_dlog(h, "ftp protocol open\n");

    s->state = DISCONNECTED;

    s->filesize = -1;

    s->position = 0;

    av_url_split(proto, sizeof(proto),

                 s->credencials, sizeof(s->credencials),

                 s->hostname, sizeof(s->hostname),

                 &s->server_control_port,

                 path, sizeof(path),

                 url);

    if (s->server_control_port < 0 || s->server_control_port > 65535)

        s->server_control_port = 21;

    if ((err = ftp_connect_control_connection(h)) < 0)

        goto fail;

    if ((err = ftp_current_dir(s)) < 0)

        goto fail;

    av_strlcat(s->path, path, sizeof(s->path));

    if (ftp_restart(s, 0) < 0) {

        h->is_streamed = 1;

    } else {

        if (ftp_file_size(s) < 0 && flags & AVIO_FLAG_READ)

            h->is_streamed = 1;

        if (s->write_seekable != 1 && flags & AVIO_FLAG_WRITE)

            h->is_streamed = 1;

    }

    return 0;

  fail:

    av_log(h, AV_LOG_ERROR, "FTP open failed\n");

    ffurl_closep(&s->conn_control);

    ffurl_closep(&s->conn_data);

    return err;

}


static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)

{

    uint8_t r, g, b;

    r = ((v >> vs->server_red_shift) & vs->server_red_max) * (vs->client_red_max + 1) /

        (vs->server_red_max + 1);

    g = ((v >> vs->server_green_shift) & vs->server_green_max) * (vs->client_green_max + 1) /

        (vs->server_green_max + 1);

    b = ((v >> vs->server_blue_shift) & vs->server_blue_max) * (vs->client_blue_max + 1) /

        (vs->server_blue_max + 1);

    v = (r << vs->client_red_shift) |

        (g << vs->client_green_shift) |

        (b << vs->client_blue_shift);

    switch(vs->pix_bpp) {

    case 1:

        buf[0] = v;

        break;

    case 2:

        if (vs->pix_big_endian) {

            buf[0] = v >> 8;

            buf[1] = v;

        } else {

            buf[1] = v >> 8;

            buf[0] = v;

        }

        break;

    default:

    case 4:

        if (vs->pix_big_endian) {

            buf[0] = v >> 24;

            buf[1] = v >> 16;

            buf[2] = v >> 8;

            buf[3] = v;

        } else {

            buf[3] = v >> 24;

            buf[2] = v >> 16;

            buf[1] = v >> 8;

            buf[0] = v;

        }

        break;

    }

}


static int thread_execute(AVFilterContext *ctx, avfilter_action_func *func,

                          void *arg, int *ret, int nb_jobs)

{

    ThreadContext *c = ctx->graph->internal->thread;

    int dummy_ret;

    if (nb_jobs <= 0)

        return 0;

    pthread_mutex_lock(&c->current_job_lock);

    c->current_job = c->nb_threads;

    c->nb_jobs     = nb_jobs;

    c->ctx         = ctx;

    c->arg         = arg;

    c->func        = func;

    if (ret) {

        c->rets    = ret;

        c->nb_rets = nb_jobs;

    } else {

        c->rets    = &dummy_ret;

        c->nb_rets = 1;

    }

    c->current_execute++;

    pthread_cond_broadcast(&c->current_job_cond);

    slice_thread_park_workers(c);

    return 0;

}


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

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret, i;

    ASFPacket *asf_pkt = NULL;

    if (!asf->sub_left) {

        uint32_t off_len, media_len;

        uint8_t stream_num;

        stream_num = avio_r8(pb);

        asf->stream_index = stream_num & ASF_STREAM_NUM;

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

            if (asf->stream_index == asf->asf_st[i]->stream_index) {

                asf_pkt               = &asf->asf_st[i]->pkt;

                asf_pkt->stream_index = asf->asf_st[i]->index;

                break;

            }

        }

        if (!asf_pkt)

            return AVERROR_INVALIDDATA;

        if (stream_num >> 7)

            asf_pkt->flags |= AV_PKT_FLAG_KEY;

        READ_LEN(asf->prop_flags & ASF_PL_MASK_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_SIZE,

                 ASF_PL_FLAG_MEDIA_OBJECT_NUMBER_LENGTH_FIELD_, media_len);

        READ_LEN(asf->prop_flags & ASF_PL_MASK_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_SIZE,

                 ASF_PL_FLAG_OFFSET_INTO_MEDIA_OBJECT_LENGTH_FIELD_, off_len);

        READ_LEN(asf->prop_flags & ASF_PL_MASK_REPLICATED_DATA_LENGTH_FIELD_SIZE,

                 ASF_PL_FLAG_REPLICATED_DATA_LENGTH_FIELD_, asf->rep_data_len);

        if (asf_pkt->size_left && (asf_pkt->frame_num != media_len)) {

            av_log(s, AV_LOG_WARNING, "Unfinished frame will be ignored\n");

            reset_packet(asf_pkt);

        }

        asf_pkt->frame_num = media_len;

        asf->sub_dts = off_len;

        if (asf->nb_mult_left) {

            if ((ret = asf_read_multiple_payload(s, pkt, asf_pkt)) < 0)

                return ret;

        } else if (asf->rep_data_len == 1) {

            asf->sub_left = 1;

            asf->state    = READ_SINGLE;

            pkt->flags    = asf_pkt->flags;

            if ((ret = asf_read_subpayload(s, pkt, 1)) < 0)

                return ret;

        } else {

            if ((ret = asf_read_single_payload(s, pkt, asf_pkt)) < 0)

                return ret;

        }

    } else {

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

            if (asf->stream_index == asf->asf_st[i]->stream_index) {

                asf_pkt = &asf->asf_st[i]->pkt;

                break;

            }

        }

        if (!asf_pkt)

            return AVERROR_INVALIDDATA;

        pkt->flags         = asf_pkt->flags;

        pkt->dts           = asf_pkt->dts;

        pkt->stream_index  = asf->asf_st[i]->index;

        if ((ret = asf_read_subpayload(s, pkt, 0)) < 0) // read subpayload without its header

            return ret;

    }

    return 0;

}


static int set_expr(AVExpr **pexpr, const char *expr, void *log_ctx)

{

    int ret;

    AVExpr *old = NULL;

    if (*pexpr)

        old = *pexpr;

    ret = av_expr_parse(pexpr, expr, var_names,

                        NULL, NULL, NULL, NULL, 0, log_ctx);

    if (ret < 0) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Error when evaluating the expression '%s'\n", expr);

        *pexpr = old;

        return ret;

    }

    av_expr_free(old);

    return 0;

}


static void av_estimate_timings_from_pts(AVFormatContext *ic, offset_t old_offset)

{

    AVPacket pkt1, *pkt = &pkt1;

    AVStream *st;

    int read_size, i, ret;

    int64_t end_time;

    int64_t filesize, offset, duration;

    /* free previous packet */

    if (ic->cur_st && ic->cur_st->parser)

        av_free_packet(&ic->cur_pkt);

    ic->cur_st = NULL;

    /* flush packet queue */

    flush_packet_queue(ic);

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

        st = ic->streams[i];

        if (st->parser) {

            av_parser_close(st->parser);

            st->parser= NULL;

        }

    }

    /* we read the first packets to get the first PTS (not fully

       accurate, but it is enough now) */

    url_fseek(&ic->pb, 0, SEEK_SET);

    read_size = 0;

    for(;;) {

        if (read_size >= DURATION_MAX_READ_SIZE)

            break;

        /* if all info is available, we can stop */

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

            st = ic->streams[i];

            if (st->start_time == AV_NOPTS_VALUE)

                break;

        }

        if (i == ic->nb_streams)

            break;

        ret = av_read_packet(ic, pkt);

        if (ret != 0)

            break;

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if (pkt->pts != AV_NOPTS_VALUE) {

            if (st->start_time == AV_NOPTS_VALUE)

                st->start_time = pkt->pts;

        }

        av_free_packet(pkt);

    }

    /* estimate the end time (duration) */

    /* XXX: may need to support wrapping */

    filesize = ic->file_size;

    offset = filesize - DURATION_MAX_READ_SIZE;

    if (offset < 0)

        offset = 0;

    url_fseek(&ic->pb, offset, SEEK_SET);

    read_size = 0;

    for(;;) {

        if (read_size >= DURATION_MAX_READ_SIZE)

            break;

        /* if all info is available, we can stop */

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

            st = ic->streams[i];

            if (st->duration == AV_NOPTS_VALUE)

                break;

        }

        if (i == ic->nb_streams)

            break;

        ret = av_read_packet(ic, pkt);

        if (ret != 0)

            break;

        read_size += pkt->size;

        st = ic->streams[pkt->stream_index];

        if (pkt->pts != AV_NOPTS_VALUE) {

            end_time = pkt->pts;

            duration = end_time - st->start_time;

            if (duration > 0) {

                if (st->duration == AV_NOPTS_VALUE ||

                    st->duration < duration)

                    st->duration = duration;

            }

        }

        av_free_packet(pkt);

    }

    fill_all_stream_timings(ic);

    url_fseek(&ic->pb, old_offset, SEEK_SET);

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

        st= ic->streams[i];

        st->cur_dts= st->first_dts;

    }

}


static inline void RENAME(rgb32tobgr16)(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

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

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

	    ::"m"(red_16mask),"m"(green_16mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

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

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

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

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

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

		"psllq	$8, %%mm3\n\t"

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

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

		"psrlq	$5, %%mm1\n\t"

		"psrlq	$5, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$19, %%mm2\n\t"

		"psrlq	$19, %%mm5\n\t"

		"pand	%2, %%mm2\n\t"

		"pand	%2, %%mm5\n\t"

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

		"por	%%mm4, %%mm3\n\t"

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

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

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

		:"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

		d += 4;

		s += 16;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int src= *((uint32_t*)s)++;

		*d++ = ((src&0xF8)<<8) + ((src&0xFC00)>>5) + ((src&0xF80000)>>19);

	}

}


static int dv_read_header(AVFormatContext *s,

                          AVFormatParameters *ap)

{

    RawDVContext *c = s->priv_data;

    c->dv_demux = dv_init_demux(s);

    return c->dv_demux ? 0 : -1;

}


static void vfio_map_bar(VFIOPCIDevice *vdev, int nr)

{

    VFIOBAR *bar = &vdev->bars[nr];

    uint64_t size = bar->region.size;

    char name[64];

    uint32_t pci_bar;

    uint8_t type;

    int ret;

    /* Skip both unimplemented BARs and the upper half of 64bit BARS. */

    if (!size) {

        return;

    }

    snprintf(name, sizeof(name), "VFIO %04x:%02x:%02x.%x BAR %d",

             vdev->host.domain, vdev->host.bus, vdev->host.slot,

             vdev->host.function, nr);

    /* Determine what type of BAR this is for registration */

    ret = pread(vdev->vbasedev.fd, &pci_bar, sizeof(pci_bar),

                vdev->config_offset + PCI_BASE_ADDRESS_0 + (4 * nr));

    if (ret != sizeof(pci_bar)) {

        error_report("vfio: Failed to read BAR %d (%m)", nr);

        return;

    }

    pci_bar = le32_to_cpu(pci_bar);

    bar->ioport = (pci_bar & PCI_BASE_ADDRESS_SPACE_IO);

    bar->mem64 = bar->ioport ? 0 : (pci_bar & PCI_BASE_ADDRESS_MEM_TYPE_64);

    type = pci_bar & (bar->ioport ? ~PCI_BASE_ADDRESS_IO_MASK :

                                    ~PCI_BASE_ADDRESS_MEM_MASK);

    /* A "slow" read/write mapping underlies all BARs */

    memory_region_init_io(&bar->region.mem, OBJECT(vdev), &vfio_region_ops,

                          bar, name, size);

    pci_register_bar(&vdev->pdev, nr, type, &bar->region.mem);

    /*

     * We can't mmap areas overlapping the MSIX vector table, so we

     * potentially insert a direct-mapped subregion before and after it.

     */

    if (vdev->msix && vdev->msix->table_bar == nr) {

        size = vdev->msix->table_offset & qemu_host_page_mask;

    }

    strncat(name, " mmap", sizeof(name) - strlen(name) - 1);

    if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,

                      &bar->region.mmap_mem, &bar->region.mmap,

                      size, 0, name)) {

        error_report("%s unsupported. Performance may be slow", name);

    }

    if (vdev->msix && vdev->msix->table_bar == nr) {

        uint64_t start;

        start = HOST_PAGE_ALIGN(vdev->msix->table_offset +

                                (vdev->msix->entries * PCI_MSIX_ENTRY_SIZE));

        size = start < bar->region.size ? bar->region.size - start : 0;

        strncat(name, " msix-hi", sizeof(name) - strlen(name) - 1);

        /* VFIOMSIXInfo contains another MemoryRegion for this mapping */

        if (vfio_mmap_region(OBJECT(vdev), &bar->region, &bar->region.mem,

                          &vdev->msix->mmap_mem,

                          &vdev->msix->mmap, size, start, name)) {

            error_report("%s unsupported. Performance may be slow", name);

        }

    }

    vfio_bar_quirk_setup(vdev, nr);

}


static void cpu_common_reset(CPUState *cpu)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int i;

    if (qemu_loglevel_mask(CPU_LOG_RESET)) {

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

        log_cpu_state(cpu, cc->reset_dump_flags);

    }

    cpu->interrupt_request = 0;

    cpu->halted = 0;

    cpu->mem_io_pc = 0;

    cpu->mem_io_vaddr = 0;

    cpu->icount_extra = 0;

    cpu->icount_decr.u32 = 0;

    cpu->can_do_io = 1;

    cpu->exception_index = -1;

    cpu->crash_occurred = false;

    if (tcg_enabled()) {

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

            atomic_set(&cpu->tb_jmp_cache[i], NULL);

        }

#ifdef CONFIG_SOFTMMU

        tlb_flush(cpu, 0);

#endif

    }

}


static void string_output_append_range(StringOutputVisitor *sov,

                                       int64_t s, int64_t e)

{

    Range *r = g_malloc0(sizeof(*r));

    r->begin = s;

    r->end = e + 1;

    sov->ranges = g_list_insert_sorted_merged(sov->ranges, r, range_compare);

}


int ff_rtsp_connect(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    char host[1024], path[1024], tcpname[1024], cmd[2048], auth[128];

    char *option_list, *option, *filename;

    URLContext *rtsp_hd, *rtsp_hd_out;

    int port, err, tcp_fd;

    RTSPMessageHeader reply1 = {}, *reply = &reply1;

    int lower_transport_mask = 0;

    char real_challenge[64];

    struct sockaddr_storage peer;

    socklen_t peer_len = sizeof(peer);

    if (!ff_network_init())

        return AVERROR(EIO);

redirect:

    rt->control_transport = RTSP_MODE_PLAIN;

    /* extract hostname and port */

    ff_url_split(NULL, 0, auth, sizeof(auth),

                 host, sizeof(host), &port, path, sizeof(path), s->filename);

    if (*auth) {

        av_strlcpy(rt->auth, auth, sizeof(rt->auth));

    }

    if (port < 0)

        port = RTSP_DEFAULT_PORT;

    /* search for options */

    option_list = strrchr(path, '?');

    if (option_list) {

        /* Strip out the RTSP specific options, write out the rest of

         * the options back into the same string. */

        filename = option_list;

        while (option_list) {

            /* move the option pointer */

            option = ++option_list;

            option_list = strchr(option_list, '&');

            if (option_list)

                *option_list = 0;

            /* handle the options */

            if (!strcmp(option, "udp")) {

                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP);

            } else if (!strcmp(option, "multicast")) {

                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_UDP_MULTICAST);

            } else if (!strcmp(option, "tcp")) {

                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);

            } else if(!strcmp(option, "http")) {

                lower_transport_mask |= (1<< RTSP_LOWER_TRANSPORT_TCP);

                rt->control_transport = RTSP_MODE_TUNNEL;

            } else {

                /* Write options back into the buffer, using memmove instead

                 * of strcpy since the strings may overlap. */

                int len = strlen(option);

                memmove(++filename, option, len);

                filename += len;

                if (option_list) *filename = '&';

            }

        }

        *filename = 0;

    }

    if (!lower_transport_mask)

        lower_transport_mask = (1 << RTSP_LOWER_TRANSPORT_NB) - 1;

    if (s->oformat) {

        /* Only UDP or TCP - UDP multicast isn't supported. */

        lower_transport_mask &= (1 << RTSP_LOWER_TRANSPORT_UDP) |

                                (1 << RTSP_LOWER_TRANSPORT_TCP);

        if (!lower_transport_mask || rt->control_transport == RTSP_MODE_TUNNEL) {

            av_log(s, AV_LOG_ERROR, "Unsupported lower transport method, "

                                    "only UDP and TCP are supported for output.\n");

            err = AVERROR(EINVAL);

            goto fail;

        }

    }

    /* Construct the URI used in request; this is similar to s->filename,

     * but with authentication credentials removed and RTSP specific options

     * stripped out. */

    ff_url_join(rt->control_uri, sizeof(rt->control_uri), "rtsp", NULL,

                host, port, "%s", path);

    if (rt->control_transport == RTSP_MODE_TUNNEL) {

        /* set up initial handshake for tunneling */

        char httpname[1024];

        char sessioncookie[17];

        char headers[1024];

        ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, "%s", path);

        snprintf(sessioncookie, sizeof(sessioncookie), "%08x%08x",

                 av_get_random_seed(), av_get_random_seed());

        /* GET requests */

        if (url_open(&rtsp_hd, httpname, URL_RDONLY) < 0) {

            err = AVERROR(EIO);

            goto fail;

        }

        /* generate GET headers */

        snprintf(headers, sizeof(headers),

                 "x-sessioncookie: %s\r\n"

                 "Accept: application/x-rtsp-tunnelled\r\n"

                 "Pragma: no-cache\r\n"

                 "Cache-Control: no-cache\r\n",

                 sessioncookie);

        ff_http_set_headers(rtsp_hd, headers);

        /* complete the connection */

        if (url_read(rtsp_hd, NULL, 0)) {

            err = AVERROR(EIO);

            goto fail;

        }

        /* POST requests */

        if (url_open(&rtsp_hd_out, httpname, URL_WRONLY) < 0 ) {

            err = AVERROR(EIO);

            goto fail;

        }

        /* generate POST headers */

        snprintf(headers, sizeof(headers),

                 "x-sessioncookie: %s\r\n"

                 "Content-Type: application/x-rtsp-tunnelled\r\n"

                 "Pragma: no-cache\r\n"

                 "Cache-Control: no-cache\r\n"

                 "Content-Length: 32767\r\n"

                 "Expires: Sun, 9 Jan 1972 00:00:00 GMT\r\n",

                 sessioncookie);

        ff_http_set_headers(rtsp_hd_out, headers);

        ff_http_set_chunked_transfer_encoding(rtsp_hd_out, 0);

    } else {

        /* open the tcp connection */

        ff_url_join(tcpname, sizeof(tcpname), "tcp", NULL, host, port, NULL);

        if (url_open(&rtsp_hd, tcpname, URL_RDWR) < 0) {

            err = AVERROR(EIO);

            goto fail;

        }

        rtsp_hd_out = rtsp_hd;

    }

    rt->rtsp_hd = rtsp_hd;

    rt->rtsp_hd_out = rtsp_hd_out;

    rt->seq = 0;

    tcp_fd = url_get_file_handle(rtsp_hd);

    if (!getpeername(tcp_fd, (struct sockaddr*) &peer, &peer_len)) {

        getnameinfo((struct sockaddr*) &peer, peer_len, host, sizeof(host),

                    NULL, 0, NI_NUMERICHOST);

    }

    /* request options supported by the server; this also detects server

     * type */

    for (rt->server_type = RTSP_SERVER_RTP;;) {

        cmd[0] = 0;

        if (rt->server_type == RTSP_SERVER_REAL)

            av_strlcat(cmd,

                       /**

                        * The following entries are required for proper

                        * streaming from a Realmedia server. They are

                        * interdependent in some way although we currently

                        * don't quite understand how. Values were copied

                        * from mplayer SVN r23589.

                        * @param CompanyID is a 16-byte ID in base64

                        * @param ClientChallenge is a 16-byte ID in hex

                        */

                       "ClientChallenge: 9e26d33f2984236010ef6253fb1887f7\r\n"

                       "PlayerStarttime: [28/03/2003:22:50:23 00:00]\r\n"

                       "CompanyID: KnKV4M4I/B2FjJ1TToLycw==\r\n"

                       "GUID: 00000000-0000-0000-0000-000000000000\r\n",

                       sizeof(cmd));

        ff_rtsp_send_cmd(s, "OPTIONS", rt->control_uri, cmd, reply, NULL);

        if (reply->status_code != RTSP_STATUS_OK) {

            err = AVERROR_INVALIDDATA;

            goto fail;

        }

        /* detect server type if not standard-compliant RTP */

        if (rt->server_type != RTSP_SERVER_REAL && reply->real_challenge[0]) {

            rt->server_type = RTSP_SERVER_REAL;

            continue;

        } else if (!strncasecmp(reply->server, "WMServer/", 9)) {

            rt->server_type = RTSP_SERVER_WMS;

        } else if (rt->server_type == RTSP_SERVER_REAL)

            strcpy(real_challenge, reply->real_challenge);

        break;

    }

    if (s->iformat)

        err = rtsp_setup_input_streams(s, reply);

    else

        err = rtsp_setup_output_streams(s, host);

    if (err)

        goto fail;

    do {

        int lower_transport = ff_log2_tab[lower_transport_mask &

                                  ~(lower_transport_mask - 1)];

        err = make_setup_request(s, host, port, lower_transport,

                                 rt->server_type == RTSP_SERVER_REAL ?

                                     real_challenge : NULL);

        if (err < 0)

            goto fail;

        lower_transport_mask &= ~(1 << lower_transport);

        if (lower_transport_mask == 0 && err == 1) {

            err = FF_NETERROR(EPROTONOSUPPORT);

            goto fail;

        }

    } while (err);

    rt->state = RTSP_STATE_IDLE;

    rt->seek_timestamp = 0; /* default is to start stream at position zero */

    return 0;

 fail:

    ff_rtsp_close_streams(s);

    ff_rtsp_close_connections(s);

    if (reply->status_code >=300 && reply->status_code < 400 && s->iformat) {

        av_strlcpy(s->filename, reply->location, sizeof(s->filename));

        av_log(s, AV_LOG_INFO, "Status %d: Redirecting to %s\n",

               reply->status_code,

               s->filename);

        goto redirect;

    }

    ff_network_close();

    return err;

}


static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts)

{

    ASFContext *asf = s->priv_data;

    AVStream *st;

    AVPacket pkt1, *pkt;

    int block_align;

    int64_t pos;

    int64_t pos_min, pos_max, pts_min, pts_max, cur_pts;

    pkt = &pkt1;

    // Validate pts

    if (pts < 0)

	pts = 0;

    if (stream_index == -1)

        stream_index= av_find_default_stream_index(s);

    st = s->streams[stream_index];

    // ASF files have fixed block sizes, store this to determine offset

    block_align = asf->packet_size;

    if (block_align <= 0)

        return -1;

    pos_min = 0;

    pts_min = asf_read_pts(s, &pos_min, stream_index);

    if (pts_min == AV_NOPTS_VALUE) return -1;

    pos_max = asf_align(s, url_filesize(url_fileno(&s->pb)) - 1 - s->data_offset); //FIXME wrong

    pts_max = pts_min + s->duration;

    while (pos_min <= pos_max) {

        if (pts <= pts_min) {

            pos = pos_min;

            goto found;

        } else if (pts >= pts_max) {

            pos = pos_max;

            goto found;

        } else {

            // interpolate position (better than dichotomy)

            pos = (int64_t)((double)(pos_max - pos_min) *

                            (double)(pts - pts_min) /

                            (double)(pts_max - pts_min)) + pos_min;

            pos= asf_align(s, pos);

        }

        // read the next timestamp

    	cur_pts = asf_read_pts(s, &pos, stream_index);

        /* check if we are lucky */

        if (pts == cur_pts) {

            goto found;

        } else if (cur_pts == AV_NOPTS_VALUE) {

	    return -1;

        } else if (pts < cur_pts) {

            pos_max = pos;

	    pts_max = asf_read_pts(s, &pos_max, stream_index); //FIXME wrong, must do backward search, or change this somehow

            if (pts >= pts_max) {

                pos = pos_max;

                goto found;

            }

        } else {

            pos_min = pos + asf->packet_size;

	    pts_min = asf_read_pts(s, &pos_min, stream_index);

            if (pts <= pts_min) {

                goto found;

            }

        }

    }

    pos = pos_min;

found:

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

    asf_reset_header(s);

    return 0;

}


static void decode_src_opc(CPUTriCoreState *env, DisasContext *ctx, int op1)

{

    int r1;

    int32_t const4;

    TCGv temp, temp2;

    r1 = MASK_OP_SRC_S1D(ctx->opcode);

    const4 = MASK_OP_SRC_CONST4_SEXT(ctx->opcode);

    switch (op1) {

    case OPC1_16_SRC_ADD:

        gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);

        break;

    case OPC1_16_SRC_ADD_A15:

        gen_addi_d(cpu_gpr_d[r1], cpu_gpr_d[15], const4);

        break;

    case OPC1_16_SRC_ADD_15A:

        gen_addi_d(cpu_gpr_d[15], cpu_gpr_d[r1], const4);

        break;

    case OPC1_16_SRC_ADD_A:

        tcg_gen_addi_tl(cpu_gpr_a[r1], cpu_gpr_a[r1], const4);

        break;

    case OPC1_16_SRC_CADD:

        gen_condi_add(TCG_COND_NE, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],

                      cpu_gpr_d[15]);

        break;

    case OPC1_16_SRC_CADDN:

        gen_condi_add(TCG_COND_EQ, cpu_gpr_d[r1], const4, cpu_gpr_d[r1],

                      cpu_gpr_d[15]);

        break;

    case OPC1_16_SRC_CMOV:

        temp = tcg_const_tl(0);

        temp2 = tcg_const_tl(const4);

        tcg_gen_movcond_tl(TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15], temp,

                           temp2, cpu_gpr_d[r1]);

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

        break;

    case OPC1_16_SRC_CMOVN:

        temp = tcg_const_tl(0);

        temp2 = tcg_const_tl(const4);

        tcg_gen_movcond_tl(TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15], temp,

                           temp2, cpu_gpr_d[r1]);

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

        break;

    case OPC1_16_SRC_EQ:

        tcg_gen_setcondi_tl(TCG_COND_EQ, cpu_gpr_d[15], cpu_gpr_d[r1],

                            const4);

        break;

    case OPC1_16_SRC_LT:

        tcg_gen_setcondi_tl(TCG_COND_LT, cpu_gpr_d[15], cpu_gpr_d[r1],

                            const4);

        break;

    case OPC1_16_SRC_MOV:

        tcg_gen_movi_tl(cpu_gpr_d[r1], const4);

        break;

    case OPC1_16_SRC_MOV_A:

        const4 = MASK_OP_SRC_CONST4(ctx->opcode);

        tcg_gen_movi_tl(cpu_gpr_a[r1], const4);

        break;

    case OPC1_16_SRC_MOV_E:

        if (tricore_feature(env, TRICORE_FEATURE_16)) {

            tcg_gen_movi_tl(cpu_gpr_d[r1], const4);

            tcg_gen_sari_tl(cpu_gpr_d[r1+1], cpu_gpr_d[r1], 31);

        } /* TODO: else raise illegal opcode trap */

        break;

    case OPC1_16_SRC_SH:

        gen_shi(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);

        break;

    case OPC1_16_SRC_SHA:

        gen_shaci(cpu_gpr_d[r1], cpu_gpr_d[r1], const4);

        break;

    }

}


int ffio_read_indirect(AVIOContext *s, unsigned char *buf, int size, unsigned char **data)

{

    if (s->buf_end - s->buf_ptr >= size && !s->write_flag) {

        *data = s->buf_ptr;

        s->buf_ptr += size;

        return size;

    } else {

        *data = buf;

        return avio_read(s, buf, size);

    }

}