static void hls_transform_tree(HEVCContext *s, int x0, int y0,

                               int xBase, int yBase, int cb_xBase, int cb_yBase,

                               int log2_cb_size, int log2_trafo_size,

                               int trafo_depth, int blk_idx)

{

    HEVCLocalContext *lc = &s->HEVClc;

    uint8_t split_transform_flag;

    if (trafo_depth > 0 && log2_trafo_size == 2) {

        SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =

            SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase);

        SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =

            SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase);

    } else {

        SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =

        SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) = 0;

    }

    if (lc->cu.intra_split_flag) {

        if (trafo_depth == 1)

            lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[blk_idx];

    } else {

        lc->tu.cur_intra_pred_mode = lc->pu.intra_pred_mode[0];

    }

    lc->tt.cbf_luma = 1;

    lc->tt.inter_split_flag = s->sps->max_transform_hierarchy_depth_inter == 0 &&

                              lc->cu.pred_mode == MODE_INTER &&

                              lc->cu.part_mode != PART_2Nx2N &&

                              trafo_depth == 0;

    if (log2_trafo_size <= s->sps->log2_max_trafo_size &&

        log2_trafo_size >  s->sps->log2_min_tb_size    &&

        trafo_depth     < lc->cu.max_trafo_depth       &&

        !(lc->cu.intra_split_flag && trafo_depth == 0)) {

        split_transform_flag = ff_hevc_split_transform_flag_decode(s, log2_trafo_size);

    } else {

        split_transform_flag = log2_trafo_size > s->sps->log2_max_trafo_size ||

                               (lc->cu.intra_split_flag && trafo_depth == 0) ||

                               lc->tt.inter_split_flag;

    }

    if (log2_trafo_size > 2) {

        if (trafo_depth == 0 ||

            SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth - 1], xBase, yBase)) {

            SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) =

                ff_hevc_cbf_cb_cr_decode(s, trafo_depth);

        }

        if (trafo_depth == 0 ||

            SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth - 1], xBase, yBase)) {

            SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0) =

                ff_hevc_cbf_cb_cr_decode(s, trafo_depth);

        }

    }

    if (split_transform_flag) {

        int x1 = x0 + ((1 << log2_trafo_size) >> 1);

        int y1 = y0 + ((1 << log2_trafo_size) >> 1);

        hls_transform_tree(s, x0, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,

                           log2_trafo_size - 1, trafo_depth + 1, 0);

        hls_transform_tree(s, x1, y0, x0, y0, cb_xBase, cb_yBase, log2_cb_size,

                           log2_trafo_size - 1, trafo_depth + 1, 1);

        hls_transform_tree(s, x0, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,

                           log2_trafo_size - 1, trafo_depth + 1, 2);

        hls_transform_tree(s, x1, y1, x0, y0, cb_xBase, cb_yBase, log2_cb_size,

                           log2_trafo_size - 1, trafo_depth + 1, 3);

    } else {

        int min_tu_size      = 1 << s->sps->log2_min_tb_size;

        int log2_min_tu_size = s->sps->log2_min_tb_size;

        int min_tu_width     = s->sps->min_tb_width;

        if (lc->cu.pred_mode == MODE_INTRA || trafo_depth != 0 ||

            SAMPLE_CBF(lc->tt.cbf_cb[trafo_depth], x0, y0) ||

            SAMPLE_CBF(lc->tt.cbf_cr[trafo_depth], x0, y0)) {

            lc->tt.cbf_luma = ff_hevc_cbf_luma_decode(s, trafo_depth);

        }

        hls_transform_unit(s, x0, y0, xBase, yBase, cb_xBase, cb_yBase,

                           log2_cb_size, log2_trafo_size, trafo_depth, blk_idx);

        // TODO: store cbf_luma somewhere else

        if (lc->tt.cbf_luma) {

            int i, j;

            for (i = 0; i < (1 << log2_trafo_size); i += min_tu_size)

                for (j = 0; j < (1 << log2_trafo_size); j += min_tu_size) {

                    int x_tu = (x0 + j) >> log2_min_tu_size;

                    int y_tu = (y0 + i) >> log2_min_tu_size;

                    s->cbf_luma[y_tu * min_tu_width + x_tu] = 1;

                }

        }

        if (!s->sh.disable_deblocking_filter_flag) {

            ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_trafo_size,

                                                  lc->slice_or_tiles_up_boundary,

                                                  lc->slice_or_tiles_left_boundary);

            if (s->pps->transquant_bypass_enable_flag &&

                lc->cu.cu_transquant_bypass_flag)

                set_deblocking_bypass(s, x0, y0, log2_trafo_size);

        }

    }

}


static void aw_pulse_set2(WMAVoiceContext *s, GetBitContext *gb,

                          int block_idx, AMRFixed *fcb)

{

    uint16_t use_mask_mem[9]; // only 5 are used, rest is padding

    uint16_t *use_mask = use_mask_mem + 2;

    /* in this function, idx is the index in the 80-bit (+ padding) use_mask

     * bit-array. Since use_mask consists of 16-bit values, the lower 4 bits

     * of idx are the position of the bit within a particular item in the

     * array (0 being the most significant bit, and 15 being the least

     * significant bit), and the remainder (>> 4) is the index in the

     * use_mask[]-array. This is faster and uses less memory than using a

     * 80-byte/80-int array. */

    int pulse_off = s->aw_first_pulse_off[block_idx],

        pulse_start, n, idx, range, aidx, start_off = 0;

    /* set offset of first pulse to within this block */

    if (s->aw_n_pulses[block_idx] > 0)

        while (pulse_off + s->aw_pulse_range < 1)

            pulse_off += fcb->pitch_lag;

    /* find range per pulse */

    if (s->aw_n_pulses[0] > 0) {

        if (block_idx == 0) {

            range = 32;

        } else /* block_idx = 1 */ {

            range = 8;

            if (s->aw_n_pulses[block_idx] > 0)

                pulse_off = s->aw_next_pulse_off_cache;

        }

    } else

        range = 16;

    pulse_start = s->aw_n_pulses[block_idx] > 0 ? pulse_off - range / 2 : 0;

    /* aw_pulse_set1() already applies pulses around pulse_off (to be exactly,

     * in the range of [pulse_off, pulse_off + s->aw_pulse_range], and thus

     * we exclude that range from being pulsed again in this function. */

    memset(&use_mask[-2], 0, 2 * sizeof(use_mask[0]));

    memset( use_mask,   -1, 5 * sizeof(use_mask[0]));

    memset(&use_mask[5], 0, 2 * sizeof(use_mask[0]));

    if (s->aw_n_pulses[block_idx] > 0)

        for (idx = pulse_off; idx < MAX_FRAMESIZE / 2; idx += fcb->pitch_lag) {

            int excl_range         = s->aw_pulse_range; // always 16 or 24

            uint16_t *use_mask_ptr = &use_mask[idx >> 4];

            int first_sh           = 16 - (idx & 15);

            *use_mask_ptr++       &= 0xFFFF << first_sh;

            excl_range            -= first_sh;

            if (excl_range >= 16) {

                *use_mask_ptr++    = 0;

                *use_mask_ptr     &= 0xFFFF >> (excl_range - 16);

            } else

                *use_mask_ptr     &= 0xFFFF >> excl_range;

        }

    /* find the 'aidx'th offset that is not excluded */

    aidx = get_bits(gb, s->aw_n_pulses[0] > 0 ? 5 - 2 * block_idx : 4);

    for (n = 0; n <= aidx; pulse_start++) {

        for (idx = pulse_start; idx < 0; idx += fcb->pitch_lag) ;

        if (idx >= MAX_FRAMESIZE / 2) { // find from zero

            if (use_mask[0])      idx = 0x0F;

            else if (use_mask[1]) idx = 0x1F;

            else if (use_mask[2]) idx = 0x2F;

            else if (use_mask[3]) idx = 0x3F;

            else if (use_mask[4]) idx = 0x4F;

            else                  return;

            idx -= av_log2_16bit(use_mask[idx >> 4]);

        }

        if (use_mask[idx >> 4] & (0x8000 >> (idx & 15))) {

            use_mask[idx >> 4] &= ~(0x8000 >> (idx & 15));

            n++;

            start_off = idx;

        }

    }

    fcb->x[fcb->n] = start_off;

    fcb->y[fcb->n] = get_bits1(gb) ? -1.0 : 1.0;

    fcb->n++;

    /* set offset for next block, relative to start of that block */

    n = (MAX_FRAMESIZE / 2 - start_off) % fcb->pitch_lag;

    s->aw_next_pulse_off_cache = n ? fcb->pitch_lag - n : 0;

}


static void asf_build_simple_index(AVFormatContext *s, int stream_index)

{

    ff_asf_guid g;

    ASFContext *asf     = s->priv_data;

    int64_t current_pos = avio_tell(s->pb);

    int i;

    avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);

    ff_get_guid(s->pb, &g);

    /* the data object can be followed by other top-level objects,

     * skip them until the simple index object is reached */

    while (ff_guidcmp(&g, &index_guid)) {

        int64_t gsize = avio_rl64(s->pb);

        if (gsize < 24 || s->pb->eof_reached) {

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

            return;

        }

        avio_skip(s->pb, gsize - 24);

        ff_get_guid(s->pb, &g);

    }

    {

        int64_t itime, last_pos = -1;

        int pct, ict;

        int64_t av_unused gsize = avio_rl64(s->pb);

        ff_get_guid(s->pb, &g);

        itime = avio_rl64(s->pb);

        pct   = avio_rl32(s->pb);

        ict   = avio_rl32(s->pb);

        av_log(s, AV_LOG_DEBUG,

               "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict);

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

            int pktnum        = avio_rl32(s->pb);

            int pktct         = avio_rl16(s->pb);

            int64_t pos       = s->data_offset + s->packet_size * (int64_t)pktnum;

            int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);

            if (pos != last_pos) {

                av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n",

                       pktnum, pktct, index_pts);

                av_add_index_entry(s->streams[stream_index], pos, index_pts,

                                   s->packet_size, 0, AVINDEX_KEYFRAME);

                last_pos = pos;

            }

        }

        asf->index_read = ict > 0;

    }

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

}


static void bdrv_qed_drain(BlockDriverState *bs)

{

    BDRVQEDState *s = bs->opaque;

    /* Cancel timer and start doing I/O that were meant to happen as if it

     * fired, that way we get bdrv_drain() taking care of the ongoing requests

     * correctly. */

    qed_cancel_need_check_timer(s);

    qed_plug_allocating_write_reqs(s);

    bdrv_aio_flush(s->bs, qed_clear_need_check, s);

}


static void test_qemu_strtol_invalid(void)

{

    const char *str = "   xxxx  \t abc";

    char f = 'X';

    const char *endptr = &f;

    long res = 999;

    int err;

    err = qemu_strtol(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

    g_assert(endptr == str);

}


static int check_bind(const char *hostname, bool *has_proto)

{

    int fd = -1;

    struct addrinfo ai, *res = NULL;

    int rc;

    int ret = -1;

    memset(&ai, 0, sizeof(ai));

    ai.ai_flags = AI_CANONNAME | AI_V4MAPPED | AI_ADDRCONFIG;

    ai.ai_family = AF_UNSPEC;

    ai.ai_socktype = SOCK_STREAM;

    /* lookup */

    rc = getaddrinfo(hostname, NULL, &ai, &res);

    if (rc != 0) {

        if (rc == EAI_ADDRFAMILY ||

            rc == EAI_FAMILY) {

            *has_proto = false;

            goto done;

        }

        goto cleanup;

    }

    fd = qemu_socket(res->ai_family, res->ai_socktype, res->ai_protocol);

    if (fd < 0) {

        goto cleanup;

    }

    if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) {

        if (errno == EADDRNOTAVAIL) {

            *has_proto = false;

            goto done;

        }

        goto cleanup;

    }

    *has_proto = true;

 done:

    ret = 0;

 cleanup:

    if (fd != -1) {

        close(fd);

    }

    if (res) {

        freeaddrinfo(res);

    }

    return ret;

}


static bool run_poll_handlers(AioContext *ctx, int64_t max_ns)

{

    bool progress = false;

    int64_t end_time;

    assert(ctx->notify_me);

    assert(ctx->walking_handlers > 0);

    assert(ctx->poll_disable_cnt == 0);

    trace_run_poll_handlers_begin(ctx, max_ns);

    end_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + max_ns;

    do {

        AioHandler *node;

        QLIST_FOREACH(node, &ctx->aio_handlers, node) {

            if (!node->deleted && node->io_poll &&

                node->io_poll(node->opaque)) {

                progress = true;

            }

            /* Caller handles freeing deleted nodes.  Don't do it here. */

        }

    } while (!progress && qemu_clock_get_ns(QEMU_CLOCK_REALTIME) < end_time);

    trace_run_poll_handlers_end(ctx, progress);

    return progress;

}


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

                                     int *got_frame, AVPacket *avpkt)

{

    ScreenpressoContext *ctx = avctx->priv_data;

    AVFrame *frame = data;

    int keyframe;

    int ret;

    /* Size check */

    if (avpkt->size < 3) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small (%d)\n", avpkt->size);

        return AVERROR_INVALIDDATA;

    }

    /* Basic sanity check, but not really harmful */

    if ((avpkt->data[0] != 0x73 && avpkt->data[0] != 0x72) ||

        avpkt->data[1] != 8) { // bpp probably

        av_log(avctx, AV_LOG_WARNING, "Unknown header 0x%02X%02X\n",

               avpkt->data[0], avpkt->data[1]);

    }

    keyframe = (avpkt->data[0] == 0x73);

    /* Resize deflate buffer and frame on resolution change */

    if (ctx->inflated_size != avctx->width * avctx->height * 3) {

        av_frame_unref(ctx->current);

        ret = ff_get_buffer(avctx, ctx->current, AV_GET_BUFFER_FLAG_REF);

        if (ret < 0)

            return ret;

        /* If malloc fails, reset len to avoid preserving an invalid value */

        ctx->inflated_size = avctx->width * avctx->height * 3;

        ret = av_reallocp(&ctx->inflated_buf, ctx->inflated_size);

        if (ret < 0) {

            ctx->inflated_size = 0;

            return ret;

        }

    }

    /* Inflate the frame after the 2 byte header */

    ret = uncompress(ctx->inflated_buf, &ctx->inflated_size,

                     avpkt->data + 2, avpkt->size - 2);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Deflate error %d.\n", ret);

        return AVERROR_UNKNOWN;

    }

    /* When a keyframe is found, copy it (flipped) */

    if (keyframe)

        av_image_copy_plane(ctx->current->data[0] +

                            ctx->current->linesize[0] * (avctx->height - 1),

                            -1 * ctx->current->linesize[0],

                            ctx->inflated_buf, avctx->width * 3,

                            avctx->width * 3, avctx->height);

    /* Otherwise sum the delta on top of the current frame */

    else

        sum_delta_flipped(ctx->current->data[0], ctx->current->linesize[0],

                          ctx->inflated_buf, avctx->width * 3,

                          avctx->width * 3, avctx->height);

    /* Frame is ready to be output */

    ret = av_frame_ref(frame, ctx->current);

    if (ret < 0)

        return ret;

    /* Usual properties */

    if (keyframe) {

        frame->pict_type = AV_PICTURE_TYPE_I;

        frame->key_frame = 1;

    } else {

        frame->pict_type = AV_PICTURE_TYPE_P;

    }

    *got_frame = 1;

    return 0;

}


static inline TCGv iwmmxt_load_creg(int reg)

{

    TCGv var = new_tmp();

    tcg_gen_ld_i32(var, cpu_env, offsetof(CPUState, iwmmxt.cregs[reg]));

    return var;

}


void HELPER(set_cp_reg64)(CPUARMState *env, void *rip, uint64_t value)

{

    const ARMCPRegInfo *ri = rip;

    ri->writefn(env, ri, value);

}


static void vhost_scsi_stop(VHostSCSI *s)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    int ret = 0;

    if (!k->set_guest_notifiers) {

        ret = k->set_guest_notifiers(qbus->parent, s->dev.nvqs, false);

        if (ret < 0) {

                error_report("vhost guest notifier cleanup failed: %d\n", ret);

        }

    }

    assert(ret >= 0);

    vhost_scsi_clear_endpoint(s);

    vhost_dev_stop(&s->dev, vdev);

    vhost_dev_disable_notifiers(&s->dev, vdev);

}


static void start_tco(const TestData *d)

{

    uint32_t val;

    val = qpci_io_readw(d->dev, d->tco_io_base + TCO1_CNT);

    val &= ~TCO_TMR_HLT;

    qpci_io_writew(d->dev, d->tco_io_base + TCO1_CNT, val);

}


void memory_global_dirty_log_stop(void)

{

    global_dirty_log = false;

    /* Refresh DIRTY_LOG_MIGRATION bit.  */

    memory_region_transaction_begin();

    memory_region_update_pending = true;

    memory_region_transaction_commit();

    MEMORY_LISTENER_CALL_GLOBAL(log_global_stop, Reverse);

}


static inline int open_by_handle(int mountfd, const char *fh, int flags)

{

    errno = ENOSYS;

    return -1;

}


static void cmd_get_event_status_notification(IDEState *s,

                                              uint8_t *buf)

{

    const uint8_t *packet = buf;

    struct {

        uint8_t opcode;

        uint8_t polled;        /* lsb bit is polled; others are reserved */

        uint8_t reserved2[2];

        uint8_t class;

        uint8_t reserved3[2];

        uint16_t len;

        uint8_t control;

    } __attribute__((packed)) *gesn_cdb;

    struct {

        uint16_t len;

        uint8_t notification_class;

        uint8_t supported_events;

    } __attribute((packed)) *gesn_event_header;

    enum notification_class_request_type {

        NCR_RESERVED1 = 1 << 0,

        NCR_OPERATIONAL_CHANGE = 1 << 1,

        NCR_POWER_MANAGEMENT = 1 << 2,

        NCR_EXTERNAL_REQUEST = 1 << 3,

        NCR_MEDIA = 1 << 4,

        NCR_MULTI_HOST = 1 << 5,

        NCR_DEVICE_BUSY = 1 << 6,

        NCR_RESERVED2 = 1 << 7,

    };

    enum event_notification_class_field {

        ENC_NO_EVENTS = 0,

        ENC_OPERATIONAL_CHANGE,

        ENC_POWER_MANAGEMENT,

        ENC_EXTERNAL_REQUEST,

        ENC_MEDIA,

        ENC_MULTIPLE_HOSTS,

        ENC_DEVICE_BUSY,

        ENC_RESERVED,

    };

    unsigned int max_len, used_len;

    gesn_cdb = (void *)packet;

    gesn_event_header = (void *)buf;

    max_len = be16_to_cpu(gesn_cdb->len);

    /* It is fine by the MMC spec to not support async mode operations */

    if (!(gesn_cdb->polled & 0x01)) { /* asynchronous mode */

        /* Only polling is supported, asynchronous mode is not. */

        ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST,

                            ASC_INV_FIELD_IN_CMD_PACKET);

        return;

    }

    /* polling mode operation */

    /*

     * These are the supported events.

     *

     * We currently only support requests of the 'media' type.

     */

    gesn_event_header->supported_events = NCR_MEDIA;

    /*

     * We use |= below to set the class field; other bits in this byte

     * are reserved now but this is useful to do if we have to use the

     * reserved fields later.

     */

    gesn_event_header->notification_class = 0;

    /*

     * Responses to requests are to be based on request priority.  The

     * notification_class_request_type enum above specifies the

     * priority: upper elements are higher prio than lower ones.

     */

    if (gesn_cdb->class & NCR_MEDIA) {

        gesn_event_header->notification_class |= ENC_MEDIA;

        used_len = event_status_media(s, buf);

    } else {

        gesn_event_header->notification_class = 0x80; /* No event available */

        used_len = sizeof(*gesn_event_header);

    }

    gesn_event_header->len = cpu_to_be16(used_len

                                         - sizeof(*gesn_event_header));

    ide_atapi_cmd_reply(s, used_len, max_len);

}


static int decode_plane(UtvideoContext *c, int plane_no,

                        uint8_t *dst, int step, ptrdiff_t stride,

                        int width, int height,

                        const uint8_t *src, int use_pred)

{

    int i, j, slice, pix;

    int sstart, send;

    VLC vlc;

    GetBitContext gb;

    int prev, fsym;

    const int cmask = c->interlaced ? ~(1 + 2 * (!plane_no && c->avctx->pix_fmt == AV_PIX_FMT_YUV420P)) : ~(!plane_no && c->avctx->pix_fmt == AV_PIX_FMT_YUV420P);

    if (build_huff(src, &vlc, &fsym)) {

        av_log(c->avctx, AV_LOG_ERROR, "Cannot build Huffman codes\n");

        return AVERROR_INVALIDDATA;

    }

    if (fsym >= 0) { // build_huff reported a symbol to fill slices with

        send = 0;

        for (slice = 0; slice < c->slices; slice++) {

            uint8_t *dest;

            sstart = send;

            send   = (height * (slice + 1) / c->slices) & cmask;

            dest   = dst + sstart * stride;

            prev = 0x80;

            for (j = sstart; j < send; j++) {

                for (i = 0; i < width * step; i += step) {

                    pix = fsym;

                    if (use_pred) {

                        prev += pix;

                        pix   = prev;

                    }

                    dest[i] = pix;

                }

                dest += stride;

            }

        }

        return 0;

    }

    src      += 256;

    send = 0;

    for (slice = 0; slice < c->slices; slice++) {

        uint8_t *dest;

        int slice_data_start, slice_data_end, slice_size;

        sstart = send;

        send   = (height * (slice + 1) / c->slices) & cmask;

        dest   = dst + sstart * stride;

        // slice offset and size validation was done earlier

        slice_data_start = slice ? AV_RL32(src + slice * 4 - 4) : 0;

        slice_data_end   = AV_RL32(src + slice * 4);

        slice_size       = slice_data_end - slice_data_start;

        if (!slice_size) {

            av_log(c->avctx, AV_LOG_ERROR, "Plane has more than one symbol "

                   "yet a slice has a length of zero.\n");

            goto fail;

        }

        memset(c->slice_bits + slice_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

        c->bdsp.bswap_buf((uint32_t *) c->slice_bits,

                          (uint32_t *)(src + slice_data_start + c->slices * 4),

                          (slice_data_end - slice_data_start + 3) >> 2);

        init_get_bits(&gb, c->slice_bits, slice_size * 8);

        prev = 0x80;

        for (j = sstart; j < send; j++) {

            for (i = 0; i < width * step; i += step) {

                pix = get_vlc2(&gb, vlc.table, VLC_BITS, 3);

                if (pix < 0) {

                    av_log(c->avctx, AV_LOG_ERROR, "Decoding error\n");

                    goto fail;

                }

                if (use_pred) {

                    prev += pix;

                    pix   = prev;

                }

                dest[i] = pix;

            }

            if (get_bits_left(&gb) < 0) {

                av_log(c->avctx, AV_LOG_ERROR,

                        "Slice decoding ran out of bits\n");

                goto fail;

            }

            dest += stride;

        }

        if (get_bits_left(&gb) > 32)

            av_log(c->avctx, AV_LOG_WARNING,

                   "%d bits left after decoding slice\n", get_bits_left(&gb));

    }

    ff_free_vlc(&vlc);

    return 0;

fail:

    ff_free_vlc(&vlc);

    return AVERROR_INVALIDDATA;

}


static int ogg_buffer_data(AVFormatContext *s, AVStream *st,

                           uint8_t *data, unsigned size, int64_t granule,

                           int header)

{

    OGGStreamContext *oggstream = st->priv_data;

    OGGContext *ogg = s->priv_data;

    int total_segments = size / 255 + 1;

    uint8_t *p = data;

    int i, segments, len, flush = 0;

    // Handles VFR by flushing page because this frame needs to have a timestamp

    // For theora, keyframes also need to have a timestamp to correctly mark

    // them as such, otherwise seeking will not work correctly at the very

    // least with old libogg versions.

    // Do not try to flush header packets though, that will create broken files.

    if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&

        (ogg_granule_to_timestamp(oggstream, granule) >

         ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||

         ogg_key_granule(oggstream, granule))) {

        if (oggstream->page.granule != -1)

            ogg_buffer_page(s, oggstream);

        flush = 1;

    }

    // avoid a continued page

    if (!header && oggstream->page.size > 0 &&

        MAX_PAGE_SIZE - oggstream->page.size < size) {

        ogg_buffer_page(s, oggstream);

    }

    for (i = 0; i < total_segments; ) {

        OGGPage *page = &oggstream->page;

        segments = FFMIN(total_segments - i, 255 - page->segments_count);

        if (i && !page->segments_count)

            page->flags |= 1; // continued packet

        memset(page->segments+page->segments_count, 255, segments - 1);

        page->segments_count += segments - 1;

        len = FFMIN(size, segments*255);

        page->segments[page->segments_count++] = len - (segments-1)*255;

        memcpy(page->data+page->size, p, len);

        p += len;

        size -= len;

        i += segments;

        page->size += len;

        if (i == total_segments)

            page->granule = granule;

        if (!header) {

            AVStream *st = s->streams[page->stream_index];

            int64_t start = av_rescale_q(page->start_granule, st->time_base,

                                         AV_TIME_BASE_Q);

            int64_t next  = av_rescale_q(page->granule, st->time_base,

                                         AV_TIME_BASE_Q);

            if (page->segments_count == 255 ||

                (ogg->pref_size     > 0 && page->size   >= ogg->pref_size) ||

                (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {

                ogg_buffer_page(s, oggstream);

            }

        }

    }

    if (flush && oggstream->page.granule != -1)

        ogg_buffer_page(s, oggstream);

    return 0;

}


void mpeg4_encode_picture_header(MpegEncContext * s, int picture_number)

{

    int time_incr;

    int time_div, time_mod;

    if(s->pict_type==AV_PICTURE_TYPE_I){

        if(!(s->flags&CODEC_FLAG_GLOBAL_HEADER)){

            if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT) //HACK, the reference sw is buggy

                mpeg4_encode_visual_object_header(s);

            if(s->strict_std_compliance < FF_COMPLIANCE_VERY_STRICT || picture_number==0) //HACK, the reference sw is buggy

                mpeg4_encode_vol_header(s, 0, 0);

        }

        if(!(s->workaround_bugs & FF_BUG_MS))

            mpeg4_encode_gop_header(s);

    }

    s->partitioned_frame= s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_B;

    put_bits(&s->pb, 16, 0);                /* vop header */

    put_bits(&s->pb, 16, VOP_STARTCODE);    /* vop header */

    put_bits(&s->pb, 2, s->pict_type - 1);  /* pict type: I = 0 , P = 1 */

    assert(s->time>=0);

    time_div= s->time/s->avctx->time_base.den;

    time_mod= s->time%s->avctx->time_base.den;

    time_incr= time_div - s->last_time_base;

    assert(time_incr >= 0);

    while(time_incr--)

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

    put_bits(&s->pb, 1, 0);

    put_bits(&s->pb, 1, 1);                             /* marker */

    put_bits(&s->pb, s->time_increment_bits, time_mod); /* time increment */

    put_bits(&s->pb, 1, 1);                             /* marker */

    put_bits(&s->pb, 1, 1);                             /* vop coded */

    if (    s->pict_type == AV_PICTURE_TYPE_P

        || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE)) {

        put_bits(&s->pb, 1, s->no_rounding);    /* rounding type */

    }

    put_bits(&s->pb, 3, 0);     /* intra dc VLC threshold */

    if(!s->progressive_sequence){

         put_bits(&s->pb, 1, s->current_picture_ptr->top_field_first);

         put_bits(&s->pb, 1, s->alternate_scan);

    }

    //FIXME sprite stuff

    put_bits(&s->pb, 5, s->qscale);

    if (s->pict_type != AV_PICTURE_TYPE_I)

        put_bits(&s->pb, 3, s->f_code); /* fcode_for */

    if (s->pict_type == AV_PICTURE_TYPE_B)

        put_bits(&s->pb, 3, s->b_code); /* fcode_back */

}


static void build_vlc(VLC *vlc, const uint8_t *bits_table, const uint8_t *val_table,

                      int nb_codes)

{

    uint8_t huff_size[256];

    uint16_t huff_code[256];

    memset(huff_size, 0, sizeof(huff_size));

    build_huffman_codes(huff_size, huff_code, bits_table, val_table);

    init_vlc(vlc, 9, nb_codes, huff_size, 1, 1, huff_code, 2, 2);

}


void qemu_coroutine_adjust_pool_size(int n)

{

    qemu_mutex_lock(&pool_lock);

    pool_max_size += n;

    /* Callers should never take away more than they added */

    assert(pool_max_size >= POOL_DEFAULT_SIZE);

    /* Trim oversized pool down to new max */

    while (pool_size > pool_max_size) {

        Coroutine *co = QSLIST_FIRST(&pool);

        QSLIST_REMOVE_HEAD(&pool, pool_next);

        pool_size--;

        qemu_coroutine_delete(co);

    }

    qemu_mutex_unlock(&pool_lock);

}


static void rndis_clear_responsequeue(USBNetState *s)

{

    struct rndis_response *r;

    while ((r = s->rndis_resp.tqh_first)) {

        TAILQ_REMOVE(&s->rndis_resp, r, entries);

        qemu_free(r);

    }

}


av_cold void ff_vp56dsp_init_x86(VP56DSPContext* c, enum AVCodecID codec)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (CONFIG_VP6_DECODER && codec == AV_CODEC_ID_VP6) {

#if ARCH_X86_32

        if (mm_flags & AV_CPU_FLAG_MMX) {

            c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx;

        }

#endif

        if (mm_flags & AV_CPU_FLAG_SSE2) {

            c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2;

        }

    }

#endif

}


int cpu_ppc_handle_mmu_fault (CPUState *env, uint32_t address, int rw,

                              int is_user, int is_softmmu)

{

    uint32_t physical;

    int prot;

    int exception = 0, error_code = 0;

    int access_type;

    int ret = 0;

//    printf("%s 0\n", __func__);

    access_type = env->access_type;

    if (env->user_mode_only) {

        /* user mode only emulation */

        ret = -2;

        goto do_fault;

    }

    /* NASTY BUG workaround */

    if (access_type == ACCESS_CODE && rw) {

	printf("%s: ERROR WRITE CODE ACCESS\n", __func__);

	access_type = ACCESS_INT;

    }

    ret = get_physical_address(env, &physical, &prot,

                               address, rw, access_type);

    if (ret == 0) {

	ret = tlb_set_page(env, address & ~0xFFF, physical, prot,

			   is_user, is_softmmu);

    } else if (ret < 0) {

    do_fault:

#if defined (DEBUG_MMU)

	if (loglevel > 0)

	    cpu_ppc_dump_state(env, logfile, 0);

#endif

        if (access_type == ACCESS_CODE) {

            exception = EXCP_ISI;

            switch (ret) {

            case -1:

                /* No matches in page tables */

                error_code = EXCP_ISI_TRANSLATE;

                break;

            case -2:

                /* Access rights violation */

                error_code = EXCP_ISI_PROT;

                break;

            case -3:

		/* No execute protection violation */

                error_code = EXCP_ISI_NOEXEC;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                error_code = EXCP_ISI_DIRECT;

                break;

            }

        } else {

            exception = EXCP_DSI;

            switch (ret) {

            case -1:

                /* No matches in page tables */

                error_code = EXCP_DSI_TRANSLATE;

                break;

            case -2:

                /* Access rights violation */

                error_code = EXCP_DSI_PROT;

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    exception = EXCP_ALIGN;

                    error_code = EXCP_ALIGN_FP;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or srwcx. */

                    exception = EXCP_DSI;

                    error_code = EXCP_DSI_NOTSUP | EXCP_DSI_DIRECT;

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    exception = EXCP_DSI;

                    error_code = EXCP_DSI_NOTSUP | EXCP_DSI_DIRECT |

			EXCP_DSI_ECXW;

                    break;

                default:

		    printf("DSI: invalid exception (%d)\n", ret);

                    exception = EXCP_PROGRAM;

                    error_code = EXCP_INVAL | EXCP_INVAL_INVAL;

                    break;

                }

            }

            if (rw)

                error_code |= EXCP_DSI_STORE;

	    /* Store fault address */

	    env->spr[DAR] = address;

        }

#if 0

        printf("%s: set exception to %d %02x\n",

               __func__, exception, error_code);

#endif

        env->exception_index = exception;

        env->error_code = error_code;

        ret = 1;

    }

    return ret;

}


static void spatial_decompose53i(DWTELEM *buffer, int width, int height, int stride){

    int y;

    DWTELEM *b0= buffer + mirror(-2-1, height-1)*stride;

    DWTELEM *b1= buffer + mirror(-2  , height-1)*stride;

    for(y=-2; y<height; y+=2){

        DWTELEM *b2= buffer + mirror(y+1, height-1)*stride;

        DWTELEM *b3= buffer + mirror(y+2, height-1)*stride;

{START_TIMER

        if(b1 <= b3)     horizontal_decompose53i(b2, width);

        if(y+2 < height) horizontal_decompose53i(b3, width);

STOP_TIMER("horizontal_decompose53i")}

{START_TIMER

        if(b1 <= b3) vertical_decompose53iH0(b1, b2, b3, width);

        if(b0 <= b2) vertical_decompose53iL0(b0, b1, b2, width);

STOP_TIMER("vertical_decompose53i*")}

        b0=b2;

        b1=b3;

    }

}


static int sd_truncate(BlockDriverState *bs, int64_t offset)

{

    BDRVSheepdogState *s = bs->opaque;

    int ret, fd;

    unsigned int datalen;

    if (offset < s->inode.vdi_size) {

        error_report("shrinking is not supported");

        return -EINVAL;

    } else if (offset > SD_MAX_VDI_SIZE) {

        error_report("too big image size");

        return -EINVAL;

    }

    fd = connect_to_sdog(s->addr, s->port);

    if (fd < 0) {

        return fd;

    }

    /* we don't need to update entire object */

    datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);

    s->inode.vdi_size = offset;

    ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),

                       s->inode.nr_copies, datalen, 0, false, s->cache_enabled);

    close(fd);

    if (ret < 0) {

        error_report("failed to update an inode.");

    }

    return ret;

}


static int rndis_parse(USBNetState *s, uint8_t *data, int length)

{

    uint32_t msg_type;

    le32 *tmp = (le32 *) data;

    msg_type = le32_to_cpup(tmp);

    switch (msg_type) {

    case RNDIS_INITIALIZE_MSG:

        s->rndis_state = RNDIS_INITIALIZED;

        return rndis_init_response(s, (rndis_init_msg_type *) data);

    case RNDIS_HALT_MSG:

        s->rndis_state = RNDIS_UNINITIALIZED;

        return 0;

    case RNDIS_QUERY_MSG:

        return rndis_query_response(s, (rndis_query_msg_type *) data, length);

    case RNDIS_SET_MSG:

        return rndis_set_response(s, (rndis_set_msg_type *) data, length);

    case RNDIS_RESET_MSG:

        rndis_clear_responsequeue(s);

        s->out_ptr = s->in_ptr = s->in_len = 0;

        return rndis_reset_response(s, (rndis_reset_msg_type *) data);

    case RNDIS_KEEPALIVE_MSG:

        /* For USB: host does this every 5 seconds */

        return rndis_keepalive_response(s, (rndis_keepalive_msg_type *) data);

    }

    return USB_RET_STALL;

}


static int sap_write_header(AVFormatContext *s)

{

    struct SAPState *sap = s->priv_data;

    char host[1024], path[1024], url[1024], announce_addr[50] = "";

    char *option_list;

    int port = 9875, base_port = 5004, i, pos = 0, same_port = 0, ttl = 255;

    AVFormatContext **contexts = NULL;

    int ret = 0;

    struct sockaddr_storage localaddr;

    socklen_t addrlen = sizeof(localaddr);

    int udp_fd;

    AVDictionaryEntry* title = av_dict_get(s->metadata, "title", NULL, 0);

    if (!ff_network_init())

        return AVERROR(EIO);

    /* extract hostname and port */

    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &base_port,

                 path, sizeof(path), s->filename);

    if (base_port < 0)

        base_port = 5004;

    /* search for options */

    option_list = strrchr(path, '?');

    if (option_list) {

        char buf[50];

        if (av_find_info_tag(buf, sizeof(buf), "announce_port", option_list)) {

            port = strtol(buf, NULL, 10);

        }

        if (av_find_info_tag(buf, sizeof(buf), "same_port", option_list)) {

            same_port = strtol(buf, NULL, 10);

        }

        if (av_find_info_tag(buf, sizeof(buf), "ttl", option_list)) {

            ttl = strtol(buf, NULL, 10);

        }

        if (av_find_info_tag(buf, sizeof(buf), "announce_addr", option_list)) {

            av_strlcpy(announce_addr, buf, sizeof(announce_addr));

        }

    }

    if (!announce_addr[0]) {

        struct addrinfo hints = { 0 }, *ai = NULL;

        hints.ai_family = AF_UNSPEC;

        if (getaddrinfo(host, NULL, &hints, &ai)) {

            av_log(s, AV_LOG_ERROR, "Unable to resolve %s\n", host);

            ret = AVERROR(EIO);

            goto fail;

        }

        if (ai->ai_family == AF_INET) {

            /* Also known as sap.mcast.net */

            av_strlcpy(announce_addr, "224.2.127.254", sizeof(announce_addr));

#if HAVE_STRUCT_SOCKADDR_IN6

        } else if (ai->ai_family == AF_INET6) {

            /* With IPv6, you can use the same destination in many different

             * multicast subnets, to choose how far you want it routed.

             * This one is intended to be routed globally. */

            av_strlcpy(announce_addr, "ff0e::2:7ffe", sizeof(announce_addr));

#endif

        } else {

            freeaddrinfo(ai);

            av_log(s, AV_LOG_ERROR, "Host %s resolved to unsupported "

                                    "address family\n", host);

            ret = AVERROR(EIO);

            goto fail;

        }

        freeaddrinfo(ai);

    }

    sap->protocols = ffurl_get_protocols(NULL, NULL);

    if (!sap->protocols) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    contexts = av_mallocz(sizeof(AVFormatContext*) * s->nb_streams);

    if (!contexts) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    s->start_time_realtime = av_gettime();

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

        URLContext *fd;

        ff_url_join(url, sizeof(url), "rtp", NULL, host, base_port,

                    "?ttl=%d", ttl);

        if (!same_port)

            base_port += 2;

        ret = ffurl_open(&fd, url, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL,

                         sap->protocols);

        if (ret) {

            ret = AVERROR(EIO);

            goto fail;

        }

        ret = ff_rtp_chain_mux_open(&contexts[i], s, s->streams[i], fd, 0, i);

        if (ret < 0)

            goto fail;

        s->streams[i]->priv_data = contexts[i];

        s->streams[i]->time_base = contexts[i]->streams[0]->time_base;

        av_strlcpy(contexts[i]->filename, url, sizeof(contexts[i]->filename));

    }

    if (s->nb_streams > 0 && title)

        av_dict_set(&contexts[0]->metadata, "title", title->value, 0);

    ff_url_join(url, sizeof(url), "udp", NULL, announce_addr, port,

                "?ttl=%d&connect=1", ttl);

    ret = ffurl_open(&sap->ann_fd, url, AVIO_FLAG_WRITE,

                     &s->interrupt_callback, NULL, sap->protocols);

    if (ret) {

        ret = AVERROR(EIO);

        goto fail;

    }

    udp_fd = ffurl_get_file_handle(sap->ann_fd);

    if (getsockname(udp_fd, (struct sockaddr*) &localaddr, &addrlen)) {

        ret = AVERROR(EIO);

        goto fail;

    }

    if (localaddr.ss_family != AF_INET

#if HAVE_STRUCT_SOCKADDR_IN6

        && localaddr.ss_family != AF_INET6

#endif

        ) {

        av_log(s, AV_LOG_ERROR, "Unsupported protocol family\n");

        ret = AVERROR(EIO);

        goto fail;

    }

    sap->ann_size = 8192;

    sap->ann = av_mallocz(sap->ann_size);

    if (!sap->ann) {

        ret = AVERROR(EIO);

        goto fail;

    }

    sap->ann[pos] = (1 << 5);

#if HAVE_STRUCT_SOCKADDR_IN6

    if (localaddr.ss_family == AF_INET6)

        sap->ann[pos] |= 0x10;

#endif

    pos++;

    sap->ann[pos++] = 0; /* Authentication length */

    AV_WB16(&sap->ann[pos], av_get_random_seed());

    pos += 2;

    if (localaddr.ss_family == AF_INET) {

        memcpy(&sap->ann[pos], &((struct sockaddr_in*)&localaddr)->sin_addr,

               sizeof(struct in_addr));

        pos += sizeof(struct in_addr);

#if HAVE_STRUCT_SOCKADDR_IN6

    } else {

        memcpy(&sap->ann[pos], &((struct sockaddr_in6*)&localaddr)->sin6_addr,

               sizeof(struct in6_addr));

        pos += sizeof(struct in6_addr);

#endif

    }

    av_strlcpy(&sap->ann[pos], "application/sdp", sap->ann_size - pos);

    pos += strlen(&sap->ann[pos]) + 1;

    if (av_sdp_create(contexts, s->nb_streams, &sap->ann[pos],

                      sap->ann_size - pos)) {

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    av_freep(&contexts);

    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", &sap->ann[pos]);

    pos += strlen(&sap->ann[pos]);

    sap->ann_size = pos;

    if (sap->ann_size > sap->ann_fd->max_packet_size) {

        av_log(s, AV_LOG_ERROR, "Announcement too large to send in one "

                                "packet\n");

        goto fail;

    }

    return 0;

fail:

    av_free(contexts);

    sap_write_close(s);

    return ret;

}


static void hls_prediction_unit(HEVCContext *s, int x0, int y0,

                                int nPbW, int nPbH,

                                int log2_cb_size, int partIdx, int idx)

{

#define POS(c_idx, x, y)                                                              \

    &s->frame->data[c_idx][((y) >> s->sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \

                           (((x) >> s->sps->hshift[c_idx]) << s->sps->pixel_shift)]

    HEVCLocalContext *lc = s->HEVClc;

    int merge_idx = 0;

    struct MvField current_mv = {{{ 0 }}};

    int min_pu_width = s->sps->min_pu_width;

    MvField *tab_mvf = s->ref->tab_mvf;

    RefPicList  *refPicList = s->ref->refPicList;

    HEVCFrame *ref0, *ref1;

    uint8_t *dst0 = POS(0, x0, y0);

    uint8_t *dst1 = POS(1, x0, y0);

    uint8_t *dst2 = POS(2, x0, y0);

    int log2_min_cb_size = s->sps->log2_min_cb_size;

    int min_cb_width     = s->sps->min_cb_width;

    int x_cb             = x0 >> log2_min_cb_size;

    int y_cb             = y0 >> log2_min_cb_size;

    int x_pu, y_pu;

    int i, j;

    int skip_flag = SAMPLE_CTB(s->skip_flag, x_cb, y_cb);

    if (!skip_flag)

        lc->pu.merge_flag = ff_hevc_merge_flag_decode(s);

    if (skip_flag || lc->pu.merge_flag) {

        if (s->sh.max_num_merge_cand > 1)

            merge_idx = ff_hevc_merge_idx_decode(s);

        else

            merge_idx = 0;

        ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,

                                   partIdx, merge_idx, &current_mv);

    } else {

        hevc_luma_mv_mpv_mode(s, x0, y0, nPbW, nPbH, log2_cb_size,

                              partIdx, merge_idx, &current_mv);

    }

    x_pu = x0 >> s->sps->log2_min_pu_size;

    y_pu = y0 >> s->sps->log2_min_pu_size;

    for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++)

        for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++)

            tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv;

    if (current_mv.pred_flag & PF_L0) {

        ref0 = refPicList[0].ref[current_mv.ref_idx[0]];

        if (!ref0)

            return;

        hevc_await_progress(s, ref0, &current_mv.mv[0], y0, nPbH);

    }

    if (current_mv.pred_flag & PF_L1) {

        ref1 = refPicList[1].ref[current_mv.ref_idx[1]];

        if (!ref1)

            return;

        hevc_await_progress(s, ref1, &current_mv.mv[1], y0, nPbH);

    }

    if (current_mv.pred_flag == PF_L0) {

        int x0_c = x0 >> s->sps->hshift[1];

        int y0_c = y0 >> s->sps->vshift[1];

        int nPbW_c = nPbW >> s->sps->hshift[1];

        int nPbH_c = nPbH >> s->sps->vshift[1];

        luma_mc_uni(s, dst0, s->frame->linesize[0], ref0->frame,

                    &current_mv.mv[0], x0, y0, nPbW, nPbH,

                    s->sh.luma_weight_l0[current_mv.ref_idx[0]],

                    s->sh.luma_offset_l0[current_mv.ref_idx[0]]);

        chroma_mc_uni(s, dst1, s->frame->linesize[1], ref0->frame->data[1], ref0->frame->linesize[1],

                      0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,

                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0]);

        chroma_mc_uni(s, dst2, s->frame->linesize[2], ref0->frame->data[2], ref0->frame->linesize[2],

                      0, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,

                      s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1]);

    } else if (current_mv.pred_flag == PF_L1) {

        int x0_c = x0 >> s->sps->hshift[1];

        int y0_c = y0 >> s->sps->vshift[1];

        int nPbW_c = nPbW >> s->sps->hshift[1];

        int nPbH_c = nPbH >> s->sps->vshift[1];

        luma_mc_uni(s, dst0, s->frame->linesize[0], ref1->frame,

                    &current_mv.mv[1], x0, y0, nPbW, nPbH,

                    s->sh.luma_weight_l1[current_mv.ref_idx[1]],

                    s->sh.luma_offset_l1[current_mv.ref_idx[1]]);

        chroma_mc_uni(s, dst1, s->frame->linesize[1], ref1->frame->data[1], ref1->frame->linesize[1],

                      1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,

                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0]);

        chroma_mc_uni(s, dst2, s->frame->linesize[2], ref1->frame->data[2], ref1->frame->linesize[2],

                      1, x0_c, y0_c, nPbW_c, nPbH_c, &current_mv,

                      s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1]);

    } else if (current_mv.pred_flag == PF_BI) {

        int x0_c = x0 >> s->sps->hshift[1];

        int y0_c = y0 >> s->sps->vshift[1];

        int nPbW_c = nPbW >> s->sps->hshift[1];

        int nPbH_c = nPbH >> s->sps->vshift[1];

        luma_mc_bi(s, dst0, s->frame->linesize[0], ref0->frame,

                   &current_mv.mv[0], x0, y0, nPbW, nPbH,

                   ref1->frame, &current_mv.mv[1], &current_mv);

        chroma_mc_bi(s, dst1, s->frame->linesize[1], ref0->frame, ref1->frame,

                     x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 0);

        chroma_mc_bi(s, dst2, s->frame->linesize[2], ref0->frame, ref1->frame,

                     x0_c, y0_c, nPbW_c, nPbH_c, &current_mv, 1);

    }

}


static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOBlock *s = VIRTIO_BLK(vdev);

    VirtIOBlockReq *req;

    MultiReqBuffer mrb = {};

    /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start

     * dataplane here instead of waiting for .set_status().

     */

    if (s->dataplane) {

        virtio_blk_data_plane_start(s->dataplane);

        return;

    }

    blk_io_plug(s->blk);

    while ((req = virtio_blk_get_request(s))) {

        virtio_blk_handle_request(req, &mrb);

    }

    if (mrb.num_reqs) {

        virtio_blk_submit_multireq(s->blk, &mrb);

    }

    blk_io_unplug(s->blk);

}


static void av_noinline filter_mb_edgeh( uint8_t *pix, int stride, int16_t bS[4], unsigned int qp, H264Context *h ) {

    const unsigned int index_a = 52 + qp + h->slice_alpha_c0_offset;

    const int alpha = alpha_table[index_a];

    const int beta  = (beta_table+52)[qp + h->slice_beta_offset];

    if (alpha ==0 || beta == 0) return;

    if( bS[0] < 4 ) {

        int8_t tc[4];

        tc[0] = tc0_table[index_a][bS[0]];

        tc[1] = tc0_table[index_a][bS[1]];

        tc[2] = tc0_table[index_a][bS[2]];

        tc[3] = tc0_table[index_a][bS[3]];

        h->s.dsp.h264_v_loop_filter_luma(pix, stride, alpha, beta, tc);

    } else {

        h->s.dsp.h264_v_loop_filter_luma_intra(pix, stride, alpha, beta);

    }

}


static void realize(DeviceState *d, Error **errp)

{

    sPAPRDRConnector *drc = SPAPR_DR_CONNECTOR(d);

    Object *root_container;

    char link_name[256];

    gchar *child_name;

    Error *err = NULL;

    trace_spapr_drc_realize(spapr_drc_index(drc));

    /* NOTE: we do this as part of realize/unrealize due to the fact

     * that the guest will communicate with the DRC via RTAS calls

     * referencing the global DRC index. By unlinking the DRC

     * from DRC_CONTAINER_PATH/<drc_index> we effectively make it

     * inaccessible by the guest, since lookups rely on this path

     * existing in the composition tree

     */

    root_container = container_get(object_get_root(), DRC_CONTAINER_PATH);

    snprintf(link_name, sizeof(link_name), "%x", spapr_drc_index(drc));

    child_name = object_get_canonical_path_component(OBJECT(drc));

    trace_spapr_drc_realize_child(spapr_drc_index(drc), child_name);

    object_property_add_alias(root_container, link_name,

                              drc->owner, child_name, &err);

    g_free(child_name);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    vmstate_register(DEVICE(drc), spapr_drc_index(drc), &vmstate_spapr_drc,

                     drc);

    qemu_register_reset(drc_reset, drc);

    trace_spapr_drc_realize_complete(spapr_drc_index(drc));

}


static void gen_ld_asi(DisasContext *dc, TCGv dst, TCGv addr,

                       int insn, int size, int sign)

{

    TCGv_i32 r_asi, r_size, r_sign;

    r_asi = gen_get_asi(dc, insn);

    r_size = tcg_const_i32(size);

    r_sign = tcg_const_i32(sign);

#ifdef TARGET_SPARC64

    gen_helper_ld_asi(dst, cpu_env, addr, r_asi, r_size, r_sign);

#else

    {

        TCGv_i64 t64 = tcg_temp_new_i64();

        gen_helper_ld_asi(t64, cpu_env, addr, r_asi, r_size, r_sign);

        tcg_gen_trunc_i64_tl(dst, t64);

        tcg_temp_free_i64(t64);

    }

#endif

    tcg_temp_free_i32(r_sign);

    tcg_temp_free_i32(r_size);

    tcg_temp_free_i32(r_asi);

}


static inline float64 ucf64_itod(uint64_t i)

{

    union {

        uint64_t i;

        float64 d;

    } v;

    v.i = i;

    return v.d;

}


int tcg_gen_code(TCGContext *s, tcg_insn_unit *gen_code_buf)

{

    int i, oi, oi_next, num_insns;

#ifdef CONFIG_PROFILER

    {

        int n;

        n = s->gen_last_op_idx + 1;

        s->op_count += n;

        if (n > s->op_count_max) {

            s->op_count_max = n;

        }

        n = s->nb_temps;

        s->temp_count += n;

        if (n > s->temp_count_max) {

            s->temp_count_max = n;

        }

    }

#endif

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {

        qemu_log("OP:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

    }

#endif

#ifdef CONFIG_PROFILER

    s->opt_time -= profile_getclock();

#endif

#ifdef USE_TCG_OPTIMIZATIONS

    tcg_optimize(s);

#endif

#ifdef CONFIG_PROFILER

    s->opt_time += profile_getclock();

    s->la_time -= profile_getclock();

#endif

    tcg_liveness_analysis(s);

#ifdef CONFIG_PROFILER

    s->la_time += profile_getclock();

#endif

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) {

        qemu_log("OP after optimization and liveness analysis:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

    }

#endif

    tcg_reg_alloc_start(s);

    s->code_buf = gen_code_buf;

    s->code_ptr = gen_code_buf;

    tcg_out_tb_init(s);

    num_insns = -1;

    for (oi = s->gen_first_op_idx; oi >= 0; oi = oi_next) {

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

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

        TCGOpcode opc = op->opc;

        const TCGOpDef *def = &tcg_op_defs[opc];

        uint16_t dead_args = s->op_dead_args[oi];

        uint8_t sync_args = s->op_sync_args[oi];

        oi_next = op->next;

#ifdef CONFIG_PROFILER

        tcg_table_op_count[opc]++;

#endif

        switch (opc) {

        case INDEX_op_mov_i32:

        case INDEX_op_mov_i64:

            tcg_reg_alloc_mov(s, def, args, dead_args, sync_args);

            break;

        case INDEX_op_movi_i32:

        case INDEX_op_movi_i64:

            tcg_reg_alloc_movi(s, args, dead_args, sync_args);

            break;

        case INDEX_op_insn_start:

            if (num_insns >= 0) {

                s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);

            }

            num_insns++;

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

                target_ulong a;

#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS

                a = ((target_ulong)args[i * 2 + 1] << 32) | args[i * 2];

#else

                a = args[i];

#endif

                s->gen_insn_data[num_insns][i] = a;

            }

            break;

        case INDEX_op_discard:

            temp_dead(s, args[0]);

            break;

        case INDEX_op_set_label:

            tcg_reg_alloc_bb_end(s, s->reserved_regs);

            tcg_out_label(s, arg_label(args[0]), s->code_ptr);

            break;

        case INDEX_op_call:

            tcg_reg_alloc_call(s, op->callo, op->calli, args,

                               dead_args, sync_args);

            break;

        default:

            /* Sanity check that we've not introduced any unhandled opcodes. */

            if (def->flags & TCG_OPF_NOT_PRESENT) {

                tcg_abort();

            }

            /* Note: in order to speed up the code, it would be much

               faster to have specialized register allocator functions for

               some common argument patterns */

            tcg_reg_alloc_op(s, def, opc, args, dead_args, sync_args);

            break;

        }

#ifndef NDEBUG

        check_regs(s);

#endif

        /* Test for (pending) buffer overflow.  The assumption is that any

           one operation beginning below the high water mark cannot overrun

           the buffer completely.  Thus we can test for overflow after

           generating code without having to check during generation.  */

        if (unlikely((void *)s->code_ptr > s->code_gen_highwater)) {

            return -1;

        }

    }

    tcg_debug_assert(num_insns >= 0);

    s->gen_insn_end_off[num_insns] = tcg_current_code_size(s);

    /* Generate TB finalization at the end of block */

    tcg_out_tb_finalize(s);

    /* flush instruction cache */

    flush_icache_range((uintptr_t)s->code_buf, (uintptr_t)s->code_ptr);

    return tcg_current_code_size(s);

}


static int ehci_process_itd(EHCIState *ehci,

                            EHCIitd *itd)

{

    USBPort *port;

    USBDevice *dev;

    int ret;

    uint32_t i, j, len, pid, dir, devaddr, endp;

    uint32_t pg, off, ptr1, ptr2, max, mult;

    dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);

    devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);

    endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);

    max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);

    mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);

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

        if (itd->transact[i] & ITD_XACT_ACTIVE) {

            pg   = get_field(itd->transact[i], ITD_XACT_PGSEL);

            off  = itd->transact[i] & ITD_XACT_OFFSET_MASK;

            ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);

            ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);

            len  = get_field(itd->transact[i], ITD_XACT_LENGTH);

            if (len > max * mult) {

                len = max * mult;

            }

            if (len > BUFF_SIZE) {

                return USB_RET_PROCERR;

            }

            qemu_sglist_init(&ehci->isgl, 2);

            if (off + len > 4096) {

                /* transfer crosses page border */

                uint32_t len2 = off + len - 4096;

                uint32_t len1 = len - len2;

                qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);

                qemu_sglist_add(&ehci->isgl, ptr2, len2);

            } else {

                qemu_sglist_add(&ehci->isgl, ptr1 + off, len);

            }

            pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;

            usb_packet_setup(&ehci->ipacket, pid, devaddr, endp);

            usb_packet_map(&ehci->ipacket, &ehci->isgl);

            ret = USB_RET_NODEV;

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

                port = &ehci->ports[j];

                dev = port->dev;

                if (!(ehci->portsc[j] &(PORTSC_CONNECT))) {

                    continue;

                }

                ret = usb_handle_packet(dev, &ehci->ipacket);

                if (ret != USB_RET_NODEV) {

                    break;

                }

            }

            usb_packet_unmap(&ehci->ipacket);

            qemu_sglist_destroy(&ehci->isgl);

#if 0

            /*  In isoch, there is no facility to indicate a NAK so let's

             *  instead just complete a zero-byte transaction.  Setting

             *  DBERR seems too draconian.

             */

            if (ret == USB_RET_NAK) {

                if (ehci->isoch_pause > 0) {

                    DPRINTF("ISOCH: received a NAK but paused so returning\n");

                    ehci->isoch_pause--;

                    return 0;

                } else if (ehci->isoch_pause == -1) {

                    DPRINTF("ISOCH: recv NAK & isoch pause inactive, setting\n");

                    // Pause frindex for up to 50 msec waiting for data from

                    // remote

                    ehci->isoch_pause = 50;

                    return 0;

                } else {

                    DPRINTF("ISOCH: isoch pause timeout! return 0\n");

                    ret = 0;

                }

            } else {

                DPRINTF("ISOCH: received ACK, clearing pause\n");

                ehci->isoch_pause = -1;

            }

#else

            if (ret == USB_RET_NAK) {

                ret = 0;

            }

#endif

            if (ret >= 0) {

                if (!dir) {

                    /* OUT */

                    set_field(&itd->transact[i], len - ret, ITD_XACT_LENGTH);

                } else {

                    /* IN */

                    set_field(&itd->transact[i], ret, ITD_XACT_LENGTH);

                }

                if (itd->transact[i] & ITD_XACT_IOC) {

                    ehci_record_interrupt(ehci, USBSTS_INT);

                }

            }

            itd->transact[i] &= ~ITD_XACT_ACTIVE;

        }

    }

    return 0;

}


static void qmp_input_pop(Visitor *v, void **obj)

{

    QmpInputVisitor *qiv = to_qiv(v);

    StackObject *tos = QSLIST_FIRST(&qiv->stack);

    assert(tos && tos->qapi == obj);

    QSLIST_REMOVE_HEAD(&qiv->stack, node);

    qmp_input_stack_object_free(tos);

}


static int vmd_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    VmdDemuxContext *vmd = (VmdDemuxContext *)s->priv_data;

    ByteIOContext *pb = &s->pb;

    AVStream *st;

    unsigned int toc_offset;

    unsigned char *raw_frame_table;

    int raw_frame_table_size;

    offset_t current_offset;

    int i, j;

    unsigned int total_frames;

    int64_t video_pts_inc = 0;

    int64_t current_video_pts = 0;

    unsigned char chunk[BYTES_PER_FRAME_RECORD];

    int lastframe = 0;

    /* fetch the main header, including the 2 header length bytes */

    url_fseek(pb, 0, SEEK_SET);

    if (get_buffer(pb, vmd->vmd_header, VMD_HEADER_SIZE) != VMD_HEADER_SIZE)

        return AVERROR_IO;

    vmd->audio_sample_counter = 0;

    vmd->audio_frame_divisor = 1;

    vmd->audio_block_align = 1;

    /* start up the decoders */

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR_NOMEM;

    av_set_pts_info(st, 33, 1, 90000);

    vmd->video_stream_index = st->index;

    st->codec->codec_type = CODEC_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_VMDVIDEO;

    st->codec->codec_tag = 0;  /* no fourcc */

    st->codec->width = LE_16(&vmd->vmd_header[12]);

    st->codec->height = LE_16(&vmd->vmd_header[14]);

    st->codec->time_base.num = 1;

    st->codec->time_base.den = 10;

    st->codec->extradata_size = VMD_HEADER_SIZE;

    st->codec->extradata = av_mallocz(VMD_HEADER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);

    memcpy(st->codec->extradata, vmd->vmd_header, VMD_HEADER_SIZE);

    /* if sample rate is 0, assume no audio */

    vmd->sample_rate = LE_16(&vmd->vmd_header[804]);

    if (vmd->sample_rate) {

        st = av_new_stream(s, 0);

        if (!st)

            return AVERROR_NOMEM;

        av_set_pts_info(st, 33, 1, 90000);

        vmd->audio_stream_index = st->index;

        st->codec->codec_type = CODEC_TYPE_AUDIO;

        st->codec->codec_id = CODEC_ID_VMDAUDIO;

        st->codec->codec_tag = 0;  /* no fourcc */

        st->codec->channels = vmd->audio_channels = (vmd->vmd_header[811] & 0x80) ? 2 : 1;

        st->codec->sample_rate = vmd->sample_rate;

        st->codec->block_align = vmd->audio_block_align =

            LE_16(&vmd->vmd_header[806]);

        if (st->codec->block_align & 0x8000) {

            st->codec->bits_per_sample = 16;

            st->codec->block_align = -(st->codec->block_align - 0x10000);

            vmd->audio_block_align = -(vmd->audio_block_align - 0x10000);

        } else {

            st->codec->bits_per_sample = 8;

        st->codec->bit_rate = st->codec->sample_rate *

            st->codec->bits_per_sample * st->codec->channels;

        /* for calculating pts */

        vmd->audio_frame_divisor = st->codec->channels;

        video_pts_inc = 90000;

        video_pts_inc *= st->codec->block_align;

        video_pts_inc /= st->codec->sample_rate;

        video_pts_inc /= st->codec->channels;

    } else {

        /* if no audio, assume 10 frames/second */

        video_pts_inc = 90000 / 10;

    toc_offset = LE_32(&vmd->vmd_header[812]);

    vmd->frame_count = LE_16(&vmd->vmd_header[6]);

    vmd->frames_per_block = LE_16(&vmd->vmd_header[18]);

    url_fseek(pb, toc_offset, SEEK_SET);

    raw_frame_table = NULL;

    vmd->frame_table = NULL;

    raw_frame_table_size = vmd->frame_count * 6;

    raw_frame_table = av_malloc(raw_frame_table_size);

    vmd->frame_table = av_malloc(vmd->frame_count * vmd->frames_per_block * sizeof(vmd_frame_t));

    if (!raw_frame_table || !vmd->frame_table) {

        av_free(raw_frame_table);

        av_free(vmd->frame_table);

        return AVERROR_NOMEM;

    if (get_buffer(pb, raw_frame_table, raw_frame_table_size) !=

        raw_frame_table_size) {

        av_free(raw_frame_table);

        av_free(vmd->frame_table);

        return AVERROR_IO;

    total_frames = 0;

    for (i = 0; i < vmd->frame_count; i++) {

        current_offset = LE_32(&raw_frame_table[6 * i + 2]);

        /* handle each entry in index block */

        for (j = 0; j < vmd->frames_per_block; j++) {

            int type;

            uint32_t size;

            get_buffer(pb, chunk, BYTES_PER_FRAME_RECORD);

            type = chunk[0];

            size = LE_32(&chunk[2]);

            if(!size)

                continue;

            switch(type) {

            case 1: /* Audio Chunk */

                vmd->frame_table[total_frames].frame_offset = current_offset;

                vmd->frame_table[total_frames].stream_index = vmd->audio_stream_index;

                vmd->frame_table[total_frames].frame_size = size;

                memcpy(vmd->frame_table[total_frames].frame_record, chunk, BYTES_PER_FRAME_RECORD);

                total_frames++;

                break;

            case 2: /* Video Chunk */

                vmd->frame_table[total_frames].frame_offset = current_offset;

                vmd->frame_table[total_frames].frame_size = size;

                vmd->frame_table[total_frames].stream_index = vmd->video_stream_index;

                memcpy(vmd->frame_table[total_frames].frame_record, chunk, BYTES_PER_FRAME_RECORD);

                vmd->frame_table[total_frames].pts = current_video_pts;

                if (lastframe) {

                    vmd->frame_table[lastframe].pts = current_video_pts - video_pts_inc;

                lastframe = total_frames;

                total_frames++;

                break;

            current_offset += size;

        current_video_pts += video_pts_inc;

    av_free(raw_frame_table);

    vmd->current_frame = 0;

    vmd->frame_count = total_frames;

    return 0;


void dsputil_init_arm(DSPContext* c, AVCodecContext *avctx)

{

    int idct_algo= avctx->idct_algo;

    ff_put_pixels_clamped = c->put_pixels_clamped;

    ff_add_pixels_clamped = c->add_pixels_clamped;

    if (avctx->lowres == 0) {

        if(idct_algo == FF_IDCT_AUTO){

#if   HAVE_IPP

            idct_algo = FF_IDCT_IPP;

#elif HAVE_NEON

            idct_algo = FF_IDCT_SIMPLENEON;

#elif HAVE_ARMV6

            idct_algo = FF_IDCT_SIMPLEARMV6;

#elif HAVE_ARMV5TE

            idct_algo = FF_IDCT_SIMPLEARMV5TE;

#else

            idct_algo = FF_IDCT_ARM;

#endif

        }

        if(idct_algo==FF_IDCT_ARM){

            c->idct_put= j_rev_dct_ARM_put;

            c->idct_add= j_rev_dct_ARM_add;

            c->idct    = j_rev_dct_ARM;

            c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;

        } else if (idct_algo==FF_IDCT_SIMPLEARM){

            c->idct_put= simple_idct_ARM_put;

            c->idct_add= simple_idct_ARM_add;

            c->idct    = simple_idct_ARM;

            c->idct_permutation_type= FF_NO_IDCT_PERM;

#if HAVE_ARMV6

        } else if (idct_algo==FF_IDCT_SIMPLEARMV6){

            c->idct_put= ff_simple_idct_put_armv6;

            c->idct_add= ff_simple_idct_add_armv6;

            c->idct    = ff_simple_idct_armv6;

            c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM;

#endif

#if HAVE_ARMV5TE

        } else if (idct_algo==FF_IDCT_SIMPLEARMV5TE){

            c->idct_put= simple_idct_put_armv5te;

            c->idct_add= simple_idct_add_armv5te;

            c->idct    = simple_idct_armv5te;

            c->idct_permutation_type = FF_NO_IDCT_PERM;

#endif

#if HAVE_IPP

        } else if (idct_algo==FF_IDCT_IPP){

            c->idct_put= simple_idct_ipp_put;

            c->idct_add= simple_idct_ipp_add;

            c->idct    = simple_idct_ipp;

            c->idct_permutation_type= FF_NO_IDCT_PERM;

#endif

#if HAVE_NEON

        } else if (idct_algo==FF_IDCT_SIMPLENEON){

            c->idct_put= ff_simple_idct_put_neon;

            c->idct_add= ff_simple_idct_add_neon;

            c->idct    = ff_simple_idct_neon;

            c->idct_permutation_type = FF_PARTTRANS_IDCT_PERM;

        } else if ((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER || CONFIG_THEORA_DECODER) &&

                   idct_algo==FF_IDCT_VP3){

            c->idct_put= ff_vp3_idct_put_neon;

            c->idct_add= ff_vp3_idct_add_neon;

            c->idct    = ff_vp3_idct_neon;

            c->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM;

#endif

        }

    }

    c->put_pixels_tab[0][0] = put_pixels16_arm;

    c->put_pixels_tab[0][1] = put_pixels16_x2_arm;

    c->put_pixels_tab[0][2] = put_pixels16_y2_arm;

    c->put_pixels_tab[0][3] = put_pixels16_xy2_arm;

    c->put_no_rnd_pixels_tab[0][0] = put_pixels16_arm;

    c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_arm;

    c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_arm;

    c->put_no_rnd_pixels_tab[0][3] = put_no_rnd_pixels16_xy2_arm;

    c->put_pixels_tab[1][0] = put_pixels8_arm;

    c->put_pixels_tab[1][1] = put_pixels8_x2_arm;

    c->put_pixels_tab[1][2] = put_pixels8_y2_arm;

    c->put_pixels_tab[1][3] = put_pixels8_xy2_arm;

    c->put_no_rnd_pixels_tab[1][0] = put_pixels8_arm;

    c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_arm;

    c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_arm;

    c->put_no_rnd_pixels_tab[1][3] = put_no_rnd_pixels8_xy2_arm;

#if HAVE_ARMV5TE

    c->prefetch = ff_prefetch_arm;

#endif

#if HAVE_IWMMXT

    dsputil_init_iwmmxt(c, avctx);

#endif

#if HAVE_ARMVFP

    ff_float_init_arm_vfp(c, avctx);

#endif

#if HAVE_NEON

    ff_dsputil_init_neon(c, avctx);

#endif

}


av_cold void ff_h264_free_context(H264Context *h)

{

    int i;

    ff_h264_free_tables(h);

    if (h->DPB) {

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

            ff_h264_unref_picture(h, &h->DPB[i]);

        av_freep(&h->DPB);

    }

    h->cur_pic_ptr = NULL;

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

        av_freep(&h->slice_ctx[i].rbsp_buffer);

    av_freep(&h->slice_ctx);

    h->nb_slice_ctx = 0;

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

        av_freep(h->sps_buffers + i);

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

        av_freep(h->pps_buffers + i);

}


bool aio_poll(AioContext *ctx, bool blocking)

{

    AioHandler *node;

    int i, ret;

    bool progress;

    int64_t timeout;

    aio_context_acquire(ctx);

    progress = false;

    /* aio_notify can avoid the expensive event_notifier_set if

     * everything (file descriptors, bottom halves, timers) will

     * be re-evaluated before the next blocking poll().  This is

     * already true when aio_poll is called with blocking == false;

     * if blocking == true, it is only true after poll() returns,

     * so disable the optimization now.

     */

    if (blocking) {

        atomic_add(&ctx->notify_me, 2);

    }

    ctx->walking_handlers++;

    assert(npfd == 0);

    /* fill pollfds */

    if (!aio_epoll_enabled(ctx)) {

        QLIST_FOREACH(node, &ctx->aio_handlers, node) {

            if (!node->deleted && node->pfd.events

                && aio_node_check(ctx, node->is_external)) {

                add_pollfd(node);

            }

        }

    }

    timeout = blocking ? aio_compute_timeout(ctx) : 0;

    /* wait until next event */

    if (timeout) {

        aio_context_release(ctx);

    }

    if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) {

        AioHandler epoll_handler;

        epoll_handler.pfd.fd = ctx->epollfd;

        epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR;

        npfd = 0;

        add_pollfd(&epoll_handler);

        ret = aio_epoll(ctx, pollfds, npfd, timeout);

    } else  {

        ret = qemu_poll_ns(pollfds, npfd, timeout);

    }

    if (blocking) {

        atomic_sub(&ctx->notify_me, 2);

    }

    if (timeout) {

        aio_context_acquire(ctx);

    }

    aio_notify_accept(ctx);

    /* if we have any readable fds, dispatch event */

    if (ret > 0) {

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

            nodes[i]->pfd.revents = pollfds[i].revents;

        }

    }

    npfd = 0;

    ctx->walking_handlers--;

    /* Run dispatch even if there were no readable fds to run timers */

    if (aio_dispatch(ctx, ret > 0)) {

        progress = true;

    }

    aio_context_release(ctx);

    return progress;

}


int avcodec_default_reget_buffer(AVCodecContext *s, AVFrame *pic)

{

    av_assert0(0);

}


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

{

    AVIOContext *pb = s->pb;

    PutBitContext bs;

    int i, len;

    uint8_t loas_header[] = "\x56\xe0\x00";

    uint8_t *buf = NULL;

    if (s->streams[0]->codec->codec_id == CODEC_ID_AAC_LATM)

        return ff_raw_write_packet(s, pkt);

    if (pkt->size > 2 && pkt->data[0] == 0xff && (pkt->data[1] >> 4) == 0xf) {

        av_log(s, AV_LOG_ERROR, "ADTS header detected - ADTS will not be incorrectly muxed into LATM\n");

        return AVERROR_INVALIDDATA;

    }

    if (pkt->size > 0x1fff)

        goto too_large;

    buf = av_malloc(pkt->size+1024);

    if (!buf)

        return AVERROR(ENOMEM);

    init_put_bits(&bs, buf, pkt->size+1024);

    latm_write_frame_header(s, &bs);

    /* PayloadLengthInfo() */

    for (i = 0; i <= pkt->size-255; i+=255)

        put_bits(&bs, 8, 255);

    put_bits(&bs, 8, pkt->size-i);

    /* The LATM payload is written unaligned */

    /* PayloadMux() */

    if (pkt->size && (pkt->data[0] & 0xe1) == 0x81) {

        // Convert byte-aligned DSE to non-aligned.

        // Due to the input format encoding we know that

        // it is naturally byte-aligned in the input stream,

        // so there are no padding bits to account for.

        // To avoid having to add padding bits and rearrange

        // the whole stream we just remove the byte-align flag.

        // This allows us to remux our FATE AAC samples into latm

        // files that are still playable with minimal effort.

        put_bits(&bs, 8, pkt->data[0] & 0xfe);

        avpriv_copy_bits(&bs, pkt->data + 1, 8*pkt->size - 8);

    } else

        avpriv_copy_bits(&bs, pkt->data, 8*pkt->size);

    avpriv_align_put_bits(&bs);

    flush_put_bits(&bs);

    len = put_bits_count(&bs) >> 3;

    if (len > 0x1fff)

        goto too_large;

    loas_header[1] |= (len >> 8) & 0x1f;

    loas_header[2] |= len & 0xff;

    avio_write(pb, loas_header, 3);

    avio_write(pb, buf, len);

    av_free(buf);

    return 0;

too_large:

    av_log(s, AV_LOG_ERROR, "LATM packet size larger than maximum size 0x1fff\n");

    av_free(buf);

    return AVERROR_INVALIDDATA;

}


static void aio_read_done(void *opaque, int ret)

{

    struct aio_ctx *ctx = opaque;

    struct timeval t2;

    gettimeofday(&t2, NULL);

    if (ret < 0) {

        printf("readv failed: %s\n", strerror(-ret));

        goto out;

    }

    if (ctx->Pflag) {

        void *cmp_buf = g_malloc(ctx->qiov.size);

        memset(cmp_buf, ctx->pattern, ctx->qiov.size);

        if (memcmp(ctx->buf, cmp_buf, ctx->qiov.size)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %zd bytes\n", ctx->offset, ctx->qiov.size);

        }

        g_free(cmp_buf);

    }

    if (ctx->qflag) {

        goto out;

    }

    if (ctx->vflag) {

        dump_buffer(ctx->buf, ctx->offset, ctx->qiov.size);

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, ctx->t1);

    print_report("read", &t2, ctx->offset, ctx->qiov.size,

                 ctx->qiov.size, 1, ctx->Cflag);

out:

    qemu_io_free(ctx->buf);

    g_free(ctx);

}


static const char *read_ts(const char *buf, int *ts_start, int *ts_end,

                           int *x1, int *y1, int *x2, int *y2)

{

    int i, hs, ms, ss, he, me, se;

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

        /* try to read timestamps in either the first or second line */

        int c = sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d"

                       "%*[ ]X1:%u X2:%u Y1:%u Y2:%u",

                       &hs, &ms, &ss, ts_start, &he, &me, &se, ts_end,

                       x1, x2, y1, y2);

        buf += strcspn(buf, "\n") + 1;

        if (c >= 8) {

            *ts_start = 100*(ss + 60*(ms + 60*hs)) + *ts_start/10;

            *ts_end   = 100*(se + 60*(me + 60*he)) + *ts_end  /10;

            return buf;

        }

    }

    return NULL;

}


target_phys_addr_t cpu_get_phys_page_debug(CPUState *env, target_ulong addr)

{

    target_ulong pde_addr, pte_addr;

    uint64_t pte;

    target_phys_addr_t paddr;

    uint32_t page_offset;

    int page_size;

    if (env->cr[4] & CR4_PAE_MASK) {

        target_ulong pdpe_addr;

        uint64_t pde, pdpe;

#ifdef TARGET_X86_64

        if (env->hflags & HF_LMA_MASK) {

            uint64_t pml4e_addr, pml4e;

            int32_t sext;

            /* test virtual address sign extension */

            sext = (int64_t)addr >> 47;

            if (sext != 0 && sext != -1)

                return -1;

            pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) &

                env->a20_mask;

            pml4e = ldq_phys(pml4e_addr);

            if (!(pml4e & PG_PRESENT_MASK))

                return -1;

            pdpe_addr = ((pml4e & ~0xfff) + (((addr >> 30) & 0x1ff) << 3)) &

                env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK))

                return -1;

        } else

#endif

        {

            pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) &

                env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK))

                return -1;

        }

        pde_addr = ((pdpe & ~0xfff) + (((addr >> 21) & 0x1ff) << 3)) &

            env->a20_mask;

        pde = ldq_phys(pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            return -1;

        }

        if (pde & PG_PSE_MASK) {

            /* 2 MB page */

            page_size = 2048 * 1024;

            pte = pde & ~( (page_size - 1) & ~0xfff); /* align to page_size */

        } else {

            /* 4 KB page */

            pte_addr = ((pde & ~0xfff) + (((addr >> 12) & 0x1ff) << 3)) &

                env->a20_mask;

            page_size = 4096;

            pte = ldq_phys(pte_addr);

        }

        if (!(pte & PG_PRESENT_MASK))

            return -1;

    } else {

        uint32_t pde;

        if (!(env->cr[0] & CR0_PG_MASK)) {

            pte = addr;

            page_size = 4096;

        } else {

            /* page directory entry */

            pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) & env->a20_mask;

            pde = ldl_phys(pde_addr);

            if (!(pde & PG_PRESENT_MASK))

                return -1;

            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

                pte = pde & ~0x003ff000; /* align to 4MB */

                page_size = 4096 * 1024;

            } else {

                /* page directory entry */

                pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & env->a20_mask;

                pte = ldl_phys(pte_addr);

                if (!(pte & PG_PRESENT_MASK))

                    return -1;

                page_size = 4096;

            }

        }

        pte = pte & env->a20_mask;

    }

    page_offset = (addr & TARGET_PAGE_MASK) & (page_size - 1);

    paddr = (pte & TARGET_PAGE_MASK) + page_offset;

    return paddr;

}


void spapr_pci_rtas_init(void)

{

    spapr_rtas_register("read-pci-config", rtas_read_pci_config);

    spapr_rtas_register("write-pci-config", rtas_write_pci_config);

    spapr_rtas_register("ibm,read-pci-config", rtas_ibm_read_pci_config);

    spapr_rtas_register("ibm,write-pci-config", rtas_ibm_write_pci_config);

    if (msi_supported) {

        spapr_rtas_register("ibm,query-interrupt-source-number",

                            rtas_ibm_query_interrupt_source_number);

        spapr_rtas_register("ibm,change-msi", rtas_ibm_change_msi);

    }

}


static void compare_sec_rs_finalize(SocketReadState *sec_rs)

{

    CompareState *s = container_of(sec_rs, CompareState, sec_rs);

    if (packet_enqueue(s, SECONDARY_IN)) {

        trace_colo_compare_main("secondary: unsupported packet in");

    } else {

        /* compare connection */

        g_queue_foreach(&s->conn_list, colo_compare_connection, s);

    }

}


FDCtrl *fdctrl_init_isa(DriveInfo **fds)

{

    ISADevice *dev;

    dev = isa_create("isa-fdc");

    if (fds[0]) {

        qdev_prop_set_drive_nofail(&dev->qdev, "driveA", fds[0]->bdrv);

    }

    if (fds[1]) {

        qdev_prop_set_drive_nofail(&dev->qdev, "driveB", fds[1]->bdrv);

    }

    if (qdev_init(&dev->qdev) < 0)

        return NULL;

    return &(DO_UPCAST(FDCtrlISABus, busdev, dev)->state);

}


static int asf_read_picture(AVFormatContext *s, int len)

{

    ASFContext *asf       = s->priv_data;

    AVPacket pkt          = { 0 };

    const CodecMime *mime = ff_id3v2_mime_tags;

    enum  AVCodecID id    = AV_CODEC_ID_NONE;

    char mimetype[64];

    uint8_t  *desc = NULL;

    AVStream   *st = NULL;

    int ret, type, picsize, desc_len;

    ASFStream *asf_st;

    /* type + picsize + mime + desc */

    if (len < 1 + 4 + 2 + 2) {

        av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len);

        return AVERROR_INVALIDDATA;

    }

    /* picture type */

    type = avio_r8(s->pb);

    len--;

    if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) {

        av_log(s, AV_LOG_WARNING, "Unknown attached picture type: %d.\n", type);

        type = 0;

    }

    /* picture data size */

    picsize = avio_rl32(s->pb);

    len    -= 4;

    /* picture MIME type */

    len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype));

    while (mime->id != AV_CODEC_ID_NONE) {

        if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {

            id = mime->id;

            break;

        }

        mime++;

    }

    if (id == AV_CODEC_ID_NONE) {

        av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n",

               mimetype);

        return 0;

    }

    if (picsize >= len) {

        av_log(s, AV_LOG_ERROR, "Invalid attached picture data size: %d >= %d.\n",

               picsize, len);

        return AVERROR_INVALIDDATA;

    }

    /* picture description */

    desc_len = (len - picsize) * 2 + 1;

    desc     = av_malloc(desc_len);

    if (!desc)

        return AVERROR(ENOMEM);

    len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len);

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

    if (ret < 0)

        goto fail;

    st  = avformat_new_stream(s, NULL);

    if (!st) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    asf->asf_st[asf->nb_streams] = av_mallocz(sizeof(*asf_st));

    asf_st = asf->asf_st[asf->nb_streams];

    if (!asf_st)

        return AVERROR(ENOMEM);

    st->disposition              |= AV_DISPOSITION_ATTACHED_PIC;

    st->codec->codec_type         = asf_st->type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id           = id;

    st->attached_pic              = pkt;

    st->attached_pic.stream_index = asf_st->index = st->index;

    st->attached_pic.flags       |= AV_PKT_FLAG_KEY;

    asf->nb_streams++;

    if (*desc) {

        if (av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL) < 0)

            av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n");

    } else

        av_freep(&desc);

    if (av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0) < 0)

        av_log(s, AV_LOG_WARNING, "av_dict_set failed.\n");

    return 0;

fail:

    av_freep(&desc);

    av_free_packet(&pkt);

    return ret;

}


void HELPER(access_check_cp_reg)(CPUARMState *env, void *rip, uint32_t syndrome)
{
    const ARMCPRegInfo *ri = rip;
    switch (ri->accessfn(env, ri)) {
    case CP_ACCESS_OK:
    case CP_ACCESS_TRAP:
        break;
    case CP_ACCESS_TRAP_UNCATEGORIZED:
        env->exception.syndrome = syn_uncategorized();
        break;
    default:
        g_assert_not_reached();


static char *scsibus_get_dev_path(DeviceState *dev)

{

    SCSIDevice *d = DO_UPCAST(SCSIDevice, qdev, dev);

    DeviceState *hba = dev->parent_bus->parent;

    char *id = NULL;

    if (hba && hba->parent_bus && hba->parent_bus->info->get_dev_path) {

        id = hba->parent_bus->info->get_dev_path(hba);

    }

    if (id) {

        return g_strdup_printf("%s/%d:%d:%d", id, d->channel, d->id, d->lun);

    } else {

        return g_strdup_printf("%d:%d:%d", d->channel, d->id, d->lun);

    }

}


static int eval_lpc_coeffs(const float *in, float *tgt, int n)

{

    int x, y;

    double f0, f1, f2;

    if (in[n] == 0)

        return 0;

    if ((f0 = *in) <= 0)

        return 0;

    in--; // To avoid a -1 subtraction in the inner loop

    for (x=1; x <= n; x++) {

        f1 = in[x+1];

        for (y=0; y < x - 1; y++)

            f1 += in[x-y]*tgt[y];

        tgt[x-1] = f2 = -f1/f0;

        for (y=0; y < x >> 1; y++) {

            float temp = tgt[y] + tgt[x-y-2]*f2;

            tgt[x-y-2] += tgt[y]*f2;

            tgt[y] = temp;

        }

        if ((f0 += f1*f2) < 0)

            return 0;

    }

    return 1;

}


int swr_init(struct SwrContext *s){

    s->in_buffer_index= 0;

    s->in_buffer_count= 0;

    s->resample_in_constraint= 0;

    free_temp(&s->postin);

    free_temp(&s->midbuf);

    free_temp(&s->preout);

    free_temp(&s->in_buffer);

    free_temp(&s->dither);

    swri_audio_convert_free(&s-> in_convert);

    swri_audio_convert_free(&s->out_convert);

    swri_audio_convert_free(&s->full_convert);

    swri_rematrix_free(s);

    s->flushed = 0;

    if(s-> in_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested input sample format %d is invalid\n", s->in_sample_fmt);

        return AVERROR(EINVAL);

    }

    if(s->out_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested output sample format %d is invalid\n", s->out_sample_fmt);

        return AVERROR(EINVAL);

    }

    //FIXME should we allow/support using FLT on material that doesnt need it ?

    if(av_get_planar_sample_fmt(s->in_sample_fmt) <= AV_SAMPLE_FMT_S16P || s->int_sample_fmt==AV_SAMPLE_FMT_S16P){

        s->int_sample_fmt= AV_SAMPLE_FMT_S16P;

    }else

        s->int_sample_fmt= AV_SAMPLE_FMT_FLTP;

    if(   s->int_sample_fmt != AV_SAMPLE_FMT_S16P

        &&s->int_sample_fmt != AV_SAMPLE_FMT_S32P

        &&s->int_sample_fmt != AV_SAMPLE_FMT_FLTP){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is not supported internally, S16/S32/FLT is supported\n", av_get_sample_fmt_name(s->int_sample_fmt));

        return AVERROR(EINVAL);

    }

    set_audiodata_fmt(&s-> in, s-> in_sample_fmt);

    set_audiodata_fmt(&s->out, s->out_sample_fmt);

    if (s->out_sample_rate!=s->in_sample_rate || (s->flags & SWR_FLAG_RESAMPLE)){

        s->resample = swri_resample_init(s->resample, s->out_sample_rate, s->in_sample_rate, s->filter_size, s->phase_shift, s->linear_interp, s->cutoff, s->int_sample_fmt);

    }else

        swri_resample_free(&s->resample);

    if(    s->int_sample_fmt != AV_SAMPLE_FMT_S16P

        && s->int_sample_fmt != AV_SAMPLE_FMT_S32P

        && s->int_sample_fmt != AV_SAMPLE_FMT_FLTP

        && s->resample){

        av_log(s, AV_LOG_ERROR, "Resampling only supported with internal s16/s32/flt\n");

        return -1;

    }

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(s->used_ch_count && s-> in_ch_layout && s->used_ch_count != av_get_channel_layout_nb_channels(s-> in_ch_layout)){

        av_log(s, AV_LOG_WARNING, "Input channel layout has a different number of channels than the number of used channels, ignoring layout\n");

        s-> in_ch_layout= 0;

    }

    if(!s-> in_ch_layout)

        s-> in_ch_layout= av_get_default_channel_layout(s->used_ch_count);

    if(!s->out_ch_layout)

        s->out_ch_layout= av_get_default_channel_layout(s->out.ch_count);

    s->rematrix= s->out_ch_layout  !=s->in_ch_layout || s->rematrix_volume!=1.0 ||

                 s->rematrix_custom;

#define RSC 1 //FIXME finetune

    if(!s-> in.ch_count)

        s-> in.ch_count= av_get_channel_layout_nb_channels(s-> in_ch_layout);

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(!s->out.ch_count)

        s->out.ch_count= av_get_channel_layout_nb_channels(s->out_ch_layout);

    if(!s-> in.ch_count){

        av_assert0(!s->in_ch_layout);

        av_log(s, AV_LOG_ERROR, "Input channel count and layout are unset\n");

        return -1;

    }

    if ((!s->out_ch_layout || !s->in_ch_layout) && s->used_ch_count != s->out.ch_count && !s->rematrix_custom) {

        av_log(s, AV_LOG_ERROR, "Rematrix is needed but there is not enough information to do it\n");

        return -1;

    }

av_assert0(s->used_ch_count);

av_assert0(s->out.ch_count);

    s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0;

    s->in_buffer= s->in;

    if(!s->resample && !s->rematrix && !s->channel_map && !s->dither_method){

        s->full_convert = swri_audio_convert_alloc(s->out_sample_fmt,

                                                   s-> in_sample_fmt, s-> in.ch_count, NULL, 0);

        return 0;

    }

    s->in_convert = swri_audio_convert_alloc(s->int_sample_fmt,

                                             s-> in_sample_fmt, s->used_ch_count, s->channel_map, 0);

    s->out_convert= swri_audio_convert_alloc(s->out_sample_fmt,

                                             s->int_sample_fmt, s->out.ch_count, NULL, 0);

    s->postin= s->in;

    s->preout= s->out;

    s->midbuf= s->in;

    if(s->channel_map){

        s->postin.ch_count=

        s->midbuf.ch_count= s->used_ch_count;

        if(s->resample)

            s->in_buffer.ch_count= s->used_ch_count;

    }

    if(!s->resample_first){

        s->midbuf.ch_count= s->out.ch_count;

        if(s->resample)

            s->in_buffer.ch_count = s->out.ch_count;

    }

    set_audiodata_fmt(&s->postin, s->int_sample_fmt);

    set_audiodata_fmt(&s->midbuf, s->int_sample_fmt);

    set_audiodata_fmt(&s->preout, s->int_sample_fmt);

    if(s->resample){

        set_audiodata_fmt(&s->in_buffer, s->int_sample_fmt);

    }

    s->dither = s->preout;

    if(s->rematrix || s->dither_method)

        return swri_rematrix_init(s);

    return 0;

}


void pc_hot_add_cpu(const int64_t id, Error **errp)
{
    DeviceState *icc_bridge;
    int64_t apic_id = x86_cpu_apic_id_from_index(id);
    if (cpu_exists(apic_id)) {
        error_setg(errp, "Unable to add CPU: %" PRIi64
                   ", it already exists", id);
    if (id >= max_cpus) {
        error_setg(errp, "Unable to add CPU: %" PRIi64
                   ", max allowed: %d", id, max_cpus - 1);
    icc_bridge = DEVICE(object_resolve_path_type("icc-bridge",
                                                 TYPE_ICC_BRIDGE, NULL));
    pc_new_cpu(current_cpu_model, apic_id, icc_bridge, errp);


static void xlnx_ep108_init(MachineState *machine)

{

    XlnxEP108 *s = g_new0(XlnxEP108, 1);

    Error *err = NULL;

    object_initialize(&s->soc, sizeof(s->soc), TYPE_XLNX_ZYNQMP);

    object_property_add_child(OBJECT(machine), "soc", OBJECT(&s->soc),

                              &error_abort);

    object_property_set_bool(OBJECT(&s->soc), true, "realized", &err);

    if (err) {

        error_report("%s", error_get_pretty(err));

        exit(1);

    }

    if (machine->ram_size > EP108_MAX_RAM_SIZE) {

        error_report("WARNING: RAM size " RAM_ADDR_FMT " above max supported, "

                     "reduced to %llx", machine->ram_size, EP108_MAX_RAM_SIZE);

        machine->ram_size = EP108_MAX_RAM_SIZE;

    }

    if (machine->ram_size <= 0x08000000) {

        qemu_log("WARNING: RAM size " RAM_ADDR_FMT " is small for EP108",

                 machine->ram_size);

    }

    memory_region_allocate_system_memory(&s->ddr_ram, NULL, "ddr-ram",

                                         machine->ram_size);

    memory_region_add_subregion(get_system_memory(), 0, &s->ddr_ram);

    xlnx_ep108_binfo.ram_size = machine->ram_size;

    xlnx_ep108_binfo.kernel_filename = machine->kernel_filename;

    xlnx_ep108_binfo.kernel_cmdline = machine->kernel_cmdline;

    xlnx_ep108_binfo.initrd_filename = machine->initrd_filename;

    xlnx_ep108_binfo.loader_start = 0;

    arm_load_kernel(s->soc.boot_cpu_ptr, &xlnx_ep108_binfo);

}


static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,

                        AVFilterInOut **open_outputs, AVClass *log_ctx)

{

    int pad = 0;

    while (**buf == '[') {

        char *name = parse_link_name(buf, log_ctx);

        AVFilterInOut *match;

        if (!name)

            return AVERROR(EINVAL);

        /* First check if the label is not in the open_outputs list */

        match = extract_inout(name, open_outputs);

        if (match) {

            av_free(name);

        } else {

            /* Not in the list, so add it as an input */

            match = av_mallocz(sizeof(AVFilterInOut));

            match->name    = name;

            match->pad_idx = pad;

        }

        insert_inout(curr_inputs, match);

        *buf += strspn(*buf, WHITESPACES);

        pad++;

    }

    return pad;

}


void vp8_mc_chroma(VP8Context *s, VP8ThreadData *td, uint8_t *dst1, uint8_t *dst2,

                   ThreadFrame *ref, const VP56mv *mv, int x_off, int y_off,

                   int block_w, int block_h, int width, int height, int linesize,

                   vp8_mc_func mc_func[3][3])

{

    uint8_t *src1 = ref->f->data[1], *src2 = ref->f->data[2];

    if (AV_RN32A(mv)) {

        int mx = mv->x&7, mx_idx = subpel_idx[0][mx];

        int my = mv->y&7, my_idx = subpel_idx[0][my];

        x_off += mv->x >> 3;

        y_off += mv->y >> 3;

        // edge emulation

        src1 += y_off * linesize + x_off;

        src2 += y_off * linesize + x_off;

        ff_thread_await_progress(ref, (3 + y_off + block_h + subpel_idx[2][my]) >> 3, 0);

        if (x_off < mx_idx || x_off >= width  - block_w - subpel_idx[2][mx] ||

            y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) {

            s->vdsp.emulated_edge_mc(td->edge_emu_buffer, src1 - my_idx * linesize - mx_idx, linesize,

                                     block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my],

                                     x_off - mx_idx, y_off - my_idx, width, height);

            src1 = td->edge_emu_buffer + mx_idx + linesize * my_idx;

            mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my);

            s->vdsp.emulated_edge_mc(td->edge_emu_buffer, src2 - my_idx * linesize - mx_idx, linesize,

                                     block_w + subpel_idx[1][mx], block_h + subpel_idx[1][my],

                                     x_off - mx_idx, y_off - my_idx, width, height);

            src2 = td->edge_emu_buffer + mx_idx + linesize * my_idx;

            mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my);

        } else {

            mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my);

            mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my);

        }

    } else {

        ff_thread_await_progress(ref, (3 + y_off + block_h) >> 3, 0);

        mc_func[0][0](dst1, linesize, src1 + y_off * linesize + x_off, linesize, block_h, 0, 0);

        mc_func[0][0](dst2, linesize, src2 + y_off * linesize + x_off, linesize, block_h, 0, 0);

    }

}


static void rgb24_to_yuv444p(AVPicture *dst, AVPicture *src,

                             int width, int height)

{

    int src_wrap, x, y;

    int r, g, b;

    uint8_t *lum, *cb, *cr;

    const uint8_t *p;

    lum = dst->data[0];

    cb = dst->data[1];

    cr = dst->data[2];

    src_wrap = src->linesize[0] - width * BPP;

    p = src->data[0];

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

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

            RGB_IN(r, g, b, p);

            lum[0] = RGB_TO_Y_CCIR(r, g, b);

            cb[0] = RGB_TO_U_CCIR(r, g, b, 0);

            cr[0] = RGB_TO_V_CCIR(r, g, b, 0);

            cb++;

            cr++;

            lum++;

        }

        p += src_wrap;

        lum += dst->linesize[0] - width;

        cb += dst->linesize[1] - width;

        cr += dst->linesize[2] - width;

    }

}


static char *pcibus_get_fw_dev_path(DeviceState *dev)

{

    PCIDevice *d = (PCIDevice *)dev;

    char path[50], name[33];

    int off;

    off = snprintf(path, sizeof(path), "%s@%x",

                   pci_dev_fw_name(dev, name, sizeof name),

                   PCI_SLOT(d->devfn));

    if (PCI_FUNC(d->devfn))

        snprintf(path + off, sizeof(path) + off, ",%x", PCI_FUNC(d->devfn));

    return strdup(path);

}


static int qio_channel_websock_handshake_send_response(QIOChannelWebsock *ioc,

                                                       const char *key,

                                                       Error **errp)

{

    char combined_key[QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN +

                      QIO_CHANNEL_WEBSOCK_GUID_LEN + 1];

    char *accept = NULL, *response = NULL;

    size_t responselen;

    g_strlcpy(combined_key, key, QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN + 1);

    g_strlcat(combined_key, QIO_CHANNEL_WEBSOCK_GUID,

              QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN +

              QIO_CHANNEL_WEBSOCK_GUID_LEN + 1);

    /* hash and encode it */

    if (qcrypto_hash_base64(QCRYPTO_HASH_ALG_SHA1,

                            combined_key,

                            QIO_CHANNEL_WEBSOCK_CLIENT_KEY_LEN +

                            QIO_CHANNEL_WEBSOCK_GUID_LEN,

                            &accept,

                            errp) < 0) {

        return -1;

    }

    response = g_strdup_printf(QIO_CHANNEL_WEBSOCK_HANDSHAKE_RESPONSE, accept);

    responselen = strlen(response);

    buffer_reserve(&ioc->encoutput, responselen);

    buffer_append(&ioc->encoutput, response, responselen);

    g_free(accept);

    g_free(response);

    return 0;

}


void dpy_gfx_copy(QemuConsole *con, int src_x, int src_y,

                  int dst_x, int dst_y, int w, int h)

{

    DisplayState *s = con->ds;

    DisplayChangeListener *dcl;

    if (!qemu_console_is_visible(con)) {

        return;

    }

    QLIST_FOREACH(dcl, &s->listeners, next) {

        if (con != (dcl->con ? dcl->con : active_console)) {

            continue;

        }

        if (dcl->ops->dpy_gfx_copy) {

            dcl->ops->dpy_gfx_copy(dcl, src_x, src_y, dst_x, dst_y, w, h);

        } else { /* TODO */

            dcl->ops->dpy_gfx_update(dcl, dst_x, dst_y, w, h);

        }

    }

}