static void imx_gpt_compute_next_timeout(IMXGPTState *s, bool event)

{

    uint32_t timeout = TIMER_MAX;

    uint32_t count = 0;

    long long limit;

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

        /* if not enabled just return */

        return;

    }

    if (event) {

        /* This is a timer event  */

        if ((s->cr & GPT_CR_FRR)  && (s->next_timeout != TIMER_MAX)) {

            /*

             * if we are in free running mode and we have not reached

             * the TIMER_MAX limit, then update the count

             */

            count = imx_gpt_update_count(s);

        }

    } else {

        /* not a timer event, then just update the count */

        count = imx_gpt_update_count(s);

    }

    /* now, find the next timeout related to count */

    if (s->ir & GPT_IR_OF1IE) {

        timeout = imx_gpt_find_limit(count, s->ocr1, timeout);

    }

    if (s->ir & GPT_IR_OF2IE) {

        timeout = imx_gpt_find_limit(count, s->ocr2, timeout);

    }

    if (s->ir & GPT_IR_OF3IE) {

        timeout = imx_gpt_find_limit(count, s->ocr3, timeout);

    }

    /* find the next set of interrupts to raise for next timer event */

    s->next_int = 0;

    if ((s->ir & GPT_IR_OF1IE) && (timeout == s->ocr1)) {

        s->next_int |= GPT_SR_OF1;

    }

    if ((s->ir & GPT_IR_OF2IE) && (timeout == s->ocr2)) {

        s->next_int |= GPT_SR_OF2;

    }

    if ((s->ir & GPT_IR_OF3IE) && (timeout == s->ocr3)) {

        s->next_int |= GPT_SR_OF3;

    }

    if ((s->ir & GPT_IR_ROVIE) && (timeout == TIMER_MAX)) {

        s->next_int |= GPT_SR_ROV;

    }

    /* the new range to count down from */

    limit = timeout - imx_gpt_update_count(s);

    if (limit < 0) {

        /*

         * if we reach here, then QEMU is running too slow and we pass the

         * timeout limit while computing it. Let's deliver the interrupt

         * and compute a new limit.

         */

        s->sr |= s->next_int;

        imx_gpt_compute_next_timeout(s, event);

        imx_gpt_update_int(s);

    } else {

        /* New timeout value */

        s->next_timeout = timeout;

        /* reset the limit to the computed range */

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

    }

}


ram_addr_t qemu_ram_alloc(ram_addr_t size, MemoryRegion *mr, Error **errp)

{

    return qemu_ram_alloc_from_ptr(size, NULL, mr, errp);

}


bool write_list_to_cpustate(ARMCPU *cpu)

{

    int i;

    bool ok = true;

    for (i = 0; i < cpu->cpreg_array_len; i++) {

        uint32_t regidx = kvm_to_cpreg_id(cpu->cpreg_indexes[i]);

        uint64_t v = cpu->cpreg_values[i];

        const ARMCPRegInfo *ri;

        ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);

        if (!ri) {

            ok = false;

            continue;

        }

        if (ri->type & ARM_CP_NO_MIGRATE) {

            continue;

        }

        /* Write value and confirm it reads back as written

         * (to catch read-only registers and partially read-only

         * registers where the incoming migration value doesn't match)

         */

        write_raw_cp_reg(&cpu->env, ri, v);

        if (read_raw_cp_reg(&cpu->env, ri) != v) {

            ok = false;

        }

    }

    return ok;

}


static int trap_msix(S390PCIBusDevice *pbdev, uint64_t offset, uint8_t pcias)

{

    if (pbdev->msix.available && pbdev->msix.table_bar == pcias &&

        offset >= pbdev->msix.table_offset &&

        offset <= pbdev->msix.table_offset +

                  (pbdev->msix.entries - 1) * PCI_MSIX_ENTRY_SIZE) {

        return 1;

    } else {

        return 0;

    }

}


static bool local_is_mapped_file_metadata(FsContext *fs_ctx, const char *name)

{

    return !strcmp(name, VIRTFS_META_DIR);

}


static void cpu_pre_save(void *opaque)

{

    ARMCPU *cpu = opaque;

    if (!write_cpustate_to_list(cpu)) {

        /* This should never fail. */

        abort();

    }

    cpu->cpreg_vmstate_array_len = cpu->cpreg_array_len;

    memcpy(cpu->cpreg_vmstate_indexes, cpu->cpreg_indexes,

           cpu->cpreg_array_len * sizeof(uint64_t));

    memcpy(cpu->cpreg_vmstate_values, cpu->cpreg_values,

           cpu->cpreg_array_len * sizeof(uint64_t));

}


static void gen_arith (CPUState *env, DisasContext *ctx, uint32_t opc,

                       int rd, int rs, int rt)

{

    const char *opn = "arith";

    TCGv t0 = tcg_temp_local_new(TCG_TYPE_TL);

    TCGv t1 = tcg_temp_local_new(TCG_TYPE_TL);

    if (rd == 0 && opc != OPC_ADD && opc != OPC_SUB

       && opc != OPC_DADD && opc != OPC_DSUB) {

        /* If no destination, treat it as a NOP.

           For add & sub, we must generate the overflow exception when needed. */

        MIPS_DEBUG("NOP");

        goto out;

    }

    gen_load_gpr(t0, rs);

    /* Specialcase the conventional move operation. */

    if (rt == 0 && (opc == OPC_ADDU || opc == OPC_DADDU

                    || opc == OPC_SUBU || opc == OPC_DSUBU)) {

        gen_store_gpr(t0, rd);

        goto out;

    }

    gen_load_gpr(t1, rt);

    switch (opc) {

    case OPC_ADD:

        {

            TCGv r_tmp1 = tcg_temp_local_new(TCG_TYPE_TL);

            TCGv r_tmp2 = tcg_temp_new(TCG_TYPE_TL);

            int l1 = gen_new_label();

            save_cpu_state(ctx, 1);

            tcg_gen_ext32s_tl(r_tmp1, t0);

            tcg_gen_ext32s_tl(r_tmp2, t1);

            tcg_gen_add_tl(t0, r_tmp1, r_tmp2);

            tcg_gen_xor_tl(r_tmp1, r_tmp1, t1);

            tcg_gen_xori_tl(r_tmp1, r_tmp1, -1);

            tcg_gen_xor_tl(r_tmp2, t0, t1);

            tcg_gen_and_tl(r_tmp1, r_tmp1, r_tmp2);

            tcg_temp_free(r_tmp2);

            tcg_gen_shri_tl(r_tmp1, r_tmp1, 31);

            tcg_gen_brcondi_tl(TCG_COND_EQ, r_tmp1, 0, l1);

            tcg_temp_free(r_tmp1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            tcg_gen_ext32s_tl(t0, t0);

        }

        opn = "add";

        break;

    case OPC_ADDU:

        tcg_gen_ext32s_tl(t0, t0);

        tcg_gen_ext32s_tl(t1, t1);

        tcg_gen_add_tl(t0, t0, t1);

        tcg_gen_ext32s_tl(t0, t0);

        opn = "addu";

        break;

    case OPC_SUB:

        {

            TCGv r_tmp1 = tcg_temp_local_new(TCG_TYPE_TL);

            TCGv r_tmp2 = tcg_temp_new(TCG_TYPE_TL);

            int l1 = gen_new_label();

            save_cpu_state(ctx, 1);

            tcg_gen_ext32s_tl(r_tmp1, t0);

            tcg_gen_ext32s_tl(r_tmp2, t1);

            tcg_gen_sub_tl(t0, r_tmp1, r_tmp2);

            tcg_gen_xor_tl(r_tmp2, r_tmp1, t1);

            tcg_gen_xor_tl(r_tmp1, r_tmp1, t0);

            tcg_gen_and_tl(r_tmp1, r_tmp1, r_tmp2);

            tcg_temp_free(r_tmp2);

            tcg_gen_shri_tl(r_tmp1, r_tmp1, 31);

            tcg_gen_brcondi_tl(TCG_COND_EQ, r_tmp1, 0, l1);

            tcg_temp_free(r_tmp1);

            /* operands of different sign, first operand and result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

            tcg_gen_ext32s_tl(t0, t0);

        }

        opn = "sub";

        break;

    case OPC_SUBU:

        tcg_gen_ext32s_tl(t0, t0);

        tcg_gen_ext32s_tl(t1, t1);

        tcg_gen_sub_tl(t0, t0, t1);

        tcg_gen_ext32s_tl(t0, t0);

        opn = "subu";

        break;

#if defined(TARGET_MIPS64)

    case OPC_DADD:

        {

            TCGv r_tmp1 = tcg_temp_local_new(TCG_TYPE_TL);

            TCGv r_tmp2 = tcg_temp_new(TCG_TYPE_TL);

            int l1 = gen_new_label();

            save_cpu_state(ctx, 1);

            tcg_gen_mov_tl(r_tmp1, t0);

            tcg_gen_add_tl(t0, t0, t1);

            tcg_gen_xor_tl(r_tmp1, r_tmp1, t1);

            tcg_gen_xori_tl(r_tmp1, r_tmp1, -1);

            tcg_gen_xor_tl(r_tmp2, t0, t1);

            tcg_gen_and_tl(r_tmp1, r_tmp1, r_tmp2);

            tcg_temp_free(r_tmp2);

            tcg_gen_shri_tl(r_tmp1, r_tmp1, 63);

            tcg_gen_brcondi_tl(TCG_COND_EQ, r_tmp1, 0, l1);

            tcg_temp_free(r_tmp1);

            /* operands of same sign, result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

        }

        opn = "dadd";

        break;

    case OPC_DADDU:

        tcg_gen_add_tl(t0, t0, t1);

        opn = "daddu";

        break;

    case OPC_DSUB:

        {

            TCGv r_tmp1 = tcg_temp_local_new(TCG_TYPE_TL);

            TCGv r_tmp2 = tcg_temp_new(TCG_TYPE_TL);

            int l1 = gen_new_label();

            save_cpu_state(ctx, 1);

            tcg_gen_mov_tl(r_tmp1, t0);

            tcg_gen_sub_tl(t0, t0, t1);

            tcg_gen_xor_tl(r_tmp2, r_tmp1, t1);

            tcg_gen_xor_tl(r_tmp1, r_tmp1, t0);

            tcg_gen_and_tl(r_tmp1, r_tmp1, r_tmp2);

            tcg_temp_free(r_tmp2);

            tcg_gen_shri_tl(r_tmp1, r_tmp1, 63);

            tcg_gen_brcondi_tl(TCG_COND_EQ, r_tmp1, 0, l1);

            tcg_temp_free(r_tmp1);

            /* operands of different sign, first operand and result different sign */

            generate_exception(ctx, EXCP_OVERFLOW);

            gen_set_label(l1);

        }

        opn = "dsub";

        break;

    case OPC_DSUBU:

        tcg_gen_sub_tl(t0, t0, t1);

        opn = "dsubu";

        break;

#endif

    case OPC_SLT:

        gen_op_lt(t0, t1);

        opn = "slt";

        break;

    case OPC_SLTU:

        gen_op_ltu(t0, t1);

        opn = "sltu";

        break;

    case OPC_AND:

        tcg_gen_and_tl(t0, t0, t1);

        opn = "and";

        break;

    case OPC_NOR:

        tcg_gen_or_tl(t0, t0, t1);

        tcg_gen_not_tl(t0, t0);

        opn = "nor";

        break;

    case OPC_OR:

        tcg_gen_or_tl(t0, t0, t1);

        opn = "or";

        break;

    case OPC_XOR:

        tcg_gen_xor_tl(t0, t0, t1);

        opn = "xor";

        break;

    case OPC_MUL:

        tcg_gen_ext32s_tl(t0, t0);

        tcg_gen_ext32s_tl(t1, t1);

        tcg_gen_mul_tl(t0, t0, t1);

        tcg_gen_ext32s_tl(t0, t0);

        opn = "mul";

        break;

    case OPC_MOVN:

        {

            int l1 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_EQ, t1, 0, l1);

            gen_store_gpr(t0, rd);

            gen_set_label(l1);

        }

        opn = "movn";

        goto print;

    case OPC_MOVZ:

        {

            int l1 = gen_new_label();

            tcg_gen_brcondi_tl(TCG_COND_NE, t1, 0, l1);

            gen_store_gpr(t0, rd);

            gen_set_label(l1);

        }

        opn = "movz";

        goto print;

    case OPC_SLLV:

        tcg_gen_ext32u_tl(t0, t0);

        tcg_gen_ext32u_tl(t1, t1);

        tcg_gen_andi_tl(t0, t0, 0x1f);

        tcg_gen_shl_tl(t0, t1, t0);

        tcg_gen_ext32s_tl(t0, t0);

        opn = "sllv";

        break;

    case OPC_SRAV:

        tcg_gen_ext32s_tl(t1, t1);

        tcg_gen_andi_tl(t0, t0, 0x1f);

        tcg_gen_sar_tl(t0, t1, t0);

        tcg_gen_ext32s_tl(t0, t0);

        opn = "srav";

        break;

    case OPC_SRLV:

        switch ((ctx->opcode >> 6) & 0x1f) {

        case 0:

            tcg_gen_ext32u_tl(t1, t1);

            tcg_gen_andi_tl(t0, t0, 0x1f);

            tcg_gen_shr_tl(t0, t1, t0);

            tcg_gen_ext32s_tl(t0, t0);

            opn = "srlv";

            break;

        case 1:

            /* rotrv is decoded as srlv on non-R2 CPUs */

            if (env->insn_flags & ISA_MIPS32R2) {

                int l1 = gen_new_label();

                int l2 = gen_new_label();

                tcg_gen_andi_tl(t0, t0, 0x1f);

                tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);

                {

                    TCGv r_tmp1 = tcg_temp_new(TCG_TYPE_I32);

                    TCGv r_tmp2 = tcg_temp_new(TCG_TYPE_I32);

                    tcg_gen_trunc_tl_i32(r_tmp1, t0);

                    tcg_gen_trunc_tl_i32(r_tmp2, t1);

                    tcg_gen_rotr_i32(r_tmp1, r_tmp1, r_tmp2);

                    tcg_temp_free(r_tmp1);

                    tcg_temp_free(r_tmp2);

                    tcg_gen_br(l2);

                }

                gen_set_label(l1);

                tcg_gen_mov_tl(t0, t1);

                gen_set_label(l2);

                opn = "rotrv";

            } else {

                tcg_gen_ext32u_tl(t1, t1);

                tcg_gen_andi_tl(t0, t0, 0x1f);

                tcg_gen_shr_tl(t0, t1, t0);

                tcg_gen_ext32s_tl(t0, t0);

                opn = "srlv";

            }

            break;

        default:

            MIPS_INVAL("invalid srlv flag");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

#if defined(TARGET_MIPS64)

    case OPC_DSLLV:

        tcg_gen_andi_tl(t0, t0, 0x3f);

        tcg_gen_shl_tl(t0, t1, t0);

        opn = "dsllv";

        break;

    case OPC_DSRAV:

        tcg_gen_andi_tl(t0, t0, 0x3f);

        tcg_gen_sar_tl(t0, t1, t0);

        opn = "dsrav";

        break;

    case OPC_DSRLV:

        switch ((ctx->opcode >> 6) & 0x1f) {

        case 0:

            tcg_gen_andi_tl(t0, t0, 0x3f);

            tcg_gen_shr_tl(t0, t1, t0);

            opn = "dsrlv";

            break;

        case 1:

            /* drotrv is decoded as dsrlv on non-R2 CPUs */

            if (env->insn_flags & ISA_MIPS32R2) {

                int l1 = gen_new_label();

                int l2 = gen_new_label();

                tcg_gen_andi_tl(t0, t0, 0x3f);

                tcg_gen_brcondi_tl(TCG_COND_EQ, t0, 0, l1);

                {

                    tcg_gen_rotr_tl(t0, t1, t0);

                    tcg_gen_br(l2);

                }

                gen_set_label(l1);

                tcg_gen_mov_tl(t0, t1);

                gen_set_label(l2);

                opn = "drotrv";

            } else {

                tcg_gen_andi_tl(t0, t0, 0x3f);

                tcg_gen_shr_tl(t0, t1, t0);

                opn = "dsrlv";

            }

            break;

        default:

            MIPS_INVAL("invalid dsrlv flag");

            generate_exception(ctx, EXCP_RI);

            break;

        }

        break;

#endif

    default:

        MIPS_INVAL(opn);

        generate_exception(ctx, EXCP_RI);

        goto out;

    }

    gen_store_gpr(t0, rd);

 print:

    MIPS_DEBUG("%s %s, %s, %s", opn, regnames[rd], regnames[rs], regnames[rt]);

 out:

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static int proxy_open2(FsContext *fs_ctx, V9fsPath *dir_path, const char *name,

                       int flags, FsCred *credp, V9fsFidOpenState *fs)

{

    V9fsString fullname;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    fs->fd = v9fs_request(fs_ctx->private, T_CREATE, NULL, "sdddd",

                          &fullname, flags, credp->fc_mode,

                          credp->fc_uid, credp->fc_gid);

    v9fs_string_free(&fullname);

    if (fs->fd < 0) {

        errno = -fs->fd;

        fs->fd = -1;

    }

    return fs->fd;

}


void memory_region_add_subregion_overlap(MemoryRegion *mr,

                                         hwaddr offset,

                                         MemoryRegion *subregion,

                                         int priority)

{

    subregion->may_overlap = true;

    subregion->priority = priority;

    memory_region_add_subregion_common(mr, offset, subregion);

}


void hd_geometry_guess(BlockBackend *blk,

                       uint32_t *pcyls, uint32_t *pheads, uint32_t *psecs,

                       int *ptrans)

{

    int cylinders, heads, secs, translation;

    if (guess_disk_lchs(blk, &cylinders, &heads, &secs) < 0) {

        /* no LCHS guess: use a standard physical disk geometry  */

        guess_chs_for_size(blk, pcyls, pheads, psecs);

        translation = hd_bios_chs_auto_trans(*pcyls, *pheads, *psecs);

    } else if (heads > 16) {

        /* LCHS guess with heads > 16 means that a BIOS LBA

           translation was active, so a standard physical disk

           geometry is OK */

        guess_chs_for_size(blk, pcyls, pheads, psecs);

        translation = *pcyls * *pheads <= 131072

            ? BIOS_ATA_TRANSLATION_LARGE

            : BIOS_ATA_TRANSLATION_LBA;

    } else {

        /* LCHS guess with heads <= 16: use as physical geometry */

        *pcyls = cylinders;

        *pheads = heads;

        *psecs = secs;

        /* disable any translation to be in sync with

           the logical geometry */

        translation = BIOS_ATA_TRANSLATION_NONE;

    }

    if (ptrans) {

        *ptrans = translation;

    }

    trace_hd_geometry_guess(blk, *pcyls, *pheads, *psecs, translation);

}


int net_init_vde(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan)

{

    const char *sock;

    const char *group;

    int port, mode;

    sock  = qemu_opt_get(opts, "sock");

    group = qemu_opt_get(opts, "group");

    port = qemu_opt_get_number(opts, "port", 0);

    mode = qemu_opt_get_number(opts, "mode", 0700);

    if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {

        return -1;

    }

    if (vlan) {

        vlan->nb_host_devs++;

    }

    return 0;

}


int read_ffserver_streams(AVFormatContext *s, const char *filename)

{

    int i;

    AVFormatContext *ic;

    ic = av_open_input_file(filename, FFM_PACKET_SIZE);

    if (!ic)

        return -EIO;

    /* copy stream format */

    s->nb_streams = ic->nb_streams;

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

        AVStream *st;

        st = av_mallocz(sizeof(AVFormatContext));

        memcpy(st, ic->streams[i], sizeof(AVStream));

        s->streams[i] = st;

    }

    av_close_input_file(ic);

    return 0;

}


void ff_restore_parser_state(AVFormatContext *s, AVParserState *state)

{

    int i;

    AVStream *st;

    AVParserStreamState *ss;

    ff_read_frame_flush(s);

    if (!state)

        return;

    avio_seek(s->pb, state->fpos, SEEK_SET);

    // copy context structures

    s->cur_st                           = state->cur_st;

    s->packet_buffer                    = state->packet_buffer;

    s->raw_packet_buffer                = state->raw_packet_buffer;

    s->raw_packet_buffer_remaining_size = state->raw_packet_buffer_remaining_size;

    // copy stream structures

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

        st = s->streams[i];

        ss = &state->stream_states[i];

        st->parser        = ss->parser;

        st->last_IP_pts   = ss->last_IP_pts;

        st->cur_dts       = ss->cur_dts;

        st->reference_dts = ss->reference_dts;

        st->cur_ptr       = ss->cur_ptr;

        st->cur_len       = ss->cur_len;

        st->probe_packets = ss->probe_packets;

        st->cur_pkt       = ss->cur_pkt;

    }

    av_free(state->stream_states);

    av_free(state);

}


int ff_img_read_header(AVFormatContext *s1)

{

    VideoDemuxData *s = s1->priv_data;

    int first_index = 1, last_index = 1;

    AVStream *st;

    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;

    s1->ctx_flags |= AVFMTCTX_NOHEADER;

    st = avformat_new_stream(s1, NULL);

    if (!st) {

        return AVERROR(ENOMEM);

    }

    if (s->pixel_format &&

        (pix_fmt = av_get_pix_fmt(s->pixel_format)) == AV_PIX_FMT_NONE) {

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

               s->pixel_format);

        return AVERROR(EINVAL);

    }

    av_strlcpy(s->path, s1->filename, sizeof(s->path));

    s->img_number = 0;

    s->img_count  = 0;

    /* find format */

    if (s1->iformat->flags & AVFMT_NOFILE)

        s->is_pipe = 0;

    else {

        s->is_pipe       = 1;

        st->need_parsing = AVSTREAM_PARSE_FULL;

    }

    if (s->ts_from_file == 2) {

#if !HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC

        av_log(s1, AV_LOG_ERROR, "POSIX.1-2008 not supported, nanosecond file timestamps unavailable\n");

        return AVERROR(ENOSYS);

#endif

        avpriv_set_pts_info(st, 64, 1, 1000000000);

    } else if (s->ts_from_file)

        avpriv_set_pts_info(st, 64, 1, 1);

    else

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

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

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

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

    }

    if (!s->is_pipe) {

        if (s->pattern_type == PT_GLOB_SEQUENCE) {

        s->use_glob = is_glob(s->path);

        if (s->use_glob) {

#if HAVE_GLOB

            char *p = s->path, *q, *dup;

            int gerr;

#endif

            av_log(s1, AV_LOG_WARNING, "Pattern type 'glob_sequence' is deprecated: "

                   "use pattern_type 'glob' instead\n");

#if HAVE_GLOB

            dup = q = av_strdup(p);

            while (*q) {

                /* Do we have room for the next char and a \ insertion? */

                if ((p - s->path) >= (sizeof(s->path) - 2))

                  break;

                if (*q == '%' && strspn(q + 1, "%*?[]{}"))

                    ++q;

                else if (strspn(q, "\\*?[]{}"))

                    *p++ = '\\';

                *p++ = *q++;

            }

            *p = 0;

            av_free(dup);

            gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);

            if (gerr != 0) {

                return AVERROR(ENOENT);

            }

            first_index = 0;

            last_index = s->globstate.gl_pathc - 1;

#endif

        }

        }

        if ((s->pattern_type == PT_GLOB_SEQUENCE && !s->use_glob) || s->pattern_type == PT_SEQUENCE) {

            if (find_image_range(&first_index, &last_index, s->path,

                                 s->start_number, s->start_number_range) < 0) {

                av_log(s1, AV_LOG_ERROR,

                       "Could find no file with path '%s' and index in the range %d-%d\n",

                       s->path, s->start_number, s->start_number + s->start_number_range - 1);

                return AVERROR(ENOENT);

            }

        } else if (s->pattern_type == PT_GLOB) {

#if HAVE_GLOB

            int gerr;

            gerr = glob(s->path, GLOB_NOCHECK|GLOB_BRACE|GLOB_NOMAGIC, NULL, &s->globstate);

            if (gerr != 0) {

                return AVERROR(ENOENT);

            }

            first_index = 0;

            last_index = s->globstate.gl_pathc - 1;

            s->use_glob = 1;

#else

            av_log(s1, AV_LOG_ERROR,

                   "Pattern type 'glob' was selected but globbing "

                   "is not supported by this libavformat build\n");

            return AVERROR(ENOSYS);

#endif

        } else if (s->pattern_type != PT_GLOB_SEQUENCE && s->pattern_type != PT_NONE) {

            av_log(s1, AV_LOG_ERROR,

                   "Unknown value '%d' for pattern_type option\n", s->pattern_type);

            return AVERROR(EINVAL);

        }

        s->img_first  = first_index;

        s->img_last   = last_index;

        s->img_number = first_index;

        /* compute duration */

        if (!s->ts_from_file) {

            st->start_time = 0;

            st->duration   = last_index - first_index + 1;

        }

    }

    if (s1->video_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id   = s1->video_codec_id;

    } else if (s1->audio_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id   = s1->audio_codec_id;

    } else if (s1->iformat->raw_codec_id) {

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

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

    } else {

        const char *str = strrchr(s->path, '.');

        s->split_planes       = str && !av_strcasecmp(str + 1, "y");

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        if (s1->pb) {

            int probe_buffer_size = 2048;

            uint8_t *probe_buffer = av_realloc(NULL, probe_buffer_size + AVPROBE_PADDING_SIZE);

            AVInputFormat *fmt = NULL;

            AVProbeData pd = { 0 };

            if (!probe_buffer)

                return AVERROR(ENOMEM);

            probe_buffer_size = avio_read(s1->pb, probe_buffer, probe_buffer_size);

            if (probe_buffer_size < 0) {

                av_free(probe_buffer);

                return probe_buffer_size;

            }

            memset(probe_buffer + probe_buffer_size, 0, AVPROBE_PADDING_SIZE);

            pd.buf = probe_buffer;

            pd.buf_size = probe_buffer_size;

            pd.filename = s1->filename;

            while ((fmt = av_iformat_next(fmt))) {

                if (fmt->read_header != ff_img_read_header ||

                    !fmt->read_probe ||

                    (fmt->flags & AVFMT_NOFILE) ||

                    !fmt->raw_codec_id)

                    continue;

                if (fmt->read_probe(&pd) > 0) {

                    st->codec->codec_id = fmt->raw_codec_id;

                    break;

                }

            }

            if (s1->flags & AVFMT_FLAG_CUSTOM_IO) {

                avio_seek(s1->pb, 0, SEEK_SET);

            } else

                ffio_rewind_with_probe_data(s1->pb, &probe_buffer, probe_buffer_size);

        }

        if (st->codec->codec_id == AV_CODEC_ID_NONE)

            st->codec->codec_id = ff_guess_image2_codec(s->path);

        if (st->codec->codec_id == AV_CODEC_ID_LJPEG)

            st->codec->codec_id = AV_CODEC_ID_MJPEG;

        if (st->codec->codec_id == AV_CODEC_ID_ALIAS_PIX) // we cannot distingiush this from BRENDER_PIX

            st->codec->codec_id = AV_CODEC_ID_NONE;

    }

    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&

        pix_fmt != AV_PIX_FMT_NONE)

        st->codec->pix_fmt = pix_fmt;

    return 0;

}


static av_always_inline void decode_bgr_1(HYuvContext *s, int count,

                                          int decorrelate, int alpha)

{

    int i;

    OPEN_READER(re, &s->gb);

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

        unsigned int index;

        int code, n;

        UPDATE_CACHE(re, &s->gb);

        index = SHOW_UBITS(re, &s->gb, VLC_BITS);

        code  = s->vlc[4].table[index][0];

        n     = s->vlc[4].table[index][1];

        if (code != -1) {

            *(uint32_t*)&s->temp[0][4 * i] = s->pix_bgr_map[code];

            LAST_SKIP_BITS(re, &s->gb, n);

        } else {

            int nb_bits;

            if(decorrelate) {

                VLC_INTERN(s->temp[0][4 * i + G], s->vlc[1].table,

                           &s->gb, re, VLC_BITS, 3);

                UPDATE_CACHE(re, &s->gb);

                index = SHOW_UBITS(re, &s->gb, VLC_BITS);

                VLC_INTERN(code, s->vlc[0].table, &s->gb, re, VLC_BITS, 3);

                s->temp[0][4 * i + B] = code + s->temp[0][4 * i + G];

                UPDATE_CACHE(re, &s->gb);

                index = SHOW_UBITS(re, &s->gb, VLC_BITS);

                VLC_INTERN(code, s->vlc[2].table, &s->gb, re, VLC_BITS, 3);

                s->temp[0][4 * i + R] = code + s->temp[0][4 * i + G];

            } else {

                VLC_INTERN(s->temp[0][4 * i + B], s->vlc[0].table,

                           &s->gb, re, VLC_BITS, 3);

                UPDATE_CACHE(re, &s->gb);

                index = SHOW_UBITS(re, &s->gb, VLC_BITS);

                VLC_INTERN(s->temp[0][4 * i + G], s->vlc[1].table,

                           &s->gb, re, VLC_BITS, 3);

                UPDATE_CACHE(re, &s->gb);

                index = SHOW_UBITS(re, &s->gb, VLC_BITS);

                VLC_INTERN(s->temp[0][4 * i + R], s->vlc[2].table,

                           &s->gb, re, VLC_BITS, 3);

            }

            if (alpha) {

                UPDATE_CACHE(re, &s->gb);

                index = SHOW_UBITS(re, &s->gb, VLC_BITS);

                VLC_INTERN(s->temp[0][4 * i + A], s->vlc[2].table,

                           &s->gb, re, VLC_BITS, 3);

            }

        }

    }

    CLOSE_READER(re, &s->gb);

}


static int dnxhd_init_rc(DNXHDEncContext *ctx)

{

    CHECKED_ALLOCZ(ctx->mb_rc, 8160*ctx->m.avctx->qmax*sizeof(RCEntry));

    if (ctx->m.avctx->mb_decision != FF_MB_DECISION_RD)

        CHECKED_ALLOCZ(ctx->mb_cmp, ctx->m.mb_num*sizeof(RCCMPEntry));

    ctx->frame_bits = (ctx->cid_table->coding_unit_size - 640 - 4) * 8;

    ctx->qscale = 1;

    ctx->lambda = 2<<LAMBDA_FRAC_BITS; // qscale 2

    return 0;

 fail:

    return -1;

}


static int mpeg1_decode_picture(AVCodecContext *avctx,

                                UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int ref, f_code;

    init_get_bits(&s->gb, buf, buf_size);

    ref = get_bits(&s->gb, 10); /* temporal ref */

    s->pict_type = get_bits(&s->gb, 3);

    dprintf("pict_type=%d number=%d\n", s->pict_type, s->picture_number);

    skip_bits(&s->gb, 16);

    if (s->pict_type == P_TYPE || s->pict_type == B_TYPE) {

        s->full_pel[0] = get_bits1(&s->gb);

        f_code = get_bits(&s->gb, 3);

        if (f_code == 0)

            return -1;

        s->mpeg_f_code[0][0] = f_code;

        s->mpeg_f_code[0][1] = f_code;

    }

    if (s->pict_type == B_TYPE) {

        s->full_pel[1] = get_bits1(&s->gb);

        f_code = get_bits(&s->gb, 3);

        if (f_code == 0)

            return -1;

        s->mpeg_f_code[1][0] = f_code;

        s->mpeg_f_code[1][1] = f_code;

    }

    s->current_picture.pict_type= s->pict_type;

    s->current_picture.key_frame= s->pict_type == I_TYPE;

    s->y_dc_scale = 8;

    s->c_dc_scale = 8;

    s->first_slice = 1;

    return 0;

}


static int mpeg1_find_frame_end(MpegEncContext *s, uint8_t *buf, int buf_size){

    ParseContext *pc= &s->parse_context;

    int i;

    uint32_t state;

    state= pc->state;

    i=0;

    if(!pc->frame_start_found){

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

            state= (state<<8) | buf[i];

            if(state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE){

                i++;

                pc->frame_start_found=1;

                break;

            }

        }

    }

    if(pc->frame_start_found){

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

            state= (state<<8) | buf[i];

            if((state&0xFFFFFF00) == 0x100){

                if(state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE){

                    pc->frame_start_found=0;

                    pc->state=-1;

                    return i-3;

                }

            }

        }

    }

    pc->state= state;

    return -1;

}


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

{

    int i;

    int64_t creation_time;

    int version = avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    if (version == 1) {

        creation_time = avio_rb64(pb);

        avio_rb64(pb);

    } else {

        creation_time = avio_rb32(pb);

        avio_rb32(pb); /* modification time */

    }

    mov_metadata_creation_time(&c->fc->metadata, creation_time);

    c->time_scale = avio_rb32(pb); /* time scale */

    if (c->time_scale <= 0) {

        av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d\n", c->time_scale);

        return AVERROR_INVALIDDATA;

    }

    av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale);

    c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */

    // set the AVCodecContext duration because the duration of individual tracks

    // may be inaccurate

    if (c->time_scale > 0 && !c->trex_data)

        c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale);

    avio_rb32(pb); /* preferred scale */

    avio_rb16(pb); /* preferred volume */

    avio_skip(pb, 10); /* reserved */

    /* movie display matrix, store it in main context and use it later on */

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

        c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point

        c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point

        c->movie_display_matrix[i][2] = avio_rb32(pb); //  2.30 fixed point

    }

    avio_rb32(pb); /* preview time */

    avio_rb32(pb); /* preview duration */

    avio_rb32(pb); /* poster time */

    avio_rb32(pb); /* selection time */

    avio_rb32(pb); /* selection duration */

    avio_rb32(pb); /* current time */

    avio_rb32(pb); /* next track ID */

    return 0;

}


static int decode_packet(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, Jpeg2000ResLevel *rlevel, int precno,

                         int layno, uint8_t *expn, int numgbits)

{

    int bandno, cblkny, cblknx, cblkno, ret;

    if (!(ret = get_bits(s, 1))){

        j2k_flush(s);

        return 0;

    } else if (ret < 0)

        return ret;

    for (bandno = 0; bandno < rlevel->nbands; bandno++){

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        int pos = 0;

        if (band->coord[0][0] == band->coord[0][1]

        ||  band->coord[1][0] == band->coord[1][1])

            continue;

        for (cblkny = prec->yi0; cblkny < prec->yi1; cblkny++)

            for(cblknx = prec->xi0, cblkno = cblkny * band->cblknx + cblknx; cblknx < prec->xi1; cblknx++, cblkno++, pos++){

                Jpeg2000Cblk *cblk = band->cblk + cblkno;

                int incl, newpasses, llen;

                if (cblk->npasses)

                    incl = get_bits(s, 1);

                else

                    incl = tag_tree_decode(s, prec->cblkincl + pos, layno+1) == layno;

                if (!incl)

                    continue;

                else if (incl < 0)

                    return incl;

                if (!cblk->npasses)

                    cblk->nonzerobits = expn[bandno] + numgbits - 1 - tag_tree_decode(s, prec->zerobits + pos, 100);

                if ((newpasses = getnpasses(s)) < 0)

                    return newpasses;

                if ((llen = getlblockinc(s)) < 0)

                    return llen;

                cblk->lblock += llen;

                if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)

                    return ret;

                cblk->lengthinc = ret;

                cblk->npasses += newpasses;

            }

    }

    j2k_flush(s);

    if (codsty->csty & JPEG2000_CSTY_EPH) {

        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH) {

            bytestream2_skip(&s->g, 2);

        } else {

            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");

        }

    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++){

        Jpeg2000Band *band = rlevel->band + bandno;

        int yi, cblknw = band->prec[precno].xi1 - band->prec[precno].xi0;

        for (yi = band->prec[precno].yi0; yi < band->prec[precno].yi1; yi++){

            int xi;

            for (xi = band->prec[precno].xi0; xi < band->prec[precno].xi1; xi++){

                Jpeg2000Cblk *cblk = band->cblk + yi * cblknw + xi;

                if (bytestream2_get_bytes_left(&s->g) < cblk->lengthinc)

                    return AVERROR(EINVAL);

                bytestream2_get_bufferu(&s->g, cblk->data, cblk->lengthinc);

                cblk->length += cblk->lengthinc;

                cblk->lengthinc = 0;

            }

        }

    }

    return 0;

}


static void avc_luma_vt_and_aver_dst_8x8_msa(const uint8_t *src,

                                             int32_t src_stride,

                                             uint8_t *dst, int32_t dst_stride)

{

    int32_t loop_cnt;

    int16_t filt_const0 = 0xfb01;

    int16_t filt_const1 = 0x1414;

    int16_t filt_const2 = 0x1fb;

    v16u8 dst0, dst1, dst2, dst3;

    v16i8 src0, src1, src2, src3, src4, src7, src8, src9, src10;

    v16i8 src10_r, src32_r, src76_r, src98_r;

    v16i8 src21_r, src43_r, src87_r, src109_r;

    v8i16 out0, out1, out2, out3;

    v16i8 filt0, filt1, filt2;

    filt0 = (v16i8) __msa_fill_h(filt_const0);

    filt1 = (v16i8) __msa_fill_h(filt_const1);

    filt2 = (v16i8) __msa_fill_h(filt_const2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_r, src21_r, src32_r, src43_r);

    for (loop_cnt = 2; loop_cnt--;) {

        LD_SB4(src, src_stride, src7, src8, src9, src10);

        src += (4 * src_stride);

        XORI_B4_128_SB(src7, src8, src9, src10);

        ILVR_B4_SB(src7, src4, src8, src7, src9, src8, src10, src9,

                   src76_r, src87_r, src98_r, src109_r);

        out0 = DPADD_SH3_SH(src10_r, src32_r, src76_r, filt0, filt1, filt2);

        out1 = DPADD_SH3_SH(src21_r, src43_r, src87_r, filt0, filt1, filt2);

        out2 = DPADD_SH3_SH(src32_r, src76_r, src98_r, filt0, filt1, filt2);

        out3 = DPADD_SH3_SH(src43_r, src87_r, src109_r, filt0, filt1, filt2);

        SRARI_H4_SH(out0, out1, out2, out3, 5);

        SAT_SH4_SH(out0, out1, out2, out3, 7);

        LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3);

        ILVR_D2_UB(dst1, dst0, dst3, dst2, dst0, dst1);

        CONVERT_UB_AVG_ST8x4_UB(out0, out1, out2, out3, dst0, dst1,

                                dst, dst_stride);

        dst += (4 * dst_stride);

        src10_r = src76_r;

        src32_r = src98_r;

        src21_r = src87_r;

        src43_r = src109_r;

        src4 = src10;

    }

}


int main (int argc, char **argv)

{

    int ret = 0, got_frame;

    if (argc != 4 && argc != 5) {

        fprintf(stderr, "usage: %s [-refcount=<old|new_norefcount|new_refcount>] "

                "input_file video_output_file audio_output_file\n"

                "API example program to show how to read frames from an input file.\n"

                "This program reads frames from a file, decodes them, and writes decoded\n"

                "video frames to a rawvideo file named video_output_file, and decoded\n"

                "audio frames to a rawaudio file named audio_output_file.\n\n"

                "If the -refcount option is specified, the program use the\n"

                "reference counting frame system which allows keeping a copy of\n"

                "the data for longer than one decode call. If unset, it's using\n"

                "the classic old method.\n"

                "\n", argv[0]);

        exit(1);

    }

    if (argc == 5) {

        const char *mode = argv[1] + strlen("-refcount=");

        if      (!strcmp(mode, "old"))            api_mode = API_MODE_OLD;

        else if (!strcmp(mode, "new_norefcount")) api_mode = API_MODE_NEW_API_NO_REF_COUNT;

        else if (!strcmp(mode, "new_refcount"))   api_mode = API_MODE_NEW_API_REF_COUNT;

        else {

            fprintf(stderr, "unknow mode '%s'\n", mode);

            exit(1);

        }

        argv++;

    }

    src_filename = argv[1];

    video_dst_filename = argv[2];

    audio_dst_filename = argv[3];

    /* register all formats and codecs */

    av_register_all();

    /* open input file, and allocate format context */

    if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {

        fprintf(stderr, "Could not open source file %s\n", src_filename);

        exit(1);

    }

    /* retrieve stream information */

    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {

        fprintf(stderr, "Could not find stream information\n");

        exit(1);

    }

    if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {

        video_stream = fmt_ctx->streams[video_stream_idx];

        video_dec_ctx = video_stream->codec;

        video_dst_file = fopen(video_dst_filename, "wb");

        if (!video_dst_file) {

            fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);

            ret = 1;

            goto end;

        }

        /* allocate image where the decoded image will be put */

        ret = av_image_alloc(video_dst_data, video_dst_linesize,

                             video_dec_ctx->width, video_dec_ctx->height,

                             video_dec_ctx->pix_fmt, 1);

        if (ret < 0) {

            fprintf(stderr, "Could not allocate raw video buffer\n");

            goto end;

        }

        video_dst_bufsize = ret;

    }

    if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {

        audio_stream = fmt_ctx->streams[audio_stream_idx];

        audio_dec_ctx = audio_stream->codec;

        audio_dst_file = fopen(audio_dst_filename, "wb");

        if (!audio_dst_file) {

            fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);

            ret = 1;

            goto end;

        }

    }

    /* dump input information to stderr */

    av_dump_format(fmt_ctx, 0, src_filename, 0);

    if (!audio_stream && !video_stream) {

        fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");

        ret = 1;

        goto end;

    }

    /* When using the new API, you need to use the libavutil/frame.h API, while

     * the classic frame management is available in libavcodec */

    if (api_mode == API_MODE_OLD)

        frame = avcodec_alloc_frame();

    else

        frame = av_frame_alloc();

    if (!frame) {

        fprintf(stderr, "Could not allocate frame\n");

        ret = AVERROR(ENOMEM);

        goto end;

    }

    /* initialize packet, set data to NULL, let the demuxer fill it */

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (video_stream)

        printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);

    if (audio_stream)

        printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);

    /* read frames from the file */

    while (av_read_frame(fmt_ctx, &pkt) >= 0) {

        AVPacket orig_pkt = pkt;

        do {

            ret = decode_packet(&got_frame, 0);

            if (ret < 0)

                break;

            pkt.data += ret;

            pkt.size -= ret;

        } while (pkt.size > 0);

        av_free_packet(&orig_pkt);

    }

    /* flush cached frames */

    pkt.data = NULL;

    pkt.size = 0;

    do {

        decode_packet(&got_frame, 1);

    } while (got_frame);

    printf("Demuxing succeeded.\n");

    if (video_stream) {

        printf("Play the output video file with the command:\n"

               "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",

               av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,

               video_dst_filename);

    }

    if (audio_stream) {

        enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;

        int n_channels = audio_dec_ctx->channels;

        const char *fmt;

        if (av_sample_fmt_is_planar(sfmt)) {

            const char *packed = av_get_sample_fmt_name(sfmt);

            printf("Warning: the sample format the decoder produced is planar "

                   "(%s). This example will output the first channel only.\n",

                   packed ? packed : "?");

            sfmt = av_get_packed_sample_fmt(sfmt);

            n_channels = 1;

        }

        if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)

            goto end;

        printf("Play the output audio file with the command:\n"

               "ffplay -f %s -ac %d -ar %d %s\n",

               fmt, n_channels, audio_dec_ctx->sample_rate,

               audio_dst_filename);

    }

end:

    if (video_dec_ctx)

        avcodec_close(video_dec_ctx);

    if (audio_dec_ctx)

        avcodec_close(audio_dec_ctx);

    avformat_close_input(&fmt_ctx);

    if (video_dst_file)

        fclose(video_dst_file);

    if (audio_dst_file)

        fclose(audio_dst_file);

    if (api_mode == API_MODE_OLD)

        avcodec_free_frame(&frame);

    else

        av_frame_free(&frame);

    av_free(video_dst_data[0]);

    return ret < 0;

}


void ff_celp_lp_synthesis_filterf(float *out,

                                  const float* filter_coeffs,

                                  const float* in,

                                  int buffer_length,

                                  int filter_length)

{

    int i,n;

    // Avoids a +1 in the inner loop.

    filter_length++;

    for (n = 0; n < buffer_length; n++) {

        out[n] = in[n];

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

            out[n] -= filter_coeffs[i-1] * out[n-i];

    }

}


static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    BinkDemuxContext *bink = s->priv_data;

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

    if (!s->pb->seekable)

        return -1;

    /* seek to the first frame */

    if (avio_seek(s->pb, vst->index_entries[0].pos, SEEK_SET) < 0)

        return -1;

    bink->video_pts = 0;

    memset(bink->audio_pts, 0, sizeof(bink->audio_pts));

    bink->current_track = -1;

    return 0;

}


static int dvvideo_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 UINT8 *buf, int buf_size)

{

    DVVideoDecodeContext *s = avctx->priv_data;

    int sct, dsf, apt, ds, nb_dif_segs, vs, width, height, i, packet_size;

    unsigned size;

    UINT8 *buf_ptr;

    const UINT16 *mb_pos_ptr;

    AVPicture *picture;

    /* parse id */

    init_get_bits(&s->gb, buf, buf_size);

    sct = get_bits(&s->gb, 3);

    if (sct != 0)

        return -1;

    skip_bits(&s->gb, 5);

    get_bits(&s->gb, 4); /* dsn (sequence number */

    get_bits(&s->gb, 1); /* fsc (channel number) */

    skip_bits(&s->gb, 3);

    get_bits(&s->gb, 8); /* dbn (diff block number 0-134) */

    dsf = get_bits(&s->gb, 1); /* 0 = NTSC 1 = PAL */

    if (get_bits(&s->gb, 1) != 0)

        return -1;

    skip_bits(&s->gb, 11);

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

    get_bits(&s->gb, 1); /* tf1 */

    skip_bits(&s->gb, 4);

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

    get_bits(&s->gb, 1); /* tf2 */

    skip_bits(&s->gb, 4);

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

    get_bits(&s->gb, 1); /* tf3 */

    skip_bits(&s->gb, 4);

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

    /* init size */

    width = 720;

    if (dsf) {

        avctx->frame_rate = 25 * FRAME_RATE_BASE;

        packet_size = PAL_FRAME_SIZE;

        height = 576;

        nb_dif_segs = 12;

    } else {

        avctx->frame_rate = 30 * FRAME_RATE_BASE;

        packet_size = NTSC_FRAME_SIZE;

        height = 480;

        nb_dif_segs = 10;

    }

    /* NOTE: we only accept several full frames */

    if (buf_size < packet_size)

        return -1;

    /* XXX: is it correct to assume that 420 is always used in PAL

       mode ? */

    s->sampling_411 = !dsf;

    if (s->sampling_411) {

        mb_pos_ptr = dv_place_411;

        avctx->pix_fmt = PIX_FMT_YUV411P;

    } else {

        mb_pos_ptr = dv_place_420;

        avctx->pix_fmt = PIX_FMT_YUV420P;

    }

    avctx->width = width;

    avctx->height = height;

    if (avctx->flags & CODEC_FLAG_DR1 && avctx->get_buffer_callback)

    {

	s->width = -1;

	avctx->dr_buffer[0] = avctx->dr_buffer[1] = avctx->dr_buffer[2] = 0;

	if(avctx->get_buffer_callback(avctx, width, height, I_TYPE) < 0){

	    fprintf(stderr, "get_buffer() failed\n");

	    return -1;

	}

    }

    /* (re)alloc picture if needed */

    if (s->width != width || s->height != height) {

	if (!(avctx->flags & CODEC_FLAG_DR1))

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

		if (avctx->dr_buffer[i] != s->current_picture[i])

		    av_freep(&s->current_picture[i]);

		avctx->dr_buffer[i] = 0;

	    }

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

	    if (avctx->dr_buffer[i]) {

		s->current_picture[i] = avctx->dr_buffer[i];

		s->linesize[i] = (i == 0) ? avctx->dr_stride : avctx->dr_uvstride;

	    } else {

		size = width * height;

		s->linesize[i] = width;

		if (i >= 1) {

		    size >>= 2;

		    s->linesize[i] >>= s->sampling_411 ? 2 : 1;

		}

		s->current_picture[i] = av_malloc(size);

	    }

            if (!s->current_picture[i])

                return -1;

        }

        s->width = width;

        s->height = height;

    }

    /* for each DIF segment */

    buf_ptr = buf;

    for (ds = 0; ds < nb_dif_segs; ds++) {

        buf_ptr += 6 * 80; /* skip DIF segment header */

        for(vs = 0; vs < 27; vs++) {

            if ((vs % 3) == 0) {

                /* skip audio block */

                buf_ptr += 80;

            }

            dv_decode_video_segment(s, buf_ptr, mb_pos_ptr);

            buf_ptr += 5 * 80;

            mb_pos_ptr += 5;

        }

    }

    emms_c();

    /* return image */

    *data_size = sizeof(AVPicture);

    picture = data;

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

        picture->data[i] = s->current_picture[i];

        picture->linesize[i] = s->linesize[i];

    }

    return packet_size;

}


static int audio_read_header(AVFormatContext *s1, AVFormatParameters *ap)

{

    AudioData *s = s1->priv_data;

    AVStream *st;

    int ret;

    if (!ap || ap->sample_rate <= 0 || ap->channels <= 0)

        return -1;

    st = av_new_stream(s1, 0);

    if (!st) {

        return -ENOMEM;

    }

    s->sample_rate = ap->sample_rate;

    s->channels = ap->channels;

    ret = audio_open(s, 0, ap->device);

    if (ret < 0) {

        av_free(st);

        return AVERROR_IO;

    }

    /* take real parameters */

    st->codec->codec_type = CODEC_TYPE_AUDIO;

    st->codec->codec_id = s->codec_id;

    st->codec->sample_rate = s->sample_rate;

    st->codec->channels = s->channels;

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

    return 0;

}


char *ff_get_ref_perms_string(char *buf, size_t buf_size, int perms)

{

    snprintf(buf, buf_size, "%s%s%s%s%s",

             perms & AV_PERM_READ      ? "r" : "",

             perms & AV_PERM_WRITE     ? "w" : "",

             perms & AV_PERM_PRESERVE  ? "p" : "",

             perms & AV_PERM_REUSE     ? "u" : "",

             perms & AV_PERM_REUSE2    ? "U" : "");

    return buf;

}


static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst,

                              int linesize, int l, int t, int w, int h)

{

    const int y_start = t * linesize;

    const uint32_t *src_px, *src_pr,

                   *src_py = src + y_start,

                   *dst_py = dst + y_start;

    const uint32_t *src_pb = src_py + t * linesize;

    uint32_t *dst_px;

    for (; src_py < src_pb; src_py += linesize, dst_py += linesize) {

        src_px = src_py + l;

        dst_px = (uint32_t *)dst_py + l;

        src_pr = src_px + w;

        for (; src_px < src_pr; src_px++, dst_px++)

            *dst_px = *src_px;

    }

}


static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                             const AVFrame *frame, int *got_packet_ptr)

{

    AlacEncodeContext *s = avctx->priv_data;

    int out_bytes, max_frame_size, ret;

    s->frame_size = frame->nb_samples;

    if (frame->nb_samples < DEFAULT_FRAME_SIZE)

        max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,

                                            avctx->bits_per_raw_sample);

    else

        max_frame_size = s->max_coded_frame_size;

    if ((ret = ff_alloc_packet2(avctx, avpkt, 2 * max_frame_size)))

        return ret;

    /* use verbatim mode for compression_level 0 */

    if (s->compression_level) {

        s->verbatim   = 0;

        s->extra_bits = avctx->bits_per_raw_sample - 16;

    } else {

        s->verbatim   = 1;

        s->extra_bits = 0;

    }

    out_bytes = write_frame(s, avpkt, frame->extended_data);

    if (out_bytes > max_frame_size) {

        /* frame too large. use verbatim mode */

        s->verbatim = 1;

        s->extra_bits = 0;

        out_bytes = write_frame(s, avpkt, frame->extended_data);

    }

    avpkt->size = out_bytes;

    *got_packet_ptr = 1;

    return 0;

}


static int bmdma_rw_buf(IDEDMA *dma, int is_write)

{

    BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);

    IDEState *s = bmdma_active_if(bm);

    struct {

        uint32_t addr;

        uint32_t size;

    } prd;

    int l, len;

    for(;;) {

        l = s->io_buffer_size - s->io_buffer_index;

        if (l <= 0)

            break;

        if (bm->cur_prd_len == 0) {

            /* end of table (with a fail safe of one page) */

            if (bm->cur_prd_last ||

                (bm->cur_addr - bm->addr) >= BMDMA_PAGE_SIZE)

                return 0;

            cpu_physical_memory_read(bm->cur_addr, (uint8_t *)&prd, 8);

            bm->cur_addr += 8;

            prd.addr = le32_to_cpu(prd.addr);

            prd.size = le32_to_cpu(prd.size);

            len = prd.size & 0xfffe;

            if (len == 0)

                len = 0x10000;

            bm->cur_prd_len = len;

            bm->cur_prd_addr = prd.addr;

            bm->cur_prd_last = (prd.size & 0x80000000);

        }

        if (l > bm->cur_prd_len)

            l = bm->cur_prd_len;

        if (l > 0) {

            if (is_write) {

                cpu_physical_memory_write(bm->cur_prd_addr,

                                          s->io_buffer + s->io_buffer_index, l);

            } else {

                cpu_physical_memory_read(bm->cur_prd_addr,

                                          s->io_buffer + s->io_buffer_index, l);

            }

            bm->cur_prd_addr += l;

            bm->cur_prd_len -= l;

            s->io_buffer_index += l;

        }

    }

    return 1;

}


static void gen_dmfc0 (DisasContext *ctx, int reg, int sel)

{

    const char *rn = "invalid";

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

           gen_op_mfc0_index();

            rn = "Index";

            break;

        case 1:

//         gen_op_dmfc0_mvpcontrol(); /* MT ASE */

            rn = "MVPControl";

//         break;

        case 2:

//         gen_op_dmfc0_mvpconf0(); /* MT ASE */

            rn = "MVPConf0";

//         break;

        case 3:

//         gen_op_dmfc0_mvpconf1(); /* MT ASE */

            rn = "MVPConf1";

//         break;

        default:

            goto die;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

            gen_op_mfc0_random();

            rn = "Random";

           break;

        case 1:

//         gen_op_dmfc0_vpecontrol(); /* MT ASE */

            rn = "VPEControl";

//         break;

        case 2:

//         gen_op_dmfc0_vpeconf0(); /* MT ASE */

            rn = "VPEConf0";

//         break;

        case 3:

//         gen_op_dmfc0_vpeconf1(); /* MT ASE */

            rn = "VPEConf1";

//         break;

        case 4:

//         gen_op_dmfc0_YQMask(); /* MT ASE */

            rn = "YQMask";

//         break;

        case 5:

//         gen_op_dmfc0_vpeschedule(); /* MT ASE */

            rn = "VPESchedule";

//         break;

        case 6:

//         gen_op_dmfc0_vpeschefback(); /* MT ASE */

            rn = "VPEScheFBack";

//         break;

        case 7:

//         gen_op_dmfc0_vpeopt(); /* MT ASE */

            rn = "VPEOpt";

//         break;

        default:

            goto die;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

           gen_op_dmfc0_entrylo0();

           rn = "EntryLo0";

           break;

        case 1:

//         gen_op_dmfc0_tcstatus(); /* MT ASE */

           rn = "TCStatus";

//         break;

        case 2:

//         gen_op_dmfc0_tcbind(); /* MT ASE */

           rn = "TCBind";

//         break;

        case 3:

//         gen_op_dmfc0_tcrestart(); /* MT ASE */

           rn = "TCRestart";

//         break;

        case 4:

//         gen_op_dmfc0_tchalt(); /* MT ASE */

           rn = "TCHalt";

//         break;

        case 5:

//         gen_op_dmfc0_tccontext(); /* MT ASE */

           rn = "TCContext";

//         break;

        case 6:

//         gen_op_dmfc0_tcschedule(); /* MT ASE */

           rn = "TCSchedule";

//         break;

        case 7:

//         gen_op_dmfc0_tcschefback(); /* MT ASE */

           rn = "TCScheFBack";

//         break;

        default:

            goto die;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

           gen_op_dmfc0_entrylo1();

           rn = "EntryLo1";

           break;

        default:

            goto die;

       }

        break;

    case 4:

        switch (sel) {

        case 0:

           gen_op_dmfc0_context();

           rn = "Context";

           break;

        case 1:

//         gen_op_dmfc0_contextconfig(); /* SmartMIPS ASE */

           rn = "ContextConfig";

//         break;

        default:

            goto die;

       }

        break;

    case 5:

        switch (sel) {

        case 0:

           gen_op_mfc0_pagemask();

           rn = "PageMask";

           break;

        case 1:

           gen_op_mfc0_pagegrain();

           rn = "PageGrain";

           break;

        default:

            goto die;

       }

        break;

    case 6:

        switch (sel) {

        case 0:

           gen_op_mfc0_wired();

           rn = "Wired";

           break;

        case 1:

//         gen_op_dmfc0_srsconf0(); /* shadow registers */

           rn = "SRSConf0";

//         break;

        case 2:

//         gen_op_dmfc0_srsconf1(); /* shadow registers */

           rn = "SRSConf1";

//         break;

        case 3:

//         gen_op_dmfc0_srsconf2(); /* shadow registers */

           rn = "SRSConf2";

//         break;

        case 4:

//         gen_op_dmfc0_srsconf3(); /* shadow registers */

           rn = "SRSConf3";

//         break;

        case 5:

//         gen_op_dmfc0_srsconf4(); /* shadow registers */

           rn = "SRSConf4";

//         break;

        default:

            goto die;

       }

        break;

    case 7:

        switch (sel) {

        case 0:

           gen_op_mfc0_hwrena();

           rn = "HWREna";

           break;

        default:

            goto die;

       }

        break;

    case 8:

        switch (sel) {

        case 0:

           gen_op_dmfc0_badvaddr();

           rn = "BadVaddr";

           break;

        default:

            goto die;

       }

        break;

    case 9:

        switch (sel) {

        case 0:

           gen_op_mfc0_count();

           rn = "Count";

           break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

       }

        break;

    case 10:

        switch (sel) {

        case 0:

           gen_op_dmfc0_entryhi();

           rn = "EntryHi";

           break;

        default:

            goto die;

       }

        break;

    case 11:

        switch (sel) {

        case 0:

           gen_op_mfc0_compare();

           rn = "Compare";

           break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

       }

        break;

    case 12:

        switch (sel) {

        case 0:

           gen_op_mfc0_status();

           rn = "Status";

           break;

        case 1:

           gen_op_mfc0_intctl();

           rn = "IntCtl";

           break;

        case 2:

           gen_op_mfc0_srsctl();

           rn = "SRSCtl";

           break;

        case 3:

           gen_op_mfc0_srsmap(); /* shadow registers */

           rn = "SRSMap";

           break;

        default:

            goto die;

       }

        break;

    case 13:

        switch (sel) {

        case 0:

           gen_op_mfc0_cause();

           rn = "Cause";

           break;

        default:

            goto die;

       }

        break;

    case 14:

        switch (sel) {

        case 0:

           gen_op_dmfc0_epc();

           rn = "EPC";

           break;

        default:

            goto die;

       }

        break;

    case 15:

        switch (sel) {

        case 0:

           gen_op_mfc0_prid();

           rn = "PRid";

           break;

        case 1:

           gen_op_dmfc0_ebase();

           rn = "EBase";

           break;

        default:

            goto die;

       }

        break;

    case 16:

        switch (sel) {

        case 0:

           gen_op_mfc0_config0();

            rn = "Config";

            break;

        case 1:

           gen_op_mfc0_config1();

            rn = "Config1";

            break;

        case 2:

           gen_op_mfc0_config2();

            rn = "Config2";

            break;

        case 3:

           gen_op_mfc0_config3();

            rn = "Config3";

            break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

        }

        break;

    case 17:

        switch (sel) {

        case 0:

           gen_op_dmfc0_lladdr();

           rn = "LLAddr";

           break;

        default:

            goto die;

        }

        break;

    case 18:

        switch (sel) {

        case 0:

           gen_op_dmfc0_watchlo0();

           rn = "WatchLo";

           break;

        case 1:

//         gen_op_dmfc0_watchlo1();

           rn = "WatchLo1";

//         break;

        case 2:

//         gen_op_dmfc0_watchlo2();

           rn = "WatchLo2";

//         break;

        case 3:

//         gen_op_dmfc0_watchlo3();

           rn = "WatchLo3";

//         break;

        case 4:

//         gen_op_dmfc0_watchlo4();

           rn = "WatchLo4";

//         break;

        case 5:

//         gen_op_dmfc0_watchlo5();

           rn = "WatchLo5";

//         break;

        case 6:

//         gen_op_dmfc0_watchlo6();

           rn = "WatchLo6";

//         break;

        case 7:

//         gen_op_dmfc0_watchlo7();

           rn = "WatchLo7";

//         break;

        default:

            goto die;

        }

        break;

    case 19:

        switch (sel) {

        case 0:

           gen_op_mfc0_watchhi0();

           rn = "WatchHi";

           break;

        case 1:

//         gen_op_mfc0_watchhi1();

           rn = "WatchHi1";

//         break;

        case 2:

//         gen_op_mfc0_watchhi2();

           rn = "WatchHi2";

//         break;

        case 3:

//         gen_op_mfc0_watchhi3();

           rn = "WatchHi3";

//         break;

        case 4:

//         gen_op_mfc0_watchhi4();

           rn = "WatchHi4";

//         break;

        case 5:

//         gen_op_mfc0_watchhi5();

           rn = "WatchHi5";

//         break;

        case 6:

//         gen_op_mfc0_watchhi6();

           rn = "WatchHi6";

//         break;

        case 7:

//         gen_op_mfc0_watchhi7();

           rn = "WatchHi7";

//         break;

        default:

            goto die;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

           /* 64 bit MMU only */

           gen_op_dmfc0_xcontext();

           rn = "XContext";

           break;

        default:

            goto die;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        switch (sel) {

        case 0:

           gen_op_mfc0_framemask();

           rn = "Framemask";

           break;

        default:

            goto die;

        }

        break;

    case 22:

       /* ignored */

       rn = "'Diagnostic"; /* implementation dependent */

       break;

    case 23:

        switch (sel) {

        case 0:

           gen_op_mfc0_debug(); /* EJTAG support */

           rn = "Debug";

           break;

        case 1:

//         gen_op_dmfc0_tracecontrol(); /* PDtrace support */

           rn = "TraceControl";

//         break;

        case 2:

//         gen_op_dmfc0_tracecontrol2(); /* PDtrace support */

           rn = "TraceControl2";

//         break;

        case 3:

//         gen_op_dmfc0_usertracedata(); /* PDtrace support */

           rn = "UserTraceData";

//         break;

        case 4:

//         gen_op_dmfc0_debug(); /* PDtrace support */

           rn = "TraceBPC";

//         break;

        default:

            goto die;

        }

        break;

    case 24:

        switch (sel) {

        case 0:

           gen_op_dmfc0_depc(); /* EJTAG support */

           rn = "DEPC";

           break;

        default:

            goto die;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

           gen_op_mfc0_performance0();

           rn = "Performance0";

            break;

        case 1:

//         gen_op_dmfc0_performance1();

           rn = "Performance1";

//         break;

        case 2:

//         gen_op_dmfc0_performance2();

           rn = "Performance2";

//         break;

        case 3:

//         gen_op_dmfc0_performance3();

           rn = "Performance3";

//         break;

        case 4:

//         gen_op_dmfc0_performance4();

           rn = "Performance4";

//         break;

        case 5:

//         gen_op_dmfc0_performance5();

           rn = "Performance5";

//         break;

        case 6:

//         gen_op_dmfc0_performance6();

           rn = "Performance6";

//         break;

        case 7:

//         gen_op_dmfc0_performance7();

           rn = "Performance7";

//         break;

        default:

            goto die;

        }

        break;

    case 26:

       rn = "ECC";

       break;

    case 27:

        switch (sel) {

        /* ignored */

        case 0 ... 3:

           rn = "CacheErr";

           break;

        default:

            goto die;

        }

        break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taglo();

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datalo();

            rn = "DataLo";

            break;

        default:

            goto die;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mfc0_taghi();

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

            gen_op_mfc0_datahi();

            rn = "DataHi";

            break;

        default:

            goto die;

        }

        break;

    case 30:

        switch (sel) {

        case 0:

           gen_op_dmfc0_errorepc();

           rn = "ErrorEPC";

           break;

        default:

            goto die;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

           gen_op_mfc0_desave(); /* EJTAG support */

           rn = "DESAVE";

           break;

        default:

            goto die;

        }

        break;

    default:

       goto die;

    }

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    return;

die:

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmfc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    generate_exception(ctx, EXCP_RI);

}


static void create_cpu(const char *cpu_model,

                       qemu_irq *cbus_irq, qemu_irq *i8259_irq)

{

    CPUMIPSState *env;

    MIPSCPU *cpu;

    int i;

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "20Kc";

#else

        cpu_model = "24Kf";

#endif

    }

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

        cpu = cpu_mips_init(cpu_model);

        if (cpu == NULL) {

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

            exit(1);

        }

        env = &cpu->env;

        /* Init internal devices */

        cpu_mips_irq_init_cpu(env);

        cpu_mips_clock_init(env);

        qemu_register_reset(main_cpu_reset, cpu);

    }

    cpu = MIPS_CPU(first_cpu);

    env = &cpu->env;

    *i8259_irq = env->irq[2];

    *cbus_irq = env->irq[4];

}


void qed_release(BDRVQEDState *s)

{

    aio_context_release(bdrv_get_aio_context(s->bs));

}


int v9fs_co_readlink(V9fsPDU *pdu, V9fsPath *path, V9fsString *buf)

{

    int err;

    ssize_t len;

    V9fsState *s = pdu->s;

    if (v9fs_request_cancelled(pdu)) {

        return -EINTR;

    }

    buf->data = g_malloc(PATH_MAX);

    v9fs_path_read_lock(s);

    v9fs_co_run_in_worker(

        {

            len = s->ops->readlink(&s->ctx, path,

                                   buf->data, PATH_MAX - 1);

            if (len > -1) {

                buf->size = len;

                buf->data[len] = 0;

                err = 0;

            } else {

                err = -errno;

            }

        });

    v9fs_path_unlock(s);

    if (err) {

        g_free(buf->data);

        buf->data = NULL;

        buf->size = 0;

    }

    return err;

}


int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,

                          QCryptoTLSCreds *tlscreds, const char *hostname,

                          QIOChannel **outioc,

                          off_t *size, Error **errp)

{

    char buf[256];

    uint64_t magic, s;

    int rc;

    bool zeroes = true;

    TRACE("Receiving negotiation tlscreds=%p hostname=%s.",

          tlscreds, hostname ? hostname : "<null>");

    rc = -EINVAL;

    if (outioc) {

        *outioc = NULL;

    }

    if (tlscreds && !outioc) {

        error_setg(errp, "Output I/O channel required for TLS");

        goto fail;

    }

    if (read_sync(ioc, buf, 8, errp) < 0) {

        error_prepend(errp, "Failed to read data");

        goto fail;

    }

    buf[8] = '\0';

    if (strlen(buf) == 0) {

        error_setg(errp, "Server connection closed unexpectedly");

        goto fail;

    }

    TRACE("Magic is %c%c%c%c%c%c%c%c",

          qemu_isprint(buf[0]) ? buf[0] : '.',

          qemu_isprint(buf[1]) ? buf[1] : '.',

          qemu_isprint(buf[2]) ? buf[2] : '.',

          qemu_isprint(buf[3]) ? buf[3] : '.',

          qemu_isprint(buf[4]) ? buf[4] : '.',

          qemu_isprint(buf[5]) ? buf[5] : '.',

          qemu_isprint(buf[6]) ? buf[6] : '.',

          qemu_isprint(buf[7]) ? buf[7] : '.');

    if (memcmp(buf, "NBDMAGIC", 8) != 0) {

        error_setg(errp, "Invalid magic received");

        goto fail;

    }

    if (read_sync(ioc, &magic, sizeof(magic), errp) < 0) {

        error_prepend(errp, "Failed to read magic");

        goto fail;

    }

    magic = be64_to_cpu(magic);

    TRACE("Magic is 0x%" PRIx64, magic);

    if (magic == NBD_OPTS_MAGIC) {

        uint32_t clientflags = 0;

        uint16_t globalflags;

        bool fixedNewStyle = false;

        if (read_sync(ioc, &globalflags, sizeof(globalflags), errp) < 0) {

            error_prepend(errp, "Failed to read server flags");

            goto fail;

        }

        globalflags = be16_to_cpu(globalflags);

        TRACE("Global flags are %" PRIx32, globalflags);

        if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {

            fixedNewStyle = true;

            TRACE("Server supports fixed new style");

            clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;

        }

        if (globalflags & NBD_FLAG_NO_ZEROES) {

            zeroes = false;

            TRACE("Server supports no zeroes");

            clientflags |= NBD_FLAG_C_NO_ZEROES;

        }

        /* client requested flags */

        clientflags = cpu_to_be32(clientflags);

        if (write_sync(ioc, &clientflags, sizeof(clientflags), errp) < 0) {

            error_prepend(errp, "Failed to send clientflags field");

            goto fail;

        }

        if (tlscreds) {

            if (fixedNewStyle) {

                *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);

                if (!*outioc) {

                    goto fail;

                }

                ioc = *outioc;

            } else {

                error_setg(errp, "Server does not support STARTTLS");

                goto fail;

            }

        }

        if (!name) {

            TRACE("Using default NBD export name \"\"");

            name = "";

        }

        if (fixedNewStyle) {

            /* Check our desired export is present in the

             * server export list. Since NBD_OPT_EXPORT_NAME

             * cannot return an error message, running this

             * query gives us good error reporting if the

             * server required TLS

             */

            if (nbd_receive_query_exports(ioc, name, errp) < 0) {

                goto fail;

            }

        }

        /* write the export name request */

        if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,

                                    errp) < 0) {

            goto fail;

        }

        /* Read the response */

        if (read_sync(ioc, &s, sizeof(s), errp) < 0) {

            error_prepend(errp, "Failed to read export length");

            goto fail;

        }

        *size = be64_to_cpu(s);

        if (read_sync(ioc, flags, sizeof(*flags), errp) < 0) {

            error_prepend(errp, "Failed to read export flags");

            goto fail;

        }

        be16_to_cpus(flags);

    } else if (magic == NBD_CLIENT_MAGIC) {

        uint32_t oldflags;

        if (name) {

            error_setg(errp, "Server does not support export names");

            goto fail;

        }

        if (tlscreds) {

            error_setg(errp, "Server does not support STARTTLS");

            goto fail;

        }

        if (read_sync(ioc, &s, sizeof(s), errp) < 0) {

            error_prepend(errp, "Failed to read export length");

            goto fail;

        }

        *size = be64_to_cpu(s);

        TRACE("Size is %" PRIu64, *size);

        if (read_sync(ioc, &oldflags, sizeof(oldflags), errp) < 0) {

            error_prepend(errp, "Failed to read export flags");

            goto fail;

        }

        be32_to_cpus(&oldflags);

        if (oldflags & ~0xffff) {

            error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);

            goto fail;

        }

        *flags = oldflags;

    } else {

        error_setg(errp, "Bad magic received");

        goto fail;

    }

    TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);

    if (zeroes && drop_sync(ioc, 124, errp) < 0) {

        error_prepend(errp, "Failed to read reserved block");

        goto fail;

    }

    rc = 0;

fail:

    return rc;

}


void spapr_events_fdt_skel(void *fdt, uint32_t epow_irq)

{

    uint32_t epow_irq_ranges[] = {cpu_to_be32(epow_irq), cpu_to_be32(1)};

    uint32_t epow_interrupts[] = {cpu_to_be32(epow_irq), 0};

    _FDT((fdt_begin_node(fdt, "event-sources")));

    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));

    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));

    _FDT((fdt_property(fdt, "interrupt-ranges",

                       epow_irq_ranges, sizeof(epow_irq_ranges))));

    _FDT((fdt_begin_node(fdt, "epow-events")));

    _FDT((fdt_property(fdt, "interrupts",

                       epow_interrupts, sizeof(epow_interrupts))));

    _FDT((fdt_end_node(fdt)));

    _FDT((fdt_end_node(fdt)));

}


static void vfio_put_device(VFIOPCIDevice *vdev)

{

    QLIST_REMOVE(vdev, next);

    vdev->vbasedev.group = NULL;

    trace_vfio_put_device(vdev->vbasedev.fd);

    close(vdev->vbasedev.fd);

    g_free(vdev->vbasedev.name);

    if (vdev->msix) {

        g_free(vdev->msix);

        vdev->msix = NULL;

    }

}


static int open_self_cmdline(void *cpu_env, int fd)

{

    int fd_orig = -1;

    bool word_skipped = false;

    fd_orig = open("/proc/self/cmdline", O_RDONLY);

    if (fd_orig < 0) {

        return fd_orig;

    }

    while (true) {

        ssize_t nb_read;

        char buf[128];

        char *cp_buf = buf;

        nb_read = read(fd_orig, buf, sizeof(buf));

        if (nb_read < 0) {

            int e = errno;

            fd_orig = close(fd_orig);

            errno = e;

            return -1;

        } else if (nb_read == 0) {

            break;

        }

        if (!word_skipped) {

            /* Skip the first string, which is the path to qemu-*-static

               instead of the actual command. */

            cp_buf = memchr(buf, 0, sizeof(buf));

            if (cp_buf) {

                /* Null byte found, skip one string */

                cp_buf++;

                nb_read -= cp_buf - buf;

                word_skipped = true;

            }

        }

        if (word_skipped) {

            if (write(fd, cp_buf, nb_read) != nb_read) {

                int e = errno;

                close(fd_orig);

                errno = e;

                return -1;

            }

        }

    }

    return close(fd_orig);

}


static int xan_decode_frame_type1(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    uint8_t *ybuf, *src = s->scratch_buffer;

    int cur, last;

    int i, j;

    int ret;

    if ((ret = xan_decode_chroma(avctx, bytestream2_get_le32(&s->gb))) != 0)

        return ret;

    bytestream2_seek(&s->gb, 16, SEEK_SET);

    ret = xan_unpack_luma(s, src,

                          s->buffer_size >> 1);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");

        return ret;

    }

    ybuf = s->y_buffer;

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

        last = (ybuf[0] + (*src++ << 1)) & 0x3F;

        ybuf[0] = last;

        for (j = 1; j < avctx->width - 1; j += 2) {

            cur = (ybuf[j + 1] + (*src++ << 1)) & 0x3F;

            ybuf[j]   = (last + cur) >> 1;

            ybuf[j+1] = cur;

            last = cur;

        }

        ybuf[j] = last;

        ybuf += avctx->width;

    }

    src = s->y_buffer;

    ybuf = s->pic.data[0];

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

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

            ybuf[i] = (src[i] << 2) | (src[i] >> 3);

        src  += avctx->width;

        ybuf += s->pic.linesize[0];

    }

    return 0;

}


static void vtd_context_device_invalidate(IntelIOMMUState *s,

                                          uint16_t source_id,

                                          uint16_t func_mask)

{

    uint16_t mask;

    VTDAddressSpace **pvtd_as;

    VTDAddressSpace *vtd_as;

    uint16_t devfn;

    uint16_t devfn_it;

    switch (func_mask & 3) {

    case 0:

        mask = 0;   /* No bits in the SID field masked */

        break;

    case 1:

        mask = 4;   /* Mask bit 2 in the SID field */

        break;

    case 2:

        mask = 6;   /* Mask bit 2:1 in the SID field */

        break;

    case 3:

        mask = 7;   /* Mask bit 2:0 in the SID field */

        break;

    }

    VTD_DPRINTF(INV, "device-selective invalidation source 0x%"PRIx16

                    " mask %"PRIu16, source_id, mask);

    pvtd_as = s->address_spaces[VTD_SID_TO_BUS(source_id)];

    if (pvtd_as) {

        devfn = VTD_SID_TO_DEVFN(source_id);

        for (devfn_it = 0; devfn_it < VTD_PCI_DEVFN_MAX; ++devfn_it) {

            vtd_as = pvtd_as[devfn_it];

            if (vtd_as && ((devfn_it & mask) == (devfn & mask))) {

                VTD_DPRINTF(INV, "invalidate context-cahce of devfn 0x%"PRIx16,

                            devfn_it);

                vtd_as->context_cache_entry.context_cache_gen = 0;

            }

        }

    }

}


static int raw_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVRawState *s = bs->opaque;

    int access_flags;

    DWORD overlapped;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *filename;

    int ret;

    s->type = FTYPE_FILE;

    opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    filename = qemu_opt_get(opts, "filename");

    raw_parse_flags(flags, &access_flags, &overlapped);

    if (filename[0] && filename[1] == ':') {

        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", filename[0]);

    } else if (filename[0] == '\\' && filename[1] == '\\') {

        s->drive_path[0] = 0;

    } else {

        /* Relative path.  */

        char buf[MAX_PATH];

        GetCurrentDirectory(MAX_PATH, buf);

        snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", buf[0]);

    }

    s->hfile = CreateFile(filename, access_flags,

                          FILE_SHARE_READ, NULL,

                          OPEN_EXISTING, overlapped, NULL);

    if (s->hfile == INVALID_HANDLE_VALUE) {

        int err = GetLastError();

        if (err == ERROR_ACCESS_DENIED) {

            ret = -EACCES;

        } else {

            ret = -EINVAL;

        }

        goto fail;

    }

    if (flags & BDRV_O_NATIVE_AIO) {

        s->aio = win32_aio_init();

        if (s->aio == NULL) {

            CloseHandle(s->hfile);

            error_setg(errp, "Could not initialize AIO");

            ret = -EINVAL;

            goto fail;

        }

        ret = win32_aio_attach(s->aio, s->hfile);

        if (ret < 0) {

            win32_aio_cleanup(s->aio);

            CloseHandle(s->hfile);

            error_setg_errno(errp, -ret, "Could not enable AIO");

            goto fail;

        }

        win32_aio_attach_aio_context(s->aio, bdrv_get_aio_context(bs));

    }

    raw_probe_alignment(bs);

    ret = 0;

fail:

    qemu_opts_del(opts);

    return ret;

}


static struct omap_watchdog_timer_s *omap_wd_timer_init(MemoryRegion *memory,

                target_phys_addr_t base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_watchdog_timer_s *s = (struct omap_watchdog_timer_s *)

            g_malloc0(sizeof(struct omap_watchdog_timer_s));

    s->timer.irq = irq;

    s->timer.clk = clk;

    s->timer.timer = qemu_new_timer_ns(vm_clock, omap_timer_tick, &s->timer);

    omap_wd_timer_reset(s);

    omap_timer_clk_setup(&s->timer);

    memory_region_init_io(&s->iomem, &omap_wd_timer_ops, s,

                          "omap-wd-timer", 0x100);

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

    return s;

}


void qmp_block_job_cancel(const char *device,

                          bool has_force, bool force, Error **errp)

{

    BlockJob *job = find_block_job(device);

    if (!has_force) {

        force = false;

    }

    if (!job) {

        error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);

        return;

    }

    if (job->paused && !force) {

        error_setg(errp, "The block job for device '%s' is currently paused",

                   device);

        return;

    }

    trace_qmp_block_job_cancel(job);

    block_job_cancel(job);

}


static void gen_flt3_ldst (DisasContext *ctx, uint32_t opc,

                           int fd, int fs, int base, int index)

{

    const char *opn = "extended float load/store";

    int store = 0;

    TCGv t0 = tcg_temp_new();

    if (base == 0) {

        gen_load_gpr(t0, index);

    } else if (index == 0) {

        gen_load_gpr(t0, base);

    } else {

        gen_load_gpr(t0, index);

        gen_op_addr_add(ctx, t0, cpu_gpr[base]);

    }

    /* Don't do NOP if destination is zero: we must perform the actual

       memory access. */

    save_cpu_state(ctx, 0);

    switch (opc) {

    case OPC_LWXC1:

        check_cop1x(ctx);

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

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

            tcg_gen_trunc_tl_i32(fp0, t0);

            gen_store_fpr32(fp0, fd);

            tcg_temp_free_i32(fp0);

        }

        opn = "lwxc1";

        break;

    case OPC_LDXC1:

        check_cop1x(ctx);

        check_cp1_registers(ctx, fd);

        {

            TCGv_i64 fp0 = tcg_temp_new_i64();

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

            gen_store_fpr64(ctx, fp0, fd);

            tcg_temp_free_i64(fp0);

        }

        opn = "ldxc1";

        break;

    case OPC_LUXC1:

        check_cp1_64bitmode(ctx);

        tcg_gen_andi_tl(t0, t0, ~0x7);

        {

            TCGv_i64 fp0 = tcg_temp_new_i64();

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

            gen_store_fpr64(ctx, fp0, fd);

            tcg_temp_free_i64(fp0);

        }

        opn = "luxc1";

        break;

    case OPC_SWXC1:

        check_cop1x(ctx);

        {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            TCGv t1 = tcg_temp_new();

            gen_load_fpr32(fp0, fs);

            tcg_gen_extu_i32_tl(t1, fp0);

            tcg_gen_qemu_st32(t1, t0, ctx->mem_idx);

            tcg_temp_free_i32(fp0);

            tcg_temp_free_i32(t1);

        }

        opn = "swxc1";

        store = 1;

        break;

    case OPC_SDXC1:

        check_cop1x(ctx);

        check_cp1_registers(ctx, fs);

        {

            TCGv_i64 fp0 = tcg_temp_new_i64();

            gen_load_fpr64(ctx, fp0, fs);

            tcg_gen_qemu_st64(fp0, t0, ctx->mem_idx);

            tcg_temp_free_i64(fp0);

        }

        opn = "sdxc1";

        store = 1;

        break;

    case OPC_SUXC1:

        check_cp1_64bitmode(ctx);

        tcg_gen_andi_tl(t0, t0, ~0x7);

        {

            TCGv_i64 fp0 = tcg_temp_new_i64();

            gen_load_fpr64(ctx, fp0, fs);

            tcg_gen_qemu_st64(fp0, t0, ctx->mem_idx);

            tcg_temp_free_i64(fp0);

        }

        opn = "suxc1";

        store = 1;

        break;

    }

    tcg_temp_free(t0);

    MIPS_DEBUG("%s %s, %s(%s)", opn, fregnames[store ? fs : fd],

               regnames[index], regnames[base]);

}


static ioreq_t *cpu_get_ioreq(XenIOState *state)

{

    int i;

    evtchn_port_t port;

    port = xc_evtchn_pending(state->xce_handle);

    if (port == state->bufioreq_local_port) {

        timer_mod(state->buffered_io_timer,

                BUFFER_IO_MAX_DELAY + qemu_clock_get_ms(QEMU_CLOCK_REALTIME));

        return NULL;

    }

    if (port != -1) {

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

            if (state->ioreq_local_port[i] == port) {

                break;

            }

        }

        if (i == max_cpus) {

            hw_error("Fatal error while trying to get io event!\n");

        }

        /* unmask the wanted port again */

        xc_evtchn_unmask(state->xce_handle, port);

        /* get the io packet from shared memory */

        state->send_vcpu = i;

        return cpu_get_ioreq_from_shared_memory(state, i);

    }

    /* read error or read nothing */

    return NULL;

}


BlockDriverAIOCB *bdrv_aio_read(BlockDriverState *bs, int64_t sector_num,

                                uint8_t *buf, int nb_sectors,

                                BlockDriverCompletionFunc *cb, void *opaque)

{

    BlockDriver *drv = bs->drv;

    BlockDriverAIOCB *ret;

    if (!drv)

        return NULL;

    /* XXX: we assume that nb_sectors == 0 is suppored by the async read */

    if (sector_num == 0 && bs->boot_sector_enabled && nb_sectors > 0) {

        memcpy(buf, bs->boot_sector_data, 512);

        sector_num++;

        nb_sectors--;

        buf += 512;

    }

    ret = drv->bdrv_aio_read(bs, sector_num, buf, nb_sectors, cb, opaque);

    if (ret) {

	/* Update stats even though technically transfer has not happened. */

	bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;

	bs->rd_ops ++;

    }

    return ret;

}


static void tcp_chr_tls_init(Chardev *chr)

{

    SocketChardev *s = SOCKET_CHARDEV(chr);

    QIOChannelTLS *tioc;

    Error *err = NULL;

    gchar *name;

    if (s->is_listen) {

        tioc = qio_channel_tls_new_server(

            s->ioc, s->tls_creds,

            NULL, /* XXX Use an ACL */

            &err);

    } else {

        tioc = qio_channel_tls_new_client(

            s->ioc, s->tls_creds,

            s->addr->u.inet.data->host,

            &err);

    }

    if (tioc == NULL) {

        error_free(err);

        tcp_chr_disconnect(chr);

        return;

    }

    name = g_strdup_printf("chardev-tls-%s-%s",

                           s->is_listen ? "server" : "client",

                           chr->label);

    qio_channel_set_name(QIO_CHANNEL(tioc), name);

    g_free(name);

    object_unref(OBJECT(s->ioc));

    s->ioc = QIO_CHANNEL(tioc);

    qio_channel_tls_handshake(tioc,

                              tcp_chr_tls_handshake,

                              chr,

                              NULL);

}


static int aac_sync(uint64_t state, AACAC3ParseContext *hdr_info,

        int *need_next_header, int *new_frame_start)

{

    GetBitContext bits;

    int size, rdb, ch, sr;

    union {

        uint64_t u64;

        uint8_t  u8[8];

    } tmp;

    tmp.u64 = be2me_64(state);

    init_get_bits(&bits, tmp.u8+8-AAC_HEADER_SIZE, AAC_HEADER_SIZE * 8);

    if(get_bits(&bits, 12) != 0xfff)

        return 0;

    skip_bits1(&bits);          /* id */

    skip_bits(&bits, 2);        /* layer */

    skip_bits1(&bits);          /* protection_absent */

    skip_bits(&bits, 2);        /* profile_objecttype */

    sr = get_bits(&bits, 4);    /* sample_frequency_index */

    if(!ff_mpeg4audio_sample_rates[sr])

        return 0;

    skip_bits1(&bits);          /* private_bit */

    ch = get_bits(&bits, 3);    /* channel_configuration */

    if(!ff_mpeg4audio_channels[ch])

        return 0;

    skip_bits1(&bits);          /* original/copy */

    skip_bits1(&bits);          /* home */

    /* adts_variable_header */

    skip_bits1(&bits);          /* copyright_identification_bit */

    skip_bits1(&bits);          /* copyright_identification_start */

    size = get_bits(&bits, 13); /* aac_frame_length */

    if(size < AAC_HEADER_SIZE)

        return 0;

    skip_bits(&bits, 11);       /* adts_buffer_fullness */

    rdb = get_bits(&bits, 2);   /* number_of_raw_data_blocks_in_frame */

    hdr_info->channels = ff_mpeg4audio_channels[ch];

    hdr_info->sample_rate = ff_mpeg4audio_sample_rates[sr];

    hdr_info->samples = (rdb + 1) * 1024;

    hdr_info->bit_rate = size * 8 * hdr_info->sample_rate / hdr_info->samples;

    *need_next_header = 0;

    *new_frame_start  = 1;

    return size;

}


static int local_post_create_passthrough(FsContext *fs_ctx, const char *path,

                                         FsCred *credp)

{

    char buffer[PATH_MAX];

    if (chmod(rpath(fs_ctx, path, buffer), credp->fc_mode & 07777) < 0) {

        return -1;

    }

    if (lchown(rpath(fs_ctx, path, buffer), credp->fc_uid,

                credp->fc_gid) < 0) {

        /*

         * If we fail to change ownership and if we are

         * using security model none. Ignore the error

         */

        if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) {

            return -1;

        }

    }

    return 0;

}


void vga_reset(void *opaque)

{

    VGAState *s = (VGAState *) opaque;

    s->lfb_addr = 0;

    s->lfb_end = 0;

    s->map_addr = 0;

    s->map_end = 0;

    s->lfb_vram_mapped = 0;

    s->bios_offset = 0;

    s->bios_size = 0;

    s->sr_index = 0;

    memset(s->sr, '\0', sizeof(s->sr));

    s->gr_index = 0;

    memset(s->gr, '\0', sizeof(s->gr));

    s->ar_index = 0;

    memset(s->ar, '\0', sizeof(s->ar));

    s->ar_flip_flop = 0;

    s->cr_index = 0;

    memset(s->cr, '\0', sizeof(s->cr));

    s->msr = 0;

    s->fcr = 0;

    s->st00 = 0;

    s->st01 = 0;

    s->dac_state = 0;

    s->dac_sub_index = 0;

    s->dac_read_index = 0;

    s->dac_write_index = 0;

    memset(s->dac_cache, '\0', sizeof(s->dac_cache));

    s->dac_8bit = 0;

    memset(s->palette, '\0', sizeof(s->palette));

    s->bank_offset = 0;

#ifdef CONFIG_BOCHS_VBE

    s->vbe_index = 0;

    memset(s->vbe_regs, '\0', sizeof(s->vbe_regs));

    s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID0;

    s->vbe_start_addr = 0;

    s->vbe_line_offset = 0;

    s->vbe_bank_mask = (s->vram_size >> 16) - 1;

#endif

    memset(s->font_offsets, '\0', sizeof(s->font_offsets));

    s->graphic_mode = -1; /* force full update */

    s->shift_control = 0;

    s->double_scan = 0;

    s->line_offset = 0;

    s->line_compare = 0;

    s->start_addr = 0;

    s->plane_updated = 0;

    s->last_cw = 0;

    s->last_ch = 0;

    s->last_width = 0;

    s->last_height = 0;

    s->last_scr_width = 0;

    s->last_scr_height = 0;

    s->cursor_start = 0;

    s->cursor_end = 0;

    s->cursor_offset = 0;

    memset(s->invalidated_y_table, '\0', sizeof(s->invalidated_y_table));

    memset(s->last_palette, '\0', sizeof(s->last_palette));

    memset(s->last_ch_attr, '\0', sizeof(s->last_ch_attr));

    switch (vga_retrace_method) {

    case VGA_RETRACE_DUMB:

        break;

    case VGA_RETRACE_PRECISE:

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

        break;

    }

}


void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y,

                    uint8_t *segment, uint8_t *ref, int layout, int is_vp7)

{

    VP56RangeCoder *c = &s->c;

    static const char *vp7_feature_name[] = { "q-index",

                                              "lf-delta",

                                              "partial-golden-update",

                                              "blit-pitch" };

    if (is_vp7) {

        int i;

        *segment = 0;

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

            if (s->feature_enabled[i]) {

                if (vp56_rac_get_prob_branchy(c, s->feature_present_prob[i])) {

                      int index = vp8_rac_get_tree(c, vp7_feature_index_tree,

                                                   s->feature_index_prob[i]);

                      av_log(s->avctx, AV_LOG_WARNING,

                             "Feature %s present in macroblock (value 0x%x)\n",

                             vp7_feature_name[i], s->feature_value[i][index]);

                }

           }

        }

    } else if (s->segmentation.update_map) {

        int bit  = vp56_rac_get_prob(c, s->prob->segmentid[0]);

        *segment = vp56_rac_get_prob(c, s->prob->segmentid[1+bit]) + 2*bit;

    } else if (s->segmentation.enabled)

        *segment = ref ? *ref : *segment;

    mb->segment = *segment;

    mb->skip = s->mbskip_enabled ? vp56_rac_get_prob(c, s->prob->mbskip) : 0;

    if (s->keyframe) {

        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_intra,

                                    vp8_pred16x16_prob_intra);

        if (mb->mode == MODE_I4x4) {

            decode_intra4x4_modes(s, c, mb, mb_x, 1, layout);

        } else {

            const uint32_t modes = (is_vp7 ? vp7_pred4x4_mode

                                           : vp8_pred4x4_mode)[mb->mode] * 0x01010101u;

            if (s->mb_layout)

                AV_WN32A(mb->intra4x4_pred_mode_top, modes);

            else

                AV_WN32A(s->intra4x4_pred_mode_top + 4 * mb_x, modes);

            AV_WN32A(s->intra4x4_pred_mode_left, modes);

        }

        mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree,

                                                vp8_pred8x8c_prob_intra);

        mb->ref_frame        = VP56_FRAME_CURRENT;

    } else if (vp56_rac_get_prob_branchy(c, s->prob->intra)) {

        // inter MB, 16.2

        if (vp56_rac_get_prob_branchy(c, s->prob->last))

            mb->ref_frame =

                (!is_vp7 && vp56_rac_get_prob(c, s->prob->golden)) ? VP56_FRAME_GOLDEN2 /* altref */

                                                                   : VP56_FRAME_GOLDEN;

        else

            mb->ref_frame = VP56_FRAME_PREVIOUS;

        s->ref_count[mb->ref_frame - 1]++;

        // motion vectors, 16.3

        if (is_vp7)

            vp7_decode_mvs(s, mb, mb_x, mb_y, layout);

        else

            vp8_decode_mvs(s, mb, mb_x, mb_y, layout);

    } else {

        // intra MB, 16.1

        mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16);

        if (mb->mode == MODE_I4x4)

            decode_intra4x4_modes(s, c, mb, mb_x, 0, layout);

        mb->chroma_pred_mode = vp8_rac_get_tree(c, vp8_pred8x8c_tree,

                                                s->prob->pred8x8c);

        mb->ref_frame        = VP56_FRAME_CURRENT;

        mb->partitioning     = VP8_SPLITMVMODE_NONE;

        AV_ZERO32(&mb->bmv[0]);

    }

}


static void asfrtp_close_context(PayloadContext *asf)

{

    ffio_free_dyn_buf(&asf->pktbuf);

    av_freep(&asf->buf);

    av_free(asf);

}


static av_cold int dilate_init(AVFilterContext *ctx, const char *args)

{

    OCVContext *ocv = ctx->priv;

    DilateContext *dilate = ocv->priv;

    char default_kernel_str[] = "3x3+0x0/rect";

    char *kernel_str;

    const char *buf = args;

    int ret;

    dilate->nb_iterations = 1;

    if (args)

        kernel_str = av_get_token(&buf, "|");

    if ((ret = parse_iplconvkernel(&dilate->kernel,

                                   *kernel_str ? kernel_str : default_kernel_str,

                                   ctx)) < 0)

        return ret;

    av_free(kernel_str);

    sscanf(buf, "|%d", &dilate->nb_iterations);

    av_log(ctx, AV_LOG_VERBOSE, "iterations_nb:%d\n", dilate->nb_iterations);

    if (dilate->nb_iterations <= 0) {

        av_log(ctx, AV_LOG_ERROR, "Invalid non-positive value '%d' for nb_iterations\n",

               dilate->nb_iterations);

        return AVERROR(EINVAL);

    }

    return 0;

}


BlockDriverState *bdrv_new(void)
{
    BlockDriverState *bs;
    int i;
    bs = g_new0(BlockDriverState, 1);
    QLIST_INIT(&bs->dirty_bitmaps);
    for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
        QLIST_INIT(&bs->op_blockers[i]);
    }
    notifier_with_return_list_init(&bs->before_write_notifiers);
    bs->refcnt = 1;
    bs->aio_context = qemu_get_aio_context();
    QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
    return bs;
}


static inline void RENAME(bgr32ToUV)(uint8_t *dstU, uint8_t *dstV, uint8_t *src1, uint8_t *src2, int width)

{

	int i;

        assert(src1 == src2);

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

	{

		const int a= ((uint32_t*)src1)[2*i+0];

		const int e= ((uint32_t*)src1)[2*i+1];

		const int l= (a&0xFF00FF) + (e&0xFF00FF);

		const int h= (a&0x00FF00) + (e&0x00FF00);

 		const int b=  l&0x3FF;

		const int g=  h>>8;

		const int r=  l>>16;

		dstU[i]= ((RU*r + GU*g + BU*b)>>(RGB2YUV_SHIFT+1)) + 128;

		dstV[i]= ((RV*r + GV*g + BV*b)>>(RGB2YUV_SHIFT+1)) + 128;

	}

}


static int qemu_rdma_init_ram_blocks(RDMAContext *rdma)

{

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    assert(rdma->blockmap == NULL);

    rdma->blockmap = g_hash_table_new(g_direct_hash, g_direct_equal);

    memset(local, 0, sizeof *local);

    qemu_ram_foreach_block(qemu_rdma_init_one_block, rdma);

    DPRINTF("Allocated %d local ram block structures\n", local->nb_blocks);

    rdma->block = (RDMARemoteBlock *) g_malloc0(sizeof(RDMARemoteBlock) *

                        rdma->local_ram_blocks.nb_blocks);

    local->init = true;

    return 0;

}


static always_inline void gen_op_subfeo (void)

{

    gen_op_move_T2_T0();

    gen_op_subfe();

    gen_op_check_subfo();

}