int h261_decode_picture_header(H261Context *h){

    MpegEncContext * const s = &h->s;

    int format, i;

    static int h261_framecounter = 0;

    uint32_t startcode;

    align_get_bits(&s->gb);

    startcode = (h->last_bits << (12 - (8-h->bits_left))) | get_bits(&s->gb, 20-8 - (8- h->bits_left));

    for(i= s->gb.size_in_bits - get_bits_count(&s->gb); i>24; i-=1){

        startcode = ((startcode << 1) | get_bits(&s->gb, 1)) & 0x000FFFFF;

        if(startcode == 0x10)

            break;

    }

    if (startcode != 0x10){

        av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");

        return -1;

    }

    /* temporal reference */

    s->picture_number = get_bits(&s->gb, 5); /* picture timestamp */

    /* PTYPE starts here */

    skip_bits1(&s->gb); /* split screen off */

    skip_bits1(&s->gb); /* camera  off */

    skip_bits1(&s->gb); /* freeze picture release off */

    format = get_bits1(&s->gb);

    //only 2 formats possible

    if (format == 0){//QCIF

        s->width = 176;

        s->height = 144;

        s->mb_width = 11;

        s->mb_height = 9;

    }else{//CIF

        s->width = 352;

        s->height = 288;

        s->mb_width = 22;

        s->mb_height = 18;

    }

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

    skip_bits1(&s->gb); /* still image mode off */

    skip_bits1(&s->gb); /* Reserved */

    /* PEI */

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

        skip_bits(&s->gb, 8);

    }

    //h261 has no I-FRAMES, pass the test in MPV_frame_start in mpegvideo.c

    if(h261_framecounter > 1)

        s->pict_type = P_TYPE;

    else

        s->pict_type = I_TYPE;

    h261_framecounter++;

    h->gob_number = 0;

    return 0;

}


void HELPER(srst)(CPUS390XState *env, uint32_t r1, uint32_t r2)

{

    uintptr_t ra = GETPC();

    uint64_t end, str;

    uint32_t len;

    uint8_t v, c = env->regs[0];

    /* Bits 32-55 must contain all 0.  */

    if (env->regs[0] & 0xffffff00u) {

        cpu_restore_state(ENV_GET_CPU(env), ra);

        program_interrupt(env, PGM_SPECIFICATION, 6);

    }

    str = get_address(env, r2);

    end = get_address(env, r1);

    /* Lest we fail to service interrupts in a timely manner, limit the

       amount of work we're willing to do.  For now, let's cap at 8k.  */

    for (len = 0; len < 0x2000; ++len) {

        if (str + len == end) {

            /* Character not found.  R1 & R2 are unmodified.  */

            env->cc_op = 2;

            return;

        }

        v = cpu_ldub_data_ra(env, str + len, ra);

        if (v == c) {

            /* Character found.  Set R1 to the location; R2 is unmodified.  */

            env->cc_op = 1;

            set_address(env, r1, str + len);

            return;

        }

    }

    /* CPU-determined bytes processed.  Advance R2 to next byte to process.  */

    env->cc_op = 3;

    set_address(env, r2, str + len);

}


void qemu_vfree(void *ptr)

{

    /* may be useful some day, but currently we do not need to free */

}


int qemu_sem_timedwait(QemuSemaphore *sem, int ms)

{

    int rc = WaitForSingleObject(sem->sema, ms);

    if (rc == WAIT_OBJECT_0) {

        return 0;

    }

    if (rc != WAIT_TIMEOUT) {

        error_exit(GetLastError(), __func__);

    }

    return -1;

}


static void disas_simd_3same_int(DisasContext *s, uint32_t insn)

{

    int is_q = extract32(insn, 30, 1);

    int u = extract32(insn, 29, 1);

    int size = extract32(insn, 22, 2);

    int opcode = extract32(insn, 11, 5);

    int rm = extract32(insn, 16, 5);

    int rn = extract32(insn, 5, 5);

    int rd = extract32(insn, 0, 5);

    int pass;

    switch (opcode) {

    case 0x13: /* MUL, PMUL */

        if (u && size != 0) {

            unallocated_encoding(s);

            return;

        }

        /* fall through */

    case 0x0: /* SHADD, UHADD */

    case 0x2: /* SRHADD, URHADD */

    case 0x4: /* SHSUB, UHSUB */

    case 0xc: /* SMAX, UMAX */

    case 0xd: /* SMIN, UMIN */

    case 0xe: /* SABD, UABD */

    case 0xf: /* SABA, UABA */

    case 0x12: /* MLA, MLS */

        if (size == 3) {

            unallocated_encoding(s);

            return;

        }

        break;

    case 0x16: /* SQDMULH, SQRDMULH */

        if (size == 0 || size == 3) {

            unallocated_encoding(s);

            return;

        }

        break;

    default:

        if (size == 3 && !is_q) {

            unallocated_encoding(s);

            return;

        }

        break;

    }

    if (!fp_access_check(s)) {

        return;

    }

    if (size == 3) {

        for (pass = 0; pass < (is_q ? 2 : 1); pass++) {

            TCGv_i64 tcg_op1 = tcg_temp_new_i64();

            TCGv_i64 tcg_op2 = tcg_temp_new_i64();

            TCGv_i64 tcg_res = tcg_temp_new_i64();

            read_vec_element(s, tcg_op1, rn, pass, MO_64);

            read_vec_element(s, tcg_op2, rm, pass, MO_64);

            handle_3same_64(s, opcode, u, tcg_res, tcg_op1, tcg_op2);

            write_vec_element(s, tcg_res, rd, pass, MO_64);

            tcg_temp_free_i64(tcg_res);

            tcg_temp_free_i64(tcg_op1);

            tcg_temp_free_i64(tcg_op2);

        }

    } else {

        for (pass = 0; pass < (is_q ? 4 : 2); pass++) {

            TCGv_i32 tcg_op1 = tcg_temp_new_i32();

            TCGv_i32 tcg_op2 = tcg_temp_new_i32();

            TCGv_i32 tcg_res = tcg_temp_new_i32();

            NeonGenTwoOpFn *genfn = NULL;

            NeonGenTwoOpEnvFn *genenvfn = NULL;

            read_vec_element_i32(s, tcg_op1, rn, pass, MO_32);

            read_vec_element_i32(s, tcg_op2, rm, pass, MO_32);

            switch (opcode) {

            case 0x0: /* SHADD, UHADD */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_hadd_s8, gen_helper_neon_hadd_u8 },

                    { gen_helper_neon_hadd_s16, gen_helper_neon_hadd_u16 },

                    { gen_helper_neon_hadd_s32, gen_helper_neon_hadd_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x1: /* SQADD, UQADD */

            {

                static NeonGenTwoOpEnvFn * const fns[3][2] = {

                    { gen_helper_neon_qadd_s8, gen_helper_neon_qadd_u8 },

                    { gen_helper_neon_qadd_s16, gen_helper_neon_qadd_u16 },

                    { gen_helper_neon_qadd_s32, gen_helper_neon_qadd_u32 },

                };

                genenvfn = fns[size][u];

                break;

            }

            case 0x2: /* SRHADD, URHADD */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_rhadd_s8, gen_helper_neon_rhadd_u8 },

                    { gen_helper_neon_rhadd_s16, gen_helper_neon_rhadd_u16 },

                    { gen_helper_neon_rhadd_s32, gen_helper_neon_rhadd_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x4: /* SHSUB, UHSUB */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_hsub_s8, gen_helper_neon_hsub_u8 },

                    { gen_helper_neon_hsub_s16, gen_helper_neon_hsub_u16 },

                    { gen_helper_neon_hsub_s32, gen_helper_neon_hsub_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x5: /* SQSUB, UQSUB */

            {

                static NeonGenTwoOpEnvFn * const fns[3][2] = {

                    { gen_helper_neon_qsub_s8, gen_helper_neon_qsub_u8 },

                    { gen_helper_neon_qsub_s16, gen_helper_neon_qsub_u16 },

                    { gen_helper_neon_qsub_s32, gen_helper_neon_qsub_u32 },

                };

                genenvfn = fns[size][u];

                break;

            }

            case 0x6: /* CMGT, CMHI */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_cgt_s8, gen_helper_neon_cgt_u8 },

                    { gen_helper_neon_cgt_s16, gen_helper_neon_cgt_u16 },

                    { gen_helper_neon_cgt_s32, gen_helper_neon_cgt_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x7: /* CMGE, CMHS */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_cge_s8, gen_helper_neon_cge_u8 },

                    { gen_helper_neon_cge_s16, gen_helper_neon_cge_u16 },

                    { gen_helper_neon_cge_s32, gen_helper_neon_cge_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x8: /* SSHL, USHL */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_shl_s8, gen_helper_neon_shl_u8 },

                    { gen_helper_neon_shl_s16, gen_helper_neon_shl_u16 },

                    { gen_helper_neon_shl_s32, gen_helper_neon_shl_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x9: /* SQSHL, UQSHL */

            {

                static NeonGenTwoOpEnvFn * const fns[3][2] = {

                    { gen_helper_neon_qshl_s8, gen_helper_neon_qshl_u8 },

                    { gen_helper_neon_qshl_s16, gen_helper_neon_qshl_u16 },

                    { gen_helper_neon_qshl_s32, gen_helper_neon_qshl_u32 },

                };

                genenvfn = fns[size][u];

                break;

            }

            case 0xa: /* SRSHL, URSHL */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_rshl_s8, gen_helper_neon_rshl_u8 },

                    { gen_helper_neon_rshl_s16, gen_helper_neon_rshl_u16 },

                    { gen_helper_neon_rshl_s32, gen_helper_neon_rshl_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0xb: /* SQRSHL, UQRSHL */

            {

                static NeonGenTwoOpEnvFn * const fns[3][2] = {

                    { gen_helper_neon_qrshl_s8, gen_helper_neon_qrshl_u8 },

                    { gen_helper_neon_qrshl_s16, gen_helper_neon_qrshl_u16 },

                    { gen_helper_neon_qrshl_s32, gen_helper_neon_qrshl_u32 },

                };

                genenvfn = fns[size][u];

                break;

            }

            case 0xc: /* SMAX, UMAX */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_max_s8, gen_helper_neon_max_u8 },

                    { gen_helper_neon_max_s16, gen_helper_neon_max_u16 },

                    { gen_max_s32, gen_max_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0xd: /* SMIN, UMIN */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_min_s8, gen_helper_neon_min_u8 },

                    { gen_helper_neon_min_s16, gen_helper_neon_min_u16 },

                    { gen_min_s32, gen_min_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0xe: /* SABD, UABD */

            case 0xf: /* SABA, UABA */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_abd_s8, gen_helper_neon_abd_u8 },

                    { gen_helper_neon_abd_s16, gen_helper_neon_abd_u16 },

                    { gen_helper_neon_abd_s32, gen_helper_neon_abd_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x10: /* ADD, SUB */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_add_u8, gen_helper_neon_sub_u8 },

                    { gen_helper_neon_add_u16, gen_helper_neon_sub_u16 },

                    { tcg_gen_add_i32, tcg_gen_sub_i32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x11: /* CMTST, CMEQ */

            {

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_tst_u8, gen_helper_neon_ceq_u8 },

                    { gen_helper_neon_tst_u16, gen_helper_neon_ceq_u16 },

                    { gen_helper_neon_tst_u32, gen_helper_neon_ceq_u32 },

                };

                genfn = fns[size][u];

                break;

            }

            case 0x13: /* MUL, PMUL */

                if (u) {

                    /* PMUL */

                    assert(size == 0);

                    genfn = gen_helper_neon_mul_p8;

                    break;

                }

                /* fall through : MUL */

            case 0x12: /* MLA, MLS */

            {

                static NeonGenTwoOpFn * const fns[3] = {

                    gen_helper_neon_mul_u8,

                    gen_helper_neon_mul_u16,

                    tcg_gen_mul_i32,

                };

                genfn = fns[size];

                break;

            }

            case 0x16: /* SQDMULH, SQRDMULH */

            {

                static NeonGenTwoOpEnvFn * const fns[2][2] = {

                    { gen_helper_neon_qdmulh_s16, gen_helper_neon_qrdmulh_s16 },

                    { gen_helper_neon_qdmulh_s32, gen_helper_neon_qrdmulh_s32 },

                };

                assert(size == 1 || size == 2);

                genenvfn = fns[size - 1][u];

                break;

            }

            default:

                g_assert_not_reached();

            }

            if (genenvfn) {

                genenvfn(tcg_res, cpu_env, tcg_op1, tcg_op2);

            } else {

                genfn(tcg_res, tcg_op1, tcg_op2);

            }

            if (opcode == 0xf || opcode == 0x12) {

                /* SABA, UABA, MLA, MLS: accumulating ops */

                static NeonGenTwoOpFn * const fns[3][2] = {

                    { gen_helper_neon_add_u8, gen_helper_neon_sub_u8 },

                    { gen_helper_neon_add_u16, gen_helper_neon_sub_u16 },

                    { tcg_gen_add_i32, tcg_gen_sub_i32 },

                };

                bool is_sub = (opcode == 0x12 && u); /* MLS */

                genfn = fns[size][is_sub];

                read_vec_element_i32(s, tcg_op1, rd, pass, MO_32);

                genfn(tcg_res, tcg_op1, tcg_res);

            }

            write_vec_element_i32(s, tcg_res, rd, pass, MO_32);

            tcg_temp_free_i32(tcg_res);

            tcg_temp_free_i32(tcg_op1);

            tcg_temp_free_i32(tcg_op2);

        }

    }

    if (!is_q) {

        clear_vec_high(s, rd);

    }

}


static ssize_t proxy_preadv(FsContext *ctx, V9fsFidOpenState *fs,

                            const struct iovec *iov,

                            int iovcnt, off_t offset)

{

    ssize_t ret;

#ifdef CONFIG_PREADV

    ret = preadv(fs->fd, iov, iovcnt, offset);

#else

    ret = lseek(fs->fd, offset, SEEK_SET);

    if (ret >= 0) {

        ret = readv(fs->fd, iov, iovcnt);

    }

#endif

    return ret;

}


MemoryRegion *address_space_translate(AddressSpace *as, hwaddr addr,

                                      hwaddr *xlat, hwaddr *plen,

                                      bool is_write)

{

    IOMMUTLBEntry iotlb;

    MemoryRegionSection *section;

    MemoryRegion *mr;

    hwaddr len = *plen;

    for (;;) {

        section = address_space_translate_internal(as->dispatch, addr, &addr, &len, true);

        mr = section->mr;

        if (!mr->iommu_ops) {

            break;

        }

        iotlb = mr->iommu_ops->translate(mr, addr);

        addr = ((iotlb.translated_addr & ~iotlb.addr_mask)

                | (addr & iotlb.addr_mask));

        len = MIN(len, (addr | iotlb.addr_mask) - addr + 1);

        if (!(iotlb.perm & (1 << is_write))) {

            mr = &io_mem_unassigned;

            break;

        }

        as = iotlb.target_as;

    }

    *plen = len;

    *xlat = addr;

    return mr;

}


static void shpc_set_status(SHPCDevice *shpc,

                            int slot, uint8_t value, uint16_t msk)

{

    uint8_t *status = shpc->config + SHPC_SLOT_STATUS(slot);

    pci_word_test_and_clear_mask(status, msk);

    pci_word_test_and_set_mask(status, value << (ffs(msk) - 1));

}


static void prom_set(uint32_t* prom_buf, int index, const char *string, ...)

{

    va_list ap;

    int32_t table_addr;

    if (index >= ENVP_NB_ENTRIES)

        return;

    if (string == NULL) {

        prom_buf[index] = 0;

        return;

    }

    table_addr = sizeof(int32_t) * ENVP_NB_ENTRIES + index * ENVP_ENTRY_SIZE;

    prom_buf[index] = tswap32(ENVP_ADDR + table_addr);

    va_start(ap, string);

    vsnprintf((char *)prom_buf + table_addr, ENVP_ENTRY_SIZE, string, ap);

    va_end(ap);

}


DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)

{

    DriveInfo *dinfo;

    /* seek interface, bus and unit */

    TAILQ_FOREACH(dinfo, &drives, next) {

        if (dinfo->type == type &&

	    dinfo->bus == bus &&

	    dinfo->unit == unit)

            return dinfo;

    }

    return NULL;

}


static void do_rematrixing(AC3DecodeContext *ctx)

{

    ac3_audio_block *ab = &ctx->audio_block;

    uint8_t bnd1 = 13, bnd2 = 25, bnd3 = 37, bnd4 = 61;

    uint8_t bndend;

    bndend = FFMIN(ab->endmant[0], ab->endmant[1]);

    if (ab->rematflg & 1)

        _do_rematrixing(ctx, bnd1, bnd2);

    if (ab->rematflg & 2)

        _do_rematrixing(ctx, bnd2, bnd3);

    if (ab->rematflg & 4) {

        if (ab->cplbegf > 0 && ab->cplbegf <= 2 && (ab->flags & AC3_AB_CPLINU))

            _do_rematrixing(ctx, bnd3, bndend);

        else {

            _do_rematrixing(ctx, bnd3, bnd4);

            if (ab->rematflg & 8)

                _do_rematrixing(ctx, bnd4, bndend);

        }

    }

}


static void acpi_table_install(const char unsigned *blob, size_t bloblen,

                               bool has_header,

                               const struct AcpiTableOptions *hdrs,

                               Error **errp)

{

    size_t body_start;

    const char unsigned *hdr_src;

    size_t body_size, acpi_payload_size;

    struct acpi_table_header *ext_hdr;

    unsigned changed_fields;

    /* Calculate where the ACPI table body starts within the blob, plus where

     * to copy the ACPI table header from.

     */

    if (has_header) {

        /*   _length             | ACPI header in blob | blob body

         *   ^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^

         *   ACPI_TABLE_PFX_SIZE     sizeof dfl_hdr      body_size

         *                           == body_start

         *

         *                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

         *                           acpi_payload_size == bloblen

         */

        body_start = sizeof dfl_hdr;

        if (bloblen < body_start) {

            error_setg(errp, "ACPI table claiming to have header is too "

                       "short, available: %zu, expected: %zu", bloblen,

                       body_start);

            return;

        }

        hdr_src = blob;

    } else {

        /*   _length             | ACPI header in template | blob body

         *   ^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^

         *   ACPI_TABLE_PFX_SIZE       sizeof dfl_hdr        body_size

         *                                                   == bloblen

         *

         *                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

         *                                  acpi_payload_size

         */

        body_start = 0;

        hdr_src = dfl_hdr;

    }

    body_size = bloblen - body_start;

    acpi_payload_size = sizeof dfl_hdr + body_size;

    if (acpi_payload_size > UINT16_MAX) {

        error_setg(errp, "ACPI table too big, requested: %zu, max: %u",

                   acpi_payload_size, (unsigned)UINT16_MAX);

        return;

    }

    /* We won't fail from here on. Initialize / extend the globals. */

    if (acpi_tables == NULL) {

        acpi_tables_len = sizeof(uint16_t);

        acpi_tables = g_malloc0(acpi_tables_len);

    }

    acpi_tables = g_realloc(acpi_tables, acpi_tables_len +

                                         ACPI_TABLE_PFX_SIZE +

                                         sizeof dfl_hdr + body_size);

    ext_hdr = (struct acpi_table_header *)(acpi_tables + acpi_tables_len);

    acpi_tables_len += ACPI_TABLE_PFX_SIZE;

    memcpy(acpi_tables + acpi_tables_len, hdr_src, sizeof dfl_hdr);

    acpi_tables_len += sizeof dfl_hdr;

    if (blob != NULL) {

        memcpy(acpi_tables + acpi_tables_len, blob + body_start, body_size);

        acpi_tables_len += body_size;

    }

    /* increase number of tables */

    stw_le_p(acpi_tables, lduw_le_p(acpi_tables) + 1u);

    /* Update the header fields. The strings need not be NUL-terminated. */

    changed_fields = 0;

    ext_hdr->_length = cpu_to_le16(acpi_payload_size);

    if (hdrs->has_sig) {

        strncpy(ext_hdr->sig, hdrs->sig, sizeof ext_hdr->sig);

        ++changed_fields;

    }

    if (has_header && le32_to_cpu(ext_hdr->length) != acpi_payload_size) {

        fprintf(stderr,

                "warning: ACPI table has wrong length, header says "

                "%" PRIu32 ", actual size %zu bytes\n",

                le32_to_cpu(ext_hdr->length), acpi_payload_size);

    }

    ext_hdr->length = cpu_to_le32(acpi_payload_size);

    if (hdrs->has_rev) {

        ext_hdr->revision = hdrs->rev;

        ++changed_fields;

    }

    ext_hdr->checksum = 0;

    if (hdrs->has_oem_id) {

        strncpy(ext_hdr->oem_id, hdrs->oem_id, sizeof ext_hdr->oem_id);

        ++changed_fields;

    }

    if (hdrs->has_oem_table_id) {

        strncpy(ext_hdr->oem_table_id, hdrs->oem_table_id,

                sizeof ext_hdr->oem_table_id);

        ++changed_fields;

    }

    if (hdrs->has_oem_rev) {

        ext_hdr->oem_revision = cpu_to_le32(hdrs->oem_rev);

        ++changed_fields;

    }

    if (hdrs->has_asl_compiler_id) {

        strncpy(ext_hdr->asl_compiler_id, hdrs->asl_compiler_id,

                sizeof ext_hdr->asl_compiler_id);

        ++changed_fields;

    }

    if (hdrs->has_asl_compiler_rev) {

        ext_hdr->asl_compiler_revision = cpu_to_le32(hdrs->asl_compiler_rev);

        ++changed_fields;

    }

    if (!has_header && changed_fields == 0) {

        warn_report("ACPI table: no headers are specified");

    }

    /* recalculate checksum */

    ext_hdr->checksum = acpi_checksum((const char unsigned *)ext_hdr +

                                      ACPI_TABLE_PFX_SIZE, acpi_payload_size);

}


static void spapr_hotplug_req_event(uint8_t hp_id, uint8_t hp_action,

                                    sPAPRDRConnectorType drc_type,

                                    union drc_identifier *drc_id)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    struct hp_log_full *new_hp;

    struct rtas_error_log *hdr;

    struct rtas_event_log_v6 *v6hdr;

    struct rtas_event_log_v6_maina *maina;

    struct rtas_event_log_v6_mainb *mainb;

    struct rtas_event_log_v6_hp *hp;

    new_hp = g_malloc0(sizeof(struct hp_log_full));

    hdr = &new_hp->hdr;

    v6hdr = &new_hp->v6hdr;

    maina = &new_hp->maina;

    mainb = &new_hp->mainb;

    hp = &new_hp->hp;

    hdr->summary = cpu_to_be32(RTAS_LOG_VERSION_6

                               | RTAS_LOG_SEVERITY_EVENT

                               | RTAS_LOG_DISPOSITION_NOT_RECOVERED

                               | RTAS_LOG_OPTIONAL_PART_PRESENT

                               | RTAS_LOG_INITIATOR_HOTPLUG

                               | RTAS_LOG_TYPE_HOTPLUG);

    hdr->extended_length = cpu_to_be32(sizeof(*new_hp)

                                       - sizeof(new_hp->hdr));

    spapr_init_v6hdr(v6hdr);

    spapr_init_maina(maina, 3 /* Main-A, Main-B, HP */);

    mainb->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_MAINB);

    mainb->hdr.section_length = cpu_to_be16(sizeof(*mainb));

    mainb->subsystem_id = 0x80; /* External environment */

    mainb->event_severity = 0x00; /* Informational / non-error */

    mainb->event_subtype = 0x00; /* Normal shutdown */

    hp->hdr.section_id = cpu_to_be16(RTAS_LOG_V6_SECTION_ID_HOTPLUG);

    hp->hdr.section_length = cpu_to_be16(sizeof(*hp));

    hp->hdr.section_version = 1; /* includes extended modifier */

    hp->hotplug_action = hp_action;

    hp->hotplug_identifier = hp_id;

    switch (drc_type) {

    case SPAPR_DR_CONNECTOR_TYPE_PCI:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_PCI;

        if (hp->hotplug_action == RTAS_LOG_V6_HP_ACTION_ADD) {

            spapr_hotplug_set_signalled(drc_id->index);

        }

        break;

    case SPAPR_DR_CONNECTOR_TYPE_LMB:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_MEMORY;

        break;

    case SPAPR_DR_CONNECTOR_TYPE_CPU:

        hp->hotplug_type = RTAS_LOG_V6_HP_TYPE_CPU;

        break;

    default:

        /* we shouldn't be signaling hotplug events for resources

         * that don't support them

         */

        g_assert(false);

        return;

    }

    if (hp_id == RTAS_LOG_V6_HP_ID_DRC_COUNT) {

        hp->drc_id.count = cpu_to_be32(drc_id->count);

    } else if (hp_id == RTAS_LOG_V6_HP_ID_DRC_INDEX) {

        hp->drc_id.index = cpu_to_be32(drc_id->index);

    } else if (hp_id == RTAS_LOG_V6_HP_ID_DRC_COUNT_INDEXED) {

        /* we should not be using count_indexed value unless the guest

         * supports dedicated hotplug event source

         */

        g_assert(spapr_ovec_test(spapr->ov5_cas, OV5_HP_EVT));

        hp->drc_id.count_indexed.count =

            cpu_to_be32(drc_id->count_indexed.count);

        hp->drc_id.count_indexed.index =

            cpu_to_be32(drc_id->count_indexed.index);

    }

    rtas_event_log_queue(RTAS_LOG_TYPE_HOTPLUG, new_hp, true);

    qemu_irq_pulse(xics_get_qirq(XICS_FABRIC(spapr),

                                 rtas_event_log_to_irq(spapr,

                                                       RTAS_LOG_TYPE_HOTPLUG)));

}


void qemu_aio_flush(void)

{

    AioHandler *node;

    int ret;

    do {

        ret = 0;

	/*

	 * If there are pending emulated aio start them now so flush

	 * will be able to return 1.

	 */

        qemu_aio_wait();

        QLIST_FOREACH(node, &aio_handlers, node) {

            if (node->io_flush) {

                ret |= node->io_flush(node->opaque);

            }

        }

    } while (qemu_bh_poll() || ret > 0);

}


static void gen_srs(DisasContext *s,

                    uint32_t mode, uint32_t amode, bool writeback)

{

    int32_t offset;

    TCGv_i32 addr = tcg_temp_new_i32();

    TCGv_i32 tmp = tcg_const_i32(mode);

    gen_helper_get_r13_banked(addr, cpu_env, tmp);

    tcg_temp_free_i32(tmp);

    switch (amode) {

    case 0: /* DA */

        offset = -4;

        break;

    case 1: /* IA */

        offset = 0;

        break;

    case 2: /* DB */

        offset = -8;

        break;

    case 3: /* IB */

        offset = 4;

        break;

    default:

        abort();

    }

    tcg_gen_addi_i32(addr, addr, offset);

    tmp = load_reg(s, 14);

    gen_aa32_st32(tmp, addr, get_mem_index(s));

    tcg_temp_free_i32(tmp);

    tmp = load_cpu_field(spsr);

    tcg_gen_addi_i32(addr, addr, 4);

    gen_aa32_st32(tmp, addr, get_mem_index(s));

    tcg_temp_free_i32(tmp);

    if (writeback) {

        switch (amode) {

        case 0:

            offset = -8;

            break;

        case 1:

            offset = 4;

            break;

        case 2:

            offset = -4;

            break;

        case 3:

            offset = 0;

            break;

        default:

            abort();

        }

        tcg_gen_addi_i32(addr, addr, offset);

        tmp = tcg_const_i32(mode);

        gen_helper_set_r13_banked(cpu_env, tmp, addr);

        tcg_temp_free_i32(tmp);

    }

    tcg_temp_free_i32(addr);

}


void kvm_mips_reset_vcpu(MIPSCPU *cpu)

{

    CPUMIPSState *env = &cpu->env;

    if (env->CP0_Config1 & (1 << CP0C1_FP)) {

        fprintf(stderr, "Warning: FPU not supported with KVM, disabling\n");

        env->CP0_Config1 &= ~(1 << CP0C1_FP);

    }

    DPRINTF("%s\n", __func__);

}


static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,

                               BlockDriverAmendStatusCB *status_cb,

                               void *cb_opaque)

{

    BDRVQcow2State *s = bs->opaque;

    int old_version = s->qcow_version, new_version = old_version;

    uint64_t new_size = 0;

    const char *backing_file = NULL, *backing_format = NULL;

    bool lazy_refcounts = s->use_lazy_refcounts;

    const char *compat = NULL;

    uint64_t cluster_size = s->cluster_size;

    bool encrypt;

    int refcount_bits = s->refcount_bits;

    Error *local_err = NULL;

    int ret;

    QemuOptDesc *desc = opts->list->desc;

    Qcow2AmendHelperCBInfo helper_cb_info;

    while (desc && desc->name) {

        if (!qemu_opt_find(opts, desc->name)) {

            /* only change explicitly defined options */

            desc++;

            continue;

        }

        if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {

            compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);

            if (!compat) {

                /* preserve default */

            } else if (!strcmp(compat, "0.10")) {

                new_version = 2;

            } else if (!strcmp(compat, "1.1")) {

                new_version = 3;

            } else {

                error_report("Unknown compatibility level %s", compat);

                return -EINVAL;

            }

        } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {

            error_report("Cannot change preallocation mode");

            return -ENOTSUP;

        } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {

            new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);

        } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {

            backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);

        } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {

            backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);

        } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {

            encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,

                                        !!s->cipher);

            if (encrypt != !!s->cipher) {

                error_report("Changing the encryption flag is not supported");

                return -ENOTSUP;

            }

        } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {

            cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,

                                             cluster_size);

            if (cluster_size != s->cluster_size) {

                error_report("Changing the cluster size is not supported");

                return -ENOTSUP;

            }

        } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {

            lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,

                                               lazy_refcounts);

        } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {

            refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,

                                                refcount_bits);

            if (refcount_bits <= 0 || refcount_bits > 64 ||

                !is_power_of_2(refcount_bits))

            {

                error_report("Refcount width must be a power of two and may "

                             "not exceed 64 bits");

                return -EINVAL;

            }

        } else {

            /* if this point is reached, this probably means a new option was

             * added without having it covered here */

            abort();

        }

        desc++;

    }

    helper_cb_info = (Qcow2AmendHelperCBInfo){

        .original_status_cb = status_cb,

        .original_cb_opaque = cb_opaque,

        .total_operations = (new_version < old_version)

                          + (s->refcount_bits != refcount_bits)

    };

    /* Upgrade first (some features may require compat=1.1) */

    if (new_version > old_version) {

        s->qcow_version = new_version;

        ret = qcow2_update_header(bs);

        if (ret < 0) {

            s->qcow_version = old_version;

            return ret;

        }

    }

    if (s->refcount_bits != refcount_bits) {

        int refcount_order = ctz32(refcount_bits);

        if (new_version < 3 && refcount_bits != 16) {

            error_report("Different refcount widths than 16 bits require "

                         "compatibility level 1.1 or above (use compat=1.1 or "

                         "greater)");

            return -EINVAL;

        }

        helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;

        ret = qcow2_change_refcount_order(bs, refcount_order,

                                          &qcow2_amend_helper_cb,

                                          &helper_cb_info, &local_err);

        if (ret < 0) {

            error_report_err(local_err);

            return ret;

        }

    }

    if (backing_file || backing_format) {

        ret = qcow2_change_backing_file(bs,

                    backing_file ?: s->image_backing_file,

                    backing_format ?: s->image_backing_format);

        if (ret < 0) {

            return ret;

        }

    }

    if (s->use_lazy_refcounts != lazy_refcounts) {

        if (lazy_refcounts) {

            if (new_version < 3) {

                error_report("Lazy refcounts only supported with compatibility "

                             "level 1.1 and above (use compat=1.1 or greater)");

                return -EINVAL;

            }

            s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;

            ret = qcow2_update_header(bs);

            if (ret < 0) {

                s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;

                return ret;

            }

            s->use_lazy_refcounts = true;

        } else {

            /* make image clean first */

            ret = qcow2_mark_clean(bs);

            if (ret < 0) {

                return ret;

            }

            /* now disallow lazy refcounts */

            s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;

            ret = qcow2_update_header(bs);

            if (ret < 0) {

                s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;

                return ret;

            }

            s->use_lazy_refcounts = false;

        }

    }

    if (new_size) {

        BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);

        ret = blk_insert_bs(blk, bs, &local_err);

        if (ret < 0) {

            error_report_err(local_err);

            blk_unref(blk);

            return ret;

        }

        ret = blk_truncate(blk, new_size, &local_err);

        blk_unref(blk);

        if (ret < 0) {

            error_report_err(local_err);

            return ret;

        }

    }

    /* Downgrade last (so unsupported features can be removed before) */

    if (new_version < old_version) {

        helper_cb_info.current_operation = QCOW2_DOWNGRADING;

        ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,

                              &helper_cb_info);

        if (ret < 0) {

            return ret;

        }

    }

    return 0;

}


static void bmdma_map(PCIDevice *pci_dev, int region_num,

                    pcibus_t addr, pcibus_t size, int type)

{

    PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, pci_dev);

    int i;

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

        BMDMAState *bm = &d->bmdma[i];

        d->bus[i].bmdma = bm;

        bm->bus = d->bus+i;

        bm->pci_dev = d;

        qemu_add_vm_change_state_handler(ide_dma_restart_cb, bm);

        register_ioport_write(addr, 1, 1, bmdma_cmd_writeb, bm);

        register_ioport_write(addr + 1, 3, 1, bmdma_writeb, bm);

        register_ioport_read(addr, 4, 1, bmdma_readb, bm);

        register_ioport_write(addr + 4, 4, 1, bmdma_addr_writeb, bm);

        register_ioport_read(addr + 4, 4, 1, bmdma_addr_readb, bm);

        register_ioport_write(addr + 4, 4, 2, bmdma_addr_writew, bm);

        register_ioport_read(addr + 4, 4, 2, bmdma_addr_readw, bm);

        register_ioport_write(addr + 4, 4, 4, bmdma_addr_writel, bm);

        register_ioport_read(addr + 4, 4, 4, bmdma_addr_readl, bm);

        addr += 8;

    }

}


static void pcnet_transmit(PCNetState *s)

{

    target_phys_addr_t xmit_cxda = 0;

    int count = CSR_XMTRL(s)-1;

    s->xmit_pos = -1;

    if (!CSR_TXON(s)) {

        s->csr[0] &= ~0x0008;

        return;

    }

    s->tx_busy = 1;

    txagain:

    if (pcnet_tdte_poll(s)) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, PHYSADDR(s,CSR_CXDA(s)));

#ifdef PCNET_DEBUG_TMD

        printf("  TMDLOAD 0x%08x\n", PHYSADDR(s,CSR_CXDA(s)));

        PRINT_TMD(&tmd);

#endif

        if (GET_FIELD(tmd.status, TMDS, STP)) {

            s->xmit_pos = 0;

            xmit_cxda = PHYSADDR(s,CSR_CXDA(s));

        }

        if (!GET_FIELD(tmd.status, TMDS, ENP)) {

            int bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT);

            s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr),

                             s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s));

            s->xmit_pos += bcnt;

        } else if (s->xmit_pos >= 0) {

            int bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT);

            s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr),

                             s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s));

            s->xmit_pos += bcnt;

#ifdef PCNET_DEBUG

            printf("pcnet_transmit size=%d\n", s->xmit_pos);

#endif

            if (CSR_LOOP(s))

                pcnet_receive(s, s->buffer, s->xmit_pos);

            else

                if (s->vc)

                    qemu_send_packet(s->vc, s->buffer, s->xmit_pos);

            s->csr[0] &= ~0x0008;   /* clear TDMD */

            s->csr[4] |= 0x0004;    /* set TXSTRT */

            s->xmit_pos = -1;

        }

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, PHYSADDR(s,CSR_CXDA(s)));

        if (!CSR_TOKINTD(s) || (CSR_LTINTEN(s) && GET_FIELD(tmd.status, TMDS, LTINT)))

            s->csr[0] |= 0x0200;    /* set TINT */

        if (CSR_XMTRC(s)<=1)

            CSR_XMTRC(s) = CSR_XMTRL(s);

        else

            CSR_XMTRC(s)--;

        if (count--)

            goto txagain;

    } else

    if (s->xmit_pos >= 0) {

        struct pcnet_TMD tmd;

        TMDLOAD(&tmd, PHYSADDR(s,xmit_cxda));

        SET_FIELD(&tmd.misc, TMDM, BUFF, 1);

        SET_FIELD(&tmd.misc, TMDM, UFLO, 1);

        SET_FIELD(&tmd.status, TMDS, ERR, 1);

        SET_FIELD(&tmd.status, TMDS, OWN, 0);

        TMDSTORE(&tmd, PHYSADDR(s,xmit_cxda));

        s->csr[0] |= 0x0200;    /* set TINT */

        if (!CSR_DXSUFLO(s)) {

            s->csr[0] &= ~0x0010;

        } else

        if (count--)

          goto txagain;

    }

    s->tx_busy = 0;

}


static av_cold int decoder_init(AVCodecContext * avctx)

{

    G729Context* ctx = avctx->priv_data;

    int i,k;

    if (avctx->channels != 1) {

        av_log(avctx, AV_LOG_ERROR, "Only mono sound is supported (requested channels: %d).\n", avctx->channels);

        return AVERROR(EINVAL);

    }

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    /* Both 8kbit/s and 6.4kbit/s modes uses two subframes per frame. */

    avctx->frame_size = SUBFRAME_SIZE << 1;

    ctx->gain_coeff = 16384; // 1.0 in (1.14)

    for (k = 0; k < MA_NP + 1; k++) {

        ctx->past_quantizer_outputs[k] = ctx->past_quantizer_output_buf[k];

        for (i = 1; i < 11; i++)

            ctx->past_quantizer_outputs[k][i - 1] = (18717 * i) >> 3;

    }

    ctx->lsp[0] = ctx->lsp_buf[0];

    ctx->lsp[1] = ctx->lsp_buf[1];

    memcpy(ctx->lsp[0], lsp_init, 10 * sizeof(int16_t));

    ctx->exc = &ctx->exc_base[PITCH_DELAY_MAX+INTERPOL_LEN];

    /* random seed initialization */

    ctx->rand_value = 21845;

    /* quantized prediction error */

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

        ctx->quant_energy[i] = -14336; // -14 in (5.10)

    avctx->dsp_mask= ~AV_CPU_FLAG_FORCE;

    dsputil_init(&ctx->dsp, avctx);

    return 0;

}


static void set_enum(Object *obj, Visitor *v, void *opaque,

                     const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    int *ptr = qdev_get_prop_ptr(dev, prop);

    if (dev->state != DEV_STATE_CREATED) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

    visit_type_enum(v, ptr, prop->info->enum_table,

                    prop->info->name, prop->name, errp);

}


static void imx_timerg_write(void *opaque, target_phys_addr_t offset,

                             uint64_t value, unsigned size)

{

    IMXTimerGState *s = (IMXTimerGState *)opaque;

    DPRINTF("g-write(offset=%x, value = 0x%x)\n", (unsigned int)offset >> 2,

            (unsigned int)value);

    switch (offset >> 2) {

    case 0: {

        uint32_t oldcr = s->cr;

        /* CR */

        if (value & GPT_CR_SWR) { /* force reset */

            value &= ~GPT_CR_SWR;

            imx_timerg_reset(&s->busdev.qdev);

            imx_timerg_update(s);

        }

        s->cr = value & ~0x7c00;

        imx_timerg_set_freq(s);

        if ((oldcr ^ value) & GPT_CR_EN) {

            if (value & GPT_CR_EN) {

                if (value & GPT_CR_ENMOD) {

                    ptimer_set_count(s->timer, s->ocr1);

                    s->cnt = 0;

                }

                ptimer_run(s->timer,

                           (value & GPT_CR_FRR) && (s->ocr1 != TIMER_MAX));

            } else {

                ptimer_stop(s->timer);

            };

        }

        return;

    }

    case 1: /* Prescaler */

        s->pr = value & 0xfff;

        imx_timerg_set_freq(s);

        return;

    case 2: /* SR */

        /*

         * No point in implementing the status register bits to do with

         * external interrupt sources.

         */

        value &= GPT_SR_OF1 | GPT_SR_ROV;

        s->sr &= ~value;

        imx_timerg_update(s);

        return;

    case 3: /* IR -- interrupt register */

        s->ir = value & 0x3f;

        imx_timerg_update(s);

        return;

    case 4: /* OCR1 -- output compare register */

        /* In non-freerun mode, reset count when this register is written */

        if (!(s->cr & GPT_CR_FRR)) {

            s->waiting_rov = 0;

            ptimer_set_limit(s->timer, value, 1);

        } else {

            imx_timerg_update_counts(s);

            if (value > s->cnt) {

                s->waiting_rov = 0;

                imx_timerg_reload(s, value);

            } else {

                s->waiting_rov = 1;

                imx_timerg_reload(s, TIMER_MAX - s->cnt);

            }

        }

        s->ocr1 = value;

        return;

    default:

        IPRINTF("imx_timerg_write: Bad offset %x\n",

                (int)offset >> 2);

    }

}


GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,

                                   int64_t whence, Error **errp)

{

    GuestFileHandle *gfh;

    GuestFileSeek *seek_data;

    HANDLE fh;

    LARGE_INTEGER new_pos, off_pos;

    off_pos.QuadPart = offset;

    BOOL res;

    gfh = guest_file_handle_find(handle, errp);

    if (!gfh) {

        return NULL;

    }

    fh = gfh->fh;

    res = SetFilePointerEx(fh, off_pos, &new_pos, whence);

    if (!res) {

        error_setg_win32(errp, GetLastError(), "failed to seek file");

        return NULL;

    }

    seek_data = g_new0(GuestFileSeek, 1);

    seek_data->position = new_pos.QuadPart;

    return seek_data;

}


static void add_to_iovec(QEMUFile *f, const uint8_t *buf, int size)

{

    /* check for adjacent buffer and coalesce them */

    if (f->iovcnt > 0 && buf == f->iov[f->iovcnt - 1].iov_base +

        f->iov[f->iovcnt - 1].iov_len) {

        f->iov[f->iovcnt - 1].iov_len += size;

    } else {

        f->iov[f->iovcnt].iov_base = (uint8_t *)buf;

        f->iov[f->iovcnt++].iov_len = size;

    }

    if (f->buf_index >= IO_BUF_SIZE || f->iovcnt >= MAX_IOV_SIZE) {

        qemu_fflush(f);

    }

}


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

                                 Error **errp)

{

    QapiCloneVisitor *qcv = to_qcv(v);

    assert(qcv->depth);

    /*

     * Pointer was already cloned by g_memdup; create fresh copy.

     * Note that as long as qmp-output-visitor accepts NULL instead of

     * "", then we must do likewise. However, we want to obey the

     * input visitor semantics of never producing NULL when the empty

     * string is intended.

     */

    *obj = g_strdup(*obj ?: "");

}


static int eth_can_receive(void *opaque)

{

    return 1;

}


static inline void terminate_compression_threads(void)

{

    int idx, thread_count;

    thread_count = migrate_compress_threads();

    quit_comp_thread = true;

    for (idx = 0; idx < thread_count; idx++) {

        qemu_mutex_lock(&comp_param[idx].mutex);

        qemu_cond_signal(&comp_param[idx].cond);

        qemu_mutex_unlock(&comp_param[idx].mutex);

    }

}


static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size)

{

    VP56RangeCoder *c = &s->c;

    int header_size, hscale, vscale, ret;

    int width  = s->avctx->width;

    int height = s->avctx->height;

    s->keyframe  = !(buf[0] & 1);

    s->profile   =  (buf[0]>>1) & 7;

    s->invisible = !(buf[0] & 0x10);

    header_size  = AV_RL24(buf) >> 5;

    buf      += 3;

    buf_size -= 3;

    if (s->profile > 3)

        av_log(s->avctx, AV_LOG_WARNING, "Unknown profile %d\n", s->profile);

    if (!s->profile)

        memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab,

               sizeof(s->put_pixels_tab));

    else    // profile 1-3 use bilinear, 4+ aren't defined so whatever

        memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab,

               sizeof(s->put_pixels_tab));

    if (header_size > buf_size - 7 * s->keyframe) {

        av_log(s->avctx, AV_LOG_ERROR, "Header size larger than data provided\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->keyframe) {

        if (AV_RL24(buf) != 0x2a019d) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "Invalid start code 0x%x\n", AV_RL24(buf));

            return AVERROR_INVALIDDATA;

        }

        width     = AV_RL16(buf + 3) & 0x3fff;

        height    = AV_RL16(buf + 5) & 0x3fff;

        hscale    = buf[4] >> 6;

        vscale    = buf[6] >> 6;

        buf      += 7;

        buf_size -= 7;

        if (hscale || vscale)

            avpriv_request_sample(s->avctx, "Upscaling");

        s->update_golden = s->update_altref = VP56_FRAME_CURRENT;

        vp78_reset_probability_tables(s);

        memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter,

               sizeof(s->prob->pred16x16));

        memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter,

               sizeof(s->prob->pred8x8c));

        memcpy(s->prob->mvc, vp8_mv_default_prob,

               sizeof(s->prob->mvc));

        memset(&s->segmentation, 0, sizeof(s->segmentation));

        memset(&s->lf_delta, 0, sizeof(s->lf_delta));

    }

    ff_vp56_init_range_decoder(c, buf, header_size);

    buf      += header_size;

    buf_size -= header_size;

    if (s->keyframe) {

        if (vp8_rac_get(c))

            av_log(s->avctx, AV_LOG_WARNING, "Unspecified colorspace\n");

        vp8_rac_get(c); // whether we can skip clamping in dsp functions

    }

    if ((s->segmentation.enabled = vp8_rac_get(c)))

        parse_segment_info(s);

    else

        s->segmentation.update_map = 0; // FIXME: move this to some init function?

    s->filter.simple    = vp8_rac_get(c);

    s->filter.level     = vp8_rac_get_uint(c, 6);

    s->filter.sharpness = vp8_rac_get_uint(c, 3);

    if ((s->lf_delta.enabled = vp8_rac_get(c)))

        if (vp8_rac_get(c))

            update_lf_deltas(s);

    if (setup_partitions(s, buf, buf_size)) {

        av_log(s->avctx, AV_LOG_ERROR, "Invalid partitions\n");

        return AVERROR_INVALIDDATA;

    }

    if (!s->macroblocks_base || /* first frame */

        width != s->avctx->width || height != s->avctx->height)

        if ((ret = vp8_update_dimensions(s, width, height)) < 0)

            return ret;

    get_quants(s);

    if (!s->keyframe) {

        update_refs(s);

        s->sign_bias[VP56_FRAME_GOLDEN]               = vp8_rac_get(c);

        s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c);

    }

    // if we aren't saving this frame's probabilities for future frames,

    // make a copy of the current probabilities

    if (!(s->update_probabilities = vp8_rac_get(c)))

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

    s->update_last = s->keyframe || vp8_rac_get(c);

    vp78_update_probability_tables(s);

    if ((s->mbskip_enabled = vp8_rac_get(c)))

        s->prob->mbskip = vp8_rac_get_uint(c, 8);

    if (!s->keyframe) {

        s->prob->intra  = vp8_rac_get_uint(c, 8);

        s->prob->last   = vp8_rac_get_uint(c, 8);

        s->prob->golden = vp8_rac_get_uint(c, 8);

        vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE);

    }

    return 0;

}


static inline void RENAME(planar2x)(const uint8_t *src, uint8_t *dst, long srcWidth, long srcHeight, long srcStride, long dstStride)

{

    long x,y;

    dst[0]= src[0];

    // first line

    for (x=0; x<srcWidth-1; x++) {

        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

    }

    dst[2*srcWidth-1]= src[srcWidth-1];

    dst+= dstStride;

    for (y=1; y<srcHeight; y++) {

#if COMPILE_TEMPLATE_MMX2 || COMPILE_TEMPLATE_AMD3DNOW

        const x86_reg mmxSize= srcWidth&~15;

        __asm__ volatile(

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

            "movq        "MANGLE(mmx_ff)", %%mm0    \n\t"

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

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

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

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

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

            "movq         (%1, %%"REG_a"), %%mm5    \n\t"

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

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

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

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

            "1:                                     \n\t"

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

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

            "movq        1(%0, %%"REG_a"), %%mm2    \n\t"

            "movq        1(%1, %%"REG_a"), %%mm3    \n\t"

            PAVGB"                  %%mm0, %%mm5    \n\t"

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

            PAVGB"                  %%mm0, %%mm5    \n\t"

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

            PAVGB"                  %%mm1, %%mm4    \n\t"

            PAVGB"                  %%mm1, %%mm2    \n\t"

            PAVGB"                  %%mm1, %%mm4    \n\t"

            PAVGB"                  %%mm1, %%mm2    \n\t"

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

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

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

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

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

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

#if 1

            MOVNTQ"                 %%mm5,  (%2, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm7, 8(%2, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm4,  (%3, %%"REG_a", 2)  \n\t"

            MOVNTQ"                 %%mm6, 8(%3, %%"REG_a", 2)  \n\t"

#else

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

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

            "movq                   %%mm4,  (%3, %%"REG_a", 2)  \n\t"

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

#endif

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

            "movq       -1(%0, %%"REG_a"), %%mm4    \n\t"

            "movq       -1(%1, %%"REG_a"), %%mm5    \n\t"

            " js                       1b                       \n\t"

            :: "r" (src + mmxSize  ), "r" (src + srcStride + mmxSize  ),

               "r" (dst + mmxSize*2), "r" (dst + dstStride + mmxSize*2),

               "g" (-mmxSize)

            : "%"REG_a

        );

#else

        const x86_reg mmxSize=1;

        dst[0        ]= (3*src[0] +   src[srcStride])>>2;

        dst[dstStride]= (  src[0] + 3*src[srcStride])>>2;

#endif

        for (x=mmxSize-1; x<srcWidth-1; x++) {

            dst[2*x          +1]= (3*src[x+0] +   src[x+srcStride+1])>>2;

            dst[2*x+dstStride+2]= (  src[x+0] + 3*src[x+srcStride+1])>>2;

            dst[2*x+dstStride+1]= (  src[x+1] + 3*src[x+srcStride  ])>>2;

            dst[2*x          +2]= (3*src[x+1] +   src[x+srcStride  ])>>2;

        }

        dst[srcWidth*2 -1            ]= (3*src[srcWidth-1] +   src[srcWidth-1 + srcStride])>>2;

        dst[srcWidth*2 -1 + dstStride]= (  src[srcWidth-1] + 3*src[srcWidth-1 + srcStride])>>2;

        dst+=dstStride*2;

        src+=srcStride;

    }

    // last line

#if 1

    dst[0]= src[0];

    for (x=0; x<srcWidth-1; x++) {

        dst[2*x+1]= (3*src[x] +   src[x+1])>>2;

        dst[2*x+2]= (  src[x] + 3*src[x+1])>>2;

    }

    dst[2*srcWidth-1]= src[srcWidth-1];

#else

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

        dst[2*x+0]=

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

    }

#endif

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(EMMS"       \n\t"

                     SFENCE"     \n\t"

                     :::"memory");

#endif

}


static av_cold void ffat_encode_flush(AVCodecContext *avctx)

{

    ATDecodeContext *at = avctx->priv_data;

    AudioConverterReset(at->converter);

    av_frame_unref(&at->new_in_frame);

    av_frame_unref(&at->in_frame);

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                         int *got_picture_ptr,

                         const AVPacket *avpkt)

{

    int ret;

    // copy to ensure we do not change avpkt

    AVPacket tmp = *avpkt;

    if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");

        return AVERROR(EINVAL);

    }

    *got_picture_ptr= 0;

    if((avctx->coded_width||avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

        return -1;

    if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){

        int did_split = av_packet_split_side_data(&tmp);

        apply_param_change(avctx, &tmp);

        avctx->pkt = &tmp;

        if (HAVE_THREADS && avctx->active_thread_type&FF_THREAD_FRAME)

             ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                          &tmp);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                              &tmp);

            picture->pkt_dts= avpkt->dts;

            if(!avctx->has_b_frames){

            picture->pkt_pos= avpkt->pos;

            }

            //FIXME these should be under if(!avctx->has_b_frames)

            if (!picture->sample_aspect_ratio.num)

                picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

            if (!picture->width)

                picture->width = avctx->width;

            if (!picture->height)

                picture->height = avctx->height;

            if (picture->format == PIX_FMT_NONE)

                picture->format = avctx->pix_fmt;

        }

        emms_c(); //needed to avoid an emms_c() call before every return;

        avctx->pkt = NULL;

        if (did_split) {

            ff_packet_free_side_data(&tmp);

            if(ret == tmp.size)

                ret = avpkt->size;

        }

        if (*got_picture_ptr){

            avctx->frame_number++;

            picture->best_effort_timestamp = guess_correct_pts(avctx,

                                                            picture->pkt_pts,

                                                            picture->pkt_dts);

        }

    }else

        ret= 0;

    return ret;

}


static void evalPrimary(Parser *p){

    double d, d2=NAN;

    char *next= p->s;

    int i;

    /* number */

    d= strtod(p->s, &next);

    if(next != p->s){

        push(p, d);

        p->s= next;

        return;

    }

    /* named constants */

    for(i=0; p->const_name[i]; i++){

        if(strmatch(p->s, p->const_name[i])){

            push(p, p->const_value[i]);

            p->s+= strlen(p->const_name[i]);

            return;

        }

    }

    p->s= strchr(p->s, '(');

    if(p->s==NULL){

        av_log(NULL, AV_LOG_ERROR, "Parser: missing ( in \"%s\"\n", next);

        return;

    }

    p->s++; // "("

    evalExpression(p);

    d= pop(p);

    p->s++; // ")" or ","

    if(p->s[-1]== ','){

        evalExpression(p);

        d2= pop(p);

        p->s++; // ")"

    }

         if( strmatch(next, "sinh"  ) ) d= sinh(d);

    else if( strmatch(next, "cosh"  ) ) d= cosh(d);

    else if( strmatch(next, "tanh"  ) ) d= tanh(d);

    else if( strmatch(next, "sin"   ) ) d= sin(d);

    else if( strmatch(next, "cos"   ) ) d= cos(d);

    else if( strmatch(next, "tan"   ) ) d= tan(d);

    else if( strmatch(next, "exp"   ) ) d= exp(d);

    else if( strmatch(next, "log"   ) ) d= log(d);

    else if( strmatch(next, "squish") ) d= 1/(1+exp(4*d));

    else if( strmatch(next, "gauss" ) ) d= exp(-d*d/2)/sqrt(2*M_PI);

    else if( strmatch(next, "abs"   ) ) d= fabs(d);

    else if( strmatch(next, "max"   ) ) d= d > d2 ? d : d2;

    else if( strmatch(next, "min"   ) ) d= d < d2 ? d : d2;

    else if( strmatch(next, "gt"    ) ) d= d > d2 ? 1.0 : 0.0;

    else if( strmatch(next, "lt"    ) ) d= d > d2 ? 0.0 : 1.0;

    else if( strmatch(next, "eq"    ) ) d= d == d2 ? 1.0 : 0.0;

//    else if( strmatch(next, "l1"    ) ) d= 1 + d2*(d - 1);

//    else if( strmatch(next, "sq01"  ) ) d= (d >= 0.0 && d <=1.0) ? 1.0 : 0.0;

    else{

        int error=1;

        for(i=0; p->func1_name && p->func1_name[i]; i++){

            if(strmatch(next, p->func1_name[i])){

                d= p->func1[i](p->opaque, d);

                error=0;

                break;

            }

        }

        for(i=0; p->func2_name && p->func2_name[i]; i++){

            if(strmatch(next, p->func2_name[i])){

                d= p->func2[i](p->opaque, d, d2);

                error=0;

                break;

            }

        }

        if(error){

            av_log(NULL, AV_LOG_ERROR, "Parser: unknown function in \"%s\"\n", next);

            return;

        }

    }

    if(p->s[-1]!= ')'){

        av_log(NULL, AV_LOG_ERROR, "Parser: missing ) in \"%s\"\n", next);

        return;

    }

    push(p, d);

}


static void test_i440fx_defaults(gconstpointer opaque)

{

    const TestData *s = opaque;

    QPCIBus *bus;

    QPCIDevice *dev;

    uint32_t value;

    bus = test_start_get_bus(s);

    dev = qpci_device_find(bus, QPCI_DEVFN(0, 0));

    g_assert(dev != NULL);

    /* 3.2.2 */

    g_assert_cmpint(qpci_config_readw(dev, PCI_VENDOR_ID), ==, 0x8086);

    /* 3.2.3 */

    g_assert_cmpint(qpci_config_readw(dev, PCI_DEVICE_ID), ==, 0x1237);

#ifndef BROKEN

    /* 3.2.4 */

    g_assert_cmpint(qpci_config_readw(dev, PCI_COMMAND), ==, 0x0006);

    /* 3.2.5 */

    g_assert_cmpint(qpci_config_readw(dev, PCI_STATUS), ==, 0x0280);

#endif

    /* 3.2.7 */

    g_assert_cmpint(qpci_config_readb(dev, PCI_CLASS_PROG), ==, 0x00);

    g_assert_cmpint(qpci_config_readw(dev, PCI_CLASS_DEVICE), ==, 0x0600);

    /* 3.2.8 */

    g_assert_cmpint(qpci_config_readb(dev, PCI_LATENCY_TIMER), ==, 0x00);

    /* 3.2.9 */

    g_assert_cmpint(qpci_config_readb(dev, PCI_HEADER_TYPE), ==, 0x00);

    /* 3.2.10 */

    g_assert_cmpint(qpci_config_readb(dev, PCI_BIST), ==, 0x00);

    /* 3.2.11 */

    value = qpci_config_readw(dev, 0x50); /* PMCCFG */

    if (s->num_cpus == 1) { /* WPE */

        g_assert(!(value & (1 << 15)));

    } else {

        g_assert((value & (1 << 15)));

    }

    g_assert(!(value & (1 << 6))); /* EPTE */

    /* 3.2.12 */

    g_assert_cmpint(qpci_config_readb(dev, 0x52), ==, 0x00); /* DETURBO */

    /* 3.2.13 */

#ifndef BROKEN

    g_assert_cmpint(qpci_config_readb(dev, 0x53), ==, 0x80); /* DBC */

#endif

    /* 3.2.14 */

    g_assert_cmpint(qpci_config_readb(dev, 0x54), ==, 0x00); /* AXC */

    /* 3.2.15 */

    g_assert_cmpint(qpci_config_readw(dev, 0x55), ==, 0x0000); /* DRT */

#ifndef BROKEN

    /* 3.2.16 */

    g_assert_cmpint(qpci_config_readb(dev, 0x57), ==, 0x01); /* DRAMC */

    /* 3.2.17 */

    g_assert_cmpint(qpci_config_readb(dev, 0x58), ==, 0x10); /* DRAMT */

#endif

    /* 3.2.18 */

    g_assert_cmpint(qpci_config_readb(dev, 0x59), ==, 0x00); /* PAM0 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5A), ==, 0x00); /* PAM1 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5B), ==, 0x00); /* PAM2 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5C), ==, 0x00); /* PAM3 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5D), ==, 0x00); /* PAM4 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5E), ==, 0x00); /* PAM5 */

    g_assert_cmpint(qpci_config_readb(dev, 0x5F), ==, 0x00); /* PAM6 */

#ifndef BROKEN

    /* 3.2.19 */

    g_assert_cmpint(qpci_config_readb(dev, 0x60), ==, 0x01); /* DRB0 */

    g_assert_cmpint(qpci_config_readb(dev, 0x61), ==, 0x01); /* DRB1 */

    g_assert_cmpint(qpci_config_readb(dev, 0x62), ==, 0x01); /* DRB2 */

    g_assert_cmpint(qpci_config_readb(dev, 0x63), ==, 0x01); /* DRB3 */

    g_assert_cmpint(qpci_config_readb(dev, 0x64), ==, 0x01); /* DRB4 */

    g_assert_cmpint(qpci_config_readb(dev, 0x65), ==, 0x01); /* DRB5 */

    g_assert_cmpint(qpci_config_readb(dev, 0x66), ==, 0x01); /* DRB6 */

    g_assert_cmpint(qpci_config_readb(dev, 0x67), ==, 0x01); /* DRB7 */

#endif

    /* 3.2.20 */

    g_assert_cmpint(qpci_config_readb(dev, 0x68), ==, 0x00); /* FDHC */

    /* 3.2.21 */

    g_assert_cmpint(qpci_config_readb(dev, 0x70), ==, 0x00); /* MTT */

#ifndef BROKEN

    /* 3.2.22 */

    g_assert_cmpint(qpci_config_readb(dev, 0x71), ==, 0x10); /* CLT */

#endif

    /* 3.2.23 */

    g_assert_cmpint(qpci_config_readb(dev, 0x72), ==, 0x02); /* SMRAM */

    /* 3.2.24 */

    g_assert_cmpint(qpci_config_readb(dev, 0x90), ==, 0x00); /* ERRCMD */

    /* 3.2.25 */

    g_assert_cmpint(qpci_config_readb(dev, 0x91), ==, 0x00); /* ERRSTS */

    /* 3.2.26 */

    g_assert_cmpint(qpci_config_readb(dev, 0x93), ==, 0x00); /* TRC */

    qtest_end();

}


BlockInfoList *qmp_query_block(Error **errp)

{

    BlockInfoList *head = NULL, **p_next = &head;

    BlockBackend *blk;

    Error *local_err = NULL;

    for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {

        BlockInfoList *info = g_malloc0(sizeof(*info));

        bdrv_query_info(blk, &info->value, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            goto err;

        }

        *p_next = info;

        p_next = &info->next;

    }

    return head;

 err:

    qapi_free_BlockInfoList(head);

    return NULL;

}


static int asf_write_header(AVFormatContext *s)

{

    ASFContext *asf = s->priv_data;

    s->packet_size  = PACKET_SIZE;

    s->max_interleave_delta = 0;

    asf->nb_packets = 0;

    asf->index_ptr             = av_malloc(sizeof(ASFIndex) * ASF_INDEX_BLOCK);

    asf->nb_index_memory_alloc = ASF_INDEX_BLOCK;

    asf->maximum_packet        = 0;

    /* the data-chunk-size has to be 50 (DATA_HEADER_SIZE), which is

     * data_size - asf->data_offset at the moment this function is done.

     * It is needed to use asf as a streamable format. */

    if (asf_write_header1(s, 0, DATA_HEADER_SIZE) < 0) {

        //av_free(asf);

        return -1;

    }

    avio_flush(s->pb);

    asf->packet_nb_payloads     = 0;

    asf->packet_timestamp_start = -1;

    asf->packet_timestamp_end   = -1;

    ffio_init_context(&asf->pb, asf->packet_buf, s->packet_size, 1,

                      NULL, NULL, NULL, NULL);

    if (s->avoid_negative_ts < 0)

        s->avoid_negative_ts = 1;

    return 0;

}


static int mp3_write_xing(AVFormatContext *s)

{

    MP3Context       *mp3 = s->priv_data;

    AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec;

    int32_t          header;

    MPADecodeHeader  mpah;

    int srate_idx, i, channels;

    int bitrate_idx;

    int best_bitrate_idx = -1;

    int best_bitrate_error = INT_MAX;

    int xing_offset;

    int ver = 0;

    int bytes_needed, lsf;

    const char *vendor = (codec->flags & CODEC_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT;

    if (!s->pb->seekable || !mp3->write_xing)

        return 0;

    for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) {

        const uint16_t base_freq = avpriv_mpa_freq_tab[i];

        if      (codec->sample_rate == base_freq)     ver = 0x3; // MPEG 1

        else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2

        else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5

        else continue;

        srate_idx = i;

        break;

    }

    if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) {

        av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing header.\n");

        return -1;

    }

    switch (codec->channels) {

    case 1:  channels = MPA_MONO;                                          break;

    case 2:  channels = MPA_STEREO;                                        break;

    default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, "

                    "not writing Xing header.\n");

             return -1;

    }

    /* dummy MPEG audio header */

    header  =  0xffU                                 << 24; // sync

    header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/

    header |= (srate_idx << 2) << 8;

    header |= channels << 6;

    for (bitrate_idx = 1; bitrate_idx < 15; bitrate_idx++) {

        int bit_rate = 1000 * avpriv_mpa_bitrate_tab[lsf][3 - 1][bitrate_idx];

        int error    = FFABS(bit_rate - codec->bit_rate);

        if (error < best_bitrate_error) {

            best_bitrate_error = error;

            best_bitrate_idx   = bitrate_idx;

        }

    }

    av_assert0(best_bitrate_idx >= 0);

    for (bitrate_idx = best_bitrate_idx; ; bitrate_idx++) {

        int32_t mask = bitrate_idx << (4 + 8);

        if (15 == bitrate_idx)

            return -1;

        header |= mask;

        avpriv_mpegaudio_decode_header(&mpah, header);

        xing_offset=xing_offtbl[mpah.lsf == 1][mpah.nb_channels == 1];

        bytes_needed = 4              // header

               + xing_offset

               + 4              // xing tag

               + 4              // frames/size/toc flags

               + 4              // frames

               + 4              // size

               + XING_TOC_SIZE   // toc

               + 24

               ;

        if (bytes_needed <= mpah.frame_size)

            break;

        header &= ~mask;

    }

    avio_wb32(s->pb, header);

    ffio_fill(s->pb, 0, xing_offset);

    mp3->xing_offset = avio_tell(s->pb);

    ffio_wfourcc(s->pb, "Xing");

    avio_wb32(s->pb, 0x01 | 0x02 | 0x04);  // frames / size / TOC

    mp3->size = mpah.frame_size;

    mp3->want=1;

    mp3->seen=0;

    mp3->pos=0;

    avio_wb32(s->pb, 0);  // frames

    avio_wb32(s->pb, 0);  // size

    // toc

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

        avio_w8(s->pb, (uint8_t)(255 * i / XING_TOC_SIZE));

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

        avio_w8(s->pb, vendor[i]);

    for (; i < 21; ++i)

        avio_w8(s->pb, 0);

    avio_wb24(s->pb, FFMAX(codec->delay - 528 - 1, 0)<<12);

    ffio_fill(s->pb, 0, mpah.frame_size - bytes_needed);

    return 0;

}


static int mkv_write_trailer(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t currentpos, cuespos;

    int ret;

    // check if we have an audio packet cached

    if (mkv->cur_audio_pkt.size > 0) {

        ret = mkv_write_packet_internal(s, &mkv->cur_audio_pkt, 0);

        av_free_packet(&mkv->cur_audio_pkt);

        if (ret < 0) {

            av_log(s, AV_LOG_ERROR,

                   "Could not write cached audio packet ret:%d\n", ret);

            return ret;

        }

    }

    if (mkv->dyn_bc) {

        end_ebml_master(mkv->dyn_bc, mkv->cluster);

        mkv_flush_dynbuf(s);

    } else if (mkv->cluster_pos != -1) {

        end_ebml_master(pb, mkv->cluster);

    }

    if (mkv->mode != MODE_WEBM) {

        ret = mkv_write_chapters(s);

        if (ret < 0)

            return ret;

    }

    if (pb->seekable) {

        if (mkv->cues->num_entries) {

            if (mkv->reserve_cues_space) {

                int64_t cues_end;

                currentpos = avio_tell(pb);

                avio_seek(pb, mkv->cues_pos, SEEK_SET);

                cuespos  = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);

                cues_end = avio_tell(pb);

                if (cues_end > cuespos + mkv->reserve_cues_space) {

                    av_log(s, AV_LOG_ERROR,

                           "Insufficient space reserved for cues: %d "

                           "(needed: %" PRId64 ").\n",

                           mkv->reserve_cues_space, cues_end - cuespos);

                    return AVERROR(EINVAL);

                }

                if (cues_end < cuespos + mkv->reserve_cues_space)

                    put_ebml_void(pb, mkv->reserve_cues_space -

                                  (cues_end - cuespos));

                avio_seek(pb, currentpos, SEEK_SET);

            } else {

                cuespos = mkv_write_cues(s, mkv->cues, mkv->tracks, s->nb_streams);

            }

            ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_CUES,

                                         cuespos);

            if (ret < 0)

                return ret;

        }

        mkv_write_seekhead(pb, mkv->main_seekhead);

        // update the duration

        av_log(s, AV_LOG_DEBUG, "end duration = %" PRIu64 "\n", mkv->duration);

        currentpos = avio_tell(pb);

        avio_seek(pb, mkv->duration_offset, SEEK_SET);

        put_ebml_float(pb, MATROSKA_ID_DURATION, mkv->duration);

        // update stream durations

        if (mkv->stream_durations) {

            int i;

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

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

                double duration_sec = mkv->stream_durations[i] * av_q2d(st->time_base);

                char duration_string[20] = "";

                av_log(s, AV_LOG_DEBUG, "stream %d end duration = %" PRIu64 "\n", i,

                       mkv->stream_durations[i]);

                if (!mkv->is_live && mkv->stream_duration_offsets[i] > 0) {

                    avio_seek(pb, mkv->stream_duration_offsets[i], SEEK_SET);

                    snprintf(duration_string, 20, "%02d:%02d:%012.9f",

                             (int) duration_sec / 3600, ((int) duration_sec / 60) % 60,

                             fmod(duration_sec, 60));

                    put_ebml_binary(pb, MATROSKA_ID_TAGSTRING, duration_string, 20);

                }

            }

        }

        avio_seek(pb, currentpos, SEEK_SET);

    }

    if (!mkv->is_live) {

        end_ebml_master(pb, mkv->segment);

    }

    av_freep(&mkv->tracks);

    av_freep(&mkv->cues->entries);

    av_freep(&mkv->cues);

    av_freep(&mkv->stream_durations);

    av_freep(&mkv->stream_duration_offsets);

    return 0;

}


static int quantize(CinepakEncContext *s, int h, AVPicture *pict, int v1mode, int size, int v4, strip_info *info)

{

    int x, y, i, j, k, x2, y2, x3, y3, plane, shift;

    int entry_size = s->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4;

    int *codebook = v1mode ? info->v1_codebook : info->v4_codebook;

    int64_t total_error = 0;

    uint8_t vq_pict_buf[(MB_AREA*3)/2];

    AVPicture sub_pict, vq_pict;

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

        for(x = 0; x < s->w; x += MB_SIZE, i += v1mode ? 1 : 4) {

            int *base = s->codebook_input + i*entry_size;

            if(v1mode) {

                //subsample

                for(j = y2 = 0; y2 < entry_size; y2 += 2) {

                    for(x2 = 0; x2 < 4; x2 += 2, j++) {

                        plane = y2 < 4 ? 0 : 1 + (x2 >> 1);

                        shift = y2 < 4 ? 0 : 1;

                        x3 = shift ? 0 : x2;

                        y3 = shift ? 0 : y2;

                        base[j] = (pict->data[plane][((x+x3) >> shift) +      ((y+y3) >> shift)      * pict->linesize[plane]] +

                                   pict->data[plane][((x+x3) >> shift) + 1 +  ((y+y3) >> shift)      * pict->linesize[plane]] +

                                   pict->data[plane][((x+x3) >> shift) +     (((y+y3) >> shift) + 1) * pict->linesize[plane]] +

                                   pict->data[plane][((x+x3) >> shift) + 1 + (((y+y3) >> shift) + 1) * pict->linesize[plane]]) >> 2;

                    }

                }

            } else {

                //copy

                for(j = y2 = 0; y2 < MB_SIZE; y2 += 2) {

                    for(x2 = 0; x2 < MB_SIZE; x2 += 2) {

                        for(k = 0; k < entry_size; k++, j++) {

                            plane = k >= 4 ? k - 3 : 0;

                            if(k >= 4) {

                                x3 = (x+x2) >> 1;

                                y3 = (y+y2) >> 1;

                            } else {

                                x3 = x + x2 + (k & 1);

                                y3 = y + y2 + (k >> 1);

                            }

                            base[j] = pict->data[plane][x3 + y3*pict->linesize[plane]];

                        }

                    }

                }

            }

        }

    }

    ff_init_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);

    ff_do_elbg(s->codebook_input, entry_size, i, codebook, size, 1, s->codebook_closest, &s->randctx);

    //setup vq_pict, which contains a single MB

    vq_pict.data[0] = vq_pict_buf;

    vq_pict.linesize[0] = MB_SIZE;

    vq_pict.data[1] = &vq_pict_buf[MB_AREA];

    vq_pict.data[2] = vq_pict.data[1] + (MB_AREA >> 2);

    vq_pict.linesize[1] = vq_pict.linesize[2] = MB_SIZE >> 1;

    //copy indices

    for(i = j = y = 0; y < h; y += MB_SIZE) {

        for(x = 0; x < s->w; x += MB_SIZE, j++, i += v1mode ? 1 : 4) {

            mb_info *mb = &s->mb[j];

            //point sub_pict to current MB

            get_sub_picture(s, x, y, pict, &sub_pict);

            if(v1mode) {

                mb->v1_vector = s->codebook_closest[i];

                //fill in vq_pict with V1 data

                decode_v1_vector(s, &vq_pict, mb, info);

                mb->v1_error = compute_mb_distortion(s, &sub_pict, &vq_pict);

                total_error += mb->v1_error;

            } else {

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

                    mb->v4_vector[v4][k] = s->codebook_closest[i+k];

                //fill in vq_pict with V4 data

                decode_v4_vector(s, &vq_pict, mb->v4_vector[v4], info);

                mb->v4_error[v4] = compute_mb_distortion(s, &sub_pict, &vq_pict);

                total_error += mb->v4_error[v4];

            }

        }

    }

    //av_log(s->avctx, AV_LOG_INFO, "mode %i size %i i %i error %li\n", v1mode, size, i, total_error);

    return 0;

}


void qemu_put_buffer_async(QEMUFile *f, const uint8_t *buf, int size)

{

    if (!f->ops->writev_buffer) {

        qemu_put_buffer(f, buf, size);

        return;

    }

    if (f->last_error) {

        return;

    }

    f->bytes_xfer += size;

    add_to_iovec(f, buf, size);

}


static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,

    uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index;

    uint64_t *l2_table;

    uint64_t entry;

    unsigned int nb_clusters;

    int ret;

    uint64_t alloc_cluster_offset;

    trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,

                             *bytes);

    assert(*bytes > 0);

    /*

     * Calculate the number of clusters to look for. We stop at L2 table

     * boundaries to keep things simple.

     */

    nb_clusters =

        size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);

    l2_index = offset_to_l2_index(s, guest_offset);

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

    /* Find L2 entry for the first involved cluster */

    ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);

    if (ret < 0) {

        return ret;

    }

    entry = be64_to_cpu(l2_table[l2_index]);

    /* For the moment, overwrite compressed clusters one by one */

    if (entry & QCOW_OFLAG_COMPRESSED) {

        nb_clusters = 1;

    } else {

        nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);

    }

    ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);

    if (ret < 0) {

        return ret;

    }

    if (nb_clusters == 0) {

        *bytes = 0;

        return 0;

    }

    /* Allocate, if necessary at a given offset in the image file */

    alloc_cluster_offset = start_of_cluster(s, *host_offset);

    ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,

                                  &nb_clusters);

    if (ret < 0) {

        goto fail;

    }

    /* Can't extend contiguous allocation */

    if (nb_clusters == 0) {

        *bytes = 0;

        return 0;

    }

    /*

     * Save info needed for meta data update.

     *

     * requested_sectors: Number of sectors from the start of the first

     * newly allocated cluster to the end of the (possibly shortened

     * before) write request.

     *

     * avail_sectors: Number of sectors from the start of the first

     * newly allocated to the end of the last newly allocated cluster.

     *

     * nb_sectors: The number of sectors from the start of the first

     * newly allocated cluster to the end of the area that the write

     * request actually writes to (excluding COW at the end)

     */

    int requested_sectors =

        (*bytes + offset_into_cluster(s, guest_offset))

        >> BDRV_SECTOR_BITS;

    int avail_sectors = nb_clusters

                        << (s->cluster_bits - BDRV_SECTOR_BITS);

    int alloc_n_start = offset_into_cluster(s, guest_offset)

                        >> BDRV_SECTOR_BITS;

    int nb_sectors = MIN(requested_sectors, avail_sectors);

    QCowL2Meta *old_m = *m;

    *m = g_malloc0(sizeof(**m));

    **m = (QCowL2Meta) {

        .next           = old_m,

        .alloc_offset   = alloc_cluster_offset,

        .offset         = start_of_cluster(s, guest_offset),

        .nb_clusters    = nb_clusters,

        .nb_available   = nb_sectors,

        .cow_start = {

            .offset     = 0,

            .nb_sectors = alloc_n_start,

        },

        .cow_end = {

            .offset     = nb_sectors * BDRV_SECTOR_SIZE,

            .nb_sectors = avail_sectors - nb_sectors,

        },

    };

    qemu_co_queue_init(&(*m)->dependent_requests);

    QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);

    *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);

    *bytes = MIN(*bytes, (nb_sectors * BDRV_SECTOR_SIZE)

                         - offset_into_cluster(s, guest_offset));

    assert(*bytes != 0);

    return 1;

fail:

    if (*m && (*m)->nb_clusters > 0) {

        QLIST_REMOVE(*m, next_in_flight);

    }

    return ret;

}


static uint32_t parse_peak(const uint8_t *peak)

{

    int64_t val = 0;

    int64_t scale = 1;

    if (!peak)

        return 0;

    peak += strspn(peak, " \t");

    if (peak[0] == '1' && peak[1] == '.')

        return UINT32_MAX;

    else if (!(peak[0] == '0' && peak[1] == '.'))

        return 0;

    peak += 2;

    while (av_isdigit(*peak)) {

        int digit = *peak - '0';

        if (scale > INT64_MAX / 10)

            break;

        val    = 10 * val + digit;

        scale *= 10;

        peak++;

    }

    return av_rescale(val, UINT32_MAX, scale);

}


void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],

                   const uint8_t *src_data[4], const int src_linesizes[4],

                   enum AVPixelFormat pix_fmt, int width, int height)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);

    if (!desc || desc->flags & PIX_FMT_HWACCEL)

    if (desc->flags & PIX_FMT_PAL ||

        desc->flags & PIX_FMT_PSEUDOPAL) {

        av_image_copy_plane(dst_data[0], dst_linesizes[0],

                            src_data[0], src_linesizes[0],

                            width, height);

        /* copy the palette */

        memcpy(dst_data[1], src_data[1], 4*256);

    } else {

        int i, planes_nb = 0;

        for (i = 0; i < desc->nb_components; i++)

            planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1);

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

            int h = height;

            int bwidth = av_image_get_linesize(pix_fmt, width, i);

            if (i == 1 || i == 2) {

                h= -((-height)>>desc->log2_chroma_h);

            av_image_copy_plane(dst_data[i], dst_linesizes[i],

                                src_data[i], src_linesizes[i],

                                bwidth, h);


static void gen_ld (CPUMIPSState *env, DisasContext *ctx, uint32_t opc,

                    int rt, int base, int16_t offset)

{

    const char *opn = "ld";

    TCGv t0, t1;

    if (rt == 0 && env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F)) {

        /* Loongson CPU uses a load to zero register for prefetch.

           We emulate it as a NOP. On other CPU we must perform the

           actual memory access. */

        MIPS_DEBUG("NOP");

        return;

    }

    t0 = tcg_temp_new();

    gen_base_offset_addr(ctx, t0, base, offset);

    switch (opc) {

#if defined(TARGET_MIPS64)

    case OPC_LWU:

        tcg_gen_qemu_ld32u(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lwu";

        break;

    case OPC_LD:

        tcg_gen_qemu_ld64(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "ld";

        break;

    case OPC_LLD:

        save_cpu_state(ctx, 1);

        op_ld_lld(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lld";

        break;

    case OPC_LDL:

        save_cpu_state(ctx, 1);

        t1 = tcg_temp_new();

        gen_load_gpr(t1, rt);

        gen_helper_1e2i(ldl, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        tcg_temp_free(t1);

        opn = "ldl";

        break;

    case OPC_LDR:

        save_cpu_state(ctx, 1);

        t1 = tcg_temp_new();

        gen_load_gpr(t1, rt);

        gen_helper_1e2i(ldr, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        tcg_temp_free(t1);

        opn = "ldr";

        break;

    case OPC_LDPC:

        t1 = tcg_const_tl(pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_qemu_ld64(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "ldpc";

        break;

#endif

    case OPC_LWPC:

        t1 = tcg_const_tl(pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        tcg_temp_free(t1);

        tcg_gen_qemu_ld32s(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lwpc";

        break;

    case OPC_LW:

        tcg_gen_qemu_ld32s(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lw";

        break;

    case OPC_LH:

        tcg_gen_qemu_ld16s(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lh";

        break;

    case OPC_LHU:

        tcg_gen_qemu_ld16u(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lhu";

        break;

    case OPC_LB:

        tcg_gen_qemu_ld8s(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lb";

        break;

    case OPC_LBU:

        tcg_gen_qemu_ld8u(t0, t0, ctx->mem_idx);

        gen_store_gpr(t0, rt);

        opn = "lbu";

        break;

    case OPC_LWL:

        save_cpu_state(ctx, 1);

        t1 = tcg_temp_new();

        gen_load_gpr(t1, rt);

        gen_helper_1e2i(lwl, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        tcg_temp_free(t1);

        opn = "lwl";

        break;

    case OPC_LWR:

        save_cpu_state(ctx, 1);

        t1 = tcg_temp_new();

        gen_load_gpr(t1, rt);

        gen_helper_1e2i(lwr, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        tcg_temp_free(t1);

        opn = "lwr";

        break;

    case OPC_LL:

        save_cpu_state(ctx, 1);

        op_ld_ll(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "ll";

        break;

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %d(%s)", opn, regnames[rt], offset, regnames[base]);

    tcg_temp_free(t0);

}


static void gxf_read_index(AVFormatContext *s, int pkt_len) {

    AVIOContext *pb = s->pb;

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

    uint32_t fields_per_map = avio_rl32(pb);

    uint32_t map_cnt = avio_rl32(pb);

    int i;

    pkt_len -= 8;

    if (s->flags & AVFMT_FLAG_IGNIDX) {

        avio_skip(pb, pkt_len);

        return;

    }

    if (map_cnt > 1000) {

        av_log(s, AV_LOG_ERROR, "too many index entries %u (%x)\n", map_cnt, map_cnt);

        map_cnt = 1000;

    }

    if (pkt_len < 4 * map_cnt) {

        av_log(s, AV_LOG_ERROR, "invalid index length\n");

        avio_skip(pb, pkt_len);

        return;

    }

    pkt_len -= 4 * map_cnt;

    av_add_index_entry(st, 0, 0, 0, 0, 0);

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

        av_add_index_entry(st, (uint64_t)avio_rl32(pb) * 1024,

                           i * (uint64_t)fields_per_map + 1, 0, 0, 0);

    avio_skip(pb, pkt_len);

}


static void draw_char(AVCodecContext *avctx, int c, int a)

{

    XbinContext *s = avctx->priv_data;

    if (s->y > avctx->height - s->font_height)

        return;

    ff_draw_pc_font(s->frame.data[0] + s->y * s->frame.linesize[0] + s->x,

                    s->frame.linesize[0], s->font, s->font_height, c,

                    a & 0x0F, a >> 4);

    s->x += FONT_WIDTH;

    if (s->x >= avctx->width) {

        s->x = 0;

        s->y += s->font_height;

    }

}


static int xwma_read_header(AVFormatContext *s)
{
    int64_t size;
    int ret;
    uint32_t dpds_table_size = 0;
    uint32_t *dpds_table = 0;
    unsigned int tag;
    AVIOContext *pb = s->pb;
    AVStream *st;
    XWMAContext *xwma = s->priv_data;
    int i;
    /* The following code is mostly copied from wav.c, with some
     * minor alterations.
     */
    /* check RIFF header */
    tag = avio_rl32(pb);
    if (tag != MKTAG('R', 'I', 'F', 'F'))
        return -1;
    avio_rl32(pb); /* file size */
    tag = avio_rl32(pb);
    if (tag != MKTAG('X', 'W', 'M', 'A'))
        return -1;
    /* parse fmt header */
    tag = avio_rl32(pb);
    if (tag != MKTAG('f', 'm', 't', ' '))
        return -1;
    size = avio_rl32(pb);
    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);
    ret = ff_get_wav_header(pb, st->codec, size);
    if (ret < 0)
        return ret;
    st->need_parsing = AVSTREAM_PARSE_NONE;
    /* All xWMA files I have seen contained WMAv2 data. If there are files
     * using WMA Pro or some other codec, then we need to figure out the right
     * extradata for that. Thus, ask the user for feedback, but try to go on
     * anyway.
     */
    if (st->codec->codec_id != AV_CODEC_ID_WMAV2) {
        av_log(s, AV_LOG_WARNING, "unexpected codec (tag 0x04%x; id %d)\n",
                              st->codec->codec_tag, st->codec->codec_id);
        av_log_ask_for_sample(s, NULL);
    } else {
        /* In all xWMA files I have seen, there is no extradata. But the WMA
         * codecs require extradata, so we provide our own fake extradata.
         *
         * First, check that there really was no extradata in the header. If
         * there was, then try to use it, after asking the user to provide a
         * sample of this unusual file.
         */
        if (st->codec->extradata_size != 0) {
            /* Surprise, surprise: We *did* get some extradata. No idea
             * if it will work, but just go on and try it, after asking
             * the user for a sample.
             */
            av_log(s, AV_LOG_WARNING, "unexpected extradata (%d bytes)\n",
                                  st->codec->extradata_size);
            av_log_ask_for_sample(s, NULL);
        } else {
            st->codec->extradata_size = 6;
            st->codec->extradata      = av_mallocz(6 + FF_INPUT_BUFFER_PADDING_SIZE);
            if (!st->codec->extradata)
                return AVERROR(ENOMEM);
            /* setup extradata with our experimentally obtained value */
            st->codec->extradata[4] = 31;
    if (!st->codec->channels) {
        av_log(s, AV_LOG_WARNING, "Invalid channel count: %d\n",
               st->codec->channels);
    if (!st->codec->bits_per_coded_sample) {
        av_log(s, AV_LOG_WARNING, "Invalid bits_per_coded_sample: %d\n",
               st->codec->bits_per_coded_sample);
    /* set the sample rate */
    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
    /* parse the remaining RIFF chunks */
    for (;;) {
        if (pb->eof_reached)
            return -1;
        /* read next chunk tag */
        tag = avio_rl32(pb);
        size = avio_rl32(pb);
        if (tag == MKTAG('d', 'a', 't', 'a')) {
            /* We assume that the data chunk comes last. */
            break;
        } else if (tag == MKTAG('d','p','d','s')) {
            /* Quoting the MSDN xWMA docs on the dpds chunk: "Contains the
             * decoded packet cumulative data size array, each element is the
             * number of bytes accumulated after the corresponding xWMA packet
             * is decoded in order."
             *
             * Each packet has size equal to st->codec->block_align, which in
             * all cases I saw so far was always 2230. Thus, we can use the
             * dpds data to compute a seeking index.
             */
            /* Error out if there is more than one dpds chunk. */
            if (dpds_table) {
                av_log(s, AV_LOG_ERROR, "two dpds chunks present\n");
                return -1;
            /* Compute the number of entries in the dpds chunk. */
            if (size & 3) {  /* Size should be divisible by four */
                av_log(s, AV_LOG_WARNING,
                       "dpds chunk size %"PRId64" not divisible by 4\n", size);
            dpds_table_size = size / 4;
            if (dpds_table_size == 0 || dpds_table_size >= INT_MAX / 4) {
                av_log(s, AV_LOG_ERROR,
                       "dpds chunk size %"PRId64" invalid\n", size);
                return -1;
            /* Allocate some temporary storage to keep the dpds data around.
             * for processing later on.
             */
            dpds_table = av_malloc(dpds_table_size * sizeof(uint32_t));
            if (!dpds_table) {
                return AVERROR(ENOMEM);
            for (i = 0; i < dpds_table_size; ++i) {
                dpds_table[i] = avio_rl32(pb);
                size -= 4;
        avio_skip(pb, size);
    /* Determine overall data length */
    if (size < 0)
        return -1;
    if (!size) {
        xwma->data_end = INT64_MAX;
    } else
        xwma->data_end = avio_tell(pb) + size;
    if (dpds_table && dpds_table_size) {
        int64_t cur_pos;
        const uint32_t bytes_per_sample
                = (st->codec->channels * st->codec->bits_per_coded_sample) >> 3;
        /* Estimate the duration from the total number of output bytes. */
        const uint64_t total_decoded_bytes = dpds_table[dpds_table_size - 1];
        st->duration = total_decoded_bytes / bytes_per_sample;
        /* Use the dpds data to build a seek table.  We can only do this after
         * we know the offset to the data chunk, as we need that to determine
         * the actual offset to each input block.
         * Note: If we allowed ourselves to assume that the data chunk always
         * follows immediately after the dpds block, we could of course guess
         * the data block's start offset already while reading the dpds chunk.
         * I decided against that, just in case other chunks ever are
         * discovered.
         */
        cur_pos = avio_tell(pb);
        for (i = 0; i < dpds_table_size; ++i) {
            /* From the number of output bytes that would accumulate in the
             * output buffer after decoding the first (i+1) packets, we compute
             * an offset / timestamp pair.
             */
            av_add_index_entry(st,
                               cur_pos + (i+1) * st->codec->block_align, /* pos */
                               dpds_table[i] / bytes_per_sample,         /* timestamp */
                               st->codec->block_align,                   /* size */
                               0,                                        /* duration */
                               AVINDEX_KEYFRAME);
    } else if (st->codec->bit_rate) {
        /* No dpds chunk was present (or only an empty one), so estimate
         * the total duration using the average bits per sample and the
         * total data length.
         */
        st->duration = (size<<3) * st->codec->sample_rate / st->codec->bit_rate;
    av_free(dpds_table);
    return 0;


static int openfile(char *name, int flags, int growable, QDict *opts)

{

    Error *local_err = NULL;

    if (qemuio_bs) {

        fprintf(stderr, "file open already, try 'help close'\n");

        return 1;

    }

    if (growable) {

        if (bdrv_open(&qemuio_bs, name, NULL, opts, flags | BDRV_O_PROTOCOL,

                      NULL, &local_err))

        {

            fprintf(stderr, "%s: can't open device %s: %s\n", progname, name,

                    error_get_pretty(local_err));

            error_free(local_err);

            return 1;

        }

    } else {

        qemuio_bs = bdrv_new("hda", &error_abort);

        if (bdrv_open(&qemuio_bs, name, NULL, opts, flags, NULL, &local_err)

            < 0)

        {

            fprintf(stderr, "%s: can't open device %s: %s\n", progname, name,

                    error_get_pretty(local_err));

            error_free(local_err);

            bdrv_unref(qemuio_bs);

            qemuio_bs = NULL;

            return 1;

        }

    }

    return 0;

}


static int cirrus_bitblt_videotovideo_copy(CirrusVGAState * s)

{

    if (blit_is_unsafe(s))

        return 0;

    return cirrus_do_copy(s, s->cirrus_blt_dstaddr - s->vga.start_addr,

            s->cirrus_blt_srcaddr - s->vga.start_addr,

            s->cirrus_blt_width, s->cirrus_blt_height);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);

    k->init = vpb_sic_init;

    dc->no_user = 1;

    dc->vmsd = &vmstate_vpb_sic;

}


static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,

                                      NvencSurface *nvenc_frame)

{

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

    NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;

    int res;

    NVENCSTATUS nv_status;

    if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {

        int reg_idx = nvenc_register_frame(avctx, frame);

        if (reg_idx < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");

            return reg_idx;

        }

        res = av_frame_ref(nvenc_frame->in_ref, frame);

        if (res < 0)

            return res;

        nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;

        nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;

        nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);

        if (nv_status != NV_ENC_SUCCESS) {

            av_frame_unref(nvenc_frame->in_ref);

            return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");

        }

        ctx->registered_frames[reg_idx].mapped = 1;

        nvenc_frame->reg_idx                   = reg_idx;

        nvenc_frame->input_surface             = nvenc_frame->in_map.mappedResource;

        nvenc_frame->format                    = nvenc_frame->in_map.mappedBufferFmt;

        nvenc_frame->pitch                     = frame->linesize[0];

        return 0;

    } else {

        NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };

        lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;

        lockBufferParams.inputBuffer = nvenc_frame->input_surface;

        nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);

        if (nv_status != NV_ENC_SUCCESS) {

            return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");

        }

        nvenc_frame->pitch = lockBufferParams.pitch;

        res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);

        nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);

        if (nv_status != NV_ENC_SUCCESS) {

            return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");

        }

        return res;

    }

}


void QEMU_NORETURN do_unassigned_access(target_phys_addr_t addr, int is_write,

                                        int is_exec, int unused, int size)

{

    env->trap_arg0 = addr;

    env->trap_arg1 = is_write;

    dynamic_excp(EXCP_MCHK, 0);

}