gen_intermediate_code_internal(MIPSCPU *cpu, TranslationBlock *tb,

                               bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUMIPSState *env = &cpu->env;

    DisasContext ctx;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj = -1;

    int num_insns;

    int max_insns;

    int insn_bytes;

    int is_branch;

    if (search_pc)

        qemu_log("search pc %d\n", search_pc);

    pc_start = tb->pc;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    ctx.pc = pc_start;

    ctx.saved_pc = -1;

    ctx.singlestep_enabled = cs->singlestep_enabled;

    ctx.insn_flags = env->insn_flags;

    ctx.tb = tb;

    ctx.bstate = BS_NONE;

    /* Restore delay slot state from the tb context.  */

    ctx.hflags = (uint32_t)tb->flags; /* FIXME: maybe use 64 bits here? */

    restore_cpu_state(env, &ctx);

#ifdef CONFIG_USER_ONLY

        ctx.mem_idx = MIPS_HFLAG_UM;

#else

        ctx.mem_idx = ctx.hflags & MIPS_HFLAG_KSU;

#endif

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    LOG_DISAS("\ntb %p idx %d hflags %04x\n", tb, ctx.mem_idx, ctx.hflags);

    gen_tb_start();

    while (ctx.bstate == BS_NONE) {

        if (unlikely(!QTAILQ_EMPTY(&env->breakpoints))) {

            QTAILQ_FOREACH(bp, &env->breakpoints, entry) {

                if (bp->pc == ctx.pc) {

                    save_cpu_state(&ctx, 1);

                    ctx.bstate = BS_BRANCH;

                    gen_helper_0e0i(raise_exception, EXCP_DEBUG);

                    /* Include the breakpoint location or the tb won't

                     * be flushed when it must be.  */

                    ctx.pc += 4;

                    goto done_generating;

                }

            }

        }

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

            }

            tcg_ctx.gen_opc_pc[lj] = ctx.pc;

            gen_opc_hflags[lj] = ctx.hflags & MIPS_HFLAG_BMASK;

            gen_opc_btarget[lj] = ctx.btarget;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

        is_branch = 0;

        if (!(ctx.hflags & MIPS_HFLAG_M16)) {

            ctx.opcode = cpu_ldl_code(env, ctx.pc);

            insn_bytes = 4;

            decode_opc(env, &ctx, &is_branch);

        } else if (ctx.insn_flags & ASE_MICROMIPS) {

            ctx.opcode = cpu_lduw_code(env, ctx.pc);

            insn_bytes = decode_micromips_opc(env, &ctx, &is_branch);

        } else if (ctx.insn_flags & ASE_MIPS16) {

            ctx.opcode = cpu_lduw_code(env, ctx.pc);

            insn_bytes = decode_mips16_opc(env, &ctx, &is_branch);

        } else {

            generate_exception(&ctx, EXCP_RI);

            ctx.bstate = BS_STOP;

            break;

        }

        if (!is_branch) {

            handle_delay_slot(&ctx, insn_bytes);

        }

        ctx.pc += insn_bytes;

        num_insns++;

        /* Execute a branch and its delay slot as a single instruction.

           This is what GDB expects and is consistent with what the

           hardware does (e.g. if a delay slot instruction faults, the

           reported PC is the PC of the branch).  */

        if (cs->singlestep_enabled && (ctx.hflags & MIPS_HFLAG_BMASK) == 0) {

            break;

        }

        if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0)

            break;

        if (tcg_ctx.gen_opc_ptr >= gen_opc_end) {

            break;

        }

        if (num_insns >= max_insns)

            break;

        if (singlestep)

            break;

    }

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (cs->singlestep_enabled && ctx.bstate != BS_BRANCH) {

        save_cpu_state(&ctx, ctx.bstate == BS_NONE);

        gen_helper_0e0i(raise_exception, EXCP_DEBUG);

    } else {

        switch (ctx.bstate) {

        case BS_STOP:

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_NONE:

            save_cpu_state(&ctx, 0);

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_EXCP:

            tcg_gen_exit_tb(0);

            break;

        case BS_BRANCH:

        default:

            break;

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        lj++;

        while (lj <= j)

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

    LOG_DISAS("\n");

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(env, pc_start, ctx.pc - pc_start, 0);

        qemu_log("\n");

    }

#endif

}


static void parse_type_bool(Visitor *v, const char *name, bool *obj,

                            Error **errp)

{

    StringInputVisitor *siv = to_siv(v);

    if (siv->string) {

        if (!strcasecmp(siv->string, "on") ||

            !strcasecmp(siv->string, "yes") ||

            !strcasecmp(siv->string, "true")) {

            *obj = true;

            return;

        }

        if (!strcasecmp(siv->string, "off") ||

            !strcasecmp(siv->string, "no") ||

            !strcasecmp(siv->string, "false")) {

            *obj = false;

            return;

        }

    }

    error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

               "boolean");

}


void ff_rtsp_undo_setup(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    int i;

    for (i = 0; i < rt->nb_rtsp_streams; i++) {

        RTSPStream *rtsp_st = rt->rtsp_streams[i];

        if (!rtsp_st)

            continue;

        if (rtsp_st->transport_priv) {

            if (s->oformat) {

                AVFormatContext *rtpctx = rtsp_st->transport_priv;

                av_write_trailer(rtpctx);

                if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP) {

                    uint8_t *ptr;

                    url_close_dyn_buf(rtpctx->pb, &ptr);

                    av_free(ptr);

                } else {

                    url_fclose(rtpctx->pb);

                }

                av_metadata_free(&rtpctx->streams[0]->metadata);

                av_metadata_free(&rtpctx->metadata);

                av_free(rtpctx->streams[0]);

                av_free(rtpctx);

            } else if (rt->transport == RTSP_TRANSPORT_RDT && CONFIG_RTPDEC)

                ff_rdt_parse_close(rtsp_st->transport_priv);

            else if (CONFIG_RTPDEC)

                rtp_parse_close(rtsp_st->transport_priv);

        }

        rtsp_st->transport_priv = NULL;

        if (rtsp_st->rtp_handle)

            url_close(rtsp_st->rtp_handle);

        rtsp_st->rtp_handle = NULL;

    }

}


static void musb_rx_req(MUSBState *s, int epnum)

{

    MUSBEndPoint *ep = s->ep + epnum;

    int total;

    /* If we already have a packet, which didn't fit into the

     * 64 bytes of the FIFO, only move the FIFO start and return. (Obsolete) */

    if (ep->packey[1].p.pid == USB_TOKEN_IN && ep->status[1] >= 0 &&

                    (ep->fifostart[1]) + ep->rxcount <

                    ep->packey[1].p.len) {

        TRACE("0x%08x, %d",  ep->fifostart[1], ep->rxcount );

        ep->fifostart[1] += ep->rxcount;

        ep->fifolen[1] = 0;

        ep->rxcount = MIN(ep->packey[0].p.len - (ep->fifostart[1]),

                        ep->maxp[1]);

        ep->csr[1] &= ~MGC_M_RXCSR_H_REQPKT;

        if (!epnum)

            ep->csr[0] &= ~MGC_M_CSR0_H_REQPKT;

        /* Clear all of the error bits first */

        ep->csr[1] &= ~(MGC_M_RXCSR_H_ERROR | MGC_M_RXCSR_H_RXSTALL |

                        MGC_M_RXCSR_DATAERROR);

        if (!epnum)

            ep->csr[0] &= ~(MGC_M_CSR0_H_ERROR | MGC_M_CSR0_H_RXSTALL |

                            MGC_M_CSR0_H_NAKTIMEOUT | MGC_M_CSR0_H_NO_PING);

        ep->csr[1] |= MGC_M_RXCSR_FIFOFULL | MGC_M_RXCSR_RXPKTRDY;

        if (!epnum)

            ep->csr[0] |= MGC_M_CSR0_RXPKTRDY;

        musb_rx_intr_set(s, epnum, 1);

        return;

    }

    /* The driver sets maxp[1] to 64 or less because it knows the hardware

     * FIFO is this deep.  Bigger packets get split in

     * usb_generic_handle_packet but we can also do the splitting locally

     * for performance.  It turns out we can also have a bigger FIFO and

     * ignore the limit set in ep->maxp[1].  The Linux MUSB driver deals

     * OK with single packets of even 32KB and we avoid splitting, however

     * usb_msd.c sometimes sends a packet bigger than what Linux expects

     * (e.g. 8192 bytes instead of 4096) and we get an OVERRUN.  Splitting

     * hides this overrun from Linux.  Up to 4096 everything is fine

     * though.  Currently this is disabled.

     *

     * XXX: mind ep->fifosize.  */

    total = MIN(ep->maxp[1] & 0x3ff, sizeof(s->buf));

#ifdef SETUPLEN_HACK

    /* Why should *we* do that instead of Linux?  */

    if (!epnum) {

        if (ep->packey[0].p.devaddr == 2) {

            total = MIN(s->setup_len, 8);

        } else {

            total = MIN(s->setup_len, 64);

        }

        s->setup_len -= total;

    }

#endif

    return musb_packet(s, ep, epnum, USB_TOKEN_IN,

                    total, musb_rx_packet_complete, 1);

}


static uint64_t sp804_read(void *opaque, target_phys_addr_t offset,

                           unsigned size)

{

    sp804_state *s = (sp804_state *)opaque;

    if (offset < 0x20) {

        return arm_timer_read(s->timer[0], offset);

    }

    if (offset < 0x40) {

        return arm_timer_read(s->timer[1], offset - 0x20);

    }

    /* TimerPeriphID */

    if (offset >= 0xfe0 && offset <= 0xffc) {

        return sp804_ids[(offset - 0xfe0) >> 2];

    }

    switch (offset) {

    /* Integration Test control registers, which we won't support */

    case 0xf00: /* TimerITCR */

    case 0xf04: /* TimerITOP (strictly write only but..) */

        return 0;

    }

    hw_error("%s: Bad offset %x\n", __func__, (int)offset);

    return 0;

}


static void timerlist_rearm(QEMUTimerList *timer_list)

{

    /* Interrupt execution to force deadline recalculation.  */

    if (timer_list->clock->type == QEMU_CLOCK_VIRTUAL) {

        qemu_start_warp_timer();

    }

    timerlist_notify(timer_list);

}


CharDriverState *text_console_init(DisplayState *ds, const char *p)

{

    CharDriverState *chr;

    TextConsole *s;

    unsigned width;

    unsigned height;

    static int color_inited;

    chr = qemu_mallocz(sizeof(CharDriverState));

    if (!chr)

        return NULL;

    s = new_console(ds, TEXT_CONSOLE);

    if (!s) {

        free(chr);

        return NULL;

    }

    if (!p)

        p = DEFAULT_MONITOR_SIZE;

    chr->opaque = s;

    chr->chr_write = console_puts;

    chr->chr_send_event = console_send_event;

    s->chr = chr;

    s->out_fifo.buf = s->out_fifo_buf;

    s->out_fifo.buf_size = sizeof(s->out_fifo_buf);

    s->kbd_timer = qemu_new_timer(rt_clock, kbd_send_chars, s);

    if (!color_inited) {

        color_inited = 1;

        console_color_init(s->ds);

    }

    s->y_displayed = 0;

    s->y_base = 0;

    s->total_height = DEFAULT_BACKSCROLL;

    s->x = 0;

    s->y = 0;

    width = s->ds->width;

    height = s->ds->height;

    if (p != 0) {

        width = strtoul(p, (char **)&p, 10);

        if (*p == 'C') {

            p++;

            width *= FONT_WIDTH;

        }

        if (*p == 'x') {

            p++;

            height = strtoul(p, (char **)&p, 10);

            if (*p == 'C') {

                p++;

                height *= FONT_HEIGHT;

            }

        }

    }

    s->g_width = width;

    s->g_height = height;

    s->hw_invalidate = text_console_invalidate;

    s->hw_text_update = text_console_update;

    s->hw = s;

    /* Set text attribute defaults */

    s->t_attrib_default.bold = 0;

    s->t_attrib_default.uline = 0;

    s->t_attrib_default.blink = 0;

    s->t_attrib_default.invers = 0;

    s->t_attrib_default.unvisible = 0;

    s->t_attrib_default.fgcol = COLOR_WHITE;

    s->t_attrib_default.bgcol = COLOR_BLACK;

    /* set current text attributes to default */

    s->t_attrib = s->t_attrib_default;

    text_console_resize(s);

    qemu_chr_reset(chr);

    return chr;

}


static void tcg_liveness_analysis(TCGContext *s)

{

    uint8_t *dead_temps, *mem_temps;

    int oi, oi_prev, nb_ops;

    nb_ops = s->gen_next_op_idx;

    s->op_dead_args = tcg_malloc(nb_ops * sizeof(uint16_t));

    s->op_sync_args = tcg_malloc(nb_ops * sizeof(uint8_t));

    dead_temps = tcg_malloc(s->nb_temps);

    mem_temps = tcg_malloc(s->nb_temps);

    tcg_la_func_end(s, dead_temps, mem_temps);

    for (oi = s->gen_last_op_idx; oi >= 0; oi = oi_prev) {

        int i, nb_iargs, nb_oargs;

        TCGOpcode opc_new, opc_new2;

        bool have_opc_new2;

        uint16_t dead_args;

        uint8_t sync_args;

        TCGArg arg;

        TCGOp * const op = &s->gen_op_buf[oi];

        TCGArg * const args = &s->gen_opparam_buf[op->args];

        TCGOpcode opc = op->opc;

        const TCGOpDef *def = &tcg_op_defs[opc];

        oi_prev = op->prev;

        switch (opc) {

        case INDEX_op_call:

            {

                int call_flags;

                nb_oargs = op->callo;

                nb_iargs = op->calli;

                call_flags = args[nb_oargs + nb_iargs + 1];

                /* pure functions can be removed if their result is unused */

                if (call_flags & TCG_CALL_NO_SIDE_EFFECTS) {

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

                        arg = args[i];

                        if (!dead_temps[arg] || mem_temps[arg]) {

                            goto do_not_remove_call;

                        }

                    }

                    goto do_remove;

                } else {

                do_not_remove_call:

                    /* output args are dead */

                    dead_args = 0;

                    sync_args = 0;

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

                        arg = args[i];

                        if (dead_temps[arg]) {

                            dead_args |= (1 << i);

                        }

                        if (mem_temps[arg]) {

                            sync_args |= (1 << i);

                        }

                        dead_temps[arg] = 1;

                        mem_temps[arg] = 0;

                    }

                    if (!(call_flags & TCG_CALL_NO_READ_GLOBALS)) {

                        /* globals should be synced to memory */

                        memset(mem_temps, 1, s->nb_globals);

                    }

                    if (!(call_flags & (TCG_CALL_NO_WRITE_GLOBALS |

                                        TCG_CALL_NO_READ_GLOBALS))) {

                        /* globals should go back to memory */

                        memset(dead_temps, 1, s->nb_globals);

                    }

                    /* input args are live */

                    for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {

                        arg = args[i];

                        if (arg != TCG_CALL_DUMMY_ARG) {

                            if (dead_temps[arg]) {

                                dead_args |= (1 << i);

                            }

                            dead_temps[arg] = 0;

                        }

                    }

                    s->op_dead_args[oi] = dead_args;

                    s->op_sync_args[oi] = sync_args;

                }

            }

            break;

        case INDEX_op_debug_insn_start:

            break;

        case INDEX_op_discard:

            /* mark the temporary as dead */

            dead_temps[args[0]] = 1;

            mem_temps[args[0]] = 0;

            break;

        case INDEX_op_add2_i32:

            opc_new = INDEX_op_add_i32;

            goto do_addsub2;

        case INDEX_op_sub2_i32:

            opc_new = INDEX_op_sub_i32;

            goto do_addsub2;

        case INDEX_op_add2_i64:

            opc_new = INDEX_op_add_i64;

            goto do_addsub2;

        case INDEX_op_sub2_i64:

            opc_new = INDEX_op_sub_i64;

        do_addsub2:

            nb_iargs = 4;

            nb_oargs = 2;

            /* Test if the high part of the operation is dead, but not

               the low part.  The result can be optimized to a simple

               add or sub.  This happens often for x86_64 guest when the

               cpu mode is set to 32 bit.  */

            if (dead_temps[args[1]] && !mem_temps[args[1]]) {

                if (dead_temps[args[0]] && !mem_temps[args[0]]) {

                    goto do_remove;

                }

                /* Replace the opcode and adjust the args in place,

                   leaving 3 unused args at the end.  */

                op->opc = opc = opc_new;

                args[1] = args[2];

                args[2] = args[4];

                /* Fall through and mark the single-word operation live.  */

                nb_iargs = 2;

                nb_oargs = 1;

            }

            goto do_not_remove;

        case INDEX_op_mulu2_i32:

            opc_new = INDEX_op_mul_i32;

            opc_new2 = INDEX_op_muluh_i32;

            have_opc_new2 = TCG_TARGET_HAS_muluh_i32;

            goto do_mul2;

        case INDEX_op_muls2_i32:

            opc_new = INDEX_op_mul_i32;

            opc_new2 = INDEX_op_mulsh_i32;

            have_opc_new2 = TCG_TARGET_HAS_mulsh_i32;

            goto do_mul2;

        case INDEX_op_mulu2_i64:

            opc_new = INDEX_op_mul_i64;

            opc_new2 = INDEX_op_muluh_i64;

            have_opc_new2 = TCG_TARGET_HAS_muluh_i64;

            goto do_mul2;

        case INDEX_op_muls2_i64:

            opc_new = INDEX_op_mul_i64;

            opc_new2 = INDEX_op_mulsh_i64;

            have_opc_new2 = TCG_TARGET_HAS_mulsh_i64;

            goto do_mul2;

        do_mul2:

            nb_iargs = 2;

            nb_oargs = 2;

            if (dead_temps[args[1]] && !mem_temps[args[1]]) {

                if (dead_temps[args[0]] && !mem_temps[args[0]]) {

                    /* Both parts of the operation are dead.  */

                    goto do_remove;

                }

                /* The high part of the operation is dead; generate the low. */

                op->opc = opc = opc_new;

                args[1] = args[2];

                args[2] = args[3];

            } else if (have_opc_new2 && dead_temps[args[0]]

                       && !mem_temps[args[0]]) {

                /* The low part of the operation is dead; generate the high. */

                op->opc = opc = opc_new2;

                args[0] = args[1];

                args[1] = args[2];

                args[2] = args[3];

            } else {

                goto do_not_remove;

            }

            /* Mark the single-word operation live.  */

            nb_oargs = 1;

            goto do_not_remove;

        default:

            /* XXX: optimize by hardcoding common cases (e.g. triadic ops) */

            nb_iargs = def->nb_iargs;

            nb_oargs = def->nb_oargs;

            /* Test if the operation can be removed because all

               its outputs are dead. We assume that nb_oargs == 0

               implies side effects */

            if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) {

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

                    arg = args[i];

                    if (!dead_temps[arg] || mem_temps[arg]) {

                        goto do_not_remove;

                    }

                }

            do_remove:

                tcg_op_remove(s, op);

            } else {

            do_not_remove:

                /* output args are dead */

                dead_args = 0;

                sync_args = 0;

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

                    arg = args[i];

                    if (dead_temps[arg]) {

                        dead_args |= (1 << i);

                    }

                    if (mem_temps[arg]) {

                        sync_args |= (1 << i);

                    }

                    dead_temps[arg] = 1;

                    mem_temps[arg] = 0;

                }

                /* if end of basic block, update */

                if (def->flags & TCG_OPF_BB_END) {

                    tcg_la_bb_end(s, dead_temps, mem_temps);

                } else if (def->flags & TCG_OPF_SIDE_EFFECTS) {

                    /* globals should be synced to memory */

                    memset(mem_temps, 1, s->nb_globals);

                }

                /* input args are live */

                for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {

                    arg = args[i];

                    if (dead_temps[arg]) {

                        dead_args |= (1 << i);

                    }

                    dead_temps[arg] = 0;

                }

                s->op_dead_args[oi] = dead_args;

                s->op_sync_args[oi] = sync_args;

            }

            break;

        }

    }

}


bool error_is_type(Error *err, const char *fmt)

{

    const char *error_class;

    char *ptr;

    char *end;

    if (!err) {

        return false;

    }

    ptr = strstr(fmt, "'class': '");

    assert(ptr != NULL);

    ptr += strlen("'class': '");

    end = strchr(ptr, '\'');

    assert(end != NULL);

    error_class = error_get_field(err, "class");

    if (strlen(error_class) != end - ptr) {

        return false;

    }

    return strncmp(ptr, error_class, end - ptr) == 0;

}


static inline int onenand_load_main(OneNANDState *s, int sec, int secn,

                void *dest)

{

    if (s->bdrv_cur)

        return bdrv_read(s->bdrv_cur, sec, dest, secn) < 0;

    else if (sec + secn > s->secs_cur)

        return 1;

    memcpy(dest, s->current + (sec << 9), secn << 9);

    return 0;

}


static void generate_offset_lut(DiracGolombLUT *lut, int off)

{

    int idx;

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

        DiracGolombLUT *l = &lut[idx];

        INIT_RESIDUE(res);

        SET_RESIDUE(res, idx, LUT_BITS);

        l->preamble      = CONVERT_TO_RESIDUE(res >> (RSIZE_BITS - off), off);

        l->preamble_bits = off;

        l->sign = ((l->preamble >> (RSIZE_BITS - l->preamble_bits)) & 1) ? -1 : +1;

        search_for_golomb(l, res << off, LUT_BITS - off);

    }

}


vmxnet3_pop_next_tx_descr(VMXNET3State *s,

                          int qidx,

                          struct Vmxnet3_TxDesc *txd,

                          uint32_t *descr_idx)

{

    Vmxnet3Ring *ring = &s->txq_descr[qidx].tx_ring;

    PCIDevice *d = PCI_DEVICE(s);

    vmxnet3_ring_read_curr_cell(d, ring, txd);

    if (txd->gen == vmxnet3_ring_curr_gen(ring)) {

        /* Only read after generation field verification */

        smp_rmb();

        /* Re-read to be sure we got the latest version */

        vmxnet3_ring_read_curr_cell(d, ring, txd);

        VMXNET3_RING_DUMP(VMW_RIPRN, "TX", qidx, ring);

        *descr_idx = vmxnet3_ring_curr_cell_idx(ring);

        vmxnet3_inc_tx_consumption_counter(s, qidx);

        return true;

    }

    return false;

}


static void init_excp_BookE (CPUPPCState *env)

{

#if !defined(CONFIG_USER_ONLY)

    env->excp_vectors[POWERPC_EXCP_CRITICAL] = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_MCHECK]   = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_DSI]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_ISI]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_EXTERNAL] = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_ALIGN]    = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_PROGRAM]  = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_FPU]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_SYSCALL]  = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_APU]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_DECR]     = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_FIT]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_WDT]      = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_DTLB]     = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_ITLB]     = 0x00000000;

    env->excp_vectors[POWERPC_EXCP_DEBUG]    = 0x00000000;

    env->excp_prefix = 0x00000000;

    env->ivor_mask = 0x0000FFE0;

    env->ivpr_mask = 0xFFFF0000;

    /* Hardware reset vector */

    env->hreset_vector = 0xFFFFFFFCUL;

#endif

}


DISAS_INSN(divw)

{

    TCGv reg;

    TCGv tmp;

    TCGv src;

    int sign;

    sign = (insn & 0x100) != 0;

    reg = DREG(insn, 9);

    if (sign) {

        tcg_gen_ext16s_i32(QREG_DIV1, reg);

    } else {

        tcg_gen_ext16u_i32(QREG_DIV1, reg);

    }

    SRC_EA(env, src, OS_WORD, sign, NULL);

    tcg_gen_mov_i32(QREG_DIV2, src);

    if (sign) {

        gen_helper_divs(cpu_env, tcg_const_i32(1));

    } else {

        gen_helper_divu(cpu_env, tcg_const_i32(1));

    }

    tmp = tcg_temp_new();

    src = tcg_temp_new();

    tcg_gen_ext16u_i32(tmp, QREG_DIV1);

    tcg_gen_shli_i32(src, QREG_DIV2, 16);

    tcg_gen_or_i32(reg, tmp, src);

    set_cc_op(s, CC_OP_FLAGS);

}


static int msrle_decode_8_16_24_32(AVCodecContext *avctx, AVPicture *pic, int depth,

                                    const uint8_t *data, int srcsize)

{

    uint8_t *output, *output_end;

    const uint8_t* src = data;

    int p1, p2, line=avctx->height, pos=0, i;

    uint16_t pix16;

    uint32_t pix32;

    output = pic->data[0] + (avctx->height - 1) * pic->linesize[0];

    output_end = pic->data[0] + (avctx->height) * pic->linesize[0];

    while(src < data + srcsize) {

        p1 = *src++;

        if(p1 == 0) { //Escape code

            p2 = *src++;

            if(p2 == 0) { //End-of-line

                output = pic->data[0] + (--line) * pic->linesize[0];

                if (line < 0){

                    av_log(avctx, AV_LOG_ERROR, "Next line is beyond picture bounds\n");

                    return -1;

                }

                pos = 0;

                continue;

            } else if(p2 == 1) { //End-of-picture

                return 0;

            } else if(p2 == 2) { //Skip

                p1 = *src++;

                p2 = *src++;

                line -= p2;

                if (line < 0){

                    av_log(avctx, AV_LOG_ERROR, "Skip beyond picture bounds\n");

                    return -1;

                }

                pos += p1;

                output = pic->data[0] + line * pic->linesize[0] + pos * (depth >> 3);

                continue;

            }

            // Copy data

            if (output + p2 * (depth >> 3) > output_end) {

                src += p2 * (depth >> 3);

                continue;

            }

            if ((depth == 8) || (depth == 24)) {

                for(i = 0; i < p2 * (depth >> 3); i++) {

                    *output++ = *src++;

                }

                // RLE8 copy is actually padded - and runs are not!

                if(depth == 8 && (p2 & 1)) {

                    src++;

                }

            } else if (depth == 16) {

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

                    pix16 = AV_RL16(src);

                    src += 2;

                    *(uint16_t*)output = pix16;

                    output += 2;

                }

            } else if (depth == 32) {

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

                    pix32 = AV_RL32(src);

                    src += 4;

                    *(uint32_t*)output = pix32;

                    output += 4;

                }

            }

            pos += p2;

        } else { //Run of pixels

            uint8_t pix[3]; //original pixel

            switch(depth){

            case  8: pix[0] = *src++;

                     break;

            case 16: pix16 = AV_RL16(src);

                     src += 2;

                     break;

            case 24: pix[0] = *src++;

                     pix[1] = *src++;

                     pix[2] = *src++;

                     break;

            case 32: pix32 = AV_RL32(src);

                     src += 4;

                     break;

            }

            if (output + p1 * (depth >> 3) > output_end)

                continue;

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

                switch(depth){

                case  8: *output++ = pix[0];

                         break;

                case 16: *(uint16_t*)output = pix16;

                         output += 2;

                         break;

                case 24: *output++ = pix[0];

                         *output++ = pix[1];

                         *output++ = pix[2];

                         break;

                case 32: *(uint32_t*)output = pix32;

                         output += 4;

                         break;

                }

            }

            pos += p1;

        }

    }

    av_log(avctx, AV_LOG_WARNING, "MS RLE warning: no End-of-picture code\n");

    return 0;

}


static void RENAME(vertical_compose53iL0)(uint8_t *_b0, uint8_t *_b1, uint8_t *_b2,

                                          int width)

{

    int i;

    TYPE *b0 = (TYPE *)_b0;

    TYPE *b1 = (TYPE *)_b1;

    TYPE *b2 = (TYPE *)_b2;

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

        b1[i] -= (b0[i] + b2[i] + 2) >> 2;

}


static void handle_user_command(Monitor *mon, const char *cmdline)

{

    QDict *qdict;

    const mon_cmd_t *cmd;

    qdict = qdict_new();

    cmd = monitor_parse_command(mon, cmdline, 0, mon->cmd_table, qdict);

    if (!cmd)

        goto out;

    if (handler_is_async(cmd)) {

        user_async_cmd_handler(mon, cmd, qdict);

    } else if (handler_is_qobject(cmd)) {

        QObject *data = NULL;

        /* XXX: ignores the error code */

        cmd->mhandler.cmd_new(mon, qdict, &data);

        assert(!monitor_has_error(mon));

        if (data) {

            cmd->user_print(mon, data);

            qobject_decref(data);

        }

    } else {

        cmd->mhandler.cmd(mon, qdict);

    }

out:

    QDECREF(qdict);

}


static void gen_exception_return(DisasContext *s, TCGv pc)

{

    TCGv tmp;

    store_reg(s, 15, pc);

    tmp = load_cpu_field(spsr);

    gen_set_cpsr(tmp, 0xffffffff);

    dead_tmp(tmp);

    s->is_jmp = DISAS_UPDATE;

}


static int fourxm_read_packet(AVFormatContext *s,

                              AVPacket *pkt)

{

    FourxmDemuxContext *fourxm = s->priv_data;

    ByteIOContext *pb = &s->pb;

    unsigned int fourcc_tag;

    unsigned int size, out_size;

    int ret = 0;

    int track_number;

    int packet_read = 0;

    unsigned char header[8];

    int64_t pts_inc;

    int audio_frame_count;

    while (!packet_read) {

        if ((ret = get_buffer(&s->pb, header, 8)) < 0)

            return ret;

        fourcc_tag = LE_32(&header[0]);

        size = LE_32(&header[4]);

        if (url_feof(pb))

            return AVERROR_IO;

        switch (fourcc_tag) {

        case LIST_TAG:

            /* this is a good time to bump the video pts */

            fourxm->video_pts += fourxm->video_pts_inc;

            /* skip the LIST-* tag and move on to the next fourcc */

            get_le32(pb);

            break;

        case ifrm_TAG:

        case pfrm_TAG:

        case cfrm_TAG:{

            /* allocate 8 more bytes than 'size' to account for fourcc

             * and size */

            if (av_new_packet(pkt, size + 8))

                return AVERROR_IO;

            pkt->stream_index = fourxm->video_stream_index;

            pkt->pts = fourxm->video_pts;

            memcpy(pkt->data, header, 8);

            ret = get_buffer(&s->pb, &pkt->data[8], size);

            if (ret < 0)

                av_free_packet(pkt);

            else

                packet_read = 1;

            break;

        }

        case snd__TAG:

            track_number = get_le32(pb);

            out_size= get_le32(pb);

            size-=8;

            if (track_number == fourxm->selected_track) {

                if (av_new_packet(pkt, size))

                    return AVERROR_IO;

                pkt->stream_index =

                    fourxm->tracks[fourxm->selected_track].stream_index;

                pkt->pts = fourxm->audio_pts;

                ret = get_buffer(&s->pb, pkt->data, size);

                if (ret < 0)

                    av_free_packet(pkt);

                else

                    packet_read = 1;

                /* pts accounting */

                audio_frame_count = size;

                if (fourxm->tracks[fourxm->selected_track].adpcm)

                    audio_frame_count -=

                        2 * (fourxm->tracks[fourxm->selected_track].channels);

                audio_frame_count /=

                      fourxm->tracks[fourxm->selected_track].channels;

                if (fourxm->tracks[fourxm->selected_track].adpcm)

                    audio_frame_count *= 2;

                else

                    audio_frame_count /=

                    (fourxm->tracks[fourxm->selected_track].bits / 8);

                pts_inc = audio_frame_count;

                pts_inc *= 90000;

                pts_inc /= fourxm->tracks[fourxm->selected_track].sample_rate;

                fourxm->audio_pts += pts_inc;

            } else {

                url_fseek(pb, size, SEEK_CUR);

            }

            break;

        default:

            url_fseek(pb, size, SEEK_CUR);

            break;

        }

    }

    return ret;

}


static bool bdrv_drain_recurse(BlockDriverState *bs, bool begin)

{

    BdrvChild *child, *tmp;

    bool waited;

    /* Ensure any pending metadata writes are submitted to bs->file.  */

    bdrv_drain_invoke(bs, begin);

    /* Wait for drained requests to finish */

    waited = BDRV_POLL_WHILE(bs, atomic_read(&bs->in_flight) > 0);

    QLIST_FOREACH_SAFE(child, &bs->children, next, tmp) {

        BlockDriverState *bs = child->bs;

        bool in_main_loop =

            qemu_get_current_aio_context() == qemu_get_aio_context();

        assert(bs->refcnt > 0);

        if (in_main_loop) {

            /* In case the recursive bdrv_drain_recurse processes a

             * block_job_defer_to_main_loop BH and modifies the graph,

             * let's hold a reference to bs until we are done.

             *

             * IOThread doesn't have such a BH, and it is not safe to call

             * bdrv_unref without BQL, so skip doing it there.

             */

            bdrv_ref(bs);

        }

        waited |= bdrv_drain_recurse(bs, begin);

        if (in_main_loop) {

            bdrv_unref(bs);

        }

    }

    return waited;

}


static int count_paired_channels(uint8_t (*layout_map)[3], int tags, int pos, int *current) {

    int num_pos_channels = 0;

    int first_cpe = 0;

    int sce_parity = 0;

    int i;

    for (i = *current; i < tags; i++) {

        if (layout_map[i][2] != pos)

            break;

        if (layout_map[i][0] == TYPE_CPE) {

            if (sce_parity) {

                if (pos == AAC_CHANNEL_FRONT || !first_cpe) {

                    sce_parity = 0;

                } else {

                    return -1;

                }

            }

            num_pos_channels += 2;

            first_cpe = 1;

        } else {

            num_pos_channels++;

            sce_parity ^= 1;

        }

    }

    if (sce_parity &&

        ((pos == AAC_CHANNEL_FRONT && first_cpe) || pos == AAC_CHANNEL_SIDE))

            return -1;

    *current = i;

    return num_pos_channels;

}


uint64_t helper_sublv (uint64_t op1, uint64_t op2)

{

    uint64_t tmp = op1;

    op1 = (uint32_t)(op1 - op2);

    if (unlikely(((~tmp) ^ op1 ^ (-1UL)) & ((~tmp) ^ op2) & (1UL << 31))) {

        helper_excp(EXCP_ARITH, EXCP_ARITH_OVERFLOW);

    }

    return op1;

}


static int decode_slice(struct AVCodecContext *avctx, void *arg)

{

    H264Context *h = *(void **)arg;

    int lf_x_start = h->mb_x;

    h->mb_skip_run = -1;

    av_assert0(h->block_offset[15] == (4 * ((scan8[15] - scan8[0]) & 7) << h->pixel_shift) + 4 * h->linesize * ((scan8[15] - scan8[0]) >> 3));

    h->is_complex = FRAME_MBAFF(h) || h->picture_structure != PICT_FRAME ||

                    avctx->codec_id != AV_CODEC_ID_H264 ||

                    (CONFIG_GRAY && (h->flags & CODEC_FLAG_GRAY));

    if (!(h->avctx->active_thread_type & FF_THREAD_SLICE) && h->picture_structure == PICT_FRAME) {

        const int start_i  = av_clip(h->resync_mb_x + h->resync_mb_y * h->mb_width, 0, h->mb_num - 1);

        if (start_i) {

            int prev_status = h->er.error_status_table[h->er.mb_index2xy[start_i - 1]];

            prev_status &= ~ VP_START;

            if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END))

                h->er.error_occurred = 1;

        }

    }

    if (h->pps.cabac) {

        /* realign */

        align_get_bits(&h->gb);

        /* init cabac */

        ff_init_cabac_decoder(&h->cabac,

                              h->gb.buffer + get_bits_count(&h->gb) / 8,

                              (get_bits_left(&h->gb) + 7) / 8);

        ff_h264_init_cabac_states(h);

        for (;;) {

            // START_TIMER

            int ret = ff_h264_decode_mb_cabac(h);

            int eos;

            // STOP_TIMER("decode_mb_cabac")

            if (ret >= 0)

                ff_h264_hl_decode_mb(h);

            // FIXME optimal? or let mb_decode decode 16x32 ?

            if (ret >= 0 && FRAME_MBAFF(h)) {

                h->mb_y++;

                ret = ff_h264_decode_mb_cabac(h);

                if (ret >= 0)

                    ff_h264_hl_decode_mb(h);

                h->mb_y--;

            }

            eos = get_cabac_terminate(&h->cabac);

            if ((h->workaround_bugs & FF_BUG_TRUNCATED) &&

                h->cabac.bytestream > h->cabac.bytestream_end + 2) {

                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,

                                h->mb_y, ER_MB_END);

                if (h->mb_x >= lf_x_start)

                    loop_filter(h, lf_x_start, h->mb_x + 1);

                return 0;

            }

            if (h->cabac.bytestream > h->cabac.bytestream_end + 2 )

                av_log(h->avctx, AV_LOG_DEBUG, "bytestream overread %td\n", h->cabac.bytestream_end - h->cabac.bytestream);

            if (ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 4) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "error while decoding MB %d %d, bytestream (%td)\n",

                       h->mb_x, h->mb_y,

                       h->cabac.bytestream_end - h->cabac.bytestream);

                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,

                                h->mb_y, ER_MB_ERROR);

                return -1;

            }

            if (++h->mb_x >= h->mb_width) {

                loop_filter(h, lf_x_start, h->mb_x);

                h->mb_x = lf_x_start = 0;

                decode_finish_row(h);

                ++h->mb_y;

                if (FIELD_OR_MBAFF_PICTURE(h)) {

                    ++h->mb_y;

                    if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)

                        predict_field_decoding_flag(h);

                }

            }

            if (eos || h->mb_y >= h->mb_height) {

                tprintf(h->avctx, "slice end %d %d\n",

                        get_bits_count(&h->gb), h->gb.size_in_bits);

                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x - 1,

                                h->mb_y, ER_MB_END);

                if (h->mb_x > lf_x_start)

                    loop_filter(h, lf_x_start, h->mb_x);

                return 0;

            }

        }

    } else {

        for (;;) {

            int ret = ff_h264_decode_mb_cavlc(h);

            if (ret >= 0)

                ff_h264_hl_decode_mb(h);

            // FIXME optimal? or let mb_decode decode 16x32 ?

            if (ret >= 0 && FRAME_MBAFF(h)) {

                h->mb_y++;

                ret = ff_h264_decode_mb_cavlc(h);

                if (ret >= 0)

                    ff_h264_hl_decode_mb(h);

                h->mb_y--;

            }

            if (ret < 0) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "error while decoding MB %d %d\n", h->mb_x, h->mb_y);

                er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,

                                h->mb_y, ER_MB_ERROR);

                return -1;

            }

            if (++h->mb_x >= h->mb_width) {

                loop_filter(h, lf_x_start, h->mb_x);

                h->mb_x = lf_x_start = 0;

                decode_finish_row(h);

                ++h->mb_y;

                if (FIELD_OR_MBAFF_PICTURE(h)) {

                    ++h->mb_y;

                    if (FRAME_MBAFF(h) && h->mb_y < h->mb_height)

                        predict_field_decoding_flag(h);

                }

                if (h->mb_y >= h->mb_height) {

                    tprintf(h->avctx, "slice end %d %d\n",

                            get_bits_count(&h->gb), h->gb.size_in_bits);

                    if (   get_bits_left(&h->gb) == 0

                        || get_bits_left(&h->gb) > 0 && !(h->avctx->err_recognition & AV_EF_AGGRESSIVE)) {

                        er_add_slice(h, h->resync_mb_x, h->resync_mb_y,

                                        h->mb_x - 1, h->mb_y,

                                        ER_MB_END);

                        return 0;

                    } else {

                        er_add_slice(h, h->resync_mb_x, h->resync_mb_y,

                                        h->mb_x, h->mb_y,

                                        ER_MB_END);

                        return -1;

                    }

                }

            }

            if (get_bits_left(&h->gb) <= 0 && h->mb_skip_run <= 0) {

                tprintf(h->avctx, "slice end %d %d\n",

                        get_bits_count(&h->gb), h->gb.size_in_bits);

                if (get_bits_left(&h->gb) == 0) {

                    er_add_slice(h, h->resync_mb_x, h->resync_mb_y,

                                    h->mb_x - 1, h->mb_y,

                                    ER_MB_END);

                    if (h->mb_x > lf_x_start)

                        loop_filter(h, lf_x_start, h->mb_x);

                    return 0;

                } else {

                    er_add_slice(h, h->resync_mb_x, h->resync_mb_y, h->mb_x,

                                    h->mb_y, ER_MB_ERROR);

                    return -1;

                }

            }

        }

    }

}


static int img_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    VideoData *s = s1->priv_data;

    char filename[1024];

    int ret;

    ByteIOContext f1, *f;

    if (get_frame_filename(filename, sizeof(filename),

                           s->path, s->img_number) < 0)

        return -EIO;

    if (!s->is_pipe) {

        f = &f1;

        if (url_fopen(f, filename, URL_RDONLY) < 0)

            return -EIO;

    } else {

        f = &s1->pb;

        if (url_feof(f))

            return -EIO;

    }

    av_new_packet(pkt, s->img_size);

    pkt->stream_index = 0;

    switch(s->img_fmt) {

    case IMGFMT_PGMYUV:

        ret = pgm_read(s, f, pkt->data, pkt->size, 1);

        break;

    case IMGFMT_PGM:

        ret = pgm_read(s, f, pkt->data, pkt->size, 0);

        break;

    case IMGFMT_YUV:

        ret = yuv_read(s, filename, pkt->data, pkt->size);

        break;

    case IMGFMT_PPM:

        ret = ppm_read(s, f, pkt->data, pkt->size);

        break;

    default:

        return -EIO;

    }

    if (!s->is_pipe) {

        url_fclose(f);

    }

    if (ret < 0) {

        av_free_packet(pkt);

        return -EIO; /* signal EOF */

    } else {

        s->img_number++;

        return 0;

    }

}


void configure_alarms(char const *opt)

{

    int i;

    int cur = 0;

    int count = ARRAY_SIZE(alarm_timers) - 1;

    char *arg;

    char *name;

    struct qemu_alarm_timer tmp;

    if (!strcmp(opt, "?")) {

        show_available_alarms();

        exit(0);

    }

    arg = g_strdup(opt);

    /* Reorder the array */

    name = strtok(arg, ",");

    while (name) {

        for (i = 0; i < count && alarm_timers[i].name; i++) {

            if (!strcmp(alarm_timers[i].name, name))

                break;

        }

        if (i == count) {

            fprintf(stderr, "Unknown clock %s\n", name);

            goto next;

        }

        if (i < cur)

            /* Ignore */

            goto next;

	/* Swap */

        tmp = alarm_timers[i];

        alarm_timers[i] = alarm_timers[cur];

        alarm_timers[cur] = tmp;

        cur++;

next:

        name = strtok(NULL, ",");

    }

    g_free(arg);

    if (cur) {

        /* Disable remaining timers */

        for (i = cur; i < count; i++)

            alarm_timers[i].name = NULL;

    } else {

        show_available_alarms();

        exit(1);

    }

}


static int motion_inter_4v_block (bit_buffer_t *bitbuf,

				  uint8_t *current, uint8_t *previous, int pitch,

				  svq1_pmv_t *motion,int x, int y) {

  uint8_t    *src;

  uint8_t    *dst;

  svq1_pmv_t  mv;

  svq1_pmv_t *pmv[4];

  int	      i, result;

  /* predict and decode motion vector (0) */

  pmv[0] = &motion[0];

  pmv[1] = &motion[(x / 8) + 2];

  pmv[2] = &motion[(x / 8) + 4];

  if (y == 0) {

    pmv[1] = pmv[0];

    pmv[2] = pmv[0];

  }

  result = decode_motion_vector (bitbuf, &mv, pmv);

  if (result != 0)

    return result;

  /* predict and decode motion vector (1) */

  pmv[0] = &mv;

  pmv[1] = &motion[(x / 8) + 3];

  if (y == 0) {

    pmv[1] = pmv[0];

    pmv[2] = pmv[0];

  }

  result = decode_motion_vector (bitbuf, &motion[0], pmv);

  if (result != 0)

    return result;

  /* predict and decode motion vector (2) */

  pmv[1] = &motion[0];

  pmv[2] = &motion[(x / 8) + 1];

  result = decode_motion_vector (bitbuf, &motion[(x / 8) + 2], pmv);

  if (result != 0)

    return result;

  /* predict and decode motion vector (3) */

  pmv[2] = &motion[(x / 8) + 2];

  pmv[3] = &motion[(x / 8) + 3];

  result = decode_motion_vector (bitbuf, pmv[3], pmv);

  if (result != 0)

    return result;

  /* form predictions */

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

    src = &previous[(x + (pmv[i]->x >> 1)) + (y + (pmv[i]->y >> 1))*pitch];

    dst = current;

    put_pixels_tab[((pmv[i]->y & 1) << 1) | (pmv[i]->x & 1)](dst,src,pitch,8);

    /* select next block */

    if (i & 1) {

      current  += 8*(pitch - 1);

      previous += 8*(pitch - 1);

    } else {

      current  += 8;

      previous += 8;

    }

  }

  return 0;

}


void ide_sector_read(IDEState *s)

{

    int64_t sector_num;

    int ret, n;

    s->status = READY_STAT | SEEK_STAT;

    s->error = 0; /* not needed by IDE spec, but needed by Windows */

    sector_num = ide_get_sector(s);

    n = s->nsector;

    if (n == 0) {

        /* no more sector to read from disk */

        ide_transfer_stop(s);

    } else {

#if defined(DEBUG_IDE)

        printf("read sector=%" PRId64 "\n", sector_num);

#endif

        if (n > s->req_nb_sectors)

            n = s->req_nb_sectors;

        bdrv_acct_start(s->bs, &s->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);

        ret = bdrv_read(s->bs, sector_num, s->io_buffer, n);

        bdrv_acct_done(s->bs, &s->acct);

        if (ret != 0) {

            if (ide_handle_rw_error(s, -ret,

                BM_STATUS_PIO_RETRY | BM_STATUS_RETRY_READ))

            {

                return;

            }

        }

        ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_read);

        ide_set_irq(s->bus);

        ide_set_sector(s, sector_num + n);

        s->nsector -= n;

    }

}


static void cpu_ioreq_pio(ioreq_t *req)

{

    int i;

    if (req->dir == IOREQ_READ) {

        if (!req->data_is_ptr) {

            req->data = do_inp(req->addr, req->size);

        } else {

            uint32_t tmp;

            for (i = 0; i < req->count; i++) {

                tmp = do_inp(req->addr, req->size);

                write_phys_req_item(req->data, req, i, &tmp);

            }

        }

    } else if (req->dir == IOREQ_WRITE) {

        if (!req->data_is_ptr) {

            do_outp(req->addr, req->size, req->data);

        } else {

            for (i = 0; i < req->count; i++) {

                uint32_t tmp = 0;

                read_phys_req_item(req->data, req, i, &tmp);

                do_outp(req->addr, req->size, tmp);

            }

        }

    }

}


static void rtas_display_character(sPAPREnvironment *spapr,

                                   uint32_t token, uint32_t nargs,

                                   target_ulong args,

                                   uint32_t nret, target_ulong rets)

{

    uint8_t c = rtas_ld(args, 0);

    VIOsPAPRDevice *sdev = vty_lookup(spapr, 0);

    if (!sdev) {

        rtas_st(rets, 0, -1);

    } else {

        vty_putchars(sdev, &c, sizeof(c));

        rtas_st(rets, 0, 0);

    }

}


static int xmv_read_header(AVFormatContext *s)

{

    XMVDemuxContext *xmv = s->priv_data;

    AVIOContext     *pb  = s->pb;

    uint32_t file_version;

    uint32_t this_packet_size;

    uint16_t audio_track;

    int ret;

    s->ctx_flags |= AVFMTCTX_NOHEADER;

    avio_skip(pb, 4); /* Next packet size */

    this_packet_size = avio_rl32(pb);

    avio_skip(pb, 4); /* Max packet size */

    avio_skip(pb, 4); /* "xobX" */

    file_version = avio_rl32(pb);

    if ((file_version != 4) && (file_version != 2))

        avpriv_request_sample(s, "Uncommon version %"PRIu32"", file_version);

    /* Video tracks */

    xmv->video_width    = avio_rl32(pb);

    xmv->video_height   = avio_rl32(pb);

    xmv->video_duration = avio_rl32(pb);

    /* Audio tracks */

    xmv->audio_track_count = avio_rl16(pb);

    avio_skip(pb, 2); /* Unknown (padding?) */

    xmv->audio = av_mallocz_array(xmv->audio_track_count, sizeof(XMVAudioPacket));

    if (!xmv->audio) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    for (audio_track = 0; audio_track < xmv->audio_track_count; audio_track++) {

        XMVAudioPacket *packet = &xmv->audio[audio_track];

        packet->compression     = avio_rl16(pb);

        packet->channels        = avio_rl16(pb);

        packet->sample_rate     = avio_rl32(pb);

        packet->bits_per_sample = avio_rl16(pb);

        packet->flags           = avio_rl16(pb);

        packet->bit_rate      = packet->bits_per_sample *

                                packet->sample_rate *

                                packet->channels;

        packet->block_align   = XMV_BLOCK_ALIGN_SIZE * packet->channels;

        packet->block_samples = 64;

        packet->codec_id      = ff_wav_codec_get_id(packet->compression,

                                                    packet->bits_per_sample);

        packet->stream_index = -1;

        packet->frame_size  = 0;

        packet->block_count = 0;

        /* TODO: ADPCM'd 5.1 sound is encoded in three separate streams.

         *       Those need to be interleaved to a proper 5.1 stream. */

        if (packet->flags & XMV_AUDIO_ADPCM51)

            av_log(s, AV_LOG_WARNING, "Unsupported 5.1 ADPCM audio stream "

                                      "(0x%04X)\n", packet->flags);

        if (!packet->channels || !packet->sample_rate ||

             packet->channels >= UINT16_MAX / XMV_BLOCK_ALIGN_SIZE) {

            av_log(s, AV_LOG_ERROR, "Invalid parameters for audio track %"PRIu16".\n",

                   audio_track);

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

    }

    /* Initialize the packet context */

    xmv->next_packet_offset = avio_tell(pb);

    xmv->next_packet_size   = this_packet_size - xmv->next_packet_offset;

    xmv->stream_count       = xmv->audio_track_count + 1;

    return 0;

fail:

    xmv_read_close(s);

    return ret;

}


static int bdrv_rd_badreq_sectors(BlockDriverState *bs,

                                  int64_t sector_num, int nb_sectors)

{

    return

        nb_sectors < 0 ||

        sector_num < 0 ||

        nb_sectors > bs->total_sectors ||

        sector_num > bs->total_sectors - nb_sectors;

}


static int handle_update_file_cred(int dirfd, const char *name, FsCred *credp)

{

    int fd, ret;

    fd = openat(dirfd, name, O_NONBLOCK | O_NOFOLLOW);

    if (fd < 0) {

        return fd;

    }

    ret = fchmod(fd, credp->fc_mode & 07777);

    if (ret < 0) {

        goto err_out;

    }

    ret = fchownat(fd, "", credp->fc_uid, credp->fc_gid, AT_EMPTY_PATH);

err_out:

    close(fd);

    return ret;

}


static av_cold int ffv1_encode_init(AVCodecContext *avctx)

{

    FFV1Context *s = avctx->priv_data;

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);

    int i, j, k, m, ret;

    ffv1_common_init(avctx);

    s->version = 0;

    if ((avctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) ||

        avctx->slices > 1)

        s->version = FFMAX(s->version, 2);

    if (avctx->level == 3) {

        s->version = 3;

    }

    if (s->ec < 0) {

        s->ec = (s->version >= 3);

    }

    if (s->version >= 2 &&

        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(avctx, AV_LOG_ERROR,

               "Version %d requested, please set -strict experimental in "

               "order to enable it\n",

               s->version);

        return AVERROR(ENOSYS);

    }

    s->ac = avctx->coder_type > 0 ? 2 : 0;

    s->plane_count = 3;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUV444P9:

    case AV_PIX_FMT_YUV422P9:

    case AV_PIX_FMT_YUV420P9:

        if (!avctx->bits_per_raw_sample)

            s->bits_per_raw_sample = 9;

    case AV_PIX_FMT_YUV444P10:

    case AV_PIX_FMT_YUV420P10:

    case AV_PIX_FMT_YUV422P10:

        s->packed_at_lsb = 1;

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 10;

    case AV_PIX_FMT_GRAY16:

    case AV_PIX_FMT_YUV444P16:

    case AV_PIX_FMT_YUV422P16:

    case AV_PIX_FMT_YUV420P16:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample) {

            s->bits_per_raw_sample = 16;

        } else if (!s->bits_per_raw_sample) {

            s->bits_per_raw_sample = avctx->bits_per_raw_sample;

        }

        if (s->bits_per_raw_sample <= 8) {

            av_log(avctx, AV_LOG_ERROR, "bits_per_raw_sample invalid\n");

            return AVERROR_INVALIDDATA;

        }

        if (!s->ac && avctx->coder_type == -1) {

            av_log(avctx, AV_LOG_INFO,

                   "bits_per_raw_sample > 8, forcing coder 1\n");

            s->ac = 2;

        }

        if (!s->ac) {

            av_log(

                avctx, AV_LOG_ERROR,

                "bits_per_raw_sample of more than 8 needs -coder 1 currently\n");

            return AVERROR_INVALIDDATA;

        }

        s->version = FFMAX(s->version, 1);

    case AV_PIX_FMT_GRAY8:

    case AV_PIX_FMT_YUV444P:

    case AV_PIX_FMT_YUV440P:

    case AV_PIX_FMT_YUV422P:

    case AV_PIX_FMT_YUV420P:

    case AV_PIX_FMT_YUV411P:

    case AV_PIX_FMT_YUV410P:

        s->chroma_planes = desc->nb_components < 3 ? 0 : 1;

        s->colorspace    = 0;

        break;

    case AV_PIX_FMT_YUVA444P:

    case AV_PIX_FMT_YUVA422P:

    case AV_PIX_FMT_YUVA420P:

        s->chroma_planes = 1;

        s->colorspace    = 0;

        s->transparency  = 1;

        break;

    case AV_PIX_FMT_RGB32:

        s->colorspace   = 1;

        s->transparency = 1;

        break;

    case AV_PIX_FMT_GBRP9:

        if (!avctx->bits_per_raw_sample)

            s->bits_per_raw_sample = 9;

    case AV_PIX_FMT_GBRP10:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 10;

    case AV_PIX_FMT_GBRP16:

        if (!avctx->bits_per_raw_sample && !s->bits_per_raw_sample)

            s->bits_per_raw_sample = 16;

        else if (!s->bits_per_raw_sample)

            s->bits_per_raw_sample = avctx->bits_per_raw_sample;

        s->colorspace    = 1;

        s->chroma_planes = 1;

        s->version       = FFMAX(s->version, 1);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "format not supported\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->transparency) {

        av_log(

            avctx, AV_LOG_WARNING,

            "Storing alpha plane, this will require a recent FFV1 decoder to playback!\n");

    }

    if (avctx->context_model > 1U) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid context model %d, valid values are 0 and 1\n",

               avctx->context_model);

        return AVERROR(EINVAL);

    }

    if (s->ac > 1)

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

            s->state_transition[i] = ffv1_ver2_state[i];

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

        s->quant_table_count = 2;

        if (s->bits_per_raw_sample <= 8) {

            s->quant_tables[0][0][i] = ffv1_quant11[i];

            s->quant_tables[0][1][i] = ffv1_quant11[i] * 11;

            s->quant_tables[0][2][i] = ffv1_quant11[i] * 11 * 11;

            s->quant_tables[1][0][i] = ffv1_quant11[i];

            s->quant_tables[1][1][i] = ffv1_quant11[i] * 11;

            s->quant_tables[1][2][i] = ffv1_quant5[i]  * 11 * 11;

            s->quant_tables[1][3][i] = ffv1_quant5[i]  *  5 * 11 * 11;

            s->quant_tables[1][4][i] = ffv1_quant5[i]  *  5 *  5 * 11 * 11;

        } else {

            s->quant_tables[0][0][i] = ffv1_quant9_10bit[i];

            s->quant_tables[0][1][i] = ffv1_quant9_10bit[i] * 11;

            s->quant_tables[0][2][i] = ffv1_quant9_10bit[i] * 11 * 11;

            s->quant_tables[1][0][i] = ffv1_quant9_10bit[i];

            s->quant_tables[1][1][i] = ffv1_quant9_10bit[i] * 11;

            s->quant_tables[1][2][i] = ffv1_quant5_10bit[i] * 11 * 11;

            s->quant_tables[1][3][i] = ffv1_quant5_10bit[i] *  5 * 11 * 11;

            s->quant_tables[1][4][i] = ffv1_quant5_10bit[i] *  5 *  5 * 11 * 11;

        }

    }

    s->context_count[0] = (11 * 11 * 11        + 1) / 2;

    s->context_count[1] = (11 * 11 * 5 * 5 * 5 + 1) / 2;

    memcpy(s->quant_table, s->quant_tables[avctx->context_model],

           sizeof(s->quant_table));

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

        PlaneContext *const p = &s->plane[i];

        memcpy(p->quant_table, s->quant_table, sizeof(p->quant_table));

        p->quant_table_index = avctx->context_model;

        p->context_count     = s->context_count[p->quant_table_index];

    }

    if ((ret = ffv1_allocate_initial_states(s)) < 0)

        return ret;

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    if (!s->transparency)

        s->plane_count = 2;

    av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_h_shift,

                                     &s->chroma_v_shift);

    s->picture_number = 0;

    if (avctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {

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

            s->rc_stat2[i] = av_mallocz(s->context_count[i] *

                                        sizeof(*s->rc_stat2[i]));

            if (!s->rc_stat2[i])

                return AVERROR(ENOMEM);

        }

    }

    if (avctx->stats_in) {

        char *p = avctx->stats_in;

        uint8_t best_state[256][256];

        int gob_count = 0;

        char *next;

        av_assert0(s->version >= 2);

        for (;; ) {

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

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

                    s->rc_stat[j][i] = strtol(p, &next, 0);

                    if (next == p) {

                        av_log(avctx, AV_LOG_ERROR,

                               "2Pass file invalid at %d %d [%s]\n", j, i, p);

                        return AVERROR_INVALIDDATA;

                    }

                    p = next;

                }

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

                for (j = 0; j < s->context_count[i]; j++) {

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

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

                            s->rc_stat2[i][j][k][m] = strtol(p, &next, 0);

                            if (next == p) {

                                av_log(avctx, AV_LOG_ERROR,

                                       "2Pass file invalid at %d %d %d %d [%s]\n",

                                       i, j, k, m, p);

                                return AVERROR_INVALIDDATA;

                            }

                            p = next;

                        }

                }

            gob_count = strtol(p, &next, 0);

            if (next == p || gob_count <= 0) {

                av_log(avctx, AV_LOG_ERROR, "2Pass file invalid\n");

                return AVERROR_INVALIDDATA;

            }

            p = next;

            while (*p == '\n' || *p == ' ')

                p++;

            if (p[0] == 0)

                break;

        }

        sort_stt(s, s->state_transition);

        find_best_state(best_state, s->state_transition);

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

            for (j = 0; j < s->context_count[i]; j++)

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

                    double p = 128;

                    if (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]) {

                        p = 256.0 * s->rc_stat2[i][j][k][1] /

                            (s->rc_stat2[i][j][k][0] + s->rc_stat2[i][j][k][1]);

                    }

                    s->initial_states[i][j][k] =

                        best_state[av_clip(round(p), 1, 255)][av_clip((s->rc_stat2[i][j][k][0] +

                                                                       s->rc_stat2[i][j][k][1]) /

                                                                      gob_count, 0, 255)];

                }

        }

    }

    if (s->version > 1) {

        for (s->num_v_slices = 2; s->num_v_slices < 9; s->num_v_slices++)

            for (s->num_h_slices = s->num_v_slices;

                 s->num_h_slices < 2 * s->num_v_slices; s->num_h_slices++)

                if (avctx->slices == s->num_h_slices * s->num_v_slices &&

                    avctx->slices <= 64 || !avctx->slices)

                    goto slices_ok;

        av_log(avctx, AV_LOG_ERROR,

               "Unsupported number %d of slices requested, please specify a "

               "supported number with -slices (ex:4,6,9,12,16, ...)\n",

               avctx->slices);

        return AVERROR(ENOSYS);

slices_ok:

        write_extradata(s);

    }

    if ((ret = ffv1_init_slice_contexts(s)) < 0)

        return ret;

    if ((ret = init_slices_state(s)) < 0)

        return ret;

#define STATS_OUT_SIZE 1024 * 1024 * 6

    if (avctx->flags & CODEC_FLAG_PASS1) {

        avctx->stats_out = av_mallocz(STATS_OUT_SIZE);

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

            for (j = 0; j < s->slice_count; j++) {

                FFV1Context *sf = s->slice_context[j];

                av_assert0(!sf->rc_stat2[i]);

                sf->rc_stat2[i] = av_mallocz(s->context_count[i] *

                                             sizeof(*sf->rc_stat2[i]));

                if (!sf->rc_stat2[i])

                    return AVERROR(ENOMEM);

            }

    }

    return 0;

}


int qemu_devtree_setprop(void *fdt, const char *node_path,

                         const char *property, void *val_array, int size)

{

    int offset;

    offset = fdt_path_offset(fdt, node_path);

    if (offset < 0)

        return offset;

    return fdt_setprop(fdt, offset, property, val_array, size);

}


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

                                const AVFrame *frame, int *got_packet_ptr)

{

    LAMEContext *s = avctx->priv_data;

    MPADecodeHeader hdr;

    int len, ret, ch;

    int lame_result;

    uint32_t h;

    if (frame) {

        switch (avctx->sample_fmt) {

        case AV_SAMPLE_FMT_S16P:

            ENCODE_BUFFER(lame_encode_buffer, int16_t, frame->data);

            break;

        case AV_SAMPLE_FMT_S32P:

            ENCODE_BUFFER(lame_encode_buffer_int, int32_t, frame->data);

            break;

        case AV_SAMPLE_FMT_FLTP:

            if (frame->linesize[0] < 4 * FFALIGN(frame->nb_samples, 8)) {

                av_log(avctx, AV_LOG_ERROR, "inadequate AVFrame plane padding\n");

                return AVERROR(EINVAL);

            }

            for (ch = 0; ch < avctx->channels; ch++) {

                s->fdsp.vector_fmul_scalar(s->samples_flt[ch],

                                           (const float *)frame->data[ch],

                                           32768.0f,

                                           FFALIGN(frame->nb_samples, 8));

            }

            ENCODE_BUFFER(lame_encode_buffer_float, float, s->samples_flt);

            break;

        default:

            return AVERROR_BUG;

        }

    } else {

        lame_result = lame_encode_flush(s->gfp, s->buffer + s->buffer_index,

                                        s->buffer_size - s->buffer_index);

    }

    if (lame_result < 0) {

        if (lame_result == -1) {

            av_log(avctx, AV_LOG_ERROR,

                   "lame: output buffer too small (buffer index: %d, free bytes: %d)\n",

                   s->buffer_index, s->buffer_size - s->buffer_index);

        }

        return -1;

    }

    s->buffer_index += lame_result;

    ret = realloc_buffer(s);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "error reallocating output buffer\n");

        return ret;

    }

    /* add current frame to the queue */

    if (frame) {

        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)

            return ret;

    }

    /* Move 1 frame from the LAME buffer to the output packet, if available.

       We have to parse the first frame header in the output buffer to

       determine the frame size. */

    if (s->buffer_index < 4)

        return 0;

    h = AV_RB32(s->buffer);

    if (ff_mpa_check_header(h) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Invalid mp3 header at start of buffer\n");

        return AVERROR_BUG;

    }

    if (avpriv_mpegaudio_decode_header(&hdr, h)) {

        av_log(avctx, AV_LOG_ERROR, "free format output not supported\n");

        return -1;

    }

    len = hdr.frame_size;

    ff_dlog(avctx, "in:%d packet-len:%d index:%d\n", avctx->frame_size, len,

            s->buffer_index);

    if (len <= s->buffer_index) {

        if ((ret = ff_alloc_packet(avpkt, len))) {

            av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");

            return ret;

        }

        memcpy(avpkt->data, s->buffer, len);

        s->buffer_index -= len;

        memmove(s->buffer, s->buffer + len, s->buffer_index);

        /* Get the next frame pts/duration */

        ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                           &avpkt->duration);

        avpkt->size = len;

        *got_packet_ptr = 1;

    }

    return 0;

}


static int tta_decode_frame(AVCodecContext *avctx,

        void *data, int *data_size,

        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TTAContext *s = avctx->priv_data;

    int i;

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

    {

        int32_t predictors[s->channels];

        TTAFilter filters[s->channels];

        TTARice rices[s->channels];

        int cur_chan = 0, framelen = s->frame_length;

        int32_t *p;

        // FIXME: seeking

        s->total_frames--;

        if (!s->total_frames && s->last_frame_length)

            framelen = s->last_frame_length;

        // init per channel states

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

            predictors[i] = 0;

            ttafilter_init(&(filters[i]), ttafilter_configs[s->bps-1][0], ttafilter_configs[s->bps-1][1]);

            rice_init(&(rices[i]), 10, 10);

        }

        for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {

            int32_t *predictor = &(predictors[cur_chan]);

            TTAFilter *filter = &(filters[cur_chan]);

            TTARice *rice = &(rices[cur_chan]);

            uint32_t unary, depth, k;

            int32_t value;

            unary = tta_get_unary(&s->gb);

            if (unary == 0) {

                depth = 0;

                k = rice->k0;

            } else {

                depth = 1;

                k = rice->k1;

                unary--;

            }

            if (k)

                value = (unary << k) + get_bits(&s->gb, k);

            else

                value = unary;

            // FIXME: copy paste from original

            switch (depth) {

            case 1:

                rice->sum1 += value - (rice->sum1 >> 4);

                if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])

                    rice->k1--;

                else if(rice->sum1 > shift_16[rice->k1 + 1])

                    rice->k1++;

                value += shift_1[rice->k0];

            default:

                rice->sum0 += value - (rice->sum0 >> 4);

                if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])

                    rice->k0--;

                else if(rice->sum0 > shift_16[rice->k0 + 1])

                    rice->k0++;

            }

            // extract coded value

#define UNFOLD(x) (((x)&1) ? (++(x)>>1) : (-(x)>>1))

            *p = UNFOLD(value);

            // run hybrid filter

            ttafilter_process(filter, p, 0);

            // fixed order prediction

#define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)

            switch (s->bps) {

                case 1: *p += PRED(*predictor, 4); break;

                case 2:

                case 3: *p += PRED(*predictor, 5); break;

                case 4: *p += *predictor; break;

            }

            *predictor = *p;

#if 0

            // extract 32bit float from last two int samples

            if (s->is_float && ((p - data) & 1)) {

                uint32_t neg = *p & 0x80000000;

                uint32_t hi = *(p - 1);

                uint32_t lo = abs(*p) - 1;

                hi += (hi || lo) ? 0x3f80 : 0;

                // SWAP16: swap all the 16 bits

                *(p - 1) = (hi << 16) | SWAP16(lo) | neg;

            }

#endif

            /*if ((get_bits_count(&s->gb)+7)/8 > buf_size)

            {

                av_log(NULL, AV_LOG_INFO, "overread!!\n");

                break;

            }*/

            // flip channels

            if (cur_chan < (s->channels-1))

                cur_chan++;

            else {

                // decorrelate in case of stereo integer

                if (!s->is_float && (s->channels > 1)) {

                    int32_t *r = p - 1;

                    for (*p += *r / 2; r > p - s->channels; r--)

                        *r = *(r + 1) - *r;

                }

                cur_chan = 0;

            }

        }

        skip_bits(&s->gb, 32); // frame crc

        // convert to output buffer

        switch(s->bps) {

            case 2: {

                uint16_t *samples = data;

                for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {

//                    *samples++ = (unsigned char)*p;

//                    *samples++ = (unsigned char)(*p >> 8);

                    *samples++ = *p;

                }

                *data_size = (uint8_t *)samples - (uint8_t *)data;

                break;

            }

            default:

                av_log(s->avctx, AV_LOG_ERROR, "Error, only 16bit samples supported!\n");

        }

    }

//    return get_bits_count(&s->gb)+7)/8;

    return buf_size;

}


yuv2rgba64_2_c_template(SwsContext *c, const int32_t *buf[2],

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf[2], uint16_t *dest, int dstW,

                       int yalpha, int uvalpha, int y,

                       enum AVPixelFormat target, int hasAlpha, int eightbytes)

{

    const int32_t *buf0  = buf[0],  *buf1  = buf[1],

                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1],

                  *abuf0 = hasAlpha ? abuf[0] : NULL,

                  *abuf1 = hasAlpha ? abuf[1] : NULL;

    int  yalpha1 = 4096 - yalpha;

    int uvalpha1 = 4096 - uvalpha;

    int i;

    int A1 = 0xffff<<14, A2 = 0xffff<<14;

    for (i = 0; i < ((dstW + 1) >> 1); i++) {

        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha) >> 14;

        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha) >> 14;

        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha + (-128 << 23)) >> 14;

        int R, G, B;

        Y1 -= c->yuv2rgb_y_offset;

        Y2 -= c->yuv2rgb_y_offset;

        Y1 *= c->yuv2rgb_y_coeff;

        Y2 *= c->yuv2rgb_y_coeff;

        Y1 += 1 << 13;

        Y2 += 1 << 13;

        R = V * c->yuv2rgb_v2r_coeff;

        G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

        B =                            U * c->yuv2rgb_u2b_coeff;

        if (hasAlpha) {

            A1 = (abuf0[i * 2    ] * yalpha1 + abuf1[i * 2    ] * yalpha) >> 1;

            A2 = (abuf0[i * 2 + 1] * yalpha1 + abuf1[i * 2 + 1] * yalpha) >> 1;

            A1 += 1 << 13;

            A2 += 1 << 13;

        }

        output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

        output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

        output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

        if (eightbytes) {

            output_pixel(&dest[3], av_clip_uintp2(A1      , 30) >> 14);

            output_pixel(&dest[4], av_clip_uintp2(R_B + Y2, 30) >> 14);

            output_pixel(&dest[5], av_clip_uintp2(  G + Y2, 30) >> 14);

            output_pixel(&dest[6], av_clip_uintp2(B_R + Y2, 30) >> 14);

            output_pixel(&dest[7], av_clip_uintp2(A2      , 30) >> 14);

            dest += 8;

        } else {

            output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

            output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

            output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

            dest += 6;

        }

    }

}


static void backup_duplicate_context(MpegEncContext *bak, MpegEncContext *src){

#define COPY(a) bak->a= src->a

    COPY(allocated_edge_emu_buffer);

    COPY(edge_emu_buffer);

    COPY(me.scratchpad);

    COPY(me.temp);

    COPY(rd_scratchpad);

    COPY(b_scratchpad);

    COPY(obmc_scratchpad);

    COPY(me.map);

    COPY(me.score_map);

    COPY(blocks);

    COPY(block);

    COPY(start_mb_y);

    COPY(end_mb_y);

    COPY(me.map_generation);

    COPY(pb);

    COPY(dct_error_sum);

    COPY(dct_count[0]);

    COPY(dct_count[1]);

    COPY(ac_val_base);

    COPY(ac_val[0]);

    COPY(ac_val[1]);

    COPY(ac_val[2]);

#undef COPY

}


static av_cold void free_frame_buffers(Indeo3DecodeContext *ctx)

{

    int p;

    ctx->width=

    ctx->height= 0;

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

        av_freep(&ctx->planes[p].buffers[0]);

        av_freep(&ctx->planes[p].buffers[1]);

        ctx->planes[p].pixels[0] = ctx->planes[p].pixels[1] = 0;

    }

}


static AVInputFormat *probe_input_format(AVProbeData *pd, int is_opened)

{

    AVInputFormat *fmt1, *fmt;

    int score, score_max;

    fmt = NULL;

    score_max = 0;

    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {

        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))

            continue;

        score = 0;

        if (fmt1->extensions) {

            if (match_ext(pd->filename, fmt1->extensions)) {

                score = 50;

            }

        } else if (fmt1->read_probe) {

            score = fmt1->read_probe(pd);

        }

        if (score > score_max) {

            score_max = score;

            fmt = fmt1;

        }

    }

    return fmt;

}


static void pc_dimm_check_memdev_is_busy(Object *obj, const char *name,

                                      Object *val, Error **errp)

{

    MemoryRegion *mr;

    mr = host_memory_backend_get_memory(MEMORY_BACKEND(val), errp);

    if (memory_region_is_mapped(mr)) {

        char *path = object_get_canonical_path_component(val);

        error_setg(errp, "can't use already busy memdev: %s", path);

        g_free(path);

    } else {

        qdev_prop_allow_set_link_before_realize(obj, name, val, errp);

    }

}


int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    int ret;

    AVStream *st;

    ff_read_frame_flush(s);

    if(flags & AVSEEK_FLAG_BYTE)

        return av_seek_frame_byte(s, stream_index, timestamp, flags);

    if(stream_index < 0){

        stream_index= av_find_default_stream_index(s);

        if(stream_index < 0)

            return -1;

        st= s->streams[stream_index];

       /* timestamp for default must be expressed in AV_TIME_BASE units */

        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);

    }

    /* first, we try the format specific seek */

    if (s->iformat->read_seek)

        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);

    else

        ret = -1;

    if (ret >= 0) {

        return 0;

    }

    if(s->iformat->read_timestamp)

        return av_seek_frame_binary(s, stream_index, timestamp, flags);

    else

        return av_seek_frame_generic(s, stream_index, timestamp, flags);

}


static int mpeg_mux_end(AVFormatContext *ctx)

{

    StreamInfo *stream;

    int i;

    /* flush each packet */

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

        stream = ctx->streams[i]->priv_data;

        if (stream->buffer_ptr > 0) {

            if (i == (ctx->nb_streams - 1))

                flush_packet(ctx, i, 1);

            else

                flush_packet(ctx, i, 0);

        }

    }

    /* write the end header */

    //put_be32(&ctx->pb, ISO_11172_END_CODE);

    //put_flush_packet(&ctx->pb);

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

        av_freep(&ctx->streams[i]->priv_data);

    return 0;

}


static void virtio_scsi_complete_req(VirtIOSCSIReq *req)

{

    VirtIOSCSI *s = req->dev;

    VirtQueue *vq = req->vq;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    qemu_iovec_from_buf(&req->resp_iov, 0, &req->resp, req->resp_size);

    virtqueue_push(vq, &req->elem, req->qsgl.size + req->resp_iov.size);

    if (s->dataplane_started && !s->dataplane_fenced) {

        virtio_scsi_dataplane_notify(vdev, req);

    } else {

        virtio_notify(vdev, vq);

    }

    if (req->sreq) {

        req->sreq->hba_private = NULL;

        scsi_req_unref(req->sreq);

    }

    virtio_scsi_free_req(req);

}


static int inet_connect_addr(struct addrinfo *addr, bool block,

                             bool *in_progress)

{

    int sock, rc;

    if (in_progress) {

        *in_progress = false;

    }

    sock = qemu_socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);

    if (sock < 0) {

        fprintf(stderr, "%s: socket(%s): %s\n", __func__,

                inet_strfamily(addr->ai_family), strerror(errno));

        return -1;

    }

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if (!block) {

        socket_set_nonblock(sock);

    }

    /* connect to peer */

    do {

        rc = 0;

        if (connect(sock, addr->ai_addr, addr->ai_addrlen) < 0) {

            rc = -socket_error();

        }

    } while (rc == -EINTR);

    if (!block && QEMU_SOCKET_RC_INPROGRESS(rc)) {

        if (in_progress) {

            *in_progress = true;

        }

    } else if (rc < 0) {

        closesocket(sock);

        return -1;

    }

    return sock;

}


static void gen_rfci(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    /* Restore CPU state */

    gen_helper_rfci(cpu_env);

    gen_sync_exception(ctx);

#endif

}


static int opt_new_stream(const char *opt, const char *arg)

{

    AVFormatContext *oc;

    if (nb_output_files <= 0) {

        fprintf(stderr, "At least one output file must be specified\n");

        ffmpeg_exit(1);

    }

    oc = output_files[nb_output_files - 1];

    if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc);

    else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc);

    else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc);

    else av_assert0(0);

    return 0;

}


void ff_vp3_v_loop_filter_c(uint8_t *first_pixel, int stride, int *bounding_values)

{

    unsigned char *end;

    int filter_value;

    const int nstride= -stride;

    for (end= first_pixel + 8; first_pixel < end; first_pixel++) {

        filter_value =

            (first_pixel[2 * nstride] - first_pixel[ stride])

         +3*(first_pixel[0          ] - first_pixel[nstride]);

        filter_value = bounding_values[(filter_value + 4) >> 3];

        first_pixel[nstride] = av_clip_uint8(first_pixel[nstride] + filter_value);

        first_pixel[0] = av_clip_uint8(first_pixel[0] - filter_value);

    }

}


void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height, int linesize_align[4]){

    int w_align= 1;

    int h_align= 1;

    switch(s->pix_fmt){

    case PIX_FMT_YUV420P:

    case PIX_FMT_YUYV422:

    case PIX_FMT_UYVY422:

    case PIX_FMT_YUV422P:

    case PIX_FMT_YUV440P:

    case PIX_FMT_YUV444P:

    case PIX_FMT_GRAY8:

    case PIX_FMT_GRAY16BE:

    case PIX_FMT_GRAY16LE:

    case PIX_FMT_YUVJ420P:

    case PIX_FMT_YUVJ422P:

    case PIX_FMT_YUVJ440P:

    case PIX_FMT_YUVJ444P:

    case PIX_FMT_YUVA420P:

    case PIX_FMT_YUV420P9LE:

    case PIX_FMT_YUV420P9BE:

    case PIX_FMT_YUV420P10LE:

    case PIX_FMT_YUV420P10BE:

    case PIX_FMT_YUV422P10LE:

    case PIX_FMT_YUV422P10BE:

        w_align= 16; //FIXME check for non mpeg style codecs and use less alignment

        h_align= 16;

        if(s->codec_id == CODEC_ID_MPEG2VIDEO || s->codec_id == CODEC_ID_MJPEG || s->codec_id == CODEC_ID_AMV || s->codec_id == CODEC_ID_THP || s->codec_id == CODEC_ID_H264)

            h_align= 32; // interlaced is rounded up to 2 MBs

        break;

    case PIX_FMT_YUV411P:

    case PIX_FMT_UYYVYY411:

        w_align=32;

        h_align=8;

        break;

    case PIX_FMT_YUV410P:

        if(s->codec_id == CODEC_ID_SVQ1){

            w_align=64;

            h_align=64;

        }

    case PIX_FMT_RGB555:

        if(s->codec_id == CODEC_ID_RPZA){

            w_align=4;

            h_align=4;

        }

    case PIX_FMT_PAL8:

    case PIX_FMT_BGR8:

    case PIX_FMT_RGB8:

        if(s->codec_id == CODEC_ID_SMC){

            w_align=4;

            h_align=4;

        }

        break;

    case PIX_FMT_BGR24:

        if((s->codec_id == CODEC_ID_MSZH) || (s->codec_id == CODEC_ID_ZLIB)){

            w_align=4;

            h_align=4;

        }

        break;

    default:

        w_align= 1;

        h_align= 1;

        break;

    }

    *width = FFALIGN(*width , w_align);

    *height= FFALIGN(*height, h_align);

    if(s->codec_id == CODEC_ID_H264 || s->lowres)

        *height+=2; // some of the optimized chroma MC reads one line too much

                    // which is also done in mpeg decoders with lowres > 0

    linesize_align[0] =

    linesize_align[1] =

    linesize_align[2] =

    linesize_align[3] = STRIDE_ALIGN;

//STRIDE_ALIGN is 8 for SSE* but this does not work for SVQ1 chroma planes

//we could change STRIDE_ALIGN to 16 for x86/sse but it would increase the

//picture size unneccessarily in some cases. The solution here is not

//pretty and better ideas are welcome!

#if HAVE_MMX

    if(s->codec_id == CODEC_ID_SVQ1 || s->codec_id == CODEC_ID_VP5 ||

       s->codec_id == CODEC_ID_VP6 || s->codec_id == CODEC_ID_VP6F ||

       s->codec_id == CODEC_ID_VP6A) {

        linesize_align[0] =

        linesize_align[1] =

        linesize_align[2] = 16;

    }

#endif

}


static int h264_slice_header_parse(H264Context *h, H264SliceContext *sl,

                                   const H2645NAL *nal)

{

    const SPS *sps;

    const PPS *pps;

    int ret;

    unsigned int slice_type, tmp, i;

    int field_pic_flag, bottom_field_flag;

    int frame_num, droppable, picture_structure;

    int mb_aff_frame = 0;

    sl->first_mb_addr = get_ue_golomb(&sl->gb);

    if (sl->first_mb_addr == 0) { // FIXME better field boundary detection

        if (h->current_slice && h->cur_pic_ptr && FIELD_PICTURE(h)) {

            ff_h264_field_end(h, sl, 1);

        }

        h->current_slice = 0;

        if (!h->first_field) {

            if (h->cur_pic_ptr && !h->droppable) {

                ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX,

                                          h->picture_structure == PICT_BOTTOM_FIELD);

            }

            h->cur_pic_ptr = NULL;

        }

    }

    slice_type = get_ue_golomb_31(&sl->gb);

    if (slice_type > 9) {

        av_log(h->avctx, AV_LOG_ERROR,

               "slice type %d too large at %d\n",

               slice_type, sl->first_mb_addr);

        return AVERROR_INVALIDDATA;

    }

    if (slice_type > 4) {

        slice_type -= 5;

        sl->slice_type_fixed = 1;

    } else

        sl->slice_type_fixed = 0;

    slice_type         = ff_h264_golomb_to_pict_type[slice_type];

    sl->slice_type     = slice_type;

    sl->slice_type_nos = slice_type & 3;

    if (nal->type  == NAL_IDR_SLICE &&

        sl->slice_type_nos != AV_PICTURE_TYPE_I) {

        av_log(h->avctx, AV_LOG_ERROR, "A non-intra slice in an IDR NAL unit.\n");

        return AVERROR_INVALIDDATA;

    }

    sl->pps_id = get_ue_golomb(&sl->gb);

    if (sl->pps_id >= MAX_PPS_COUNT) {

        av_log(h->avctx, AV_LOG_ERROR, "pps_id %u out of range\n", sl->pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (!h->ps.pps_list[sl->pps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing PPS %u referenced\n",

               sl->pps_id);

        return AVERROR_INVALIDDATA;

    }

    if (h->current_slice > 0 &&

        h->ps.pps != (const PPS*)h->ps.pps_list[sl->pps_id]->data) {

        av_log(h->avctx, AV_LOG_ERROR, "PPS changed between slices\n");

        return AVERROR_INVALIDDATA;

    }

    pps = (const PPS*)h->ps.pps_list[sl->pps_id]->data;

    if (!h->ps.sps_list[pps->sps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing SPS %u referenced\n", pps->sps_id);

        return AVERROR_INVALIDDATA;

    }

    sps = (const SPS*)h->ps.sps_list[pps->sps_id]->data;

    frame_num = get_bits(&sl->gb, sps->log2_max_frame_num);

    if (!h->setup_finished)

        h->poc.frame_num = frame_num;

    sl->mb_mbaff       = 0;

    droppable = nal->ref_idc == 0;

    if (sps->frame_mbs_only_flag) {

        picture_structure = PICT_FRAME;

    } else {

        field_pic_flag = get_bits1(&sl->gb);

        if (field_pic_flag) {

            bottom_field_flag = get_bits1(&sl->gb);

            picture_structure = PICT_TOP_FIELD + bottom_field_flag;

        } else {

            picture_structure = PICT_FRAME;

            mb_aff_frame      = sps->mb_aff;

        }

    }

    if (!h->setup_finished) {

        h->mb_aff_frame      = mb_aff_frame;

    }

    sl->picture_structure      = picture_structure;

    sl->mb_field_decoding_flag = picture_structure != PICT_FRAME;

    if (h->current_slice != 0) {

        if (h->picture_structure != picture_structure ||

            h->droppable         != droppable) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "Changing field mode (%d -> %d) between slices is not allowed\n",

                   h->picture_structure, picture_structure);

            return AVERROR_INVALIDDATA;

        } else if (!h->cur_pic_ptr) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "unset cur_pic_ptr on slice %d\n",

                   h->current_slice + 1);

            return AVERROR_INVALIDDATA;

        }

    }

    if (picture_structure == PICT_FRAME) {

        h->curr_pic_num = h->poc.frame_num;

        h->max_pic_num  = 1 << sps->log2_max_frame_num;

    } else {

        h->curr_pic_num = 2 * h->poc.frame_num + 1;

        h->max_pic_num  = 1 << (sps->log2_max_frame_num + 1);

    }

    if (nal->type == NAL_IDR_SLICE)

        get_ue_golomb(&sl->gb); /* idr_pic_id */

    if (sps->poc_type == 0) {

        int poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);

        if (!h->setup_finished)

            h->poc.poc_lsb = poc_lsb;

        if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME) {

            int delta_poc_bottom = get_se_golomb(&sl->gb);

            if (!h->setup_finished)

                h->poc.delta_poc_bottom = delta_poc_bottom;

        }

    }

    if (sps->poc_type == 1 && !sps->delta_pic_order_always_zero_flag) {

        int delta_poc = get_se_golomb(&sl->gb);

        if (!h->setup_finished)

            h->poc.delta_poc[0] = delta_poc;

        if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME) {

            delta_poc = get_se_golomb(&sl->gb);

            if (!h->setup_finished)

                h->poc.delta_poc[1] = delta_poc;

        }

    }

    if (pps->redundant_pic_cnt_present)

        sl->redundant_pic_count = get_ue_golomb(&sl->gb);

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B)

        sl->direct_spatial_mv_pred = get_bits1(&sl->gb);

    ret = ff_h264_parse_ref_count(&sl->list_count, sl->ref_count,

                                  &sl->gb, pps, sl->slice_type_nos,

                                  picture_structure);

    if (ret < 0)

        return ret;

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I) {

       ret = ff_h264_decode_ref_pic_list_reordering(h, sl);

       if (ret < 0) {

           sl->ref_count[1] = sl->ref_count[0] = 0;

           return ret;

       }

    }

    sl->pwt.use_weight = 0;

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

        sl->pwt.luma_weight_flag[i]   = 0;

        sl->pwt.chroma_weight_flag[i] = 0;

    }

    if ((pps->weighted_pred && sl->slice_type_nos == AV_PICTURE_TYPE_P) ||

        (pps->weighted_bipred_idc == 1 &&

         sl->slice_type_nos == AV_PICTURE_TYPE_B))

        ff_h264_pred_weight_table(&sl->gb, sps, sl->ref_count,

                                  sl->slice_type_nos, &sl->pwt);

    sl->explicit_ref_marking = 0;

    if (nal->ref_idc) {

        ret = ff_h264_decode_ref_pic_marking(h, sl, &sl->gb);

        if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))

            return AVERROR_INVALIDDATA;

    }

    if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR, "cabac_init_idc %u overflow\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->cabac_init_idc = tmp;

    }

    sl->last_qscale_diff = 0;

    tmp = pps->init_qp + get_se_golomb(&sl->gb);

    if (tmp > 51 + 6 * (sps->bit_depth_luma - 8)) {

        av_log(h->avctx, AV_LOG_ERROR, "QP %u out of range\n", tmp);

        return AVERROR_INVALIDDATA;

    }

    sl->qscale       = tmp;

    sl->chroma_qp[0] = get_chroma_qp(pps, 0, sl->qscale);

    sl->chroma_qp[1] = get_chroma_qp(pps, 1, sl->qscale);

    // FIXME qscale / qp ... stuff

    if (sl->slice_type == AV_PICTURE_TYPE_SP)

        get_bits1(&sl->gb); /* sp_for_switch_flag */

    if (sl->slice_type == AV_PICTURE_TYPE_SP ||

        sl->slice_type == AV_PICTURE_TYPE_SI)

        get_se_golomb(&sl->gb); /* slice_qs_delta */

    sl->deblocking_filter     = 1;

    sl->slice_alpha_c0_offset = 0;

    sl->slice_beta_offset     = 0;

    if (pps->deblocking_filter_parameters_present) {

        tmp = get_ue_golomb_31(&sl->gb);

        if (tmp > 2) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "deblocking_filter_idc %u out of range\n", tmp);

            return AVERROR_INVALIDDATA;

        }

        sl->deblocking_filter = tmp;

        if (sl->deblocking_filter < 2)

            sl->deblocking_filter ^= 1;  // 1<->0

        if (sl->deblocking_filter) {

            sl->slice_alpha_c0_offset = get_se_golomb(&sl->gb) * 2;

            sl->slice_beta_offset     = get_se_golomb(&sl->gb) * 2;

            if (sl->slice_alpha_c0_offset >  12 ||

                sl->slice_alpha_c0_offset < -12 ||

                sl->slice_beta_offset >  12     ||

                sl->slice_beta_offset < -12) {

                av_log(h->avctx, AV_LOG_ERROR,

                       "deblocking filter parameters %d %d out of range\n",

                       sl->slice_alpha_c0_offset, sl->slice_beta_offset);

                return AVERROR_INVALIDDATA;

            }

        }

    }

    return 0;

}


static inline void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)

{

    int i, csize = 1;

    void *src[3];

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

        if (tile->codsty[0].transform != tile->codsty[i].transform) {

            av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");

            return;

        }

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

        if (tile->codsty[0].transform == FF_DWT97)

            src[i] = tile->comp[i].f_data;

        else

            src[i] = tile->comp[i].i_data;

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

        csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];

    s->dsp.mct_decode[tile->codsty[0].transform](src[0], src[1], src[2], csize);

}


static inline void RENAME(rgb2rgb_init)(void)

{

#if !COMPILE_TEMPLATE_SSE2

#if !COMPILE_TEMPLATE_AMD3DNOW

    rgb15to16          = RENAME(rgb15to16);

    rgb15tobgr24       = RENAME(rgb15tobgr24);

    rgb15to32          = RENAME(rgb15to32);

    rgb16tobgr24       = RENAME(rgb16tobgr24);

    rgb16to32          = RENAME(rgb16to32);

    rgb16to15          = RENAME(rgb16to15);

    rgb24tobgr16       = RENAME(rgb24tobgr16);

    rgb24tobgr15       = RENAME(rgb24tobgr15);

    rgb24tobgr32       = RENAME(rgb24tobgr32);

    rgb32to16          = RENAME(rgb32to16);

    rgb32to15          = RENAME(rgb32to15);

    rgb32tobgr24       = RENAME(rgb32tobgr24);

    rgb24to15          = RENAME(rgb24to15);

    rgb24to16          = RENAME(rgb24to16);

    rgb24tobgr24       = RENAME(rgb24tobgr24);

    shuffle_bytes_2103 = RENAME(shuffle_bytes_2103);

    rgb32tobgr16       = RENAME(rgb32tobgr16);

    rgb32tobgr15       = RENAME(rgb32tobgr15);

    yv12toyuy2         = RENAME(yv12toyuy2);

    yv12touyvy         = RENAME(yv12touyvy);

    yuv422ptoyuy2      = RENAME(yuv422ptoyuy2);

    yuv422ptouyvy      = RENAME(yuv422ptouyvy);

    yuy2toyv12         = RENAME(yuy2toyv12);

    vu9_to_vu12        = RENAME(vu9_to_vu12);

    yvu9_to_yuy2       = RENAME(yvu9_to_yuy2);

    uyvytoyuv422       = RENAME(uyvytoyuv422);

    yuyvtoyuv422       = RENAME(yuyvtoyuv422);

#endif /* !COMPILE_TEMPLATE_AMD3DNOW */

#if COMPILE_TEMPLATE_MMXEXT || COMPILE_TEMPLATE_AMD3DNOW

    planar2x           = RENAME(planar2x);

#endif /* COMPILE_TEMPLATE_MMXEXT || COMPILE_TEMPLATE_AMD3DNOW */

    rgb24toyv12        = RENAME(rgb24toyv12);

    yuyvtoyuv420       = RENAME(yuyvtoyuv420);

    uyvytoyuv420       = RENAME(uyvytoyuv420);

#endif /* !COMPILE_TEMPLATE_SSE2 */

#if !COMPILE_TEMPLATE_AMD3DNOW

    interleaveBytes    = RENAME(interleaveBytes);

#endif /* !COMPILE_TEMPLATE_AMD3DNOW */

}


static int hls_write_header(AVFormatContext *s)

{

    HLSContext *hls = s->priv_data;

    int ret, i;

    char *p;

    const char *pattern = "%d.ts";

    int basename_size = strlen(s->filename) + strlen(pattern);

    hls->number      = 0;

    hls->recording_time = hls->time * 1000000;

    hls->start_pts      = AV_NOPTS_VALUE;

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

        hls->has_video +=

            s->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO;

    if (hls->has_video > 1)

        av_log(s, AV_LOG_WARNING,

               "More than a single video stream present, "

               "expect issues decoding it.\n");

    hls->oformat = av_guess_format("mpegts", NULL, NULL);

    if (!hls->oformat) {

        ret = AVERROR_MUXER_NOT_FOUND;

        goto fail;

    }

    hls->basename = av_malloc(basename_size);

    if (!hls->basename) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    strcpy(hls->basename, s->filename);

    p = strrchr(hls->basename, '.');

    if (p)

        *p = '\0';

    av_strlcat(hls->basename, "%d.ts", basename_size);

    if ((ret = hls_mux_init(s)) < 0)

        goto fail;

    if ((ret = hls_start(s)) < 0)

        goto fail;

    if ((ret = avformat_write_header(hls->avf, NULL)) < 0)

        return ret;

fail:

    if (ret) {

        av_free(hls->basename);

        if (hls->avf)

            avformat_free_context(hls->avf);

    }

    return ret;

}