static void gen_compute_branch(DisasContext *ctx, uint32_t opc, int r1,

                               int r2 , int32_t constant , int32_t offset)

{

    TCGv temp, temp2;

    int n;

    switch (opc) {

/* SB-format jumps */

    case OPC1_16_SB_J:

    case OPC1_32_B_J:

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

    case OPC1_32_B_CALL:

    case OPC1_16_SB_CALL:

        gen_helper_1arg(call, ctx->next_pc);

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

    case OPC1_16_SB_JZ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], 0, offset);

        break;

    case OPC1_16_SB_JNZ:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], 0, offset);

        break;

/* SBC-format jumps */

    case OPC1_16_SBC_JEQ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[15], constant, offset);

        break;

    case OPC1_16_SBC_JNE:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[15], constant, offset);

        break;

/* SBRN-format jumps */

    case OPC1_16_SBRN_JZ_T:

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);

        gen_branch_condi(ctx, TCG_COND_EQ, temp, 0, offset);

        tcg_temp_free(temp);

        break;

    case OPC1_16_SBRN_JNZ_T:

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[15], 0x1u << constant);

        gen_branch_condi(ctx, TCG_COND_NE, temp, 0, offset);

        tcg_temp_free(temp);

        break;

/* SBR-format jumps */

    case OPC1_16_SBR_JEQ:

        gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[15],

                        offset);

        break;

    case OPC1_16_SBR_JNE:

        gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[15],

                        offset);

        break;

    case OPC1_16_SBR_JNZ:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JNZ_A:

        gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_a[r1], 0, offset);

        break;

    case OPC1_16_SBR_JGEZ:

        gen_branch_condi(ctx, TCG_COND_GE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JGTZ:

        gen_branch_condi(ctx, TCG_COND_GT, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JLEZ:

        gen_branch_condi(ctx, TCG_COND_LE, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JLTZ:

        gen_branch_condi(ctx, TCG_COND_LT, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JZ:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[r1], 0, offset);

        break;

    case OPC1_16_SBR_JZ_A:

        gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_a[r1], 0, offset);

        break;

    case OPC1_16_SBR_LOOP:

        gen_loop(ctx, r1, offset * 2 - 32);

        break;

/* SR-format jumps */

    case OPC1_16_SR_JI:

        tcg_gen_andi_tl(cpu_PC, cpu_gpr_a[r1], 0xfffffffe);

        tcg_gen_exit_tb(0);

        break;

    case OPC2_32_SYS_RET:

    case OPC2_16_SR_RET:

        gen_helper_ret(cpu_env);

        tcg_gen_exit_tb(0);

        break;

/* B-format */

    case OPC1_32_B_CALLA:

        gen_helper_1arg(call, ctx->next_pc);

        gen_goto_tb(ctx, 0, EA_B_ABSOLUT(offset));

        break;

    case OPC1_32_B_FCALL:

        gen_fcall_save_ctx(ctx);

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

    case OPC1_32_B_FCALLA:

        gen_fcall_save_ctx(ctx);

        gen_goto_tb(ctx, 0, EA_B_ABSOLUT(offset));

        break;

    case OPC1_32_B_JLA:

        tcg_gen_movi_tl(cpu_gpr_a[11], ctx->next_pc);

        /* fall through */

    case OPC1_32_B_JA:

        gen_goto_tb(ctx, 0, EA_B_ABSOLUT(offset));

        break;

    case OPC1_32_B_JL:

        tcg_gen_movi_tl(cpu_gpr_a[11], ctx->next_pc);

        gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        break;

/* BOL format */

    case OPCM_32_BRC_EQ_NEQ:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JEQ) {

            gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_d[r1], constant, offset);

         } else {

            gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_d[r1], constant, offset);

         }

         break;

    case OPCM_32_BRC_GE:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OP2_32_BRC_JGE) {

            gen_branch_condi(ctx, TCG_COND_GE, cpu_gpr_d[r1], constant, offset);

         } else {

            constant = MASK_OP_BRC_CONST4(ctx->opcode);

            gen_branch_condi(ctx, TCG_COND_GEU, cpu_gpr_d[r1], constant,

                             offset);

         }

         break;

    case OPCM_32_BRC_JLT:

         if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JLT) {

            gen_branch_condi(ctx, TCG_COND_LT, cpu_gpr_d[r1], constant, offset);

         } else {

            constant = MASK_OP_BRC_CONST4(ctx->opcode);

            gen_branch_condi(ctx, TCG_COND_LTU, cpu_gpr_d[r1], constant,

                             offset);

         }

         break;

    case OPCM_32_BRC_JNE:

        temp = tcg_temp_new();

        if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRC_JNED) {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* subi is unconditional */

            tcg_gen_subi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_condi(ctx, TCG_COND_NE, temp, constant, offset);

        } else {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* addi is unconditional */

            tcg_gen_addi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_condi(ctx, TCG_COND_NE, temp, constant, offset);

        }

        tcg_temp_free(temp);

        break;

/* BRN format */

    case OPCM_32_BRN_JTT:

        n = MASK_OP_BRN_N(ctx->opcode);

        temp = tcg_temp_new();

        tcg_gen_andi_tl(temp, cpu_gpr_d[r1], (1 << n));

        if (MASK_OP_BRN_OP2(ctx->opcode) == OPC2_32_BRN_JNZ_T) {

            gen_branch_condi(ctx, TCG_COND_NE, temp, 0, offset);

        } else {

            gen_branch_condi(ctx, TCG_COND_EQ, temp, 0, offset);

        }

        tcg_temp_free(temp);

        break;

/* BRR Format */

    case OPCM_32_BRR_EQ_NEQ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JEQ) {

            gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_ADDR_EQ_NEQ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JEQ_A) {

            gen_branch_cond(ctx, TCG_COND_EQ, cpu_gpr_a[r1], cpu_gpr_a[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_NE, cpu_gpr_a[r1], cpu_gpr_a[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_GE:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JGE) {

            gen_branch_cond(ctx, TCG_COND_GE, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_GEU, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_JLT:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JLT) {

            gen_branch_cond(ctx, TCG_COND_LT, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        } else {

            gen_branch_cond(ctx, TCG_COND_LTU, cpu_gpr_d[r1], cpu_gpr_d[r2],

                            offset);

        }

        break;

    case OPCM_32_BRR_LOOP:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_LOOP) {

            gen_loop(ctx, r2, offset * 2);

        } else {

            /* OPC2_32_BRR_LOOPU */

            gen_goto_tb(ctx, 0, ctx->pc + offset * 2);

        }

        break;

    case OPCM_32_BRR_JNE:

        temp = tcg_temp_new();

        temp2 = tcg_temp_new();

        if (MASK_OP_BRC_OP2(ctx->opcode) == OPC2_32_BRR_JNED) {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* also save r2, in case of r1 == r2, so r2 is not decremented */

            tcg_gen_mov_tl(temp2, cpu_gpr_d[r2]);

            /* subi is unconditional */

            tcg_gen_subi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_cond(ctx, TCG_COND_NE, temp, temp2, offset);

        } else {

            tcg_gen_mov_tl(temp, cpu_gpr_d[r1]);

            /* also save r2, in case of r1 == r2, so r2 is not decremented */

            tcg_gen_mov_tl(temp2, cpu_gpr_d[r2]);

            /* addi is unconditional */

            tcg_gen_addi_tl(cpu_gpr_d[r1], cpu_gpr_d[r1], 1);

            gen_branch_cond(ctx, TCG_COND_NE, temp, temp2, offset);

        }

        tcg_temp_free(temp);

        tcg_temp_free(temp2);

        break;

    case OPCM_32_BRR_JNZ:

        if (MASK_OP_BRR_OP2(ctx->opcode) == OPC2_32_BRR_JNZ_A) {

            gen_branch_condi(ctx, TCG_COND_NE, cpu_gpr_a[r1], 0, offset);

        } else {

            gen_branch_condi(ctx, TCG_COND_EQ, cpu_gpr_a[r1], 0, offset);

        }

        break;

    default:

        printf("Branch Error at %x\n", ctx->pc);

    }

    ctx->bstate = BS_BRANCH;

}


static inline void RENAME(bgr16ToY)(uint8_t *dst, uint8_t *src, int width)

{

	int i;

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

	{

		int d= ((uint16_t*)src)[i];

		int b= d&0x1F;

		int g= (d>>5)&0x3F;

		int r= (d>>11)&0x1F;

		dst[i]= ((2*RY*r + GY*g + 2*BY*b)>>(RGB2YUV_SHIFT-2)) + 16;

	}

}


static int film_read_packet(AVFormatContext *s,

                            AVPacket *pkt)

{

    FilmDemuxContext *film = s->priv_data;

    AVIOContext *pb = s->pb;

    film_sample *sample;

    int ret = 0;

    int i;

    int left, right;

    if (film->current_sample >= film->sample_count)

    sample = &film->sample_table[film->current_sample];

    /* position the stream (will probably be there anyway) */

    avio_seek(pb, sample->sample_offset, SEEK_SET);

    /* do a special song and dance when loading FILM Cinepak chunks */

    if ((sample->stream == film->video_stream_index) &&

        (film->video_type == CODEC_ID_CINEPAK)) {

        pkt->pos= avio_tell(pb);

        if (av_new_packet(pkt, sample->sample_size))

            return AVERROR(ENOMEM);

        avio_read(pb, pkt->data, sample->sample_size);

    } else if ((sample->stream == film->audio_stream_index) &&

        (film->audio_channels == 2) &&

        (film->audio_type != CODEC_ID_ADPCM_ADX)) {

        /* stereo PCM needs to be interleaved */

        if (av_new_packet(pkt, sample->sample_size))

            return AVERROR(ENOMEM);

        /* make sure the interleave buffer is large enough */

        if (sample->sample_size > film->stereo_buffer_size) {

            av_free(film->stereo_buffer);

            film->stereo_buffer_size = sample->sample_size;

            film->stereo_buffer = av_malloc(film->stereo_buffer_size);

            if (!film->stereo_buffer) {

                film->stereo_buffer_size = 0;

                return AVERROR(ENOMEM);

            }

        }

        pkt->pos= avio_tell(pb);

        ret = avio_read(pb, film->stereo_buffer, sample->sample_size);

        if (ret != sample->sample_size)

            ret = AVERROR(EIO);

        left = 0;

        right = sample->sample_size / 2;

        for (i = 0; i < sample->sample_size; ) {

            if (film->audio_bits == 8) {

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[right++];

            } else {

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[left++];

                pkt->data[i++] = film->stereo_buffer[right++];

                pkt->data[i++] = film->stereo_buffer[right++];

            }

        }

    } else {

        ret= av_get_packet(pb, pkt, sample->sample_size);

        if (ret != sample->sample_size)

            ret = AVERROR(EIO);

    }

    pkt->stream_index = sample->stream;

    pkt->pts = sample->pts;

    film->current_sample++;

    return ret;

}


static void tcg_out_qemu_st(TCGContext* s, TCGReg data_reg, TCGReg addr_reg,

                            TCGMemOpIdx oi)

{

    TCGMemOp opc = get_memop(oi);

#ifdef CONFIG_SOFTMMU

    unsigned mem_index = get_mmuidx(oi);

    tcg_insn_unit *label_ptr;

    TCGReg base_reg;

    base_reg = tcg_out_tlb_read(s, addr_reg, opc, mem_index, 0);

    label_ptr = s->code_ptr + 1;

    tcg_out_insn(s, RI, BRC, S390_CC_NE, 0);

    tcg_out_qemu_st_direct(s, opc, data_reg, base_reg, TCG_REG_R2, 0);

    add_qemu_ldst_label(s, 0, oi, data_reg, addr_reg, s->code_ptr, label_ptr);

#else

    TCGReg index_reg;

    tcg_target_long disp;

    tcg_prepare_user_ldst(s, &addr_reg, &index_reg, &disp);

    tcg_out_qemu_st_direct(s, opc, data_reg, addr_reg, index_reg, disp);

#endif

}


static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)

{

    int64_t sector_num, end;

    BlockDriverState *base = s->base;

    BlockDriverState *bs = s->source;

    BlockDriverState *target_bs = blk_bs(s->target);

    int ret, n;

    end = s->bdev_length / BDRV_SECTOR_SIZE;

    if (base == NULL && !bdrv_has_zero_init(target_bs)) {

        if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {

            bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, end);

            return 0;

        }

        s->initial_zeroing_ongoing = true;

        for (sector_num = 0; sector_num < end; ) {

            int nb_sectors = MIN(end - sector_num,

                QEMU_ALIGN_DOWN(INT_MAX, s->granularity) >> BDRV_SECTOR_BITS);

            mirror_throttle(s);

            if (block_job_is_cancelled(&s->common)) {

                s->initial_zeroing_ongoing = false;

                return 0;

            }

            if (s->in_flight >= MAX_IN_FLIGHT) {

                trace_mirror_yield(s, s->in_flight, s->buf_free_count, -1);

                mirror_wait_for_io(s);

                continue;

            }

            mirror_do_zero_or_discard(s, sector_num, nb_sectors, false);

            sector_num += nb_sectors;

        }

        mirror_wait_for_all_io(s);

        s->initial_zeroing_ongoing = false;

    }

    /* First part, loop on the sectors and initialize the dirty bitmap.  */

    for (sector_num = 0; sector_num < end; ) {

        /* Just to make sure we are not exceeding int limit. */

        int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,

                             end - sector_num);

        mirror_throttle(s);

        if (block_job_is_cancelled(&s->common)) {

            return 0;

        }

        ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);

        if (ret < 0) {

            return ret;

        }

        assert(n > 0);

        if (ret == 1) {

            bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);

        }

        sector_num += n;

    }

    return 0;

}


uint32_t do_arm_semihosting(CPUARMState *env)

{

    target_ulong args;

    char * s;

    int nr;

    uint32_t ret;

    uint32_t len;

#ifdef CONFIG_USER_ONLY

    TaskState *ts = env->opaque;

#else

    CPUARMState *ts = env;

#endif

    nr = env->regs[0];

    args = env->regs[1];

    switch (nr) {

    case TARGET_SYS_OPEN:

        if (!(s = lock_user_string(ARG(0))))

            /* FIXME - should this error code be -TARGET_EFAULT ? */

            return (uint32_t)-1;

        if (ARG(1) >= 12)

            return (uint32_t)-1;

        if (strcmp(s, ":tt") == 0) {

            if (ARG(1) < 4)

                return STDIN_FILENO;

            else

                return STDOUT_FILENO;

        }

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "open,%s,%x,1a4", ARG(0),

			   (int)ARG(2)+1, gdb_open_modeflags[ARG(1)]);

            return env->regs[0];

        } else {

            ret = set_swi_errno(ts, open(s, open_modeflags[ARG(1)], 0644));

        }

        unlock_user(s, ARG(0), 0);

        return ret;

    case TARGET_SYS_CLOSE:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "close,%x", ARG(0));

            return env->regs[0];

        } else {

            return set_swi_errno(ts, close(ARG(0)));

        }

    case TARGET_SYS_WRITEC:

        {

          char c;

          if (get_user_u8(c, args))

              /* FIXME - should this error code be -TARGET_EFAULT ? */

              return (uint32_t)-1;

          /* Write to debug console.  stderr is near enough.  */

          if (use_gdb_syscalls()) {

                gdb_do_syscall(arm_semi_cb, "write,2,%x,1", args);

                return env->regs[0];

          } else {

                return write(STDERR_FILENO, &c, 1);

          }

        }

    case TARGET_SYS_WRITE0:

        if (!(s = lock_user_string(args)))

            /* FIXME - should this error code be -TARGET_EFAULT ? */

            return (uint32_t)-1;

        len = strlen(s);

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "write,2,%x,%x\n", args, len);

            ret = env->regs[0];

        } else {

            ret = write(STDERR_FILENO, s, len);

        }

        unlock_user(s, args, 0);

        return ret;

    case TARGET_SYS_WRITE:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            arm_semi_syscall_len = len;

            gdb_do_syscall(arm_semi_cb, "write,%x,%x,%x", ARG(0), ARG(1), len);

            return env->regs[0];

        } else {

            if (!(s = lock_user(VERIFY_READ, ARG(1), len, 1)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret = set_swi_errno(ts, write(ARG(0), s, len));

            unlock_user(s, ARG(1), 0);

            if (ret == (uint32_t)-1)

                return -1;

            return len - ret;

        }

    case TARGET_SYS_READ:

        len = ARG(2);

        if (use_gdb_syscalls()) {

            arm_semi_syscall_len = len;

            gdb_do_syscall(arm_semi_cb, "read,%x,%x,%x", ARG(0), ARG(1), len);

            return env->regs[0];

        } else {

            if (!(s = lock_user(VERIFY_WRITE, ARG(1), len, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            do

              ret = set_swi_errno(ts, read(ARG(0), s, len));

            while (ret == -1 && errno == EINTR);

            unlock_user(s, ARG(1), len);

            if (ret == (uint32_t)-1)

                return -1;

            return len - ret;

        }

    case TARGET_SYS_READC:

       /* XXX: Read from debug console. Not implemented.  */

        return 0;

    case TARGET_SYS_ISTTY:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "isatty,%x", ARG(0));

            return env->regs[0];

        } else {

            return isatty(ARG(0));

        }

    case TARGET_SYS_SEEK:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "lseek,%x,%x,0", ARG(0), ARG(1));

            return env->regs[0];

        } else {

            ret = set_swi_errno(ts, lseek(ARG(0), ARG(1), SEEK_SET));

            if (ret == (uint32_t)-1)

              return -1;

            return 0;

        }

    case TARGET_SYS_FLEN:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_flen_cb, "fstat,%x,%x",

			   ARG(0), env->regs[13]-64);

            return env->regs[0];

        } else {

            struct stat buf;

            ret = set_swi_errno(ts, fstat(ARG(0), &buf));

            if (ret == (uint32_t)-1)

                return -1;

            return buf.st_size;

        }

    case TARGET_SYS_TMPNAM:

        /* XXX: Not implemented.  */

        return -1;

    case TARGET_SYS_REMOVE:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "unlink,%s", ARG(0), (int)ARG(1)+1);

            ret = env->regs[0];

        } else {

            if (!(s = lock_user_string(ARG(0))))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret =  set_swi_errno(ts, remove(s));

            unlock_user(s, ARG(0), 0);

        }

        return ret;

    case TARGET_SYS_RENAME:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "rename,%s,%s",

                           ARG(0), (int)ARG(1)+1, ARG(2), (int)ARG(3)+1);

            return env->regs[0];

        } else {

            char *s2;

            s = lock_user_string(ARG(0));

            s2 = lock_user_string(ARG(2));

            if (!s || !s2)

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                ret = (uint32_t)-1;

            else

                ret = set_swi_errno(ts, rename(s, s2));

            if (s2)

                unlock_user(s2, ARG(2), 0);

            if (s)

                unlock_user(s, ARG(0), 0);

            return ret;

        }

    case TARGET_SYS_CLOCK:

        return clock() / (CLOCKS_PER_SEC / 100);

    case TARGET_SYS_TIME:

        return set_swi_errno(ts, time(NULL));

    case TARGET_SYS_SYSTEM:

        if (use_gdb_syscalls()) {

            gdb_do_syscall(arm_semi_cb, "system,%s", ARG(0), (int)ARG(1)+1);

            return env->regs[0];

        } else {

            if (!(s = lock_user_string(ARG(0))))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ret = set_swi_errno(ts, system(s));

            unlock_user(s, ARG(0), 0);

            return ret;

        }

    case TARGET_SYS_ERRNO:

#ifdef CONFIG_USER_ONLY

        return ts->swi_errno;

#else

        return syscall_err;

#endif

    case TARGET_SYS_GET_CMDLINE:

        {

            /* Build a command-line from the original argv.

             *

             * The inputs are:

             *     * ARG(0), pointer to a buffer of at least the size

             *               specified in ARG(1).

             *     * ARG(1), size of the buffer pointed to by ARG(0) in

             *               bytes.

             *

             * The outputs are:

             *     * ARG(0), pointer to null-terminated string of the

             *               command line.

             *     * ARG(1), length of the string pointed to by ARG(0).

             */

            char *output_buffer;

            size_t input_size = ARG(1);

            size_t output_size;

            int status = 0;

            /* Compute the size of the output string.  */

#if !defined(CONFIG_USER_ONLY)

            output_size = strlen(ts->boot_info->kernel_filename)

                        + 1  /* Separating space.  */

                        + strlen(ts->boot_info->kernel_cmdline)

                        + 1; /* Terminating null byte.  */

#else

            unsigned int i;

            output_size = ts->info->arg_end - ts->info->arg_start;

            if (!output_size) {

                /* We special-case the "empty command line" case (argc==0).

                   Just provide the terminating 0. */

                output_size = 1;

            }

#endif

            if (output_size > input_size) {

                 /* Not enough space to store command-line arguments.  */

                return -1;

            }

            /* Adjust the command-line length.  */

            SET_ARG(1, output_size - 1);

            /* Lock the buffer on the ARM side.  */

            output_buffer = lock_user(VERIFY_WRITE, ARG(0), output_size, 0);

            if (!output_buffer) {

                return -1;

            }

            /* Copy the command-line arguments.  */

#if !defined(CONFIG_USER_ONLY)

            pstrcpy(output_buffer, output_size, ts->boot_info->kernel_filename);

            pstrcat(output_buffer, output_size, " ");

            pstrcat(output_buffer, output_size, ts->boot_info->kernel_cmdline);

#else

            if (output_size == 1) {

                /* Empty command-line.  */

                output_buffer[0] = '\0';

                goto out;

            }

            if (copy_from_user(output_buffer, ts->info->arg_start,

                               output_size)) {

                status = -1;

                goto out;

            }

            /* Separate arguments by white spaces.  */

            for (i = 0; i < output_size - 1; i++) {

                if (output_buffer[i] == 0) {

                    output_buffer[i] = ' ';

                }

            }

        out:

#endif

            /* Unlock the buffer on the ARM side.  */

            unlock_user(output_buffer, ARG(0), output_size);

            return status;

        }

    case TARGET_SYS_HEAPINFO:

        {

            uint32_t *ptr;

            uint32_t limit;

#ifdef CONFIG_USER_ONLY

            /* Some C libraries assume the heap immediately follows .bss, so

               allocate it using sbrk.  */

            if (!ts->heap_limit) {

                abi_ulong ret;

                ts->heap_base = do_brk(0);

                limit = ts->heap_base + ARM_ANGEL_HEAP_SIZE;

                /* Try a big heap, and reduce the size if that fails.  */

                for (;;) {

                    ret = do_brk(limit);

                    if (ret >= limit) {

                        break;

                    }

                    limit = (ts->heap_base >> 1) + (limit >> 1);

                }

                ts->heap_limit = limit;

            }

            if (!(ptr = lock_user(VERIFY_WRITE, ARG(0), 16, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            ptr[0] = tswap32(ts->heap_base);

            ptr[1] = tswap32(ts->heap_limit);

            ptr[2] = tswap32(ts->stack_base);

            ptr[3] = tswap32(0); /* Stack limit.  */

            unlock_user(ptr, ARG(0), 16);

#else

            limit = ram_size;

            if (!(ptr = lock_user(VERIFY_WRITE, ARG(0), 16, 0)))

                /* FIXME - should this error code be -TARGET_EFAULT ? */

                return (uint32_t)-1;

            /* TODO: Make this use the limit of the loaded application.  */

            ptr[0] = tswap32(limit / 2);

            ptr[1] = tswap32(limit);

            ptr[2] = tswap32(limit); /* Stack base */

            ptr[3] = tswap32(0); /* Stack limit.  */

            unlock_user(ptr, ARG(0), 16);

#endif

            return 0;

        }

    case TARGET_SYS_EXIT:

        gdb_exit(env, 0);

        exit(0);

    default:

        fprintf(stderr, "qemu: Unsupported SemiHosting SWI 0x%02x\n", nr);

        cpu_dump_state(env, stderr, fprintf, 0);

        abort();

    }

}


static void video_audio_display(VideoState *s)

{

    int i, i_start, x, y1, y, ys, delay, n, nb_display_channels;

    int ch, channels, h, h2, bgcolor, fgcolor;

    int16_t time_diff;

    int rdft_bits, nb_freq;

    for (rdft_bits = 1; (1 << rdft_bits) < 2 * s->height; rdft_bits++)

        ;

    nb_freq = 1 << (rdft_bits - 1);

    /* compute display index : center on currently output samples */

    channels = s->audio_tgt.channels;

    nb_display_channels = channels;

    if (!s->paused) {

        int data_used= s->show_mode == SHOW_MODE_WAVES ? s->width : (2*nb_freq);

        n = 2 * channels;

        delay = s->audio_write_buf_size;

        delay /= n;

        /* to be more precise, we take into account the time spent since

           the last buffer computation */

        if (audio_callback_time) {

            time_diff = av_gettime() - audio_callback_time;

            delay -= (time_diff * s->audio_tgt.freq) / 1000000;

        }

        delay += 2 * data_used;

        if (delay < data_used)

            delay = data_used;

        i_start= x = compute_mod(s->sample_array_index - delay * channels, SAMPLE_ARRAY_SIZE);

        if (s->show_mode == SHOW_MODE_WAVES) {

            h = INT_MIN;

            for (i = 0; i < 1000; i += channels) {

                int idx = (SAMPLE_ARRAY_SIZE + x - i) % SAMPLE_ARRAY_SIZE;

                int a = s->sample_array[idx];

                int b = s->sample_array[(idx + 4 * channels) % SAMPLE_ARRAY_SIZE];

                int c = s->sample_array[(idx + 5 * channels) % SAMPLE_ARRAY_SIZE];

                int d = s->sample_array[(idx + 9 * channels) % SAMPLE_ARRAY_SIZE];

                int score = a - d;

                if (h < score && (b ^ c) < 0) {

                    h = score;

                    i_start = idx;

                }

            }

        }

        s->last_i_start = i_start;

    } else {

        i_start = s->last_i_start;

    }

    bgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);

    if (s->show_mode == SHOW_MODE_WAVES) {

        fill_rectangle(screen,

                       s->xleft, s->ytop, s->width, s->height,

                       bgcolor, 0);

        fgcolor = SDL_MapRGB(screen->format, 0xff, 0xff, 0xff);

        /* total height for one channel */

        h = s->height / nb_display_channels;

        /* graph height / 2 */

        h2 = (h * 9) / 20;

        for (ch = 0; ch < nb_display_channels; ch++) {

            i = i_start + ch;

            y1 = s->ytop + ch * h + (h / 2); /* position of center line */

            for (x = 0; x < s->width; x++) {

                y = (s->sample_array[i] * h2) >> 15;

                if (y < 0) {

                    y = -y;

                    ys = y1 - y;

                } else {

                    ys = y1;

                }

                fill_rectangle(screen,

                               s->xleft + x, ys, 1, y,

                               fgcolor, 0);

                i += channels;

                if (i >= SAMPLE_ARRAY_SIZE)

                    i -= SAMPLE_ARRAY_SIZE;

            }

        }

        fgcolor = SDL_MapRGB(screen->format, 0x00, 0x00, 0xff);

        for (ch = 1; ch < nb_display_channels; ch++) {

            y = s->ytop + ch * h;

            fill_rectangle(screen,

                           s->xleft, y, s->width, 1,

                           fgcolor, 0);

        }

        SDL_UpdateRect(screen, s->xleft, s->ytop, s->width, s->height);

    } else {

        nb_display_channels= FFMIN(nb_display_channels, 2);

        if (rdft_bits != s->rdft_bits) {

            av_rdft_end(s->rdft);

            av_free(s->rdft_data);

            s->rdft = av_rdft_init(rdft_bits, DFT_R2C);

            s->rdft_bits = rdft_bits;

            s->rdft_data = av_malloc(4 * nb_freq * sizeof(*s->rdft_data));

        }

        {

            FFTSample *data[2];

            for (ch = 0; ch < nb_display_channels; ch++) {

                data[ch] = s->rdft_data + 2 * nb_freq * ch;

                i = i_start + ch;

                for (x = 0; x < 2 * nb_freq; x++) {

                    double w = (x-nb_freq) * (1.0 / nb_freq);

                    data[ch][x] = s->sample_array[i] * (1.0 - w * w);

                    i += channels;

                    if (i >= SAMPLE_ARRAY_SIZE)

                        i -= SAMPLE_ARRAY_SIZE;

                }

                av_rdft_calc(s->rdft, data[ch]);

            }

            // least efficient way to do this, we should of course directly access it but its more than fast enough

            for (y = 0; y < s->height; y++) {

                double w = 1 / sqrt(nb_freq);

                int a = sqrt(w * sqrt(data[0][2 * y + 0] * data[0][2 * y + 0] + data[0][2 * y + 1] * data[0][2 * y + 1]));

                int b = (nb_display_channels == 2 ) ? sqrt(w * sqrt(data[1][2 * y + 0] * data[1][2 * y + 0]

                       + data[1][2 * y + 1] * data[1][2 * y + 1])) : a;

                a = FFMIN(a, 255);

                b = FFMIN(b, 255);

                fgcolor = SDL_MapRGB(screen->format, a, b, (a + b) / 2);

                fill_rectangle(screen,

                            s->xpos, s->height-y, 1, 1,

                            fgcolor, 0);

            }

        }

        SDL_UpdateRect(screen, s->xpos, s->ytop, 1, s->height);

        if (!s->paused)

            s->xpos++;

        if (s->xpos >= s->width)

            s->xpos= s->xleft;

    }

}


static int dirac_unpack_prediction_parameters(DiracContext *s)

{

    static const uint8_t default_blen[] = { 4, 12, 16, 24 };

    static const uint8_t default_bsep[] = { 4,  8, 12, 16 };

    GetBitContext *gb = &s->gb;

    unsigned idx, ref;

    align_get_bits(gb);

    /* [DIRAC_STD] 11.2.2 Block parameters. block_parameters() */

    /* Luma and Chroma are equal. 11.2.3 */

    idx = svq3_get_ue_golomb(gb); /* [DIRAC_STD] index */

    if (idx > 4) {

        av_log(s->avctx, AV_LOG_ERROR, "Block prediction index too high\n");

        return -1;

    }

    if (idx == 0) {

        s->plane[0].xblen = svq3_get_ue_golomb(gb);

        s->plane[0].yblen = svq3_get_ue_golomb(gb);

        s->plane[0].xbsep = svq3_get_ue_golomb(gb);

        s->plane[0].ybsep = svq3_get_ue_golomb(gb);

    } else {

        /*[DIRAC_STD] preset_block_params(index). Table 11.1 */

        s->plane[0].xblen = default_blen[idx-1];

        s->plane[0].yblen = default_blen[idx-1];

        s->plane[0].xbsep = default_bsep[idx-1];

        s->plane[0].ybsep = default_bsep[idx-1];

    }

    /*[DIRAC_STD] 11.2.4 motion_data_dimensions()

      Calculated in function dirac_unpack_block_motion_data */

    if (s->plane[0].xbsep < s->plane[0].xblen/2 || s->plane[0].ybsep < s->plane[0].yblen/2) {

        av_log(s->avctx, AV_LOG_ERROR, "Block separation too small\n");

        return -1;

    }

    if (s->plane[0].xbsep > s->plane[0].xblen || s->plane[0].ybsep > s->plane[0].yblen) {

        av_log(s->avctx, AV_LOG_ERROR, "Block seperation greater than size\n");

        return -1;

    }

    if (FFMAX(s->plane[0].xblen, s->plane[0].yblen) > MAX_BLOCKSIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "Unsupported large block size\n");

        return -1;

    }

    /*[DIRAC_STD] 11.2.5 Motion vector precision. motion_vector_precision()

      Read motion vector precision */

    s->mv_precision = svq3_get_ue_golomb(gb);

    if (s->mv_precision > 3) {

        av_log(s->avctx, AV_LOG_ERROR, "MV precision finer than eighth-pel\n");

        return -1;

    }

    /*[DIRAC_STD] 11.2.6 Global motion. global_motion()

      Read the global motion compensation parameters */

    s->globalmc_flag = get_bits1(gb);

    if (s->globalmc_flag) {

        memset(s->globalmc, 0, sizeof(s->globalmc));

        /* [DIRAC_STD] pan_tilt(gparams) */

        for (ref = 0; ref < s->num_refs; ref++) {

            if (get_bits1(gb)) {

                s->globalmc[ref].pan_tilt[0] = dirac_get_se_golomb(gb);

                s->globalmc[ref].pan_tilt[1] = dirac_get_se_golomb(gb);

            }

            /* [DIRAC_STD] zoom_rotate_shear(gparams)

               zoom/rotation/shear parameters */

            if (get_bits1(gb)) {

                s->globalmc[ref].zrs_exp   = svq3_get_ue_golomb(gb);

                s->globalmc[ref].zrs[0][0] = dirac_get_se_golomb(gb);

                s->globalmc[ref].zrs[0][1] = dirac_get_se_golomb(gb);

                s->globalmc[ref].zrs[1][0] = dirac_get_se_golomb(gb);

                s->globalmc[ref].zrs[1][1] = dirac_get_se_golomb(gb);

            } else {

                s->globalmc[ref].zrs[0][0] = 1;

                s->globalmc[ref].zrs[1][1] = 1;

            }

            /* [DIRAC_STD] perspective(gparams) */

            if (get_bits1(gb)) {

                s->globalmc[ref].perspective_exp = svq3_get_ue_golomb(gb);

                s->globalmc[ref].perspective[0]  = dirac_get_se_golomb(gb);

                s->globalmc[ref].perspective[1]  = dirac_get_se_golomb(gb);

            }

        }

    }

    /*[DIRAC_STD] 11.2.7 Picture prediction mode. prediction_mode()

      Picture prediction mode, not currently used. */

    if (svq3_get_ue_golomb(gb)) {

        av_log(s->avctx, AV_LOG_ERROR, "Unknown picture prediction mode\n");

        return -1;

    }

    /* [DIRAC_STD] 11.2.8 Reference picture weight. reference_picture_weights()

       just data read, weight calculation will be done later on. */

    s->weight_log2denom = 1;

    s->weight[0]        = 1;

    s->weight[1]        = 1;

    if (get_bits1(gb)) {

        s->weight_log2denom = svq3_get_ue_golomb(gb);

        s->weight[0] = dirac_get_se_golomb(gb);

        if (s->num_refs == 2)

            s->weight[1] = dirac_get_se_golomb(gb);

    }

    return 0;

}


static int check_timecode(void *log_ctx, AVTimecode *tc)

{

    if (tc->fps <= 0) {

        av_log(log_ctx, AV_LOG_ERROR, "Timecode frame rate must be specified\n");

        return AVERROR(EINVAL);

    }

    if ((tc->flags & AV_TIMECODE_FLAG_DROPFRAME) && tc->fps != 30 && tc->fps != 60) {

        av_log(log_ctx, AV_LOG_ERROR, "Drop frame is only allowed with 30000/1001 or 60000/1001 FPS\n");

        return AVERROR(EINVAL);

    }

    if (check_fps(tc->fps) < 0) {

        av_log(log_ctx, AV_LOG_WARNING, "Using non-standard frame rate %d/%d\n",

               tc->rate.num, tc->rate.den);

    }

    return 0;

}


static void RENAME(yuv2rgb555_1)(SwsContext *c, const int16_t *buf0,

                                 const int16_t *ubuf[2], const int16_t *bguf[2],

                                 const int16_t *abuf0, uint8_t *dest,

                                 int dstW, int uvalpha, int y)

{

    const int16_t *ubuf0 = ubuf[0], *ubuf1 = ubuf[1];

    const int16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB15(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    } else {

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1b(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB15(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    }

}


static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDisplay *display,

                                          const uint8_t *buf, int buf_size, int top_bottom, int non_mod)

{

    DVBSubContext *ctx = avctx->priv_data;

    DVBSubRegion *region = get_region(ctx, display->region_id);

    const uint8_t *buf_end = buf + buf_size;

    uint8_t *pbuf;

    int x_pos, y_pos;

    int i;

    uint8_t map2to4[] = { 0x0,  0x7,  0x8,  0xf};

    uint8_t map2to8[] = {0x00, 0x77, 0x88, 0xff};

    uint8_t map4to8[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,

                         0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    uint8_t *map_table;

    av_dlog(avctx, "DVB pixel block size %d, %s field:\n", buf_size,

            top_bottom ? "bottom" : "top");

#ifdef DEBUG_PACKET_CONTENTS

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

        if (i % 16 == 0)

            av_log(avctx, AV_LOG_INFO, "0x%08p: ", buf+i);

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

        if (i % 16 == 15)

            av_log(avctx, AV_LOG_INFO, "\n");

    }

    if (i % 16)

        av_log(avctx, AV_LOG_INFO, "\n");

#endif

    if (region == 0)

        return;

    pbuf = region->pbuf;

    x_pos = display->x_pos;

    y_pos = display->y_pos;

    if ((y_pos & 1) != top_bottom)

        y_pos++;

    while (buf < buf_end) {

        if (x_pos > region->width || y_pos > region->height) {

            av_log(avctx, AV_LOG_ERROR, "Invalid object location!\n");

            return;

        }

        switch (*buf++) {

        case 0x10:

            if (region->depth == 8)

                map_table = map2to8;

            else if (region->depth == 4)

                map_table = map2to4;

            else

                map_table = NULL;

            x_pos += dvbsub_read_2bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_size,

                                                non_mod, map_table);

            break;

        case 0x11:

            if (region->depth < 4) {

                av_log(avctx, AV_LOG_ERROR, "4-bit pixel string in %d-bit region!\n", region->depth);

                return;

            }

            if (region->depth == 8)

                map_table = map4to8;

            else

                map_table = NULL;

            x_pos += dvbsub_read_4bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_size,

                                                non_mod, map_table);

            break;

        case 0x12:

            if (region->depth < 8) {

                av_log(avctx, AV_LOG_ERROR, "8-bit pixel string in %d-bit region!\n", region->depth);

                return;

            }

            x_pos += dvbsub_read_8bit_string(pbuf + (y_pos * region->width) + x_pos,

                                                region->width - x_pos, &buf, buf_size,

                                                non_mod, NULL);

            break;

        case 0x20:

            map2to4[0] = (*buf) >> 4;

            map2to4[1] = (*buf++) & 0xf;

            map2to4[2] = (*buf) >> 4;

            map2to4[3] = (*buf++) & 0xf;

            break;

        case 0x21:

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

                map2to8[i] = *buf++;

            break;

        case 0x22:

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

                map4to8[i] = *buf++;

            break;

        case 0xf0:

            x_pos = display->x_pos;

            y_pos += 2;

            break;

        default:

            av_log(avctx, AV_LOG_INFO, "Unknown/unsupported pixel block 0x%x\n", *(buf-1));

        }

    }

}


static inline void gen_op_sdivx(TCGv dst, TCGv src1, TCGv src2)

{

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    tcg_gen_mov_tl(cpu_cc_src, src1);

    tcg_gen_mov_tl(cpu_cc_src2, src2);

    gen_trap_ifdivzero_tl(cpu_cc_src2);

    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_cc_src, INT64_MIN, l1);

    tcg_gen_brcondi_tl(TCG_COND_NE, cpu_cc_src2, -1, l1);

    tcg_gen_movi_i64(dst, INT64_MIN);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_div_i64(dst, cpu_cc_src, cpu_cc_src2);

    gen_set_label(l2);

}


static void iterative_me(SnowContext *s){

    int pass, mb_x, mb_y;

    const int b_width = s->b_width  << s->block_max_depth;

    const int b_height= s->b_height << s->block_max_depth;

    const int b_stride= b_width;

    int color[3];

    for(pass=0; pass<50; pass++){

        int change= 0;

        for(mb_y= 0; mb_y<b_height; mb_y++){

            for(mb_x= 0; mb_x<b_width; mb_x++){

                int dia_change, i, j;

                int best_rd= INT_MAX;

                BlockNode backup;

                const int index= mb_x + mb_y * b_stride;

                BlockNode *block= &s->block[index];

                BlockNode *tb =                 mb_y          ? &s->block[index-b_stride  ] : &null_block;

                BlockNode *lb = mb_x                          ? &s->block[index         -1] : &null_block;

                BlockNode *rb = mb_x<b_width                  ? &s->block[index         +1] : &null_block;

                BlockNode *bb =                 mb_y<b_height ? &s->block[index+b_stride  ] : &null_block;

                BlockNode *tlb= mb_x         && mb_y          ? &s->block[index-b_stride-1] : &null_block;

                BlockNode *trb= mb_x<b_width && mb_y          ? &s->block[index-b_stride+1] : &null_block;

                BlockNode *blb= mb_x         && mb_y<b_height ? &s->block[index+b_stride-1] : &null_block;

                BlockNode *brb= mb_x<b_width && mb_y<b_height ? &s->block[index+b_stride+1] : &null_block;

                if(pass && (block->type & BLOCK_OPT))

                    continue;

                block->type |= BLOCK_OPT;

                backup= *block;

                if(!s->me_cache_generation)

                    memset(s->me_cache, 0, sizeof(s->me_cache));

                s->me_cache_generation += 1<<22;

                // get previous score (cant be cached due to OBMC)

                check_block(s, mb_x, mb_y, (int[2]){block->mx, block->my}, 0, &best_rd);

                check_block(s, mb_x, mb_y, (int[2]){0, 0}, 0, &best_rd);

                check_block(s, mb_x, mb_y, (int[2]){tb->mx, tb->my}, 0, &best_rd);

                check_block(s, mb_x, mb_y, (int[2]){lb->mx, lb->my}, 0, &best_rd);

                check_block(s, mb_x, mb_y, (int[2]){rb->mx, rb->my}, 0, &best_rd);

                check_block(s, mb_x, mb_y, (int[2]){bb->mx, bb->my}, 0, &best_rd);

                /* fullpel ME */

                //FIXME avoid subpel interpol / round to nearest integer

                do{

                    dia_change=0;

                    for(i=0; i<FFMAX(s->avctx->dia_size, 1); i++){

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

                            dia_change |= check_block(s, mb_x, mb_y, (int[2]){block->mx+4*(i-j), block->my+(4*j)}, 0, &best_rd);

                            dia_change |= check_block(s, mb_x, mb_y, (int[2]){block->mx-4*(i-j), block->my-(4*j)}, 0, &best_rd);

                            dia_change |= check_block(s, mb_x, mb_y, (int[2]){block->mx+4*(i-j), block->my-(4*j)}, 0, &best_rd);

                            dia_change |= check_block(s, mb_x, mb_y, (int[2]){block->mx-4*(i-j), block->my+(4*j)}, 0, &best_rd);

                        }

                    }

                }while(dia_change);

                /* subpel ME */

                do{

                    static const int square[8][2]= {{+1, 0},{-1, 0},{ 0,+1},{ 0,-1},{+1,+1},{-1,-1},{+1,-1},{-1,+1},};

                    dia_change=0;

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

                        dia_change |= check_block(s, mb_x, mb_y, (int[2]){block->mx+square[i][0], block->my+square[i][1]}, 0, &best_rd);

                }while(dia_change);

                //FIXME or try the standard 2 pass qpel or similar

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

                    color[i]= get_dc(s, mb_x, mb_y, i);

                }

                check_block(s, mb_x, mb_y, color, 1, &best_rd);

                //FIXME RD style color selection

                if(!same_block(block, &backup)){

                    if(tb != &null_block) tb ->type &= ~BLOCK_OPT;

                    if(lb != &null_block) lb ->type &= ~BLOCK_OPT;

                    if(rb != &null_block) rb ->type &= ~BLOCK_OPT;

                    if(bb != &null_block) bb ->type &= ~BLOCK_OPT;

                    if(tlb!= &null_block) tlb->type &= ~BLOCK_OPT;

                    if(trb!= &null_block) trb->type &= ~BLOCK_OPT;

                    if(blb!= &null_block) blb->type &= ~BLOCK_OPT;

                    if(brb!= &null_block) brb->type &= ~BLOCK_OPT;

                    change ++;

                }

            }

        }

        av_log(NULL, AV_LOG_ERROR, "pass:%d changed:%d\n", pass, change);

        if(!change)

            break;

    }

}


static void coroutine_fn v9fs_xattrcreate(void *opaque)

{

    int flags;

    int32_t fid;

    int64_t size;

    ssize_t err = 0;

    V9fsString name;

    size_t offset = 7;

    V9fsFidState *file_fidp;

    V9fsFidState *xattr_fidp;

    V9fsPDU *pdu = opaque;

    v9fs_string_init(&name);

    err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);

    if (err < 0) {

        goto out_nofid;

    }

    trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);

    file_fidp = get_fid(pdu, fid);

    if (file_fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* Make the file fid point to xattr */

    xattr_fidp = file_fidp;

    xattr_fidp->fid_type = P9_FID_XATTR;

    xattr_fidp->fs.xattr.copied_len = 0;

    xattr_fidp->fs.xattr.len = size;

    xattr_fidp->fs.xattr.flags = flags;

    v9fs_string_init(&xattr_fidp->fs.xattr.name);

    v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);

    xattr_fidp->fs.xattr.value = g_malloc(size);

    err = offset;

    put_fid(pdu, file_fidp);

out_nofid:

    pdu_complete(pdu, err);

    v9fs_string_free(&name);

}


static int matroska_parse_block(MatroskaDemuxContext *matroska, uint8_t *data,

                                int size, int64_t pos, uint64_t cluster_time,

                                uint64_t block_duration, int is_keyframe,

                                uint8_t *additional, uint64_t additional_id, int additional_size,

                                int64_t cluster_pos, int64_t discard_padding)

{

    uint64_t timecode = AV_NOPTS_VALUE;

    MatroskaTrack *track;

    int res = 0;

    AVStream *st;

    int16_t block_time;

    uint32_t *lace_size = NULL;

    int n, flags, laces = 0;

    uint64_t num;

    int trust_default_duration = 1;

    if ((n = matroska_ebmlnum_uint(matroska, data, size, &num)) < 0) {

        av_log(matroska->ctx, AV_LOG_ERROR, "EBML block data error\n");

        return n;

    }

    data += n;

    size -= n;

    track = matroska_find_track_by_num(matroska, num);

    if (!track || !track->stream) {

        av_log(matroska->ctx, AV_LOG_INFO,

               "Invalid stream %"PRIu64" or size %u\n", num, size);

        return AVERROR_INVALIDDATA;

    } else if (size <= 3)

        return 0;

    st = track->stream;

    if (st->discard >= AVDISCARD_ALL)

        return res;

    av_assert1(block_duration != AV_NOPTS_VALUE);

    block_time = sign_extend(AV_RB16(data), 16);

    data      += 2;

    flags      = *data++;

    size      -= 3;

    if (is_keyframe == -1)

        is_keyframe = flags & 0x80 ? AV_PKT_FLAG_KEY : 0;

    if (cluster_time != (uint64_t) -1 &&

        (block_time >= 0 || cluster_time >= -block_time)) {

        timecode = cluster_time + block_time - track->codec_delay_in_track_tb;

        if (track->type == MATROSKA_TRACK_TYPE_SUBTITLE &&

            timecode < track->end_timecode)

            is_keyframe = 0;  /* overlapping subtitles are not key frame */

        if (is_keyframe)

            av_add_index_entry(st, cluster_pos, timecode, 0, 0,

                               AVINDEX_KEYFRAME);

    }

    if (matroska->skip_to_keyframe &&

        track->type != MATROSKA_TRACK_TYPE_SUBTITLE) {

        if (timecode < matroska->skip_to_timecode)

            return res;

        if (is_keyframe)

            matroska->skip_to_keyframe = 0;

        else if (!st->skip_to_keyframe) {

            av_log(matroska->ctx, AV_LOG_ERROR, "File is broken, keyframes not correctly marked!\n");

            matroska->skip_to_keyframe = 0;

        }

    }

    res = matroska_parse_laces(matroska, &data, &size, (flags & 0x06) >> 1,

                               &lace_size, &laces);

    if (res)

        goto end;

    if (track->audio.samplerate == 8000) {

        // If this is needed for more codecs, then add them here

        if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {

            if (track->audio.samplerate != st->codecpar->sample_rate || !st->codecpar->frame_size)

                trust_default_duration = 0;

        }

    }

    if (!block_duration && trust_default_duration)

        block_duration = track->default_duration * laces / matroska->time_scale;

    if (cluster_time != (uint64_t)-1 && (block_time >= 0 || cluster_time >= -block_time))

        track->end_timecode =

            FFMAX(track->end_timecode, timecode + block_duration);

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

        int64_t lace_duration = block_duration*(n+1) / laces - block_duration*n / laces;

        if (lace_size[n] > size) {

            av_log(matroska->ctx, AV_LOG_ERROR, "Invalid packet size\n");

            break;

        }

        if ((st->codecpar->codec_id == AV_CODEC_ID_RA_288 ||

             st->codecpar->codec_id == AV_CODEC_ID_COOK   ||

             st->codecpar->codec_id == AV_CODEC_ID_SIPR   ||

             st->codecpar->codec_id == AV_CODEC_ID_ATRAC3) &&

            st->codecpar->block_align && track->audio.sub_packet_size) {

            res = matroska_parse_rm_audio(matroska, track, st, data,

                                          lace_size[n],

                                          timecode, pos);

            if (res)

                goto end;

        } else if (st->codecpar->codec_id == AV_CODEC_ID_WEBVTT) {

            res = matroska_parse_webvtt(matroska, track, st,

                                        data, lace_size[n],

                                        timecode, lace_duration,

                                        pos);

            if (res)

                goto end;

        } else {

            res = matroska_parse_frame(matroska, track, st, data, lace_size[n],

                                       timecode, lace_duration, pos,

                                       !n ? is_keyframe : 0,

                                       additional, additional_id, additional_size,

                                       discard_padding);

            if (res)

                goto end;

        }

        if (timecode != AV_NOPTS_VALUE)

            timecode = lace_duration ? timecode + lace_duration : AV_NOPTS_VALUE;

        data += lace_size[n];

        size -= lace_size[n];

    }

end:

    av_free(lace_size);

    return res;

}


void cpu_x86_dump_state(CPUX86State *env, FILE *f, int flags)

{

    int eflags, i;

    char cc_op_name[32];

    static const char *seg_name[6] = { "ES", "CS", "SS", "DS", "FS", "GS" };

    eflags = env->eflags;

    fprintf(f, "EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n"

            "ESI=%08x EDI=%08x EBP=%08x ESP=%08x\n"

            "EIP=%08x EFL=%08x [%c%c%c%c%c%c%c]    CPL=%d II=%d A20=%d\n",

            env->regs[R_EAX], env->regs[R_EBX], env->regs[R_ECX], env->regs[R_EDX],

            env->regs[R_ESI], env->regs[R_EDI], env->regs[R_EBP], env->regs[R_ESP],

            env->eip, eflags,

            eflags & DF_MASK ? 'D' : '-',

            eflags & CC_O ? 'O' : '-',

            eflags & CC_S ? 'S' : '-',

            eflags & CC_Z ? 'Z' : '-',

            eflags & CC_A ? 'A' : '-',

            eflags & CC_P ? 'P' : '-',

            eflags & CC_C ? 'C' : '-',

            env->hflags & HF_CPL_MASK,

            (env->hflags >> HF_INHIBIT_IRQ_SHIFT) & 1,

            (env->a20_mask >> 20) & 1);

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

        SegmentCache *sc = &env->segs[i];

        fprintf(f, "%s =%04x %08x %08x %08x\n",

                seg_name[i],

                sc->selector,

                (int)sc->base,

                sc->limit,

                sc->flags);

    }

    fprintf(f, "LDT=%04x %08x %08x %08x\n",

            env->ldt.selector,

            (int)env->ldt.base,

            env->ldt.limit,

            env->ldt.flags);

    fprintf(f, "TR =%04x %08x %08x %08x\n",

            env->tr.selector,

            (int)env->tr.base,

            env->tr.limit,

            env->tr.flags);

    fprintf(f, "GDT=     %08x %08x\n",

            (int)env->gdt.base, env->gdt.limit);

    fprintf(f, "IDT=     %08x %08x\n",

            (int)env->idt.base, env->idt.limit);

    fprintf(f, "CR0=%08x CR2=%08x CR3=%08x CR4=%08x\n",

            env->cr[0], env->cr[2], env->cr[3], env->cr[4]);

    if (flags & X86_DUMP_CCOP) {

        if ((unsigned)env->cc_op < CC_OP_NB)

            strcpy(cc_op_name, cc_op_str[env->cc_op]);

        else

            snprintf(cc_op_name, sizeof(cc_op_name), "[%d]", env->cc_op);

        fprintf(f, "CCS=%08x CCD=%08x CCO=%-8s\n",

                env->cc_src, env->cc_dst, cc_op_name);

    }

    if (flags & X86_DUMP_FPU) {

        fprintf(f, "ST0=%f ST1=%f ST2=%f ST3=%f\n",

                (double)env->fpregs[0],

                (double)env->fpregs[1],

                (double)env->fpregs[2],

                (double)env->fpregs[3]);

        fprintf(f, "ST4=%f ST5=%f ST6=%f ST7=%f\n",

                (double)env->fpregs[4],

                (double)env->fpregs[5],

                (double)env->fpregs[7],

                (double)env->fpregs[8]);

    }

}


static void memory_region_read_accessor(MemoryRegion *mr,

                                        hwaddr addr,

                                        uint64_t *value,

                                        unsigned size,

                                        unsigned shift,

                                        uint64_t mask)

{

    uint64_t tmp;

    if (mr->flush_coalesced_mmio) {

        qemu_flush_coalesced_mmio_buffer();

    }

    tmp = mr->ops->read(mr->opaque, addr, size);

    trace_memory_region_ops_read(mr, addr, tmp, size);

    *value |= (tmp & mask) << shift;

}


static void dec_load(DisasContext *dc)

{

    TCGv t, *addr;

    unsigned int size;

    size = 1 << (dc->opcode & 3);

    LOG_DIS("l %x %d\n", dc->opcode, size);

    t_sync_flags(dc);

    addr = compute_ldst_addr(dc, &t);

    /* If we get a fault on a dslot, the jmpstate better be in sync.  */

    sync_jmpstate(dc);

    /* Verify alignment if needed.  */

    if ((dc->env->pvr.regs[2] & PVR2_UNALIGNED_EXC_MASK) && size > 1) {

        gen_helper_memalign(*addr, tcg_const_tl(dc->rd),

                            tcg_const_tl(0), tcg_const_tl(size - 1));

    if (dc->rd) {

        gen_load(dc, cpu_R[dc->rd], *addr, size);

    } else {

        gen_load(dc, env_imm, *addr, size);

    if (addr == &t)

        tcg_temp_free(t);


static void test_visitor_in_int_overflow(TestInputVisitorData *data,

                                         const void *unused)

{

    int64_t res = 0;

    Error *err = NULL;

    Visitor *v;

    /* this will overflow a Qint/int64, so should be deserialized into

     * a QFloat/double field instead, leading to an error if we pass it

     * to visit_type_int. confirm this.

     */

    v = visitor_input_test_init(data, "%f", DBL_MAX);

    visit_type_int(v, &res, NULL, &err);

    g_assert(err);

    error_free(err);

}


static void compute_pkt_fields(AVFormatContext *s, AVStream *st,

                               AVCodecParserContext *pc, AVPacket *pkt)

{

    int num, den, presentation_delayed, delay, i;

    int64_t offset;

    if (s->flags & AVFMT_FLAG_NOFILLIN)

        return;

    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)

        pkt->dts= AV_NOPTS_VALUE;

    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == AV_PICTURE_TYPE_B)

        //FIXME Set low_delay = 0 when has_b_frames = 1

        st->codec->has_b_frames = 1;

    /* do we have a video B-frame ? */

    delay= st->codec->has_b_frames;

    presentation_delayed = 0;

    // ignore delay caused by frame threading so that the mpeg2-without-dts

    // warning will not trigger

    if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)

        delay -= st->codec->thread_count-1;

    /* XXX: need has_b_frame, but cannot get it if the codec is

        not initialized */

    if (delay &&

        pc && pc->pict_type != AV_PICTURE_TYPE_B)

        presentation_delayed = 1;

    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts - (1LL<<(st->pts_wrap_bits-1)) > pkt->pts && st->pts_wrap_bits<63){

        pkt->dts -= 1LL<<st->pts_wrap_bits;

    }

    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)

    // we take the conservative approach and discard both

    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.

    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){

        av_log(s, AV_LOG_DEBUG, "invalid dts/pts combination %"PRIi64"\n", pkt->dts);

        pkt->dts= pkt->pts= AV_NOPTS_VALUE;

    }

    if (pkt->duration == 0) {

        compute_frame_duration(&num, &den, st, pc, pkt);

        if (den && num) {

            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);

            if(pkt->duration != 0 && s->packet_buffer)

                update_initial_durations(s, st, pkt);

        }

    }

    /* correct timestamps with byte offset if demuxers only have timestamps

       on packet boundaries */

    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){

        /* this will estimate bitrate based on this frame's duration and size */

        offset = av_rescale(pc->offset, pkt->duration, pkt->size);

        if(pkt->pts != AV_NOPTS_VALUE)

            pkt->pts += offset;

        if(pkt->dts != AV_NOPTS_VALUE)

            pkt->dts += offset;

    }

    if (pc && pc->dts_sync_point >= 0) {

        // we have synchronization info from the parser

        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;

        if (den > 0) {

            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;

            if (pkt->dts != AV_NOPTS_VALUE) {

                // got DTS from the stream, update reference timestamp

                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;

                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;

            } else if (st->reference_dts != AV_NOPTS_VALUE) {

                // compute DTS based on reference timestamp

                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;

                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;

            }

            if (pc->dts_sync_point > 0)

                st->reference_dts = pkt->dts; // new reference

        }

    }

    /* This may be redundant, but it should not hurt. */

    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)

        presentation_delayed = 1;

//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);

    /* interpolate PTS and DTS if they are not present */

    //We skip H264 currently because delay and has_b_frames are not reliably set

    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){

        if (presentation_delayed) {

            /* DTS = decompression timestamp */

            /* PTS = presentation timestamp */

            if (pkt->dts == AV_NOPTS_VALUE)

                pkt->dts = st->last_IP_pts;

            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);

            if (pkt->dts == AV_NOPTS_VALUE)

                pkt->dts = st->cur_dts;

            /* this is tricky: the dts must be incremented by the duration

            of the frame we are displaying, i.e. the last I- or P-frame */

            if (st->last_IP_duration == 0)

                st->last_IP_duration = pkt->duration;

            if(pkt->dts != AV_NOPTS_VALUE)

                st->cur_dts = pkt->dts + st->last_IP_duration;

            st->last_IP_duration  = pkt->duration;

            st->last_IP_pts= pkt->pts;

            /* cannot compute PTS if not present (we can compute it only

            by knowing the future */

        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){

            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){

                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);

                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);

                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){

                    pkt->pts += pkt->duration;

    //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);

                }

            }

            /* presentation is not delayed : PTS and DTS are the same */

            if(pkt->pts == AV_NOPTS_VALUE)

                pkt->pts = pkt->dts;

            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);

            if(pkt->pts == AV_NOPTS_VALUE)

                pkt->pts = st->cur_dts;

            pkt->dts = pkt->pts;

            if(pkt->pts != AV_NOPTS_VALUE)

                st->cur_dts = pkt->pts + pkt->duration;

        }

    }

    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){

        st->pts_buffer[0]= pkt->pts;

        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)

            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);

        if(pkt->dts == AV_NOPTS_VALUE)

            pkt->dts= st->pts_buffer[0];

        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here

            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet

        }

        if(pkt->dts > st->cur_dts)

            st->cur_dts = pkt->dts;

    }

//    av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);

    /* update flags */

    if(is_intra_only(st->codec))

        pkt->flags |= AV_PKT_FLAG_KEY;

    else if (pc) {

        pkt->flags = 0;

        /* keyframe computation */

        if (pc->key_frame == 1)

            pkt->flags |= AV_PKT_FLAG_KEY;

        else if (pc->key_frame == -1 && pc->pict_type == AV_PICTURE_TYPE_I)

            pkt->flags |= AV_PKT_FLAG_KEY;

    }

    if (pc)

        pkt->convergence_duration = pc->convergence_duration;

}


static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)

{

    AVFilterContext *ctx = inlink->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    ShowWavesContext *showwaves = ctx->priv;

    const int nb_samples = insamples->audio->nb_samples;

    AVFilterBufferRef *outpicref = showwaves->outpicref;

    int linesize = outpicref ? outpicref->linesize[0] : 0;

    int16_t *p = (int16_t *)insamples->data[0];

    int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);

    int i, j, h;

    const int n = showwaves->n;

    const int x = 255 / (nb_channels * n); /* multiplication factor, pre-computed to avoid in-loop divisions */

    /* draw data in the buffer */

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

        if (showwaves->buf_idx == 0 && showwaves->sample_count_mod == 0) {

            showwaves->outpicref = outpicref =

                ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN,

                                    outlink->w, outlink->h);

            outpicref->video->w = outlink->w;

            outpicref->video->h = outlink->h;

            outpicref->pts = insamples->pts +

                             av_rescale_q((p - (int16_t *)insamples->data[0]) / nb_channels,

                                          (AVRational){ 1, inlink->sample_rate },

                                          outlink->time_base);

            linesize = outpicref->linesize[0];

            memset(outpicref->data[0], 0, showwaves->h*linesize);

        }

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

            h = showwaves->h/2 - av_rescale(*p++, showwaves->h/2, MAX_INT16);

            if (h >= 0 && h < outlink->h)

                *(outpicref->data[0] + showwaves->buf_idx + h * linesize) += x;

        }

        showwaves->sample_count_mod++;

        if (showwaves->sample_count_mod == n) {

            showwaves->sample_count_mod = 0;

            showwaves->buf_idx++;

        }

        if (showwaves->buf_idx == showwaves->w)

            push_frame(outlink);

    }

    avfilter_unref_buffer(insamples);

    return 0;

}


static inline void quantize_coefs(double *coef, int *idx, float *lpc, int order,

                                  int c_bits)

{

    int i;

    const float *quant_arr = tns_tmp2_map[c_bits];

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

        idx[i] = quant_array_idx((float)coef[i], quant_arr, c_bits ? 16 : 8);

        lpc[i] = quant_arr[idx[i]];

    }

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);

    sc->realize      = scsi_block_realize;

    sc->unrealize    = scsi_unrealize;

    sc->alloc_req    = scsi_block_new_request;

    sc->parse_cdb    = scsi_block_parse_cdb;

    dc->fw_name = "disk";

    dc->desc = "SCSI block device passthrough";

    dc->reset = scsi_disk_reset;

    dc->props = scsi_block_properties;

    dc->vmsd  = &vmstate_scsi_disk_state;

}


static inline target_phys_addr_t get_pgaddr(target_phys_addr_t sdr1,

                                            int sdr_sh,

                                            target_phys_addr_t hash,

                                            target_phys_addr_t mask)

{

    return (sdr1 & ((target_phys_addr_t)(-1ULL) << sdr_sh)) | (hash & mask);

}


int vhdx_parse_log(BlockDriverState *bs, BDRVVHDXState *s, bool *flushed,

                   Error **errp)

{

    int ret = 0;

    VHDXHeader *hdr;

    VHDXLogSequence logs = { 0 };

    hdr = s->headers[s->curr_header];

    *flushed = false;

    /* s->log.hdr is freed in vhdx_close() */

    if (s->log.hdr == NULL) {

        s->log.hdr = qemu_blockalign(bs, sizeof(VHDXLogEntryHeader));

    }

    s->log.offset = hdr->log_offset;

    s->log.length = hdr->log_length;

    if (s->log.offset < VHDX_LOG_MIN_SIZE ||

        s->log.offset % VHDX_LOG_MIN_SIZE) {

        ret = -EINVAL;

        goto exit;

    }

    /* per spec, only log version of 0 is supported */

    if (hdr->log_version != 0) {

        ret = -EINVAL;

        goto exit;

    }

    /* If either the log guid, or log length is zero,

     * then a replay log is not present */

    if (guid_eq(hdr->log_guid, zero_guid)) {

        goto exit;

    }

    if (hdr->log_length == 0) {

        goto exit;

    }

    if (hdr->log_length % VHDX_LOG_MIN_SIZE) {

        ret = -EINVAL;

        goto exit;

    }

    /* The log is present, we need to find if and where there is an active

     * sequence of valid entries present in the log.  */

    ret = vhdx_log_search(bs, s, &logs);

    if (ret < 0) {

        goto exit;

    }

    if (logs.valid) {

        if (bs->read_only) {

            ret = -EPERM;

            error_setg_errno(errp, EPERM,

                             "VHDX image file '%s' opened read-only, but "

                             "contains a log that needs to be replayed.  To "

                             "replay the log, execute:\n qemu-img check -r "

                             "all '%s'",

                             bs->filename, bs->filename);

            goto exit;

        }

        /* now flush the log */

        ret = vhdx_log_flush(bs, s, &logs);

        if (ret < 0) {

            goto exit;

        }

        *flushed = true;

    }

exit:

    return ret;

}


static gboolean fd_trampoline(GIOChannel *chan, GIOCondition cond, gpointer opaque)

{

    IOTrampoline *tramp = opaque;

    if ((cond & G_IO_IN) && tramp->fd_read) {

        tramp->fd_read(tramp->opaque);

    }

    if ((cond & G_IO_OUT) && tramp->fd_write) {

        tramp->fd_write(tramp->opaque);

    }

    return TRUE;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VirtIOS390DeviceClass *k = VIRTIO_S390_DEVICE_CLASS(klass);

    k->init = s390_virtio_serial_init;

    dc->props = s390_virtio_serial_properties;

    dc->alias = "virtio-serial";

}


static uint64_t get_fourcc(AVIOContext *bc)

{

    unsigned int len = ffio_read_varlen(bc);

    if (len == 2)

        return avio_rl16(bc);

    else if (len == 4)

        return avio_rl32(bc);

    else

        return -1;

}


void qemu_chr_be_generic_open(CharDriverState *s)

{

    if (s->idle_tag == 0) {

        s->idle_tag = g_idle_add(qemu_chr_be_generic_open_bh, s);

    }

}


static void write_fp_dreg(DisasContext *s, int reg, TCGv_i64 v)

{

    TCGv_i64 tcg_zero = tcg_const_i64(0);

    tcg_gen_st_i64(v, cpu_env, fp_reg_offset(reg, MO_64));

    tcg_gen_st_i64(tcg_zero, cpu_env, fp_reg_hi_offset(reg));

    tcg_temp_free_i64(tcg_zero);

}


static int ac3_probe(AVProbeData *p)

{

    int max_frames, first_frames = 0, frames;

    uint8_t *buf, *buf2, *end;

    AC3HeaderInfo hdr;

    if(p->buf_size < 7)

        return 0;

    max_frames = 0;

    buf = p->buf;

    end = buf + p->buf_size;

    for(; buf < end; buf++) {

        buf2 = buf;

        for(frames = 0; buf2 < end; frames++) {

            if(ff_ac3_parse_header(buf2, &hdr) < 0)

                break;

            buf2 += hdr.frame_size;

        }

        max_frames = FFMAX(max_frames, frames);

        if(buf == p->buf)

            first_frames = frames;

    }

    if   (first_frames>=3) return AVPROBE_SCORE_MAX * 3 / 4;

    else if(max_frames>=3) return AVPROBE_SCORE_MAX / 2;

    else if(max_frames>=1) return 1;

    else                   return 0;

}


int init_put_byte(ByteIOContext *s,

                  unsigned char *buffer,

                  int buffer_size,

                  int write_flag,

                  void *opaque,

                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),

                  void (*write_packet)(void *opaque, uint8_t *buf, int buf_size),

                  int (*seek)(void *opaque, offset_t offset, int whence))

{

    s->buffer = buffer;

    s->buffer_size = buffer_size;

    s->buf_ptr = buffer;

    s->write_flag = write_flag;

    if (!s->write_flag)

        s->buf_end = buffer;

    else

        s->buf_end = buffer + buffer_size;

    s->opaque = opaque;

    s->write_packet = write_packet;

    s->read_packet = read_packet;

    s->seek = seek;

    s->pos = 0;

    s->must_flush = 0;

    s->eof_reached = 0;

    s->is_streamed = 0;

    s->max_packet_size = 0;

    s->checksum_ptr= NULL;

    s->update_checksum= NULL;

    return 0;

}


static void do_interrupt_v7m(CPUARMState *env)

{

    uint32_t xpsr = xpsr_read(env);

    uint32_t lr;

    uint32_t addr;

    lr = 0xfffffff1;

    if (env->v7m.current_sp)

        lr |= 4;

    if (env->v7m.exception == 0)

        lr |= 8;

    /* For exceptions we just mark as pending on the NVIC, and let that

       handle it.  */

    /* TODO: Need to escalate if the current priority is higher than the

       one we're raising.  */

    switch (env->exception_index) {

    case EXCP_UDEF:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_USAGE);

        return;

    case EXCP_SWI:

        env->regs[15] += 2;

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_SVC);

        return;

    case EXCP_PREFETCH_ABORT:

    case EXCP_DATA_ABORT:

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_MEM);

        return;

    case EXCP_BKPT:

        if (semihosting_enabled) {

            int nr;

            nr = lduw_code(env->regs[15]) & 0xff;

            if (nr == 0xab) {

                env->regs[15] += 2;

                env->regs[0] = do_arm_semihosting(env);

                return;

            }

        }

        armv7m_nvic_set_pending(env->nvic, ARMV7M_EXCP_DEBUG);

        return;

    case EXCP_IRQ:

        env->v7m.exception = armv7m_nvic_acknowledge_irq(env->nvic);

        break;

    case EXCP_EXCEPTION_EXIT:

        do_v7m_exception_exit(env);

        return;

    default:

        cpu_abort(env, "Unhandled exception 0x%x\n", env->exception_index);

        return; /* Never happens.  Keep compiler happy.  */

    }

    /* Align stack pointer.  */

    /* ??? Should only do this if Configuration Control Register

       STACKALIGN bit is set.  */

    if (env->regs[13] & 4) {

        env->regs[13] -= 4;

        xpsr |= 0x200;

    }

    /* Switch to the handler mode.  */

    v7m_push(env, xpsr);

    v7m_push(env, env->regs[15]);

    v7m_push(env, env->regs[14]);

    v7m_push(env, env->regs[12]);

    v7m_push(env, env->regs[3]);

    v7m_push(env, env->regs[2]);

    v7m_push(env, env->regs[1]);

    v7m_push(env, env->regs[0]);

    switch_v7m_sp(env, 0);

    /* Clear IT bits */

    env->condexec_bits = 0;

    env->regs[14] = lr;

    addr = ldl_phys(env->v7m.vecbase + env->v7m.exception * 4);

    env->regs[15] = addr & 0xfffffffe;

    env->thumb = addr & 1;

}


static int aac_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame_ptr, AVPacket *avpkt)
{
    AACContext *ac = avctx->priv_data;
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    GetBitContext gb;
    int buf_consumed;
    int buf_offset;
    int err;
    int new_extradata_size;
    const uint8_t *new_extradata = av_packet_get_side_data(avpkt,
                                       AV_PKT_DATA_NEW_EXTRADATA,
                                       &new_extradata_size);
    int jp_dualmono_size;
    const uint8_t *jp_dualmono   = av_packet_get_side_data(avpkt,
                                       AV_PKT_DATA_JP_DUALMONO,
                                       &jp_dualmono_size);
    if (new_extradata && 0) {
        av_free(avctx->extradata);
        avctx->extradata = av_mallocz(new_extradata_size +
                                      FF_INPUT_BUFFER_PADDING_SIZE);
        if (!avctx->extradata)
            return AVERROR(ENOMEM);
        avctx->extradata_size = new_extradata_size;
        memcpy(avctx->extradata, new_extradata, new_extradata_size);
        push_output_configuration(ac);
        if (decode_audio_specific_config(ac, ac->avctx, &ac->oc[1].m4ac,
                                         avctx->extradata,
                                         avctx->extradata_size*8, 1) < 0) {
            pop_output_configuration(ac);
        }
    }
    ac->dmono_mode = 0;
    if (jp_dualmono && jp_dualmono_size > 0)
        ac->dmono_mode =  1 + *jp_dualmono;
    if (ac->force_dmono_mode >= 0)
        ac->dmono_mode = ac->force_dmono_mode;
    init_get_bits(&gb, buf, buf_size * 8);
    if ((err = aac_decode_frame_int(avctx, data, got_frame_ptr, &gb, avpkt)) < 0)
        return err;
    buf_consumed = (get_bits_count(&gb) + 7) >> 3;
    for (buf_offset = buf_consumed; buf_offset < buf_size; buf_offset++)
        if (buf[buf_offset])
            break;
    return buf_size > buf_offset ? buf_consumed : buf_size;
}


static void block_job_unref(BlockJob *job)

{

    if (--job->refcnt == 0) {

        BlockDriverState *bs = blk_bs(job->blk);

        bs->job = NULL;

        block_job_remove_all_bdrv(job);

        blk_remove_aio_context_notifier(job->blk,

                                        block_job_attached_aio_context,

                                        block_job_detach_aio_context, job);

        blk_unref(job->blk);

        error_free(job->blocker);

        g_free(job->id);

        QLIST_REMOVE(job, job_list);

        g_free(job);

    }

}


static int rawvideo_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    int packet_size, ret, width, height;

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

    width = st->codec->width;

    height = st->codec->height;

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

    if (packet_size < 0)

        return -1;

    ret= av_get_packet(s->pb, pkt, packet_size);

    pkt->pts=

    pkt->dts= pkt->pos / packet_size;

    pkt->stream_index = 0;

    if (ret != packet_size)

        return AVERROR(EIO);

    return 0;

}


static int mpeg_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    Mpeg1Context *s = avctx->priv_data;

    AVFrame *picture = data;

    MpegEncContext *s2 = &s->mpeg_enc_ctx;

    av_dlog(avctx, "fill_buffer\n");

    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == SEQ_END_CODE)) {

        /* special case for last picture */

        if (s2->low_delay == 0 && s2->next_picture_ptr) {

            *picture = s2->next_picture_ptr->f;

            s2->next_picture_ptr = NULL;

            *data_size = sizeof(AVFrame);

        }

        return buf_size;

    }

    if (s2->flags & CODEC_FLAG_TRUNCATED) {

        int next = ff_mpeg1_find_frame_end(&s2->parse_context, buf, buf_size, NULL);

        if (ff_combine_frame(&s2->parse_context, next, (const uint8_t **)&buf, &buf_size) < 0)

            return buf_size;

    }

    s2->codec_tag = avpriv_toupper4(avctx->codec_tag);

    if (s->mpeg_enc_ctx_allocated == 0 && (   s2->codec_tag == AV_RL32("VCR2")

                                           || s2->codec_tag == AV_RL32("BW10")

                                          ))

        vcr2_init_sequence(avctx);

    s->slice_count = 0;

    if (avctx->extradata && !avctx->frame_number) {

        int ret = decode_chunks(avctx, picture, data_size, avctx->extradata, avctx->extradata_size);

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

            return ret;

    }

    return decode_chunks(avctx, picture, data_size, buf, buf_size);

}


void ff_h264_remove_all_refs(H264Context *h)

{

    int i;

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

        remove_long(h, i, 0);

    }

    assert(h->long_ref_count == 0);

    if (h->short_ref_count && !h->last_pic_for_ec.f->data[0]) {

        ff_h264_unref_picture(h, &h->last_pic_for_ec);

        if (h->short_ref[0]->f->buf[0])

            ff_h264_ref_picture(h, &h->last_pic_for_ec, h->short_ref[0]);

    }

    for (i = 0; i < h->short_ref_count; i++) {

        unreference_pic(h, h->short_ref[i], 0);

        h->short_ref[i] = NULL;

    }

    h->short_ref_count = 0;

    memset(h->default_ref, 0, sizeof(h->default_ref));

}


static int oss_init_in (HWVoiceIn *hw, struct audsettings *as)

{

    OSSVoiceIn *oss = (OSSVoiceIn *) hw;

    struct oss_params req, obt;

    int endianness;

    int err;

    int fd;

    audfmt_e effective_fmt;

    struct audsettings obt_as;

    oss->fd = -1;

    req.fmt = aud_to_ossfmt (as->fmt, as->endianness);

    req.freq = as->freq;

    req.nchannels = as->nchannels;

    req.fragsize = conf.fragsize;

    req.nfrags = conf.nfrags;

    if (oss_open (1, &req, &obt, &fd)) {

        return -1;

    }

    err = oss_to_audfmt (obt.fmt, &effective_fmt, &endianness);

    if (err) {

        oss_anal_close (&fd);

        return -1;

    }

    obt_as.freq = obt.freq;

    obt_as.nchannels = obt.nchannels;

    obt_as.fmt = effective_fmt;

    obt_as.endianness = endianness;

    audio_pcm_init_info (&hw->info, &obt_as);

    oss->nfrags = obt.nfrags;

    oss->fragsize = obt.fragsize;

    if (obt.nfrags * obt.fragsize & hw->info.align) {

        dolog ("warning: Misaligned ADC buffer, size %d, alignment %d\n",

               obt.nfrags * obt.fragsize, hw->info.align + 1);

    }

    hw->samples = (obt.nfrags * obt.fragsize) >> hw->info.shift;

    oss->pcm_buf = audio_calloc (AUDIO_FUNC, hw->samples, 1 << hw->info.shift);

    if (!oss->pcm_buf) {

        dolog ("Could not allocate ADC buffer (%d samples, each %d bytes)\n",

               hw->samples, 1 << hw->info.shift);

        oss_anal_close (&fd);

        return -1;

    }

    oss->fd = fd;

    return 0;

}