cpu_x86_dump_seg_cache(CPUState *env, FILE *f, fprintf_function cpu_fprintf,

                       const char *name, struct SegmentCache *sc)

{

#ifdef TARGET_X86_64

    if (env->hflags & HF_CS64_MASK) {

        cpu_fprintf(f, "%-3s=%04x %016" PRIx64 " %08x %08x", name,

                    sc->selector, sc->base, sc->limit, sc->flags);

    } else

#endif

    {

        cpu_fprintf(f, "%-3s=%04x %08x %08x %08x", name, sc->selector,

                    (uint32_t)sc->base, sc->limit, sc->flags);

    }

    if (!(env->hflags & HF_PE_MASK) || !(sc->flags & DESC_P_MASK))

        goto done;

    cpu_fprintf(f, " DPL=%d ", (sc->flags & DESC_DPL_MASK) >> DESC_DPL_SHIFT);

    if (sc->flags & DESC_S_MASK) {

        if (sc->flags & DESC_CS_MASK) {

            cpu_fprintf(f, (sc->flags & DESC_L_MASK) ? "CS64" :

                           ((sc->flags & DESC_B_MASK) ? "CS32" : "CS16"));

            cpu_fprintf(f, " [%c%c", (sc->flags & DESC_C_MASK) ? 'C' : '-',

                        (sc->flags & DESC_R_MASK) ? 'R' : '-');

        } else {

            cpu_fprintf(f, (sc->flags & DESC_B_MASK) ? "DS  " : "DS16");

            cpu_fprintf(f, " [%c%c", (sc->flags & DESC_E_MASK) ? 'E' : '-',

                        (sc->flags & DESC_W_MASK) ? 'W' : '-');

        }

        cpu_fprintf(f, "%c]", (sc->flags & DESC_A_MASK) ? 'A' : '-');

    } else {

        static const char *sys_type_name[2][16] = {

            { /* 32 bit mode */

                "Reserved", "TSS16-avl", "LDT", "TSS16-busy",

                "CallGate16", "TaskGate", "IntGate16", "TrapGate16",

                "Reserved", "TSS32-avl", "Reserved", "TSS32-busy",

                "CallGate32", "Reserved", "IntGate32", "TrapGate32"

            },

            { /* 64 bit mode */

                "<hiword>", "Reserved", "LDT", "Reserved", "Reserved",

                "Reserved", "Reserved", "Reserved", "Reserved",

                "TSS64-avl", "Reserved", "TSS64-busy", "CallGate64",

                "Reserved", "IntGate64", "TrapGate64"

            }

        };

        cpu_fprintf(f, "%s",

                    sys_type_name[(env->hflags & HF_LMA_MASK) ? 1 : 0]

                                 [(sc->flags & DESC_TYPE_MASK)

                                  >> DESC_TYPE_SHIFT]);

    }

done:

    cpu_fprintf(f, "\n");

}


void FUNCC(ff_h264_idct_add)(uint8_t *_dst, DCTELEM *_block, int stride)

{

    int i;

    INIT_CLIP

    pixel *dst = (pixel*)_dst;

    dctcoef *block = (dctcoef*)_block;

    stride /= sizeof(pixel);

    block[0] += 1 << 5;

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

        const int z0=  block[i + 4*0]     +  block[i + 4*2];

        const int z1=  block[i + 4*0]     -  block[i + 4*2];

        const int z2= (block[i + 4*1]>>1) -  block[i + 4*3];

        const int z3=  block[i + 4*1]     + (block[i + 4*3]>>1);

        block[i + 4*0]= z0 + z3;

        block[i + 4*1]= z1 + z2;

        block[i + 4*2]= z1 - z2;

        block[i + 4*3]= z0 - z3;

    }

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

        const int z0=  block[0 + 4*i]     +  block[2 + 4*i];

        const int z1=  block[0 + 4*i]     -  block[2 + 4*i];

        const int z2= (block[1 + 4*i]>>1) -  block[3 + 4*i];

        const int z3=  block[1 + 4*i]     + (block[3 + 4*i]>>1);

        dst[i + 0*stride]= CLIP(dst[i + 0*stride] + ((z0 + z3) >> 6));

        dst[i + 1*stride]= CLIP(dst[i + 1*stride] + ((z1 + z2) >> 6));

        dst[i + 2*stride]= CLIP(dst[i + 2*stride] + ((z1 - z2) >> 6));

        dst[i + 3*stride]= CLIP(dst[i + 3*stride] + ((z0 - z3) >> 6));

    }

}


static void disas_fp_ccomp(DisasContext *s, uint32_t insn)

{

    unsigned int mos, type, rm, cond, rn, op, nzcv;

    TCGv_i64 tcg_flags;

    int label_continue = -1;

    mos = extract32(insn, 29, 3);

    type = extract32(insn, 22, 2); /* 0 = single, 1 = double */

    rm = extract32(insn, 16, 5);

    cond = extract32(insn, 12, 4);

    rn = extract32(insn, 5, 5);

    op = extract32(insn, 4, 1);

    nzcv = extract32(insn, 0, 4);

    if (mos || type > 1) {

        unallocated_encoding(s);

        return;

    }

    if (!fp_access_check(s)) {

        return;

    }

    if (cond < 0x0e) { /* not always */

        int label_match = gen_new_label();

        label_continue = gen_new_label();

        arm_gen_test_cc(cond, label_match);

        /* nomatch: */

        tcg_flags = tcg_const_i64(nzcv << 28);

        gen_set_nzcv(tcg_flags);

        tcg_temp_free_i64(tcg_flags);

        tcg_gen_br(label_continue);

        gen_set_label(label_match);

    }

    handle_fp_compare(s, type, rn, rm, false, op);

    if (cond < 0x0e) {

        gen_set_label(label_continue);

    }

}


static inline int test_bit(unsigned int bit, const unsigned long *map)

{

    return !!((map)[(bit) / BITS_PER_LONG] & (1UL << ((bit) % BITS_PER_LONG)));

}


static bool try_poll_mode(AioContext *ctx, bool blocking)

{

    if (blocking && ctx->poll_max_ns && ctx->poll_disable_cnt == 0) {

        /* See qemu_soonest_timeout() uint64_t hack */

        int64_t max_ns = MIN((uint64_t)aio_compute_timeout(ctx),

                             (uint64_t)ctx->poll_ns);

        if (max_ns) {

            poll_set_started(ctx, true);

            if (run_poll_handlers(ctx, max_ns)) {

                return true;

            }

        }

    }

    poll_set_started(ctx, false);

    /* Even if we don't run busy polling, try polling once in case it can make

     * progress and the caller will be able to avoid ppoll(2)/epoll_wait(2).

     */

    return run_poll_handlers_once(ctx);

}


static int qmp_tmp105_get_temperature(const char *id)

{

    QDict *response;

    int ret;

    response = qmp("{ 'execute': 'qom-get', 'arguments': { 'path': '%s', "

                   "'property': 'temperature' } }", id);

    g_assert(qdict_haskey(response, "return"));

    ret = qdict_get_int(response, "return");

    QDECREF(response);

    return ret;

}


static void decode_sys_interrupts(CPUTriCoreState *env, DisasContext *ctx)

{

    uint32_t op2;

    uint32_t r1;

    TCGLabel *l1;

    TCGv tmp;

    op2 = MASK_OP_SYS_OP2(ctx->opcode);

    r1  = MASK_OP_SYS_S1D(ctx->opcode);

    switch (op2) {

    case OPC2_32_SYS_DEBUG:

        /* raise EXCP_DEBUG */

        break;

    case OPC2_32_SYS_DISABLE:

        tcg_gen_andi_tl(cpu_ICR, cpu_ICR, ~MASK_ICR_IE);

        break;

    case OPC2_32_SYS_DSYNC:

        break;

    case OPC2_32_SYS_ENABLE:

        tcg_gen_ori_tl(cpu_ICR, cpu_ICR, MASK_ICR_IE);

        break;

    case OPC2_32_SYS_ISYNC:

        break;

    case OPC2_32_SYS_NOP:

        break;

    case OPC2_32_SYS_RET:

        gen_compute_branch(ctx, op2, 0, 0, 0, 0);

        break;

    case OPC2_32_SYS_FRET:

        gen_fret(ctx);

        break;

    case OPC2_32_SYS_RFE:

        gen_helper_rfe(cpu_env);

        tcg_gen_exit_tb(0);

        ctx->bstate = BS_BRANCH;

        break;

    case OPC2_32_SYS_RFM:

        if ((ctx->hflags & TRICORE_HFLAG_KUU) == TRICORE_HFLAG_SM) {

            tmp = tcg_temp_new();

            l1 = gen_new_label();

            tcg_gen_ld32u_tl(tmp, cpu_env, offsetof(CPUTriCoreState, DBGSR));

            tcg_gen_andi_tl(tmp, tmp, MASK_DBGSR_DE);

            tcg_gen_brcondi_tl(TCG_COND_NE, tmp, 1, l1);

            gen_helper_rfm(cpu_env);

            gen_set_label(l1);

            tcg_gen_exit_tb(0);

            ctx->bstate = BS_BRANCH;

            tcg_temp_free(tmp);

        } else {

            /* generate privilege trap */

        }

        break;

    case OPC2_32_SYS_RSLCX:

        gen_helper_rslcx(cpu_env);

        break;

    case OPC2_32_SYS_SVLCX:

        gen_helper_svlcx(cpu_env);

        break;

    case OPC2_32_SYS_RESTORE:

        if (tricore_feature(env, TRICORE_FEATURE_16)) {

            if ((ctx->hflags & TRICORE_HFLAG_KUU) == TRICORE_HFLAG_SM ||

                (ctx->hflags & TRICORE_HFLAG_KUU) == TRICORE_HFLAG_UM1) {

                tcg_gen_deposit_tl(cpu_ICR, cpu_ICR, cpu_gpr_d[r1], 8, 1);

            } /* else raise privilege trap */

        } /* else raise illegal opcode trap */

        break;

    case OPC2_32_SYS_TRAPSV:

        l1 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_GE, cpu_PSW_SV, 0, l1);

        generate_trap(ctx, TRAPC_ASSERT, TIN5_SOVF);

        gen_set_label(l1);

        break;

    case OPC2_32_SYS_TRAPV:

        l1 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_GE, cpu_PSW_V, 0, l1);

        generate_trap(ctx, TRAPC_ASSERT, TIN5_OVF);

        gen_set_label(l1);

        break;

    }

}


static void pci_hotplug(void)

{

    QVirtioPCIDevice *dev;

    QOSState *qs;

    const char *arch = qtest_get_arch();

    qs = pci_test_start();

    /* plug secondary disk */

    qpci_plug_device_test("virtio-blk-pci", "drv1", PCI_SLOT_HP,

                          "'drive': 'drive1'");

    dev = virtio_blk_pci_init(qs->pcibus, PCI_SLOT_HP);

    g_assert(dev);

    qvirtio_pci_device_disable(dev);

    g_free(dev);

    /* unplug secondary disk */

    if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) {

        qpci_unplug_acpi_device_test("drv1", PCI_SLOT_HP);

    }

    qtest_shutdown(qs);

}


static unsigned long iv_decode_frame(Indeo3DecodeContext *s,
                                     unsigned char *buf, int buf_size)
{
  unsigned int hdr_width, hdr_height,
    chroma_width, chroma_height;
  unsigned long fflags1, fflags2, fflags3, offs1, offs2, offs3, offs;
  unsigned char *hdr_pos, *buf_pos;
  buf_pos = buf;
  buf_pos += 18;
  fflags1 = le2me_16(*(uint16_t *)buf_pos);
  buf_pos += 2;
  fflags3 = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  fflags2 = *buf_pos++;
  buf_pos += 3;
  hdr_height = le2me_16(*(uint16_t *)buf_pos);
  buf_pos += 2;
  hdr_width = le2me_16(*(uint16_t *)buf_pos);
  buf_pos += 2;
  chroma_height = ((hdr_height >> 2) + 3) & 0x7ffc;
  chroma_width = ((hdr_width >> 2) + 3) & 0x7ffc;
  offs1 = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  offs2 = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  offs3 = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 8;
  hdr_pos = buf_pos;
  if(fflags3 == 0x80) return 4;
  if(fflags1 & 0x200) {
    s->cur_frame = s->iv_frame + 1;
    s->ref_frame = s->iv_frame;
  } else {
    s->cur_frame = s->iv_frame;
    s->ref_frame = s->iv_frame + 1;
  }
  buf_pos = buf + 16 + offs1;
  offs = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  iv_Decode_Chunk(s, s->cur_frame->Ybuf, s->ref_frame->Ybuf, hdr_width,
    hdr_height, buf_pos + offs * 2, fflags2, hdr_pos, buf_pos,
    min(hdr_width, 160));
  if (!(s->avctx->flags & CODEC_FLAG_GRAY))
  {
  buf_pos = buf + 16 + offs2;
  offs = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  iv_Decode_Chunk(s, s->cur_frame->Vbuf, s->ref_frame->Vbuf, chroma_width,
    chroma_height, buf_pos + offs * 2, fflags2, hdr_pos, buf_pos,
    min(chroma_width, 40));
  buf_pos = buf + 16 + offs3;
  offs = le2me_32(*(uint32_t *)buf_pos);
  buf_pos += 4;
  iv_Decode_Chunk(s, s->cur_frame->Ubuf, s->ref_frame->Ubuf, chroma_width,
    chroma_height, buf_pos + offs * 2, fflags2, hdr_pos, buf_pos,
    min(chroma_width, 40));
  }
  return 8;
}


int gen_intermediate_code_internal (CPUState *env, TranslationBlock *tb,

                                    int search_pc)

{

    DisasContext ctx, *ctxp = &ctx;

    opc_handler_t **table, *handler;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    int j, lj = -1;

    pc_start = tb->pc;

    gen_opc_ptr = gen_opc_buf;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    gen_opparam_ptr = gen_opparam_buf;

    nb_gen_labels = 0;

    ctx.nip = pc_start;

    ctx.tb = tb;

    ctx.exception = EXCP_NONE;

    ctx.spr_cb = env->spr_cb;

#if defined(CONFIG_USER_ONLY)

    ctx.mem_idx = msr_le;

#else

    ctx.supervisor = 1 - msr_pr;

    ctx.mem_idx = ((1 - msr_pr) << 1) | msr_le;

#endif

    ctx.fpu_enabled = msr_fp;

    ctx.singlestep_enabled = env->singlestep_enabled;

#if defined (DO_SINGLE_STEP) && 0

    /* Single step trace mode */

    msr_se = 1;

#endif

    /* Set env in case of segfault during code fetch */

    while (ctx.exception == EXCP_NONE && gen_opc_ptr < gen_opc_end) {

        if (unlikely(env->nb_breakpoints > 0)) {

            for (j = 0; j < env->nb_breakpoints; j++) {

                if (env->breakpoints[j] == ctx.nip) {

                    gen_op_update_nip(ctx.nip);

                    gen_op_debug();

                    break;

                }

            }

        }

        if (unlikely(search_pc)) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

                gen_opc_pc[lj] = ctx.nip;

                gen_opc_instr_start[lj] = 1;

            }

        }

#if defined PPC_DEBUG_DISAS

        if (loglevel & CPU_LOG_TB_IN_ASM) {

            fprintf(logfile, "----------------\n");

            fprintf(logfile, "nip=%08x super=%d ir=%d\n",

                    ctx.nip, 1 - msr_pr, msr_ir);

        }

#endif

        ctx.opcode = ldl_code(ctx.nip);

        if (msr_le) {

            ctx.opcode = ((ctx.opcode & 0xFF000000) >> 24) |

                ((ctx.opcode & 0x00FF0000) >> 8) |

                ((ctx.opcode & 0x0000FF00) << 8) |

                ((ctx.opcode & 0x000000FF) << 24);

        }

#if defined PPC_DEBUG_DISAS

        if (loglevel & CPU_LOG_TB_IN_ASM) {

            fprintf(logfile, "translate opcode %08x (%02x %02x %02x) (%s)\n",

                    ctx.opcode, opc1(ctx.opcode), opc2(ctx.opcode),

                    opc3(ctx.opcode), msr_le ? "little" : "big");

        }

#endif

        ctx.nip += 4;

        table = env->opcodes;

        handler = table[opc1(ctx.opcode)];

        if (is_indirect_opcode(handler)) {

            table = ind_table(handler);

            handler = table[opc2(ctx.opcode)];

            if (is_indirect_opcode(handler)) {

                table = ind_table(handler);

                handler = table[opc3(ctx.opcode)];

            }

        }

        /* Is opcode *REALLY* valid ? */

        if (unlikely(handler->handler == &gen_invalid)) {

            if (loglevel > 0) {

                fprintf(logfile, "invalid/unsupported opcode: "

                        "%02x - %02x - %02x (%08x) 0x%08x %d\n",

                        opc1(ctx.opcode), opc2(ctx.opcode),

                        opc3(ctx.opcode), ctx.opcode, ctx.nip - 4, msr_ir);

            } else {

                printf("invalid/unsupported opcode: "

                       "%02x - %02x - %02x (%08x) 0x%08x %d\n",

                       opc1(ctx.opcode), opc2(ctx.opcode),

                       opc3(ctx.opcode), ctx.opcode, ctx.nip - 4, msr_ir);

            }

        } else {

            if (unlikely((ctx.opcode & handler->inval) != 0)) {

                if (loglevel > 0) {

                    fprintf(logfile, "invalid bits: %08x for opcode: "

                            "%02x -%02x - %02x (0x%08x) (0x%08x)\n",

                            ctx.opcode & handler->inval, opc1(ctx.opcode),

                            opc2(ctx.opcode), opc3(ctx.opcode),

                            ctx.opcode, ctx.nip - 4);

                } else {

                    printf("invalid bits: %08x for opcode: "

                           "%02x -%02x - %02x (0x%08x) (0x%08x)\n",

                           ctx.opcode & handler->inval, opc1(ctx.opcode),

                           opc2(ctx.opcode), opc3(ctx.opcode),

                           ctx.opcode, ctx.nip - 4);

                }

                RET_INVAL(ctxp);

                break;

            }

        }

        (*(handler->handler))(&ctx);

#if defined(DO_PPC_STATISTICS)

        handler->count++;

#endif

        /* Check trace mode exceptions */

        if (unlikely((msr_be && ctx.exception == EXCP_BRANCH) ||

                     /* Check in single step trace mode

                      * we need to stop except if:

                      * - rfi, trap or syscall

                      * - first instruction of an exception handler

                      */

                     (msr_se && (ctx.nip < 0x100 ||

                                 ctx.nip > 0xF00 ||

                                 (ctx.nip & 0xFC) != 0x04) &&

                      ctx.exception != EXCP_SYSCALL &&

                      ctx.exception != EXCP_SYSCALL_USER &&

                      ctx.exception != EXCP_TRAP))) {

            RET_EXCP(ctxp, EXCP_TRACE, 0);

        }

        /* if we reach a page boundary or are single stepping, stop

         * generation

         */

        if (unlikely(((ctx.nip & (TARGET_PAGE_SIZE - 1)) == 0) ||

                     (env->singlestep_enabled))) {

            break;

        }

#if defined (DO_SINGLE_STEP)

        break;

#endif

    }

    if (ctx.exception == EXCP_NONE) {

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

    } else if (ctx.exception != EXCP_BRANCH) {

        gen_op_reset_T0();

        /* Generate the return instruction */

        gen_op_exit_tb();

    }

    *gen_opc_ptr = INDEX_op_end;

    if (unlikely(search_pc)) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

        tb->size = 0;

    } else {

        tb->size = ctx.nip - pc_start;

    }

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_CPU) {

        fprintf(logfile, "---------------- excp: %04x\n", ctx.exception);

        cpu_dump_state(env, logfile, fprintf, 0);

    }

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        int flags;

        flags = msr_le;

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

        target_disas(logfile, pc_start, ctx.nip - pc_start, flags);

        fprintf(logfile, "\n");

    }

    if (loglevel & CPU_LOG_TB_OP) {

        fprintf(logfile, "OP:\n");

        dump_ops(gen_opc_buf, gen_opparam_buf);

        fprintf(logfile, "\n");

    }

#endif

    return 0;

}


static void test_ide_drive_cd_0(void)

{

    char *argv[256];

    int argc, ide_idx;

    Backend i;

    argc = setup_common(argv, ARRAY_SIZE(argv));

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

        ide_idx = backend_empty - i;

        cur_ide[ide_idx] = &hd_chst[i][mbr_blank];

        argc = setup_ide(argc, argv, ARRAY_SIZE(argv),

                         ide_idx, NULL, i, mbr_blank, "");

    }

    qtest_start(g_strjoinv(" ", argv));

    test_cmos();

    qtest_end();

}


static int decode_vol_header(MpegEncContext *s, GetBitContext *gb){

    int width, height, vo_ver_id;

    /* vol header */

    skip_bits(gb, 1); /* random access */

    s->vo_type= get_bits(gb, 8);

    if (get_bits1(gb) != 0) { /* is_ol_id */

        vo_ver_id = get_bits(gb, 4); /* vo_ver_id */

        skip_bits(gb, 3); /* vo_priority */

    } else {

        vo_ver_id = 1;

    }

//printf("vo type:%d\n",s->vo_type);

    s->aspect_ratio_info= get_bits(gb, 4);

    if(s->aspect_ratio_info == FF_ASPECT_EXTENDED){

        s->aspected_width = get_bits(gb, 8); // par_width

        s->aspected_height = get_bits(gb, 8); // par_height

    }else{

        s->aspected_width = pixel_aspect[s->aspect_ratio_info][0];

        s->aspected_height= pixel_aspect[s->aspect_ratio_info][1];

    }

    if ((s->vol_control_parameters=get_bits1(gb))) { /* vol control parameter */

        int chroma_format= get_bits(gb, 2);

        if(chroma_format!=1){

            printf("illegal chroma format\n");

        }

        s->low_delay= get_bits1(gb);

        if(get_bits1(gb)){ /* vbv parameters */

            get_bits(gb, 15);	/* first_half_bitrate */

            skip_bits1(gb);	/* marker */

            get_bits(gb, 15);	/* latter_half_bitrate */

            skip_bits1(gb);	/* marker */

            get_bits(gb, 15);	/* first_half_vbv_buffer_size */

            skip_bits1(gb);	/* marker */

            get_bits(gb, 3);	/* latter_half_vbv_buffer_size */

            get_bits(gb, 11);	/* first_half_vbv_occupancy */

            skip_bits1(gb);	/* marker */

            get_bits(gb, 15);	/* latter_half_vbv_occupancy */

            skip_bits1(gb);	/* marker */

        }

    }else{

        // set low delay flag only once so the smart? low delay detection wont be overriden

        if(s->picture_number==0)

            s->low_delay=0;

    }

    s->shape = get_bits(gb, 2); /* vol shape */

    if(s->shape != RECT_SHAPE) printf("only rectangular vol supported\n");

    if(s->shape == GRAY_SHAPE && vo_ver_id != 1){

        printf("Gray shape not supported\n");

        skip_bits(gb, 4);  //video_object_layer_shape_extension

    }

    skip_bits1(gb);   /* marker */

    s->time_increment_resolution = get_bits(gb, 16);

    s->time_increment_bits = av_log2(s->time_increment_resolution - 1) + 1;

    if (s->time_increment_bits < 1)

        s->time_increment_bits = 1;

    skip_bits1(gb);   /* marker */

    if (get_bits1(gb) != 0) {   /* fixed_vop_rate  */

        skip_bits(gb, s->time_increment_bits);

    }

    if (s->shape != BIN_ONLY_SHAPE) {

        if (s->shape == RECT_SHAPE) {

            skip_bits1(gb);   /* marker */

            width = get_bits(gb, 13);

            skip_bits1(gb);   /* marker */

            height = get_bits(gb, 13);

            skip_bits1(gb);   /* marker */

            if(width && height){ /* they should be non zero but who knows ... */

                s->width = width;

                s->height = height;

//                printf("width/height: %d %d\n", width, height);

            }

        }

        s->progressive_sequence= get_bits1(gb)^1;

        if(!get_bits1(gb)) printf("OBMC not supported (very likely buggy encoder)\n");   /* OBMC Disable */

        if (vo_ver_id == 1) {

            s->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */

        } else {

            s->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */

        }

        if(s->vol_sprite_usage==STATIC_SPRITE) printf("Static Sprites not supported\n");

        if(s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE){

            if(s->vol_sprite_usage==STATIC_SPRITE){

                s->sprite_width = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_height= get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_left  = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

                s->sprite_top   = get_bits(gb, 13);

                skip_bits1(gb); /* marker */

            }

            s->num_sprite_warping_points= get_bits(gb, 6);

            s->sprite_warping_accuracy = get_bits(gb, 2);

            s->sprite_brightness_change= get_bits1(gb);

            if(s->vol_sprite_usage==STATIC_SPRITE)

                s->low_latency_sprite= get_bits1(gb);

        }

        // FIXME sadct disable bit if verid!=1 && shape not rect

        if (get_bits1(gb) == 1) {   /* not_8_bit */

            s->quant_precision = get_bits(gb, 4); /* quant_precision */

            if(get_bits(gb, 4)!=8) printf("N-bit not supported\n"); /* bits_per_pixel */

            if(s->quant_precision!=5) printf("quant precission %d\n", s->quant_precision);

        } else {

            s->quant_precision = 5;

        }

        // FIXME a bunch of grayscale shape things

        if((s->mpeg_quant=get_bits1(gb))){ /* vol_quant_type */

            int i, v;

            /* load default matrixes */

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

                int j= s->dsp.idct_permutation[i];

                v= ff_mpeg4_default_intra_matrix[i];

                s->intra_matrix[j]= v;

                s->chroma_intra_matrix[j]= v;

                v= ff_mpeg4_default_non_intra_matrix[i];

                s->inter_matrix[j]= v;

                s->chroma_inter_matrix[j]= v;

            }

            /* load custom intra matrix */

            if(get_bits1(gb)){

                int last=0;

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

                    int j;

                    v= get_bits(gb, 8);

                    if(v==0) break;

                    last= v;

                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->intra_matrix[j]= v;

                    s->chroma_intra_matrix[j]= v;

                }

                /* replicate last value */

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

		    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->intra_matrix[j]= v;

                    s->chroma_intra_matrix[j]= v;

                }

            }

            /* load custom non intra matrix */

            if(get_bits1(gb)){

                int last=0;

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

                    int j;

                    v= get_bits(gb, 8);

                    if(v==0) break;

                    last= v;

                    j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->inter_matrix[j]= v;

                    s->chroma_inter_matrix[j]= v;

                }

                /* replicate last value */

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

		    int j= s->dsp.idct_permutation[ ff_zigzag_direct[i] ];

                    s->inter_matrix[j]= last;

                    s->chroma_inter_matrix[j]= last;

                }

            }

            // FIXME a bunch of grayscale shape things

        }

        if(vo_ver_id != 1)

             s->quarter_sample= get_bits1(gb);

        else s->quarter_sample=0;

        if(!get_bits1(gb)) printf("Complexity estimation not supported\n");

        s->resync_marker= !get_bits1(gb); /* resync_marker_disabled */

        s->data_partitioning= get_bits1(gb);

        if(s->data_partitioning){

            s->rvlc= get_bits1(gb);

            if(s->rvlc){

                printf("reversible vlc not supported\n");

            }

        }

        if(vo_ver_id != 1) {

            s->new_pred= get_bits1(gb);

            if(s->new_pred){

                printf("new pred not supported\n");

                skip_bits(gb, 2); /* requested upstream message type */

                skip_bits1(gb); /* newpred segment type */

            }

            s->reduced_res_vop= get_bits1(gb);

            if(s->reduced_res_vop) printf("reduced resolution VOP not supported\n");

        }

        else{

            s->new_pred=0;

            s->reduced_res_vop= 0;

        }

        s->scalability= get_bits1(gb);

        if (s->scalability) {

            GetBitContext bak= *gb;

            int ref_layer_id;

            int ref_layer_sampling_dir;

            int h_sampling_factor_n;

            int h_sampling_factor_m;

            int v_sampling_factor_n;

            int v_sampling_factor_m;

            s->hierachy_type= get_bits1(gb);

            ref_layer_id= get_bits(gb, 4);

            ref_layer_sampling_dir= get_bits1(gb);

            h_sampling_factor_n= get_bits(gb, 5);

            h_sampling_factor_m= get_bits(gb, 5);

            v_sampling_factor_n= get_bits(gb, 5);

            v_sampling_factor_m= get_bits(gb, 5);

            s->enhancement_type= get_bits1(gb);

            if(   h_sampling_factor_n==0 || h_sampling_factor_m==0

               || v_sampling_factor_n==0 || v_sampling_factor_m==0){

//                fprintf(stderr, "illegal scalability header (VERY broken encoder), trying to workaround\n");

                s->scalability=0;

                *gb= bak;

            }else

                printf("scalability not supported\n");

            // bin shape stuff FIXME

        }

    }

    return 0;

}


void ff_init_me(MpegEncContext *s){

    MotionEstContext * const c= &s->me;

    c->avctx= s->avctx;

    ff_set_cmp(&s->dsp, s->dsp.me_pre_cmp, c->avctx->me_pre_cmp);

    ff_set_cmp(&s->dsp, s->dsp.me_cmp, c->avctx->me_cmp);

    ff_set_cmp(&s->dsp, s->dsp.me_sub_cmp, c->avctx->me_sub_cmp);

    ff_set_cmp(&s->dsp, s->dsp.mb_cmp, c->avctx->mb_cmp);

    c->flags    = get_flags(c, 0, c->avctx->me_cmp    &FF_CMP_CHROMA);

    c->sub_flags= get_flags(c, 0, c->avctx->me_sub_cmp&FF_CMP_CHROMA);

    c->mb_flags = get_flags(c, 0, c->avctx->mb_cmp    &FF_CMP_CHROMA);

/*FIXME s->no_rounding b_type*/

    if(s->flags&CODEC_FLAG_QPEL){

        c->sub_motion_search= qpel_motion_search;

        c->qpel_avg= s->dsp.avg_qpel_pixels_tab;

        if(s->no_rounding) c->qpel_put= s->dsp.put_no_rnd_qpel_pixels_tab;

        else               c->qpel_put= s->dsp.put_qpel_pixels_tab;

    }else{

        if(c->avctx->me_sub_cmp&FF_CMP_CHROMA)

            c->sub_motion_search= hpel_motion_search;

        else if(   c->avctx->me_sub_cmp == FF_CMP_SAD

                && c->avctx->    me_cmp == FF_CMP_SAD

                && c->avctx->    mb_cmp == FF_CMP_SAD)

            c->sub_motion_search= sad_hpel_motion_search; // 2050 vs. 2450 cycles

        else

            c->sub_motion_search= hpel_motion_search;

    }

    c->hpel_avg= s->dsp.avg_pixels_tab;

    if(s->no_rounding) c->hpel_put= s->dsp.put_no_rnd_pixels_tab;

    else               c->hpel_put= s->dsp.put_pixels_tab;

    if(s->linesize){

        c->stride  = s->linesize;

        c->uvstride= s->uvlinesize;

    }else{

        c->stride  = 16*s->mb_width + 32;

        c->uvstride=  8*s->mb_width + 16;

    }

    // 8x8 fullpel search would need a 4x4 chroma compare, which we dont have yet, and even if we had the motion estimation code doesnt expect it

    if((c->avctx->me_cmp&FF_CMP_CHROMA) && !s->dsp.me_cmp[2]){

        s->dsp.me_cmp[2]= zero_cmp;

    }

    if((c->avctx->me_sub_cmp&FF_CMP_CHROMA) && !s->dsp.me_sub_cmp[2]){

        s->dsp.me_sub_cmp[2]= zero_cmp;

    }

    c->hpel_put[2][0]= c->hpel_put[2][1]=

    c->hpel_put[2][2]= c->hpel_put[2][3]= zero_hpel;

    c->temp= c->scratchpad;

}


static void filter(MpegAudioContext *s, int ch, short *samples, int incr)

{

    short *p, *q;

    int sum, offset, i, j, norm, n;

    short tmp[64];

    int tmp1[32];

    int *out;

    //    print_pow1(samples, 1152);

    offset = s->samples_offset[ch];

    out = &s->sb_samples[ch][0][0][0];

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

        /* 32 samples at once */

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

            s->samples_buf[ch][offset + (31 - i)] = samples[0];

            samples += incr;

        }

        /* filter */

        p = s->samples_buf[ch] + offset;

        q = filter_bank;

        /* maxsum = 23169 */

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

            sum = p[0*64] * q[0*64];

            sum += p[1*64] * q[1*64];

            sum += p[2*64] * q[2*64];

            sum += p[3*64] * q[3*64];

            sum += p[4*64] * q[4*64];

            sum += p[5*64] * q[5*64];

            sum += p[6*64] * q[6*64];

            sum += p[7*64] * q[7*64];

            tmp[i] = sum >> 14;

            p++;

            q++;

        }

        tmp1[0] = tmp[16];

        for( i=1; i<=16; i++ ) tmp1[i] = tmp[i+16]+tmp[16-i];

        for( i=17; i<=31; i++ ) tmp1[i] = tmp[i+16]-tmp[80-i];

        /* integer IDCT 32 with normalization. XXX: There may be some

           overflow left */

        norm = 0;

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

            norm |= abs(tmp1[i]);

        }

        n = av_log2(norm) - 12;

        if (n > 0) {

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

                tmp1[i] >>= n;

        } else {

            n = 0;

        }

        idct32(out, tmp1, s->sblimit, n);

        /* advance of 32 samples */

        offset -= 32;

        out += 32;

        /* handle the wrap around */

        if (offset < 0) {

            memmove(s->samples_buf[ch] + SAMPLES_BUF_SIZE - (512 - 32),

                    s->samples_buf[ch], (512 - 32) * 2);

            offset = SAMPLES_BUF_SIZE - 512;

        }

    }

    s->samples_offset[ch] = offset;

    //    print_pow(s->sb_samples, 1152);

}


int kvm_arch_handle_exit(CPUState *cs, struct kvm_run *run)

{

    S390CPU *cpu = S390_CPU(cs);

    int ret = 0;

    switch (run->exit_reason) {

        case KVM_EXIT_S390_SIEIC:

            ret = handle_intercept(cpu);

            break;

        case KVM_EXIT_S390_RESET:

            qemu_system_reset_request();

            break;

        case KVM_EXIT_S390_TSCH:

            ret = handle_tsch(cpu);

            break;

        case KVM_EXIT_DEBUG:

            ret = kvm_arch_handle_debug_exit(cpu);

            break;

        default:

            fprintf(stderr, "Unknown KVM exit: %d\n", run->exit_reason);

            break;

    }

    if (ret == 0) {

        ret = EXCP_INTERRUPT;

    }

    return ret;

}


AddressSpace *pci_device_iommu_address_space(PCIDevice *dev)

{

    PCIBus *bus = PCI_BUS(dev->bus);

    PCIBus *iommu_bus = bus;

    while(iommu_bus && !iommu_bus->iommu_fn && iommu_bus->parent_dev) {

        iommu_bus = PCI_BUS(iommu_bus->parent_dev->bus);

    }

    if (iommu_bus && iommu_bus->iommu_fn) {

        return iommu_bus->iommu_fn(bus, iommu_bus->iommu_opaque, dev->devfn);

    }

    return &address_space_memory;

}


static inline void gen_op_eval_fbo(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_and_tl(dst, dst, cpu_tmp0);

    tcg_gen_xori_tl(dst, dst, 0x1);

}


static int dvbsub_decode(AVCodecContext *avctx,

                         void *data, int *data_size,

                         AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DVBSubContext *ctx = avctx->priv_data;

    AVSubtitle *sub = data;

    const uint8_t *p, *p_end;

    int segment_type;

    int page_id;

    int segment_length;

    int i;

    av_dlog(avctx, "DVB sub packet:\n");

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

        av_dlog(avctx, "%02x ", buf[i]);

        if (i % 16 == 15)

            av_dlog(avctx, "\n");

    }

    if (i % 16)

        av_dlog(avctx, "\n");

    if (buf_size <= 6 || *buf != 0x0f) {

        av_dlog(avctx, "incomplete or broken packet");

        return -1;

    }

    p = buf;

    p_end = buf + buf_size;

    while (p_end - p >= 6 && *p == 0x0f) {

        p += 1;

        segment_type = *p++;

        page_id = AV_RB16(p);

        p += 2;

        segment_length = AV_RB16(p);

        p += 2;

        if (p_end - p < segment_length) {

            av_dlog(avctx, "incomplete or broken packet");

            return -1;

        }

        if (page_id == ctx->composition_id || page_id == ctx->ancillary_id ||

            ctx->composition_id == -1 || ctx->ancillary_id == -1) {

            switch (segment_type) {

            case DVBSUB_PAGE_SEGMENT:

                dvbsub_parse_page_segment(avctx, p, segment_length);

                break;

            case DVBSUB_REGION_SEGMENT:

                dvbsub_parse_region_segment(avctx, p, segment_length);

                break;

            case DVBSUB_CLUT_SEGMENT:

                dvbsub_parse_clut_segment(avctx, p, segment_length);

                break;

            case DVBSUB_OBJECT_SEGMENT:

                dvbsub_parse_object_segment(avctx, p, segment_length);

                break;

            case DVBSUB_DISPLAYDEFINITION_SEGMENT:

                dvbsub_parse_display_definition_segment(avctx, p, segment_length);

                break;

            case DVBSUB_DISPLAY_SEGMENT:

                *data_size = dvbsub_display_end_segment(avctx, p, segment_length, sub);

                break;

            default:

                av_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",

                        segment_type, page_id, segment_length);

                break;

            }

        }

        p += segment_length;

    }

    return p - buf;

}


static void *mpc8544_load_device_tree(target_phys_addr_t addr,

                                     uint32_t ramsize,

                                     target_phys_addr_t initrd_base,

                                     target_phys_addr_t initrd_size,

                                     const char *kernel_cmdline)

{

    void *fdt = NULL;

#ifdef CONFIG_FDT

    uint32_t mem_reg_property[] = {0, ramsize};

    char *filename;

    int fdt_size;

    int ret;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);

    if (!filename) {

        goto out;

    }

    fdt = load_device_tree(filename, &fdt_size);

    qemu_free(filename);

    if (fdt == NULL) {

        goto out;

    }

    /* Manipulate device tree in memory. */

    ret = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,

                               sizeof(mem_reg_property));

    if (ret < 0)

        fprintf(stderr, "couldn't set /memory/reg\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                                    initrd_base);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                                    (initrd_base + initrd_size));

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",

                                      kernel_cmdline);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/bootargs\n");

    if (kvm_enabled()) {

        struct dirent *dirp;

        DIR *dp;

        char buf[128];

        if ((dp = opendir("/proc/device-tree/cpus/")) == NULL) {

            printf("Can't open directory /proc/device-tree/cpus/\n");

            goto out;

        }

        buf[0] = '\0';

        while ((dirp = readdir(dp)) != NULL) {

            if (strncmp(dirp->d_name, "PowerPC", 7) == 0) {

                snprintf(buf, 128, "/cpus/%s", dirp->d_name);

                break;

            }

        }

        closedir(dp);

        if (buf[0] == '\0') {

            printf("Unknow host!\n");

            goto out;

        }

        mpc8544_copy_soc_cell(fdt, buf, "clock-frequency");

        mpc8544_copy_soc_cell(fdt, buf, "timebase-frequency");

    }

    cpu_physical_memory_write (addr, (void *)fdt, fdt_size);

out:

#endif

    return fdt;

}


static int mov_read_trak(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    int ret;

    st = av_new_stream(c->fc, c->fc->nb_streams);

    if (!st) return AVERROR(ENOMEM);

    sc = av_mallocz(sizeof(MOVStreamContext));

    if (!sc) return AVERROR(ENOMEM);

    st->priv_data = sc;

    st->codec->codec_type = CODEC_TYPE_DATA;

    st->start_time = 0; /* XXX: check */

    if ((ret = mov_read_default(c, pb, atom)) < 0)

        return ret;

    /* sanity checks */

    if(sc->chunk_count && (!sc->stts_count || !sc->sample_to_chunk_sz ||

                           (!sc->sample_size && !sc->sample_count))){

        av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n",

               st->index);

        sc->sample_count = 0; //ignore track

        return 0;

    }

    if(!sc->time_rate)

        sc->time_rate=1;

    if(!sc->time_scale)

        sc->time_scale= c->time_scale;

    av_set_pts_info(st, 64, sc->time_rate, sc->time_scale);

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

        !st->codec->frame_size && sc->stts_count == 1)

        st->codec->frame_size = av_rescale(sc->time_rate, st->codec->sample_rate, sc->time_scale);

    if(st->duration != AV_NOPTS_VALUE){

        assert(st->duration % sc->time_rate == 0);

        st->duration /= sc->time_rate;

    }

    sc->ffindex = st->index;

    mov_build_index(c, st);

    if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) {

        if (url_fopen(&sc->pb, sc->drefs[sc->dref_id-1].path, URL_RDONLY) < 0)

            av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening file %s: %s\n",

                   st->index, sc->drefs[sc->dref_id-1].path, strerror(errno));

    } else

        sc->pb = c->fc->pb;

    switch (st->codec->codec_id) {

#ifdef CONFIG_H261_DECODER

    case CODEC_ID_H261:

#endif

#ifdef CONFIG_H263_DECODER

    case CODEC_ID_H263:

#endif

#ifdef CONFIG_MPEG4_DECODER

    case CODEC_ID_MPEG4:

#endif

        st->codec->width= 0; /* let decoder init width/height */

        st->codec->height= 0;

        break;

#ifdef CONFIG_VORBIS_DECODER

    case CODEC_ID_VORBIS:

#endif

        st->codec->sample_rate= 0; /* let decoder init parameters properly */

        break;

    }

    /* Do not need those anymore. */

    av_freep(&sc->chunk_offsets);

    av_freep(&sc->sample_to_chunk);

    av_freep(&sc->sample_sizes);

    av_freep(&sc->keyframes);

    av_freep(&sc->stts_data);

    return 0;

}


static av_cold int libschroedinger_encode_init(AVCodecContext *avctx)

{

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    SchroVideoFormatEnum preset;

    /* Initialize the libraries that libschroedinger depends on. */

    schro_init();

    /* Create an encoder object. */

    p_schro_params->encoder = schro_encoder_new();

    if (!p_schro_params->encoder) {

        av_log(avctx, AV_LOG_ERROR,

               "Unrecoverable Error: schro_encoder_new failed. ");

        return -1;

    }

    /* Initialize the format. */

    preset = ff_get_schro_video_format_preset(avctx);

    p_schro_params->format =

                    schro_encoder_get_video_format(p_schro_params->encoder);

    schro_video_format_set_std_video_format(p_schro_params->format, preset);

    p_schro_params->format->width  = avctx->width;

    p_schro_params->format->height = avctx->height;

    if (set_chroma_format(avctx) == -1)

        return -1;

    if (avctx->color_primaries == AVCOL_PRI_BT709) {

        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_HDTV;

    } else if (avctx->color_primaries == AVCOL_PRI_BT470BG) {

        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_625;

    } else if (avctx->color_primaries == AVCOL_PRI_SMPTE170M) {

        p_schro_params->format->colour_primaries = SCHRO_COLOUR_PRIMARY_SDTV_525;

    }

    if (avctx->colorspace == AVCOL_SPC_BT709) {

        p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_HDTV;

    } else if (avctx->colorspace == AVCOL_SPC_BT470BG) {

        p_schro_params->format->colour_matrix = SCHRO_COLOUR_MATRIX_SDTV;

    }

    if (avctx->color_trc == AVCOL_TRC_BT709) {

        p_schro_params->format->transfer_function = SCHRO_TRANSFER_CHAR_TV_GAMMA;

    }

    if (ff_get_schro_frame_format(p_schro_params->format->chroma_format,

                                  &p_schro_params->frame_format) == -1) {

        av_log(avctx, AV_LOG_ERROR,

               "This codec currently supports only planar YUV 4:2:0, 4:2:2"

               " and 4:4:4 formats.\n");

        return -1;

    }

    p_schro_params->format->frame_rate_numerator   = avctx->time_base.den;

    p_schro_params->format->frame_rate_denominator = avctx->time_base.num;

    p_schro_params->frame_size = avpicture_get_size(avctx->pix_fmt,

                                                    avctx->width,

                                                    avctx->height);

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    if (!avctx->gop_size) {

        schro_encoder_setting_set_double(p_schro_params->encoder,

                                         "gop_structure",

                                         SCHRO_ENCODER_GOP_INTRA_ONLY);

        if (avctx->coder_type == FF_CODER_TYPE_VLC)

            schro_encoder_setting_set_double(p_schro_params->encoder,

                                             "enable_noarith", 1);

    } else {

        schro_encoder_setting_set_double(p_schro_params->encoder,

                                         "au_distance", avctx->gop_size);

        avctx->has_b_frames = 1;

        p_schro_params->dts = -1;

    }

    /* FIXME - Need to handle SCHRO_ENCODER_RATE_CONTROL_LOW_DELAY. */

    if (avctx->flags & CODEC_FLAG_QSCALE) {

        if (!avctx->global_quality) {

            /* lossless coding */

            schro_encoder_setting_set_double(p_schro_params->encoder,

                                             "rate_control",

                                             SCHRO_ENCODER_RATE_CONTROL_LOSSLESS);

        } else {

            int quality;

            schro_encoder_setting_set_double(p_schro_params->encoder,

                                             "rate_control",

                                             SCHRO_ENCODER_RATE_CONTROL_CONSTANT_QUALITY);

            quality = avctx->global_quality / FF_QP2LAMBDA;

            if (quality > 10)

                quality = 10;

            schro_encoder_setting_set_double(p_schro_params->encoder,

                                             "quality", quality);

        }

    } else {

        schro_encoder_setting_set_double(p_schro_params->encoder,

                                         "rate_control",

                                         SCHRO_ENCODER_RATE_CONTROL_CONSTANT_BITRATE);

        schro_encoder_setting_set_double(p_schro_params->encoder,

                                         "bitrate", avctx->bit_rate);

    }

    if (avctx->flags & CODEC_FLAG_INTERLACED_ME)

        /* All material can be coded as interlaced or progressive

           irrespective of the type of source material. */

        schro_encoder_setting_set_double(p_schro_params->encoder,

                                         "interlaced_coding", 1);

    schro_encoder_setting_set_double(p_schro_params->encoder, "open_gop",

                                     !(avctx->flags & CODEC_FLAG_CLOSED_GOP));

    /* FIXME: Signal range hardcoded to 8-bit data until both libschroedinger

     * and libdirac support other bit-depth data. */

    schro_video_format_set_std_signal_range(p_schro_params->format,

                                            SCHRO_SIGNAL_RANGE_8BIT_VIDEO);

    /* Set the encoder format. */

    schro_encoder_set_video_format(p_schro_params->encoder,

                                   p_schro_params->format);

    /* Set the debug level. */

    schro_debug_set_level(avctx->debug);

    schro_encoder_start(p_schro_params->encoder);

    /* Initialize the encoded frame queue. */

    ff_schro_queue_init(&p_schro_params->enc_frame_queue);

    return 0;

}


static struct omap_mcbsp_s *omap_mcbsp_init(MemoryRegion *system_memory,

                                            target_phys_addr_t base,

                                            qemu_irq txirq, qemu_irq rxirq,

                                            qemu_irq *dma, omap_clk clk)

{

    struct omap_mcbsp_s *s = (struct omap_mcbsp_s *)

            g_malloc0(sizeof(struct omap_mcbsp_s));

    s->txirq = txirq;

    s->rxirq = rxirq;

    s->txdrq = dma[0];

    s->rxdrq = dma[1];

    s->sink_timer = qemu_new_timer_ns(vm_clock, omap_mcbsp_sink_tick, s);

    s->source_timer = qemu_new_timer_ns(vm_clock, omap_mcbsp_source_tick, s);

    omap_mcbsp_reset(s);

    memory_region_init_io(&s->iomem, &omap_mcbsp_ops, s, "omap-mcbsp", 0x800);

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

    return s;

}


static void rv34_pred_mv(RV34DecContext *r, int block_type, int subblock_no, int dmv_no)

{

    MpegEncContext *s = &r->s;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride;

    int A[2] = {0}, B[2], C[2];

    int i, j;

    int mx, my;

    int avail_index = avail_indexes[subblock_no];

    int c_off = part_sizes_w[block_type];

    mv_pos += (subblock_no & 1) + (subblock_no >> 1)*s->b8_stride;

    if(subblock_no == 3)

        c_off = -1;

    if(r->avail_cache[avail_index - 1]){

        A[0] = s->current_picture_ptr->f.motion_val[0][mv_pos-1][0];

        A[1] = s->current_picture_ptr->f.motion_val[0][mv_pos-1][1];

    }

    if(r->avail_cache[avail_index - 4]){

        B[0] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride][0];

        B[1] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride][1];

    }else{

        B[0] = A[0];

        B[1] = A[1];

    }

    if(!r->avail_cache[avail_index - 4 + c_off]){

        if(r->avail_cache[avail_index - 4] && (r->avail_cache[avail_index - 1] || r->rv30)){

            C[0] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride-1][0];

            C[1] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride-1][1];

        }else{

            C[0] = A[0];

            C[1] = A[1];

        }

    }else{

        C[0] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride+c_off][0];

        C[1] = s->current_picture_ptr->f.motion_val[0][mv_pos-s->b8_stride+c_off][1];

    }

    mx = mid_pred(A[0], B[0], C[0]);

    my = mid_pred(A[1], B[1], C[1]);

    mx += r->dmv[dmv_no][0];

    my += r->dmv[dmv_no][1];

    for(j = 0; j < part_sizes_h[block_type]; j++){

        for(i = 0; i < part_sizes_w[block_type]; i++){

            s->current_picture_ptr->f.motion_val[0][mv_pos + i + j*s->b8_stride][0] = mx;

            s->current_picture_ptr->f.motion_val[0][mv_pos + i + j*s->b8_stride][1] = my;

        }

    }

}