static void encode_cblk(Jpeg2000EncoderContext *s, Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk, Jpeg2000Tile *tile,

                        int width, int height, int bandpos, int lev)

{

    int pass_t = 2, passno, x, y, max=0, nmsedec, bpno;

    int64_t wmsedec = 0;

    memset(t1->flags, 0, t1->stride * (height + 2) * sizeof(*t1->flags));

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

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

            if (t1->data[(y) * t1->stride + x] < 0){

                t1->flags[(y+1) * t1->stride + x+1] |= JPEG2000_T1_SGN;

                t1->data[(y) * t1->stride + x] = -t1->data[(y) * t1->stride + x];

            }

            max = FFMAX(max, t1->data[(y) * t1->stride + x]);

        }

    }

    if (max == 0){

        cblk->nonzerobits = 0;

        bpno = 0;

    } else{

        cblk->nonzerobits = av_log2(max) + 1 - NMSEDEC_FRACBITS;

        bpno = cblk->nonzerobits - 1;

    }

    ff_mqc_initenc(&t1->mqc, cblk->data);

    for (passno = 0; bpno >= 0; passno++){

        nmsedec=0;

        switch(pass_t){

            case 0: encode_sigpass(t1, width, height, bandpos, &nmsedec, bpno);

                    break;

            case 1: encode_refpass(t1, width, height, &nmsedec, bpno);

                    break;

            case 2: encode_clnpass(t1, width, height, bandpos, &nmsedec, bpno);

                    break;

        }

        cblk->passes[passno].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno].flushed, &cblk->passes[passno].flushed_len);

        wmsedec += (int64_t)nmsedec << (2*bpno);

        cblk->passes[passno].disto = wmsedec;

        if (++pass_t == 3){

            pass_t = 0;

            bpno--;

        }

    }

    cblk->npasses = passno;

    cblk->ninclpasses = passno;

    cblk->passes[passno-1].rate = ff_mqc_flush_to(&t1->mqc, cblk->passes[passno-1].flushed, &cblk->passes[passno-1].flushed_len);

}


static void gic_dist_writeb(void *opaque, hwaddr offset,

                            uint32_t value, MemTxAttrs attrs)

{

    GICState *s = (GICState *)opaque;

    int irq;

    int i;

    int cpu;

    cpu = gic_get_current_cpu(s);

    if (offset < 0x100) {

        if (offset == 0) {

            if (s->security_extn && !attrs.secure) {

                /* NS version is just an alias of the S version's bit 1 */

                s->ctlr = deposit32(s->ctlr, 1, 1, value);

            } else if (gic_has_groups(s)) {

                s->ctlr = value & (GICD_CTLR_EN_GRP0 | GICD_CTLR_EN_GRP1);

            } else {

                s->ctlr = value & GICD_CTLR_EN_GRP0;

            }

            DPRINTF("Distributor: Group0 %sabled; Group 1 %sabled\n",

                    s->ctlr & GICD_CTLR_EN_GRP0 ? "En" : "Dis",

                    s->ctlr & GICD_CTLR_EN_GRP1 ? "En" : "Dis");

        } else if (offset < 4) {

            /* ignored.  */

        } else if (offset >= 0x80) {

            /* Interrupt Group Registers: RAZ/WI for NS access to secure

             * GIC, or for GICs without groups.

             */

            if (!(s->security_extn && !attrs.secure) && gic_has_groups(s)) {

                /* Every byte offset holds 8 group status bits */

                irq = (offset - 0x80) * 8 + GIC_BASE_IRQ;

                if (irq >= s->num_irq) {

                    goto bad_reg;

                }

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

                    /* Group bits are banked for private interrupts */

                    int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                    if (value & (1 << i)) {

                        /* Group1 (Non-secure) */

                        GIC_SET_GROUP(irq + i, cm);

                    } else {

                        /* Group0 (Secure) */

                        GIC_CLEAR_GROUP(irq + i, cm);

                    }

                }

            }

        } else {

            goto bad_reg;

        }

    } else if (offset < 0x180) {

        /* Interrupt Set Enable.  */

        irq = (offset - 0x100) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0xff;

        }

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

            if (value & (1 << i)) {

                int mask =

                    (irq < GIC_INTERNAL) ? (1 << cpu) : GIC_TARGET(irq + i);

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (!GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Enabled IRQ %d\n", irq + i);

                }

                GIC_SET_ENABLED(irq + i, cm);

                /* If a raised level triggered IRQ enabled then mark

                   is as pending.  */

                if (GIC_TEST_LEVEL(irq + i, mask)

                        && !GIC_TEST_EDGE_TRIGGER(irq + i)) {

                    DPRINTF("Set %d pending mask %x\n", irq + i, mask);

                    GIC_SET_PENDING(irq + i, mask);

                }

            }

        }

    } else if (offset < 0x200) {

        /* Interrupt Clear Enable.  */

        irq = (offset - 0x180) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            if (value & (1 << i)) {

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Disabled IRQ %d\n", irq + i);

                    trace_gic_disable_irq(irq + i);

                }

                GIC_CLEAR_ENABLED(irq + i, cm);

            }

        }

    } else if (offset < 0x280) {

        /* Interrupt Set Pending.  */

        irq = (offset - 0x200) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            if (value & (1 << i)) {

                GIC_SET_PENDING(irq + i, GIC_TARGET(irq + i));

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Clear Pending.  */

        irq = (offset - 0x280) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            /* ??? This currently clears the pending bit for all CPUs, even

               for per-CPU interrupts.  It's unclear whether this is the

               corect behavior.  */

            if (value & (1 << i)) {

                GIC_CLEAR_PENDING(irq + i, ALL_CPU_MASK);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        goto bad_reg;

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        gic_set_priority(s, cpu, irq, value, attrs);

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target. RAZ/WI on uniprocessor GICs, with the

         * annoying exception of the 11MPCore's GIC.

         */

        if (s->num_cpu != 1 || s->revision == REV_11MPCORE) {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq < 29) {

                value = 0;

            } else if (irq < GIC_INTERNAL) {

                value = ALL_CPU_MASK;

            }

            s->irq_target[irq] = value & ALL_CPU_MASK;

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS)

            value |= 0xaa;

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

            if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

                if (value & (1 << (i * 2))) {

                    GIC_SET_MODEL(irq + i);

                } else {

                    GIC_CLEAR_MODEL(irq + i);

                }

            }

            if (value & (2 << (i * 2))) {

                GIC_SET_EDGE_TRIGGER(irq + i);

            } else {

                GIC_CLEAR_EDGE_TRIGGER(irq + i);

            }

        }

    } else if (offset < 0xf10) {

        /* 0xf00 is only handled for 32-bit writes.  */

        goto bad_reg;

    } else if (offset < 0xf20) {

        /* GICD_CPENDSGIRn */

        if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

            goto bad_reg;

        }

        irq = (offset - 0xf10);

        s->sgi_pending[irq][cpu] &= ~value;

        if (s->sgi_pending[irq][cpu] == 0) {

            GIC_CLEAR_PENDING(irq, 1 << cpu);

        }

    } else if (offset < 0xf30) {

        /* GICD_SPENDSGIRn */

        if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

            goto bad_reg;

        }

        irq = (offset - 0xf20);

        GIC_SET_PENDING(irq, 1 << cpu);

        s->sgi_pending[irq][cpu] |= value;

    } else {

        goto bad_reg;

    }

    gic_update(s);

    return;

bad_reg:

    qemu_log_mask(LOG_GUEST_ERROR,

                  "gic_dist_writeb: Bad offset %x\n", (int)offset);

}


static int gif_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt)
{
    GifState *s = avctx->priv_data;
    AVFrame *picture = data;
    int ret;
    bytestream2_init(&s->gb, avpkt->data, avpkt->size);
    s->picture.pts          = avpkt->pts;
    s->picture.pkt_pts      = avpkt->pts;
    s->picture.pkt_dts      = avpkt->dts;
    s->picture.pkt_duration = avpkt->duration;
    if (avpkt->size >= 6) {
        s->keyframe = memcmp(avpkt->data, gif87a_sig, 6) == 0 ||
                      memcmp(avpkt->data, gif89a_sig, 6) == 0;
    } else {
        s->keyframe = 0;
    if (s->keyframe) {
        s->keyframe_ok = 0;
        if ((ret = gif_read_header1(s)) < 0)
            return ret;
        if ((ret = av_image_check_size(s->screen_width, s->screen_height, 0, avctx)) < 0)
            return ret;
        avcodec_set_dimensions(avctx, s->screen_width, s->screen_height);
        if (s->picture.data[0])
            avctx->release_buffer(avctx, &s->picture);
        if ((ret = ff_get_buffer(avctx, &s->picture)) < 0) {
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
            return ret;
        s->picture.pict_type = AV_PICTURE_TYPE_I;
        s->picture.key_frame = 1;
    } else {
        if ((ret = avctx->reget_buffer(avctx, &s->picture)) < 0) {
            av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
            return ret;
        s->picture.pict_type = AV_PICTURE_TYPE_P;
        s->picture.key_frame = 0;
    ret = gif_parse_next_image(s, got_frame);
    if (ret < 0)
        return ret;
    else if (*got_frame)
        *picture = s->picture;
    return avpkt->size;


static GSList *gd_vc_init(GtkDisplayState *s, VirtualConsole *vc, int index, GSList *group,

                          GtkWidget *view_menu)

{

#if defined(CONFIG_VTE)

    const char *label;

    char buffer[32];

    char path[32];

#if VTE_CHECK_VERSION(0, 26, 0)

    VtePty *pty;

#endif

    GIOChannel *chan;

    GtkWidget *scrolled_window;

    GtkAdjustment *vadjustment;

    int master_fd, slave_fd;

    snprintf(buffer, sizeof(buffer), "vc%d", index);

    snprintf(path, sizeof(path), "<QEMU>/View/VC%d", index);

    vc->chr = vcs[index];

    if (vc->chr->label) {

        label = vc->chr->label;

    } else {

        label = buffer;

    }

    vc->menu_item = gtk_radio_menu_item_new_with_mnemonic(group, label);

    group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(vc->menu_item));

    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(vc->menu_item), path);

    gtk_accel_map_add_entry(path, GDK_KEY_2 + index, HOTKEY_MODIFIERS);

    vc->terminal = vte_terminal_new();

    master_fd = qemu_openpty_raw(&slave_fd, NULL);

    g_assert(master_fd != -1);

#if VTE_CHECK_VERSION(0, 26, 0)

    pty = vte_pty_new_foreign(master_fd, NULL);

    vte_terminal_set_pty_object(VTE_TERMINAL(vc->terminal), pty);

#else

    vte_terminal_set_pty(VTE_TERMINAL(vc->terminal), master_fd);

#endif

    vte_terminal_set_scrollback_lines(VTE_TERMINAL(vc->terminal), -1);

#if VTE_CHECK_VERSION(0, 28, 0) && GTK_CHECK_VERSION(3, 0, 0)

    vadjustment = gtk_scrollable_get_vadjustment(GTK_SCROLLABLE(vc->terminal));

#else

    vadjustment = vte_terminal_get_adjustment(VTE_TERMINAL(vc->terminal));

#endif

    scrolled_window = gtk_scrolled_window_new(NULL, vadjustment);

    gtk_container_add(GTK_CONTAINER(scrolled_window), vc->terminal);

    vte_terminal_set_size(VTE_TERMINAL(vc->terminal), 80, 25);

    vc->fd = slave_fd;

    vc->chr->opaque = vc;

    vc->scrolled_window = scrolled_window;

    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(vc->scrolled_window),

                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

    gtk_notebook_append_page(GTK_NOTEBOOK(s->notebook), scrolled_window, gtk_label_new(label));

    g_signal_connect(vc->menu_item, "activate",

                     G_CALLBACK(gd_menu_switch_vc), s);

    gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), vc->menu_item);

    qemu_chr_be_generic_open(vc->chr);

    if (vc->chr->init) {

        vc->chr->init(vc->chr);

    }

    chan = g_io_channel_unix_new(vc->fd);

    g_io_add_watch(chan, G_IO_IN, gd_vc_in, vc);

#endif /* CONFIG_VTE */

    return group;

}


static int parse_packet(AVFormatContext *s, AVPacket *pkt, int stream_index)

{

    AVPacket out_pkt = { 0 }, flush_pkt = { 0 };

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

    uint8_t *data = pkt ? pkt->data : NULL;

    int size      = pkt ? pkt->size : 0;

    int ret = 0, got_output = 0;

    if (!pkt) {

        av_init_packet(&flush_pkt);

        pkt        = &flush_pkt;

        got_output = 1;

    } else if (!size && st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) {

        // preserve 0-size sync packets

        compute_pkt_fields(s, st, st->parser, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);

    }

    while (size > 0 || (pkt == &flush_pkt && got_output)) {

        int len;

        int64_t next_pts = pkt->pts;

        int64_t next_dts = pkt->dts;

        av_init_packet(&out_pkt);

        len = av_parser_parse2(st->parser, st->codec,

                               &out_pkt.data, &out_pkt.size, data, size,

                               pkt->pts, pkt->dts, pkt->pos);

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

        pkt->pos = -1;

        /* increment read pointer */

        data += len;

        size -= len;

        got_output = !!out_pkt.size;

        if (!out_pkt.size)

            continue;

        if (pkt->side_data) {

            out_pkt.side_data       = pkt->side_data;

            out_pkt.side_data_elems = pkt->side_data_elems;

            pkt->side_data          = NULL;

            pkt->side_data_elems    = 0;

        }

        /* set the duration */

        out_pkt.duration = (st->parser->flags & PARSER_FLAG_COMPLETE_FRAMES) ? pkt->duration : 0;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (st->codec->sample_rate > 0) {

                out_pkt.duration =

                    av_rescale_q_rnd(st->parser->duration,

                                     (AVRational) { 1, st->codec->sample_rate },

                                     st->time_base,

                                     AV_ROUND_DOWN);

            }

        }

        out_pkt.stream_index = st->index;

        out_pkt.pts          = st->parser->pts;

        out_pkt.dts          = st->parser->dts;

        out_pkt.pos          = st->parser->pos;

        if (st->need_parsing == AVSTREAM_PARSE_FULL_RAW)

            out_pkt.pos = st->parser->frame_offset;

        if (st->parser->key_frame == 1 ||

            (st->parser->key_frame == -1 &&

             st->parser->pict_type == AV_PICTURE_TYPE_I))

            out_pkt.flags |= AV_PKT_FLAG_KEY;

        if (st->parser->key_frame == -1 && st->parser->pict_type ==AV_PICTURE_TYPE_NONE && (pkt->flags&AV_PKT_FLAG_KEY))

            out_pkt.flags |= AV_PKT_FLAG_KEY;

        compute_pkt_fields(s, st, st->parser, &out_pkt, next_dts, next_pts);

        if ((ret = add_to_pktbuf(&s->internal->parse_queue, &out_pkt,

                                 &s->internal->parse_queue_end,

                                 1))) {

            av_packet_unref(&out_pkt);

            goto fail;

        }

    }

    /* end of the stream => close and free the parser */

    if (pkt == &flush_pkt) {

        av_parser_close(st->parser);

        st->parser = NULL;

    }

fail:

    av_packet_unref(pkt);

    return ret;

}


int ff_frame_thread_init(AVCodecContext *avctx)

{

    int thread_count = avctx->thread_count;

    const AVCodec *codec = avctx->codec;

    AVCodecContext *src = avctx;

    FrameThreadContext *fctx;

    int i, err = 0;

#if HAVE_W32THREADS

    w32thread_init();

#endif

    if (!thread_count) {

        int nb_cpus = av_cpu_count();

        av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);

        // use number of cores + 1 as thread count if there is more than one

        if (nb_cpus > 1)

            thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);

        else

            thread_count = avctx->thread_count = 1;

    }

    if (thread_count <= 1) {

        avctx->active_thread_type = 0;

        return 0;

    }

    avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));

    fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);

    pthread_mutex_init(&fctx->buffer_mutex, NULL);

    fctx->delaying = 1;

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

        AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));

        PerThreadContext *p  = &fctx->threads[i];

        pthread_mutex_init(&p->mutex, NULL);

        pthread_mutex_init(&p->progress_mutex, NULL);

        pthread_cond_init(&p->input_cond, NULL);

        pthread_cond_init(&p->progress_cond, NULL);

        pthread_cond_init(&p->output_cond, NULL);

        p->frame = av_frame_alloc();

        if (!p->frame) {

            err = AVERROR(ENOMEM);

            goto error;

        }

        p->parent = fctx;

        p->avctx  = copy;

        if (!copy) {

            err = AVERROR(ENOMEM);

            goto error;

        }

        *copy = *src;

        copy->internal = av_malloc(sizeof(AVCodecInternal));

        if (!copy->internal) {

            err = AVERROR(ENOMEM);

            goto error;

        }

        *copy->internal = *src->internal;

        copy->internal->thread_ctx = p;

        copy->internal->pkt = &p->avpkt;

        if (!i) {

            src = copy;

            if (codec->init)

                err = codec->init(copy);

            update_context_from_thread(avctx, copy, 1);

        } else {

            copy->priv_data = av_malloc(codec->priv_data_size);

            if (!copy->priv_data) {

                err = AVERROR(ENOMEM);

                goto error;

            }

            memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);

            copy->internal->is_copy = 1;

            if (codec->init_thread_copy)

                err = codec->init_thread_copy(copy);

        }

        if (err) goto error;

        if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))

            p->thread_init = 1;

    }

    return 0;

error:

    ff_frame_thread_free(avctx, i+1);

    return err;

}


CPUState *cpu_generic_init(const char *typename, const char *cpu_model)

{

    /* TODO: all callers of cpu_generic_init() need to be converted to

     * call cpu_parse_features() only once, before calling cpu_generic_init().

     */

    const char *cpu_type = cpu_parse_cpu_model(typename, cpu_model);

    if (cpu_type) {

        return cpu_create(cpu_type);

    }

    return NULL;

}


static int handle_metadata(RTMPContext *rt, RTMPPacket *pkt)

{

    int ret, old_flv_size, type;

    const uint8_t *next;

    uint8_t *p;

    uint32_t size;

    uint32_t ts, cts, pts = 0;

    old_flv_size = update_offset(rt, pkt->size);

    if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {

        rt->flv_size = rt->flv_off = 0;

        return ret;

    }

    next = pkt->data;

    p    = rt->flv_data + old_flv_size;

    /* copy data while rewriting timestamps */

    ts = pkt->timestamp;

    while (next - pkt->data < pkt->size - RTMP_HEADER) {

        type = bytestream_get_byte(&next);

        size = bytestream_get_be24(&next);

        cts  = bytestream_get_be24(&next);

        cts |= bytestream_get_byte(&next) << 24;

        if (!pts)

            pts = cts;

        ts += cts - pts;

        pts = cts;

        bytestream_put_byte(&p, type);

        bytestream_put_be24(&p, size);

        bytestream_put_be24(&p, ts);

        bytestream_put_byte(&p, ts >> 24);

        memcpy(p, next, size + 3 + 4);

        next += size + 3 + 4;

        p    += size + 3 + 4;

    }

    memcpy(p, next, RTMP_HEADER);

    return 0;

}


static void gen_sub_carry(TCGv dest, TCGv t0, TCGv t1)

{

    TCGv tmp;

    tcg_gen_sub_i32(dest, t0, t1);

    tmp = load_cpu_field(CF);

    tcg_gen_add_i32(dest, dest, tmp);

    tcg_gen_subi_i32(dest, dest, 1);

    dead_tmp(tmp);

}


static void gen_dstst(DisasContext *ctx)

{

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

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_LSWX);

    } else {

        /* interpreted as no-op */

    }

}


static MMSSCPacketType get_tcp_server_response(MMSTContext *mmst)

{

    int read_result;

    MMSSCPacketType packet_type= -1;

    MMSContext *mms = &mmst->mms;

    for(;;) {

        read_result = url_read_complete(mms->mms_hd, mms->in_buffer, 8);

        if (read_result != 8) {

            if(read_result < 0) {

                av_log(NULL, AV_LOG_ERROR,

                       "Error reading packet header: %d (%s)\n",

                       read_result, strerror(read_result));

                packet_type = SC_PKT_CANCEL;

            } else {

                av_log(NULL, AV_LOG_ERROR,

                       "The server closed the connection\n");

                packet_type = SC_PKT_NO_DATA;

            }

            return packet_type;

        }

        // handle command packet.

        if(AV_RL32(mms->in_buffer + 4)==0xb00bface) {

            int length_remaining, hr;

            mmst->incoming_flags= mms->in_buffer[3];

            read_result= url_read_complete(mms->mms_hd, mms->in_buffer+8, 4);

            if(read_result != 4) {

                av_log(NULL, AV_LOG_ERROR,

                       "Reading command packet length failed: %d (%s)\n",

                       read_result,

                       read_result < 0 ? strerror(read_result) :

                           "The server closed the connection");

                return read_result < 0 ? read_result : AVERROR_IO;

            }

            length_remaining= AV_RL32(mms->in_buffer+8) + 4;

            av_dlog(NULL, "Length remaining is %d\n", length_remaining);

            // read the rest of the packet.

            if (length_remaining < 0

                || length_remaining > sizeof(mms->in_buffer) - 12) {

                av_log(NULL, AV_LOG_ERROR,

                       "Incoming packet length %d exceeds bufsize %zu\n",

                       length_remaining, sizeof(mms->in_buffer) - 12);

                return AVERROR_INVALIDDATA;

            }

            read_result = url_read_complete(mms->mms_hd, mms->in_buffer + 12,

                                            length_remaining) ;

            if (read_result != length_remaining) {

                av_log(NULL, AV_LOG_ERROR,

                       "Reading pkt data (length=%d) failed: %d (%s)\n",

                       length_remaining, read_result,

                       read_result < 0 ? strerror(read_result) :

                           "The server closed the connection");

                return read_result < 0 ? read_result : AVERROR_IO;

            }

            packet_type= AV_RL16(mms->in_buffer+36);

            hr = AV_RL32(mms->in_buffer + 40);

            if (hr) {

                av_log(NULL, AV_LOG_ERROR,

                       "Server sent a message with packet type 0x%x and error status code 0x%08x\n", packet_type, hr);

                return AVERROR_UNKNOWN;

            }

        } else {

            int length_remaining;

            int packet_id_type;

            int tmp;

            // note we cache the first 8 bytes,

            // then fill up the buffer with the others

            tmp                       = AV_RL16(mms->in_buffer + 6);

            length_remaining          = (tmp - 8) & 0xffff;

            mmst->incoming_packet_seq = AV_RL32(mms->in_buffer);

            packet_id_type            = mms->in_buffer[4];

            mmst->incoming_flags      = mms->in_buffer[5];

            if (length_remaining < 0

                || length_remaining > sizeof(mms->in_buffer) - 8) {

                av_log(NULL, AV_LOG_ERROR,

                       "Data length %d is invalid or too large (max=%zu)\n",

                       length_remaining, sizeof(mms->in_buffer));

                return AVERROR_INVALIDDATA;

            }

            mms->remaining_in_len    = length_remaining;

            mms->read_in_ptr         = mms->in_buffer;

            read_result= url_read_complete(mms->mms_hd, mms->in_buffer, length_remaining);

            if(read_result != length_remaining) {

                av_log(NULL, AV_LOG_ERROR,

                       "Failed to read packet data of size %d: %d (%s)\n",

                       length_remaining, read_result,

                       read_result < 0 ? strerror(read_result) :

                           "The server closed the connection");

                return read_result < 0 ? read_result : AVERROR_IO;

            }

            // if we successfully read everything.

            if(packet_id_type == mmst->header_packet_id) {

                packet_type = SC_PKT_ASF_HEADER;

                // Store the asf header

                if(!mms->header_parsed) {

                    void *p = av_realloc(mms->asf_header,

                                  mms->asf_header_size + mms->remaining_in_len);

                    if (!p) {

                        av_freep(&mms->asf_header);

                        return AVERROR(ENOMEM);

                    }

                    mms->asf_header = p;

                    memcpy(mms->asf_header + mms->asf_header_size,

                           mms->read_in_ptr, mms->remaining_in_len);

                    mms->asf_header_size += mms->remaining_in_len;

                }

                // 0x04 means asf header is sent in multiple packets.

                if (mmst->incoming_flags == 0x04)

                    continue;

            } else if(packet_id_type == mmst->packet_id) {

                packet_type = SC_PKT_ASF_MEDIA;

            } else {

                av_dlog(NULL, "packet id type %d is old.", packet_id_type);

                continue;

            }

        }

        // preprocess some packet type

        if(packet_type == SC_PKT_KEEPALIVE) {

            send_keepalive_packet(mmst);

            continue;

        } else if(packet_type == SC_PKT_STREAM_CHANGING) {

            handle_packet_stream_changing_type(mmst);

        } else if(packet_type == SC_PKT_ASF_MEDIA) {

            pad_media_packet(mms);

        }

        return packet_type;

    }

}


static void invalid_dict_comma(void)

{

    QObject *obj = qobject_from_json("{'abc':32,}", NULL);

    g_assert(obj == NULL);

}


static void type_initialize(TypeImpl *ti)

{

    TypeImpl *parent;

    if (ti->class) {

        return;

    }

    ti->class_size = type_class_get_size(ti);

    ti->instance_size = type_object_get_size(ti);

    ti->class = g_malloc0(ti->class_size);

    parent = type_get_parent(ti);

    if (parent) {

        type_initialize(parent);

        GSList *e;

        int i;

        g_assert(parent->class_size <= ti->class_size);

        memcpy(ti->class, parent->class, parent->class_size);

        ti->class->interfaces = NULL;

        for (e = parent->class->interfaces; e; e = e->next) {

            ObjectClass *iface = e->data;

            type_initialize_interface(ti, object_class_get_name(iface));

        }

        for (i = 0; i < ti->num_interfaces; i++) {

            TypeImpl *t = type_get_by_name(ti->interfaces[i].typename);

            for (e = ti->class->interfaces; e; e = e->next) {

                TypeImpl *target_type = OBJECT_CLASS(e->data)->type;

                if (type_is_ancestor(target_type, t)) {

                    break;

                }

            }

            if (e) {

                continue;

            }

            type_initialize_interface(ti, ti->interfaces[i].typename);

        }

    }

    ti->class->type = ti;

    while (parent) {

        if (parent->class_base_init) {

            parent->class_base_init(ti->class, ti->class_data);

        }

        parent = type_get_parent(parent);

    }

    if (ti->class_init) {

        ti->class_init(ti->class, ti->class_data);

    }

}


static av_cold int decode_close_mp3on4(AVCodecContext * avctx)
{
    MP3On4DecodeContext *s = avctx->priv_data;
    int i;
    for (i = 0; i < s->frames; i++)
        av_freep(&s->mp3decctx[i]);
    return 0;
}


static inline void encode_vlc_codeword(PutBitContext *pb, unsigned codebook, int val)

{

    unsigned int rice_order, exp_order, switch_bits, switch_val;

    int exponent;

    /* number of prefix bits to switch between Rice and expGolomb */

    switch_bits = (codebook & 3) + 1;

    rice_order  =  codebook >> 5;       /* rice code order */

    exp_order   = (codebook >> 2) & 7;  /* exp golomb code order */

    switch_val  = switch_bits << rice_order;

    if (val >= switch_val) {

        val -= switch_val - (1 << exp_order);

        exponent = av_log2(val);

        put_bits(pb, exponent - exp_order + switch_bits, 0);

        put_bits(pb, 1, 1);

        put_bits(pb, exponent, val);

    } else {

        exponent = val >> rice_order;

        if (exponent)

            put_bits(pb, exponent, 0);

        put_bits(pb, 1, 1);

        if (rice_order)

            put_sbits(pb, rice_order, val);

    }

}


static int decoder_decode_frame(Decoder *d, void *fframe) {

    int got_frame = 0;

    AVFrame *frame = fframe;

    d->flushed = 0;

    do {

        int ret = -1;

        if (d->queue->abort_request)

            return -1;

        if (!d->packet_pending || d->queue->serial != d->pkt_serial) {

            AVPacket pkt;

            do {

                if (d->queue->nb_packets == 0)

                    SDL_CondSignal(d->empty_queue_cond);

                if (packet_queue_get(d->queue, &pkt, 1, &d->pkt_serial) < 0)

                    return -1;

                if (pkt.data == flush_pkt.data) {

                    avcodec_flush_buffers(d->avctx);

                    d->finished = 0;

                    d->flushed = 1;

                    d->next_pts = d->start_pts;

                    d->next_pts_tb = d->start_pts_tb;

                }

            } while (pkt.data == flush_pkt.data || d->queue->serial != d->pkt_serial);

            av_free_packet(&d->pkt);

            d->pkt_temp = d->pkt = pkt;

            d->packet_pending = 1;

        }

        switch (d->avctx->codec_type) {

            case AVMEDIA_TYPE_VIDEO:

                ret = avcodec_decode_video2(d->avctx, frame, &got_frame, &d->pkt_temp);

                if (got_frame) {

                    if (decoder_reorder_pts == -1) {

                        frame->pts = av_frame_get_best_effort_timestamp(frame);

                    } else if (decoder_reorder_pts) {

                        frame->pts = frame->pkt_pts;

                    } else {

                        frame->pts = frame->pkt_dts;

                    }

                }

                break;

            case AVMEDIA_TYPE_AUDIO:

                ret = avcodec_decode_audio4(d->avctx, frame, &got_frame, &d->pkt_temp);

                if (got_frame) {

                    AVRational tb = (AVRational){1, frame->sample_rate};

                    if (frame->pts != AV_NOPTS_VALUE)

                        frame->pts = av_rescale_q(frame->pts, d->avctx->time_base, tb);

                    else if (frame->pkt_pts != AV_NOPTS_VALUE)

                        frame->pts = av_rescale_q(frame->pkt_pts, av_codec_get_pkt_timebase(d->avctx), tb);

                    else if (d->next_pts != AV_NOPTS_VALUE)

                        frame->pts = av_rescale_q(d->next_pts, d->next_pts_tb, tb);

                    if (frame->pts != AV_NOPTS_VALUE) {

                        d->next_pts = frame->pts + frame->nb_samples;

                        d->next_pts_tb = tb;

                    }

                }

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                ret = avcodec_decode_subtitle2(d->avctx, fframe, &got_frame, &d->pkt_temp);

                break;

        }

        if (ret < 0) {

            d->packet_pending = 0;

        } else {

            d->pkt_temp.dts =

            d->pkt_temp.pts = AV_NOPTS_VALUE;

            if (d->pkt_temp.data) {

                if (d->avctx->codec_type != AVMEDIA_TYPE_AUDIO)

                    ret = d->pkt_temp.size;

                d->pkt_temp.data += ret;

                d->pkt_temp.size -= ret;

                if (d->pkt_temp.size <= 0)

                    d->packet_pending = 0;

            } else {

                if (!got_frame) {

                    d->packet_pending = 0;

                    d->finished = d->pkt_serial;

                }

            }

        }

    } while (!got_frame && !d->finished);

    return got_frame;

}


static void boston_mach_init(MachineState *machine)

{

    DeviceState *dev;

    BostonState *s;

    Error *err = NULL;

    const char *cpu_model;

    MemoryRegion *flash, *ddr, *ddr_low_alias, *lcd, *platreg;

    MemoryRegion *sys_mem = get_system_memory();

    XilinxPCIEHost *pcie2;

    PCIDevice *ahci;

    DriveInfo *hd[6];

    Chardev *chr;

    int fw_size, fit_err;

    bool is_64b;

    if ((machine->ram_size % G_BYTE) ||

        (machine->ram_size > (2 * G_BYTE))) {

        error_report("Memory size must be 1GB or 2GB");

        exit(1);

    }

    cpu_model = machine->cpu_model ?: "I6400";

    dev = qdev_create(NULL, TYPE_MIPS_BOSTON);

    qdev_init_nofail(dev);

    s = BOSTON(dev);

    s->mach = machine;

    s->cps = g_new0(MIPSCPSState, 1);

    if (!cpu_supports_cps_smp(cpu_model)) {

        error_report("Boston requires CPUs which support CPS");

        exit(1);

    }

    is_64b = cpu_supports_isa(cpu_model, ISA_MIPS64);

    object_initialize(s->cps, sizeof(MIPSCPSState), TYPE_MIPS_CPS);

    qdev_set_parent_bus(DEVICE(s->cps), sysbus_get_default());

    object_property_set_str(OBJECT(s->cps), cpu_model, "cpu-model", &err);

    object_property_set_int(OBJECT(s->cps), smp_cpus, "num-vp", &err);

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

    if (err != NULL) {

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

        exit(1);

    }

    sysbus_mmio_map_overlap(SYS_BUS_DEVICE(s->cps), 0, 0, 1);

    flash =  g_new(MemoryRegion, 1);

    memory_region_init_rom_device(flash, NULL, &boston_flash_ops, s,

                                  "boston.flash", 128 * M_BYTE, &err);

    memory_region_add_subregion_overlap(sys_mem, 0x18000000, flash, 0);

    ddr = g_new(MemoryRegion, 1);

    memory_region_allocate_system_memory(ddr, NULL, "boston.ddr",

                                         machine->ram_size);

    memory_region_add_subregion_overlap(sys_mem, 0x80000000, ddr, 0);

    ddr_low_alias = g_new(MemoryRegion, 1);

    memory_region_init_alias(ddr_low_alias, NULL, "boston_low.ddr",

                             ddr, 0, MIN(machine->ram_size, (256 * M_BYTE)));

    memory_region_add_subregion_overlap(sys_mem, 0, ddr_low_alias, 0);

    xilinx_pcie_init(sys_mem, 0,

                     0x10000000, 32 * M_BYTE,

                     0x40000000, 1 * G_BYTE,

                     get_cps_irq(s->cps, 2), false);

    xilinx_pcie_init(sys_mem, 1,

                     0x12000000, 32 * M_BYTE,

                     0x20000000, 512 * M_BYTE,

                     get_cps_irq(s->cps, 1), false);

    pcie2 = xilinx_pcie_init(sys_mem, 2,

                             0x14000000, 32 * M_BYTE,

                             0x16000000, 1 * M_BYTE,

                             get_cps_irq(s->cps, 0), true);

    platreg = g_new(MemoryRegion, 1);

    memory_region_init_io(platreg, NULL, &boston_platreg_ops, s,

                          "boston-platregs", 0x1000);

    memory_region_add_subregion_overlap(sys_mem, 0x17ffd000, platreg, 0);

    if (!serial_hds[0]) {

        serial_hds[0] = qemu_chr_new("serial0", "null");

    }

    s->uart = serial_mm_init(sys_mem, 0x17ffe000, 2,

                             get_cps_irq(s->cps, 3), 10000000,

                             serial_hds[0], DEVICE_NATIVE_ENDIAN);

    lcd = g_new(MemoryRegion, 1);

    memory_region_init_io(lcd, NULL, &boston_lcd_ops, s, "boston-lcd", 0x8);

    memory_region_add_subregion_overlap(sys_mem, 0x17fff000, lcd, 0);

    chr = qemu_chr_new("lcd", "vc:320x240");

    qemu_chr_fe_init(&s->lcd_display, chr, NULL);

    qemu_chr_fe_set_handlers(&s->lcd_display, NULL, NULL,

                             boston_lcd_event, s, NULL, true);

    ahci = pci_create_simple_multifunction(&PCI_BRIDGE(&pcie2->root)->sec_bus,

                                           PCI_DEVFN(0, 0),

                                           true, TYPE_ICH9_AHCI);

    g_assert(ARRAY_SIZE(hd) == ICH_AHCI(ahci)->ahci.ports);

    ide_drive_get(hd, ICH_AHCI(ahci)->ahci.ports);

    ahci_ide_create_devs(ahci, hd);

    if (machine->firmware) {

        fw_size = load_image_targphys(machine->firmware,

                                      0x1fc00000, 4 * M_BYTE);

        if (fw_size == -1) {

            error_printf("unable to load firmware image '%s'\n",

                          machine->firmware);

            exit(1);

        }

    } else if (machine->kernel_filename) {

        fit_err = load_fit(&boston_fit_loader, machine->kernel_filename, s);

        if (fit_err) {

            error_printf("unable to load FIT image\n");

            exit(1);

        }

        gen_firmware(memory_region_get_ram_ptr(flash) + 0x7c00000,

                     s->kernel_entry, s->fdt_base, is_64b);

    } else if (!qtest_enabled()) {

        error_printf("Please provide either a -kernel or -bios argument\n");

        exit(1);

    }

}


static int cng_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame_ptr, AVPacket *avpkt)
{
    AVFrame *frame = data;
    CNGContext *p = avctx->priv_data;
    int buf_size  = avpkt->size;
    int ret, i;
    int16_t *buf_out;
    float e = 1.0;
    float scaling;
    if (avpkt->size) {
        int dbov = -avpkt->data[0];
        p->target_energy = 1081109975 * ff_exp10(dbov / 10.0) * 0.75;
        memset(p->target_refl_coef, 0, p->order * sizeof(*p->target_refl_coef));
        for (i = 0; i < FFMIN(avpkt->size - 1, p->order); i++) {
            p->target_refl_coef[i] = (avpkt->data[1 + i] - 127) / 128.0;
    if (p->inited) {
        p->energy = p->energy / 2 + p->target_energy / 2;
        for (i = 0; i < p->order; i++)
            p->refl_coef[i] = 0.6 *p->refl_coef[i] + 0.4 * p->target_refl_coef[i];
    } else {
        p->energy = p->target_energy;
        memcpy(p->refl_coef, p->target_refl_coef, p->order * sizeof(*p->refl_coef));
        p->inited = 1;
    make_lpc_coefs(p->lpc_coef, p->refl_coef, p->order);
    for (i = 0; i < p->order; i++)
        e *= 1.0 - p->refl_coef[i]*p->refl_coef[i];
    scaling = sqrt(e * p->energy / 1081109975);
    for (i = 0; i < avctx->frame_size; i++) {
        int r = (av_lfg_get(&p->lfg) & 0xffff) - 0x8000;
        p->excitation[i] = scaling * r;
    ff_celp_lp_synthesis_filterf(p->filter_out + p->order, p->lpc_coef,
                                 p->excitation, avctx->frame_size, p->order);
    frame->nb_samples = avctx->frame_size;
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
        return ret;
    buf_out = (int16_t *)frame->data[0];
    for (i = 0; i < avctx->frame_size; i++)
        buf_out[i] = p->filter_out[i + p->order];
    memcpy(p->filter_out, p->filter_out + avctx->frame_size,
           p->order * sizeof(*p->filter_out));
    *got_frame_ptr = 1;
    return buf_size;


static int vfio_pci_hot_reset_multi(VFIOPCIDevice *vdev)

{

    return vfio_pci_hot_reset(vdev, false);

}


void qerror_print(QError *qerror)

{

    QString *qstring = qerror_human(qerror);

    loc_push_restore(&qerror->loc);

    error_report("%s", qstring_get_str(qstring));

    loc_pop(&qerror->loc);

    QDECREF(qstring);

}


static int is_async_return(const QObject *data)

{

    if (data && qobject_type(data) == QTYPE_QDICT) {

        return qdict_haskey(qobject_to_qdict(data), "__mon_async");

    }

    return 0;

}


static void stereo_processing(PSContext *ps, float (*l)[32][2], float (*r)[32][2], int is34)

{

    int e, b, k, n;

    float (*H11)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H11;

    float (*H12)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H12;

    float (*H21)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H21;

    float (*H22)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H22;

    int8_t *opd_hist = ps->opd_hist;

    int8_t *ipd_hist = ps->ipd_hist;

    int8_t iid_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t icc_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t ipd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t opd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t (*iid_mapped)[PS_MAX_NR_IIDICC] = iid_mapped_buf;

    int8_t (*icc_mapped)[PS_MAX_NR_IIDICC] = icc_mapped_buf;

    int8_t (*ipd_mapped)[PS_MAX_NR_IIDICC] = ipd_mapped_buf;

    int8_t (*opd_mapped)[PS_MAX_NR_IIDICC] = opd_mapped_buf;

    const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;

    const float (*H_LUT)[8][4] = (PS_BASELINE || ps->icc_mode < 3) ? HA : HB;

    //Remapping

    if (ps->num_env_old) {

        memcpy(H11[0][0], H11[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[0][0][0]));

        memcpy(H11[1][0], H11[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[1][0][0]));

        memcpy(H12[0][0], H12[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[0][0][0]));

        memcpy(H12[1][0], H12[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[1][0][0]));

        memcpy(H21[0][0], H21[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[0][0][0]));

        memcpy(H21[1][0], H21[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[1][0][0]));

        memcpy(H22[0][0], H22[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[0][0][0]));

        memcpy(H22[1][0], H22[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[1][0][0]));

    }

    if (is34) {

        remap34(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);

        remap34(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);

        if (ps->enable_ipdopd) {

            remap34(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);

            remap34(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);

        }

        if (!ps->is34bands_old) {

            map_val_20_to_34(H11[0][0]);

            map_val_20_to_34(H11[1][0]);

            map_val_20_to_34(H12[0][0]);

            map_val_20_to_34(H12[1][0]);

            map_val_20_to_34(H21[0][0]);

            map_val_20_to_34(H21[1][0]);

            map_val_20_to_34(H22[0][0]);

            map_val_20_to_34(H22[1][0]);

            ipdopd_reset(ipd_hist, opd_hist);

        }

    } else {

        remap20(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);

        remap20(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);

        if (ps->enable_ipdopd) {

            remap20(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);

            remap20(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);

        }

        if (ps->is34bands_old) {

            map_val_34_to_20(H11[0][0]);

            map_val_34_to_20(H11[1][0]);

            map_val_34_to_20(H12[0][0]);

            map_val_34_to_20(H12[1][0]);

            map_val_34_to_20(H21[0][0]);

            map_val_34_to_20(H21[1][0]);

            map_val_34_to_20(H22[0][0]);

            map_val_34_to_20(H22[1][0]);

            ipdopd_reset(ipd_hist, opd_hist);

        }

    }

    //Mixing

    for (e = 0; e < ps->num_env; e++) {

        for (b = 0; b < NR_PAR_BANDS[is34]; b++) {

            float h11, h12, h21, h22;

            h11 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][0];

            h12 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][1];

            h21 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][2];

            h22 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][3];

            if (!PS_BASELINE && ps->enable_ipdopd && b < ps->nr_ipdopd_par) {

                //The spec say says to only run this smoother when enable_ipdopd

                //is set but the reference decoder appears to run it constantly

                float h11i, h12i, h21i, h22i;

                float ipd_adj_re, ipd_adj_im;

                int opd_idx = opd_hist[b] * 8 + opd_mapped[e][b];

                int ipd_idx = ipd_hist[b] * 8 + ipd_mapped[e][b];

                float opd_re = pd_re_smooth[opd_idx];

                float opd_im = pd_im_smooth[opd_idx];

                float ipd_re = pd_re_smooth[ipd_idx];

                float ipd_im = pd_im_smooth[ipd_idx];

                opd_hist[b] = opd_idx & 0x3F;

                ipd_hist[b] = ipd_idx & 0x3F;

                ipd_adj_re = opd_re*ipd_re + opd_im*ipd_im;

                ipd_adj_im = opd_im*ipd_re - opd_re*ipd_im;

                h11i = h11 * opd_im;

                h11  = h11 * opd_re;

                h12i = h12 * ipd_adj_im;

                h12  = h12 * ipd_adj_re;

                h21i = h21 * opd_im;

                h21  = h21 * opd_re;

                h22i = h22 * ipd_adj_im;

                h22  = h22 * ipd_adj_re;

                H11[1][e+1][b] = h11i;

                H12[1][e+1][b] = h12i;

                H21[1][e+1][b] = h21i;

                H22[1][e+1][b] = h22i;

            }

            H11[0][e+1][b] = h11;

            H12[0][e+1][b] = h12;

            H21[0][e+1][b] = h21;

            H22[0][e+1][b] = h22;

        }

        for (k = 0; k < NR_BANDS[is34]; k++) {

            float h11r, h12r, h21r, h22r;

            float h11i, h12i, h21i, h22i;

            float h11r_step, h12r_step, h21r_step, h22r_step;

            float h11i_step, h12i_step, h21i_step, h22i_step;

            int start = ps->border_position[e];

            int stop  = ps->border_position[e+1];

            float width = 1.f / (stop - start);

            b = k_to_i[k];

            h11r = H11[0][e][b];

            h12r = H12[0][e][b];

            h21r = H21[0][e][b];

            h22r = H22[0][e][b];

            if (!PS_BASELINE && ps->enable_ipdopd) {

            //Is this necessary? ps_04_new seems unchanged

            if ((is34 && k <= 13 && k >= 9) || (!is34 && k <= 1)) {

                h11i = -H11[1][e][b];

                h12i = -H12[1][e][b];

                h21i = -H21[1][e][b];

                h22i = -H22[1][e][b];

            } else {

                h11i = H11[1][e][b];

                h12i = H12[1][e][b];

                h21i = H21[1][e][b];

                h22i = H22[1][e][b];

            }

            }

            //Interpolation

            h11r_step = (H11[0][e+1][b] - h11r) * width;

            h12r_step = (H12[0][e+1][b] - h12r) * width;

            h21r_step = (H21[0][e+1][b] - h21r) * width;

            h22r_step = (H22[0][e+1][b] - h22r) * width;

            if (!PS_BASELINE && ps->enable_ipdopd) {

                h11i_step = (H11[1][e+1][b] - h11i) * width;

                h12i_step = (H12[1][e+1][b] - h12i) * width;

                h21i_step = (H21[1][e+1][b] - h21i) * width;

                h22i_step = (H22[1][e+1][b] - h22i) * width;

            }

            for (n = start + 1; n <= stop; n++) {

                //l is s, r is d

                float l_re = l[k][n][0];

                float l_im = l[k][n][1];

                float r_re = r[k][n][0];

                float r_im = r[k][n][1];

                h11r += h11r_step;

                h12r += h12r_step;

                h21r += h21r_step;

                h22r += h22r_step;

                if (!PS_BASELINE && ps->enable_ipdopd) {

                    h11i += h11i_step;

                    h12i += h12i_step;

                    h21i += h21i_step;

                    h22i += h22i_step;

                    l[k][n][0] = h11r*l_re + h21r*r_re - h11i*l_im - h21i*r_im;

                    l[k][n][1] = h11r*l_im + h21r*r_im + h11i*l_re + h21i*r_re;

                    r[k][n][0] = h12r*l_re + h22r*r_re - h12i*l_im - h22i*r_im;

                    r[k][n][1] = h12r*l_im + h22r*r_im + h12i*l_re + h22i*r_re;

                } else {

                    l[k][n][0] = h11r*l_re + h21r*r_re;

                    l[k][n][1] = h11r*l_im + h21r*r_im;

                    r[k][n][0] = h12r*l_re + h22r*r_re;

                    r[k][n][1] = h12r*l_im + h22r*r_im;

                }

            }

        }

    }

}


static int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,

                                 void *opaque)

{

    if (mon->rs) {

        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);

        /* prompt is printed on return from the command handler */

        return 0;

    } else {

        monitor_printf(mon, "terminal does not support password prompting\n");

        return -ENOTTY;

    }

}


static inline void gen_efdnabs(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

#if defined(TARGET_PPC64)

    tcg_gen_ori_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], 0x8000000000000000LL);

#else

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

    tcg_gen_ori_tl(cpu_gprh[rD(ctx->opcode)], cpu_gprh[rA(ctx->opcode)], 0x80000000);

#endif

}


int vhost_dev_init(struct vhost_dev *hdev, void *opaque,

                   VhostBackendType backend_type)

{

    uint64_t features;

    int i, r;

    if (vhost_set_backend_type(hdev, backend_type) < 0) {

        close((uintptr_t)opaque);

        return -1;

    }

    if (hdev->vhost_ops->vhost_backend_init(hdev, opaque) < 0) {

        close((uintptr_t)opaque);

        return -errno;

    }

    r = hdev->vhost_ops->vhost_call(hdev, VHOST_SET_OWNER, NULL);

    if (r < 0) {

        goto fail;

    }

    r = hdev->vhost_ops->vhost_call(hdev, VHOST_GET_FEATURES, &features);

    if (r < 0) {

        goto fail;

    }

    for (i = 0; i < hdev->nvqs; ++i) {

        r = vhost_virtqueue_init(hdev, hdev->vqs + i, i);

        if (r < 0) {

            goto fail_vq;

        }

    }

    hdev->features = features;

    hdev->memory_listener = (MemoryListener) {

        .begin = vhost_begin,

        .commit = vhost_commit,

        .region_add = vhost_region_add,

        .region_del = vhost_region_del,

        .region_nop = vhost_region_nop,

        .log_start = vhost_log_start,

        .log_stop = vhost_log_stop,

        .log_sync = vhost_log_sync,

        .log_global_start = vhost_log_global_start,

        .log_global_stop = vhost_log_global_stop,

        .eventfd_add = vhost_eventfd_add,

        .eventfd_del = vhost_eventfd_del,

        .priority = 10

    };

    hdev->migration_blocker = NULL;

    if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {

        error_setg(&hdev->migration_blocker,

                   "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");

        migrate_add_blocker(hdev->migration_blocker);

    }

    hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));

    hdev->n_mem_sections = 0;

    hdev->mem_sections = NULL;

    hdev->log = NULL;

    hdev->log_size = 0;

    hdev->log_enabled = false;

    hdev->started = false;

    hdev->memory_changed = false;

    memory_listener_register(&hdev->memory_listener, &address_space_memory);

    return 0;

fail_vq:

    while (--i >= 0) {

        vhost_virtqueue_cleanup(hdev->vqs + i);

    }

fail:

    r = -errno;

    hdev->vhost_ops->vhost_backend_cleanup(hdev);

    return r;

}


static void tcg_out_ld(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg1,

                       tcg_target_long arg2)

{

    uint8_t *old_code_ptr = s->code_ptr;

    if (type == TCG_TYPE_I32) {

        tcg_out_op_t(s, INDEX_op_ld_i32);

        tcg_out_r(s, ret);

        tcg_out_r(s, arg1);

        tcg_out32(s, arg2);

    } else {

        assert(type == TCG_TYPE_I64);

#if TCG_TARGET_REG_BITS == 64

        tcg_out_op_t(s, INDEX_op_ld_i64);

        tcg_out_r(s, ret);

        tcg_out_r(s, arg1);

        assert(arg2 == (uint32_t)arg2);

        tcg_out32(s, arg2);

#else

        TODO();

#endif

    }

    old_code_ptr[1] = s->code_ptr - old_code_ptr;

}


static int tight_send_framebuffer_update(VncState *vs, int x, int y,

                                         int w, int h)

{

    int max_rows;

    if (vs->clientds.pf.bytes_per_pixel == 4 && vs->clientds.pf.rmax == 0xFF &&

        vs->clientds.pf.bmax == 0xFF && vs->clientds.pf.gmax == 0xFF) {

        vs->tight.pixel24 = true;

    } else {

        vs->tight.pixel24 = false;

    }

    if (vs->tight.quality != -1) {

        double freq = vnc_update_freq(vs, x, y, w, h);

        if (freq > tight_jpeg_conf[vs->tight.quality].jpeg_freq_threshold) {

            return send_rect_simple(vs, x, y, w, h, false);

        }

    }

    if (w * h < VNC_TIGHT_MIN_SPLIT_RECT_SIZE) {

        return send_rect_simple(vs, x, y, w, h, true);

    }

    /* Calculate maximum number of rows in one non-solid rectangle. */

    max_rows = tight_conf[vs->tight.compression].max_rect_size;

    max_rows /= MIN(tight_conf[vs->tight.compression].max_rect_width, w);

    return find_large_solid_color_rect(vs, x, y, w, h, max_rows);

}


void helper_booke206_tlbwe(CPUPPCState *env)

{

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    uint32_t tlbncfg, tlbn;

    ppcmas_tlb_t *tlb;

    uint32_t size_tlb, size_ps;

    target_ulong mask;

    switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {

    case MAS0_WQ_ALWAYS:

        /* good to go, write that entry */

        break;

    case MAS0_WQ_COND:

        /* XXX check if reserved */

        if (0) {

            return;

        }

        break;

    case MAS0_WQ_CLR_RSRV:

        /* XXX clear entry */

        return;

    default:

        /* no idea what to do */

        return;

    }

    if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&

        !msr_gs) {

        /* XXX we don't support direct LRAT setting yet */

        fprintf(stderr, "cpu: don't support LRAT setting yet\n");

        return;

    }

    tlbn = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;

    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlbn];

    tlb = booke206_cur_tlb(env);

    if (!tlb) {

        raise_exception_err_ra(env, POWERPC_EXCP_PROGRAM,

                               POWERPC_EXCP_INVAL |

                               POWERPC_EXCP_INVAL_INVAL, GETPC());

    }

    /* check that we support the targeted size */

    size_tlb = (env->spr[SPR_BOOKE_MAS1] & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;

    size_ps = booke206_tlbnps(env, tlbn);

    if ((env->spr[SPR_BOOKE_MAS1] & MAS1_VALID) && (tlbncfg & TLBnCFG_AVAIL) &&

        !(size_ps & (1 << size_tlb))) {

        raise_exception_err_ra(env, POWERPC_EXCP_PROGRAM,

                               POWERPC_EXCP_INVAL |

                               POWERPC_EXCP_INVAL_INVAL, GETPC());

    }

    if (msr_gs) {

        cpu_abort(CPU(cpu), "missing HV implementation\n");

    }

    tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |

        env->spr[SPR_BOOKE_MAS3];

    tlb->mas1 = env->spr[SPR_BOOKE_MAS1];

    if ((env->spr[SPR_MMUCFG] & MMUCFG_MAVN) == MMUCFG_MAVN_V2) {

        /* For TLB which has a fixed size TSIZE is ignored with MAV2 */

        booke206_fixed_size_tlbn(env, tlbn, tlb);

    } else {

        if (!(tlbncfg & TLBnCFG_AVAIL)) {

            /* force !AVAIL TLB entries to correct page size */

            tlb->mas1 &= ~MAS1_TSIZE_MASK;

            /* XXX can be configured in MMUCSR0 */

            tlb->mas1 |= (tlbncfg & TLBnCFG_MINSIZE) >> 12;

        }

    }

    /* Make a mask from TLB size to discard invalid bits in EPN field */

    mask = ~(booke206_tlb_to_page_size(env, tlb) - 1);

    /* Add a mask for page attributes */

    mask |= MAS2_ACM | MAS2_VLE | MAS2_W | MAS2_I | MAS2_M | MAS2_G | MAS2_E;

    if (!msr_cm) {

        /* Executing a tlbwe instruction in 32-bit mode will set

         * bits 0:31 of the TLB EPN field to zero.

         */

        mask &= 0xffffffff;

    }

    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & mask;

    if (!(tlbncfg & TLBnCFG_IPROT)) {

        /* no IPROT supported by TLB */

        tlb->mas1 &= ~MAS1_IPROT;

    }

    if (booke206_tlb_to_page_size(env, tlb) == TARGET_PAGE_SIZE) {

        tlb_flush_page(CPU(cpu), tlb->mas2 & MAS2_EPN_MASK);

    } else {

        tlb_flush(CPU(cpu));

    }

}


static uint32_t qpi_mem_readl(void *opaque, target_phys_addr_t addr)

{

    CPUState *env;

    env = cpu_single_env;

    if (!env)

        return 0;

    return env->eflags & (IF_MASK | IOPL_MASK);

}


static void test_visitor_out_number(TestOutputVisitorData *data,

                                    const void *unused)

{

    double value = 3.14;

    QObject *obj;

    visit_type_number(data->ov, NULL, &value, &error_abort);

    obj = visitor_get(data);

    g_assert(qobject_type(obj) == QTYPE_QFLOAT);

    g_assert(qfloat_get_double(qobject_to_qfloat(obj)) == value);

}


static int find_pte32(CPUPPCState *env, struct mmu_ctx_hash32 *ctx,

                      target_ulong eaddr, int h, int rwx, int target_page_bits)

{

    hwaddr pteg_off;

    target_ulong pte0, pte1;

    int i, good = -1;

    int ret, r;

    ret = -1; /* No entry found */

    pteg_off = get_pteg_offset32(env, ctx->hash[h]);

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

        pte0 = ppc_hash32_load_hpte0(env, pteg_off + i*HASH_PTE_SIZE_32);

        pte1 = ppc_hash32_load_hpte1(env, pteg_off + i*HASH_PTE_SIZE_32);

        r = pte_check_hash32(ctx, pte0, pte1, h, rwx);

        LOG_MMU("Load pte from %08" HWADDR_PRIx " => " TARGET_FMT_lx " "

                TARGET_FMT_lx " %d %d %d " TARGET_FMT_lx "\n",

                pteg_off + (i * 8), pte0, pte1, (int)(pte0 >> 31), h,

                (int)((pte0 >> 6) & 1), ctx->ptem);

        switch (r) {

        case -3:

            /* PTE inconsistency */

            return -1;

        case -2:

            /* Access violation */

            ret = -2;

            good = i;

            break;

        case -1:

        default:

            /* No PTE match */

            break;

        case 0:

            /* access granted */

            /* XXX: we should go on looping to check all PTEs consistency

             *      but if we can speed-up the whole thing as the

             *      result would be undefined if PTEs are not consistent.

             */

            ret = 0;

            good = i;

            goto done;

        }

    }

    if (good != -1) {

    done:

        LOG_MMU("found PTE at addr %08" HWADDR_PRIx " prot=%01x ret=%d\n",

                ctx->raddr, ctx->prot, ret);

        /* Update page flags */

        pte1 = ctx->raddr;

        if (ppc_hash32_pte_update_flags(ctx, &pte1, ret, rwx) == 1) {

            ppc_hash32_store_hpte1(env, pteg_off + good * HASH_PTE_SIZE_32,

                                   pte1);

        }

    }

    /* We have a TLB that saves 4K pages, so let's

     * split a huge page to 4k chunks */

    if (target_page_bits != TARGET_PAGE_BITS) {

        ctx->raddr |= (eaddr & ((1 << target_page_bits) - 1))

                      & TARGET_PAGE_MASK;

    }

    return ret;

}


int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);

    AVPicture dummy_pict;

    int ret;

    if (!desc)

        return AVERROR(EINVAL);

    if ((ret = av_image_check_size(width, height, 0, NULL)) < 0)

        return ret;

    if (desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)

        // do not include palette for these pseudo-paletted formats

        return width * height;

    return avpicture_fill(&dummy_pict, NULL, pix_fmt, width, height);

}


uint32_t HELPER(testblock)(CPUS390XState *env, uint64_t real_addr)

{

    uintptr_t ra = GETPC();

    CPUState *cs = CPU(s390_env_get_cpu(env));

    int i;

    real_addr = wrap_address(env, real_addr) & TARGET_PAGE_MASK;

    /* Check low-address protection */

    if ((env->cregs[0] & CR0_LOWPROT) && real_addr < 0x2000) {

        cpu_restore_state(cs, ra);

        program_interrupt(env, PGM_PROTECTION, 4);

        return 1;

    }

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

        cpu_stq_real_ra(env, real_addr + i, 0, ra);

    }

    return 0;

}


static void block_dirty_bitmap_add_prepare(BlkActionState *common,

                                           Error **errp)

{

    Error *local_err = NULL;

    BlockDirtyBitmapAdd *action;

    BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,

                                             common, common);

    if (action_check_completion_mode(common, errp) < 0) {

        return;

    }

    action = common->action->u.block_dirty_bitmap_add;

    /* AIO context taken and released within qmp_block_dirty_bitmap_add */

    qmp_block_dirty_bitmap_add(action->node, action->name,

                               action->has_granularity, action->granularity,

                               &local_err);

    if (!local_err) {

        state->prepared = true;

    } else {

        error_propagate(errp, local_err);

    }

}


int32_t scsi_req_enqueue(SCSIRequest *req, uint8_t *buf)

{

    int32_t rc;

    assert(!req->enqueued);

    scsi_req_ref(req);

    req->enqueued = true;

    QTAILQ_INSERT_TAIL(&req->dev->requests, req, next);

    scsi_req_ref(req);

    rc = req->ops->send_command(req, buf);

    scsi_req_unref(req);

    return rc;

}


static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,

                        char *vdi, uint32_t *snapid, char *tag)

{

    URI *uri;

    QueryParams *qp = NULL;

    int ret = 0;

    uri = uri_parse(filename);

    if (!uri) {

        return -EINVAL;

    }

    /* transport */

    if (!strcmp(uri->scheme, "sheepdog")) {

        s->is_unix = false;

    } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {

        s->is_unix = false;

    } else if (!strcmp(uri->scheme, "sheepdog+unix")) {

        s->is_unix = true;

    } else {

        ret = -EINVAL;

        goto out;

    }

    if (uri->path == NULL || !strcmp(uri->path, "/")) {

        ret = -EINVAL;

        goto out;

    }

    pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);

    qp = query_params_parse(uri->query);

    if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {

        ret = -EINVAL;

        goto out;

    }

    if (s->is_unix) {

        /* sheepdog+unix:///vdiname?socket=path */

        if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {

            ret = -EINVAL;

            goto out;

        }

        s->host_spec = g_strdup(qp->p[0].value);

    } else {

        /* sheepdog[+tcp]://[host:port]/vdiname */

        s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,

                                       uri->port ?: SD_DEFAULT_PORT);

    }

    /* snapshot tag */

    if (uri->fragment) {

        *snapid = strtoul(uri->fragment, NULL, 10);

        if (*snapid == 0) {

            pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);

        }

    } else {

        *snapid = CURRENT_VDI_ID; /* search current vdi */

    }

out:

    if (qp) {

        query_params_free(qp);

    }

    uri_free(uri);

    return ret;

}


static void rtas_ibm_query_interrupt_source_number(sPAPREnvironment *spapr,

                                                   uint32_t token,

                                                   uint32_t nargs,

                                                   target_ulong args,

                                                   uint32_t nret,

                                                   target_ulong rets)

{

    uint32_t config_addr = rtas_ld(args, 0);

    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    unsigned int intr_src_num = -1, ioa_intr_num = rtas_ld(args, 3);

    int ndev;

    sPAPRPHBState *phb = NULL;

    /* Fins sPAPRPHBState */

    phb = find_phb(spapr, buid);

    if (!phb) {

        rtas_st(rets, 0, -3); /* Parameter error */

        return;

    }

    /* Find device descriptor and start IRQ */

    ndev = spapr_msicfg_find(phb, config_addr, false);

    if (ndev < 0) {

        trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr);

        rtas_st(rets, 0, -1); /* Hardware error */

        return;

    }

    intr_src_num = phb->msi_table[ndev].irq + ioa_intr_num;

    trace_spapr_pci_rtas_ibm_query_interrupt_source_number(ioa_intr_num,

                                                           intr_src_num);

    rtas_st(rets, 0, 0);

    rtas_st(rets, 1, intr_src_num);

    rtas_st(rets, 2, 1);/* 0 == level; 1 == edge */

}


static void mpic_irq_raise(openpic_t *mpp, int n_CPU, IRQ_src_t *src)

{

    int n_ci = IDR_CI0 - n_CPU;

    if(test_bit(&src->ide, n_ci)) {

        qemu_irq_raise(mpp->dst[n_CPU].irqs[OPENPIC_OUTPUT_CINT]);

    }

    else {

        qemu_irq_raise(mpp->dst[n_CPU].irqs[OPENPIC_OUTPUT_INT]);

    }

}


static void tc6393xb_gpio_handler_update(TC6393xbState *s)

{

    uint32_t level, diff;

    int bit;

    level = s->gpio_level & s->gpio_dir;

    for (diff = s->prev_level ^ level; diff; diff ^= 1 << bit) {

        bit = ffs(diff) - 1;

        qemu_set_irq(s->handler[bit], (level >> bit) & 1);

    }

    s->prev_level = level;

}


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

{

    /* We don't use SPAPR_MACHINE() in order to exit gracefully if the user

     * tries to add a sPAPR CPU core to a non-pseries machine.

     */

    sPAPRMachineState *spapr =

        (sPAPRMachineState *) object_dynamic_cast(qdev_get_machine(),

                                                  TYPE_SPAPR_MACHINE);

    sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev));

    sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(dev));

    CPUCore *cc = CPU_CORE(OBJECT(dev));

    size_t size;

    Error *local_err = NULL;

    void *obj;

    int i, j;

    if (!spapr) {

        error_setg(errp, TYPE_SPAPR_CPU_CORE " needs a pseries machine");

        return;

    }

    size = object_type_get_instance_size(scc->cpu_type);

    sc->threads = g_malloc0(size * cc->nr_threads);

    for (i = 0; i < cc->nr_threads; i++) {

        char id[32];

        CPUState *cs;

        PowerPCCPU *cpu;

        obj = sc->threads + i * size;

        object_initialize(obj, size, scc->cpu_type);

        cs = CPU(obj);

        cpu = POWERPC_CPU(cs);

        cs->cpu_index = cc->core_id + i;

        cpu->vcpu_id = (cc->core_id * spapr->vsmt / smp_threads) + i;

        if (kvm_enabled() && !kvm_vcpu_id_is_valid(cpu->vcpu_id)) {

            error_setg(&local_err, "Can't create CPU with id %d in KVM",

                       cpu->vcpu_id);

            error_append_hint(&local_err, "Adjust the number of cpus to %d "

                              "or try to raise the number of threads per core\n",

                              cpu->vcpu_id * smp_threads / spapr->vsmt);

            goto err;

        }

        /* Set NUMA node for the threads belonged to core  */

        cpu->node_id = sc->node_id;

        snprintf(id, sizeof(id), "thread[%d]", i);

        object_property_add_child(OBJECT(sc), id, obj, &local_err);

        if (local_err) {

            goto err;

        }

        object_unref(obj);

    }

    for (j = 0; j < cc->nr_threads; j++) {

        obj = sc->threads + j * size;

        spapr_cpu_core_realize_child(obj, spapr, &local_err);

        if (local_err) {

            goto err;

        }

    }

    return;

err:

    while (--i >= 0) {

        obj = sc->threads + i * size;

        object_unparent(obj);

    }

    g_free(sc->threads);

    error_propagate(errp, local_err);

}


static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)

{

    int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;

    int num_blocks = s->total_num_coded_frags;

    for (qpi = 0; qpi < s->nqps-1 && num_blocks > 0; qpi++) {

        i = blocks_decoded = num_blocks_at_qpi = 0;

        bit = get_bits1(gb);

        do {

            run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;

            if (run_length == 34)

                run_length += get_bits(gb, 12);

            blocks_decoded += run_length;

            if (!bit)

                num_blocks_at_qpi += run_length;

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

                if (i >= s->total_num_coded_frags)

                    return -1;

                if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {

                    s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;

                    j++;

                }

            }

            if (run_length == MAXIMUM_LONG_BIT_RUN)

                bit = get_bits1(gb);

            else

                bit ^= 1;

        } while (blocks_decoded < num_blocks);

        num_blocks -= num_blocks_at_qpi;

    }

    return 0;

}


static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)

{

    BDRVSheepdogState *s = bs->opaque;

    SheepdogAIOCB *acb;

    AIOReq *aio_req;

    if (s->cache_flags != SD_FLAG_CMD_CACHE) {

        return 0;

    }

    acb = sd_aio_setup(bs, NULL, 0, 0);

    acb->aiocb_type = AIOCB_FLUSH_CACHE;

    acb->aio_done_func = sd_finish_aiocb;

    aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),

                            0, 0, 0, 0, 0);

    QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

    add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);

    qemu_coroutine_yield();

    return acb->ret;

}


void qemu_notify_event(void)

{

    CPUState *env = cpu_single_env;

    qemu_event_increment ();

    if (env) {

        cpu_exit(env);

    }

    if (next_cpu && env != next_cpu) {

        cpu_exit(next_cpu);

    }

    exit_request = 1;

}


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

                            TCGMemOpIdx oi)

{

    TCGMemOp opc = get_memop(oi);

#ifdef CONFIG_SOFTMMU

    unsigned mem_index = get_mmuidx(oi);

    tcg_insn_unit *label_ptr;

    TCGReg base_reg;

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

    label_ptr = s->code_ptr + 1;

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

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

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

#else

    TCGReg index_reg;

    tcg_target_long disp;

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

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

#endif

}


char *qdist_pr_plain(const struct qdist *dist, size_t n)

{

    struct qdist binned;

    char *ret;

    if (dist->n == 0) {

        return NULL;

    }

    qdist_bin__internal(&binned, dist, n);

    ret = qdist_pr_internal(&binned);

    qdist_destroy(&binned);

    return ret;

}


static int dvvideo_encode_frame(AVCodecContext *c, uint8_t *buf, int buf_size,

                                void *data)

{

    DVVideoContext *s = c->priv_data;

    s->sys = dv_codec_profile(c);

    if (!s->sys)

        return -1;

    if(buf_size < s->sys->frame_size)

        return -1;

    c->pix_fmt = s->sys->pix_fmt;

    s->picture = *((AVFrame *)data);

    s->picture.key_frame = 1;

    s->picture.pict_type = FF_I_TYPE;

    s->buf = buf;

    c->execute(c, dv_encode_mt, (void**)&s->dv_anchor[0], NULL,

               s->sys->difseg_size * 27);

    emms_c();

    return s->sys->frame_size;

}


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

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    int tag, len;

    get_be32(pb); /* version + flags */

    len = mp4_read_descr(c, pb, &tag);

    if (tag == MP4ESDescrTag) {

        get_be16(pb); /* ID */

        get_byte(pb); /* priority */

    } else

        get_be16(pb); /* ID */

    len = mp4_read_descr(c, pb, &tag);

    if (tag == MP4DecConfigDescrTag) {

        int object_type_id = get_byte(pb);

        get_byte(pb); /* stream type */

        get_be24(pb); /* buffer size db */

        get_be32(pb); /* max bitrate */

        get_be32(pb); /* avg bitrate */

        st->codec->codec_id= codec_get_id(ff_mp4_obj_type, object_type_id);

        dprintf(c->fc, "esds object type id %d\n", object_type_id);

        len = mp4_read_descr(c, pb, &tag);

        if (tag == MP4DecSpecificDescrTag) {

            dprintf(c->fc, "Specific MPEG4 header len=%d\n", len);

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

            if (!st->codec->extradata)

                return AVERROR(ENOMEM);

            get_buffer(pb, st->codec->extradata, len);

            st->codec->extradata_size = len;

            /* from mplayer */

            if ((*st->codec->extradata >> 3) == 29) {

                st->codec->codec_id = CODEC_ID_MP3ON4;

            }

        }

    }

    return 0;

}


static void audio_run_in (AudioState *s)

{

    HWVoiceIn *hw = NULL;

    while ((hw = audio_pcm_hw_find_any_enabled_in (hw))) {

        SWVoiceIn *sw;

        int captured, min;

        captured = hw->pcm_ops->run_in (hw);

        min = audio_pcm_hw_find_min_in (hw);

        hw->total_samples_captured += captured - min;

        hw->ts_helper += captured;

        for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {

            sw->total_hw_samples_acquired -= min;

            if (sw->active) {

                int avail;

                avail = audio_get_avail (sw);

                if (avail > 0) {

                    sw->callback.fn (sw->callback.opaque, avail);

                }

            }

        }

    }

}


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

{

    AvsFormat *avs = s->priv_data;

    int sub_type = 0, size = 0;

    AvsBlockType type = AVS_NONE;

    int palette_size = 0;

    uint8_t palette[4 + 3 * 256];

    int ret;

    if (avs->remaining_audio_size > 0)

        if (avs_read_audio_packet(s, pkt) > 0)

            return 0;

    while (1) {

        if (avs->remaining_frame_size <= 0) {

            if (!avio_rl16(s->pb))    /* found EOF */

                return AVERROR(EIO);

            avs->remaining_frame_size = avio_rl16(s->pb) - 4;

        }

        while (avs->remaining_frame_size > 0) {

            sub_type = avio_r8(s->pb);

            type = avio_r8(s->pb);

            size = avio_rl16(s->pb);

            if (size < 4)

            avs->remaining_frame_size -= size;

            switch (type) {

            case AVS_PALETTE:

                ret = avio_read(s->pb, palette, size - 4);

                if (ret < size - 4)

                    return AVERROR(EIO);

                palette_size = size;

                break;

            case AVS_VIDEO:

                if (!avs->st_video) {

                    avs->st_video = av_new_stream(s, AVS_VIDEO);

                    if (avs->st_video == NULL)

                        return AVERROR(ENOMEM);

                    avs->st_video->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                    avs->st_video->codec->codec_id = CODEC_ID_AVS;

                    avs->st_video->codec->width = avs->width;

                    avs->st_video->codec->height = avs->height;

                    avs->st_video->codec->bits_per_coded_sample=avs->bits_per_sample;

                    avs->st_video->nb_frames = avs->nb_frames;

                    avs->st_video->codec->time_base = (AVRational) {

                    1, avs->fps};

                }

                return avs_read_video_packet(s, pkt, type, sub_type, size,

                                             palette, palette_size);

            case AVS_AUDIO:

                if (!avs->st_audio) {

                    avs->st_audio = av_new_stream(s, AVS_AUDIO);

                    if (avs->st_audio == NULL)

                        return AVERROR(ENOMEM);

                    avs->st_audio->codec->codec_type = AVMEDIA_TYPE_AUDIO;

                }

                avs->remaining_audio_size = size - 4;

                size = avs_read_audio_packet(s, pkt);

                if (size != 0)

                    return size;

                break;

            default:

                avio_skip(s->pb, size - 4);

            }

        }

    }

}


void HELPER(simcall)(CPUXtensaState *env)

{

    uint32_t *regs = env->regs;

    switch (regs[2]) {

    case TARGET_SYS_exit:

        qemu_log("exit(%d) simcall\n", regs[3]);

        exit(regs[3]);

        break;

    case TARGET_SYS_read:

    case TARGET_SYS_write:

        {

            bool is_write = regs[2] == TARGET_SYS_write;

            uint32_t fd = regs[3];

            uint32_t vaddr = regs[4];

            uint32_t len = regs[5];

            while (len > 0) {

                target_phys_addr_t paddr =

                    cpu_get_phys_page_debug(env, vaddr);

                uint32_t page_left =

                    TARGET_PAGE_SIZE - (vaddr & (TARGET_PAGE_SIZE - 1));

                uint32_t io_sz = page_left < len ? page_left : len;

                target_phys_addr_t sz = io_sz;

                void *buf = cpu_physical_memory_map(paddr, &sz, is_write);

                if (buf) {

                    vaddr += io_sz;

                    len -= io_sz;

                    regs[2] = is_write ?

                        write(fd, buf, io_sz) :

                        read(fd, buf, io_sz);

                    regs[3] = errno;

                    cpu_physical_memory_unmap(buf, sz, is_write, sz);

                    if (regs[2] == -1) {

                        break;

                    }

                } else {

                    regs[3] = EINVAL;

                    break;

                }

            }

        }

        break;

    case TARGET_SYS_open:

        {

            char name[1024];

            int rc;

            int i;

            for (i = 0; i < ARRAY_SIZE(name); ++i) {

                rc = cpu_memory_rw_debug(

                        env, regs[3] + i, (uint8_t *)name + i, 1, 0);

                if (rc != 0 || name[i] == 0) {

                    break;

                }

            }

            if (rc == 0 && i < ARRAY_SIZE(name)) {

                regs[2] = open(name, regs[4], regs[5]);

                regs[3] = errno;

            } else {

                regs[3] = EINVAL;

            }

        }

        break;

    case TARGET_SYS_close:

        if (regs[3] < 3) {

            regs[2] = regs[3] = 0;

        } else {

            regs[2] = close(regs[3]);

            regs[3] = errno;

        }

        break;

    case TARGET_SYS_lseek:

        regs[2] = lseek(regs[3], (off_t)(int32_t)regs[4], regs[5]);

        regs[3] = errno;

        break;

    case TARGET_SYS_select_one:

        {

            uint32_t fd = regs[3];

            uint32_t rq = regs[4];

            uint32_t target_tv = regs[5];

            uint32_t target_tvv[2];

            struct timeval tv = {0};

            fd_set fdset;

            FD_ZERO(&fdset);

            FD_SET(fd, &fdset);

            if (target_tv) {

                cpu_memory_rw_debug(env, target_tv,

                        (uint8_t *)target_tvv, sizeof(target_tvv), 0);

                tv.tv_sec = (int32_t)tswap32(target_tvv[0]);

                tv.tv_usec = (int32_t)tswap32(target_tvv[1]);

            }

            regs[2] = select(fd + 1,

                    rq == SELECT_ONE_READ   ? &fdset : NULL,

                    rq == SELECT_ONE_WRITE  ? &fdset : NULL,

                    rq == SELECT_ONE_EXCEPT ? &fdset : NULL,

                    target_tv ? &tv : NULL);

            regs[3] = errno;

        }

        break;

    case TARGET_SYS_argc:

        regs[2] = 1;

        regs[3] = 0;

        break;

    case TARGET_SYS_argv_sz:

        regs[2] = 128;

        regs[3] = 0;

        break;

    case TARGET_SYS_argv:

        {

            struct Argv {

                uint32_t argptr[2];

                char text[120];

            } argv = {

                {0, 0},

                "test"

            };

            argv.argptr[0] = tswap32(regs[3] + offsetof(struct Argv, text));

            cpu_memory_rw_debug(

                    env, regs[3], (uint8_t *)&argv, sizeof(argv), 1);

        }

        break;

    case TARGET_SYS_memset:

        {

            uint32_t base = regs[3];

            uint32_t sz = regs[5];

            while (sz) {

                target_phys_addr_t len = sz;

                void *buf = cpu_physical_memory_map(base, &len, 1);

                if (buf && len) {

                    memset(buf, regs[4], len);

                    cpu_physical_memory_unmap(buf, len, 1, len);

                } else {

                    len = 1;

                }

                base += len;

                sz -= len;

            }

            regs[2] = regs[3];

            regs[3] = 0;

        }

        break;

    default:

        qemu_log("%s(%d): not implemented\n", __func__, regs[2]);

        break;

    }

}


static void decode_lpc(int32_t *coeffs, int mode, int length)

{

    int i;

    if (length < 2)

        return;

    if (mode == 1) {

        unsigned a1 = *coeffs++;

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

            *coeffs   += a1;

            coeffs[1] += *coeffs;

            a1         = coeffs[1];

            coeffs    += 2;

        }

        if (length - 1 & 1)

            *coeffs += a1;

    } else if (mode == 2) {

        unsigned a1    = coeffs[1];

        unsigned a2    = a1 + *coeffs;

        coeffs[1] = a2;

        if (length > 2) {

            coeffs += 2;

            for (i = 0; i < length - 2 >> 1; i++) {

                unsigned a3    = *coeffs + a1;

                unsigned a4    = a3 + a2;

                *coeffs   = a4;

                a1        = coeffs[1] + a3;

                a2        = a1 + a4;

                coeffs[1] = a2;

                coeffs   += 2;

            }

            if (length & 1)

                *coeffs += a1 + a2;

        }

    } else if (mode == 3) {

        unsigned a1    = coeffs[1];

        unsigned a2    = a1 + *coeffs;

        coeffs[1] = a2;

        if (length > 2) {

            unsigned a3  = coeffs[2];

            unsigned a4  = a3 + a1;

            unsigned a5  = a4 + a2;

            coeffs[2] = a5;

            coeffs += 3;

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

                a3     += *coeffs;

                a4     += a3;

                a5     += a4;

                *coeffs = a5;

                coeffs++;

            }

        }

    }

}


static void term_init(void)

{

#ifndef __MINGW32__

    struct termios tty;

    tcgetattr (0, &tty);

    oldtty = tty;

    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP

                          |INLCR|IGNCR|ICRNL|IXON);

    tty.c_oflag |= OPOST;

    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);

    tty.c_cflag &= ~(CSIZE|PARENB);

    tty.c_cflag |= CS8;

    tty.c_cc[VMIN] = 1;

    tty.c_cc[VTIME] = 0;

    tcsetattr (0, TCSANOW, &tty);

    signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */

#endif

    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */

    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */

    /*

    register a function to be called at normal program termination

    */

    atexit(term_exit);

#ifdef CONFIG_BEOS_NETSERVER

    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);

#endif

}


static int xan_decode_frame_type0(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    uint8_t *ybuf, *prev_buf, *src = s->scratch_buffer;

    unsigned  chroma_off, corr_off;

    int cur, last;

    int i, j;

    int ret;

    chroma_off = bytestream2_get_le32(&s->gb);

    corr_off   = bytestream2_get_le32(&s->gb);

    if ((ret = xan_decode_chroma(avctx, chroma_off)) != 0)

        return ret;

    if (corr_off >= bytestream2_size(&s->gb)) {

        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid correction block position\n");

        corr_off = 0;

    }

    bytestream2_seek(&s->gb, 12, SEEK_SET);

    ret = xan_unpack_luma(s, src, s->buffer_size >> 1);

    if (ret) {

        av_log(avctx, AV_LOG_ERROR, "Luma decoding failed\n");

        return ret;

    }

    ybuf = s->y_buffer;

    last = *src++;

    ybuf[0] = last << 1;

    for (j = 1; j < avctx->width - 1; j += 2) {

        cur = (last + *src++) & 0x1F;

        ybuf[j]   = last + cur;

        ybuf[j+1] = cur << 1;

        last = cur;

    }

    ybuf[j]  = last << 1;

    prev_buf = ybuf;

    ybuf += avctx->width;

    for (i = 1; i < avctx->height; i++) {

        last = ((prev_buf[0] >> 1) + *src++) & 0x1F;

        ybuf[0] = last << 1;

        for (j = 1; j < avctx->width - 1; j += 2) {

            cur = ((prev_buf[j + 1] >> 1) + *src++) & 0x1F;

            ybuf[j]   = last + cur;

            ybuf[j+1] = cur << 1;

            last = cur;

        }

        if(j < avctx->width)

            ybuf[j] = last << 1;

        prev_buf = ybuf;

        ybuf += avctx->width;

    }

    if (corr_off) {

        int dec_size;

        bytestream2_seek(&s->gb, 8 + corr_off, SEEK_SET);

        dec_size = xan_unpack(s, s->scratch_buffer, s->buffer_size);

        if (dec_size < 0)

            dec_size = 0;

        else

            dec_size = FFMIN(dec_size, s->buffer_size/2 - 1);

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

            s->y_buffer[i*2+1] = (s->y_buffer[i*2+1] + (s->scratch_buffer[i] << 1)) & 0x3F;

    }

    src  = s->y_buffer;

    ybuf = s->pic.data[0];

    for (j = 0; j < avctx->height; j++) {

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

            ybuf[i] = (src[i] << 2) | (src[i] >> 3);

        src  += avctx->width;

        ybuf += s->pic.linesize[0];

    }

    return 0;

}


static int bethsoftvid_decode_frame(AVCodecContext *avctx,

                              void *data, int *data_size,

                              AVPacket *avpkt)

{

    BethsoftvidContext * vid = avctx->priv_data;

    char block_type;

    uint8_t * dst;

    uint8_t * frame_end;

    int remaining = avctx->width;          // number of bytes remaining on a line

    const int wrap_to_next_line = vid->frame.linesize[0] - avctx->width;

    int code;

    int yoffset;

    if (avctx->reget_buffer(avctx, &vid->frame)) {

        av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return -1;

    }

    bytestream2_init(&vid->g, avpkt->data, avpkt->size);

    dst = vid->frame.data[0];

    frame_end = vid->frame.data[0] + vid->frame.linesize[0] * avctx->height;

    switch(block_type = bytestream2_get_byte(&vid->g)){

        case PALETTE_BLOCK: {

            int ret;

            *data_size = 0;

            if ((ret = set_palette(vid)) < 0) {

                av_log(avctx, AV_LOG_ERROR, "error reading palette\n");

                return ret;

            }

            return bytestream2_tell(&vid->g);

        }

        case VIDEO_YOFF_P_FRAME:

            yoffset = bytestream2_get_le16(&vid->g);

            if(yoffset >= avctx->height)

                return -1;

            dst += vid->frame.linesize[0] * yoffset;

    }

    // main code

    while((code = bytestream2_get_byte(&vid->g))){

        int length = code & 0x7f;

        // copy any bytes starting at the current position, and ending at the frame width

        while(length > remaining){

            if(code < 0x80)

                bytestream2_get_buffer(&vid->g, dst, remaining);

            else if(block_type == VIDEO_I_FRAME)

                memset(dst, bytestream2_peek_byte(&vid->g), remaining);

            length -= remaining;      // decrement the number of bytes to be copied

            dst += remaining + wrap_to_next_line;    // skip over extra bytes at end of frame

            remaining = avctx->width;

            if(dst == frame_end)

                goto end;

        }

        // copy any remaining bytes after / if line overflows

        if(code < 0x80)

            bytestream2_get_buffer(&vid->g, dst, length);

        else if(block_type == VIDEO_I_FRAME)

            memset(dst, bytestream2_get_byte(&vid->g), length);

        remaining -= length;

        dst += length;

    }

    end:

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = vid->frame;

    return avpkt->size;

}


static void decode_delta_d(uint8_t *dst,

                           const uint8_t *buf, const uint8_t *buf_end,

                           int w, int flag, int bpp, int dst_size)

{

    int planepitch = FFALIGN(w, 16) >> 3;

    int pitch = planepitch * bpp;

    int planepitch_byte = (w + 7) / 8;

    unsigned entries, ofssrc;

    GetByteContext gb, ptrs;

    PutByteContext pb;

    int k;

    if (buf_end - buf <= 4 * bpp)

        return;

    bytestream2_init_writer(&pb, dst, dst_size);

    bytestream2_init(&ptrs, buf, bpp * 4);

    for (k = 0; k < bpp; k++) {

        ofssrc = bytestream2_get_be32(&ptrs);

        if (!ofssrc)

            continue;

        if (ofssrc >= buf_end - buf)

            continue;

        bytestream2_init(&gb, buf + ofssrc, buf_end - (buf + ofssrc));

        entries = bytestream2_get_be32(&gb);

        while (entries) {

            int32_t opcode  = bytestream2_get_be32(&gb);

            unsigned offset = bytestream2_get_be32(&gb);

            bytestream2_seek_p(&pb, (offset / planepitch_byte) * pitch + (offset % planepitch_byte) + k * planepitch, SEEK_SET);

            if (opcode >= 0) {

                uint32_t x = bytestream2_get_be32(&gb);

                while (opcode && bytestream2_get_bytes_left_p(&pb) > 0) {

                    bytestream2_put_be32(&pb, x);

                    bytestream2_skip_p(&pb, pitch - 4);

                    opcode--;

                }

            } else {

                opcode = -opcode;

                while (opcode && bytestream2_get_bytes_left(&gb) > 0) {

                    bytestream2_put_be32(&pb, bytestream2_get_be32(&gb));

                    bytestream2_skip_p(&pb, pitch - 4);

                    opcode--;

                }

            }

            entries--;

        }

    }

}


static void avc_luma_hv_qrt_and_aver_dst_8x8_msa(const uint8_t *src_x,

                                                 const uint8_t *src_y,

                                                 int32_t src_stride,

                                                 uint8_t *dst,

                                                 int32_t dst_stride)

{

    uint32_t loop_cnt;

    v16i8 src_hz0, src_hz1, src_hz2, src_hz3;

    v16u8 dst0, dst1, dst2, dst3;

    v16i8 src_vt0, src_vt1, src_vt2, src_vt3;

    v16i8 src_vt4, src_vt5, src_vt6, src_vt7, src_vt8;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, hz_out2, hz_out3;

    v8i16 vert_out0, vert_out1, vert_out2, vert_out3;

    v8i16 out0, out1, out2, out3;

    LD_SB3(&luma_mask_arr[0], 16, mask0, mask1, mask2);

    LD_SB5(src_y, src_stride, src_vt0, src_vt1, src_vt2, src_vt3, src_vt4);

    src_y += (5 * src_stride);

    src_vt0 = (v16i8) __msa_insve_d((v2i64) src_vt0, 1, (v2i64) src_vt1);

    src_vt1 = (v16i8) __msa_insve_d((v2i64) src_vt1, 1, (v2i64) src_vt2);

    src_vt2 = (v16i8) __msa_insve_d((v2i64) src_vt2, 1, (v2i64) src_vt3);

    src_vt3 = (v16i8) __msa_insve_d((v2i64) src_vt3, 1, (v2i64) src_vt4);

    XORI_B4_128_SB(src_vt0, src_vt1, src_vt2, src_vt3);

    for (loop_cnt = 2; loop_cnt--;) {

        LD_SB4(src_x, src_stride, src_hz0, src_hz1, src_hz2, src_hz3);

        XORI_B4_128_SB(src_hz0, src_hz1, src_hz2, src_hz3);

        src_x += (4 * src_stride);

        LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3);

        hz_out0 = AVC_HORZ_FILTER_SH(src_hz0, mask0, mask1, mask2);

        hz_out1 = AVC_HORZ_FILTER_SH(src_hz1, mask0, mask1, mask2);

        hz_out2 = AVC_HORZ_FILTER_SH(src_hz2, mask0, mask1, mask2);

        hz_out3 = AVC_HORZ_FILTER_SH(src_hz3, mask0, mask1, mask2);

        SRARI_H4_SH(hz_out0, hz_out1, hz_out2, hz_out3, 5);

        SAT_SH4_SH(hz_out0, hz_out1, hz_out2, hz_out3, 7);

        LD_SB4(src_y, src_stride, src_vt5, src_vt6, src_vt7, src_vt8);

        src_y += (4 * src_stride);

        src_vt4 = (v16i8) __msa_insve_d((v2i64) src_vt4, 1, (v2i64) src_vt5);

        src_vt5 = (v16i8) __msa_insve_d((v2i64) src_vt5, 1, (v2i64) src_vt6);

        src_vt6 = (v16i8) __msa_insve_d((v2i64) src_vt6, 1, (v2i64) src_vt7);

        src_vt7 = (v16i8) __msa_insve_d((v2i64) src_vt7, 1, (v2i64) src_vt8);

        XORI_B4_128_SB(src_vt4, src_vt5, src_vt6, src_vt7);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src_vt0, src_vt1, src_vt2, src_vt3,

                                        src_vt4, src_vt5, vert_out0, vert_out1);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src_vt2, src_vt3, src_vt4, src_vt5,

                                        src_vt6, src_vt7, vert_out2, vert_out3);

        SRARI_H4_SH(vert_out0, vert_out1, vert_out2, vert_out3, 5);

        SAT_SH4_SH(vert_out0, vert_out1, vert_out2, vert_out3, 7);

        out0 = __msa_srari_h((hz_out0 + vert_out0), 1);

        out1 = __msa_srari_h((hz_out1 + vert_out1), 1);

        out2 = __msa_srari_h((hz_out2 + vert_out2), 1);

        out3 = __msa_srari_h((hz_out3 + vert_out3), 1);

        SAT_SH4_SH(out0, out1, out2, out3, 7);

        ILVR_D2_UB(dst1, dst0, dst3, dst2, dst0, dst1);

        CONVERT_UB_AVG_ST8x4_UB(out0, out1, out2, out3, dst0, dst1,

                                dst, dst_stride);

        dst += (4 * dst_stride);

        src_vt0 = src_vt4;

        src_vt1 = src_vt5;

        src_vt2 = src_vt6;

        src_vt3 = src_vt7;

        src_vt4 = src_vt8;

    }

}


static void hScale8To19_c(SwsContext *c, int16_t *_dst, int dstW, const uint8_t *src,

                          const int16_t *filter, const int16_t *filterPos,

                          int filterSize)

{

    int i;

    int32_t *dst = (int32_t *) _dst;

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

        int j;

        int srcPos= filterPos[i];

        int val=0;

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

            val += ((int)src[srcPos + j])*filter[filterSize*i + j];

        }

        //filter += hFilterSize;

        dst[i] = FFMIN(val>>3, (1<<19)-1); // the cubic equation does overflow ...

        //dst[i] = val>>7;

    }

}


static void cpu_notify_map_clients_locked(void)

{

    MapClient *client;

    while (!QLIST_EMPTY(&map_client_list)) {

        client = QLIST_FIRST(&map_client_list);

        client->callback(client->opaque);

        cpu_unregister_map_client(client);

    }

}


int show_bsfs(void *optctx, const char *opt, const char *arg)

{

    AVBitStreamFilter *bsf = NULL;

    printf("Bitstream filters:\n");

    while ((bsf = av_bitstream_filter_next(bsf)))

        printf("%s\n", bsf->name);

    printf("\n");

    return 0;

}