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

{

	int x,y;

	dst[0]= src[0];

	// first line

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

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

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

	}

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

        dst+= dstStride;

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

#if defined (HAVE_MMX2) || defined (HAVE_3DNOW)

		const long mmxSize= srcWidth&~15;

		asm volatile(

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

			"1:				\n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#if 1

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

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

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

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

#else

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

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

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

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

#endif

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

			" js 1b				\n\t"

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

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

			   "g" (-mmxSize)

			: "%"REG_a

		);

#else

		const int mmxSize=1;

#endif

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

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

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

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

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

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

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

		}

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

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

		dst+=dstStride*2;

		src+=srcStride;

	}

	// last line

#if 1

	dst[0]= src[0];

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

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

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

	}

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

#else

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

		dst[2*x+0]=

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

	}

#endif

#ifdef HAVE_MMX

asm volatile(   EMMS" \n\t"

        	SFENCE" \n\t"

        	:::"memory");

#endif

}


static MemTxResult memory_region_write_accessor(MemoryRegion *mr,

                                                hwaddr addr,

                                                uint64_t *value,

                                                unsigned size,

                                                unsigned shift,

                                                uint64_t mask,

                                                MemTxAttrs attrs)

{

    uint64_t tmp;

    tmp = (*value >> shift) & mask;

    if (mr->subpage) {

        trace_memory_region_subpage_write(get_cpu_index(), mr, addr, tmp, size);

    } else if (TRACE_MEMORY_REGION_OPS_WRITE_ENABLED) {

        hwaddr abs_addr = memory_region_to_absolute_addr(mr, addr);

        trace_memory_region_ops_write(get_cpu_index(), mr, abs_addr, tmp, size);

    }

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

    return MEMTX_OK;

}


void qemu_del_vlan_client(VLANClientState *vc)

{

    if (vc->vlan) {

        QTAILQ_REMOVE(&vc->vlan->clients, vc, next);

    } else {

        if (vc->send_queue) {

            qemu_del_net_queue(vc->send_queue);

        }

        QTAILQ_REMOVE(&non_vlan_clients, vc, next);

        if (vc->peer) {

            vc->peer->peer = NULL;

        }

    }

    if (vc->info->cleanup) {

        vc->info->cleanup(vc);

    }

    qemu_free(vc->name);

    qemu_free(vc->model);

    qemu_free(vc);

}


static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st)

{

    MXFPackage *temp_package = NULL;

    MXFPackage *physical_package = NULL;

    MXFTrack *physical_track = NULL;

    MXFStructuralComponent *component = NULL;

    MXFStructuralComponent *sourceclip = NULL;

    MXFTimecodeComponent *mxf_tc = NULL;

    MXFPulldownComponent *mxf_pulldown = NULL;

    int i, j, k;

    AVTimecode tc;

    int flags;

    int64_t start_position;

    for (i = 0; i < source_track->sequence->structural_components_count; i++) {

        component = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip);

        if (!component)

            continue;

        for (j = 0; j < mxf->packages_count; j++) {

            temp_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[j], SourcePackage);

            if (!temp_package)

                continue;

            if (!memcmp(temp_package->package_uid, component->source_package_uid, 16)){

                physical_package = temp_package;

                sourceclip = component;

                break;

            }

        }

        if (!physical_package)

            break;

        /* the name of physical source package is name of the reel or tape */

        if (physical_package->name[0])

            av_dict_set(&st->metadata, "reel_name", physical_package->name, 0);

        /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track

         * to the start_frame of the timecode component located on one of the tracks of the physical source package.

         */

        for (j = 0; j < physical_package->tracks_count; j++) {

            if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) {

                av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n");

                continue;

            }

            if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) {

                av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n");

                continue;

            }

            for (k = 0; k < physical_track->sequence->structural_components_count; k++) {

                component = mxf_resolve_strong_ref(mxf, &physical_track->sequence->structural_components_refs[k], TimecodeComponent);

                if (!component){

                    /* timcode component may be located on a pulldown component */

                    component = mxf_resolve_strong_ref(mxf, &physical_track->sequence->structural_components_refs[k], PulldownComponent);

                    if (!component)

                        continue;

                    mxf_pulldown = (MXFPulldownComponent*)component;

                    component = mxf_resolve_strong_ref(mxf, &mxf_pulldown->input_segment_ref, TimecodeComponent);

                    if (!component)

                        continue;

                }

                mxf_tc = (MXFTimecodeComponent*)component;

                flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0;

                /* scale sourceclip start_position to match physical track edit rate */

                start_position = av_rescale_q(sourceclip->start_position,

                                              physical_track->edit_rate,

                                              source_track->edit_rate);

                if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) {

                    mxf_add_timecode_metadata(&st->metadata, "timecode", &tc);

                    return 0;

                }

            }

        }

    }

    return 0;

}


static void user_monitor_complete(void *opaque, QObject *ret_data)

{

    MonitorCompletionData *data = (MonitorCompletionData *)opaque;

    if (ret_data) {

        data->user_print(data->mon, ret_data);

    }

    monitor_resume(data->mon);

    g_free(data);

}


static int set_string_number(void *obj, const AVOption *o, const char *val, void *dst)

{

    int ret = 0, notfirst = 0;

    for (;;) {

        int i, den = 1;

        char buf[256];

        int cmd = 0;

        double d, num = 1;

        int64_t intnum = 1;

        if (*val == '+' || *val == '-')

            cmd = *(val++);

        for (i = 0; i < sizeof(buf) - 1 && val[i] && val[i] != '+' && val[i] != '-'; i++)

            buf[i] = val[i];

        buf[i] = 0;

        {

            const AVOption *o_named = av_opt_find(obj, buf, o->unit, 0, 0);

            if (o_named && o_named->type == AV_OPT_TYPE_CONST)

                d = DEFAULT_NUMVAL(o_named);

            else if (!strcmp(buf, "default")) d = DEFAULT_NUMVAL(o);

            else if (!strcmp(buf, "max"    )) d = o->max;

            else if (!strcmp(buf, "min"    )) d = o->min;

            else if (!strcmp(buf, "none"   )) d = 0;

            else if (!strcmp(buf, "all"    )) d = ~0;

            else {

                int res = av_expr_parse_and_eval(&d, buf, const_names, const_values, NULL, NULL, NULL, NULL, NULL, 0, obj);

                if (res < 0) {

                    av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\"\n", val);

                    return res;

                }

            }

        }

        if (o->type == AV_OPT_TYPE_FLAGS) {

            read_number(o, dst, NULL, NULL, &intnum);

            if      (cmd == '+') d = intnum | (int64_t)d;

            else if (cmd == '-') d = intnum &~(int64_t)d;

        } else {

            read_number(o, dst, &num, &den, &intnum);

            if      (cmd == '+') d = notfirst*num*intnum/den + d;

            else if (cmd == '-') d = notfirst*num*intnum/den - d;

        }

        if ((ret = write_number(obj, o, dst, d, 1, 1)) < 0)

            return ret;

        val += i;

        if (!*val)

            return 0;

        notfirst = 1;

    }

    return 0;

}


static int amr_wb_encode_frame(AVCodecContext *avctx,

                            unsigned char *frame/*out*/, int buf_size, void *data/*in*/)

{

    AMRWBContext *s;

    int size;

    s = (AMRWBContext*) avctx->priv_data;

    s->mode=getWBBitrateMode(avctx->bit_rate);

    size = E_IF_encode(s->state, s->mode, data, frame, s->allow_dtx);

    return size;

}


static void lag_pred_line(LagarithContext *l, uint8_t *buf,

                          int width, int stride, int line)

{

    int L, TL;

    /* Left pixel is actually prev_row[width] */

    L = buf[width - stride - 1];

    if (!line) {

        /* Left prediction only for first line */

        L = l->dsp.add_hfyu_left_prediction(buf + 1, buf + 1,

                                            width - 1, buf[0]);

        return;

    } else if (line == 1) {

        /* Second line, left predict first pixel, the rest of the line is median predicted

         * NOTE: In the case of RGB this pixel is top predicted */

        TL = l->avctx->pix_fmt == PIX_FMT_YUV420P ? buf[-stride] : L;

    } else {

        /* Top left is 2 rows back, last pixel */

        TL = buf[width - (2 * stride) - 1];

    }

    add_lag_median_prediction(buf, buf - stride, buf,

                              width, &L, &TL);

}


static void fill_tone_level_array (QDM2Context *q, int flag)

{

    int i, sb, ch, sb_used;

    int tmp, tab;

    // This should never happen

    if (q->nb_channels <= 0)

        return;

    for (ch = 0; ch < q->nb_channels; ch++)

        for (sb = 0; sb < 30; sb++)

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

                if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))

                    tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+

                          q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];

                else

                    tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];

                if(tmp < 0)

                    tmp += 0xff;

                q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;

            }

    sb_used = QDM2_SB_USED(q->sub_sampling);

    if ((q->superblocktype_2_3 != 0) && !flag) {

        for (sb = 0; sb < sb_used; sb++)

            for (ch = 0; ch < q->nb_channels; ch++)

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

                    q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];

                    if (q->tone_level_idx[ch][sb][i] < 0)

                        q->tone_level[ch][sb][i] = 0;

                    else

                        q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];

                }

    } else {

        tab = q->superblocktype_2_3 ? 0 : 1;

        for (sb = 0; sb < sb_used; sb++) {

            if ((sb >= 4) && (sb <= 23)) {

                for (ch = 0; ch < q->nb_channels; ch++)

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

                        tmp = q->tone_level_idx_base[ch][sb][i / 8] -

                              q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -

                              q->tone_level_idx_mid[ch][sb - 4][i / 8] -

                              q->tone_level_idx_hi2[ch][sb - 4];

                        q->tone_level_idx[ch][sb][i] = tmp & 0xff;

                        if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                            q->tone_level[ch][sb][i] = 0;

                        else

                            q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                }

            } else {

                if (sb > 4) {

                    for (ch = 0; ch < q->nb_channels; ch++)

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

                            tmp = q->tone_level_idx_base[ch][sb][i / 8] -

                                  q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -

                                  q->tone_level_idx_hi2[ch][sb - 4];

                            q->tone_level_idx[ch][sb][i] = tmp & 0xff;

                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                                q->tone_level[ch][sb][i] = 0;

                            else

                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                    }

                } else {

                    for (ch = 0; ch < q->nb_channels; ch++)

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

                            tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];

                            if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))

                                q->tone_level[ch][sb][i] = 0;

                            else

                                q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];

                        }

                }

            }

        }

    }

    return;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *src_buffer)

{

    AVFilterContext  *ctx = inlink->dst;

    ATempoContext *atempo = ctx->priv;

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

    int ret = 0;

    int n_in = src_buffer->nb_samples;

    int n_out = (int)(0.5 + ((double)n_in) / atempo->tempo);

    const uint8_t *src = src_buffer->data[0];

    const uint8_t *src_end = src + n_in * atempo->stride;

    while (src < src_end) {

        if (!atempo->dst_buffer) {

            atempo->dst_buffer = ff_get_audio_buffer(outlink, n_out);

            av_frame_copy_props(atempo->dst_buffer, src_buffer);

            atempo->dst = atempo->dst_buffer->data[0];

            atempo->dst_end = atempo->dst + n_out * atempo->stride;

        }

        yae_apply(atempo, &src, src_end, &atempo->dst, atempo->dst_end);

        if (atempo->dst == atempo->dst_end) {

            ret = push_samples(atempo, outlink, n_out);

            if (ret < 0)

                goto end;

            atempo->request_fulfilled = 1;

        }

    }

    atempo->nsamples_in += n_in;

end:

    av_frame_free(&src_buffer);

    return ret;

}


static void put_buffer(GDBState *s, const uint8_t *buf, int len)

{

#ifdef CONFIG_USER_ONLY

    int ret;

    while (len > 0) {

        ret = send(s->fd, buf, len, 0);

        if (ret < 0) {

            if (errno != EINTR && errno != EAGAIN)

                return;

        } else {

            buf += ret;

            len -= ret;

        }

    }

#else

    qemu_chr_fe_write(s->chr, buf, len);

#endif

}


static Suite *qdict_suite(void)

{

    Suite *s;

    TCase *qdict_public_tcase;

    TCase *qdict_public2_tcase;

    TCase *qdict_stress_tcase;

    TCase *qdict_errors_tcase;

    s = suite_create("QDict test-suite");

    qdict_public_tcase = tcase_create("Public Interface");

    suite_add_tcase(s, qdict_public_tcase);

    tcase_add_test(qdict_public_tcase, qdict_new_test);

    tcase_add_test(qdict_public_tcase, qdict_put_obj_test);

    tcase_add_test(qdict_public_tcase, qdict_destroy_simple_test);

    /* Continue, but now with fixtures */

    qdict_public2_tcase = tcase_create("Public Interface (2)");

    suite_add_tcase(s, qdict_public2_tcase);

    tcase_add_checked_fixture(qdict_public2_tcase, qdict_setup, qdict_teardown);

    tcase_add_test(qdict_public2_tcase, qdict_get_test);

    tcase_add_test(qdict_public2_tcase, qdict_get_int_test);

    tcase_add_test(qdict_public2_tcase, qdict_get_try_int_test);

    tcase_add_test(qdict_public2_tcase, qdict_get_str_test);

    tcase_add_test(qdict_public2_tcase, qdict_get_try_str_test);

    tcase_add_test(qdict_public2_tcase, qdict_haskey_not_test);

    tcase_add_test(qdict_public2_tcase, qdict_haskey_test);

    tcase_add_test(qdict_public2_tcase, qdict_del_test);

    tcase_add_test(qdict_public2_tcase, qobject_to_qdict_test);

    tcase_add_test(qdict_public2_tcase, qdict_iterapi_test);

    qdict_errors_tcase = tcase_create("Errors");

    suite_add_tcase(s, qdict_errors_tcase);

    tcase_add_checked_fixture(qdict_errors_tcase, qdict_setup, qdict_teardown);

    tcase_add_test(qdict_errors_tcase, qdict_put_exists_test);

    tcase_add_test(qdict_errors_tcase, qdict_get_not_exists_test);

    /* The Big one */

    qdict_stress_tcase = tcase_create("Stress Test");

    suite_add_tcase(s, qdict_stress_tcase);

    tcase_add_test(qdict_stress_tcase, qdict_stress_test);

    return s;

}


static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)

{

    Error *local_err = NULL;

    QObject *obj, *data;

    QDict *input, *args;

    const mon_cmd_t *cmd;

    const char *cmd_name;

    Monitor *mon = cur_mon;

    args = input = NULL;

    data = NULL;

    obj = json_parser_parse(tokens, NULL);

    if (!obj) {

        // FIXME: should be triggered in json_parser_parse()

        qerror_report(QERR_JSON_PARSING);

        goto err_out;

    }

    input = qmp_check_input_obj(obj, &local_err);

    if (!input) {

        qerror_report_err(local_err);

        qobject_decref(obj);

        goto err_out;

    }

    mon->mc->id = qdict_get(input, "id");

    qobject_incref(mon->mc->id);

    cmd_name = qdict_get_str(input, "execute");

    trace_handle_qmp_command(mon, cmd_name);

    cmd = qmp_find_cmd(cmd_name);

    if (!cmd) {

        qerror_report(ERROR_CLASS_COMMAND_NOT_FOUND,

                      "The command %s has not been found", cmd_name);

        goto err_out;

    }

    if (invalid_qmp_mode(mon, cmd)) {

        goto err_out;

    }

    obj = qdict_get(input, "arguments");

    if (!obj) {

        args = qdict_new();

    } else {

        args = qobject_to_qdict(obj);

        QINCREF(args);

    }

    qmp_check_client_args(cmd, args, &local_err);

    if (local_err) {

        qerror_report_err(local_err);

        goto err_out;

    }

    if (cmd->mhandler.cmd_new(mon, args, &data)) {

        /* Command failed... */

        if (!monitor_has_error(mon)) {

            /* ... without setting an error, so make one up */

            qerror_report(QERR_UNDEFINED_ERROR);

        }

    }

err_out:

    monitor_protocol_emitter(mon, data);

    qobject_decref(data);

    QDECREF(input);

    QDECREF(args);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);

    k->init = aer915_init;

    k->event = aer915_event;

    k->recv = aer915_recv;

    k->send = aer915_send;

    dc->vmsd = &vmstate_aer915_state;

}


static av_always_inline void decode_line(FFV1Context *s, int w,

                                         int16_t *sample[2],

                                         int plane_index, int bits)

{

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

    RangeCoder *const c   = &s->c;

    int x;

    int run_count = 0;

    int run_mode  = 0;

    int run_index = s->run_index;

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

        int diff, context, sign;

        context = get_context(p, sample[1] + x, sample[0] + x, sample[1] + x);

        if (context < 0) {

            context = -context;

            sign    = 1;

        } else

            sign = 0;

        av_assert2(context < p->context_count);

        if (s->ac) {

            diff = get_symbol_inline(c, p->state[context], 1);

        } else {

            if (context == 0 && run_mode == 0)

                run_mode = 1;

            if (run_mode) {

                if (run_count == 0 && run_mode == 1) {

                    if (get_bits1(&s->gb)) {

                        run_count = 1 << ff_log2_run[run_index];

                        if (x + run_count <= w)

                            run_index++;

                    } else {

                        if (ff_log2_run[run_index])

                            run_count = get_bits(&s->gb, ff_log2_run[run_index]);

                        else

                            run_count = 0;

                        if (run_index)

                            run_index--;

                        run_mode = 2;

                    }

                }

                run_count--;

                if (run_count < 0) {

                    run_mode  = 0;

                    run_count = 0;

                    diff      = get_vlc_symbol(&s->gb, &p->vlc_state[context],

                                               bits);

                    if (diff >= 0)

                        diff++;

                } else

                    diff = 0;

            } else

                diff = get_vlc_symbol(&s->gb, &p->vlc_state[context], bits);

            ff_dlog(s->avctx, "count:%d index:%d, mode:%d, x:%d pos:%d\n",

                    run_count, run_index, run_mode, x, get_bits_count(&s->gb));

        }

        if (sign)

            diff = -diff;

        sample[1][x] = (predict(sample[1] + x, sample[0] + x) + diff) &

                       ((1 << bits) - 1);

    }

    s->run_index = run_index;

}


static uint64_t mcf_fec_read(void *opaque, target_phys_addr_t addr,

                             unsigned size)

{

    mcf_fec_state *s = (mcf_fec_state *)opaque;

    switch (addr & 0x3ff) {

    case 0x004: return s->eir;

    case 0x008: return s->eimr;

    case 0x010: return s->rx_enabled ? (1 << 24) : 0; /* RDAR */

    case 0x014: return 0; /* TDAR */

    case 0x024: return s->ecr;

    case 0x040: return s->mmfr;

    case 0x044: return s->mscr;

    case 0x064: return 0; /* MIBC */

    case 0x084: return s->rcr;

    case 0x0c4: return s->tcr;

    case 0x0e4: /* PALR */

        return (s->conf.macaddr.a[0] << 24) | (s->conf.macaddr.a[1] << 16)

              | (s->conf.macaddr.a[2] << 8) | s->conf.macaddr.a[3];

        break;

    case 0x0e8: /* PAUR */

        return (s->conf.macaddr.a[4] << 24) | (s->conf.macaddr.a[5] << 16) | 0x8808;

    case 0x0ec: return 0x10000; /* OPD */

    case 0x118: return 0;

    case 0x11c: return 0;

    case 0x120: return 0;

    case 0x124: return 0;

    case 0x144: return s->tfwr;

    case 0x14c: return 0x600;

    case 0x150: return s->rfsr;

    case 0x180: return s->erdsr;

    case 0x184: return s->etdsr;

    case 0x188: return s->emrbr;

    default:

        hw_error("mcf_fec_read: Bad address 0x%x\n", (int)addr);

        return 0;

    }

}


static hwaddr ppc_hash64_pteg_search(PowerPCCPU *cpu, hwaddr hash,

                                     const struct ppc_one_seg_page_size *sps,

                                     target_ulong ptem,

                                     ppc_hash_pte64_t *pte, unsigned *pshift)

{

    CPUPPCState *env = &cpu->env;

    int i;

    const ppc_hash_pte64_t *pteg;

    target_ulong pte0, pte1;

    target_ulong ptex;

    ptex = (hash & env->htab_mask) * HPTES_PER_GROUP;

    pteg = ppc_hash64_map_hptes(cpu, ptex, HPTES_PER_GROUP);

    if (!pteg) {

        return -1;

    }

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

        pte0 = ppc_hash64_hpte0(cpu, pteg, i);

        pte1 = ppc_hash64_hpte1(cpu, pteg, i);

        /* This compares V, B, H (secondary) and the AVPN */

        if (HPTE64_V_COMPARE(pte0, ptem)) {

            *pshift = hpte_page_shift(sps, pte0, pte1);

            /*

             * If there is no match, ignore the PTE, it could simply

             * be for a different segment size encoding and the

             * architecture specifies we should not match. Linux will

             * potentially leave behind PTEs for the wrong base page

             * size when demoting segments.

             */

            if (*pshift == 0) {

                continue;

            }

            /* We don't do anything with pshift yet as qemu TLB only deals

             * with 4K pages anyway

             */

            pte->pte0 = pte0;

            pte->pte1 = pte1;

            ppc_hash64_unmap_hptes(cpu, pteg, ptex, HPTES_PER_GROUP);

            return ptex + i;

        }

    }

    ppc_hash64_unmap_hptes(cpu, pteg, ptex, HPTES_PER_GROUP);

    /*

     * We didn't find a valid entry.

     */

    return -1;

}


static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,

                                            int64_t sector_num,

                                            int nb_sectors, int *pnum,

                                            BlockDriverState **file)

{

    BDRVRawState *s = bs->opaque;

    *pnum = nb_sectors;

    *file = bs->file->bs;

    sector_num += s->offset / BDRV_SECTOR_SIZE;

    return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID | BDRV_BLOCK_DATA |

           (sector_num << BDRV_SECTOR_BITS);

}


static void v9fs_wstat_post_rename(V9fsState *s, V9fsWstatState *vs, int err)

{

    if (err < 0) {

        goto out;

    }

    if (vs->v9stat.name.size != 0) {

        v9fs_string_free(&vs->nname);

    }

    if (vs->v9stat.length != -1) {

        if (v9fs_do_truncate(s, &vs->fidp->path, vs->v9stat.length) < 0) {

            err = -errno;

        }

    }

    v9fs_wstat_post_truncate(s, vs, err);

    return;

out:

    v9fs_stat_free(&vs->v9stat);

    complete_pdu(s, vs->pdu, err);

    qemu_free(vs);

}


static int pci_unin_internal_init_device(SysBusDevice *dev)

{

    UNINState *s;

    int pci_mem_config, pci_mem_data;

    /* Uninorth internal bus */

    s = FROM_SYSBUS(UNINState, dev);

    pci_mem_config = cpu_register_io_memory(pci_unin_config_read,

                                            pci_unin_config_write, s);

    pci_mem_data = cpu_register_io_memory(pci_unin_read,

                                          pci_unin_write, s);

    sysbus_init_mmio(dev, 0x1000, pci_mem_config);

    sysbus_init_mmio(dev, 0x1000, pci_mem_data);

    return 0;

}


e1000e_process_tx_desc(E1000ECore *core,

                       struct e1000e_tx *tx,

                       struct e1000_tx_desc *dp,

                       int queue_index)

{

    uint32_t txd_lower = le32_to_cpu(dp->lower.data);

    uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D);

    unsigned int split_size = txd_lower & 0xffff;

    uint64_t addr;

    struct e1000_context_desc *xp = (struct e1000_context_desc *)dp;

    bool eop = txd_lower & E1000_TXD_CMD_EOP;

    if (dtype == E1000_TXD_CMD_DEXT) { /* context descriptor */

        e1000x_read_tx_ctx_descr(xp, &tx->props);

        e1000e_process_snap_option(core, le32_to_cpu(xp->cmd_and_length));

        return;

    } else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) {

        /* data descriptor */

        tx->props.sum_needed = le32_to_cpu(dp->upper.data) >> 8;

        tx->props.cptse = (txd_lower & E1000_TXD_CMD_TSE) ? 1 : 0;

        e1000e_process_ts_option(core, dp);

    } else {

        /* legacy descriptor */

        e1000e_process_ts_option(core, dp);

        tx->props.cptse = 0;

    }

    addr = le64_to_cpu(dp->buffer_addr);

    if (!tx->skip_cp) {

        if (!net_tx_pkt_add_raw_fragment(tx->tx_pkt, addr, split_size)) {

            tx->skip_cp = true;

        }

    }

    if (eop) {

        if (!tx->skip_cp && net_tx_pkt_parse(tx->tx_pkt)) {

            if (e1000x_vlan_enabled(core->mac) &&

                e1000x_is_vlan_txd(txd_lower)) {

                net_tx_pkt_setup_vlan_header_ex(tx->tx_pkt,

                    le16_to_cpu(dp->upper.fields.special), core->vet);

            }

            if (e1000e_tx_pkt_send(core, tx, queue_index)) {

                e1000e_on_tx_done_update_stats(core, tx->tx_pkt);

            }

        }

        tx->skip_cp = false;

        net_tx_pkt_reset(tx->tx_pkt);

        tx->props.sum_needed = 0;

        tx->props.cptse = 0;

    }

}


BlockAIOCB *ide_issue_trim(

        int64_t offset, QEMUIOVector *qiov,

        BlockCompletionFunc *cb, void *cb_opaque, void *opaque)

{

    BlockBackend *blk = opaque;

    TrimAIOCB *iocb;

    iocb = blk_aio_get(&trim_aiocb_info, blk, cb, cb_opaque);

    iocb->blk = blk;

    iocb->bh = qemu_bh_new(ide_trim_bh_cb, iocb);

    iocb->ret = 0;

    iocb->qiov = qiov;

    iocb->i = -1;

    iocb->j = 0;

    ide_issue_trim_cb(iocb, 0);

    return &iocb->common;

}


static int fw_cfg_boot_set(void *opaque, const char *boot_device)

{

    fw_cfg_add_i16(opaque, FW_CFG_BOOT_DEVICE, boot_device[0]);

    return 0;

}


static bool next_query_bds(BlockBackend **blk, BlockDriverState **bs,

                           bool query_nodes)

{

    if (query_nodes) {

        *bs = bdrv_next_node(*bs);

        return !!*bs;

    }

    *blk = blk_next(*blk);

    *bs = *blk ? blk_bs(*blk) : NULL;

    return !!*blk;

}


unsigned int EmulateAll(unsigned int opcode, FPA11* qfpa, CPUARMState* qregs)

{

  unsigned int nRc = 0;

//  unsigned long flags;

  FPA11 *fpa11;

//  save_flags(flags); sti();

  qemufpa=qfpa;

  user_registers=qregs;

#if 0

  fprintf(stderr,"emulating FP insn 0x%08x, PC=0x%08x\n",

          opcode, qregs[REG_PC]);

#endif

  fpa11 = GET_FPA11();

  if (fpa11->initflag == 0)		/* good place for __builtin_expect */

  {

    resetFPA11();

    SetRoundingMode(ROUND_TO_NEAREST);

    SetRoundingPrecision(ROUND_EXTENDED);

    fpa11->initflag = 1;

  }

  set_float_exception_flags(0, &fpa11->fp_status);

  if (TEST_OPCODE(opcode,MASK_CPRT))

  {

    //fprintf(stderr,"emulating CPRT\n");

    /* Emulate conversion opcodes. */

    /* Emulate register transfer opcodes. */

    /* Emulate comparison opcodes. */

    nRc = EmulateCPRT(opcode);

  }

  else if (TEST_OPCODE(opcode,MASK_CPDO))

  {

    //fprintf(stderr,"emulating CPDO\n");

    /* Emulate monadic arithmetic opcodes. */

    /* Emulate dyadic arithmetic opcodes. */

    nRc = EmulateCPDO(opcode);

  }

  else if (TEST_OPCODE(opcode,MASK_CPDT))

  {

    //fprintf(stderr,"emulating CPDT\n");

    /* Emulate load/store opcodes. */

    /* Emulate load/store multiple opcodes. */

    nRc = EmulateCPDT(opcode);

  }

  else

  {

    /* Invalid instruction detected.  Return FALSE. */

    nRc = 0;

  }

//  restore_flags(flags);

  if(nRc == 1 && get_float_exception_flags(&fpa11->fp_status))

  {

    //printf("fef 0x%x\n",float_exception_flags);

    nRc -= get_float_exception_flags(&fpa11->fp_status);

  }

  //printf("returning %d\n",nRc);

  return(nRc);

}


static gboolean io_watch_poll_dispatch(GSource *source, GSourceFunc callback,

                                       gpointer user_data)

{

    return g_io_watch_funcs.dispatch(source, callback, user_data);

}


static void iostatus_bdrv_it(void *opaque, BlockDriverState *bs)

{

    bdrv_iostatus_reset(bs);

}


void op_flush_icache_range(void) {

    CALL_FROM_TB2(tlb_flush_page, env, T0 + T1);

    RETURN();

}


static uint64_t lan9118_readl(void *opaque, hwaddr offset,

                              unsigned size)

{

    lan9118_state *s = (lan9118_state *)opaque;

    //DPRINTF("Read reg 0x%02x\n", (int)offset);

    if (offset < 0x20) {

        /* RX FIFO */

        return rx_fifo_pop(s);

    }

    switch (offset) {

    case 0x40:

        return rx_status_fifo_pop(s);

    case 0x44:

        return s->rx_status_fifo[s->tx_status_fifo_head];

    case 0x48:

        return tx_status_fifo_pop(s);

    case 0x4c:

        return s->tx_status_fifo[s->tx_status_fifo_head];

    case CSR_ID_REV:

        return 0x01180001;

    case CSR_IRQ_CFG:

        return s->irq_cfg;

    case CSR_INT_STS:

        return s->int_sts;

    case CSR_INT_EN:

        return s->int_en;

    case CSR_BYTE_TEST:

        return 0x87654321;

    case CSR_FIFO_INT:

        return s->fifo_int;

    case CSR_RX_CFG:

        return s->rx_cfg;

    case CSR_TX_CFG:

        return s->tx_cfg;

    case CSR_HW_CFG:

        return s->hw_cfg;

    case CSR_RX_DP_CTRL:

        return 0;

    case CSR_RX_FIFO_INF:

        return (s->rx_status_fifo_used << 16) | (s->rx_fifo_used << 2);

    case CSR_TX_FIFO_INF:

        return (s->tx_status_fifo_used << 16)

               | (s->tx_fifo_size - s->txp->fifo_used);

    case CSR_PMT_CTRL:

        return s->pmt_ctrl;

    case CSR_GPIO_CFG:

        return s->gpio_cfg;

    case CSR_GPT_CFG:

        return s->gpt_cfg;

    case CSR_GPT_CNT:

        return ptimer_get_count(s->timer);

    case CSR_WORD_SWAP:

        return s->word_swap;

    case CSR_FREE_RUN:

        return (qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / 40) - s->free_timer_start;

    case CSR_RX_DROP:

        /* TODO: Implement dropped frames counter.  */

        return 0;

    case CSR_MAC_CSR_CMD:

        return s->mac_cmd;

    case CSR_MAC_CSR_DATA:

        return s->mac_data;

    case CSR_AFC_CFG:

        return s->afc_cfg;

    case CSR_E2P_CMD:

        return s->e2p_cmd;

    case CSR_E2P_DATA:

        return s->e2p_data;

    }

    hw_error("lan9118_read: Bad reg 0x%x\n", (int)offset);

    return 0;

}


static void do_attach(USBDevice *dev)

{

    USBBus *bus = usb_bus_from_device(dev);

    USBPort *port;

    if (dev->attached) {

        fprintf(stderr, "Warning: tried to attach usb device %s twice\n",

                dev->devname);

        return;

    }

    dev->attached++;

    port = TAILQ_FIRST(&bus->free);

    TAILQ_REMOVE(&bus->free, port, next);

    bus->nfree--;

    usb_attach(port, dev);

    TAILQ_INSERT_TAIL(&bus->used, port, next);

    bus->nused++;

}


static void add_to_pool(BufferPoolEntry *buf)

{

    AVBufferPool *pool;

    BufferPoolEntry *cur, *end = buf;

    if (!buf)

        return;

    pool = buf->pool;

    while (end->next)

        end = end->next;

    while ((cur = avpriv_atomic_ptr_cas((void * volatile *)&pool->pool, NULL, buf))) {

        /* pool is not empty, retrieve it and append it to our list */

        cur = get_pool(pool);

        end->next = cur;

        while (end->next)

            end = end->next;

    }

}


static int tcp_get_msgfds(CharDriverState *chr, int *fds, int num)
{
    TCPCharDriver *s = chr->opaque;
    int to_copy = (s->read_msgfds_num < num) ? s->read_msgfds_num : num;
    if (to_copy) {
        memcpy(fds, s->read_msgfds, to_copy * sizeof(int));
        g_free(s->read_msgfds);
        s->read_msgfds = 0;
        s->read_msgfds_num = 0;
    return to_copy;


void *qht_do_lookup(struct qht_bucket *head, qht_lookup_func_t func,

                    const void *userp, uint32_t hash)

{

    struct qht_bucket *b = head;

    int i;

    do {

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

            if (b->hashes[i] == hash) {

                /* The pointer is dereferenced before seqlock_read_retry,

                 * so (unlike qht_insert__locked) we need to use

                 * atomic_rcu_read here.

                 */

                void *p = atomic_rcu_read(&b->pointers[i]);

                if (likely(p) && likely(func(p, userp))) {

                    return p;

                }

            }

        }

        b = atomic_rcu_read(&b->next);

    } while (b);

    return NULL;

}


static void test_io_channel_command_fifo(bool async)

{

#define TEST_FIFO "tests/test-io-channel-command.fifo"

    QIOChannel *src, *dst;

    QIOChannelTest *test;

    char *srcfifo = g_strdup_printf("PIPE:%s,wronly", TEST_FIFO);

    char *dstfifo = g_strdup_printf("PIPE:%s,rdonly", TEST_FIFO);

    const char *srcargv[] = {

        "/bin/socat", "-", srcfifo, NULL,

    };

    const char *dstargv[] = {

        "/bin/socat", dstfifo, "-", NULL,

    };

    unlink(TEST_FIFO);

    if (access("/bin/socat", X_OK) < 0) {

        return; /* Pretend success if socat is not present */

    }

    if (mkfifo(TEST_FIFO, 0600) < 0) {

        abort();

    }

    src = QIO_CHANNEL(qio_channel_command_new_spawn(srcargv,

                                                    O_WRONLY,

                                                    &error_abort));

    dst = QIO_CHANNEL(qio_channel_command_new_spawn(dstargv,

                                                    O_RDONLY,

                                                    &error_abort));

    test = qio_channel_test_new();

    qio_channel_test_run_threads(test, async, src, dst);

    qio_channel_test_validate(test);

    object_unref(OBJECT(src));

    object_unref(OBJECT(dst));

    g_free(srcfifo);

    g_free(dstfifo);

    unlink(TEST_FIFO);

}


static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)

{

    BlockDriverState *source = s->common.bs;

    int nb_sectors, sectors_per_chunk, nb_chunks;

    int64_t end, sector_num, next_chunk, next_sector, hbitmap_next_sector;

    uint64_t delay_ns = 0;

    MirrorOp *op;

    s->sector_num = hbitmap_iter_next(&s->hbi);

    if (s->sector_num < 0) {

        bdrv_dirty_iter_init(source, s->dirty_bitmap, &s->hbi);

        s->sector_num = hbitmap_iter_next(&s->hbi);

        trace_mirror_restart_iter(s,

                                  bdrv_get_dirty_count(source, s->dirty_bitmap));

        assert(s->sector_num >= 0);

    }

    hbitmap_next_sector = s->sector_num;

    sector_num = s->sector_num;

    sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;

    end = s->bdev_length / BDRV_SECTOR_SIZE;

    /* Extend the QEMUIOVector to include all adjacent blocks that will

     * be copied in this operation.

     *

     * We have to do this if we have no backing file yet in the destination,

     * and the cluster size is very large.  Then we need to do COW ourselves.

     * The first time a cluster is copied, copy it entirely.  Note that,

     * because both the granularity and the cluster size are powers of two,

     * the number of sectors to copy cannot exceed one cluster.

     *

     * We also want to extend the QEMUIOVector to include more adjacent

     * dirty blocks if possible, to limit the number of I/O operations and

     * run efficiently even with a small granularity.

     */

    nb_chunks = 0;

    nb_sectors = 0;

    next_sector = sector_num;

    next_chunk = sector_num / sectors_per_chunk;

    /* Wait for I/O to this cluster (from a previous iteration) to be done.  */

    while (test_bit(next_chunk, s->in_flight_bitmap)) {

        trace_mirror_yield_in_flight(s, sector_num, s->in_flight);

        qemu_coroutine_yield();

    }

    do {

        int added_sectors, added_chunks;

        if (!bdrv_get_dirty(source, s->dirty_bitmap, next_sector) ||

            test_bit(next_chunk, s->in_flight_bitmap)) {

            assert(nb_sectors > 0);

            break;

        }

        added_sectors = sectors_per_chunk;

        if (s->cow_bitmap && !test_bit(next_chunk, s->cow_bitmap)) {

            bdrv_round_to_clusters(s->target,

                                   next_sector, added_sectors,

                                   &next_sector, &added_sectors);

            /* On the first iteration, the rounding may make us copy

             * sectors before the first dirty one.

             */

            if (next_sector < sector_num) {

                assert(nb_sectors == 0);

                sector_num = next_sector;

                next_chunk = next_sector / sectors_per_chunk;

            }

        }

        added_sectors = MIN(added_sectors, end - (sector_num + nb_sectors));

        added_chunks = (added_sectors + sectors_per_chunk - 1) / sectors_per_chunk;

        /* When doing COW, it may happen that there is not enough space for

         * a full cluster.  Wait if that is the case.

         */

        while (nb_chunks == 0 && s->buf_free_count < added_chunks) {

            trace_mirror_yield_buf_busy(s, nb_chunks, s->in_flight);

            qemu_coroutine_yield();

        }

        if (s->buf_free_count < nb_chunks + added_chunks) {

            trace_mirror_break_buf_busy(s, nb_chunks, s->in_flight);

            break;

        }

        /* We have enough free space to copy these sectors.  */

        bitmap_set(s->in_flight_bitmap, next_chunk, added_chunks);

        nb_sectors += added_sectors;

        nb_chunks += added_chunks;

        next_sector += added_sectors;

        next_chunk += added_chunks;

        if (!s->synced && s->common.speed) {

            delay_ns = ratelimit_calculate_delay(&s->limit, added_sectors);

        }

    } while (delay_ns == 0 && next_sector < end);

    /* Allocate a MirrorOp that is used as an AIO callback.  */

    op = g_slice_new(MirrorOp);

    op->s = s;

    op->sector_num = sector_num;

    op->nb_sectors = nb_sectors;

    /* Now make a QEMUIOVector taking enough granularity-sized chunks

     * from s->buf_free.

     */

    qemu_iovec_init(&op->qiov, nb_chunks);

    next_sector = sector_num;

    while (nb_chunks-- > 0) {

        MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);

        size_t remaining = (nb_sectors * BDRV_SECTOR_SIZE) - op->qiov.size;

        QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);

        s->buf_free_count--;

        qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));

        /* Advance the HBitmapIter in parallel, so that we do not examine

         * the same sector twice.

         */

        if (next_sector > hbitmap_next_sector

            && bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {

            hbitmap_next_sector = hbitmap_iter_next(&s->hbi);

        }

        next_sector += sectors_per_chunk;

    }

    bdrv_reset_dirty(source, sector_num, nb_sectors);

    /* Copy the dirty cluster.  */

    s->in_flight++;

    s->sectors_in_flight += nb_sectors;

    trace_mirror_one_iteration(s, sector_num, nb_sectors);

    bdrv_aio_readv(source, sector_num, &op->qiov, nb_sectors,

                   mirror_read_complete, op);

    return delay_ns;

}


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

{

    LibQuviContext *qc = s->priv_data;

    return av_seek_frame(qc->fmtctx, stream_index, timestamp, flags);

}


static void sysbus_ahci_realize(DeviceState *dev, Error **errp)

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    SysbusAHCIState *s = SYSBUS_AHCI(dev);

    ahci_init(&s->ahci, dev, NULL, s->num_ports);

    sysbus_init_mmio(sbd, &s->ahci.mem);

    sysbus_init_irq(sbd, &s->ahci.irq);

}


static int spapr_vty_init(VIOsPAPRDevice *sdev)
{
    VIOsPAPRVTYDevice *dev = (VIOsPAPRVTYDevice *)sdev;
    qemu_chr_add_handlers(dev->chardev, vty_can_receive,
                          vty_receive, NULL, dev);
    return 0;


static void exynos4210_ltick_recalc_count(struct tick_timer *s)

{

    uint64_t to_count;

    if ((s->cnt_run && s->last_tcnto) || (s->int_run && s->last_icnto)) {

        /*

         * one or both timers run and not counted to the end;

         * distance is not passed, recalculate with last_tcnto * last_icnto

         */

        if (s->last_tcnto) {

            to_count = s->last_tcnto * s->last_icnto;

        } else {

            to_count = s->last_icnto;

        }

    } else {

        /* distance is passed, recalculate with tcnto * icnto */

        if (s->icntb) {

            s->distance = s->tcntb * s->icntb;

        } else {

            s->distance = s->tcntb;

        }

        to_count = s->distance;

        s->progress = 0;

    }

    if (to_count > MCT_LT_COUNTER_STEP) {

        /* count by step */

        s->count = MCT_LT_COUNTER_STEP;

    } else {

        s->count = to_count;

    }

}


static void mirror_start_job(const char *job_id, BlockDriverState *bs,

                             int creation_flags, BlockDriverState *target,

                             const char *replaces, int64_t speed,

                             uint32_t granularity, int64_t buf_size,

                             BlockMirrorBackingMode backing_mode,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base,

                             bool auto_complete, const char *filter_node_name,

                             Error **errp)

{

    MirrorBlockJob *s;

    BlockDriverState *mirror_top_bs;

    bool target_graph_mod;

    bool target_is_backing;

    Error *local_err = NULL;

    int ret;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    assert ((granularity & (granularity - 1)) == 0);

    /* Granularity must be large enough for sector-based dirty bitmap */

    assert(granularity >= BDRV_SECTOR_SIZE);

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    /* In the case of active commit, add dummy driver to provide consistent

     * reads on the top, while disabling it in the intermediate nodes, and make

     * the backing chain writable. */

    mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,

                                         BDRV_O_RDWR, errp);

    if (mirror_top_bs == NULL) {

        return;

    mirror_top_bs->total_sectors = bs->total_sectors;

    bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));

    /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep

     * it alive until block_job_create() succeeds even if bs has no parent. */

    bdrv_ref(mirror_top_bs);

    bdrv_drained_begin(bs);

    bdrv_append(mirror_top_bs, bs, &local_err);

    bdrv_drained_end(bs);

    if (local_err) {

        bdrv_unref(mirror_top_bs);

        error_propagate(errp, local_err);

        return;

    /* Make sure that the source is not resized while the job is running */

    s = block_job_create(job_id, driver, mirror_top_bs,

                         BLK_PERM_CONSISTENT_READ,

                         BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |

                         BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,

                         creation_flags, cb, opaque, errp);

    if (!s) {

        goto fail;

    /* The block job now has a reference to this node */

    bdrv_unref(mirror_top_bs);

    s->source = bs;

    s->mirror_top_bs = mirror_top_bs;

    /* No resize for the target either; while the mirror is still running, a

     * consistent read isn't necessarily possible. We could possibly allow

     * writes and graph modifications, though it would likely defeat the

     * purpose of a mirror, so leave them blocked for now.

     *

     * In the case of active commit, things look a bit different, though,

     * because the target is an already populated backing file in active use.

     * We can allow anything except resize there.*/

    target_is_backing = bdrv_chain_contains(bs, target);

    target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);

    s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |

                        (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),

                        BLK_PERM_WRITE_UNCHANGED |

                        (target_is_backing ? BLK_PERM_CONSISTENT_READ |

                                             BLK_PERM_WRITE |

                                             BLK_PERM_GRAPH_MOD : 0));

    ret = blk_insert_bs(s->target, target, errp);

    if (ret < 0) {

        goto fail;

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->is_none_mode = is_none_mode;

    s->backing_mode = backing_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    if (auto_complete) {

        s->should_complete = true;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        goto fail;

    /* Required permissions are already taken with blk_new() */

    block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,

                       &error_abort);

    /* In commit_active_start() all intermediate nodes disappear, so

     * any jobs in them must be blocked */

    if (target_is_backing) {

        BlockDriverState *iter;

        for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {

            /* XXX BLK_PERM_WRITE needs to be allowed so we don't block

             * ourselves at s->base (if writes are blocked for a node, they are

             * also blocked for its backing file). The other options would be a

             * second filter driver above s->base (== target). */

            ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,

                                     BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,

                                     errp);

            if (ret < 0) {

                goto fail;

    trace_mirror_start(bs, s, opaque);

    block_job_start(&s->common);

    return;

fail:

    if (s) {

        /* Make sure this BDS does not go away until we have completed the graph

         * changes below */

        bdrv_ref(mirror_top_bs);

        g_free(s->replaces);

        blk_unref(s->target);

        block_job_early_fail(&s->common);

    bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,

                            &error_abort);

    bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);

    bdrv_unref(mirror_top_bs);


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

{

    ASFContext *asf = s->priv_data;

    ASFStream *asf_st = 0;

    ByteIOContext *pb = &s->pb;

    //static int pc = 0;

    for (;;) {

        int rsize = 0;

        if (asf->packet_size_left < FRAME_HEADER_SIZE

            || asf->packet_segments < 1) {

            //asf->packet_size_left <= asf->packet_padsize) {

            int ret = asf->packet_size_left + asf->packet_padsize;

            //printf("PacketLeftSize:%d  Pad:%d Pos:%Ld\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));

            if((url_ftell(&s->pb) + ret - s->data_offset) % asf->packet_size)

                ret += asf->packet_size - ((url_ftell(&s->pb) + ret - s->data_offset) % asf->packet_size);

            /* fail safe */

            url_fskip(pb, ret);

            asf->packet_pos= url_ftell(&s->pb);

            ret = asf_get_packet(s);

            //printf("READ ASF PACKET  %d   r:%d   c:%d\n", ret, asf->packet_size_left, pc++);

            if (ret < 0 || url_feof(pb))

                return AVERROR_IO;

            asf->packet_time_start = 0;

            continue;

        }

        if (asf->packet_time_start == 0) {

            /* read frame header */

            int num = get_byte(pb);

            asf->packet_segments--;

            rsize++;

            asf->packet_key_frame = (num & 0x80) >> 7;

            asf->stream_index = asf->asfid2avid[num & 0x7f];

            // sequence should be ignored!

            DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);

            DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);

            DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);

//printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);

            if (asf->packet_replic_size > 1) {

                assert(asf->packet_replic_size >= 8);

                // it should be always at least 8 bytes - FIXME validate

                asf->packet_obj_size = get_le32(pb);

                asf->packet_frag_timestamp = get_le32(pb); // timestamp

                if (asf->packet_replic_size > 8)

                    url_fskip(pb, asf->packet_replic_size - 8);

                rsize += asf->packet_replic_size; // FIXME - check validity

            } else if (asf->packet_replic_size==1){

                // multipacket - frag_offset is begining timestamp

                asf->packet_time_start = asf->packet_frag_offset;

                asf->packet_frag_offset = 0;

                asf->packet_frag_timestamp = asf->packet_timestamp;

                asf->packet_time_delta = get_byte(pb);

                rsize++;

            }else{

                assert(asf->packet_replic_size==0);

            }

            if (asf->packet_flags & 0x01) {

                DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal

#undef DO_2BITS

                //printf("Fragsize %d\n", asf->packet_frag_size);

            } else {

                asf->packet_frag_size = asf->packet_size_left - rsize;

                //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);

            }

            if (asf->packet_replic_size == 1) {

                asf->packet_multi_size = asf->packet_frag_size;

                if (asf->packet_multi_size > asf->packet_size_left) {

                    asf->packet_segments = 0;

                    continue;

                }

            }

            asf->packet_size_left -= rsize;

            //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);

            if (asf->stream_index < 0

                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL

                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)

                ) {

                asf->packet_time_start = 0;

                /* unhandled packet (should not happen) */

                url_fskip(pb, asf->packet_frag_size);

                asf->packet_size_left -= asf->packet_frag_size;

                if(asf->stream_index < 0)

                    av_log(s, AV_LOG_ERROR, "ff asf skip %d  %d\n", asf->packet_frag_size, num & 0x7f);

                continue;

            }

            asf->asf_st = s->streams[asf->stream_index]->priv_data;

        }

        asf_st = asf->asf_st;

        if ((asf->packet_frag_offset != asf_st->frag_offset

             || (asf->packet_frag_offset

                 && asf->packet_seq != asf_st->seq)) // seq should be ignored

           ) {

            /* cannot continue current packet: free it */

            // FIXME better check if packet was already allocated

            av_log(s, AV_LOG_INFO, "ff asf parser skips: %d - %d     o:%d - %d    %d %d   fl:%d\n",

                   asf_st->pkt.size,

                   asf->packet_obj_size,

                   asf->packet_frag_offset, asf_st->frag_offset,

                   asf->packet_seq, asf_st->seq, asf->packet_frag_size);

            if (asf_st->pkt.size)

                av_free_packet(&asf_st->pkt);

            asf_st->frag_offset = 0;

            if (asf->packet_frag_offset != 0) {

                url_fskip(pb, asf->packet_frag_size);

                av_log(s, AV_LOG_INFO, "ff asf parser skipping %db\n", asf->packet_frag_size);

                asf->packet_size_left -= asf->packet_frag_size;

                continue;

            }

        }

        if (asf->packet_replic_size == 1) {

            // frag_offset is here used as the begining timestamp

            asf->packet_frag_timestamp = asf->packet_time_start;

            asf->packet_time_start += asf->packet_time_delta;

            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);

            asf->packet_size_left--;

            asf->packet_multi_size--;

            if (asf->packet_multi_size < asf->packet_obj_size)

            {

                asf->packet_time_start = 0;

                url_fskip(pb, asf->packet_multi_size);

                asf->packet_size_left -= asf->packet_multi_size;

                continue;

            }

            asf->packet_multi_size -= asf->packet_obj_size;

            //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);

        }

        if (asf_st->frag_offset == 0) {

            /* new packet */

            av_new_packet(&asf_st->pkt, asf->packet_obj_size);

            asf_st->seq = asf->packet_seq;

            asf_st->pkt.pts = asf->packet_frag_timestamp;

            asf_st->pkt.stream_index = asf->stream_index;

            asf_st->pkt.pos =

            asf_st->packet_pos= asf->packet_pos;

//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",

//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,

//s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);

            if (s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO)

                asf->packet_key_frame = 1;

            if (asf->packet_key_frame)

                asf_st->pkt.flags |= PKT_FLAG_KEY;

        }

        /* read data */

        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",

        //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,

        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);

        asf->packet_size_left -= asf->packet_frag_size;

        if (asf->packet_size_left < 0)

            continue;

        get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,

                   asf->packet_frag_size);

        asf_st->frag_offset += asf->packet_frag_size;

        /* test if whole packet is read */

        if (asf_st->frag_offset == asf_st->pkt.size) {

            /* return packet */

            if (asf_st->ds_span > 1) {

                /* packet descrambling */

                char* newdata = av_malloc(asf_st->pkt.size);

                if (newdata) {

                    int offset = 0;

                    while (offset < asf_st->pkt.size) {

                        int off = offset / asf_st->ds_chunk_size;

                        int row = off / asf_st->ds_span;

                        int col = off % asf_st->ds_span;

                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;

                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);

                        memcpy(newdata + offset,

                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,

                               asf_st->ds_chunk_size);

                        offset += asf_st->ds_chunk_size;

                    }

                    av_free(asf_st->pkt.data);

                    asf_st->pkt.data = newdata;

                }

            }

            asf_st->frag_offset = 0;

            memcpy(pkt, &asf_st->pkt, sizeof(AVPacket));

            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);

            asf_st->pkt.size = 0;

            asf_st->pkt.data = 0;

            break; // packet completed

        }

    }

    return 0;

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TiffContext *const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame *const p = &s->picture;

    const uint8_t *orig_buf = buf, *end_buf = buf + buf_size;

    unsigned off;

    int id, le, ret;

    int i, j, entries;

    int stride;

    unsigned soff, ssize;

    uint8_t *dst;

    //parse image header

    if (end_buf - buf < 8)

        return AVERROR_INVALIDDATA;

    id = AV_RL16(buf);

    buf += 2;

    if (id == 0x4949)

        le = 1;

    else if (id == 0x4D4D)

        le = 0;

    else {

        av_log(avctx, AV_LOG_ERROR, "TIFF header not found\n");

        return -1;

    }

    s->le = le;

    s->invert = 0;

    s->compr = TIFF_RAW;

    s->fill_order = 0;

    free_geotags(s);

    /* free existing metadata */

    av_dict_free(&s->picture.metadata);

    // As TIFF 6.0 specification puts it "An arbitrary but carefully chosen number

    // that further identifies the file as a TIFF file"

    if (tget_short(&buf, le) != 42) {

        av_log(avctx, AV_LOG_ERROR,

               "The answer to life, universe and everything is not correct!\n");

        return -1;

    }

    // Reset these pointers so we can tell if they were set this frame

    s->stripsizes = s->stripdata = NULL;

    /* parse image file directory */

    off = tget_long(&buf, le);

    if (off >= UINT_MAX - 14 || end_buf - orig_buf < off + 14) {

        av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n");

        return AVERROR_INVALIDDATA;

    }

    buf = orig_buf + off;

    entries = tget_short(&buf, le);

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

        if (tiff_decode_tag(s, orig_buf, buf, end_buf) < 0)

            return -1;

        buf += 12;

    }

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

        const char *keyname = get_geokey_name(s->geotags[i].key);

        if (!keyname) {

            av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key);

            continue;

        }

        if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) {

            av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key);

            continue;

        }

        ret = av_dict_set(&s->picture.metadata, keyname, s->geotags[i].val, 0);

        if (ret<0) {

            av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname);

            return ret;

        }

    }

    if (!s->stripdata && !s->stripoff) {

        av_log(avctx, AV_LOG_ERROR, "Image data is missing\n");

        return -1;

    }

    /* now we have the data and may start decoding */

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

        return ret;

    if (s->strips == 1 && !s->stripsize) {

        av_log(avctx, AV_LOG_WARNING, "Image data size missing\n");

        s->stripsize = buf_size - s->stripoff;

    }

    stride = p->linesize[0];

    dst = p->data[0];

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

        if (s->stripsizes) {

            if (s->stripsizes >= end_buf)

                return AVERROR_INVALIDDATA;

            ssize = tget(&s->stripsizes, s->sstype, s->le);

        } else

            ssize = s->stripsize;

        if (s->stripdata) {

            if (s->stripdata >= end_buf)

                return AVERROR_INVALIDDATA;

            soff = tget(&s->stripdata, s->sot, s->le);

        } else

            soff = s->stripoff;

        if (soff > buf_size || ssize > buf_size - soff) {

            av_log(avctx, AV_LOG_ERROR, "Invalid strip size/offset\n");

            return -1;

        }

        if (tiff_unpack_strip(s, dst, stride, orig_buf + soff, ssize,

                              FFMIN(s->rps, s->height - i)) < 0)

            break;

        dst += s->rps * stride;

    }

    if (s->predictor == 2) {

        dst = p->data[0];

        soff = s->bpp >> 3;

        ssize = s->width * soff;

        if (s->avctx->pix_fmt == PIX_FMT_RGB48LE ||

            s->avctx->pix_fmt == PIX_FMT_RGBA64LE) {

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

                for (j = soff; j < ssize; j += 2)

                    AV_WL16(dst + j, AV_RL16(dst + j) + AV_RL16(dst + j - soff));

                dst += stride;

            }

        } else if (s->avctx->pix_fmt == PIX_FMT_RGB48BE ||

                   s->avctx->pix_fmt == PIX_FMT_RGBA64BE) {

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

                for (j = soff; j < ssize; j += 2)

                    AV_WB16(dst + j, AV_RB16(dst + j) + AV_RB16(dst + j - soff));

                dst += stride;

            }

        } else {

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

                for (j = soff; j < ssize; j++)

                    dst[j] += dst[j - soff];

                dst += stride;

            }

        }

    }

    if (s->invert) {

        dst = s->picture.data[0];

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

            for (j = 0; j < s->picture.linesize[0]; j++)

                dst[j] = (s->avctx->pix_fmt == PIX_FMT_PAL8 ? (1<<s->bpp) - 1 : 255) - dst[j];

            dst += s->picture.linesize[0];

        }

    }

    *picture   = s->picture;

    *data_size = sizeof(AVPicture);

    return buf_size;

}


void ff_limiter_init_x86(LimiterDSPContext *dsp, int bpp)

{

    int cpu_flags = av_get_cpu_flags();

    if (ARCH_X86_64 && EXTERNAL_SSE2(cpu_flags)) {

        if (bpp <= 8) {

            dsp->limiter = ff_limiter_8bit_sse2;

        }

    }

    if (ARCH_X86_64 && EXTERNAL_SSE4(cpu_flags)) {

        if (bpp > 8) {

            dsp->limiter = ff_limiter_16bit_sse4;

        }

    }

}


void *virtqueue_pop(VirtQueue *vq, size_t sz)
{
    unsigned int i, head, max;
    hwaddr desc_pa = vq->vring.desc;
    VirtIODevice *vdev = vq->vdev;
    VirtQueueElement *elem;
    unsigned out_num, in_num;
    hwaddr addr[VIRTQUEUE_MAX_SIZE];
    struct iovec iov[VIRTQUEUE_MAX_SIZE];
    VRingDesc desc;
    if (virtio_queue_empty(vq)) {
        return NULL;
    /* Needed after virtio_queue_empty(), see comment in
     * virtqueue_num_heads(). */
    smp_rmb();
    /* When we start there are none of either input nor output. */
    out_num = in_num = 0;
    max = vq->vring.num;
    i = head = virtqueue_get_head(vq, vq->last_avail_idx++);
    if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {
        vring_set_avail_event(vq, vq->last_avail_idx);
    vring_desc_read(vdev, &desc, desc_pa, i);
    if (desc.flags & VRING_DESC_F_INDIRECT) {
        if (desc.len % sizeof(VRingDesc)) {
            error_report("Invalid size for indirect buffer table");
        /* loop over the indirect descriptor table */
        max = desc.len / sizeof(VRingDesc);
        desc_pa = desc.addr;
        i = 0;
        vring_desc_read(vdev, &desc, desc_pa, i);
    /* Collect all the descriptors */
    do {
        if (desc.flags & VRING_DESC_F_WRITE) {
            virtqueue_map_desc(&in_num, addr + out_num, iov + out_num,
                               VIRTQUEUE_MAX_SIZE - out_num, true, desc.addr, desc.len);
        } else {
            if (in_num) {
                error_report("Incorrect order for descriptors");
            virtqueue_map_desc(&out_num, addr, iov,
                               VIRTQUEUE_MAX_SIZE, false, desc.addr, desc.len);
        /* If we've got too many, that implies a descriptor loop. */
        if ((in_num + out_num) > max) {
            error_report("Looped descriptor");
    } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);
    /* Now copy what we have collected and mapped */
    elem = virtqueue_alloc_element(sz, out_num, in_num);
    elem->index = head;
    for (i = 0; i < out_num; i++) {
        elem->out_addr[i] = addr[i];
        elem->out_sg[i] = iov[i];
    for (i = 0; i < in_num; i++) {
        elem->in_addr[i] = addr[out_num + i];
        elem->in_sg[i] = iov[out_num + i];
    vq->inuse++;
    trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);
    return elem;


static int img_open_password(BlockBackend *blk, const char *filename,

                             int flags, bool quiet)

{

    BlockDriverState *bs;

    char password[256];

    bs = blk_bs(blk);

    if (bdrv_is_encrypted(bs) && bdrv_key_required(bs) &&

        !(flags & BDRV_O_NO_IO)) {

        qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);

        if (qemu_read_password(password, sizeof(password)) < 0) {

            error_report("No password given");

            return -1;

        }

        if (bdrv_set_key(bs, password) < 0) {

            error_report("invalid password");

            return -1;

        }

    }

    return 0;

}


static void dump(unsigned char *buf,size_t len)

{

	int i;

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

		if ((i&15)==0) printf("%04x  ",i);

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

		if ((i&15)==15) printf("\n");

	}

	printf("\n");

}


static int hls_decode_entry_wpp(AVCodecContext *avctxt, void *input_ctb_row, int job, int self_id)

{

    HEVCContext *s1  = avctxt->priv_data, *s;

    HEVCLocalContext *lc;

    int ctb_size    = 1<< s1->ps.sps->log2_ctb_size;

    int more_data   = 1;

    int *ctb_row_p    = input_ctb_row;

    int ctb_row = ctb_row_p[job];

    int ctb_addr_rs = s1->sh.slice_ctb_addr_rs + ctb_row * ((s1->ps.sps->width + ctb_size - 1) >> s1->ps.sps->log2_ctb_size);

    int ctb_addr_ts = s1->ps.pps->ctb_addr_rs_to_ts[ctb_addr_rs];

    int thread = ctb_row % s1->threads_number;

    int ret;

    s = s1->sList[self_id];

    lc = s->HEVClc;

    if(ctb_row) {

        ret = init_get_bits8(&lc->gb, s->data + s->sh.offset[ctb_row - 1], s->sh.size[ctb_row - 1]);

        if (ret < 0)

            return ret;

        ff_init_cabac_decoder(&lc->cc, s->data + s->sh.offset[(ctb_row)-1], s->sh.size[ctb_row - 1]);

    }

    while(more_data && ctb_addr_ts < s->ps.sps->ctb_size) {

        int x_ctb = (ctb_addr_rs % s->ps.sps->ctb_width) << s->ps.sps->log2_ctb_size;

        int y_ctb = (ctb_addr_rs / s->ps.sps->ctb_width) << s->ps.sps->log2_ctb_size;

        hls_decode_neighbour(s, x_ctb, y_ctb, ctb_addr_ts);

        ff_thread_await_progress2(s->avctx, ctb_row, thread, SHIFT_CTB_WPP);

        if (avpriv_atomic_int_get(&s1->wpp_err)){

            ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);

            return 0;

        }

        ff_hevc_cabac_init(s, ctb_addr_ts);

        hls_sao_param(s, x_ctb >> s->ps.sps->log2_ctb_size, y_ctb >> s->ps.sps->log2_ctb_size);

        more_data = hls_coding_quadtree(s, x_ctb, y_ctb, s->ps.sps->log2_ctb_size, 0);

        if (more_data < 0) {

            s->tab_slice_address[ctb_addr_rs] = -1;

            return more_data;

        }

        ctb_addr_ts++;

        ff_hevc_save_states(s, ctb_addr_ts);

        ff_thread_report_progress2(s->avctx, ctb_row, thread, 1);

        ff_hevc_hls_filters(s, x_ctb, y_ctb, ctb_size);

        if (!more_data && (x_ctb+ctb_size) < s->ps.sps->width && ctb_row != s->sh.num_entry_point_offsets) {

            return 0;

        }

        if ((x_ctb+ctb_size) >= s->ps.sps->width && (y_ctb+ctb_size) >= s->ps.sps->height ) {

            ff_hevc_hls_filter(s, x_ctb, y_ctb, ctb_size);

            ff_thread_report_progress2(s->avctx, ctb_row , thread, SHIFT_CTB_WPP);

            return ctb_addr_ts;

        }

        ctb_addr_rs       = s->ps.pps->ctb_addr_ts_to_rs[ctb_addr_ts];

        x_ctb+=ctb_size;

        if(x_ctb >= s->ps.sps->width) {

            break;

        }

    }

    return 0;

}


static int mpegts_raw_read_packet(AVFormatContext *s,

                                  AVPacket *pkt)

{

    MpegTSContext *ts = s->priv_data;

    int ret, i;

    int64_t pcr_h, next_pcr_h, pos;

    int pcr_l, next_pcr_l;

    uint8_t pcr_buf[12];

    uint8_t *data;

    if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)

        return AVERROR(ENOMEM);

    pkt->pos= avio_tell(s->pb);

    ret = read_packet(s, pkt->data, ts->raw_packet_size, &data);

    if (ret < 0) {

        av_free_packet(pkt);

        return ret;

    }

    if (data != pkt->data)

        memcpy(pkt->data, data, ts->raw_packet_size);

    finished_reading_packet(s, ts->raw_packet_size);

    if (ts->mpeg2ts_compute_pcr) {

        /* compute exact PCR for each packet */

        if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {

            /* we read the next PCR (XXX: optimize it by using a bigger buffer */

            pos = avio_tell(s->pb);

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

                avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);

                avio_read(s->pb, pcr_buf, 12);

                if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {

                    /* XXX: not precise enough */

                    ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /

                        (i + 1);

                    break;

                }

            }

            avio_seek(s->pb, pos, SEEK_SET);

            /* no next PCR found: we use previous increment */

            ts->cur_pcr = pcr_h * 300 + pcr_l;

        }

        pkt->pts = ts->cur_pcr;

        pkt->duration = ts->pcr_incr;

        ts->cur_pcr += ts->pcr_incr;

    }

    pkt->stream_index = 0;

    return 0;

}


static inline void RENAME(rgb24tobgr16)(const uint8_t *src, uint8_t *dst, int src_size)

{

    const uint8_t *s = src;

    const uint8_t *end;

    const uint8_t *mm_end;

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

    __asm__ volatile(PREFETCH"    %0"::"m"(*src):"memory");

    __asm__ volatile(

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

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

        ::"m"(red_16mask),"m"(green_16mask));

    mm_end = end - 11;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"    32%1           \n\t"

            "movd          %1, %%mm0    \n\t"

            "movd         3%1, %%mm3    \n\t"

            "punpckldq    6%1, %%mm0    \n\t"

            "punpckldq    9%1, %%mm3    \n\t"

            "movq       %%mm0, %%mm1    \n\t"

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

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

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

            "psrlq         $3, %%mm0    \n\t"

            "psrlq         $3, %%mm3    \n\t"

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

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

            "psrlq         $5, %%mm1    \n\t"

            "psrlq         $5, %%mm4    \n\t"

            "pand       %%mm6, %%mm1    \n\t"

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

            "psrlq         $8, %%mm2    \n\t"

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

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

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

            "por        %%mm1, %%mm0    \n\t"

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

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

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

            "psllq        $16, %%mm3    \n\t"

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

            MOVNTQ"     %%mm0, %0       \n\t"

            :"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

        d += 4;

        s += 12;

    }

    __asm__ volatile(SFENCE:::"memory");

    __asm__ volatile(EMMS:::"memory");

    while (s < end) {

        const int b = *s++;

        const int g = *s++;

        const int r = *s++;

        *d++ = (b>>3) | ((g&0xFC)<<3) | ((r&0xF8)<<8);

    }

}


static void gen_mfdcrx(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    /* NIP cannot be restored if the memory exception comes from an helper */

    gen_update_nip(ctx, ctx->nip - 4);

    gen_helper_load_dcr(cpu_gpr[rD(ctx->opcode)], cpu_env,

                        cpu_gpr[rA(ctx->opcode)]);

    /* Note: Rc update flag set leads to undefined state of Rc0 */

#endif

}


static void png_save2(const char *filename, uint32_t *bitmap, int w, int h)

{

    int x, y, v;

    FILE *f;

    char fname[40], fname2[40];

    char command[1024];

    snprintf(fname, 40, "%s.ppm", filename);

    f = fopen(fname, "w");

    if (!f) {

        perror(fname);

        exit(1);

    }

    fprintf(f, "P6\n"

            "%d %d\n"

            "%d\n",

            w, h, 255);

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

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

            v = bitmap[y * w + x];

            putc((v >> 16) & 0xff, f);

            putc((v >> 8) & 0xff, f);

            putc((v >> 0) & 0xff, f);

        }

    }

    fclose(f);

    snprintf(fname2, 40, "%s-a.pgm", filename);

    f = fopen(fname2, "w");

    if (!f) {

        perror(fname2);

        exit(1);

    }

    fprintf(f, "P5\n"

            "%d %d\n"

            "%d\n",

            w, h, 255);

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

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

            v = bitmap[y * w + x];

            putc((v >> 24) & 0xff, f);

        }

    }

    fclose(f);

    snprintf(command, 1024, "pnmtopng -alpha %s %s > %s.png 2> /dev/null", fname2, fname, filename);

    system(command);

    snprintf(command, 1024, "rm %s %s", fname, fname2);

    system(command);

}


static int spdif_write_packet(struct AVFormatContext *s, AVPacket *pkt)

{

    IEC61937Context *ctx = s->priv_data;

    int ret, padding;

    ctx->out_buf = pkt->data;

    ctx->out_bytes = pkt->size;

    ctx->length_code = FFALIGN(pkt->size, 2) << 3;

    ctx->use_preamble = 1;

    ctx->extra_bswap = 0;

    ret = ctx->header_info(s, pkt);

    if (ret < 0)

        return ret;

    if (!ctx->pkt_offset)

        return 0;

    padding = (ctx->pkt_offset - ctx->use_preamble * BURST_HEADER_SIZE - ctx->out_bytes) & ~1;

    if (padding < 0) {

        av_log(s, AV_LOG_ERROR, "bitrate is too high\n");

        return AVERROR(EINVAL);

    }

    if (ctx->use_preamble) {

        put_le16(s->pb, SYNCWORD1);       //Pa

        put_le16(s->pb, SYNCWORD2);       //Pb

        put_le16(s->pb, ctx->data_type);  //Pc

        put_le16(s->pb, ctx->length_code);//Pd

    }

    if (HAVE_BIGENDIAN ^ ctx->extra_bswap) {

    put_buffer(s->pb, ctx->out_buf, ctx->out_bytes & ~1);

    } else {

    av_fast_malloc(&ctx->buffer, &ctx->buffer_size, ctx->out_bytes + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!ctx->buffer)

        return AVERROR(ENOMEM);

    ff_spdif_bswap_buf16((uint16_t *)ctx->buffer, (uint16_t *)ctx->out_buf, ctx->out_bytes >> 1);

    put_buffer(s->pb, ctx->buffer, ctx->out_bytes & ~1);

    }

    if (ctx->out_bytes & 1)

        put_be16(s->pb, ctx->out_buf[ctx->out_bytes - 1]);

    put_nbyte(s->pb, 0, padding);

    av_log(s, AV_LOG_DEBUG, "type=%x len=%i pkt_offset=%i\n",

           ctx->data_type, ctx->out_bytes, ctx->pkt_offset);

    put_flush_packet(s->pb);

    return 0;

}


av_cold void ff_rl_init(RLTable *rl,

                        uint8_t static_store[2][2 * MAX_RUN + MAX_LEVEL + 3])

{

    int8_t  max_level[MAX_RUN + 1], max_run[MAX_LEVEL + 1];

    uint8_t index_run[MAX_RUN + 1];

    int last, run, level, start, end, i;

    /* If table is static, we can quit if rl->max_level[0] is not NULL */

    if (static_store && rl->max_level[0])

        return;

    /* compute max_level[], max_run[] and index_run[] */

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

        if (last == 0) {

            start = 0;

            end = rl->last;

        } else {

            start = rl->last;

            end = rl->n;

        }

        memset(max_level, 0, MAX_RUN + 1);

        memset(max_run, 0, MAX_LEVEL + 1);

        memset(index_run, rl->n, MAX_RUN + 1);

        for (i = start; i < end; i++) {

            run   = rl->table_run[i];

            level = rl->table_level[i];

            if (index_run[run] == rl->n)

                index_run[run] = i;

            if (level > max_level[run])

                max_level[run] = level;

            if (run > max_run[level])

                max_run[level] = run;

        }

        if (static_store)

            rl->max_level[last] = static_store[last];

        else

            rl->max_level[last] = av_malloc(MAX_RUN + 1);

        memcpy(rl->max_level[last], max_level, MAX_RUN + 1);

        if (static_store)

            rl->max_run[last]   = static_store[last] + MAX_RUN + 1;

        else

            rl->max_run[last]   = av_malloc(MAX_LEVEL + 1);

        memcpy(rl->max_run[last], max_run, MAX_LEVEL + 1);

        if (static_store)

            rl->index_run[last] = static_store[last] + MAX_RUN + MAX_LEVEL + 2;

        else

            rl->index_run[last] = av_malloc(MAX_RUN + 1);

        memcpy(rl->index_run[last], index_run, MAX_RUN + 1);

    }

}


static void gen_slbie(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_slbie(cpu_env, cpu_gpr[rB(ctx->opcode)]);

#endif

}


static int usb_hid_handle_data(USBDevice *dev, USBPacket *p)

{

    USBHIDState *s = (USBHIDState *)dev;

    int ret = 0;

    switch(p->pid) {

    case USB_TOKEN_IN:

        if (p->devep == 1) {

            int64_t curtime = qemu_get_clock_ns(vm_clock);

            if (!s->changed && (!s->idle || s->next_idle_clock - curtime > 0))

                return USB_RET_NAK;

            usb_hid_set_next_idle(s, curtime);

            if (s->kind == USB_MOUSE || s->kind == USB_TABLET) {

                ret = usb_pointer_poll(s, p->data, p->len);

            }

            else if (s->kind == USB_KEYBOARD) {

                ret = usb_keyboard_poll(s, p->data, p->len);

            }

            s->changed = s->n > 0;

        } else {

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


int av_opencl_init(AVDictionary *options, AVOpenCLExternalEnv *ext_opencl_env)

{

    int ret = 0;

    AVDictionaryEntry *opt_build_entry;

    AVDictionaryEntry *opt_platform_entry;

    AVDictionaryEntry *opt_device_entry;

    LOCK_OPENCL

    if (!gpu_env.init_count) {

        opt_platform_entry = av_dict_get(options, "platform_idx", NULL, 0);

        opt_device_entry   = av_dict_get(options, "device_idx", NULL, 0);

        /* initialize devices, context, command_queue */

        gpu_env.usr_spec_dev_info.platform_idx = -1;

        gpu_env.usr_spec_dev_info.dev_idx = -1;

        if (opt_platform_entry) {

            gpu_env.usr_spec_dev_info.platform_idx = strtol(opt_platform_entry->value, NULL, 10);

        }

        if (opt_device_entry) {

            gpu_env.usr_spec_dev_info.dev_idx = strtol(opt_device_entry->value, NULL, 10);

        }

        ret = init_opencl_env(&gpu_env, ext_opencl_env);

        if (ret < 0)

            goto end;

    }

    /*initialize program, kernel_name, kernel_count*/

    opt_build_entry = av_dict_get(options, "build_options", NULL, 0);

    if (opt_build_entry)

        ret = compile_kernel_file(&gpu_env, opt_build_entry->value);

    else

        ret = compile_kernel_file(&gpu_env, NULL);

    if (ret < 0)

        goto end;

    av_assert1(gpu_env.kernel_code_count > 0);

    gpu_env.init_count++;

end:

    UNLOCK_OPENCL

    return ret;

}


static int msf_read_header(AVFormatContext *s)

{

    unsigned codec, align, size;

    AVStream *st;

    avio_skip(s->pb, 4);

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;

    codec                  = avio_rb32(s->pb);

    st->codec->channels    = avio_rb32(s->pb);

    if (st->codec->channels <= 0)

        return AVERROR_INVALIDDATA;

    size = avio_rb32(s->pb);

    st->codec->sample_rate = avio_rb32(s->pb);

    if (st->codec->sample_rate <= 0)

        return AVERROR_INVALIDDATA;

    align = avio_rb32(s->pb) ;

    if (align > INT_MAX / st->codec->channels)

        return AVERROR_INVALIDDATA;

    st->codec->block_align = align;

    switch (codec) {

    case 0: st->codec->codec_id = AV_CODEC_ID_PCM_S16BE; break;

    case 3: st->codec->block_align = 16 * st->codec->channels;

            st->codec->codec_id = AV_CODEC_ID_ADPCM_PSX; break;

    case 7: st->need_parsing = AVSTREAM_PARSE_FULL_RAW;

            st->codec->codec_id = AV_CODEC_ID_MP3;       break;

    default:

            avpriv_request_sample(s, "Codec %d", codec);

            return AVERROR_PATCHWELCOME;

    }

    st->duration = av_get_audio_frame_duration(st->codec, size);

    avio_skip(s->pb, 0x40 - avio_tell(s->pb));

    avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);

    return 0;

}


void dump_exec_info(FILE *f, fprintf_function cpu_fprintf)

{

    int i, target_code_size, max_target_code_size;

    int direct_jmp_count, direct_jmp2_count, cross_page;

    TranslationBlock *tb;

    target_code_size = 0;

    max_target_code_size = 0;

    cross_page = 0;

    direct_jmp_count = 0;

    direct_jmp2_count = 0;

    for (i = 0; i < tcg_ctx.tb_ctx.nb_tbs; i++) {

        tb = &tcg_ctx.tb_ctx.tbs[i];

        target_code_size += tb->size;

        if (tb->size > max_target_code_size) {

            max_target_code_size = tb->size;

        }

        if (tb->page_addr[1] != -1) {

            cross_page++;

        }

        if (tb->tb_next_offset[0] != 0xffff) {

            direct_jmp_count++;

            if (tb->tb_next_offset[1] != 0xffff) {

                direct_jmp2_count++;

            }

        }

    }

    /* XXX: avoid using doubles ? */

    cpu_fprintf(f, "Translation buffer state:\n");

    cpu_fprintf(f, "gen code size       %td/%zd\n",

                tcg_ctx.code_gen_ptr - tcg_ctx.code_gen_buffer,

                tcg_ctx.code_gen_buffer_max_size);

    cpu_fprintf(f, "TB count            %d/%d\n",

            tcg_ctx.tb_ctx.nb_tbs, tcg_ctx.code_gen_max_blocks);

    cpu_fprintf(f, "TB avg target size  %d max=%d bytes\n",

            tcg_ctx.tb_ctx.nb_tbs ? target_code_size /

                    tcg_ctx.tb_ctx.nb_tbs : 0,

            max_target_code_size);

    cpu_fprintf(f, "TB avg host size    %td bytes (expansion ratio: %0.1f)\n",

            tcg_ctx.tb_ctx.nb_tbs ? (tcg_ctx.code_gen_ptr -

                                     tcg_ctx.code_gen_buffer) /

                                     tcg_ctx.tb_ctx.nb_tbs : 0,

                target_code_size ? (double) (tcg_ctx.code_gen_ptr -

                                             tcg_ctx.code_gen_buffer) /

                                             target_code_size : 0);

    cpu_fprintf(f, "cross page TB count %d (%d%%)\n", cross_page,

            tcg_ctx.tb_ctx.nb_tbs ? (cross_page * 100) /

                                    tcg_ctx.tb_ctx.nb_tbs : 0);

    cpu_fprintf(f, "direct jump count   %d (%d%%) (2 jumps=%d %d%%)\n",

                direct_jmp_count,

                tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp_count * 100) /

                        tcg_ctx.tb_ctx.nb_tbs : 0,

                direct_jmp2_count,

                tcg_ctx.tb_ctx.nb_tbs ? (direct_jmp2_count * 100) /

                        tcg_ctx.tb_ctx.nb_tbs : 0);

    cpu_fprintf(f, "\nStatistics:\n");

    cpu_fprintf(f, "TB flush count      %d\n", tcg_ctx.tb_ctx.tb_flush_count);

    cpu_fprintf(f, "TB invalidate count %d\n",

            tcg_ctx.tb_ctx.tb_phys_invalidate_count);

    cpu_fprintf(f, "TLB flush count     %d\n", tlb_flush_count);

    tcg_dump_info(f, cpu_fprintf);

}