static int decode_subframe_fixed(FLACContext *s, int channel, int pred_order)

{

    int i;

    av_log(s->avctx, AV_LOG_DEBUG, "  SUBFRAME FIXED\n");

    /* warm up samples */

    av_log(s->avctx, AV_LOG_DEBUG, "   warm up samples: %d\n", pred_order);

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

    {

        s->decoded[channel][i] = get_sbits(&s->gb, s->curr_bps);

//        av_log(s->avctx, AV_LOG_DEBUG, "    %d: %d\n", i, s->decoded[channel][i]);

    }

    if (decode_residuals(s, channel, pred_order) < 0)

        return -1;

    switch(pred_order)

    {

        case 0:

            break;

        case 1:

            for (i = pred_order; i < s->blocksize; i++)

                s->decoded[channel][i] +=   s->decoded[channel][i-1];

            break;

        case 2:

            for (i = pred_order; i < s->blocksize; i++)

                s->decoded[channel][i] += 2*s->decoded[channel][i-1]

                                          - s->decoded[channel][i-2];

            break;

        case 3:

            for (i = pred_order; i < s->blocksize; i++)

                s->decoded[channel][i] += 3*s->decoded[channel][i-1]

                                        - 3*s->decoded[channel][i-2]

                                        +   s->decoded[channel][i-3];

            break;

        case 4:

            for (i = pred_order; i < s->blocksize; i++)

                s->decoded[channel][i] += 4*s->decoded[channel][i-1]

                                        - 6*s->decoded[channel][i-2]

                                        + 4*s->decoded[channel][i-3]

                                        -   s->decoded[channel][i-4];

            break;

        default:

            av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);

            return -1;

    }

    return 0;

}


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

                            const AVFrame *frame, int *got_packet_ptr)

{

    AACEncContext *s = avctx->priv_data;

    float **samples = s->planar_samples, *samples2, *la, *overlap;

    ChannelElement *cpe;

    SingleChannelElement *sce;

    IndividualChannelStream *ics;

    int i, its, ch, w, chans, tag, start_ch, ret, frame_bits;

    int target_bits, rate_bits, too_many_bits, too_few_bits;

    int ms_mode = 0, is_mode = 0, tns_mode = 0, pred_mode = 0;

    int chan_el_counter[4];

    FFPsyWindowInfo windows[AAC_MAX_CHANNELS];

    if (s->last_frame == 2)

        return 0;

    /* add current frame to queue */

    if (frame) {

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

            return ret;

    }

    copy_input_samples(s, frame);

    if (s->psypp)

        ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);

    if (!avctx->frame_number)

        return 0;

    start_ch = 0;

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

        FFPsyWindowInfo* wi = windows + start_ch;

        tag      = s->chan_map[i+1];

        chans    = tag == TYPE_CPE ? 2 : 1;

        cpe      = &s->cpe[i];

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

            float clip_avoidance_factor;

            sce = &cpe->ch[ch];

            ics = &sce->ics;

            s->cur_channel = start_ch + ch;

            overlap  = &samples[s->cur_channel][0];

            samples2 = overlap + 1024;

            la       = samples2 + (448+64);

            if (!frame)

                la = NULL;

            if (tag == TYPE_LFE) {

                wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;

                wi[ch].window_shape   = 0;

                wi[ch].num_windows    = 1;

                wi[ch].grouping[0]    = 1;

                /* Only the lowest 12 coefficients are used in a LFE channel.

                 * The expression below results in only the bottom 8 coefficients

                 * being used for 11.025kHz to 16kHz sample rates.

                 */

                ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;

            } else {

                wi[ch] = s->psy.model->window(&s->psy, samples2, la, s->cur_channel,

                                              ics->window_sequence[0]);

            }

            ics->window_sequence[1] = ics->window_sequence[0];

            ics->window_sequence[0] = wi[ch].window_type[0];

            ics->use_kb_window[1]   = ics->use_kb_window[0];

            ics->use_kb_window[0]   = wi[ch].window_shape;

            ics->num_windows        = wi[ch].num_windows;

            ics->swb_sizes          = s->psy.bands    [ics->num_windows == 8];

            ics->num_swb            = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];

            ics->max_sfb            = FFMIN(ics->max_sfb, ics->num_swb);

            ics->swb_offset         = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?

                                        ff_swb_offset_128 [s->samplerate_index]:

                                        ff_swb_offset_1024[s->samplerate_index];

            ics->tns_max_bands      = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?

                                        ff_tns_max_bands_128 [s->samplerate_index]:

                                        ff_tns_max_bands_1024[s->samplerate_index];

            clip_avoidance_factor = 0.0f;

            for (w = 0; w < ics->num_windows; w++)

                ics->group_len[w] = wi[ch].grouping[w];

            for (w = 0; w < ics->num_windows; w++) {

                if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {

                    ics->window_clipping[w] = 1;

                    clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);

                } else {

                    ics->window_clipping[w] = 0;

                }

            }

            if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {

                ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;

            } else {

                ics->clip_avoidance_factor = 1.0f;

            }

            apply_window_and_mdct(s, sce, overlap);

            if (s->options.ltp && s->coder->update_ltp) {

                s->coder->update_ltp(s, sce);

                apply_window[sce->ics.window_sequence[0]](s->fdsp, sce, &sce->ltp_state[0]);

                s->mdct1024.mdct_calc(&s->mdct1024, sce->lcoeffs, sce->ret_buf);

            }

            if (isnan(cpe->ch->coeffs[0])) {

                av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");

                return AVERROR(EINVAL);

            }

            avoid_clipping(s, sce);

        }

        start_ch += chans;

    }

    if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)

        return ret;

    frame_bits = its = 0;

    do {

        init_put_bits(&s->pb, avpkt->data, avpkt->size);

        if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & AV_CODEC_FLAG_BITEXACT))

            put_bitstream_info(s, LIBAVCODEC_IDENT);

        start_ch = 0;

        target_bits = 0;

        memset(chan_el_counter, 0, sizeof(chan_el_counter));

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

            FFPsyWindowInfo* wi = windows + start_ch;

            const float *coeffs[2];

            tag      = s->chan_map[i+1];

            chans    = tag == TYPE_CPE ? 2 : 1;

            cpe      = &s->cpe[i];

            cpe->common_window = 0;

            memset(cpe->is_mask, 0, sizeof(cpe->is_mask));

            memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));

            put_bits(&s->pb, 3, tag);

            put_bits(&s->pb, 4, chan_el_counter[tag]++);

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

                sce = &cpe->ch[ch];

                coeffs[ch] = sce->coeffs;

                sce->ics.predictor_present = 0;

                sce->ics.ltp.present = 0;

                memset(sce->ics.ltp.used, 0, sizeof(sce->ics.ltp.used));

                memset(sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));

                memset(&sce->tns, 0, sizeof(TemporalNoiseShaping));

                for (w = 0; w < 128; w++)

                    if (sce->band_type[w] > RESERVED_BT)

                        sce->band_type[w] = 0;

            }

            s->psy.bitres.alloc = -1;

            s->psy.bitres.bits = s->last_frame_pb_count / s->channels;

            s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);

            if (s->psy.bitres.alloc > 0) {

                /* Lambda unused here on purpose, we need to take psy's unscaled allocation */

                target_bits += s->psy.bitres.alloc

                    * (s->lambda / (avctx->global_quality ? avctx->global_quality : 120));

                s->psy.bitres.alloc /= chans;

            }

            s->cur_type = tag;

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

                s->cur_channel = start_ch + ch;

                if (s->options.pns && s->coder->mark_pns)

                    s->coder->mark_pns(s, avctx, &cpe->ch[ch]);

                s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);

            }

            if (chans > 1

                && wi[0].window_type[0] == wi[1].window_type[0]

                && wi[0].window_shape   == wi[1].window_shape) {

                cpe->common_window = 1;

                for (w = 0; w < wi[0].num_windows; w++) {

                    if (wi[0].grouping[w] != wi[1].grouping[w]) {

                        cpe->common_window = 0;

                        break;

                    }

                }

            }

            for (ch = 0; ch < chans; ch++) { /* TNS and PNS */

                sce = &cpe->ch[ch];

                s->cur_channel = start_ch + ch;

                if (s->options.tns && s->coder->search_for_tns)

                    s->coder->search_for_tns(s, sce);

                if (s->options.tns && s->coder->apply_tns_filt)

                    s->coder->apply_tns_filt(s, sce);

                if (sce->tns.present)

                    tns_mode = 1;

                if (s->options.pns && s->coder->search_for_pns)

                    s->coder->search_for_pns(s, avctx, sce);

            }

            s->cur_channel = start_ch;

            if (s->options.intensity_stereo) { /* Intensity Stereo */

                if (s->coder->search_for_is)

                    s->coder->search_for_is(s, avctx, cpe);

                if (cpe->is_mode) is_mode = 1;

                apply_intensity_stereo(cpe);

            }

            if (s->options.pred) { /* Prediction */

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

                    sce = &cpe->ch[ch];

                    s->cur_channel = start_ch + ch;

                    if (s->options.pred && s->coder->search_for_pred)

                        s->coder->search_for_pred(s, sce);

                    if (cpe->ch[ch].ics.predictor_present) pred_mode = 1;

                }

                if (s->coder->adjust_common_pred)

                    s->coder->adjust_common_pred(s, cpe);

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

                    sce = &cpe->ch[ch];

                    s->cur_channel = start_ch + ch;

                    if (s->options.pred && s->coder->apply_main_pred)

                        s->coder->apply_main_pred(s, sce);

                }

                s->cur_channel = start_ch;

            }

            if (s->options.mid_side) { /* Mid/Side stereo */

                if (s->options.mid_side == -1 && s->coder->search_for_ms)

                    s->coder->search_for_ms(s, cpe);

                else if (cpe->common_window)

                    memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask));

                apply_mid_side_stereo(cpe);

            }

            adjust_frame_information(cpe, chans);

            if (s->options.ltp) { /* LTP */

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

                    sce = &cpe->ch[ch];

                    s->cur_channel = start_ch + ch;

                    if (s->coder->search_for_ltp)

                        s->coder->search_for_ltp(s, sce, cpe->common_window);

                    if (sce->ics.ltp.present) pred_mode = 1;

                }

                s->cur_channel = start_ch;

                if (s->coder->adjust_common_ltp)

                    s->coder->adjust_common_ltp(s, cpe);

            }

            if (chans == 2) {

                put_bits(&s->pb, 1, cpe->common_window);

                if (cpe->common_window) {

                    put_ics_info(s, &cpe->ch[0].ics);

                    if (s->coder->encode_main_pred)

                        s->coder->encode_main_pred(s, &cpe->ch[0]);

                    if (s->coder->encode_ltp_info)

                        s->coder->encode_ltp_info(s, &cpe->ch[0], 1);

                    encode_ms_info(&s->pb, cpe);

                    if (cpe->ms_mode) ms_mode = 1;

                }

            }

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

                s->cur_channel = start_ch + ch;

                encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);

            }

            start_ch += chans;

        }

        if (avctx->flags & CODEC_FLAG_QSCALE) {

            /* When using a constant Q-scale, don't mess with lambda */

            break;

        }

        /* rate control stuff

         * allow between the nominal bitrate, and what psy's bit reservoir says to target

         * but drift towards the nominal bitrate always

         */

        frame_bits = put_bits_count(&s->pb);

        rate_bits = avctx->bit_rate * 1024 / avctx->sample_rate;

        rate_bits = FFMIN(rate_bits, 6144 * s->channels - 3);

        too_many_bits = FFMAX(target_bits, rate_bits);

        too_many_bits = FFMIN(too_many_bits, 6144 * s->channels - 3);

        too_few_bits = FFMIN(FFMAX(rate_bits - rate_bits/4, target_bits), too_many_bits);

        /* When using ABR, be strict (but only for increasing) */

        too_few_bits = too_few_bits - too_few_bits/8;

        too_many_bits = too_many_bits + too_many_bits/2;

        if (   its == 0 /* for steady-state Q-scale tracking */

            || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))

            || frame_bits >= 6144 * s->channels - 3  )

        {

            float ratio = ((float)rate_bits) / frame_bits;

            if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {

                /*

                 * This path is for steady-state Q-scale tracking

                 * When frame bits fall within the stable range, we still need to adjust

                 * lambda to maintain it like so in a stable fashion (large jumps in lambda

                 * create artifacts and should be avoided), but slowly

                 */

                ratio = sqrtf(sqrtf(ratio));

                ratio = av_clipf(ratio, 0.9f, 1.1f);

            } else {

                /* Not so fast though */

                ratio = sqrtf(ratio);

            }

            s->lambda = FFMIN(s->lambda * ratio, 65536.f);

            /* Keep iterating if we must reduce and lambda is in the sky */

            if (ratio > 0.9f && ratio < 1.1f) {

                break;

            } else {

                if (is_mode || ms_mode || tns_mode || pred_mode) {

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

                        // Must restore coeffs

                        chans = tag == TYPE_CPE ? 2 : 1;

                        cpe = &s->cpe[i];

                        for (ch = 0; ch < chans; ch++)

                            memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));

                    }

                }

                its++;

            }

        } else {

            break;

        }

    } while (1);

    if (s->options.ltp && s->coder->ltp_insert_new_frame)

        s->coder->ltp_insert_new_frame(s);

    put_bits(&s->pb, 3, TYPE_END);

    flush_put_bits(&s->pb);

    s->last_frame_pb_count = put_bits_count(&s->pb);

    s->lambda_sum += s->lambda;

    s->lambda_count++;

    if (!frame)

        s->last_frame++;

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

                       &avpkt->duration);

    avpkt->size = put_bits_count(&s->pb) >> 3;

    *got_packet_ptr = 1;

    return 0;

}


void virtio_config_writel(VirtIODevice *vdev, uint32_t addr, uint32_t data)

{

    VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);

    uint32_t val = data;

    if (addr > (vdev->config_len - sizeof(val)))

        return;

    stl_p(vdev->config + addr, val);

    if (k->set_config) {

        k->set_config(vdev, vdev->config);

    }

}


int bdrv_open_image(BlockDriverState **pbs, const char *filename,

                    QDict *options, const char *bdref_key, int flags,

                    bool allow_none, Error **errp)

{

    QDict *image_options;

    int ret;

    char *bdref_key_dot;

    const char *reference;

    assert(pbs);

    assert(*pbs == NULL);

    bdref_key_dot = g_strdup_printf("%s.", bdref_key);

    qdict_extract_subqdict(options, &image_options, bdref_key_dot);

    g_free(bdref_key_dot);

    reference = qdict_get_try_str(options, bdref_key);

    if (!filename && !reference && !qdict_size(image_options)) {

        if (allow_none) {

            ret = 0;

        } else {

            error_setg(errp, "A block device must be specified for \"%s\"",

                       bdref_key);

            ret = -EINVAL;

        }

        goto done;

    }

    ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);

done:

    qdict_del(options, bdref_key);

    return ret;

}


static void musb_packet(MUSBState *s, MUSBEndPoint *ep,

                int epnum, int pid, int len, USBCallback cb, int dir)

{

    int ret;

    int idx = epnum && dir;

    int ttype;

    /* ep->type[0,1] contains:

     * in bits 7:6 the speed (0 - invalid, 1 - high, 2 - full, 3 - slow)

     * in bits 5:4 the transfer type (BULK / INT)

     * in bits 3:0 the EP num

     */

    ttype = epnum ? (ep->type[idx] >> 4) & 3 : 0;

    ep->timeout[dir] = musb_timeout(ttype,

                    ep->type[idx] >> 6, ep->interval[idx]);

    ep->interrupt[dir] = ttype == USB_ENDPOINT_XFER_INT;

    ep->delayed_cb[dir] = cb;

    ep->packey[dir].p.pid = pid;

    /* A wild guess on the FADDR semantics... */

    ep->packey[dir].p.devaddr = ep->faddr[idx];

    ep->packey[dir].p.devep = ep->type[idx] & 0xf;

    ep->packey[dir].p.data = (void *) ep->buf[idx];

    ep->packey[dir].p.len = len;

    ep->packey[dir].ep = ep;

    ep->packey[dir].dir = dir;

    if (s->port.dev)

        ret = usb_handle_packet(s->port.dev, &ep->packey[dir].p);

    else

        ret = USB_RET_NODEV;

    if (ret == USB_RET_ASYNC) {

        ep->status[dir] = len;

        return;

    }

    ep->status[dir] = ret;

    musb_schedule_cb(&s->port, &ep->packey[dir].p);

}


bool st_set_trace_file(const char *file)

{

    st_set_trace_file_enabled(false);

    free(trace_file_name);

    if (!file) {

        if (asprintf(&trace_file_name, CONFIG_TRACE_FILE, getpid()) < 0) {

            trace_file_name = NULL;

            return false;

        }

    } else {

        if (asprintf(&trace_file_name, "%s", file) < 0) {

            trace_file_name = NULL;

            return false;

        }

    }

    st_set_trace_file_enabled(true);

    return true;

}


static int kvm_client_migration_log(struct CPUPhysMemoryClient *client,

                                    int enable)

{

    return kvm_set_migration_log(enable);

}


static AVFilterContext *parse_filter(const char **buf, AVFilterGraph *graph,

                                     int index, AVClass *log_ctx)

{

    char *opts = NULL;

    char *name = consume_string(buf);

    if(**buf == '=') {

        (*buf)++;

        opts = consume_string(buf);

    }

    return create_filter(graph, index, name, opts, log_ctx);

}


static AVCodec *AVCodecInitialize(enum AVCodecID codec_id)

{

    AVCodec *res;

    avcodec_register_all();

    av_log_set_level(AV_LOG_PANIC);

    res = avcodec_find_decoder(codec_id);

    if (!res)

        error("Failed to find decoder");

    return res;

}


static int poll_rest(gboolean poll_msgs, HANDLE *handles, gint nhandles,

                     GPollFD *fds, guint nfds, gint timeout)

{

    DWORD ready;

    GPollFD *f;

    int recursed_result;

    if (poll_msgs) {

        /* Wait for either messages or handles

         * -> Use MsgWaitForMultipleObjectsEx

         */

        ready = MsgWaitForMultipleObjectsEx(nhandles, handles, timeout,

                                            QS_ALLINPUT, MWMO_ALERTABLE);

        if (ready == WAIT_FAILED) {

            gchar *emsg = g_win32_error_message(GetLastError());

            g_warning("MsgWaitForMultipleObjectsEx failed: %s", emsg);

            g_free(emsg);

        }

    } else if (nhandles == 0) {

        /* No handles to wait for, just the timeout */

        if (timeout == INFINITE) {

            ready = WAIT_FAILED;

        } else {

            SleepEx(timeout, TRUE);

            ready = WAIT_TIMEOUT;

        }

    } else {

        /* Wait for just handles

         * -> Use WaitForMultipleObjectsEx

         */

        ready =

            WaitForMultipleObjectsEx(nhandles, handles, FALSE, timeout, TRUE);

        if (ready == WAIT_FAILED) {

            gchar *emsg = g_win32_error_message(GetLastError());

            g_warning("WaitForMultipleObjectsEx failed: %s", emsg);

            g_free(emsg);

        }

    }

    if (ready == WAIT_FAILED) {

        return -1;

    } else if (ready == WAIT_TIMEOUT || ready == WAIT_IO_COMPLETION) {

        return 0;

    } else if (poll_msgs && ready == WAIT_OBJECT_0 + nhandles) {

        for (f = fds; f < &fds[nfds]; ++f) {

            if (f->fd == G_WIN32_MSG_HANDLE && f->events & G_IO_IN) {

                f->revents |= G_IO_IN;

            }

        }

        /* If we have a timeout, or no handles to poll, be satisfied

         * with just noticing we have messages waiting.

         */

        if (timeout != 0 || nhandles == 0) {

            return 1;

        }

        /* If no timeout and handles to poll, recurse to poll them,

         * too.

         */

        recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);

        return (recursed_result == -1) ? -1 : 1 + recursed_result;

    } else if (/* QEMU: removed the following unneeded statement which causes

                * a compiler warning: ready >= WAIT_OBJECT_0 && */

               ready < WAIT_OBJECT_0 + nhandles) {

        for (f = fds; f < &fds[nfds]; ++f) {

            if ((HANDLE) f->fd == handles[ready - WAIT_OBJECT_0]) {

                f->revents = f->events;

            }

        }

        /* If no timeout and polling several handles, recurse to poll

         * the rest of them.

         */

        if (timeout == 0 && nhandles > 1) {

            /* Remove the handle that fired */

            int i;

            if (ready < nhandles - 1) {

                for (i = ready - WAIT_OBJECT_0 + 1; i < nhandles; i++) {

                    handles[i-1] = handles[i];

                }

            }

            nhandles--;

            recursed_result = poll_rest(FALSE, handles, nhandles, fds, nfds, 0);

            return (recursed_result == -1) ? -1 : 1 + recursed_result;

        }

        return 1;

    }

    return 0;

}


int kvm_arch_pre_run(CPUState *env, struct kvm_run *run)

{

    /* Inject NMI */

    if (env->interrupt_request & CPU_INTERRUPT_NMI) {

        env->interrupt_request &= ~CPU_INTERRUPT_NMI;

        DPRINTF("injected NMI\n");

        kvm_vcpu_ioctl(env, KVM_NMI);

    }

    if (!kvm_irqchip_in_kernel()) {

        /* Force the VCPU out of its inner loop to process the INIT request */

        if (env->interrupt_request & CPU_INTERRUPT_INIT) {

            env->exit_request = 1;

        }

        /* Try to inject an interrupt if the guest can accept it */

        if (run->ready_for_interrupt_injection &&

            (env->interrupt_request & CPU_INTERRUPT_HARD) &&

            (env->eflags & IF_MASK)) {

            int irq;

            env->interrupt_request &= ~CPU_INTERRUPT_HARD;

            irq = cpu_get_pic_interrupt(env);

            if (irq >= 0) {

                struct kvm_interrupt intr;

                intr.irq = irq;

                /* FIXME: errors */

                DPRINTF("injected interrupt %d\n", irq);

                kvm_vcpu_ioctl(env, KVM_INTERRUPT, &intr);

            }

        }

        /* If we have an interrupt but the guest is not ready to receive an

         * interrupt, request an interrupt window exit.  This will

         * cause a return to userspace as soon as the guest is ready to

         * receive interrupts. */

        if ((env->interrupt_request & CPU_INTERRUPT_HARD)) {

            run->request_interrupt_window = 1;

        } else {

            run->request_interrupt_window = 0;

        }

        DPRINTF("setting tpr\n");

        run->cr8 = cpu_get_apic_tpr(env->apic_state);

    }

    return 0;

}


static void gen_msync(DisasContext *ctx)

{

    /* interpreted as no-op */

}


static void nvram_writeb (void *opaque, target_phys_addr_t addr, uint32_t value)

{

    M48t59State *NVRAM = opaque;

    m48t59_write(NVRAM, addr, value & 0xff);

}


static int json_lexer_feed_char(JSONLexer *lexer, char ch, bool flush)

{

    int char_consumed, new_state;

    lexer->x++;

    if (ch == '\n') {

        lexer->x = 0;

        lexer->y++;

    }

    do {

        new_state = json_lexer[lexer->state][(uint8_t)ch];

        char_consumed = !TERMINAL_NEEDED_LOOKAHEAD(lexer->state, new_state);

        if (char_consumed) {

            qstring_append_chr(lexer->token, ch);

        }

        switch (new_state) {

        case JSON_OPERATOR:

        case JSON_ESCAPE:

        case JSON_INTEGER:

        case JSON_FLOAT:

        case JSON_KEYWORD:

        case JSON_STRING:

            lexer->emit(lexer, lexer->token, new_state, lexer->x, lexer->y);

        case JSON_SKIP:

            QDECREF(lexer->token);

            lexer->token = qstring_new();

            new_state = IN_START;

            break;

        case IN_ERROR:

            QDECREF(lexer->token);

            lexer->token = qstring_new();

            new_state = IN_START;

            return -EINVAL;

        default:

            break;

        }

        lexer->state = new_state;

    } while (!char_consumed && !flush);

    /* Do not let a single token grow to an arbitrarily large size,

     * this is a security consideration.

     */

    if (lexer->token->length > MAX_TOKEN_SIZE) {

        lexer->emit(lexer, lexer->token, lexer->state, lexer->x, lexer->y);

        QDECREF(lexer->token);

        lexer->token = qstring_new();

        lexer->state = IN_START;

    }

    return 0;

}


static int coroutine_fn qed_aio_write_alloc(QEDAIOCB *acb, size_t len)

{

    BDRVQEDState *s = acb_to_s(acb);

    int ret;

    /* Cancel timer when the first allocating request comes in */

    if (s->allocating_acb == NULL) {

        qed_cancel_need_check_timer(s);

    }

    /* Freeze this request if another allocating write is in progress */

    if (s->allocating_acb != acb || s->allocating_write_reqs_plugged) {

        if (s->allocating_acb != NULL) {

            qemu_co_queue_wait(&s->allocating_write_reqs, NULL);

            assert(s->allocating_acb == NULL);

        }

        s->allocating_acb = acb;

        return -EAGAIN; /* start over with looking up table entries */

    }

    acb->cur_nclusters = qed_bytes_to_clusters(s,

            qed_offset_into_cluster(s, acb->cur_pos) + len);

    qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);

    if (acb->flags & QED_AIOCB_ZERO) {

        /* Skip ahead if the clusters are already zero */

        if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {

            return 0;

        }

        acb->cur_cluster = 1;

    } else {

        acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);

    }

    if (qed_should_set_need_check(s)) {

        s->header.features |= QED_F_NEED_CHECK;

        ret = qed_write_header(s);

        if (ret < 0) {

            return ret;

        }

    }

    if (!(acb->flags & QED_AIOCB_ZERO)) {

        ret = qed_aio_write_cow(acb);

        if (ret < 0) {

            return ret;

        }

    }

    return qed_aio_write_l2_update(acb, acb->cur_cluster);

}


int qcow2_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)

{

    BDRVQcow2State *s = bs->opaque;

    QCowSnapshot *new_snapshot_list = NULL;

    QCowSnapshot *old_snapshot_list = NULL;

    QCowSnapshot sn1, *sn = &sn1;

    int i, ret;

    uint64_t *l1_table = NULL;

    int64_t l1_table_offset;

    if (s->nb_snapshots >= QCOW_MAX_SNAPSHOTS) {

        return -EFBIG;

    }

    memset(sn, 0, sizeof(*sn));

    /* Generate an ID */

    find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));

    /* Check that the ID is unique */

    if (find_snapshot_by_id_and_name(bs, sn_info->id_str, NULL) >= 0) {

        return -EEXIST;

    }

    /* Populate sn with passed data */

    sn->id_str = g_strdup(sn_info->id_str);

    sn->name = g_strdup(sn_info->name);

    sn->disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;

    sn->vm_state_size = sn_info->vm_state_size;

    sn->date_sec = sn_info->date_sec;

    sn->date_nsec = sn_info->date_nsec;

    sn->vm_clock_nsec = sn_info->vm_clock_nsec;

    /* Allocate the L1 table of the snapshot and copy the current one there. */

    l1_table_offset = qcow2_alloc_clusters(bs, s->l1_size * sizeof(uint64_t));

    if (l1_table_offset < 0) {

        ret = l1_table_offset;

        goto fail;

    }

    sn->l1_table_offset = l1_table_offset;

    sn->l1_size = s->l1_size;

    l1_table = g_try_new(uint64_t, s->l1_size);

    if (s->l1_size && l1_table == NULL) {

        ret = -ENOMEM;

        goto fail;

    }

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

        l1_table[i] = cpu_to_be64(s->l1_table[i]);

    }

    ret = qcow2_pre_write_overlap_check(bs, 0, sn->l1_table_offset,

                                        s->l1_size * sizeof(uint64_t));

    if (ret < 0) {

        goto fail;

    }

    ret = bdrv_pwrite(bs->file, sn->l1_table_offset, l1_table,

                      s->l1_size * sizeof(uint64_t));

    if (ret < 0) {

        goto fail;

    }

    g_free(l1_table);

    l1_table = NULL;

    /*

     * Increase the refcounts of all clusters and make sure everything is

     * stable on disk before updating the snapshot table to contain a pointer

     * to the new L1 table.

     */

    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);

    if (ret < 0) {

        goto fail;

    }

    /* Append the new snapshot to the snapshot list */

    new_snapshot_list = g_new(QCowSnapshot, s->nb_snapshots + 1);

    if (s->snapshots) {

        memcpy(new_snapshot_list, s->snapshots,

               s->nb_snapshots * sizeof(QCowSnapshot));

        old_snapshot_list = s->snapshots;

    }

    s->snapshots = new_snapshot_list;

    s->snapshots[s->nb_snapshots++] = *sn;

    ret = qcow2_write_snapshots(bs);

    if (ret < 0) {

        g_free(s->snapshots);

        s->snapshots = old_snapshot_list;

        s->nb_snapshots--;

        goto fail;

    }

    g_free(old_snapshot_list);

    /* The VM state isn't needed any more in the active L1 table; in fact, it

     * hurts by causing expensive COW for the next snapshot. */

    qcow2_discard_clusters(bs, qcow2_vm_state_offset(s),

                           align_offset(sn->vm_state_size, s->cluster_size)

                                >> BDRV_SECTOR_BITS,

                           QCOW2_DISCARD_NEVER, false);

#ifdef DEBUG_ALLOC

    {

      BdrvCheckResult result = {0};

      qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return 0;

fail:

    g_free(sn->id_str);

    g_free(sn->name);

    g_free(l1_table);

    return ret;

}


static void superio_ioport_writeb(void *opaque, uint32_t addr, uint32_t data)

{

    int can_write;

    SuperIOConfig *superio_conf = opaque;

    DPRINTF("superio_ioport_writeb  address 0x%x  val 0x%x  \n", addr, data);

    if (addr == 0x3f0) {

        superio_conf->index = data & 0xff;

    } else {

        /* 0x3f1 */

        switch (superio_conf->index) {

        case 0x00 ... 0xdf:

        case 0xe4:

        case 0xe5:

        case 0xe9 ... 0xed:

        case 0xf3:

        case 0xf5:

        case 0xf7:

        case 0xf9 ... 0xfb:

        case 0xfd ... 0xff:

            can_write = 0;

            break;

        default:

            can_write = 1;

            if (can_write) {

                switch (superio_conf->index) {

                case 0xe7:

                    if ((data & 0xff) != 0xfe) {

                        DPRINTF("chage uart 1 base. unsupported yet \n");

                    }

                    break;

                case 0xe8:

                    if ((data & 0xff) != 0xbe) {

                        DPRINTF("chage uart 2 base. unsupported yet \n");

                    }

                    break;

                default:

                    superio_conf->config[superio_conf->index] = data & 0xff;

                }

            }

        }

        superio_conf->config[superio_conf->index] = data & 0xff;

    }

}


static void monitor_handle_command1(void *opaque, const char *cmdline)

{

    monitor_handle_command(cmdline);

    if (!monitor_suspended)

        monitor_start_input();

    else

        monitor_suspended = 2;

}


static void do_pci_unregister_device(PCIDevice *pci_dev)

{

    pci_dev->bus->devices[pci_dev->devfn] = NULL;

    pci_config_free(pci_dev);

    if (memory_region_is_mapped(&pci_dev->bus_master_enable_region)) {

        memory_region_del_subregion(&pci_dev->bus_master_container_region,

                                    &pci_dev->bus_master_enable_region);

    }

    address_space_destroy(&pci_dev->bus_master_as);

}


CPUState *ppc405cr_init (target_phys_addr_t ram_bases[4],

                         target_phys_addr_t ram_sizes[4],

                         uint32_t sysclk, qemu_irq **picp,

                         int do_init)

{

    clk_setup_t clk_setup[PPC405CR_CLK_NB];

    qemu_irq dma_irqs[4];

    CPUState *env;

    qemu_irq *pic, *irqs;

    memset(clk_setup, 0, sizeof(clk_setup));

    env = ppc4xx_init("405cr", &clk_setup[PPC405CR_CPU_CLK],

                      &clk_setup[PPC405CR_TMR_CLK], sysclk);

    /* Memory mapped devices registers */

    /* PLB arbitrer */

    ppc4xx_plb_init(env);

    /* PLB to OPB bridge */

    ppc4xx_pob_init(env);

    /* OBP arbitrer */

    ppc4xx_opba_init(0xef600600);

    /* Universal interrupt controller */

    irqs = g_malloc0(sizeof(qemu_irq) * PPCUIC_OUTPUT_NB);

    irqs[PPCUIC_OUTPUT_INT] =

        ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_INT];

    irqs[PPCUIC_OUTPUT_CINT] =

        ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_CINT];

    pic = ppcuic_init(env, irqs, 0x0C0, 0, 1);

    *picp = pic;

    /* SDRAM controller */

    ppc4xx_sdram_init(env, pic[14], 1, ram_bases, ram_sizes, do_init);

    /* External bus controller */

    ppc405_ebc_init(env);

    /* DMA controller */

    dma_irqs[0] = pic[26];

    dma_irqs[1] = pic[25];

    dma_irqs[2] = pic[24];

    dma_irqs[3] = pic[23];

    ppc405_dma_init(env, dma_irqs);

    /* Serial ports */

    if (serial_hds[0] != NULL) {

        serial_mm_init(0xef600300, 0, pic[0], PPC_SERIAL_MM_BAUDBASE,

                       serial_hds[0], 1, 1);

    }

    if (serial_hds[1] != NULL) {

        serial_mm_init(0xef600400, 0, pic[1], PPC_SERIAL_MM_BAUDBASE,

                       serial_hds[1], 1, 1);

    }

    /* IIC controller */

    ppc405_i2c_init(0xef600500, pic[2]);

    /* GPIO */

    ppc405_gpio_init(0xef600700);

    /* CPU control */

    ppc405cr_cpc_init(env, clk_setup, sysclk);

    return env;

}


int nbd_client_session_co_discard(NbdClientSession *client, int64_t sector_num,

    int nb_sectors)

{

    struct nbd_request request = { .type = NBD_CMD_TRIM };

    struct nbd_reply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) {

        return 0;

    }

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, NULL, 0);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL, 0);

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


static void sdhci_do_adma(SDHCIState *s)

{

    unsigned int n, begin, length;

    const uint16_t block_size = s->blksize & 0x0fff;

    ADMADescr dscr;

    int i;

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

        s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;

        get_adma_description(s, &dscr);

        DPRINT_L2("ADMA loop: addr=" TARGET_FMT_plx ", len=%d, attr=%x\n",

                dscr.addr, dscr.length, dscr.attr);

        if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {

            /* Indicate that error occurred in ST_FDS state */

            s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;

            s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;

            /* Generate ADMA error interrupt */

            if (s->errintstsen & SDHC_EISEN_ADMAERR) {

                s->errintsts |= SDHC_EIS_ADMAERR;

                s->norintsts |= SDHC_NIS_ERR;

            }

            sdhci_update_irq(s);

            return;

        }

        length = dscr.length ? dscr.length : 65536;

        switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {

        case SDHC_ADMA_ATTR_ACT_TRAN:  /* data transfer */

            if (s->trnmod & SDHC_TRNS_READ) {

                while (length) {

                    if (s->data_count == 0) {

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

                            s->fifo_buffer[n] = sd_read_data(s->card);

                        }

                    }

                    begin = s->data_count;

                    if ((length + begin) < block_size) {

                        s->data_count = length + begin;

                        length = 0;

                     } else {

                        s->data_count = block_size;

                        length -= block_size - begin;

                    }

                    dma_memory_write(&address_space_memory, dscr.addr,

                                     &s->fifo_buffer[begin],

                                     s->data_count - begin);

                    dscr.addr += s->data_count - begin;

                    if (s->data_count == block_size) {

                        s->data_count = 0;

                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                            s->blkcnt--;

                            if (s->blkcnt == 0) {

                                break;

                            }

                        }

                    }

                }

            } else {

                while (length) {

                    begin = s->data_count;

                    if ((length + begin) < block_size) {

                        s->data_count = length + begin;

                        length = 0;

                     } else {

                        s->data_count = block_size;

                        length -= block_size - begin;

                    }

                    dma_memory_read(&address_space_memory, dscr.addr,

                                    &s->fifo_buffer[begin],

                                    s->data_count - begin);

                    dscr.addr += s->data_count - begin;

                    if (s->data_count == block_size) {

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

                            sd_write_data(s->card, s->fifo_buffer[n]);

                        }

                        s->data_count = 0;

                        if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

                            s->blkcnt--;

                            if (s->blkcnt == 0) {

                                break;

                            }

                        }

                    }

                }

            }

            s->admasysaddr += dscr.incr;

            break;

        case SDHC_ADMA_ATTR_ACT_LINK:   /* link to next descriptor table */

            s->admasysaddr = dscr.addr;

            DPRINT_L1("ADMA link: admasysaddr=0x%lx\n", s->admasysaddr);

            break;

        default:

            s->admasysaddr += dscr.incr;

            break;

        }

        if (dscr.attr & SDHC_ADMA_ATTR_INT) {

            DPRINT_L1("ADMA interrupt: admasysaddr=0x%lx\n", s->admasysaddr);

            if (s->norintstsen & SDHC_NISEN_DMA) {

                s->norintsts |= SDHC_NIS_DMA;

            }

            sdhci_update_irq(s);

        }

        /* ADMA transfer terminates if blkcnt == 0 or by END attribute */

        if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&

                    (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {

            DPRINT_L2("ADMA transfer completed\n");

            if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&

                (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&

                s->blkcnt != 0)) {

                ERRPRINT("SD/MMC host ADMA length mismatch\n");

                s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |

                        SDHC_ADMAERR_STATE_ST_TFR;

                if (s->errintstsen & SDHC_EISEN_ADMAERR) {

                    ERRPRINT("Set ADMA error flag\n");

                    s->errintsts |= SDHC_EIS_ADMAERR;

                    s->norintsts |= SDHC_NIS_ERR;

                }

                sdhci_update_irq(s);

            }

            SDHCI_GET_CLASS(s)->end_data_transfer(s);

            return;

        }

    }

    /* we have unfinished business - reschedule to continue ADMA */

    timer_mod(s->transfer_timer,

                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);

}


static uint32_t omap_sysctl_read8(void *opaque, target_phys_addr_t addr)

{

    struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;

    int pad_offset, byte_offset;

    int value;

    switch (addr) {

    case 0x030 ... 0x140:	/* CONTROL_PADCONF - only used in the POP */

        pad_offset = (addr - 0x30) >> 2;

        byte_offset = (addr - 0x30) & (4 - 1);

        value = s->padconf[pad_offset];

        value = (value >> (byte_offset * 8)) & 0xff;

        return value;

    default:

        break;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


abi_ulong mmap_find_vma(abi_ulong start, abi_ulong size)

{

    void *ptr, *prev;

    abi_ulong addr;

    int wrapped, repeat;

    /* If 'start' == 0, then a default start address is used. */

    if (start == 0) {

        start = mmap_next_start;

    } else {

        start &= qemu_host_page_mask;

    }

    size = HOST_PAGE_ALIGN(size);

    if (RESERVED_VA) {

        return mmap_find_vma_reserved(start, size);

    }

    addr = start;

    wrapped = repeat = 0;

    prev = 0;

    for (;; prev = ptr) {

        /*

         * Reserve needed memory area to avoid a race.

         * It should be discarded using:

         *  - mmap() with MAP_FIXED flag

         *  - mremap() with MREMAP_FIXED flag

         *  - shmat() with SHM_REMAP flag

         */

        ptr = mmap(g2h(addr), size, PROT_NONE,

                   MAP_ANONYMOUS|MAP_PRIVATE|MAP_NORESERVE, -1, 0);

        /* ENOMEM, if host address space has no memory */

        if (ptr == MAP_FAILED) {

            return (abi_ulong)-1;

        }

        /* Count the number of sequential returns of the same address.

           This is used to modify the search algorithm below.  */

        repeat = (ptr == prev ? repeat + 1 : 0);

        if (h2g_valid(ptr + size - 1)) {

            addr = h2g(ptr);

            if ((addr & ~TARGET_PAGE_MASK) == 0) {

                /* Success.  */

                if (start == mmap_next_start && addr >= TASK_UNMAPPED_BASE) {

                    mmap_next_start = addr + size;

                }

                return addr;

            }

            /* The address is not properly aligned for the target.  */

            switch (repeat) {

            case 0:

                /* Assume the result that the kernel gave us is the

                   first with enough free space, so start again at the

                   next higher target page.  */

                addr = TARGET_PAGE_ALIGN(addr);

                break;

            case 1:

                /* Sometimes the kernel decides to perform the allocation

                   at the top end of memory instead.  */

                addr &= TARGET_PAGE_MASK;

                break;

            case 2:

                /* Start over at low memory.  */

                addr = 0;

                break;

            default:

                /* Fail.  This unaligned block must the last.  */

                addr = -1;

                break;

            }

        } else {

            /* Since the result the kernel gave didn't fit, start

               again at low memory.  If any repetition, fail.  */

            addr = (repeat ? -1 : 0);

        }

        /* Unmap and try again.  */

        munmap(ptr, size);

        /* ENOMEM if we checked the whole of the target address space.  */

        if (addr == -1ul) {

            return (abi_ulong)-1;

        } else if (addr == 0) {

            if (wrapped) {

                return (abi_ulong)-1;

            }

            wrapped = 1;

            /* Don't actually use 0 when wrapping, instead indicate

               that we'd truely like an allocation in low memory.  */

            addr = (mmap_min_addr > TARGET_PAGE_SIZE

                     ? TARGET_PAGE_ALIGN(mmap_min_addr)

                     : TARGET_PAGE_SIZE);

        } else if (wrapped && addr >= start) {

            return (abi_ulong)-1;

        }

    }

}


static int do_token_out(USBDevice *s, USBPacket *p)

{

    assert(p->devep == 0);

    switch(s->setup_state) {

    case SETUP_STATE_ACK:

        if (s->setup_buf[0] & USB_DIR_IN) {

            s->setup_state = SETUP_STATE_IDLE;

            /* transfer OK */

        } else {

            /* ignore additional output */

        }

        return 0;

    case SETUP_STATE_DATA:

        if (!(s->setup_buf[0] & USB_DIR_IN)) {

            int len = s->setup_len - s->setup_index;

            if (len > p->iov.size) {

                len = p->iov.size;

            }

            usb_packet_copy(p, s->data_buf + s->setup_index, len);

            s->setup_index += len;

            if (s->setup_index >= s->setup_len)

                s->setup_state = SETUP_STATE_ACK;

            return len;

        }

        s->setup_state = SETUP_STATE_IDLE;

        return USB_RET_STALL;

    default:

        return USB_RET_STALL;

    }

}


int page_unprotect(target_ulong address, uintptr_t pc)

{

    unsigned int prot;

    PageDesc *p;

    target_ulong host_start, host_end, addr;

    /* Technically this isn't safe inside a signal handler.  However we

       know this only ever happens in a synchronous SEGV handler, so in

       practice it seems to be ok.  */

    mmap_lock();

    p = page_find(address >> TARGET_PAGE_BITS);

    if (!p) {

        mmap_unlock();

        return 0;

    }

    /* if the page was really writable, then we change its

       protection back to writable */

    if ((p->flags & PAGE_WRITE_ORG) && !(p->flags & PAGE_WRITE)) {

        host_start = address & qemu_host_page_mask;

        host_end = host_start + qemu_host_page_size;

        prot = 0;

        for (addr = host_start ; addr < host_end ; addr += TARGET_PAGE_SIZE) {

            p = page_find(addr >> TARGET_PAGE_BITS);

            p->flags |= PAGE_WRITE;

            prot |= p->flags;

            /* and since the content will be modified, we must invalidate

               the corresponding translated code. */

            if (tb_invalidate_phys_page(addr, pc)) {

                mmap_unlock();

                return 2;

            }

#ifdef DEBUG_TB_CHECK

            tb_invalidate_check(addr);

#endif

        }

        mprotect((void *)g2h(host_start), qemu_host_page_size,

                 prot & PAGE_BITS);

        mmap_unlock();

        return 1;

    }

    mmap_unlock();

    return 0;

}


static void truncpasses(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile)

{

    int precno, compno, reslevelno, bandno, cblkno, lev;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    for (compno = 0; compno < s->ncomponents; compno++){

        Jpeg2000Component *comp = tile->comp + compno;

        for (reslevelno = 0, lev = codsty->nreslevels-1; reslevelno < codsty->nreslevels; reslevelno++, lev--){

            Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;

            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){

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

                    int bandpos = bandno + (reslevelno > 0);

                    Jpeg2000Band *band = reslevel->band + bandno;

                    Jpeg2000Prec *prec = band->prec + precno;

                    for (cblkno = 0; cblkno < prec->nb_codeblocks_height * prec->nb_codeblocks_width; cblkno++){

                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                        cblk->ninclpasses = getcut(cblk, s->lambda,

                                (int64_t)dwt_norms[codsty->transform][bandpos][lev] * (int64_t)band->i_stepsize >> 16);

                    }

                }

            }

        }

    }

}


uint64_t blk_mig_bytes_remaining(void)

{

    return blk_mig_bytes_total() - blk_mig_bytes_transferred();

}


static int init_tile(Jpeg2000DecoderContext *s, int tileno)

{

    int compno;

    int tilex = tileno % s->numXtiles;

    int tiley = tileno / s->numXtiles;

    Jpeg2000Tile *tile = s->tile + tileno;

    if (!tile->comp)

        return AVERROR(ENOMEM);

    tile->coord[0][0] = av_clip(tilex       * s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);

    tile->coord[0][1] = av_clip((tilex + 1) * s->tile_width  + s->tile_offset_x, s->image_offset_x, s->width);

    tile->coord[1][0] = av_clip(tiley       * s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);

    tile->coord[1][1] = av_clip((tiley + 1) * s->tile_height + s->tile_offset_y, s->image_offset_y, s->height);

    for (compno = 0; compno < s->ncomponents; compno++) {

        Jpeg2000Component *comp = tile->comp + compno;

        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

        Jpeg2000QuantStyle  *qntsty = tile->qntsty + compno;

        int ret; // global bandno

        comp->coord_o[0][0] = tile->coord[0][0];

        comp->coord_o[0][1] = tile->coord[0][1];

        comp->coord_o[1][0] = tile->coord[1][0];

        comp->coord_o[1][1] = tile->coord[1][1];

        if (compno) {

            comp->coord_o[0][0] /= s->cdx[compno];

            comp->coord_o[0][1] /= s->cdx[compno];

            comp->coord_o[1][0] /= s->cdy[compno];

            comp->coord_o[1][1] /= s->cdy[compno];

        }

        comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);

        comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);

        comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);

        comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);

        if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,

                                             s->cbps[compno], s->cdx[compno],

                                             s->cdy[compno], s->avctx))

            return ret;

    }

    return 0;

}


static int srt_write_packet(AVFormatContext *avf, AVPacket *pkt)

{

    SRTContext *srt = avf->priv_data;

    int write_ts = avf->streams[0]->codec->codec_id != AV_CODEC_ID_SRT;

    srt->index++;

    if (write_ts) {

        int64_t s = pkt->pts, e, d = pkt->duration;

        if (d <= 0)

            /* For backward compatibility, fallback to convergence_duration. */

            d = pkt->convergence_duration;

        if (s == AV_NOPTS_VALUE || d < 0) {

            av_log(avf, AV_LOG_ERROR, "Insufficient timestamps.\n");

            return AVERROR(EINVAL);

        }

        e = s + d;

        avio_printf(avf->pb, "%d\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n",

                       srt->index,

                       (int)(s / 3600000),      (int)(s / 60000) % 60,

                       (int)(s /    1000) % 60, (int)(s %  1000),

                       (int)(e / 3600000),      (int)(e / 60000) % 60,

                       (int)(e /    1000) % 60, (int)(e %  1000));

    }

    avio_write(avf->pb, pkt->data, pkt->size);

    if (write_ts)

        avio_write(avf->pb, "\n\n", 2);

    avio_flush(avf->pb);

    return 0;

}


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

                             const AVFrame *frame, int *got_packet_ptr)

{

    FlacEncodeContext *s;

    int frame_bytes, out_bytes, ret;

    s = avctx->priv_data;

    /* when the last block is reached, update the header in extradata */

    if (!frame) {

        s->max_framesize = s->max_encoded_framesize;

        av_md5_final(s->md5ctx, s->md5sum);

        write_streaminfo(s, avctx->extradata);

        return 0;

    }

    /* change max_framesize for small final frame */

    if (frame->nb_samples < s->frame.blocksize) {

        s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,

                                                      s->channels,

                                                      avctx->bits_per_raw_sample);

    }

    init_frame(s, frame->nb_samples);

    copy_samples(s, frame->data[0]);

    channel_decorrelation(s);

    remove_wasted_bits(s);

    frame_bytes = encode_frame(s);

    /* fallback to verbatim mode if the compressed frame is larger than it

       would be if encoded uncompressed. */

    if (frame_bytes < 0 || frame_bytes > s->max_framesize) {

        s->frame.verbatim_only = 1;

        frame_bytes = encode_frame(s);

        if (frame_bytes < 0) {

            av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");

            return frame_bytes;

        }

    }

    if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)))

        return ret;

    out_bytes = write_frame(s, avpkt);

    s->frame_count++;

    s->sample_count += frame->nb_samples;

    if ((ret = update_md5_sum(s, frame->data[0])) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");

        return ret;

    }

    if (out_bytes > s->max_encoded_framesize)

        s->max_encoded_framesize = out_bytes;

    if (out_bytes < s->min_framesize)

        s->min_framesize = out_bytes;

    avpkt->pts      = frame->pts;

    avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);

    avpkt->size     = out_bytes;

    *got_packet_ptr = 1;

    return 0;

}


void ff_vp3_v_loop_filter_mmx(uint8_t *src, int stride, int *bounding_values)

{

    __asm__ volatile(

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

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

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

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

        VP3_LOOP_FILTER(%4)

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

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

        : "+m" (*(uint64_t*)(src - 2*stride)),

          "+m" (*(uint64_t*)(src - 1*stride)),

          "+m" (*(uint64_t*)(src + 0*stride)),

          "+m" (*(uint64_t*)(src + 1*stride))

        : "m"(*(uint64_t*)(bounding_values+129))

    );

}


static int decode(AVCodecContext *avctx, void *data, int *data_size,

                  AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    const uint8_t *buf_end;

    uint8_t       segment_type;

    int           segment_length;

    int i, ret;

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

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

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

        if (i % 16 == 15)

            av_dlog(avctx, "\n");

    }

    if (i & 15)

        av_dlog(avctx, "\n");

    *data_size = 0;

    /* Ensure that we have received at a least a segment code and segment length */

    if (buf_size < 3)

        return -1;

    buf_end = buf + buf_size;

    /* Step through buffer to identify segments */

    while (buf < buf_end) {

        segment_type   = bytestream_get_byte(&buf);

        segment_length = bytestream_get_be16(&buf);

        av_dlog(avctx, "Segment Length %d, Segment Type %x\n", segment_length, segment_type);

        if (segment_type != DISPLAY_SEGMENT && segment_length > buf_end - buf)

            break;

        switch (segment_type) {

        case PALETTE_SEGMENT:

            parse_palette_segment(avctx, buf, segment_length);

            break;

        case PICTURE_SEGMENT:

            parse_picture_segment(avctx, buf, segment_length);

            break;

        case PRESENTATION_SEGMENT:

            ret = parse_presentation_segment(avctx, buf, segment_length, avpkt->pts);

            if (ret < 0)

                return ret;

            break;

        case WINDOW_SEGMENT:

            /*

             * Window Segment Structure (No new information provided):

             *     2 bytes: Unknown,

             *     2 bytes: X position of subtitle,

             *     2 bytes: Y position of subtitle,

             *     2 bytes: Width of subtitle,

             *     2 bytes: Height of subtitle.

             */

            break;

        case DISPLAY_SEGMENT:

            *data_size = display_end_segment(avctx, data, buf, segment_length);

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unknown subtitle segment type 0x%x, length %d\n",

                   segment_type, segment_length);

            break;

        }

        buf += segment_length;

    }

    return buf_size;

}


static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb,

                                   AVStream *st, MOVStreamContext *sc)

{

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

        !st->codec->sample_rate && sc->time_scale > 1)

        st->codec->sample_rate = sc->time_scale;

    /* special codec parameters handling */

    switch (st->codec->codec_id) {

#if CONFIG_DV_DEMUXER

    case AV_CODEC_ID_DVAUDIO:

        c->dv_fctx = avformat_alloc_context();

        if (!c->dv_fctx) {

            av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n");

            return AVERROR(ENOMEM);

        }

        c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);

        if (!c->dv_demux) {

            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");

            return AVERROR(ENOMEM);

        }

        sc->dv_audio_container = 1;

        st->codec->codec_id    = AV_CODEC_ID_PCM_S16LE;

        break;

#endif

    /* no ifdef since parameters are always those */

    case AV_CODEC_ID_QCELP:

        st->codec->channels = 1;

        // force sample rate for qcelp when not stored in mov

        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))

            st->codec->sample_rate = 8000;

        break;

    case AV_CODEC_ID_AMR_NB:

        st->codec->channels    = 1;

        /* force sample rate for amr, stsd in 3gp does not store sample rate */

        st->codec->sample_rate = 8000;

        break;

    case AV_CODEC_ID_AMR_WB:

        st->codec->channels    = 1;

        st->codec->sample_rate = 16000;

        break;

    case AV_CODEC_ID_MP2:

    case AV_CODEC_ID_MP3:

        /* force type after stsd for m1a hdlr */

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->need_parsing      = AVSTREAM_PARSE_FULL;

        break;

    case AV_CODEC_ID_GSM:

    case AV_CODEC_ID_ADPCM_MS:

    case AV_CODEC_ID_ADPCM_IMA_WAV:

    case AV_CODEC_ID_ILBC:

        st->codec->block_align = sc->bytes_per_frame;

        break;

    case AV_CODEC_ID_ALAC:

        if (st->codec->extradata_size == 36) {

            st->codec->channels    = AV_RB8 (st->codec->extradata + 21);

            st->codec->sample_rate = AV_RB32(st->codec->extradata + 32);

        }

        break;

    case AV_CODEC_ID_VC1:

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    default:

        break;

    }

    return 0;

}


void OPPROTO op_srli_T1 (void)

{

    T1 = T1 >> PARAM1;

    RETURN();

}


static int decode_pic_hdr(IVI45DecContext *ctx, AVCodecContext *avctx)

{

    int             pic_size_indx, i, p;

    IVIPicConfig    pic_conf;

    if (get_bits(&ctx->gb, 18) != 0x3FFF8) {

        av_log(avctx, AV_LOG_ERROR, "Invalid picture start code!\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->prev_frame_type = ctx->frame_type;

    ctx->frame_type      = get_bits(&ctx->gb, 3);

    if (ctx->frame_type == 7) {

        av_log(avctx, AV_LOG_ERROR, "Invalid frame type: %d\n", ctx->frame_type);

        return AVERROR_INVALIDDATA;

    }

#if IVI4_STREAM_ANALYSER

    if (ctx->frame_type == FRAMETYPE_BIDIR)

        ctx->has_b_frames = 1;

#endif

    ctx->transp_status = get_bits1(&ctx->gb);

#if IVI4_STREAM_ANALYSER

    if (ctx->transp_status) {

        ctx->has_transp = 1;

    }

#endif

    /* unknown bit: Mac decoder ignores this bit, XANIM returns error */

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

        av_log(avctx, AV_LOG_ERROR, "Sync bit is set!\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->data_size = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 24) : 0;

    /* null frames don't contain anything else so we just return */

    if (ctx->frame_type >= FRAMETYPE_NULL_FIRST) {

        av_dlog(avctx, "Null frame encountered!\n");

        return 0;

    }

    /* Check key lock status. If enabled - ignore lock word.         */

    /* Usually we have to prompt the user for the password, but      */

    /* we don't do that because Indeo 4 videos can be decoded anyway */

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

        skip_bits_long(&ctx->gb, 32);

        av_dlog(avctx, "Password-protected clip!\n");

    }

    pic_size_indx = get_bits(&ctx->gb, 3);

    if (pic_size_indx == IVI4_PIC_SIZE_ESC) {

        pic_conf.pic_height = get_bits(&ctx->gb, 16);

        pic_conf.pic_width  = get_bits(&ctx->gb, 16);

    } else {

        pic_conf.pic_height = ivi4_common_pic_sizes[pic_size_indx * 2 + 1];

        pic_conf.pic_width  = ivi4_common_pic_sizes[pic_size_indx * 2    ];

    }

    /* Decode tile dimensions. */

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

        pic_conf.tile_height = scale_tile_size(pic_conf.pic_height, get_bits(&ctx->gb, 4));

        pic_conf.tile_width  = scale_tile_size(pic_conf.pic_width,  get_bits(&ctx->gb, 4));

#if IVI4_STREAM_ANALYSER

        ctx->uses_tiling = 1;

#endif

    } else {

        pic_conf.tile_height = pic_conf.pic_height;

        pic_conf.tile_width  = pic_conf.pic_width;

    }

    /* Decode chroma subsampling. We support only 4:4 aka YVU9. */

    if (get_bits(&ctx->gb, 2)) {

        av_log(avctx, AV_LOG_ERROR, "Only YVU9 picture format is supported!\n");

        return AVERROR_INVALIDDATA;

    }

    pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;

    pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;

    /* decode subdivision of the planes */

    pic_conf.luma_bands = decode_plane_subdivision(&ctx->gb);

    if (pic_conf.luma_bands)

        pic_conf.chroma_bands = decode_plane_subdivision(&ctx->gb);

    ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;

    if (ctx->is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {

        av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",

               pic_conf.luma_bands, pic_conf.chroma_bands);

        return AVERROR_INVALIDDATA;

    }

    /* check if picture layout was changed and reallocate buffers */

    if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {

        if (ff_ivi_init_planes(ctx->planes, &pic_conf)) {

            av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");

            return AVERROR(ENOMEM);

        }

        ctx->pic_conf = pic_conf;

        /* set default macroblock/block dimensions */

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

            for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {

                ctx->planes[p].bands[i].mb_size  = !p ? (!ctx->is_scalable ? 16 : 8) : 4;

                ctx->planes[p].bands[i].blk_size = !p ? 8 : 4;

            }

        }

        if (ff_ivi_init_tiles(ctx->planes, ctx->pic_conf.tile_width,

                              ctx->pic_conf.tile_height)) {

            av_log(avctx, AV_LOG_ERROR,

                   "Couldn't reallocate internal structures!\n");

            return AVERROR(ENOMEM);

        }

    }

    ctx->frame_num = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 20) : 0;

    /* skip decTimeEst field if present */

    if (get_bits1(&ctx->gb))

        skip_bits(&ctx->gb, 8);

    /* decode macroblock and block huffman codebooks */

    if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_MB_HUFF,  &ctx->mb_vlc,  avctx) ||

        ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF, &ctx->blk_vlc, avctx))

        return AVERROR_INVALIDDATA;

    ctx->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;

    ctx->in_imf = get_bits1(&ctx->gb);

    ctx->in_q   = get_bits1(&ctx->gb);

    ctx->pic_glob_quant = get_bits(&ctx->gb, 5);

    /* TODO: ignore this parameter if unused */

    ctx->unknown1 = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 0;

    ctx->checksum = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 16) : 0;

    /* skip picture header extension if any */

    while (get_bits1(&ctx->gb)) {

        av_dlog(avctx, "Pic hdr extension encountered!\n");

        skip_bits(&ctx->gb, 8);

    }

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

        av_log(avctx, AV_LOG_ERROR, "Bad blocks bits encountered!\n");

    }

    align_get_bits(&ctx->gb);

    return 0;

}


void ff_vp3_idct_add_altivec(uint8_t *dst, int stride, DCTELEM block[64])

{

    LOAD_ZERO;

    vec_u8 t, vdst;

    vec_s16 vdst_16;

    vec_u8 vdst_mask = vec_mergeh(vec_splat_u8(-1), vec_lvsl(0, dst));

    IDCT_START

    IDCT_1D(NOP, NOP)

    TRANSPOSE8(b0, b1, b2, b3, b4, b5, b6, b7);

    IDCT_1D(ADD8, SHIFT4)

#define ADD(a)\

    vdst = vec_ld(0, dst);\

    vdst_16 = (vec_s16)vec_perm(vdst, zero_u8v, vdst_mask);\

    vdst_16 = vec_adds(a, vdst_16);\

    t = vec_packsu(vdst_16, vdst_16);\

    vec_ste((vec_u32)t, 0, (unsigned int *)dst);\

    vec_ste((vec_u32)t, 4, (unsigned int *)dst);

    ADD(b0)     dst += stride;

    ADD(b1)     dst += stride;

    ADD(b2)     dst += stride;

    ADD(b3)     dst += stride;

    ADD(b4)     dst += stride;

    ADD(b5)     dst += stride;

    ADD(b6)     dst += stride;

    ADD(b7)

}


static void qobject_output_type_uint64(Visitor *v, const char *name,

                                       uint64_t *obj, Error **errp)

{

    /* FIXME values larger than INT64_MAX become negative */

    QObjectOutputVisitor *qov = to_qov(v);

    qobject_output_add(qov, name, qnum_from_int(*obj));

}


static int asf_read_replicated_data(AVFormatContext *s, ASFPacket *asf_pkt)

{

    ASFContext *asf = s->priv_data;

    AVIOContext *pb = s->pb;

    int ret;

    if (!asf_pkt->data_size) {

        asf_pkt->data_size = asf_pkt->size_left = avio_rl32(pb); // read media object size

        if (asf_pkt->data_size <= 0)

            return AVERROR_INVALIDDATA;

        if ((ret = av_new_packet(&asf_pkt->avpkt, asf_pkt->data_size)) < 0)

            return ret;

    } else

        avio_skip(pb, 4); // reading of media object size is already done

    asf_pkt->dts = avio_rl32(pb); // read presentation time

    if (asf->rep_data_len && (asf->rep_data_len >= 8))

        avio_skip(pb, asf->rep_data_len - 8); // skip replicated data

    return 0;

}


float64 float64_muladd(float64 a, float64 b, float64 c, int flags STATUS_PARAM)

{

    flag aSign, bSign, cSign, zSign;

    int_fast16_t aExp, bExp, cExp, pExp, zExp, expDiff;

    uint64_t aSig, bSig, cSig;

    flag pInf, pZero, pSign;

    uint64_t pSig0, pSig1, cSig0, cSig1, zSig0, zSig1;

    int shiftcount;

    flag signflip, infzero;

    a = float64_squash_input_denormal(a STATUS_VAR);

    b = float64_squash_input_denormal(b STATUS_VAR);

    c = float64_squash_input_denormal(c STATUS_VAR);

    aSig = extractFloat64Frac(a);

    aExp = extractFloat64Exp(a);

    aSign = extractFloat64Sign(a);

    bSig = extractFloat64Frac(b);

    bExp = extractFloat64Exp(b);

    bSign = extractFloat64Sign(b);

    cSig = extractFloat64Frac(c);

    cExp = extractFloat64Exp(c);

    cSign = extractFloat64Sign(c);

    infzero = ((aExp == 0 && aSig == 0 && bExp == 0x7ff && bSig == 0) ||

               (aExp == 0x7ff && aSig == 0 && bExp == 0 && bSig == 0));

    /* It is implementation-defined whether the cases of (0,inf,qnan)

     * and (inf,0,qnan) raise InvalidOperation or not (and what QNaN

     * they return if they do), so we have to hand this information

     * off to the target-specific pick-a-NaN routine.

     */

    if (((aExp == 0x7ff) && aSig) ||

        ((bExp == 0x7ff) && bSig) ||

        ((cExp == 0x7ff) && cSig)) {

        return propagateFloat64MulAddNaN(a, b, c, infzero STATUS_VAR);

    }

    if (infzero) {

        float_raise(float_flag_invalid STATUS_VAR);

        return float64_default_nan;

    }

    if (flags & float_muladd_negate_c) {

        cSign ^= 1;

    }

    signflip = (flags & float_muladd_negate_result) ? 1 : 0;

    /* Work out the sign and type of the product */

    pSign = aSign ^ bSign;

    if (flags & float_muladd_negate_product) {

        pSign ^= 1;

    }

    pInf = (aExp == 0x7ff) || (bExp == 0x7ff);

    pZero = ((aExp | aSig) == 0) || ((bExp | bSig) == 0);

    if (cExp == 0x7ff) {

        if (pInf && (pSign ^ cSign)) {

            /* addition of opposite-signed infinities => InvalidOperation */

            float_raise(float_flag_invalid STATUS_VAR);

            return float64_default_nan;

        }

        /* Otherwise generate an infinity of the same sign */

        return packFloat64(cSign ^ signflip, 0x7ff, 0);

    }

    if (pInf) {

        return packFloat64(pSign ^ signflip, 0x7ff, 0);

    }

    if (pZero) {

        if (cExp == 0) {

            if (cSig == 0) {

                /* Adding two exact zeroes */

                if (pSign == cSign) {

                    zSign = pSign;

                } else if (STATUS(float_rounding_mode) == float_round_down) {

                    zSign = 1;

                } else {

                    zSign = 0;

                }

                return packFloat64(zSign ^ signflip, 0, 0);

            }

            /* Exact zero plus a denorm */

            if (STATUS(flush_to_zero)) {

                float_raise(float_flag_output_denormal STATUS_VAR);

                return packFloat64(cSign ^ signflip, 0, 0);

            }

        }

        /* Zero plus something non-zero : just return the something */

        return packFloat64(cSign ^ signflip, cExp, cSig);

    }

    if (aExp == 0) {

        normalizeFloat64Subnormal(aSig, &aExp, &aSig);

    }

    if (bExp == 0) {

        normalizeFloat64Subnormal(bSig, &bExp, &bSig);

    }

    /* Calculate the actual result a * b + c */

    /* Multiply first; this is easy. */

    /* NB: we subtract 0x3fe where float64_mul() subtracts 0x3ff

     * because we want the true exponent, not the "one-less-than"

     * flavour that roundAndPackFloat64() takes.

     */

    pExp = aExp + bExp - 0x3fe;

    aSig = (aSig | LIT64(0x0010000000000000))<<10;

    bSig = (bSig | LIT64(0x0010000000000000))<<11;

    mul64To128(aSig, bSig, &pSig0, &pSig1);

    if ((int64_t)(pSig0 << 1) >= 0) {

        shortShift128Left(pSig0, pSig1, 1, &pSig0, &pSig1);

        pExp--;

    }

    zSign = pSign ^ signflip;

    /* Now [pSig0:pSig1] is the significand of the multiply, with the explicit

     * bit in position 126.

     */

    if (cExp == 0) {

        if (!cSig) {

            /* Throw out the special case of c being an exact zero now */

            shift128RightJamming(pSig0, pSig1, 64, &pSig0, &pSig1);

            return roundAndPackFloat64(zSign, pExp - 1,

                                       pSig1 STATUS_VAR);

        }

        normalizeFloat64Subnormal(cSig, &cExp, &cSig);

    }

    /* Shift cSig and add the explicit bit so [cSig0:cSig1] is the

     * significand of the addend, with the explicit bit in position 126.

     */

    cSig0 = cSig << (126 - 64 - 52);

    cSig1 = 0;

    cSig0 |= LIT64(0x4000000000000000);

    expDiff = pExp - cExp;

    if (pSign == cSign) {

        /* Addition */

        if (expDiff > 0) {

            /* scale c to match p */

            shift128RightJamming(cSig0, cSig1, expDiff, &cSig0, &cSig1);

            zExp = pExp;

        } else if (expDiff < 0) {

            /* scale p to match c */

            shift128RightJamming(pSig0, pSig1, -expDiff, &pSig0, &pSig1);

            zExp = cExp;

        } else {

            /* no scaling needed */

            zExp = cExp;

        }

        /* Add significands and make sure explicit bit ends up in posn 126 */

        add128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

        if ((int64_t)zSig0 < 0) {

            shift128RightJamming(zSig0, zSig1, 1, &zSig0, &zSig1);

        } else {

            zExp--;

        }

        shift128RightJamming(zSig0, zSig1, 64, &zSig0, &zSig1);

        return roundAndPackFloat64(zSign, zExp, zSig1 STATUS_VAR);

    } else {

        /* Subtraction */

        if (expDiff > 0) {

            shift128RightJamming(cSig0, cSig1, expDiff, &cSig0, &cSig1);

            sub128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

            zExp = pExp;

        } else if (expDiff < 0) {

            shift128RightJamming(pSig0, pSig1, -expDiff, &pSig0, &pSig1);

            sub128(cSig0, cSig1, pSig0, pSig1, &zSig0, &zSig1);

            zExp = cExp;

            zSign ^= 1;

        } else {

            zExp = pExp;

            if (lt128(cSig0, cSig1, pSig0, pSig1)) {

                sub128(pSig0, pSig1, cSig0, cSig1, &zSig0, &zSig1);

            } else if (lt128(pSig0, pSig1, cSig0, cSig1)) {

                sub128(cSig0, cSig1, pSig0, pSig1, &zSig0, &zSig1);

                zSign ^= 1;

            } else {

                /* Exact zero */

                zSign = signflip;

                if (STATUS(float_rounding_mode) == float_round_down) {

                    zSign ^= 1;

                }

                return packFloat64(zSign, 0, 0);

            }

        }

        --zExp;

        /* Do the equivalent of normalizeRoundAndPackFloat64() but

         * starting with the significand in a pair of uint64_t.

         */

        if (zSig0) {

            shiftcount = countLeadingZeros64(zSig0) - 1;

            shortShift128Left(zSig0, zSig1, shiftcount, &zSig0, &zSig1);

            if (zSig1) {

                zSig0 |= 1;

            }

            zExp -= shiftcount;

        } else {

            shiftcount = countLeadingZeros64(zSig1) - 1;

            zSig0 = zSig1 << shiftcount;

            zExp -= (shiftcount + 64);

        }

        return roundAndPackFloat64(zSign, zExp, zSig0 STATUS_VAR);

    }

}


static void vga_precise_update_retrace_info(VGACommonState *s)

{

    int htotal_chars;

    int hretr_start_char;

    int hretr_skew_chars;

    int hretr_end_char;

    int vtotal_lines;

    int vretr_start_line;

    int vretr_end_line;

    int dots;

#if 0

    int div2, sldiv2;

#endif

    int clocking_mode;

    int clock_sel;

    const int clk_hz[] = {25175000, 28322000, 25175000, 25175000};

    int64_t chars_per_sec;

    struct vga_precise_retrace *r = &s->retrace_info.precise;

    htotal_chars = s->cr[VGA_CRTC_H_TOTAL] + 5;

    hretr_start_char = s->cr[VGA_CRTC_H_SYNC_START];

    hretr_skew_chars = (s->cr[VGA_CRTC_H_SYNC_END] >> 5) & 3;

    hretr_end_char = s->cr[VGA_CRTC_H_SYNC_END] & 0x1f;

    vtotal_lines = (s->cr[VGA_CRTC_V_TOTAL] |

                    (((s->cr[VGA_CRTC_OVERFLOW] & 1) |

                      ((s->cr[VGA_CRTC_OVERFLOW] >> 4) & 2)) << 8)) + 2;

    vretr_start_line = s->cr[VGA_CRTC_V_SYNC_START] |

        ((((s->cr[VGA_CRTC_OVERFLOW] >> 2) & 1) |

          ((s->cr[VGA_CRTC_OVERFLOW] >> 6) & 2)) << 8);

    vretr_end_line = s->cr[VGA_CRTC_V_SYNC_END] & 0xf;

    clocking_mode = (s->sr[VGA_SEQ_CLOCK_MODE] >> 3) & 1;

    clock_sel = (s->msr >> 2) & 3;

    dots = (s->msr & 1) ? 8 : 9;

    chars_per_sec = clk_hz[clock_sel] / dots;

    htotal_chars <<= clocking_mode;

    r->total_chars = vtotal_lines * htotal_chars;

    if (r->freq) {

        r->ticks_per_char = NANOSECONDS_PER_SECOND / (r->total_chars * r->freq);

    } else {

        r->ticks_per_char = NANOSECONDS_PER_SECOND / chars_per_sec;

    }

    r->vstart = vretr_start_line;

    r->vend = r->vstart + vretr_end_line + 1;

    r->hstart = hretr_start_char + hretr_skew_chars;

    r->hend = r->hstart + hretr_end_char + 1;

    r->htotal = htotal_chars;

#if 0

    div2 = (s->cr[VGA_CRTC_MODE] >> 2) & 1;

    sldiv2 = (s->cr[VGA_CRTC_MODE] >> 3) & 1;

    printf (

        "hz=%f\n"

        "htotal = %d\n"

        "hretr_start = %d\n"

        "hretr_skew = %d\n"

        "hretr_end = %d\n"

        "vtotal = %d\n"

        "vretr_start = %d\n"

        "vretr_end = %d\n"

        "div2 = %d sldiv2 = %d\n"

        "clocking_mode = %d\n"

        "clock_sel = %d %d\n"

        "dots = %d\n"

        "ticks/char = %" PRId64 "\n"

        "\n",

        (double) NANOSECONDS_PER_SECOND / (r->ticks_per_char * r->total_chars),

        htotal_chars,

        hretr_start_char,

        hretr_skew_chars,

        hretr_end_char,

        vtotal_lines,

        vretr_start_line,

        vretr_end_line,

        div2, sldiv2,

        clocking_mode,

        clock_sel,

        clk_hz[clock_sel],

        dots,

        r->ticks_per_char

        );

#endif

}


static void diag288_timer_expired(void *dev)

{

    qemu_log_mask(CPU_LOG_RESET, "Watchdog timer expired.\n");

    watchdog_perform_action();

    /* Reset the watchdog only if the guest was notified about expiry. */

    switch (get_watchdog_action()) {

    case WDT_DEBUG:

    case WDT_NONE:

    case WDT_PAUSE:

         return;

    }

    wdt_diag288_reset(dev);

}


void pcie_aer_inject_error_print(Monitor *mon, const QObject *data)

{

    QDict *qdict;

    int devfn;

    assert(qobject_type(data) == QTYPE_QDICT);

    qdict = qobject_to_qdict(data);

    devfn = (int)qdict_get_int(qdict, "devfn");

    monitor_printf(mon, "OK id: %s root bus: %s, bus: %x devfn: %x.%x\n",

                   qdict_get_str(qdict, "id"),

                   qdict_get_str(qdict, "root_bus"),

                   (int) qdict_get_int(qdict, "bus"),

                   PCI_SLOT(devfn), PCI_FUNC(devfn));

}


static void gen_branch(DisasContext *ctx, int insn_bytes)

{

    if (ctx->hflags & MIPS_HFLAG_BMASK) {

        int proc_hflags = ctx->hflags & MIPS_HFLAG_BMASK;

        /* Branches completion */

        ctx->hflags &= ~MIPS_HFLAG_BMASK;

        ctx->bstate = BS_BRANCH;

        save_cpu_state(ctx, 0);

        /* FIXME: Need to clear can_do_io.  */

        switch (proc_hflags & MIPS_HFLAG_BMASK_BASE) {

        case MIPS_HFLAG_FBNSLOT:

            MIPS_DEBUG("forbidden slot");

            gen_goto_tb(ctx, 0, ctx->pc + insn_bytes);

            break;

        case MIPS_HFLAG_B:

            /* unconditional branch */

            MIPS_DEBUG("unconditional branch");

            if (proc_hflags & MIPS_HFLAG_BX) {

                tcg_gen_xori_i32(hflags, hflags, MIPS_HFLAG_M16);

            }

            gen_goto_tb(ctx, 0, ctx->btarget);

            break;

        case MIPS_HFLAG_BL:

            /* blikely taken case */

            MIPS_DEBUG("blikely branch taken");

            gen_goto_tb(ctx, 0, ctx->btarget);

            break;

        case MIPS_HFLAG_BC:

            /* Conditional branch */

            MIPS_DEBUG("conditional branch");

            {

                TCGLabel *l1 = gen_new_label();

                tcg_gen_brcondi_tl(TCG_COND_NE, bcond, 0, l1);

                gen_goto_tb(ctx, 1, ctx->pc + insn_bytes);

                gen_set_label(l1);

                gen_goto_tb(ctx, 0, ctx->btarget);

            }

            break;

        case MIPS_HFLAG_BR:

            /* unconditional branch to register */

            MIPS_DEBUG("branch to register");

            if (ctx->insn_flags & (ASE_MIPS16 | ASE_MICROMIPS)) {

                TCGv t0 = tcg_temp_new();

                TCGv_i32 t1 = tcg_temp_new_i32();

                tcg_gen_andi_tl(t0, btarget, 0x1);

                tcg_gen_trunc_tl_i32(t1, t0);

                tcg_temp_free(t0);

                tcg_gen_andi_i32(hflags, hflags, ~(uint32_t)MIPS_HFLAG_M16);

                tcg_gen_shli_i32(t1, t1, MIPS_HFLAG_M16_SHIFT);

                tcg_gen_or_i32(hflags, hflags, t1);

                tcg_temp_free_i32(t1);

                tcg_gen_andi_tl(cpu_PC, btarget, ~(target_ulong)0x1);

            } else {

                tcg_gen_mov_tl(cpu_PC, btarget);

            }

            if (ctx->singlestep_enabled) {

                save_cpu_state(ctx, 0);

                gen_helper_0e0i(raise_exception, EXCP_DEBUG);

            }

            tcg_gen_exit_tb(0);

            break;

        default:

            MIPS_DEBUG("unknown branch");

            break;

        }

    }

}


static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,

                             int buf_size, void *data)

{

    FlacEncodeContext *s;

    const int16_t *samples = data;

    int frame_bytes, out_bytes;

    s = avctx->priv_data;

    /* when the last block is reached, update the header in extradata */

    if (!data) {

        s->max_framesize = s->max_encoded_framesize;

        av_md5_final(s->md5ctx, s->md5sum);

        write_streaminfo(s, avctx->extradata);

        return 0;

    }

    /* change max_framesize for small final frame */

    if (avctx->frame_size < s->frame.blocksize) {

        s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,

                                                      s->channels, 16);

    }

    init_frame(s);

    copy_samples(s, samples);

    channel_decorrelation(s);

    frame_bytes = encode_frame(s);

    if (buf_size < frame_bytes) {

        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");

        return 0;

    }

    out_bytes = write_frame(s, frame, buf_size);

    /* fallback to verbatim mode if the compressed frame is larger than it

       would be if encoded uncompressed. */

    if (out_bytes > s->max_framesize) {

        s->frame.verbatim_only = 1;

        frame_bytes = encode_frame(s);

        if (buf_size < frame_bytes) {

            av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");

            return 0;

        }

        out_bytes = write_frame(s, frame, buf_size);

    }

    s->frame_count++;

    avctx->coded_frame->pts = s->sample_count;

    s->sample_count += avctx->frame_size;

    update_md5_sum(s, samples);

    if (out_bytes > s->max_encoded_framesize)

        s->max_encoded_framesize = out_bytes;

    if (out_bytes < s->min_framesize)

        s->min_framesize = out_bytes;

    return out_bytes;

}


static int dnxhd_decode_frame(AVCodecContext *avctx, void *data,

                              int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    DNXHDContext *ctx = avctx->priv_data;

    ThreadFrame frame = { .f = data };

    AVFrame *picture = data;

    int first_field = 1;

    int ret, i;

    ff_dlog(avctx, "frame size %d\n", buf_size);

decode_coding_unit:

    if ((ret = dnxhd_decode_header(ctx, picture, buf, buf_size, first_field)) < 0)

        return ret;

    if ((avctx->width || avctx->height) &&

        (ctx->width != avctx->width || ctx->height != avctx->height)) {

        av_log(avctx, AV_LOG_WARNING, "frame size changed: %dx%d -> %dx%d\n",

               avctx->width, avctx->height, ctx->width, ctx->height);

        first_field = 1;

    }

    if (avctx->pix_fmt != AV_PIX_FMT_NONE && avctx->pix_fmt != ctx->pix_fmt) {

        av_log(avctx, AV_LOG_WARNING, "pix_fmt changed: %s -> %s\n",

               av_get_pix_fmt_name(avctx->pix_fmt), av_get_pix_fmt_name(ctx->pix_fmt));

        first_field = 1;

    }

    avctx->pix_fmt = ctx->pix_fmt;

    ret = ff_set_dimensions(avctx, ctx->width, ctx->height);

    if (ret < 0)

        return ret;

    if (first_field) {

        if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

            return ret;

        picture->pict_type = AV_PICTURE_TYPE_I;

        picture->key_frame = 1;

    }

    ctx->buf_size = buf_size - 0x280;

    ctx->buf = buf + 0x280;

    avctx->execute2(avctx, dnxhd_decode_row, picture, NULL, ctx->mb_height);

    if (first_field && picture->interlaced_frame) {

        buf      += ctx->cid_table->coding_unit_size;

        buf_size -= ctx->cid_table->coding_unit_size;

        first_field = 0;

        goto decode_coding_unit;

    }

    ret = 0;

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

        ret += ctx->rows[i].errors;

        ctx->rows[i].errors = 0;

    }

    if (ret) {

        av_log(ctx->avctx, AV_LOG_ERROR, "%d lines with errors\n", ret);

        return AVERROR_INVALIDDATA;

    }

    *got_frame = 1;

    return avpkt->size;

}


qemu_irq qemu_irq_invert(qemu_irq irq)

{

    /* The default state for IRQs is low, so raise the output now.  */

    qemu_irq_raise(irq);

    return qemu_allocate_irqs(qemu_notirq, irq, 1)[0];

}


static int dca_exss_parse_asset_header(DCAContext *s)

{

    int header_pos = get_bits_count(&s->gb);

    int header_size;

    int channels;

    int embedded_stereo = 0;

    int embedded_6ch    = 0;

    int drc_code_present;

    int extensions_mask;

    int i, j;

    if (get_bits_left(&s->gb) < 16)

        return -1;

    /* We will parse just enough to get to the extensions bitmask with which

     * we can set the profile value. */

    header_size = get_bits(&s->gb, 9) + 1;

    skip_bits(&s->gb, 3); // asset index

    if (s->static_fields) {

        if (get_bits1(&s->gb))

            skip_bits(&s->gb, 4); // asset type descriptor

        if (get_bits1(&s->gb))

            skip_bits_long(&s->gb, 24); // language descriptor

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

            /* How can one fit 1024 bytes of text here if the maximum value

             * for the asset header size field above was 512 bytes? */

            int text_length = get_bits(&s->gb, 10) + 1;

            if (get_bits_left(&s->gb) < text_length * 8)

                return -1;

            skip_bits_long(&s->gb, text_length * 8); // info text

        }

        skip_bits(&s->gb, 5); // bit resolution - 1

        skip_bits(&s->gb, 4); // max sample rate code

        channels = get_bits(&s->gb, 8) + 1;

        if (get_bits1(&s->gb)) { // 1-to-1 channels to speakers

            int spkr_remap_sets;

            int spkr_mask_size = 16;

            int num_spkrs[7];

            if (channels > 2)

                embedded_stereo = get_bits1(&s->gb);

            if (channels > 6)

                embedded_6ch = get_bits1(&s->gb);

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

                spkr_mask_size = (get_bits(&s->gb, 2) + 1) << 2;

                skip_bits(&s->gb, spkr_mask_size); // spkr activity mask

            }

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

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

                /* std layout mask for each remap set */

                num_spkrs[i] = dca_exss_mask2count(get_bits(&s->gb, spkr_mask_size));

            }

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

                int num_dec_ch_remaps = get_bits(&s->gb, 5) + 1;

                if (get_bits_left(&s->gb) < 0)

                    return -1;

                for (j = 0; j < num_spkrs[i]; j++) {

                    int remap_dec_ch_mask = get_bits_long(&s->gb, num_dec_ch_remaps);

                    int num_dec_ch = av_popcount(remap_dec_ch_mask);

                    skip_bits_long(&s->gb, num_dec_ch * 5); // remap codes

                }

            }

        } else {

            skip_bits(&s->gb, 3); // representation type

        }

    }

    drc_code_present = get_bits1(&s->gb);

    if (drc_code_present)

        get_bits(&s->gb, 8); // drc code

    if (get_bits1(&s->gb))

        skip_bits(&s->gb, 5); // dialog normalization code

    if (drc_code_present && embedded_stereo)

        get_bits(&s->gb, 8); // drc stereo code

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

        skip_bits(&s->gb, 1); // external mix

        skip_bits(&s->gb, 6); // post mix gain code

        if (get_bits(&s->gb, 2) != 3) // mixer drc code

            skip_bits(&s->gb, 3); // drc limit

        else

            skip_bits(&s->gb, 8); // custom drc code

        if (get_bits1(&s->gb)) // channel specific scaling

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

                skip_bits_long(&s->gb, s->mix_config_num_ch[i] * 6); // scale codes

        else

            skip_bits_long(&s->gb, s->num_mix_configs * 6); // scale codes

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

            if (get_bits_left(&s->gb) < 0)

                return -1;

            dca_exss_skip_mix_coeffs(&s->gb, channels, s->mix_config_num_ch[i]);

            if (embedded_6ch)

                dca_exss_skip_mix_coeffs(&s->gb, 6, s->mix_config_num_ch[i]);

            if (embedded_stereo)

                dca_exss_skip_mix_coeffs(&s->gb, 2, s->mix_config_num_ch[i]);

        }

    }

    switch (get_bits(&s->gb, 2)) {

    case 0: extensions_mask = get_bits(&s->gb, 12); break;

    case 1: extensions_mask = DCA_EXT_EXSS_XLL;     break;

    case 2: extensions_mask = DCA_EXT_EXSS_LBR;     break;

    case 3: extensions_mask = 0; /* aux coding */   break;

    }

    /* not parsed further, we were only interested in the extensions mask */

    if (get_bits_left(&s->gb) < 0)

        return -1;

    if (get_bits_count(&s->gb) - header_pos > header_size * 8) {

        av_log(s->avctx, AV_LOG_WARNING, "Asset header size mismatch.\n");

        return -1;

    }

    skip_bits_long(&s->gb, header_pos + header_size * 8 - get_bits_count(&s->gb));

    if (extensions_mask & DCA_EXT_EXSS_XLL)

        s->profile = FF_PROFILE_DTS_HD_MA;

    else if (extensions_mask & (DCA_EXT_EXSS_XBR | DCA_EXT_EXSS_X96 |

                                DCA_EXT_EXSS_XXCH))

        s->profile = FF_PROFILE_DTS_HD_HRA;

    if (!(extensions_mask & DCA_EXT_CORE))

        av_log(s->avctx, AV_LOG_WARNING, "DTS core detection mismatch.\n");

    if ((extensions_mask & DCA_CORE_EXTS) != s->core_ext_mask)

        av_log(s->avctx, AV_LOG_WARNING,

               "DTS extensions detection mismatch (%d, %d)\n",

               extensions_mask & DCA_CORE_EXTS, s->core_ext_mask);

    return 0;

}


void ff_aac_search_for_ltp(AACEncContext *s, SingleChannelElement *sce,

                           int common_window)

{

    int w, g, w2, i, start = 0, count = 0;

    int saved_bits = -(15 + FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB));

    float *C34 = &s->scoefs[128*0], *PCD = &s->scoefs[128*1];

    float *PCD34 = &s->scoefs[128*2];

    const int max_ltp = FFMIN(sce->ics.max_sfb, MAX_LTP_LONG_SFB);

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) {

        if (sce->ics.ltp.lag) {

            memset(&sce->lcoeffs[0], 0.0f, 3072*sizeof(sce->lcoeffs[0]));

            memset(&sce->ics.ltp, 0, sizeof(LongTermPrediction));

        }

        return;

    }

    if (!sce->ics.ltp.lag)

        return;

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        start = 0;

        for (g = 0;  g < sce->ics.num_swb; g++) {

            int bits1 = 0, bits2 = 0;

            float dist1 = 0.0f, dist2 = 0.0f;

            if (w*16+g > max_ltp) {

                start += sce->ics.swb_sizes[g];

                continue;

            }

            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                int bits_tmp1, bits_tmp2;

                FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];

                for (i = 0; i < sce->ics.swb_sizes[g]; i++)

                    PCD[i] = sce->coeffs[start+(w+w2)*128+i] - sce->lcoeffs[start+(w+w2)*128+i];

                abs_pow34_v(C34,  &sce->coeffs[start+(w+w2)*128],  sce->ics.swb_sizes[g]);

                abs_pow34_v(PCD34, PCD, sce->ics.swb_sizes[g]);

                dist1 += quantize_band_cost(s, &sce->coeffs[start+(w+w2)*128], C34, sce->ics.swb_sizes[g],

                                            sce->sf_idx[(w+w2)*16+g], sce->band_type[(w+w2)*16+g],

                                            s->lambda/band->threshold, INFINITY, &bits_tmp1, NULL, 0);

                dist2 += quantize_band_cost(s, PCD, PCD34, sce->ics.swb_sizes[g],

                                            sce->sf_idx[(w+w2)*16+g],

                                            sce->band_type[(w+w2)*16+g],

                                            s->lambda/band->threshold, INFINITY, &bits_tmp2, NULL, 0);

                bits1 += bits_tmp1;

                bits2 += bits_tmp2;

            }

            if (dist2 < dist1 && bits2 < bits1) {

                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)

                    for (i = 0; i < sce->ics.swb_sizes[g]; i++)

                        sce->coeffs[start+(w+w2)*128+i] -= sce->lcoeffs[start+(w+w2)*128+i];

                sce->ics.ltp.used[w*16+g] = 1;

                saved_bits += bits1 - bits2;

                count++;

            }

            start += sce->ics.swb_sizes[g];

        }

    }

    sce->ics.ltp.present = !!count && (saved_bits >= 0);

    sce->ics.predictor_present = !!sce->ics.ltp.present;

    /* Reset any marked sfbs */

    if (!sce->ics.ltp.present && !!count) {

        for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

            start = 0;

            for (g = 0;  g < sce->ics.num_swb; g++) {

                if (sce->ics.ltp.used[w*16+g]) {

                    for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                        for (i = 0; i < sce->ics.swb_sizes[g]; i++) {

                            sce->coeffs[start+(w+w2)*128+i] += sce->lcoeffs[start+(w+w2)*128+i];

                        }

                    }

                }

                start += sce->ics.swb_sizes[g];

            }

        }

    }

}


static void gen_std(DisasContext *ctx)

{

    int rs;

    TCGv EA;

    rs = rS(ctx->opcode);

    if ((ctx->opcode & 0x3) == 0x2) {

#if defined(CONFIG_USER_ONLY)

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

        /* stq */

        if (unlikely(ctx->mem_idx == 0)) {

            gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

            return;

        }

        if (unlikely(rs & 1)) {

            gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

            return;

        }

        if (unlikely(ctx->le_mode)) {

            /* Little-endian mode is not handled */

            gen_exception_err(ctx, POWERPC_EXCP_ALIGN, POWERPC_EXCP_ALIGN_LE);

            return;

        }

        gen_set_access_type(ctx, ACCESS_INT);

        EA = tcg_temp_new();

        gen_addr_imm_index(ctx, EA, 0x03);

        gen_qemu_st64(ctx, cpu_gpr[rs], EA);

        gen_addr_add(ctx, EA, EA, 8);

        gen_qemu_st64(ctx, cpu_gpr[rs+1], EA);

        tcg_temp_free(EA);

#endif

    } else {

        /* std / stdu */

        if (Rc(ctx->opcode)) {

            if (unlikely(rA(ctx->opcode) == 0)) {

                gen_inval_exception(ctx, POWERPC_EXCP_INVAL_INVAL);

                return;

            }

        }

        gen_set_access_type(ctx, ACCESS_INT);

        EA = tcg_temp_new();

        gen_addr_imm_index(ctx, EA, 0x03);

        gen_qemu_st64(ctx, cpu_gpr[rs], EA);

        if (Rc(ctx->opcode))

            tcg_gen_mov_tl(cpu_gpr[rA(ctx->opcode)], EA);

        tcg_temp_free(EA);

    }

}


static int parse_vtrk(AVFormatContext *s,

                      FourxmDemuxContext *fourxm, uint8_t *buf, int size,

                      int left)

{

    AVStream *st;

    /* check that there is enough data */

    if (size != vtrk_SIZE || left < size + 8) {

        return AVERROR_INVALIDDATA;

    }

    /* allocate a new AVStream */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 60, 1, fourxm->fps);

    fourxm->video_stream_index = st->index;

    st->codec->codec_type     = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id       = AV_CODEC_ID_4XM;

    st->codec->extradata_size = 4;

    st->codec->extradata      = av_malloc(4);

    AV_WL32(st->codec->extradata, AV_RL32(buf + 16));

    st->codec->width  = AV_RL32(buf + 36);

    st->codec->height = AV_RL32(buf + 40);

    return 0;

}


static void free_test_data(test_data *data)

{

    AcpiSdtTable *temp;

    int i;

    g_free(data->rsdt_tables_addr);

    for (i = 0; i < data->tables->len; ++i) {

        temp = &g_array_index(data->tables, AcpiSdtTable, i);

        g_free(temp->aml);

        if (temp->aml_file &&

            !temp->tmp_files_retain &&

            g_strstr_len(temp->aml_file, -1, "aml-")) {

            unlink(temp->aml_file);

        }

        g_free(temp->aml_file);

        g_free(temp->asl);

        if (temp->asl_file &&

            !temp->tmp_files_retain) {

            unlink(temp->asl_file);

        }

        g_free(temp->asl_file);

    }

    g_array_free(data->tables, false);

}