static void v9fs_symlink(void *opaque)
{
    V9fsPDU *pdu = opaque;
    V9fsString name;
    V9fsString symname;
    V9fsFidState *dfidp;
    V9fsQID qid;
    struct stat stbuf;
    int32_t dfid;
    int err = 0;
    gid_t gid;
    size_t offset = 7;
    v9fs_string_init(&name);
    v9fs_string_init(&symname);
    err = pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid);
    if (err < 0) {
    trace_v9fs_symlink(pdu->tag, pdu->id, dfid, name.data, symname.data, gid);
    if (name_is_illegal(name.data)) {
        err = -ENOENT;
    dfidp = get_fid(pdu, dfid);
    if (dfidp == NULL) {
        err = -EINVAL;
    err = v9fs_co_symlink(pdu, dfidp, &name, symname.data, gid, &stbuf);
    if (err < 0) {
        goto out;
    stat_to_qid(&stbuf, &qid);
    err =  pdu_marshal(pdu, offset, "Q", &qid);
    if (err < 0) {
        goto out;
    err += offset;
    trace_v9fs_symlink_return(pdu->tag, pdu->id,
                              qid.type, qid.version, qid.path);
out:
    put_fid(pdu, dfidp);
out_nofid:
    pdu_complete(pdu, err);
    v9fs_string_free(&name);
    v9fs_string_free(&symname);


void ff_tls_init(void)

{

    avpriv_lock_avformat();

#if CONFIG_OPENSSL

    if (!openssl_init) {

        SSL_library_init();

        SSL_load_error_strings();

#if HAVE_THREADS

        if (!CRYPTO_get_locking_callback()) {

            int i;

            openssl_mutexes = av_malloc_array(sizeof(pthread_mutex_t), CRYPTO_num_locks());

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

                pthread_mutex_init(&openssl_mutexes[i], NULL);

            CRYPTO_set_locking_callback(openssl_lock);

#if !defined(WIN32) && OPENSSL_VERSION_NUMBER < 0x10000000

            CRYPTO_set_id_callback(openssl_thread_id);

#endif

        }

#endif

    }

    openssl_init++;

#endif

#if CONFIG_GNUTLS

#if HAVE_THREADS && GNUTLS_VERSION_NUMBER < 0x020b00

    if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0)

        gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

#endif

    gnutls_global_init();

#endif

    avpriv_unlock_avformat();

}


uint64_t helper_cvttq(CPUAlphaState *env, uint64_t a)

{

    return inline_cvttq(env, a, FP_STATUS.float_rounding_mode, 1);

}


void ppc_store_msr_32 (CPUPPCState *env, uint32_t value)

{

    do_store_msr(env,

                 (do_load_msr(env) & ~0xFFFFFFFFULL) | (value & 0xFFFFFFFF));

}


static void usb_serial_read(void *opaque, const uint8_t *buf, int size)

{

    USBSerialState *s = opaque;

    int first_size = RECV_BUF - s->recv_ptr;

    if (first_size > size)

        first_size = size;

    memcpy(s->recv_buf + s->recv_ptr + s->recv_used, buf, first_size);

    if (size > first_size)

        memcpy(s->recv_buf, buf + first_size, size - first_size);

    s->recv_used += size;

}


struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,

                unsigned long sdram_size,

                const char *core)

{

    struct omap_mpu_state_s *s = g_new0(struct omap_mpu_state_s, 1);

    qemu_irq dma_irqs[4];

    DriveInfo *dinfo;

    int i;

    SysBusDevice *busdev;

    struct omap_target_agent_s *ta;

    /* Core */

    s->mpu_model = omap2420;

    s->cpu = cpu_arm_init(core ?: "arm1136-r2");

    if (s->cpu == NULL) {

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

        exit(1);

    }

    s->sdram_size = sdram_size;

    s->sram_size = OMAP242X_SRAM_SIZE;

    s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0);

    /* Clocks */

    omap_clk_init(s);

    /* Memory-mapped stuff */

    memory_region_allocate_system_memory(&s->sdram, NULL, "omap2.dram",

                                         s->sdram_size);

    memory_region_add_subregion(sysmem, OMAP2_Q2_BASE, &s->sdram);

    memory_region_init_ram(&s->sram, NULL, "omap2.sram", s->sram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->sram);

    memory_region_add_subregion(sysmem, OMAP2_SRAM_BASE, &s->sram);

    s->l4 = omap_l4_init(sysmem, OMAP2_L4_BASE, 54);

    /* Actually mapped at any 2K boundary in the ARM11 private-peripheral if */

    s->ih[0] = qdev_create(NULL, "omap2-intc");

    qdev_prop_set_uint8(s->ih[0], "revision", 0x21);

    qdev_prop_set_ptr(s->ih[0], "fclk", omap_findclk(s, "mpu_intc_fclk"));

    qdev_prop_set_ptr(s->ih[0], "iclk", omap_findclk(s, "mpu_intc_iclk"));

    qdev_init_nofail(s->ih[0]);

    busdev = SYS_BUS_DEVICE(s->ih[0]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_IRQ));

    sysbus_connect_irq(busdev, 1,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_FIQ));

    sysbus_mmio_map(busdev, 0, 0x480fe000);

    s->prcm = omap_prcm_init(omap_l4tao(s->l4, 3),

                             qdev_get_gpio_in(s->ih[0],

                                              OMAP_INT_24XX_PRCM_MPU_IRQ),

                             NULL, NULL, s);

    s->sysc = omap_sysctl_init(omap_l4tao(s->l4, 1),

                    omap_findclk(s, "omapctrl_iclk"), s);

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

        dma_irqs[i] = qdev_get_gpio_in(s->ih[omap2_dma_irq_map[i].ih],

                                       omap2_dma_irq_map[i].intr);

    }

    s->dma = omap_dma4_init(0x48056000, dma_irqs, sysmem, s, 256, 32,

                    omap_findclk(s, "sdma_iclk"),

                    omap_findclk(s, "sdma_fclk"));

    s->port->addr_valid = omap2_validate_addr;

    /* Register SDRAM and SRAM ports for fast DMA transfers.  */

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sdram),

                         OMAP2_Q2_BASE, s->sdram_size);

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sram),

                         OMAP2_SRAM_BASE, s->sram_size);

    s->uart[0] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 19),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART1_IRQ),

                    omap_findclk(s, "uart1_fclk"),

                    omap_findclk(s, "uart1_iclk"),

                    s->drq[OMAP24XX_DMA_UART1_TX],

                    s->drq[OMAP24XX_DMA_UART1_RX],

                    "uart1",

                    serial_hds[0]);

    s->uart[1] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 20),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART2_IRQ),

                    omap_findclk(s, "uart2_fclk"),

                    omap_findclk(s, "uart2_iclk"),

                    s->drq[OMAP24XX_DMA_UART2_TX],

                    s->drq[OMAP24XX_DMA_UART2_RX],

                    "uart2",

                    serial_hds[0] ? serial_hds[1] : NULL);

    s->uart[2] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 21),

                                 qdev_get_gpio_in(s->ih[0],

                                                  OMAP_INT_24XX_UART3_IRQ),

                    omap_findclk(s, "uart3_fclk"),

                    omap_findclk(s, "uart3_iclk"),

                    s->drq[OMAP24XX_DMA_UART3_TX],

                    s->drq[OMAP24XX_DMA_UART3_RX],

                    "uart3",

                    serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);

    s->gptimer[0] = omap_gp_timer_init(omap_l4ta(s->l4, 7),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER1),

                    omap_findclk(s, "wu_gpt1_clk"),

                    omap_findclk(s, "wu_l4_iclk"));

    s->gptimer[1] = omap_gp_timer_init(omap_l4ta(s->l4, 8),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER2),

                    omap_findclk(s, "core_gpt2_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[2] = omap_gp_timer_init(omap_l4ta(s->l4, 22),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER3),

                    omap_findclk(s, "core_gpt3_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[3] = omap_gp_timer_init(omap_l4ta(s->l4, 23),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER4),

                    omap_findclk(s, "core_gpt4_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[4] = omap_gp_timer_init(omap_l4ta(s->l4, 24),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER5),

                    omap_findclk(s, "core_gpt5_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[5] = omap_gp_timer_init(omap_l4ta(s->l4, 25),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER6),

                    omap_findclk(s, "core_gpt6_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[6] = omap_gp_timer_init(omap_l4ta(s->l4, 26),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER7),

                    omap_findclk(s, "core_gpt7_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[7] = omap_gp_timer_init(omap_l4ta(s->l4, 27),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER8),

                    omap_findclk(s, "core_gpt8_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[8] = omap_gp_timer_init(omap_l4ta(s->l4, 28),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER9),

                    omap_findclk(s, "core_gpt9_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[9] = omap_gp_timer_init(omap_l4ta(s->l4, 29),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER10),

                    omap_findclk(s, "core_gpt10_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[10] = omap_gp_timer_init(omap_l4ta(s->l4, 30),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER11),

                    omap_findclk(s, "core_gpt11_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    s->gptimer[11] = omap_gp_timer_init(omap_l4ta(s->l4, 31),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER12),

                    omap_findclk(s, "core_gpt12_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    omap_tap_init(omap_l4ta(s->l4, 2), s);

    s->synctimer = omap_synctimer_init(omap_l4tao(s->l4, 2), s,

                    omap_findclk(s, "clk32-kHz"),

                    omap_findclk(s, "core_l4_iclk"));

    s->i2c[0] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[0], "revision", 0x34);

    qdev_prop_set_ptr(s->i2c[0], "iclk", omap_findclk(s, "i2c1.iclk"));

    qdev_prop_set_ptr(s->i2c[0], "fclk", omap_findclk(s, "i2c1.fclk"));

    qdev_init_nofail(s->i2c[0]);

    busdev = SYS_BUS_DEVICE(s->i2c[0]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C1_IRQ));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C1_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C1_RX]);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 5), 0));

    s->i2c[1] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[1], "revision", 0x34);

    qdev_prop_set_ptr(s->i2c[1], "iclk", omap_findclk(s, "i2c2.iclk"));

    qdev_prop_set_ptr(s->i2c[1], "fclk", omap_findclk(s, "i2c2.fclk"));

    qdev_init_nofail(s->i2c[1]);

    busdev = SYS_BUS_DEVICE(s->i2c[1]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C2_IRQ));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C2_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C2_RX]);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 6), 0));

    s->gpio = qdev_create(NULL, "omap2-gpio");

    qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);

    qdev_prop_set_ptr(s->gpio, "iclk", omap_findclk(s, "gpio_iclk"));

    qdev_prop_set_ptr(s->gpio, "fclk0", omap_findclk(s, "gpio1_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk1", omap_findclk(s, "gpio2_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk2", omap_findclk(s, "gpio3_dbclk"));

    qdev_prop_set_ptr(s->gpio, "fclk3", omap_findclk(s, "gpio4_dbclk"));

    if (s->mpu_model == omap2430) {

        qdev_prop_set_ptr(s->gpio, "fclk4", omap_findclk(s, "gpio5_dbclk"));

    }

    qdev_init_nofail(s->gpio);

    busdev = SYS_BUS_DEVICE(s->gpio);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK1));

    sysbus_connect_irq(busdev, 3,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK2));

    sysbus_connect_irq(busdev, 6,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK3));

    sysbus_connect_irq(busdev, 9,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK4));

    if (s->mpu_model == omap2430) {

        sysbus_connect_irq(busdev, 12,

                           qdev_get_gpio_in(s->ih[0],

                                            OMAP_INT_243X_GPIO_BANK5));

    }

    ta = omap_l4ta(s->l4, 3);

    sysbus_mmio_map(busdev, 0, omap_l4_region_base(ta, 1));

    sysbus_mmio_map(busdev, 1, omap_l4_region_base(ta, 0));

    sysbus_mmio_map(busdev, 2, omap_l4_region_base(ta, 2));

    sysbus_mmio_map(busdev, 3, omap_l4_region_base(ta, 4));

    sysbus_mmio_map(busdev, 4, omap_l4_region_base(ta, 5));

    s->sdrc = omap_sdrc_init(sysmem, 0x68009000);

    s->gpmc = omap_gpmc_init(s, 0x6800a000,

                             qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPMC_IRQ),

                             s->drq[OMAP24XX_DMA_GPMC]);

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9),

                    blk_by_legacy_dinfo(dinfo),

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ),

                    &s->drq[OMAP24XX_DMA_MMC1_TX],

                    omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));

    s->mcspi[0] = omap_mcspi_init(omap_l4ta(s->l4, 35), 4,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI1_IRQ),

                    &s->drq[OMAP24XX_DMA_SPI1_TX0],

                    omap_findclk(s, "spi1_fclk"),

                    omap_findclk(s, "spi1_iclk"));

    s->mcspi[1] = omap_mcspi_init(omap_l4ta(s->l4, 36), 2,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI2_IRQ),

                    &s->drq[OMAP24XX_DMA_SPI2_TX0],

                    omap_findclk(s, "spi2_fclk"),

                    omap_findclk(s, "spi2_iclk"));

    s->dss = omap_dss_init(omap_l4ta(s->l4, 10), sysmem, 0x68000800,

                    /* XXX wire M_IRQ_25, D_L2_IRQ_30 and I_IRQ_13 together */

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_DSS_IRQ),

                           s->drq[OMAP24XX_DMA_DSS],

                    omap_findclk(s, "dss_clk1"), omap_findclk(s, "dss_clk2"),

                    omap_findclk(s, "dss_54m_clk"),

                    omap_findclk(s, "dss_l3_iclk"),

                    omap_findclk(s, "dss_l4_iclk"));

    omap_sti_init(omap_l4ta(s->l4, 18), sysmem, 0x54000000,

                  qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_STI),

                  omap_findclk(s, "emul_ck"),

                    serial_hds[0] && serial_hds[1] && serial_hds[2] ?

                    serial_hds[3] : NULL);

    s->eac = omap_eac_init(omap_l4ta(s->l4, 32),

                           qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_EAC_IRQ),

                    /* Ten consecutive lines */

                    &s->drq[OMAP24XX_DMA_EAC_AC_RD],

                    omap_findclk(s, "func_96m_clk"),

                    omap_findclk(s, "core_l4_iclk"));

    /* All register mappings (includin those not currenlty implemented):

     * SystemControlMod	48000000 - 48000fff

     * SystemControlL4	48001000 - 48001fff

     * 32kHz Timer Mod	48004000 - 48004fff

     * 32kHz Timer L4	48005000 - 48005fff

     * PRCM ModA	48008000 - 480087ff

     * PRCM ModB	48008800 - 48008fff

     * PRCM L4		48009000 - 48009fff

     * TEST-BCM Mod	48012000 - 48012fff

     * TEST-BCM L4	48013000 - 48013fff

     * TEST-TAP Mod	48014000 - 48014fff

     * TEST-TAP L4	48015000 - 48015fff

     * GPIO1 Mod	48018000 - 48018fff

     * GPIO Top		48019000 - 48019fff

     * GPIO2 Mod	4801a000 - 4801afff

     * GPIO L4		4801b000 - 4801bfff

     * GPIO3 Mod	4801c000 - 4801cfff

     * GPIO4 Mod	4801e000 - 4801efff

     * WDTIMER1 Mod	48020000 - 48010fff

     * WDTIMER Top	48021000 - 48011fff

     * WDTIMER2 Mod	48022000 - 48012fff

     * WDTIMER L4	48023000 - 48013fff

     * WDTIMER3 Mod	48024000 - 48014fff

     * WDTIMER3 L4	48025000 - 48015fff

     * WDTIMER4 Mod	48026000 - 48016fff

     * WDTIMER4 L4	48027000 - 48017fff

     * GPTIMER1 Mod	48028000 - 48018fff

     * GPTIMER1 L4	48029000 - 48019fff

     * GPTIMER2 Mod	4802a000 - 4801afff

     * GPTIMER2 L4	4802b000 - 4801bfff

     * L4-Config AP	48040000 - 480407ff

     * L4-Config IP	48040800 - 48040fff

     * L4-Config LA	48041000 - 48041fff

     * ARM11ETB Mod	48048000 - 48049fff

     * ARM11ETB L4	4804a000 - 4804afff

     * DISPLAY Top	48050000 - 480503ff

     * DISPLAY DISPC	48050400 - 480507ff

     * DISPLAY RFBI	48050800 - 48050bff

     * DISPLAY VENC	48050c00 - 48050fff

     * DISPLAY L4	48051000 - 48051fff

     * CAMERA Top	48052000 - 480523ff

     * CAMERA core	48052400 - 480527ff

     * CAMERA DMA	48052800 - 48052bff

     * CAMERA MMU	48052c00 - 48052fff

     * CAMERA L4	48053000 - 48053fff

     * SDMA Mod		48056000 - 48056fff

     * SDMA L4		48057000 - 48057fff

     * SSI Top		48058000 - 48058fff

     * SSI GDD		48059000 - 48059fff

     * SSI Port1	4805a000 - 4805afff

     * SSI Port2	4805b000 - 4805bfff

     * SSI L4		4805c000 - 4805cfff

     * USB Mod		4805e000 - 480fefff

     * USB L4		4805f000 - 480fffff

     * WIN_TRACER1 Mod	48060000 - 48060fff

     * WIN_TRACER1 L4	48061000 - 48061fff

     * WIN_TRACER2 Mod	48062000 - 48062fff

     * WIN_TRACER2 L4	48063000 - 48063fff

     * WIN_TRACER3 Mod	48064000 - 48064fff

     * WIN_TRACER3 L4	48065000 - 48065fff

     * WIN_TRACER4 Top	48066000 - 480660ff

     * WIN_TRACER4 ETT	48066100 - 480661ff

     * WIN_TRACER4 WT	48066200 - 480662ff

     * WIN_TRACER4 L4	48067000 - 48067fff

     * XTI Mod		48068000 - 48068fff

     * XTI L4		48069000 - 48069fff

     * UART1 Mod	4806a000 - 4806afff

     * UART1 L4		4806b000 - 4806bfff

     * UART2 Mod	4806c000 - 4806cfff

     * UART2 L4		4806d000 - 4806dfff

     * UART3 Mod	4806e000 - 4806efff

     * UART3 L4		4806f000 - 4806ffff

     * I2C1 Mod		48070000 - 48070fff

     * I2C1 L4		48071000 - 48071fff

     * I2C2 Mod		48072000 - 48072fff

     * I2C2 L4		48073000 - 48073fff

     * McBSP1 Mod	48074000 - 48074fff

     * McBSP1 L4	48075000 - 48075fff

     * McBSP2 Mod	48076000 - 48076fff

     * McBSP2 L4	48077000 - 48077fff

     * GPTIMER3 Mod	48078000 - 48078fff

     * GPTIMER3 L4	48079000 - 48079fff

     * GPTIMER4 Mod	4807a000 - 4807afff

     * GPTIMER4 L4	4807b000 - 4807bfff

     * GPTIMER5 Mod	4807c000 - 4807cfff

     * GPTIMER5 L4	4807d000 - 4807dfff

     * GPTIMER6 Mod	4807e000 - 4807efff

     * GPTIMER6 L4	4807f000 - 4807ffff

     * GPTIMER7 Mod	48080000 - 48080fff

     * GPTIMER7 L4	48081000 - 48081fff

     * GPTIMER8 Mod	48082000 - 48082fff

     * GPTIMER8 L4	48083000 - 48083fff

     * GPTIMER9 Mod	48084000 - 48084fff

     * GPTIMER9 L4	48085000 - 48085fff

     * GPTIMER10 Mod	48086000 - 48086fff

     * GPTIMER10 L4	48087000 - 48087fff

     * GPTIMER11 Mod	48088000 - 48088fff

     * GPTIMER11 L4	48089000 - 48089fff

     * GPTIMER12 Mod	4808a000 - 4808afff

     * GPTIMER12 L4	4808b000 - 4808bfff

     * EAC Mod		48090000 - 48090fff

     * EAC L4		48091000 - 48091fff

     * FAC Mod		48092000 - 48092fff

     * FAC L4		48093000 - 48093fff

     * MAILBOX Mod	48094000 - 48094fff

     * MAILBOX L4	48095000 - 48095fff

     * SPI1 Mod		48098000 - 48098fff

     * SPI1 L4		48099000 - 48099fff

     * SPI2 Mod		4809a000 - 4809afff

     * SPI2 L4		4809b000 - 4809bfff

     * MMC/SDIO Mod	4809c000 - 4809cfff

     * MMC/SDIO L4	4809d000 - 4809dfff

     * MS_PRO Mod	4809e000 - 4809efff

     * MS_PRO L4	4809f000 - 4809ffff

     * RNG Mod		480a0000 - 480a0fff

     * RNG L4		480a1000 - 480a1fff

     * DES3DES Mod	480a2000 - 480a2fff

     * DES3DES L4	480a3000 - 480a3fff

     * SHA1MD5 Mod	480a4000 - 480a4fff

     * SHA1MD5 L4	480a5000 - 480a5fff

     * AES Mod		480a6000 - 480a6fff

     * AES L4		480a7000 - 480a7fff

     * PKA Mod		480a8000 - 480a9fff

     * PKA L4		480aa000 - 480aafff

     * MG Mod		480b0000 - 480b0fff

     * MG L4		480b1000 - 480b1fff

     * HDQ/1-wire Mod	480b2000 - 480b2fff

     * HDQ/1-wire L4	480b3000 - 480b3fff

     * MPU interrupt	480fe000 - 480fefff

     * STI channel base	54000000 - 5400ffff

     * IVA RAM		5c000000 - 5c01ffff

     * IVA ROM		5c020000 - 5c027fff

     * IMG_BUF_A	5c040000 - 5c040fff

     * IMG_BUF_B	5c042000 - 5c042fff

     * VLCDS		5c048000 - 5c0487ff

     * IMX_COEF		5c049000 - 5c04afff

     * IMX_CMD		5c051000 - 5c051fff

     * VLCDQ		5c053000 - 5c0533ff

     * VLCDH		5c054000 - 5c054fff

     * SEQ_CMD		5c055000 - 5c055fff

     * IMX_REG		5c056000 - 5c0560ff

     * VLCD_REG		5c056100 - 5c0561ff

     * SEQ_REG		5c056200 - 5c0562ff

     * IMG_BUF_REG	5c056300 - 5c0563ff

     * SEQIRQ_REG	5c056400 - 5c0564ff

     * OCP_REG		5c060000 - 5c060fff

     * SYSC_REG		5c070000 - 5c070fff

     * MMU_REG		5d000000 - 5d000fff

     * sDMA R		68000400 - 680005ff

     * sDMA W		68000600 - 680007ff

     * Display Control	68000800 - 680009ff

     * DSP subsystem	68000a00 - 68000bff

     * MPU subsystem	68000c00 - 68000dff

     * IVA subsystem	68001000 - 680011ff

     * USB		68001200 - 680013ff

     * Camera		68001400 - 680015ff

     * VLYNQ (firewall)	68001800 - 68001bff

     * VLYNQ		68001e00 - 68001fff

     * SSI		68002000 - 680021ff

     * L4		68002400 - 680025ff

     * DSP (firewall)	68002800 - 68002bff

     * DSP subsystem	68002e00 - 68002fff

     * IVA (firewall)	68003000 - 680033ff

     * IVA		68003600 - 680037ff

     * GFX		68003a00 - 68003bff

     * CMDWR emulation	68003c00 - 68003dff

     * SMS		68004000 - 680041ff

     * OCM		68004200 - 680043ff

     * GPMC		68004400 - 680045ff

     * RAM (firewall)	68005000 - 680053ff

     * RAM (err login)	68005400 - 680057ff

     * ROM (firewall)	68005800 - 68005bff

     * ROM (err login)	68005c00 - 68005fff

     * GPMC (firewall)	68006000 - 680063ff

     * GPMC (err login)	68006400 - 680067ff

     * SMS (err login)	68006c00 - 68006fff

     * SMS registers	68008000 - 68008fff

     * SDRC registers	68009000 - 68009fff

     * GPMC registers	6800a000   6800afff

     */

    qemu_register_reset(omap2_mpu_reset, s);

    return s;

}


static void test_dealloc_partial(void)

{

    static const char text[] = "don't leak me";

    UserDefTwo *ud2 = NULL;

    Error *err = NULL;

    /* create partial object */

    {

        QDict *ud2_dict;

        QmpInputVisitor *qiv;

        ud2_dict = qdict_new();

        qdict_put_obj(ud2_dict, "string0", QOBJECT(qstring_from_str(text)));

        qiv = qmp_input_visitor_new(QOBJECT(ud2_dict));

        visit_type_UserDefTwo(qmp_input_get_visitor(qiv), &ud2, NULL, &err);

        qmp_input_visitor_cleanup(qiv);

        QDECREF(ud2_dict);

    }

    /* verify partial success */

    assert(ud2 != NULL);

    assert(ud2->string0 != NULL);

    assert(strcmp(ud2->string0, text) == 0);

    assert(ud2->dict1 == NULL);

    /* confirm & release construction error */

    assert(err != NULL);

    error_free(err);

    /* tear down partial object */

    qapi_free_UserDefTwo(ud2);

}


static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
                         Error **errp)
{
    BDRVQEDState *s = bs->opaque;
    QEDHeader le_header;
    int64_t file_size;
    int ret;
    s->bs = bs;
    QSIMPLEQ_INIT(&s->allocating_write_reqs);
    ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
    if (ret < 0) {
        return ret;
    qed_header_le_to_cpu(&le_header, &s->header);
    if (s->header.magic != QED_MAGIC) {
        error_setg(errp, "Image not in QED format");
    if (s->header.features & ~QED_FEATURE_MASK) {
        /* image uses unsupported feature bits */
        char buf[64];
        snprintf(buf, sizeof(buf), "%" PRIx64,
            s->header.features & ~QED_FEATURE_MASK);
        error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
            bdrv_get_device_name(bs), "QED", buf);
        return -ENOTSUP;
    if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
    /* Round down file size to the last cluster */
    file_size = bdrv_getlength(bs->file);
    if (file_size < 0) {
        return file_size;
    s->file_size = qed_start_of_cluster(s, file_size);
    if (!qed_is_table_size_valid(s->header.table_size)) {
    if (!qed_is_image_size_valid(s->header.image_size,
                                 s->header.cluster_size,
                                 s->header.table_size)) {
    if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
    s->table_nelems = (s->header.cluster_size * s->header.table_size) /
                      sizeof(uint64_t);
    s->l2_shift = ffs(s->header.cluster_size) - 1;
    s->l2_mask = s->table_nelems - 1;
    s->l1_shift = s->l2_shift + ffs(s->table_nelems) - 1;
    if ((s->header.features & QED_F_BACKING_FILE)) {
        if ((uint64_t)s->header.backing_filename_offset +
            s->header.backing_filename_size >
            s->header.cluster_size * s->header.header_size) {
        ret = qed_read_string(bs->file, s->header.backing_filename_offset,
                              s->header.backing_filename_size, bs->backing_file,
                              sizeof(bs->backing_file));
        if (ret < 0) {
            return ret;
        if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
            pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
    /* Reset unknown autoclear feature bits.  This is a backwards
     * compatibility mechanism that allows images to be opened by older
     * programs, which "knock out" unknown feature bits.  When an image is
     * opened by a newer program again it can detect that the autoclear
     * feature is no longer valid.
     */
    if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
        !bdrv_is_read_only(bs->file) && !(flags & BDRV_O_INCOMING)) {
        s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
        ret = qed_write_header_sync(s);
        if (ret) {
            return ret;
        /* From here on only known autoclear feature bits are valid */
        bdrv_flush(bs->file);
    s->l1_table = qed_alloc_table(s);
    qed_init_l2_cache(&s->l2_cache);
    ret = qed_read_l1_table_sync(s);
    if (ret) {
        goto out;
    /* If image was not closed cleanly, check consistency */
    if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
        /* Read-only images cannot be fixed.  There is no risk of corruption
         * since write operations are not possible.  Therefore, allow
         * potentially inconsistent images to be opened read-only.  This can
         * aid data recovery from an otherwise inconsistent image.
         */
        if (!bdrv_is_read_only(bs->file) &&
            !(flags & BDRV_O_INCOMING)) {
            BdrvCheckResult result = {0};
            ret = qed_check(s, &result, true);
            if (ret) {
                goto out;
    bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
out:
    if (ret) {
        qed_free_l2_cache(&s->l2_cache);
        qemu_vfree(s->l1_table);
    return ret;


void gen_intermediate_code(CPUAlphaState *env, struct TranslationBlock *tb)
{
    AlphaCPU *cpu = alpha_env_get_cpu(env);
    CPUState *cs = CPU(cpu);
    DisasContext ctx, *ctxp = &ctx;
    target_ulong pc_start;
    target_ulong pc_mask;
    uint32_t insn;
    ExitStatus ret;
    int num_insns;
    int max_insns;
    pc_start = tb->pc;
    ctx.tb = tb;
    ctx.pc = pc_start;
    ctx.tbflags = tb->flags;
    ctx.mem_idx = cpu_mmu_index(env, false);
    ctx.implver = env->implver;
    ctx.amask = env->amask;
    ctx.singlestep_enabled = cs->singlestep_enabled;
#ifdef CONFIG_USER_ONLY
    ctx.ir = cpu_std_ir;
#else
    ctx.palbr = env->palbr;
    ctx.ir = (ctx.tbflags & ENV_FLAG_PAL_MODE ? cpu_pal_ir : cpu_std_ir);
#endif
    /* ??? Every TB begins with unset rounding mode, to be initialized on
       the first fp insn of the TB.  Alternately we could define a proper
       default for every TB (e.g. QUAL_RM_N or QUAL_RM_D) and make sure
       to reset the FP_STATUS to that default at the end of any TB that
       changes the default.  We could even (gasp) dynamiclly figure out
       what default would be most efficient given the running program.  */
    ctx.tb_rm = -1;
    /* Similarly for flush-to-zero.  */
    ctx.tb_ftz = -1;
    TCGV_UNUSED_I64(ctx.zero);
    TCGV_UNUSED_I64(ctx.sink);
    TCGV_UNUSED_I64(ctx.lit);
    num_insns = 0;
    max_insns = tb->cflags & CF_COUNT_MASK;
    if (max_insns == 0) {
        max_insns = CF_COUNT_MASK;
    if (max_insns > TCG_MAX_INSNS) {
        max_insns = TCG_MAX_INSNS;
    if (in_superpage(&ctx, pc_start)) {
        pc_mask = (1ULL << 41) - 1;
    } else {
        pc_mask = ~TARGET_PAGE_MASK;
    gen_tb_start(tb);
    tcg_clear_temp_count();
    do {
        tcg_gen_insn_start(ctx.pc);
        num_insns++;
        if (unlikely(cpu_breakpoint_test(cs, ctx.pc, BP_ANY))) {
            ret = gen_excp(&ctx, EXCP_DEBUG, 0);
            /* The address covered by the breakpoint must be included in
               [tb->pc, tb->pc + tb->size) in order to for it to be
               properly cleared -- thus we increment the PC here so that
               the logic setting tb->size below does the right thing.  */
            ctx.pc += 4;
            break;
        if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {
            gen_io_start();
        insn = cpu_ldl_code(env, ctx.pc);
        ctx.pc += 4;
        ret = translate_one(ctxp, insn);
        free_context_temps(ctxp);
        /* If we reach a page boundary, are single stepping,
           or exhaust instruction count, stop generation.  */
        if (ret == NO_EXIT
            && ((ctx.pc & pc_mask) == 0
                || tcg_op_buf_full()
                || num_insns >= max_insns
                || singlestep
                || ctx.singlestep_enabled)) {
            ret = EXIT_FALLTHRU;
    } while (ret == NO_EXIT);
    if (tb->cflags & CF_LAST_IO) {
        gen_io_end();
    switch (ret) {
    case EXIT_GOTO_TB:
    case EXIT_NORETURN:
        break;
    case EXIT_FALLTHRU:
        if (use_goto_tb(&ctx, ctx.pc)) {
            tcg_gen_goto_tb(0);
            tcg_gen_movi_i64(cpu_pc, ctx.pc);
            tcg_gen_exit_tb((uintptr_t)ctx.tb);
        /* FALLTHRU */
    case EXIT_PC_STALE:
        tcg_gen_movi_i64(cpu_pc, ctx.pc);
        /* FALLTHRU */
    case EXIT_PC_UPDATED:
        if (!use_exit_tb(&ctx)) {
            tcg_gen_lookup_and_goto_ptr(cpu_pc);
            break;
        /* FALLTHRU */
    case EXIT_PC_UPDATED_NOCHAIN:
        if (ctx.singlestep_enabled) {
            gen_excp_1(EXCP_DEBUG, 0);
        } else {
            tcg_gen_exit_tb(0);
        break;
    default:
        g_assert_not_reached();
    gen_tb_end(tb, num_insns);
    tb->size = ctx.pc - pc_start;
    tb->icount = num_insns;
#ifdef DEBUG_DISAS
    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
        && qemu_log_in_addr_range(pc_start)) {
        qemu_log_lock();
        qemu_log("IN: %s\n", lookup_symbol(pc_start));
        log_target_disas(cs, pc_start, ctx.pc - pc_start, 1);
        qemu_log("\n");
        qemu_log_unlock();
#endif


static int vble_decode_frame(AVCodecContext *avctx, void *data, int *data_size,
                             AVPacket *avpkt)
{
    VBLEContext *ctx = avctx->priv_data;
    AVFrame *pic = avctx->coded_frame;
    GetBitContext gb;
    const uint8_t *src = avpkt->data;
    int version;
    int offset = 0;
    int width_uv = avctx->width / 2, height_uv = avctx->height / 2;
    pic->reference = 0;
    /* Clear buffer if need be */
    if (pic->data[0])
        avctx->release_buffer(avctx, pic);
    /* Allocate buffer */
    if (avctx->get_buffer(avctx, pic) < 0) {
        av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");
        return AVERROR(ENOMEM);
    /* Set flags */
    pic->key_frame = 1;
    pic->pict_type = AV_PICTURE_TYPE_I;
    /* Version should always be 1 */
    version = AV_RL32(src);
    if (version != 1)
        av_log(avctx, AV_LOG_WARNING, "Unsupported VBLE Version: %d\n", version);
    init_get_bits(&gb, src + 4, (avpkt->size - 4) * 8);
    /* Unpack */
    if (vble_unpack(ctx, &gb) < 0) {
        av_log(avctx, AV_LOG_ERROR, "Invalid Code\n");
    /* Restore planes. Should be almost identical to Huffyuv's. */
    vble_restore_plane(ctx, &gb, 0, offset, avctx->width, avctx->height);
    /* Chroma */
    if (!(ctx->avctx->flags & CODEC_FLAG_GRAY)) {
        offset += avctx->width * avctx->height;
        vble_restore_plane(ctx, &gb, 1, offset, width_uv, height_uv);
        offset += width_uv * height_uv;
        vble_restore_plane(ctx, &gb, 2, offset, width_uv, height_uv);
    *data_size = sizeof(AVFrame);
    *(AVFrame *)data = *pic;
    return avpkt->size;


static int virtio_balloon_device_exit(DeviceState *qdev)

{

    VirtIOBalloon *s = VIRTIO_BALLOON(qdev);

    VirtIODevice *vdev = VIRTIO_DEVICE(qdev);

    balloon_stats_destroy_timer(s);

    qemu_remove_balloon_handler(s);

    unregister_savevm(qdev, "virtio-balloon", s);

    virtio_cleanup(vdev);

    return 0;

}


uint8_t* ff_AMediaCodec_getInputBuffer(FFAMediaCodec* codec, size_t idx, size_t *out_size)

{

    uint8_t *ret = NULL;

    JNIEnv *env = NULL;

    jobject buffer = NULL;

    JNI_GET_ENV_OR_RETURN(env, codec, NULL);

    if (codec->has_get_i_o_buffer) {

        buffer = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_input_buffer_id, idx);

        if (ff_jni_exception_check(env, 1, codec) < 0) {

            goto fail;

        }

    } else {

        if (!codec->input_buffers) {

            codec->input_buffers = (*env)->CallObjectMethod(env, codec->object, codec->jfields.get_input_buffers_id);

            if (ff_jni_exception_check(env, 1, codec) < 0) {

                goto fail;

            }

            codec->input_buffers = (*env)->NewGlobalRef(env, codec->input_buffers);

            if (ff_jni_exception_check(env, 1, codec) < 0) {

                goto fail;

            }

        }

        buffer = (*env)->GetObjectArrayElement(env, codec->input_buffers, idx);

        if (ff_jni_exception_check(env, 1, codec) < 0) {

            goto fail;

        }

    }

    ret = (*env)->GetDirectBufferAddress(env, buffer);

    *out_size = (*env)->GetDirectBufferCapacity(env, buffer);

fail:

    if (buffer) {

        (*env)->DeleteLocalRef(env, buffer);

    }

    return ret;

}


static int fic_decode_slice(AVCodecContext *avctx, void *tdata)

{

    FICContext *ctx        = avctx->priv_data;

    FICThreadContext *tctx = tdata;

    GetBitContext gb;

    uint8_t *src = tctx->src;

    int slice_h  = tctx->slice_h;

    int src_size = tctx->src_size;

    int y_off    = tctx->y_off;

    int x, y, p;

    init_get_bits(&gb, src, src_size * 8);

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

        int stride   = ctx->frame->linesize[p];

        uint8_t* dst = ctx->frame->data[p] + (y_off >> !!p) * stride;

        for (y = 0; y < (slice_h >> !!p); y += 8) {

            for (x = 0; x < (ctx->aligned_width >> !!p); x += 8) {

                int ret;

                if ((ret = fic_decode_block(ctx, &gb, dst + x, stride, tctx->block)) != 0)

                    return ret;

            }

            dst += 8 * stride;

        }

    }

    return 0;

}


fdctrl_t *sun4m_fdctrl_init (qemu_irq irq, target_phys_addr_t io_base,

                             DriveInfo **fds, qemu_irq *fdc_tc)

{

    DeviceState *dev;

    fdctrl_sysbus_t *sys;

    fdctrl_t *fdctrl;

    dev = qdev_create(NULL, "SUNW,fdtwo");

    qdev_prop_set_drive(dev, "drive", fds[0]);

    if (qdev_init(dev) != 0)

        return NULL;

    sys = DO_UPCAST(fdctrl_sysbus_t, busdev.qdev, dev);

    fdctrl = &sys->state;

    sysbus_connect_irq(&sys->busdev, 0, irq);

    sysbus_mmio_map(&sys->busdev, 0, io_base);

    *fdc_tc = qdev_get_gpio_in(dev, 0);

    return fdctrl;

}


static av_cold int XAVS_init(AVCodecContext *avctx)

{

    XavsContext *x4 = avctx->priv_data;

    x4->sei_size = 0;

    xavs_param_default(&x4->params);

    x4->params.pf_log               = XAVS_log;

    x4->params.p_log_private        = avctx;

    x4->params.i_keyint_max         = avctx->gop_size;

    if (avctx->bit_rate) {

        x4->params.rc.i_bitrate   = avctx->bit_rate / 1000;

        x4->params.rc.i_rc_method = XAVS_RC_ABR;

    }

    x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;

    x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;

    x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;

    if (avctx->flags & CODEC_FLAG_PASS2) {

        x4->params.rc.b_stat_read = 1;

    } else {

        if (x4->crf >= 0) {

            x4->params.rc.i_rc_method   = XAVS_RC_CRF;

            x4->params.rc.f_rf_constant = x4->crf;

        } else if (x4->cqp >= 0) {

            x4->params.rc.i_rc_method   = XAVS_RC_CQP;

            x4->params.rc.i_qp_constant = x4->cqp;

        }

    }

    if (x4->aud >= 0)

        x4->params.b_aud                      = x4->aud;

    if (x4->mbtree >= 0)

        x4->params.rc.b_mb_tree               = x4->mbtree;

    if (x4->direct_pred >= 0)

        x4->params.analyse.i_direct_mv_pred   = x4->direct_pred;

    if (x4->fast_pskip >= 0)

        x4->params.analyse.b_fast_pskip       = x4->fast_pskip;

    if (x4->mixed_refs >= 0)

        x4->params.analyse.b_mixed_references = x4->mixed_refs;

    if (x4->b_bias != INT_MIN)

        x4->params.i_bframe_bias              = x4->b_bias;

    if (x4->cplxblur >= 0)

        x4->params.rc.f_complexity_blur = x4->cplxblur;

    x4->params.i_bframe          = avctx->max_b_frames;

    /* cabac is not included in AVS JiZhun Profile */

    x4->params.b_cabac           = 0;

    x4->params.i_bframe_adaptive = avctx->b_frame_strategy;

    avctx->has_b_frames          = !!avctx->max_b_frames;

    /* AVS doesn't allow B picture as reference */

    /* The max allowed reference frame number of B is 2 */

    x4->params.i_keyint_min      = avctx->keyint_min;

    if (x4->params.i_keyint_min > x4->params.i_keyint_max)

        x4->params.i_keyint_min = x4->params.i_keyint_max;

    x4->params.i_scenecut_threshold        = avctx->scenechange_threshold;

   // x4->params.b_deblocking_filter       = avctx->flags & CODEC_FLAG_LOOP_FILTER;

    x4->params.rc.i_qp_min                 = avctx->qmin;

    x4->params.rc.i_qp_max                 = avctx->qmax;

    x4->params.rc.i_qp_step                = avctx->max_qdiff;

    x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */

    x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */

    x4->params.i_frame_reference    = avctx->refs;

    x4->params.i_width              = avctx->width;

    x4->params.i_height             = avctx->height;

    x4->params.vui.i_sar_width      = avctx->sample_aspect_ratio.num;

    x4->params.vui.i_sar_height     = avctx->sample_aspect_ratio.den;

    /* This is only used for counting the fps */

    x4->params.i_fps_num            = avctx->time_base.den;

    x4->params.i_fps_den            = avctx->time_base.num;

    x4->params.analyse.inter        = XAVS_ANALYSE_I8x8 |XAVS_ANALYSE_PSUB16x16| XAVS_ANALYSE_BSUB16x16;

    switch (avctx->me_method) {

         case  ME_EPZS:

               x4->params.analyse.i_me_method = XAVS_ME_DIA;

               break;

         case  ME_HEX:

               x4->params.analyse.i_me_method = XAVS_ME_HEX;

               break;

         case  ME_UMH:

               x4->params.analyse.i_me_method = XAVS_ME_UMH;

               break;

         case  ME_FULL:

               x4->params.analyse.i_me_method = XAVS_ME_ESA;

               break;

         case  ME_TESA:

               x4->params.analyse.i_me_method = XAVS_ME_TESA;

               break;

         default:

               x4->params.analyse.i_me_method = XAVS_ME_HEX;

    }

    x4->params.analyse.i_me_range = avctx->me_range;

    x4->params.analyse.i_subpel_refine    = avctx->me_subpel_quality;

    x4->params.analyse.b_chroma_me        = avctx->me_cmp & FF_CMP_CHROMA;

    /* AVS P2 only enables 8x8 transform */

    x4->params.analyse.b_transform_8x8    = 1; //avctx->flags2 & CODEC_FLAG2_8X8DCT;

    x4->params.analyse.i_trellis          = avctx->trellis;

    x4->params.analyse.i_noise_reduction  = avctx->noise_reduction;

    if (avctx->level > 0)

        x4->params.i_level_idc = avctx->level;

    x4->params.rc.f_rate_tolerance =

        (float)avctx->bit_rate_tolerance/avctx->bit_rate;

    if ((avctx->rc_buffer_size) &&

        (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {

        x4->params.rc.f_vbv_buffer_init =

            (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;

    } else

        x4->params.rc.f_vbv_buffer_init = 0.9;

    /* TAG:do we have MB tree RC method */

    /* what is the RC method we are now using? Default NO */

    x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);

    x4->params.rc.f_pb_factor             = avctx->b_quant_factor;

    x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;

    x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;

    x4->params.i_log_level    = XAVS_LOG_DEBUG;

    x4->params.i_threads      = avctx->thread_count;

    x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)

        x4->params.b_repeat_headers = 0;

    x4->enc = xavs_encoder_open(&x4->params);

    if (!x4->enc)

        return -1;

    if (!(x4->pts_buffer = av_mallocz_array((avctx->max_b_frames+1), sizeof(*x4->pts_buffer))))

        return AVERROR(ENOMEM);

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    /* TAG: Do we have GLOBAL HEADER in AVS */

    /* We Have PPS and SPS in AVS */

    if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER && 0) {

        xavs_nal_t *nal;

        int nnal, s, i, size;

        uint8_t *p;

        s = xavs_encoder_headers(x4->enc, &nal, &nnal);

        avctx->extradata = p = av_malloc(s);

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

            /* Don't put the SEI in extradata. */

            if (nal[i].i_type == NAL_SEI) {

                x4->sei = av_malloc( 5 + nal[i].i_payload * 4 / 3 );

                if (xavs_nal_encode(x4->sei, &x4->sei_size, 1, nal + i) < 0)

                    return -1;

                continue;

            }

            size = xavs_nal_encode(p, &s, 1, nal + i);

            if (size < 0)

                return -1;

            p += size;

        }

        avctx->extradata_size = p - avctx->extradata;

    }

    return 0;

}


av_cold int ff_huffyuv_alloc_temp(HYuvContext *s)

{

    int i;

    if (s->bitstream_bpp<24 || s->version > 2) {

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

            s->temp[i]= av_malloc(2*s->width + 16);

            if (!s->temp[i])

                return AVERROR(ENOMEM);

            s->temp16[i] = (uint16_t*)s->temp[i];

        }

    } else {

        s->temp[0]= av_mallocz(4*s->width + 16);

        if (!s->temp[0])

            return AVERROR(ENOMEM);

    }

    return 0;

}


void dump_mmu(FILE *f, fprintf_function cpu_fprintf, CPUPPCState *env)

{

    switch (env->mmu_model) {

    case POWERPC_MMU_BOOKE:

        mmubooke_dump_mmu(f, cpu_fprintf, env);

        break;

    case POWERPC_MMU_BOOKE206:

        mmubooke206_dump_mmu(f, cpu_fprintf, env);

        break;

    case POWERPC_MMU_SOFT_6xx:

    case POWERPC_MMU_SOFT_74xx:

        mmu6xx_dump_mmu(f, cpu_fprintf, env);

        break;

#if defined(TARGET_PPC64)

    case POWERPC_MMU_64B:

    case POWERPC_MMU_2_03:

    case POWERPC_MMU_2_06:

    case POWERPC_MMU_2_07:

        dump_slb(f, cpu_fprintf, env);

        break;

#endif

    default:

        qemu_log_mask(LOG_UNIMP, "%s: unimplemented\n", __func__);

    }

}


static void monitor_qapi_event_handler(void *opaque)

{

    MonitorQAPIEventState *evstate = opaque;

    MonitorQAPIEventConf *evconf = &monitor_qapi_event_conf[evstate->event];

    trace_monitor_protocol_event_handler(evstate->event, evstate->qdict);

    qemu_mutex_lock(&monitor_lock);

    if (evstate->qdict) {

        int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

        monitor_qapi_event_emit(evstate->event, evstate->qdict);

        QDECREF(evstate->qdict);

        evstate->qdict = NULL;

        timer_mod_ns(evstate->timer, now + evconf->rate);

    } else {

        g_hash_table_remove(monitor_qapi_event_state, evstate);

        QDECREF(evstate->data);

        timer_free(evstate->timer);

        g_free(evstate);

    }

    qemu_mutex_unlock(&monitor_lock);

}


static void body(uint32_t ABCD[4], uint32_t X[16])

{

    int i av_unused;

    uint32_t t;

    uint32_t a = ABCD[3];

    uint32_t b = ABCD[2];

    uint32_t c = ABCD[1];

    uint32_t d = ABCD[0];

#if HAVE_BIGENDIAN

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

        X[i] = av_bswap32(X[i]);

#endif

#if CONFIG_SMALL

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

        CORE(i, a, b, c, d);

        t = d;

        d = c;

        c = b;

        b = a;

        a = t;

    }

#else

#define CORE2(i)                                                        \

    CORE( i,   a,b,c,d); CORE((i+1),d,a,b,c);                           \

    CORE((i+2),c,d,a,b); CORE((i+3),b,c,d,a)

#define CORE4(i) CORE2(i); CORE2((i+4)); CORE2((i+8)); CORE2((i+12))

    CORE4(0); CORE4(16); CORE4(32); CORE4(48);

#endif

    ABCD[0] += d;

    ABCD[1] += c;

    ABCD[2] += b;

    ABCD[3] += a;

}


static int v210_read_header(AVFormatContext *ctx)

{

    V210DemuxerContext *s = ctx->priv_data;

    AVStream *st;

    st = avformat_new_stream(ctx, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = ctx->iformat->raw_codec_id;

    avpriv_set_pts_info(st, 64, s->framerate.den, s->framerate.num);

    st->codec->width    = s->width;

    st->codec->height   = s->height;

    st->codec->pix_fmt  = ctx->iformat->raw_codec_id == AV_CODEC_ID_V210 ?

                          AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV422P16;

    st->codec->bit_rate = av_rescale_q(GET_PACKET_SIZE(s->width, s->height),

                                       (AVRational){8,1}, st->time_base);

    return 0;

}


int ff_h263_decode_mb(MpegEncContext *s,

                      int16_t block[6][64])

{

    int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;

    int16_t *mot_val;

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

    int cbpb = 0, pb_mv_count = 0;

    assert(!s->h263_pred);

    if (s->pict_type == AV_PICTURE_TYPE_P) {

        do{

            if (get_bits1(&s->gb)) {

                /* skip mb */

                s->mb_intra = 0;

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

                    s->block_last_index[i] = -1;

                s->mv_dir = MV_DIR_FORWARD;

                s->mv_type = MV_TYPE_16X16;

                s->current_picture.mb_type[xy] = MB_TYPE_SKIP | MB_TYPE_16x16 | MB_TYPE_L0;

                s->mv[0][0][0] = 0;

                s->mv[0][0][1] = 0;

                s->mb_skipped = !(s->obmc | s->loop_filter);

                goto end;

            }

            cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);

            if (cbpc < 0){

                av_log(s->avctx, AV_LOG_ERROR, "cbpc damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

        }while(cbpc == 20);

        s->dsp.clear_blocks(s->block[0]);

        dquant = cbpc & 8;

        s->mb_intra = ((cbpc & 4) != 0);

        if (s->mb_intra) goto intra;

        if(s->pb_frame && get_bits1(&s->gb))

            pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);

        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);

        if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)

            cbpy ^= 0xF;

        cbp = (cbpc & 3) | (cbpy << 2);

        if (dquant) {

            h263_decode_dquant(s);

        }

        s->mv_dir = MV_DIR_FORWARD;

        if ((cbpc & 16) == 0) {

            s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;

            /* 16x16 motion prediction */

            s->mv_type = MV_TYPE_16X16;

            ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);

            if (s->umvplus)

               mx = h263p_decode_umotion(s, pred_x);

            else

               mx = ff_h263_decode_motion(s, pred_x, 1);

            if (mx >= 0xffff)

                return -1;

            if (s->umvplus)

               my = h263p_decode_umotion(s, pred_y);

            else

               my = ff_h263_decode_motion(s, pred_y, 1);

            if (my >= 0xffff)

                return -1;

            s->mv[0][0][0] = mx;

            s->mv[0][0][1] = my;

            if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)

               skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */

        } else {

            s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;

            s->mv_type = MV_TYPE_8X8;

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

                mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);

                if (s->umvplus)

                  mx = h263p_decode_umotion(s, pred_x);

                else

                  mx = ff_h263_decode_motion(s, pred_x, 1);

                if (mx >= 0xffff)

                    return -1;

                if (s->umvplus)

                  my = h263p_decode_umotion(s, pred_y);

                else

                  my = ff_h263_decode_motion(s, pred_y, 1);

                if (my >= 0xffff)

                    return -1;

                s->mv[0][i][0] = mx;

                s->mv[0][i][1] = my;

                if (s->umvplus && (mx - pred_x) == 1 && (my - pred_y) == 1)

                  skip_bits1(&s->gb); /* Bit stuffing to prevent PSC */

                mot_val[0] = mx;

                mot_val[1] = my;

            }

        }

    } else if(s->pict_type==AV_PICTURE_TYPE_B) {

        int mb_type;

        const int stride= s->b8_stride;

        int16_t *mot_val0 = s->current_picture.motion_val[0][2 * (s->mb_x + s->mb_y * stride)];

        int16_t *mot_val1 = s->current_picture.motion_val[1][2 * (s->mb_x + s->mb_y * stride)];

//        const int mv_xy= s->mb_x + 1 + s->mb_y * s->mb_stride;

        //FIXME ugly

        mot_val0[0       ]= mot_val0[2       ]= mot_val0[0+2*stride]= mot_val0[2+2*stride]=

        mot_val0[1       ]= mot_val0[3       ]= mot_val0[1+2*stride]= mot_val0[3+2*stride]=

        mot_val1[0       ]= mot_val1[2       ]= mot_val1[0+2*stride]= mot_val1[2+2*stride]=

        mot_val1[1       ]= mot_val1[3       ]= mot_val1[1+2*stride]= mot_val1[3+2*stride]= 0;

        do{

            mb_type= get_vlc2(&s->gb, h263_mbtype_b_vlc.table, H263_MBTYPE_B_VLC_BITS, 2);

            if (mb_type < 0){

                av_log(s->avctx, AV_LOG_ERROR, "b mb_type damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            mb_type= h263_mb_type_b_map[ mb_type ];

        }while(!mb_type);

        s->mb_intra = IS_INTRA(mb_type);

        if(HAS_CBP(mb_type)){

            s->dsp.clear_blocks(s->block[0]);

            cbpc = get_vlc2(&s->gb, cbpc_b_vlc.table, CBPC_B_VLC_BITS, 1);

            if(s->mb_intra){

                dquant = IS_QUANT(mb_type);

                goto intra;

            }

            cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);

            if (cbpy < 0){

                av_log(s->avctx, AV_LOG_ERROR, "b cbpy damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

            if(s->alt_inter_vlc==0 || (cbpc & 3)!=3)

                cbpy ^= 0xF;

            cbp = (cbpc & 3) | (cbpy << 2);

        }else

            cbp=0;

        assert(!s->mb_intra);

        if(IS_QUANT(mb_type)){

            h263_decode_dquant(s);

        }

        if(IS_DIRECT(mb_type)){

            s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;

            mb_type |= ff_mpeg4_set_direct_mv(s, 0, 0);

        }else{

            s->mv_dir = 0;

            s->mv_type= MV_TYPE_16X16;

//FIXME UMV

            if(USES_LIST(mb_type, 0)){

                int16_t *mot_val= ff_h263_pred_motion(s, 0, 0, &mx, &my);

                s->mv_dir = MV_DIR_FORWARD;

                mx = ff_h263_decode_motion(s, mx, 1);

                my = ff_h263_decode_motion(s, my, 1);

                s->mv[0][0][0] = mx;

                s->mv[0][0][1] = my;

                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;

                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;

            }

            if(USES_LIST(mb_type, 1)){

                int16_t *mot_val= ff_h263_pred_motion(s, 0, 1, &mx, &my);

                s->mv_dir |= MV_DIR_BACKWARD;

                mx = ff_h263_decode_motion(s, mx, 1);

                my = ff_h263_decode_motion(s, my, 1);

                s->mv[1][0][0] = mx;

                s->mv[1][0][1] = my;

                mot_val[0       ]= mot_val[2       ]= mot_val[0+2*stride]= mot_val[2+2*stride]= mx;

                mot_val[1       ]= mot_val[3       ]= mot_val[1+2*stride]= mot_val[3+2*stride]= my;

            }

        }

        s->current_picture.mb_type[xy] = mb_type;

    } else { /* I-Frame */

        do{

            cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);

            if (cbpc < 0){

                av_log(s->avctx, AV_LOG_ERROR, "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);

                return -1;

            }

        }while(cbpc == 8);

        s->dsp.clear_blocks(s->block[0]);

        dquant = cbpc & 4;

        s->mb_intra = 1;

intra:

        s->current_picture.mb_type[xy] = MB_TYPE_INTRA;

        if (s->h263_aic) {

            s->ac_pred = get_bits1(&s->gb);

            if(s->ac_pred){

                s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;

                s->h263_aic_dir = get_bits1(&s->gb);

            }

        }else

            s->ac_pred = 0;

        if(s->pb_frame && get_bits1(&s->gb))

            pb_mv_count = h263_get_modb(&s->gb, s->pb_frame, &cbpb);

        cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);

        if(cbpy<0){

            av_log(s->avctx, AV_LOG_ERROR, "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

        cbp = (cbpc & 3) | (cbpy << 2);

        if (dquant) {

            h263_decode_dquant(s);

        }

        pb_mv_count += !!s->pb_frame;

    }

    while(pb_mv_count--){

        ff_h263_decode_motion(s, 0, 1);

        ff_h263_decode_motion(s, 0, 1);

    }

    /* decode each block */

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

        if (h263_decode_block(s, block[i], i, cbp&32) < 0)

            return -1;

        cbp+=cbp;

    }

    if(s->pb_frame && h263_skip_b_part(s, cbpb) < 0)

        return -1;

    if(s->obmc && !s->mb_intra){

        if(s->pict_type == AV_PICTURE_TYPE_P && s->mb_x+1<s->mb_width && s->mb_num_left != 1)

            preview_obmc(s);

    }

end:

        /* per-MB end of slice check */

    {

        int v= show_bits(&s->gb, 16);

        if (get_bits_left(&s->gb) < 16) {

            v >>= 16 - get_bits_left(&s->gb);

        }

        if(v==0)

            return SLICE_END;

    }

    return SLICE_OK;

}


const QEMUSizedBuffer *qemu_buf_get(QEMUFile *f)

{

    QEMUBuffer *p;

    qemu_fflush(f);

    p = f->opaque;

    return p->qsb;

}


static int vncws_start_tls_handshake(struct VncState *vs)
{
    int ret = gnutls_handshake(vs->tls.session);
    if (ret < 0) {
        if (!gnutls_error_is_fatal(ret)) {
            VNC_DEBUG("Handshake interrupted (blocking)\n");
            if (!gnutls_record_get_direction(vs->tls.session)) {
                qemu_set_fd_handler(vs->csock, vncws_tls_handshake_io,
                                    NULL, vs);
                qemu_set_fd_handler(vs->csock, NULL, vncws_tls_handshake_io,
                                    vs);
            return 0;
        VNC_DEBUG("Handshake failed %s\n", gnutls_strerror(ret));
    VNC_DEBUG("Handshake done, switching to TLS data mode\n");
    qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read, NULL, vs);
    return 0;


static uint8_t *read_huffman_tables(FourXContext *f, uint8_t * const buf){

    int frequency[512];

    uint8_t flag[512];

    int up[512];

    uint8_t len_tab[257];

    int bits_tab[257];

    int start, end;

    uint8_t *ptr= buf;

    int j;

    memset(frequency, 0, sizeof(frequency));

    memset(up, -1, sizeof(up));

    start= *ptr++;

    end= *ptr++;

    for(;;){

        int i;

        for(i=start; i<=end; i++){

            frequency[i]= *ptr++;

//            printf("%d %d %d\n", start, end, frequency[i]);

        }

        start= *ptr++;

        if(start==0) break;

        end= *ptr++;

    }

    frequency[256]=1;

    while((ptr - buf)&3) ptr++; // 4byte align

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

//        printf("%2X", ptr[j]);

    for(j=257; j<512; j++){

        int min_freq[2]= {256*256, 256*256};

        int smallest[2]= {0, 0};

        int i;

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

            if(frequency[i] == 0) continue;

            if(frequency[i] < min_freq[1]){

                if(frequency[i] < min_freq[0]){

                    min_freq[1]= min_freq[0]; smallest[1]= smallest[0];

                    min_freq[0]= frequency[i];smallest[0]= i;

                }else{

                    min_freq[1]= frequency[i];smallest[1]= i;

                }

            }

        }

        if(min_freq[1] == 256*256) break;

        frequency[j]= min_freq[0] + min_freq[1];

        flag[ smallest[0] ]= 0;

        flag[ smallest[1] ]= 1;

        up[ smallest[0] ]=

        up[ smallest[1] ]= j;

        frequency[ smallest[0] ]= frequency[ smallest[1] ]= 0;

    }

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

        int node;

        int len=0;

        int bits=0;

        for(node= j; up[node] != -1; node= up[node]){

            bits += flag[node]<<len;

            len++;

            if(len > 31) av_log(f->avctx, AV_LOG_ERROR, "vlc length overflow\n"); //can this happen at all ?

        }

        bits_tab[j]= bits;

        len_tab[j]= len;

    }

    init_vlc(&f->pre_vlc, ACDC_VLC_BITS, 257,

             len_tab , 1, 1,

             bits_tab, 4, 4);

    return ptr;

}


static bool ohci_eof_timer_needed(void *opaque)

{

    OHCIState *ohci = opaque;

    return ohci->eof_timer != NULL;

}


static int decode_frame_apng(AVCodecContext *avctx,

                        void *data, int *got_frame,

                        AVPacket *avpkt)

{

    PNGDecContext *const s = avctx->priv_data;

    int ret;

    AVFrame *p;

    ff_thread_release_buffer(avctx, &s->last_picture);

    FFSWAP(ThreadFrame, s->picture, s->last_picture);

    p = s->picture.f;

    if (!(s->state & PNG_IHDR)) {

        int side_data_size = 0;

        uint8_t *side_data = NULL;

        if (avpkt)

            side_data = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_data_size);

        if (side_data_size) {

            av_freep(&s->extra_data);

            s->extra_data = av_mallocz(side_data_size + AV_INPUT_BUFFER_PADDING_SIZE);

            if (!s->extra_data)

                return AVERROR(ENOMEM);

            s->extra_data_size = side_data_size;

            memcpy(s->extra_data, side_data, s->extra_data_size);

        }

        if (!s->extra_data_size)

            return AVERROR_INVALIDDATA;

        /* only init fields, there is no zlib use in extradata */

        s->zstream.zalloc = ff_png_zalloc;

        s->zstream.zfree  = ff_png_zfree;

        bytestream2_init(&s->gb, s->extra_data, s->extra_data_size);

        if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)

            goto end;

    }

    /* reset state for a new frame */

    if ((ret = inflateInit(&s->zstream)) != Z_OK) {

        av_log(avctx, AV_LOG_ERROR, "inflateInit returned error %d\n", ret);

        ret = AVERROR_EXTERNAL;

        goto end;

    }

    s->y = 0;

    s->state &= ~(PNG_IDAT | PNG_ALLIMAGE);

    bytestream2_init(&s->gb, avpkt->data, avpkt->size);

    if ((ret = decode_frame_common(avctx, s, p, avpkt)) < 0)

        goto end;

    if (!(s->state & PNG_ALLIMAGE))

        av_log(avctx, AV_LOG_WARNING, "Frame did not contain a complete image\n");

    if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {

        ret = AVERROR_INVALIDDATA;

        goto end;

    }

    if ((ret = av_frame_ref(data, s->picture.f)) < 0)

        goto end;

    *got_frame = 1;

    ret = bytestream2_tell(&s->gb);

end:

    inflateEnd(&s->zstream);

    return ret;

}


static abi_ulong mmap_find_vma_reserved(abi_ulong start, abi_ulong size)

{

    abi_ulong addr;

    abi_ulong end_addr;

    int prot;

    int looped = 0;

    if (size > reserved_va) {

        return (abi_ulong)-1;

    }

    size = HOST_PAGE_ALIGN(size);

    end_addr = start + size;

    if (end_addr > reserved_va) {

        end_addr = reserved_va;

    }

    addr = end_addr - qemu_host_page_size;

    while (1) {

        if (addr > end_addr) {

            if (looped) {

                return (abi_ulong)-1;

            }

            end_addr = reserved_va;

            addr = end_addr - qemu_host_page_size;

            looped = 1;

            continue;

        }

        prot = page_get_flags(addr);

        if (prot) {

            end_addr = addr;

        }

        if (addr + size == end_addr) {

            break;

        }

        addr -= qemu_host_page_size;

    }

    if (start == mmap_next_start) {

        mmap_next_start = addr;

    }

    return addr;

}


static av_always_inline int process_frame(WriterContext *w,

                                          InputFile *ifile,

                                          AVFrame *frame, AVPacket *pkt)

{

    AVFormatContext *fmt_ctx = ifile->fmt_ctx;

    AVCodecContext *dec_ctx = ifile->streams[pkt->stream_index].dec_ctx;

    AVCodecParameters *par = ifile->streams[pkt->stream_index].st->codecpar;

    AVSubtitle sub;

    int ret = 0, got_frame = 0;

    if (dec_ctx->codec) {

        switch (par->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);

            break;

        case AVMEDIA_TYPE_AUDIO:

            ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);

            break;

        }

    }

    if (ret < 0)

        return ret;

    ret = FFMIN(ret, pkt->size); /* guard against bogus return values */

    pkt->data += ret;

    pkt->size -= ret;

    if (got_frame) {

        int is_sub = (par->codec_type == AVMEDIA_TYPE_SUBTITLE);

        nb_streams_frames[pkt->stream_index]++;

        if (do_show_frames)

            if (is_sub)

                show_subtitle(w, &sub, ifile->streams[pkt->stream_index].st, fmt_ctx);

            else

                show_frame(w, frame, ifile->streams[pkt->stream_index].st, fmt_ctx);

        if (is_sub)

            avsubtitle_free(&sub);

    }

    return got_frame;

}


static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    int ret;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams - 1];

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    sc->stsd_count = avio_rb32(pb); /* entries */

    /* Prepare space for hosting multiple extradata. */

    sc->extradata = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata));

    if (!sc->extradata)

        return AVERROR(ENOMEM);

    sc->extradata_size = av_mallocz_array(sc->stsd_count, sizeof(*sc->extradata_size));

    if (!sc->extradata_size)

        return AVERROR(ENOMEM);

    ret = ff_mov_read_stsd_entries(c, pb, sc->stsd_count);

    if (ret < 0)

        return ret;

    /* Restore back the primary extradata. */

    av_freep(&st->codecpar->extradata);

    st->codecpar->extradata_size = sc->extradata_size[0];

    if (sc->extradata_size[0]) {

        st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE);

        if (!st->codecpar->extradata)

            return AVERROR(ENOMEM);

        memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]);

    }

    return 0;

}


static void implicit_weight_table(H264Context *h){

    MpegEncContext * const s = &h->s;

    int ref0, ref1, i;

    int cur_poc = s->current_picture_ptr->poc;

    if(   h->ref_count[0] == 1 && h->ref_count[1] == 1

       && h->ref_list[0][0].poc + h->ref_list[1][0].poc == 2*cur_poc){

        h->use_weight= 0;

        h->use_weight_chroma= 0;

        return;

    }

    h->use_weight= 2;

    h->use_weight_chroma= 2;

    h->luma_log2_weight_denom= 5;

    h->chroma_log2_weight_denom= 5;

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

        h->luma_weight_flag[i]   = 0;

        h->chroma_weight_flag[i] = 0;

    }

    for(ref0=0; ref0 < h->ref_count[0]; ref0++){

        int poc0 = h->ref_list[0][ref0].poc;

        for(ref1=0; ref1 < h->ref_count[1]; ref1++){

            int poc1 = h->ref_list[1][ref1].poc;

            int td = av_clip(poc1 - poc0, -128, 127);

            if(td){

                int tb = av_clip(cur_poc - poc0, -128, 127);

                int tx = (16384 + (FFABS(td) >> 1)) / td;

                int dist_scale_factor = av_clip((tb*tx + 32) >> 6, -1024, 1023) >> 2;

                if(dist_scale_factor < -64 || dist_scale_factor > 128)

                    h->implicit_weight[ref0][ref1] = 32;

                else

                    h->implicit_weight[ref0][ref1] = 64 - dist_scale_factor;

            }else

                h->implicit_weight[ref0][ref1] = 32;

        }

    }

}


static av_cold int ra144_encode_init(AVCodecContext * avctx)

{

    RA144Context *ractx;

    int ret;

    if (avctx->channels != 1) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of channels: %d\n",

               avctx->channels);

        return -1;

    }

    avctx->frame_size = NBLOCKS * BLOCKSIZE;

    avctx->delay      = avctx->frame_size;

    avctx->bit_rate = 8000;

    ractx = avctx->priv_data;

    ractx->lpc_coef[0] = ractx->lpc_tables[0];

    ractx->lpc_coef[1] = ractx->lpc_tables[1];

    ractx->avctx = avctx;

    ret = ff_lpc_init(&ractx->lpc_ctx, avctx->frame_size, LPC_ORDER,

                      FF_LPC_TYPE_LEVINSON);

    if (ret < 0)

        goto error;

    ff_af_queue_init(avctx, &ractx->afq);

    return 0;

error:

    ra144_encode_close(avctx);

    return ret;

}


static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset)

{

    MXFDescriptor *descriptor = arg;

    descriptor->pix_fmt = AV_PIX_FMT_NONE;

    switch(tag) {

    case 0x3F01:

        descriptor->sub_descriptors_count = avio_rb32(pb);

        if (descriptor->sub_descriptors_count >= UINT_MAX / sizeof(UID))

            return AVERROR_INVALIDDATA;

        descriptor->sub_descriptors_refs = av_malloc(descriptor->sub_descriptors_count * sizeof(UID));

        if (!descriptor->sub_descriptors_refs)

            return AVERROR(ENOMEM);

        avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */

        avio_read(pb, (uint8_t *)descriptor->sub_descriptors_refs, descriptor->sub_descriptors_count * sizeof(UID));

        break;

    case 0x3004:

        avio_read(pb, descriptor->essence_container_ul, 16);

        break;

    case 0x3006:

        descriptor->linked_track_id = avio_rb32(pb);

        break;

    case 0x3201: /* PictureEssenceCoding */

        avio_read(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3203:

        descriptor->width = avio_rb32(pb);

        break;

    case 0x3202:

        descriptor->height = avio_rb32(pb);

        break;

    case 0x320C:

        descriptor->frame_layout = avio_r8(pb);

        break;

    case 0x320E:

        descriptor->aspect_ratio.num = avio_rb32(pb);

        descriptor->aspect_ratio.den = avio_rb32(pb);

        break;

    case 0x3301:

        descriptor->component_depth = avio_rb32(pb);

        break;

    case 0x3302:

        descriptor->horiz_subsampling = avio_rb32(pb);

        break;

    case 0x3308:

        descriptor->vert_subsampling = avio_rb32(pb);

        break;

    case 0x3D03:

        descriptor->sample_rate.num = avio_rb32(pb);

        descriptor->sample_rate.den = avio_rb32(pb);

        break;

    case 0x3D06: /* SoundEssenceCompression */

        avio_read(pb, descriptor->essence_codec_ul, 16);

        break;

    case 0x3D07:

        descriptor->channels = avio_rb32(pb);

        break;

    case 0x3D01:

        descriptor->bits_per_sample = avio_rb32(pb);

        break;

    case 0x3401:

        mxf_read_pixel_layout(pb, descriptor);

        break;

    default:

        /* Private uid used by SONY C0023S01.mxf */

        if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) {

            descriptor->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!descriptor->extradata)

                return AVERROR(ENOMEM);

            descriptor->extradata_size = size;

            avio_read(pb, descriptor->extradata, size);

        }

        break;

    }

    return 0;

}


int pt_removexattr(FsContext *ctx, const char *path, const char *name)

{

    char *buffer;

    int ret;

    buffer = rpath(ctx, path);

    ret = lremovexattr(path, name);

    g_free(buffer);

    return ret;

}


int64_t ff_ape_parse_tag(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    int file_size = avio_size(pb);

    uint32_t val, fields, tag_bytes;

    uint8_t buf[8];

    int64_t tag_start;

    int i;

    if (file_size < APE_TAG_FOOTER_BYTES)

        return 0;

    avio_seek(pb, file_size - APE_TAG_FOOTER_BYTES, SEEK_SET);

    avio_read(pb, buf, 8);     /* APETAGEX */

    if (strncmp(buf, "APETAGEX", 8)) {

        return 0;

    }

    val = avio_rl32(pb);       /* APE tag version */

    if (val > APE_TAG_VERSION) {

        av_log(s, AV_LOG_ERROR, "Unsupported tag version. (>=%d)\n", APE_TAG_VERSION);

        return 0;

    }

    tag_bytes = avio_rl32(pb); /* tag size */

    if (tag_bytes - APE_TAG_FOOTER_BYTES > (1024 * 1024 * 16)) {

        av_log(s, AV_LOG_ERROR, "Tag size is way too big\n");

        return 0;

    }

    tag_start = file_size - tag_bytes - APE_TAG_FOOTER_BYTES;

    if (tag_start < 0) {

        av_log(s, AV_LOG_ERROR, "Invalid tag size %u.\n", tag_bytes);

        return 0;

    }

    fields = avio_rl32(pb);    /* number of fields */

    if (fields > 65536) {

        av_log(s, AV_LOG_ERROR, "Too many tag fields (%d)\n", fields);

        return 0;

    }

    val = avio_rl32(pb);       /* flags */

    if (val & APE_TAG_FLAG_IS_HEADER) {

        av_log(s, AV_LOG_ERROR, "APE Tag is a header\n");

        return 0;

    }

    avio_seek(pb, file_size - tag_bytes, SEEK_SET);

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

        if (ape_tag_read_field(s) < 0) break;

    return tag_start;

}


static void* attribute_align_arg worker(void *v)

{

    ThreadContext *c = v;

    int our_job      = c->nb_jobs;

    int nb_threads   = c->nb_threads;

    unsigned int last_execute = 0;

    int self_id;

    pthread_mutex_lock(&c->current_job_lock);

    self_id = c->current_job++;

    for (;;) {

        while (our_job >= c->nb_jobs) {

            if (c->current_job == nb_threads + c->nb_jobs)

                pthread_cond_signal(&c->last_job_cond);

            while (last_execute == c->current_execute && !c->done)

                pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);

            last_execute = c->current_execute;

            our_job = self_id;

            if (c->done) {

                pthread_mutex_unlock(&c->current_job_lock);

                return NULL;

            }

        }

        pthread_mutex_unlock(&c->current_job_lock);

        c->rets[our_job % c->nb_rets] = c->func(c->ctx, c->arg, our_job, c->nb_jobs);

        pthread_mutex_lock(&c->current_job_lock);

        our_job = c->current_job++;

    }

}


static void pc87312_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = pc87312_realize;

    dc->reset = pc87312_reset;

    dc->vmsd = &vmstate_pc87312;

    dc->props = pc87312_properties;

}


static int mkv_field_order(MatroskaDemuxContext *matroska, int64_t field_order)

{

    int major, minor, micro, bttb = 0;

    /* workaround a bug in our Matroska muxer, introduced in version 57.36 alongside

     * this function, and fixed in 57.52 */

    if (sscanf(matroska->muxingapp, "Lavf%d.%d.%d", &major, &minor, &micro) == 3)

        bttb = (major == 57 && minor >= 36 && minor <= 51 && micro >= 100);

    switch (field_order) {

    case MATROSKA_VIDEO_FIELDORDER_PROGRESSIVE:

        return AV_FIELD_PROGRESSIVE;

    case MATROSKA_VIDEO_FIELDORDER_UNDETERMINED:

        return AV_FIELD_UNKNOWN;

    case MATROSKA_VIDEO_FIELDORDER_TT:

        return AV_FIELD_TT;

    case MATROSKA_VIDEO_FIELDORDER_BB:

        return AV_FIELD_BB;

    case MATROSKA_VIDEO_FIELDORDER_BT:

        return bttb ? AV_FIELD_TB : AV_FIELD_BT;

    case MATROSKA_VIDEO_FIELDORDER_TB:

        return bttb ? AV_FIELD_BT : AV_FIELD_TB;

    default:

        return AV_FIELD_UNKNOWN;

    }

}


av_cold void ff_fft_init_arm(FFTContext *s)

{

    int cpu_flags = av_get_cpu_flags();

    if (have_vfp(cpu_flags) && !have_vfpv3(cpu_flags)) {

        s->fft_calc     = ff_fft_calc_vfp;

#if CONFIG_MDCT

        s->imdct_half   = ff_imdct_half_vfp;

#endif

    }

    if (have_neon(cpu_flags)) {

        s->fft_permute  = ff_fft_permute_neon;

        s->fft_calc     = ff_fft_calc_neon;

#if CONFIG_MDCT

        s->imdct_calc   = ff_imdct_calc_neon;

        s->imdct_half   = ff_imdct_half_neon;

        s->mdct_calc    = ff_mdct_calc_neon;

        s->mdct_permutation = FF_MDCT_PERM_INTERLEAVE;

#endif

    }

}


unsigned long find_next_bit(const unsigned long *addr, unsigned long size,

			    unsigned long offset)

{

    const unsigned long *p = addr + BITOP_WORD(offset);

    unsigned long result = offset & ~(BITS_PER_LONG-1);

    unsigned long tmp;

    if (offset >= size) {

        return size;

    }

    size -= result;

    offset %= BITS_PER_LONG;

    if (offset) {

        tmp = *(p++);

        tmp &= (~0UL << offset);

        if (size < BITS_PER_LONG) {

            goto found_first;

        }

        if (tmp) {

            goto found_middle;

        }

        size -= BITS_PER_LONG;

        result += BITS_PER_LONG;

    }

    while (size & ~(BITS_PER_LONG-1)) {

        if ((tmp = *(p++))) {

            goto found_middle;

        }

        result += BITS_PER_LONG;

        size -= BITS_PER_LONG;

    }

    if (!size) {

        return result;

    }

    tmp = *p;

found_first:

    tmp &= (~0UL >> (BITS_PER_LONG - size));

    if (tmp == 0UL) {		/* Are any bits set? */

        return result + size;	/* Nope. */

    }

found_middle:

    return result + bitops_ffsl(tmp);

}


void migration_set_outgoing_channel(MigrationState *s,

                                    QIOChannel *ioc)

{

    QEMUFile *f = qemu_fopen_channel_output(ioc);

    s->to_dst_file = f;

    migrate_fd_connect(s);

}


static void qemu_wait_io_event_common(CPUState *cpu)

{

    if (cpu->stop) {

        cpu->stop = false;

        cpu->stopped = true;

        qemu_cond_broadcast(&qemu_pause_cond);

    }

    process_queued_cpu_work(cpu);

    cpu->thread_kicked = false;

}


static void ahci_test_identify(AHCIQState *ahci)
{
    uint16_t buff[256];
    unsigned px;
    int rc;
    uint16_t sect_size;
    const size_t buffsize = 512;
    g_assert(ahci != NULL);
    /**
     * This serves as a bit of a tutorial on AHCI device programming:
     *
     * (1) Create a data buffer for the IDENTIFY response to be sent to
     * (2) Create a Command Table buffer, where we will store the
     *     command and PRDT (Physical Region Descriptor Table)
     * (3) Construct an FIS host-to-device command structure, and write it to
     *     the top of the Command Table buffer.
     * (4) Create one or more Physical Region Descriptors (PRDs) that describe
     *     a location in memory where data may be stored/retrieved.
     * (5) Write these PRDTs to the bottom (offset 0x80) of the Command Table.
     * (6) Each AHCI port has up to 32 command slots. Each slot contains a
     *     header that points to a Command Table buffer. Pick an unused slot
     *     and update it to point to the Command Table we have built.
     * (7) Now: Command #n points to our Command Table, and our Command Table
     *     contains the FIS (that describes our command) and the PRDTL, which
     *     describes our buffer.
     * (8) We inform the HBA via PxCI (Command Issue) that the command in slot
     *     #n is ready for processing.
     */
    /* Pick the first implemented and running port */
    px = ahci_port_select(ahci);
    g_test_message("Selected port %u for test", px);
    /* Clear out the FIS Receive area and any pending interrupts. */
    ahci_port_clear(ahci, px);
    /* "Read" 512 bytes using CMD_IDENTIFY into the host buffer. */
    ahci_io(ahci, px, CMD_IDENTIFY, &buff, buffsize);
    /* Check serial number/version in the buffer */
    /* NB: IDENTIFY strings are packed in 16bit little endian chunks.
     * Since we copy byte-for-byte in ahci-test, on both LE and BE, we need to
     * unchunk this data. By contrast, ide-test copies 2 bytes at a time, and
     * as a consequence, only needs to unchunk the data on LE machines. */
    string_bswap16(&buff[10], 20);
    rc = memcmp(&buff[10], "testdisk            ", 20);
    g_assert_cmphex(rc, ==, 0);
    string_bswap16(&buff[23], 8);
    rc = memcmp(&buff[23], "version ", 8);
    g_assert_cmphex(rc, ==, 0);
}


static void rc4030_realize(DeviceState *dev, Error **errp)

{

    rc4030State *s = RC4030(dev);

    Object *o = OBJECT(dev);

    int i;

    s->periodic_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                     rc4030_periodic_timer, s);

    memory_region_init_io(&s->iomem_chipset, NULL, &rc4030_ops, s,

                          "rc4030.chipset", 0x300);

    memory_region_init_io(&s->iomem_jazzio, NULL, &jazzio_ops, s,

                          "rc4030.jazzio", 0x00001000);

    memory_region_init_rom_device(&s->dma_tt, o,

                                  &rc4030_dma_tt_ops, s, "dma-table",

                                  MAX_TL_ENTRIES * sizeof(dma_pagetable_entry),

                                  NULL);

    memory_region_init(&s->dma_tt_alias, o, "dma-table-alias", 0);

    memory_region_init(&s->dma_mr, o, "dma", INT32_MAX);

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

        memory_region_init_alias(&s->dma_mrs[i], o, "dma-alias",

                                 get_system_memory(), 0, DMA_PAGESIZE);

        memory_region_set_enabled(&s->dma_mrs[i], false);

        memory_region_add_subregion(&s->dma_mr, i * DMA_PAGESIZE,

                                    &s->dma_mrs[i]);

    }

    address_space_init(&s->dma_as, &s->dma_mr, "rc4030-dma");

}


static int fourxm_probe(AVProbeData *p)

{

    if ((AV_RL32(&p->buf[0]) != RIFF_TAG) ||

        (AV_RL32(&p->buf[8]) != _4XMV_TAG))

        return 0;

    return AVPROBE_SCORE_MAX;

}


void monitor_disas(Monitor *mon, CPUState *cpu,

                   target_ulong pc, int nb_insn, int is_physical)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int count, i;

    CPUDebug s;

    INIT_DISASSEMBLE_INFO(s.info, (FILE *)mon, monitor_fprintf);

    s.cpu = cpu;

    monitor_disas_is_physical = is_physical;

    s.info.read_memory_func = monitor_read_memory;

    s.info.print_address_func = generic_print_address;

    s.info.buffer_vma = pc;

    s.info.cap_arch = -1;

    s.info.cap_mode = 0;

#ifdef TARGET_WORDS_BIGENDIAN

    s.info.endian = BFD_ENDIAN_BIG;

#else

    s.info.endian = BFD_ENDIAN_LITTLE;

#endif

    if (cc->disas_set_info) {

        cc->disas_set_info(cpu, &s.info);

    }

    if (s.info.cap_arch >= 0 && cap_disas_monitor(&s.info, pc, nb_insn)) {

        return;

    }

    if (!s.info.print_insn) {

        monitor_printf(mon, "0x" TARGET_FMT_lx

                       ": Asm output not supported on this arch\n", pc);

        return;

    }

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

	monitor_printf(mon, "0x" TARGET_FMT_lx ":  ", pc);

        count = s.info.print_insn(pc, &s.info);

	monitor_printf(mon, "\n");

	if (count < 0)

	    break;

        pc += count;

    }

}


static struct omap_pwl_s *omap_pwl_init(MemoryRegion *system_memory,

                                        hwaddr base,

                                        omap_clk clk)

{

    struct omap_pwl_s *s = g_malloc0(sizeof(*s));

    omap_pwl_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_pwl_ops, s,

                          "omap-pwl", 0x800);

    memory_region_add_subregion(system_memory, base, &s->iomem);

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_pwl_clk_update, s, 1)[0]);

    return s;

}


static int amr_nb_decode_frame(AVCodecContext * avctx,

            void *data, int *data_size,

            uint8_t * buf, int buf_size)

{

    AMRContext *s = avctx->priv_data;

    uint8_t*amrData=buf;

    int offset=0;

    UWord8 toc, q, ft;

    Word16 serial[SERIAL_FRAMESIZE];   /* coded bits */

    Word16 *synth;

    UWord8 *packed_bits;

    static Word16 packed_size[16] = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0};

    int i;

    //printf("amr_decode_frame data_size=%i buf=0x%X buf_size=%d frameCount=%d!!\n",*data_size,buf,buf_size,s->frameCount);

    synth=data;

//    while(offset<buf_size)

    {

        toc=amrData[offset];

        /* read rest of the frame based on ToC byte */

        q  = (toc >> 2) & 0x01;

        ft = (toc >> 3) & 0x0F;

        //printf("offset=%d, packet_size=%d amrData= 0x%X %X %X %X\n",offset,packed_size[ft],amrData[offset],amrData[offset+1],amrData[offset+2],amrData[offset+3]);

        offset++;

        packed_bits=amrData+offset;

        offset+=packed_size[ft];

        //Unsort and unpack bits

        s->rx_type = UnpackBits(q, ft, packed_bits, &s->mode, &serial[1]);

        //We have a new frame

        s->frameCount++;

        if (s->rx_type == RX_NO_DATA)

        {

            s->mode = s->speech_decoder_state->prev_mode;

        }

        else {

            s->speech_decoder_state->prev_mode = s->mode;

        }

        /* if homed: check if this frame is another homing frame */

        if (s->reset_flag_old == 1)

        {

            /* only check until end of first subframe */

            s->reset_flag = decoder_homing_frame_test_first(&serial[1], s->mode);

        }

        /* produce encoder homing frame if homed & input=decoder homing frame */

        if ((s->reset_flag != 0) && (s->reset_flag_old != 0))

        {

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

            {

                synth[i] = EHF_MASK;

            }

        }

        else

        {

            /* decode frame */

            Speech_Decode_Frame(s->speech_decoder_state, s->mode, &serial[1], s->rx_type, synth);

        }

        //Each AMR-frame results in 160 16-bit samples

        *data_size+=160*2;

        synth+=160;

        /* if not homed: check whether current frame is a homing frame */

        if (s->reset_flag_old == 0)

        {

            /* check whole frame */

            s->reset_flag = decoder_homing_frame_test(&serial[1], s->mode);

        }

        /* reset decoder if current frame is a homing frame */

        if (s->reset_flag != 0)

        {

            Speech_Decode_Frame_reset(s->speech_decoder_state);

        }

        s->reset_flag_old = s->reset_flag;

    }

    return offset;

}


static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

    int ret;

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

    ffio_wfourcc(pb, "stbl");

    mov_write_stsd_tag(s, pb, mov, track);

    mov_write_stts_tag(pb, track);

    if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||

         track->par->codec_tag == MKTAG('r','t','p',' ')) &&

        track->has_keyframes && track->has_keyframes < track->entry)

        mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);

    if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)

        mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);

    if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&

        track->flags & MOV_TRACK_CTTS && track->entry) {

        if ((ret = mov_write_ctts_tag(pb, track)) < 0)

            return ret;

    }

    mov_write_stsc_tag(pb, track);

    mov_write_stsz_tag(pb, track);

    mov_write_stco_tag(pb, track);

    if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {

        ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);

    }

    if (track->par->codec_id == AV_CODEC_ID_OPUS) {

        mov_preroll_write_stbl_atoms(pb, track);

    }

    return update_size(pb, pos);

}


static av_cold void h264dsp_init_neon(H264DSPContext *c, const int bit_depth,

                                      const int chroma_format_idc)

{

    if (bit_depth == 8) {

    c->h264_v_loop_filter_luma   = ff_h264_v_loop_filter_luma_neon;

    c->h264_h_loop_filter_luma   = ff_h264_h_loop_filter_luma_neon;

    c->h264_v_loop_filter_chroma = ff_h264_v_loop_filter_chroma_neon;

    c->h264_h_loop_filter_chroma = ff_h264_h_loop_filter_chroma_neon;

    c->weight_h264_pixels_tab[0] = ff_weight_h264_pixels_16_neon;

    c->weight_h264_pixels_tab[1] = ff_weight_h264_pixels_8_neon;

    c->weight_h264_pixels_tab[2] = ff_weight_h264_pixels_4_neon;

    c->biweight_h264_pixels_tab[0] = ff_biweight_h264_pixels_16_neon;

    c->biweight_h264_pixels_tab[1] = ff_biweight_h264_pixels_8_neon;

    c->biweight_h264_pixels_tab[2] = ff_biweight_h264_pixels_4_neon;

    c->h264_idct_add        = ff_h264_idct_add_neon;

    c->h264_idct_dc_add     = ff_h264_idct_dc_add_neon;

    c->h264_idct_add16      = ff_h264_idct_add16_neon;

    c->h264_idct_add16intra = ff_h264_idct_add16intra_neon;

    if (chroma_format_idc == 1)

        c->h264_idct_add8   = ff_h264_idct_add8_neon;

    c->h264_idct8_add       = ff_h264_idct8_add_neon;

    c->h264_idct8_dc_add    = ff_h264_idct8_dc_add_neon;

    c->h264_idct8_add4      = ff_h264_idct8_add4_neon;

    }

}


ssize_t qemu_sendv_packet(VLANClientState *vc1, const struct iovec *iov,

                          int iovcnt)

{

    VLANState *vlan = vc1->vlan;

    VLANClientState *vc;

    ssize_t max_len = 0;

    if (vc1->link_down)

        return calc_iov_length(iov, iovcnt);

    for (vc = vlan->first_client; vc != NULL; vc = vc->next) {

        ssize_t len = 0;

        if (vc == vc1)

            continue;

        if (vc->link_down)

            len = calc_iov_length(iov, iovcnt);

        else if (vc->fd_readv)

            len = vc->fd_readv(vc->opaque, iov, iovcnt);

        else if (vc->fd_read)

            len = vc_sendv_compat(vc, iov, iovcnt);

        max_len = MAX(max_len, len);

    }

    return max_len;

}


static bool blit_region_is_unsafe(struct CirrusVGAState *s,

                                  int32_t pitch, int32_t addr)

{

    if (pitch < 0) {

        int64_t min = addr

            + ((int64_t)s->cirrus_blt_height-1) * pitch;

        int32_t max = addr

            + s->cirrus_blt_width;

        if (min < 0 || max >= s->vga.vram_size) {

            return true;

        }

    } else {

        int64_t max = addr

            + ((int64_t)s->cirrus_blt_height-1) * pitch

            + s->cirrus_blt_width;

        if (max >= s->vga.vram_size) {

            return true;

        }

    }

    return false;

}


static int rv10_decode_picture_header(MpegEncContext *s)

{

    int mb_count, pb_frame, marker, h, full_frame;

    /* skip packet header */

    h = get_bits(&s->gb, 8);

    if ((h & 0xc0) == 0xc0) {

        int len, pos;

        full_frame = 1;

        len = get_num(&s->gb);

        pos = get_num(&s->gb);

    } else {

        int seq, frame_size, pos;

        full_frame = 0;

        seq = get_bits(&s->gb, 8);

        frame_size = get_num(&s->gb);

        pos = get_num(&s->gb);

    }

    /* picture number */

    get_bits(&s->gb, 8);

    marker = get_bits(&s->gb, 1);

    if (get_bits(&s->gb, 1))

        s->pict_type = P_TYPE;

    else

        s->pict_type = I_TYPE;

    pb_frame = get_bits(&s->gb, 1);

#ifdef DEBUG

    printf("pict_type=%d pb_frame=%d\n", s->pict_type, pb_frame);

#endif

    if (pb_frame)

        return -1;

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

    if (s->pict_type == I_TYPE) {

        if (s->rv10_version == 3) {

            /* specific MPEG like DC coding not used */

            s->last_dc[0] = get_bits(&s->gb, 8);

            s->last_dc[1] = get_bits(&s->gb, 8);

            s->last_dc[2] = get_bits(&s->gb, 8);

#ifdef DEBUG

            printf("DC:%d %d %d\n",

                   s->last_dc[0],

                   s->last_dc[1],

                   s->last_dc[2]);

#endif

        }

    }

    /* if multiple packets per frame are sent, the position at which

       to display the macro blocks is coded here */

    if (!full_frame) {

        s->mb_x = get_bits(&s->gb, 6);	/* mb_x */

        s->mb_y = get_bits(&s->gb, 6);	/* mb_y */

        mb_count = get_bits(&s->gb, 12);

    } else {

        s->mb_x = 0;

        s->mb_y = 0;

        mb_count = s->mb_width * s->mb_height;

    }

    get_bits(&s->gb, 3);	/* ignored */

    s->f_code = 1;

    s->unrestricted_mv = 1;

#if 0

    s->h263_long_vectors = 1;

#endif

    return mb_count;

}


host_memory_backend_get_host_nodes(Object *obj, Visitor *v, const char *name,

                                   void *opaque, Error **errp)

{

    HostMemoryBackend *backend = MEMORY_BACKEND(obj);

    uint16List *host_nodes = NULL;

    uint16List **node = &host_nodes;

    unsigned long value;

    value = find_first_bit(backend->host_nodes, MAX_NODES);

    node = host_memory_append_node(node, value);

    if (value == MAX_NODES) {

        goto out;

    }

    do {

        value = find_next_bit(backend->host_nodes, MAX_NODES, value + 1);

        if (value == MAX_NODES) {

            break;

        }

        node = host_memory_append_node(node, value);

    } while (true);

out:

    visit_type_uint16List(v, name, &host_nodes, errp);

}


static int v4l2_read_header(AVFormatContext *s1)

{

    struct video_data *s = s1->priv_data;

    AVStream *st;

    int res = 0;

    uint32_t desired_format;

    enum AVCodecID codec_id = AV_CODEC_ID_NONE;

    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;

    struct v4l2_input input = { 0 };

    st = avformat_new_stream(s1, NULL);

    if (!st)

        return AVERROR(ENOMEM);

#if CONFIG_LIBV4L2

    /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL

       and errors will get sent to stderr */

    v4l2_log_file = fopen("/dev/null", "w");

#endif

    s->fd = device_open(s1);

    if (s->fd < 0)

        return s->fd;

    if (s->channel != -1) {

        /* set video input */

        av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);

        if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {

            res = AVERROR(errno);

            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));

            return res;

        }

    } else {

        /* get current video input */

        if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {

            res = AVERROR(errno);

            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));

            return res;

        }

    }

    /* enum input */

    input.index = s->channel;

    if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {

        res = AVERROR(errno);

        av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));

        return res;

    }

    s->std_id = input.std;

    av_log(s1, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s\n",

           s->channel, input.name);

    if (s->list_format) {

        list_formats(s1, s->fd, s->list_format);

        return AVERROR_EXIT;

    }

    if (s->list_standard) {

        list_standards(s1);

        return AVERROR_EXIT;

    }

    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    if (s->pixel_format) {

        AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);

        if (codec)

            s1->video_codec_id = codec->id;

        pix_fmt = av_get_pix_fmt(s->pixel_format);

        if (pix_fmt == AV_PIX_FMT_NONE && !codec) {

            av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",

                   s->pixel_format);

            return AVERROR(EINVAL);

        }

    }

    if (!s->width && !s->height) {

        struct v4l2_format fmt;

        av_log(s1, AV_LOG_VERBOSE,

               "Querying the device for the current frame size\n");

        fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

        if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {

            res = AVERROR(errno);

            av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));

            return res;

        }

        s->width  = fmt.fmt.pix.width;

        s->height = fmt.fmt.pix.height;

        av_log(s1, AV_LOG_VERBOSE,

               "Setting frame size to %dx%d\n", s->width, s->height);

    }

    res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);

    if (res < 0) {

        v4l2_close(s->fd);

        return res;

    }

    /* If no pixel_format was specified, the codec_id was not known up

     * until now. Set video_codec_id in the context, as codec_id will

     * not be available outside this function

     */

    if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)

        s1->video_codec_id = codec_id;

    if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)

        return res;

    s->frame_format = desired_format;

    if ((res = v4l2_set_parameters(s1)) < 0)

        return res;

    st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);

    s->frame_size =

        avpicture_get_size(st->codec->pix_fmt, s->width, s->height);

    if ((res = mmap_init(s1)) ||

        (res = mmap_start(s1)) < 0) {

        v4l2_close(s->fd);

        return res;

    }

    s->top_field_first = first_field(s->fd);

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = codec_id;

    if (codec_id == AV_CODEC_ID_RAWVIDEO)

        st->codec->codec_tag =

            avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);

    if (desired_format == V4L2_PIX_FMT_YVU420)

        st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');

    else if (desired_format == V4L2_PIX_FMT_YVU410)

        st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');

    st->codec->width = s->width;

    st->codec->height = s->height;

    st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;

    return 0;

}


avfilter_get_video_buffer_ref_from_arrays(uint8_t *data[4], int linesize[4], int perms,

                                          int w, int h, enum PixelFormat format)

{

    AVFilterBuffer *pic = av_mallocz(sizeof(AVFilterBuffer));

    AVFilterBufferRef *picref = av_mallocz(sizeof(AVFilterBufferRef));

    if (!pic || !picref)

        goto fail;

    picref->buf = pic;

    picref->buf->free = ff_avfilter_default_free_buffer;

    if (!(picref->video = av_mallocz(sizeof(AVFilterBufferRefVideoProps))))

        goto fail;

    picref->video->w = w;

    picref->video->h = h;

    /* make sure the buffer gets read permission or it's useless for output */

    picref->perms = perms | AV_PERM_READ;

    pic->refcount = 1;

    picref->type = AVMEDIA_TYPE_VIDEO;

    picref->format = format;

    memcpy(pic->data,        data,          sizeof(pic->data));

    memcpy(pic->linesize,    linesize,      sizeof(pic->linesize));

    memcpy(picref->data,     pic->data,     sizeof(picref->data));

    memcpy(picref->linesize, pic->linesize, sizeof(picref->linesize));

    return picref;

fail:

    if (picref && picref->video)

        av_free(picref->video);

    av_free(picref);

    av_free(pic);

    return NULL;

}