static NetSocketState *net_socket_fd_init_stream(VLANState *vlan,

                                                 const char *model,

                                                 const char *name,

                                                 int fd, int is_connected)

{

    NetSocketState *s;

    s = qemu_mallocz(sizeof(NetSocketState));

    s->fd = fd;

    s->vc = qemu_new_vlan_client(vlan, model, name,

                                 net_socket_receive, NULL, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str),

             "socket: fd=%d", fd);

    if (is_connected) {

        net_socket_connect(s);

    } else {

        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);

    }

    return s;

}


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

{

    VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(dev);

    SysBusDevice *sbdev = SYS_BUS_DEVICE(dev);

    VFIODevice *vbasedev = &vdev->vbasedev;

    VFIOINTp *intp;

    int i, ret;

    vbasedev->type = VFIO_DEVICE_TYPE_PLATFORM;

    vbasedev->ops = &vfio_platform_ops;

    trace_vfio_platform_realize(vbasedev->name, vdev->compat);

    ret = vfio_base_device_init(vbasedev);

    if (ret) {

        error_setg(errp, "vfio: vfio_base_device_init failed for %s",

                   vbasedev->name);

        return;

    }

    for (i = 0; i < vbasedev->num_regions; i++) {

        vfio_map_region(vdev, i);

        sysbus_init_mmio(sbdev, &vdev->regions[i]->mem);

    }

    QLIST_FOREACH(intp, &vdev->intp_list, next) {

        vfio_start_eventfd_injection(intp);

    }

}


void v_resample16_altivec(uint8_t *dst, int dst_width, const uint8_t *src,

                          int wrap, int16_t *filter)

{

    int sum, i;

    const uint8_t *s;

    vector unsigned char *tv, tmp, dstv, zero;

    vec_ss_t srchv[4], srclv[4], fv[4];

    vector signed short zeros, sumhv, sumlv;

    s = src;

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

    {

        /*

           The vec_madds later on does an implicit >>15 on the result.

           Since FILTER_BITS is 8, and we have 15 bits of magnitude in

           a signed short, we have just enough bits to pre-shift our

           filter constants <<7 to compensate for vec_madds.

        */

        fv[i].s[0] = filter[i] << (15-FILTER_BITS);

        fv[i].v = vec_splat(fv[i].v, 0);

    }

    zero = vec_splat_u8(0);

    zeros = vec_splat_s16(0);

    /*

       When we're resampling, we'd ideally like both our input buffers,

       and output buffers to be 16-byte aligned, so we can do both aligned

       reads and writes. Sadly we can't always have this at the moment, so

       we opt for aligned writes, as unaligned writes have a huge overhead.

       To do this, do enough scalar resamples to get dst 16-byte aligned.

    */

    i = (-(int)dst) & 0xf;

    while(i>0) {

        sum = s[0 * wrap] * filter[0] +

        s[1 * wrap] * filter[1] +

        s[2 * wrap] * filter[2] +

        s[3 * wrap] * filter[3];

        sum = sum >> FILTER_BITS;

        if (sum<0) sum = 0; else if (sum>255) sum=255;

        dst[0] = sum;

        dst++;

        s++;

        dst_width--;

        i--;

    }

    /* Do our altivec resampling on 16 pixels at once. */

    while(dst_width>=16) {

        /*

           Read 16 (potentially unaligned) bytes from each of

           4 lines into 4 vectors, and split them into shorts.

           Interleave the multipy/accumulate for the resample

           filter with the loads to hide the 3 cycle latency

           the vec_madds have.

        */

        tv = (vector unsigned char *) &s[0 * wrap];

        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[i * wrap]));

        srchv[0].v = (vector signed short) vec_mergeh(zero, tmp);

        srclv[0].v = (vector signed short) vec_mergel(zero, tmp);

        sumhv = vec_madds(srchv[0].v, fv[0].v, zeros);

        sumlv = vec_madds(srclv[0].v, fv[0].v, zeros);

        tv = (vector unsigned char *) &s[1 * wrap];

        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[1 * wrap]));

        srchv[1].v = (vector signed short) vec_mergeh(zero, tmp);

        srclv[1].v = (vector signed short) vec_mergel(zero, tmp);

        sumhv = vec_madds(srchv[1].v, fv[1].v, sumhv);

        sumlv = vec_madds(srclv[1].v, fv[1].v, sumlv);

        tv = (vector unsigned char *) &s[2 * wrap];

        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[2 * wrap]));

        srchv[2].v = (vector signed short) vec_mergeh(zero, tmp);

        srclv[2].v = (vector signed short) vec_mergel(zero, tmp);

        sumhv = vec_madds(srchv[2].v, fv[2].v, sumhv);

        sumlv = vec_madds(srclv[2].v, fv[2].v, sumlv);

        tv = (vector unsigned char *) &s[3 * wrap];

        tmp = vec_perm(tv[0], tv[1], vec_lvsl(0, &s[3 * wrap]));

        srchv[3].v = (vector signed short) vec_mergeh(zero, tmp);

        srclv[3].v = (vector signed short) vec_mergel(zero, tmp);

        sumhv = vec_madds(srchv[3].v, fv[3].v, sumhv);

        sumlv = vec_madds(srclv[3].v, fv[3].v, sumlv);

        /*

           Pack the results into our destination vector,

           and do an aligned write of that back to memory.

        */

        dstv = vec_packsu(sumhv, sumlv) ;

        vec_st(dstv, 0, (vector unsigned char *) dst);

        dst+=16;

        s+=16;

        dst_width-=16;

    }

    /*

       If there are any leftover pixels, resample them

       with the slow scalar method.

    */

    while(dst_width>0) {

        sum = s[0 * wrap] * filter[0] +

        s[1 * wrap] * filter[1] +

        s[2 * wrap] * filter[2] +

        s[3 * wrap] * filter[3];

        sum = sum >> FILTER_BITS;

        if (sum<0) sum = 0; else if (sum>255) sum=255;

        dst[0] = sum;

        dst++;

        s++;

        dst_width--;

    }

}


static void kmvc_decode_intra_8x8(KmvcContext * ctx, const uint8_t * src, int w, int h)

{

    BitBuf bb;

    int res, val;

    int i, j;

    int bx, by;

    int l0x, l1x, l0y, l1y;

    int mx, my;

    kmvc_init_getbits(bb, src);

    for (by = 0; by < h; by += 8)

        for (bx = 0; bx < w; bx += 8) {

            kmvc_getbit(bb, src, res);

            if (!res) {         // fill whole 8x8 block

                val = *src++;

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

                    BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) = val;

            } else {            // handle four 4x4 subblocks

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

                    l0x = bx + (i & 1) * 4;

                    l0y = by + (i & 2) * 2;

                    kmvc_getbit(bb, src, res);

                    if (!res) {

                        kmvc_getbit(bb, src, res);

                        if (!res) {     // fill whole 4x4 block

                            val = *src++;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) = val;

                        } else {        // copy block from already decoded place

                            val = *src++;

                            mx = val & 0xF;

                            my = val >> 4;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) =

                                    BLK(ctx->cur, l0x + (j & 3) - mx, l0y + (j >> 2) - my);

                        }

                    } else {    // descend to 2x2 sub-sub-blocks

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

                            l1x = l0x + (j & 1) * 2;

                            l1y = l0y + (j & 2);

                            kmvc_getbit(bb, src, res);

                            if (!res) {

                                kmvc_getbit(bb, src, res);

                                if (!res) {     // fill whole 2x2 block

                                    val = *src++;

                                    BLK(ctx->cur, l1x, l1y) = val;

                                    BLK(ctx->cur, l1x + 1, l1y) = val;

                                    BLK(ctx->cur, l1x, l1y + 1) = val;

                                    BLK(ctx->cur, l1x + 1, l1y + 1) = val;

                                } else {        // copy block from already decoded place

                                    val = *src++;

                                    mx = val & 0xF;

                                    my = val >> 4;

                                    BLK(ctx->cur, l1x, l1y) = BLK(ctx->cur, l1x - mx, l1y - my);

                                    BLK(ctx->cur, l1x + 1, l1y) =

                                        BLK(ctx->cur, l1x + 1 - mx, l1y - my);

                                    BLK(ctx->cur, l1x, l1y + 1) =

                                        BLK(ctx->cur, l1x - mx, l1y + 1 - my);

                                    BLK(ctx->cur, l1x + 1, l1y + 1) =

                                        BLK(ctx->cur, l1x + 1 - mx, l1y + 1 - my);

                                }

                            } else {    // read values for block

                                BLK(ctx->cur, l1x, l1y) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y) = *src++;

                                BLK(ctx->cur, l1x, l1y + 1) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y + 1) = *src++;

                            }

                        }

                    }

                }

            }

        }

}


static void handle_windowevent(SDL_Event *ev)
{
    struct sdl2_console *scon = get_scon_from_window(ev->window.windowID);
    switch (ev->window.event) {
    case SDL_WINDOWEVENT_RESIZED:
        {
            QemuUIInfo info;
            memset(&info, 0, sizeof(info));
            info.width = ev->window.data1;
            info.height = ev->window.data2;
            dpy_set_ui_info(scon->dcl.con, &info);
        sdl2_redraw(scon);
        break;
    case SDL_WINDOWEVENT_EXPOSED:
        sdl2_redraw(scon);
        break;
    case SDL_WINDOWEVENT_FOCUS_GAINED:
    case SDL_WINDOWEVENT_ENTER:
        if (!gui_grab && (qemu_input_is_absolute() || absolute_enabled)) {
            absolute_mouse_grab(scon);
        break;
    case SDL_WINDOWEVENT_FOCUS_LOST:
        if (gui_grab && !gui_fullscreen) {
            sdl_grab_end(scon);
        break;
    case SDL_WINDOWEVENT_RESTORED:
        update_displaychangelistener(&scon->dcl, GUI_REFRESH_INTERVAL_DEFAULT);
        break;
    case SDL_WINDOWEVENT_MINIMIZED:
        update_displaychangelistener(&scon->dcl, 500);
        break;
    case SDL_WINDOWEVENT_CLOSE:
        if (!no_quit) {
            no_shutdown = 0;
            qemu_system_shutdown_request();
        break;
    case SDL_WINDOWEVENT_SHOWN:
        if (scon->hidden) {
            SDL_HideWindow(scon->real_window);
        break;
    case SDL_WINDOWEVENT_HIDDEN:
        if (!scon->hidden) {
            SDL_ShowWindow(scon->real_window);
        break;


static int uhci_handle_td(UHCIState *s, UHCIQueue *q,

                          UHCI_TD *td, uint32_t td_addr, uint32_t *int_mask)

{

    UHCIAsync *async;

    int len = 0, max_len;

    bool spd;

    bool queuing = (q != NULL);

    uint8_t pid = td->token & 0xff;

    /* Is active ? */

    if (!(td->ctrl & TD_CTRL_ACTIVE)) {

        /*

         * ehci11d spec page 22: "Even if the Active bit in the TD is already

         * cleared when the TD is fetched ... an IOC interrupt is generated"

         */

        if (td->ctrl & TD_CTRL_IOC) {

                *int_mask |= 0x01;

        }

        return TD_RESULT_NEXT_QH;

    }

    async = uhci_async_find_td(s, td_addr, td);

    if (async) {

        /* Already submitted */

        async->queue->valid = 32;

        if (!async->done)

            return TD_RESULT_ASYNC_CONT;

        if (queuing) {

            /* we are busy filling the queue, we are not prepared

               to consume completed packages then, just leave them

               in async state */

            return TD_RESULT_ASYNC_CONT;

        }

        uhci_async_unlink(async);

        goto done;

    }

    /* Allocate new packet */

    if (q == NULL) {

        USBDevice *dev = uhci_find_device(s, (td->token >> 8) & 0x7f);

        USBEndpoint *ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);

        q = uhci_queue_get(s, td, ep);

    }

    async = uhci_async_alloc(q, td_addr);

    /* valid needs to be large enough to handle 10 frame delay

     * for initial isochronous requests

     */

    async->queue->valid = 32;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    spd = (pid == USB_TOKEN_IN && (td->ctrl & TD_CTRL_SPD) != 0);

    usb_packet_setup(&async->packet, pid, q->ep, td_addr, spd,

                     (td->ctrl & TD_CTRL_IOC) != 0);

    qemu_sglist_add(&async->sgl, td->buffer, max_len);

    usb_packet_map(&async->packet, &async->sgl);

    switch(pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

        len = usb_handle_packet(q->ep->dev, &async->packet);

        if (len >= 0)

            len = max_len;

        break;

    case USB_TOKEN_IN:

        len = usb_handle_packet(q->ep->dev, &async->packet);

        break;

    default:

        /* invalid pid : frame interrupted */

        usb_packet_unmap(&async->packet, &async->sgl);

        uhci_async_free(async);

        s->status |= UHCI_STS_HCPERR;

        uhci_update_irq(s);

        return TD_RESULT_STOP_FRAME;

    }

    if (len == USB_RET_ASYNC) {

        uhci_async_link(async);

        if (!queuing) {

            uhci_queue_fill(q, td);

        }

        return TD_RESULT_ASYNC_START;

    }

    async->packet.result = len;

done:

    len = uhci_complete_td(s, td, async, int_mask);

    usb_packet_unmap(&async->packet, &async->sgl);

    uhci_async_free(async);

    return len;

}


int qtest_init(void)

{

    CharDriverState *chr;

    g_assert(qtest_chrdev != NULL);

    configure_icount("0");

    chr = qemu_chr_new("qtest", qtest_chrdev, NULL);

    qemu_chr_add_handlers(chr, qtest_can_read, qtest_read, qtest_event, chr);

    qemu_chr_fe_set_echo(chr, true);

    inbuf = g_string_new("");

    if (qtest_log) {

        if (strcmp(qtest_log, "none") != 0) {

            qtest_log_fp = fopen(qtest_log, "w+");

        }

    } else {

        qtest_log_fp = stderr;

    }

    qtest_chr = chr;

    return 0;

}


static av_cold int smvjpeg_decode_end(AVCodecContext *avctx)

{

    SMVJpegDecodeContext *s = avctx->priv_data;

    MJpegDecodeContext *jpg = &s->jpg;

    int ret;

    jpg->picture_ptr = NULL;

    av_frame_free(&s->picture[0]);

    av_frame_free(&s->picture[1]);

    ret = avcodec_close(s->avctx);

    av_freep(&s->avctx);

    return ret;

}


static void check_native_list(QObject *qobj,

                              UserDefNativeListUnionKind kind)

{

    QDict *qdict;

    QList *qlist;

    int i;

    qdict = qobject_to_qdict(qobj);

    g_assert(qdict);

    g_assert(qdict_haskey(qdict, "data"));

    qlist = qlist_copy(qobject_to_qlist(qdict_get(qdict, "data")));

    switch (kind) {

    case USER_DEF_NATIVE_LIST_UNION_KIND_S8:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S16:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S32:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S64:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U8:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U16:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U32:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U64:

        /*

         * All integer elements in JSON arrays get stored into QNums

         * when we convert to QObjects, so we can check them all in

         * the same fashion, so simply fall through here.

         */

    case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER:

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

            QObject *tmp;

            QNum *qvalue;

            int64_t val;

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qnum(tmp);

            g_assert(qnum_get_try_int(qvalue, &val));

            g_assert_cmpint(val, ==, i);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN:

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

            QObject *tmp;

            QBool *qvalue;

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qbool(tmp);

            g_assert_cmpint(qbool_get_bool(qvalue), ==, i % 3 == 0);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_STRING:

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

            QObject *tmp;

            QString *qvalue;

            gchar str[8];

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qstring(tmp);

            sprintf(str, "%d", i);

            g_assert_cmpstr(qstring_get_str(qvalue), ==, str);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER:

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

            QObject *tmp;

            QNum *qvalue;

            GString *double_expected = g_string_new("");

            GString *double_actual = g_string_new("");

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qnum(tmp);

            g_string_printf(double_expected, "%.6f", (double)i / 3);

            g_string_printf(double_actual, "%.6f", qnum_get_double(qvalue));

            g_assert_cmpstr(double_actual->str, ==, double_expected->str);

            qobject_decref(qlist_pop(qlist));

            g_string_free(double_expected, true);

            g_string_free(double_actual, true);

        }

        break;

    default:

        g_assert_not_reached();

    }

    QDECREF(qlist);

}


int net_init_vde(QemuOpts *opts, const char *name, VLANState *vlan)

{

    const char *sock;

    const char *group;

    int port, mode;

    sock  = qemu_opt_get(opts, "sock");

    group = qemu_opt_get(opts, "group");

    port = qemu_opt_get_number(opts, "port", 0);

    mode = qemu_opt_get_number(opts, "mode", 0700);

    if (net_vde_init(vlan, "vde", name, sock, port, group, mode) == -1) {

        return -1;

    }

    return 0;

}


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

{

    stellaris_enet_state *s = STELLARIS_ENET(dev);

    unregister_savevm(DEVICE(s), "stellaris_enet", s);

    memory_region_destroy(&s->mmio);

}


static bool memory_region_dispatch_read(MemoryRegion *mr,

                                        hwaddr addr,

                                        uint64_t *pval,

                                        unsigned size)

{

    if (!memory_region_access_valid(mr, addr, size, false)) {

        *pval = unassigned_mem_read(mr, addr, size);

        return true;

    }

    *pval = memory_region_dispatch_read1(mr, addr, size);

    adjust_endianness(mr, pval, size);

    return false;

}


static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){

    int i;

    MERGE(dct_count[0]); //note, the other dct vars are not part of the context

    MERGE(dct_count[1]);

    MERGE(mv_bits);

    MERGE(i_tex_bits);

    MERGE(p_tex_bits);

    MERGE(i_count);

    MERGE(f_count);

    MERGE(b_count);

    MERGE(skip_count);

    MERGE(misc_bits);

    MERGE(er.error_count);

    MERGE(padding_bug_score);

    MERGE(current_picture.f->error[0]);

    MERGE(current_picture.f->error[1]);

    MERGE(current_picture.f->error[2]);

    if(dst->avctx->noise_reduction){

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

            MERGE(dct_error_sum[0][i]);

            MERGE(dct_error_sum[1][i]);

        }

    }

    assert(put_bits_count(&src->pb) % 8 ==0);

    assert(put_bits_count(&dst->pb) % 8 ==0);

    avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));

    flush_put_bits(&dst->pb);

}


int ff_h264_decode_seq_parameter_set(H264Context *h)

{

    int profile_idc, level_idc, constraint_set_flags = 0;

    unsigned int sps_id;

    int i, log2_max_frame_num_minus4;

    SPS *sps;

    profile_idc           = get_bits(&h->gb, 8);

    constraint_set_flags |= get_bits1(&h->gb) << 0;   // constraint_set0_flag

    constraint_set_flags |= get_bits1(&h->gb) << 1;   // constraint_set1_flag

    constraint_set_flags |= get_bits1(&h->gb) << 2;   // constraint_set2_flag

    constraint_set_flags |= get_bits1(&h->gb) << 3;   // constraint_set3_flag

    constraint_set_flags |= get_bits1(&h->gb) << 4;   // constraint_set4_flag

    constraint_set_flags |= get_bits1(&h->gb) << 5;   // constraint_set5_flag

    skip_bits(&h->gb, 2);                             // reserved_zero_2bits

    level_idc = get_bits(&h->gb, 8);

    sps_id    = get_ue_golomb_31(&h->gb);

    if (sps_id >= MAX_SPS_COUNT) {

        av_log(h->avctx, AV_LOG_ERROR, "sps_id %u out of range\n", sps_id);

        return AVERROR_INVALIDDATA;

    }

    sps = av_mallocz(sizeof(SPS));

    if (!sps)

        return AVERROR(ENOMEM);

    sps->sps_id               = sps_id;

    sps->time_offset_length   = 24;

    sps->profile_idc          = profile_idc;

    sps->constraint_set_flags = constraint_set_flags;

    sps->level_idc            = level_idc;

    memset(sps->scaling_matrix4, 16, sizeof(sps->scaling_matrix4));

    memset(sps->scaling_matrix8, 16, sizeof(sps->scaling_matrix8));

    sps->scaling_matrix_present = 0;

    if (sps->profile_idc == 100 ||  // High profile

        sps->profile_idc == 110 ||  // High10 profile

        sps->profile_idc == 122 ||  // High422 profile

        sps->profile_idc == 244 ||  // High444 Predictive profile

        sps->profile_idc ==  44 ||  // Cavlc444 profile

        sps->profile_idc ==  83 ||  // Scalable Constrained High profile (SVC)

        sps->profile_idc ==  86 ||  // Scalable High Intra profile (SVC)

        sps->profile_idc == 118 ||  // Stereo High profile (MVC)

        sps->profile_idc == 128 ||  // Multiview High profile (MVC)

        sps->profile_idc == 138 ||  // Multiview Depth High profile (MVCD)

        sps->profile_idc == 144) {  // old High444 profile

        sps->chroma_format_idc = get_ue_golomb_31(&h->gb);

        if (sps->chroma_format_idc > 3) {

            avpriv_request_sample(h->avctx, "chroma_format_idc %u",

                                  sps->chroma_format_idc);

            goto fail;

        } else if (sps->chroma_format_idc == 3) {

            sps->residual_color_transform_flag = get_bits1(&h->gb);

        }

        sps->bit_depth_luma   = get_ue_golomb(&h->gb) + 8;

        sps->bit_depth_chroma = get_ue_golomb(&h->gb) + 8;

        if (sps->bit_depth_chroma != sps->bit_depth_luma) {

            avpriv_request_sample(h->avctx,

                                  "Different chroma and luma bit depth");

            goto fail;

        }

        sps->transform_bypass = get_bits1(&h->gb);

        decode_scaling_matrices(h, sps, NULL, 1,

                                sps->scaling_matrix4, sps->scaling_matrix8);

    } else {

        sps->chroma_format_idc = 1;

        sps->bit_depth_luma    = 8;

        sps->bit_depth_chroma  = 8;

    }

    log2_max_frame_num_minus4 = get_ue_golomb(&h->gb);

    if (log2_max_frame_num_minus4 < MIN_LOG2_MAX_FRAME_NUM - 4 ||

        log2_max_frame_num_minus4 > MAX_LOG2_MAX_FRAME_NUM - 4) {

        av_log(h->avctx, AV_LOG_ERROR,

               "log2_max_frame_num_minus4 out of range (0-12): %d\n",

               log2_max_frame_num_minus4);

        goto fail;

    }

    sps->log2_max_frame_num = log2_max_frame_num_minus4 + 4;

    sps->poc_type = get_ue_golomb_31(&h->gb);

    if (sps->poc_type == 0) { // FIXME #define

        sps->log2_max_poc_lsb = get_ue_golomb(&h->gb) + 4;

    } else if (sps->poc_type == 1) { // FIXME #define

        sps->delta_pic_order_always_zero_flag = get_bits1(&h->gb);

        sps->offset_for_non_ref_pic           = get_se_golomb(&h->gb);

        sps->offset_for_top_to_bottom_field   = get_se_golomb(&h->gb);

        sps->poc_cycle_length                 = get_ue_golomb(&h->gb);

        if ((unsigned)sps->poc_cycle_length >=

            FF_ARRAY_ELEMS(sps->offset_for_ref_frame)) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "poc_cycle_length overflow %d\n", sps->poc_cycle_length);

            goto fail;

        }

        for (i = 0; i < sps->poc_cycle_length; i++)

            sps->offset_for_ref_frame[i] = get_se_golomb(&h->gb);

    } else if (sps->poc_type != 2) {

        av_log(h->avctx, AV_LOG_ERROR, "illegal POC type %d\n", sps->poc_type);

        goto fail;

    }

    sps->ref_frame_count = get_ue_golomb_31(&h->gb);

    if (sps->ref_frame_count > H264_MAX_PICTURE_COUNT - 2 ||

        sps->ref_frame_count >= 32U) {

        av_log(h->avctx, AV_LOG_ERROR,

               "too many reference frames %d\n", sps->ref_frame_count);

        goto fail;

    }

    sps->gaps_in_frame_num_allowed_flag = get_bits1(&h->gb);

    sps->mb_width                       = get_ue_golomb(&h->gb) + 1;

    sps->mb_height                      = get_ue_golomb(&h->gb) + 1;

    if ((unsigned)sps->mb_width  >= INT_MAX / 16 ||

        (unsigned)sps->mb_height >= INT_MAX / 16 ||

        av_image_check_size(16 * sps->mb_width,

                            16 * sps->mb_height, 0, h->avctx)) {

        av_log(h->avctx, AV_LOG_ERROR, "mb_width/height overflow\n");

        goto fail;

    }

    sps->frame_mbs_only_flag = get_bits1(&h->gb);

    if (!sps->frame_mbs_only_flag)

        sps->mb_aff = get_bits1(&h->gb);

    else

        sps->mb_aff = 0;

    sps->direct_8x8_inference_flag = get_bits1(&h->gb);

    if (!sps->frame_mbs_only_flag && !sps->direct_8x8_inference_flag) {

        av_log(h->avctx, AV_LOG_ERROR,

               "This stream was generated by a broken encoder, invalid 8x8 inference\n");

        goto fail;

    }

#ifndef ALLOW_INTERLACE

    if (sps->mb_aff)

        av_log(h->avctx, AV_LOG_ERROR,

               "MBAFF support not included; enable it at compile-time.\n");

#endif

    sps->crop = get_bits1(&h->gb);

    if (sps->crop) {

        unsigned int crop_left   = get_ue_golomb(&h->gb);

        unsigned int crop_right  = get_ue_golomb(&h->gb);

        unsigned int crop_top    = get_ue_golomb(&h->gb);

        unsigned int crop_bottom = get_ue_golomb(&h->gb);

        if (h->avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP) {

            av_log(h->avctx, AV_LOG_DEBUG, "discarding sps cropping, original "

                                           "values are l:%d r:%d t:%d b:%d\n",

                   crop_left, crop_right, crop_top, crop_bottom);

            sps->crop_left   =

            sps->crop_right  =

            sps->crop_top    =

            sps->crop_bottom = 0;

        } else {

            int vsub   = (sps->chroma_format_idc == 1) ? 1 : 0;

            int hsub   = (sps->chroma_format_idc == 1 ||

                          sps->chroma_format_idc == 2) ? 1 : 0;

            int step_x = 1 << hsub;

            int step_y = (2 - sps->frame_mbs_only_flag) << vsub;

            if (crop_left & (0x1F >> (sps->bit_depth_luma > 8)) &&

                !(h->avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {

                crop_left &= ~(0x1F >> (sps->bit_depth_luma > 8));

                av_log(h->avctx, AV_LOG_WARNING,

                       "Reducing left cropping to %d "

                       "chroma samples to preserve alignment.\n",

                       crop_left);

            }

            if (INT_MAX / step_x             <= crop_left               ||

                INT_MAX / step_x - crop_left <= crop_right              ||

                16 * sps->mb_width <= step_x * (crop_left + crop_right) ||

                INT_MAX / step_y             <= crop_top                ||

                INT_MAX / step_y - crop_top  <= crop_bottom             ||

                16 * sps->mb_height <= step_y * (crop_top + crop_bottom)) {

                av_log(h->avctx, AV_LOG_WARNING, "Invalid crop parameters\n");

                if (h->avctx->err_recognition & AV_EF_EXPLODE)

                    goto fail;

                crop_left = crop_right = crop_top = crop_bottom = 0;

            }

            sps->crop_left   = crop_left   * step_x;

            sps->crop_right  = crop_right  * step_x;

            sps->crop_top    = crop_top    * step_y;

            sps->crop_bottom = crop_bottom * step_y;

        }

    } else {

        sps->crop_left   =

        sps->crop_right  =

        sps->crop_top    =

        sps->crop_bottom =

        sps->crop        = 0;

    }

    sps->vui_parameters_present_flag = get_bits1(&h->gb);

    if (sps->vui_parameters_present_flag) {

        int ret = decode_vui_parameters(h, sps);

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

            goto fail;

    }

    /* if the maximum delay is not stored in the SPS, derive it based on the

     * level */

    if (!sps->bitstream_restriction_flag) {

        sps->num_reorder_frames = MAX_DELAYED_PIC_COUNT - 1;

        for (i = 0; i < FF_ARRAY_ELEMS(level_max_dpb_mbs); i++) {

            if (level_max_dpb_mbs[i][0] == sps->level_idc) {

                sps->num_reorder_frames = FFMIN(level_max_dpb_mbs[i][1] / (sps->mb_width * sps->mb_height),

                                                sps->num_reorder_frames);

                break;

            }

        }

    }

    if (!sps->sar.den)

        sps->sar.den = 1;

    if (h->avctx->debug & FF_DEBUG_PICT_INFO) {

        static const char csp[4][5] = { "Gray", "420", "422", "444" };

        av_log(h->avctx, AV_LOG_DEBUG,

               "sps:%u profile:%d/%d poc:%d ref:%d %dx%d %s %s crop:%u/%u/%u/%u %s %s %"PRId32"/%"PRId32"\n",

               sps_id, sps->profile_idc, sps->level_idc,

               sps->poc_type,

               sps->ref_frame_count,

               sps->mb_width, sps->mb_height,

               sps->frame_mbs_only_flag ? "FRM" : (sps->mb_aff ? "MB-AFF" : "PIC-AFF"),

               sps->direct_8x8_inference_flag ? "8B8" : "",

               sps->crop_left, sps->crop_right,

               sps->crop_top, sps->crop_bottom,

               sps->vui_parameters_present_flag ? "VUI" : "",

               csp[sps->chroma_format_idc],

               sps->timing_info_present_flag ? sps->num_units_in_tick : 0,

               sps->timing_info_present_flag ? sps->time_scale : 0);

    }

    sps->new = 1;

    av_free(h->sps_buffers[sps_id]);

    h->sps_buffers[sps_id] = sps;

    h->sps                 = *sps;

    return 0;

fail:

    av_free(sps);

    return AVERROR_INVALIDDATA;

}


static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)

{

    PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;

    NVENCSTATUS nvstatus;

    NvencContext *ctx = avctx->priv_data;

    NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;

    if (!nvenc_check_cuda(avctx))

        return 0;

    if (dl_fn->nvenc_lib)

        return 1;

#if defined(_WIN32)

    if (sizeof(void*) == 8) {

        dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));

    } else {

        dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));

    }

#else

    dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);

#endif

    if (!dl_fn->nvenc_lib) {

        av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");

        goto error;

    }

    nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");

    if (!nvEncodeAPICreateInstance) {

        av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");

        goto error;

    }

    dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;

    nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);

    if (nvstatus != NV_ENC_SUCCESS) {

        nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");

        goto error;

    }

    av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");

    return 1;

error:

    if (dl_fn->nvenc_lib)

        DL_CLOSE_FUNC(dl_fn->nvenc_lib);

    dl_fn->nvenc_lib = NULL;

    return 0;

}


static inline void h264_loop_filter_chroma_intra_c(uint8_t *pix, int xstride, int ystride, int alpha, int beta)

{

    int d;

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

        const int p0 = pix[-1*xstride];

        const int p1 = pix[-2*xstride];

        const int q0 = pix[0];

        const int q1 = pix[1*xstride];

        if( FFABS( p0 - q0 ) < alpha &&

            FFABS( p1 - p0 ) < beta &&

            FFABS( q1 - q0 ) < beta ) {

            pix[-xstride] = ( 2*p1 + p0 + q1 + 2 ) >> 2;   /* p0' */

            pix[0]        = ( 2*q1 + q0 + p1 + 2 ) >> 2;   /* q0' */

        }

        pix += ystride;

    }

}


real_parse_asm_rulebook(AVFormatContext *s, AVStream *orig_st,

                        const char *p)

{

    const char *end;

    int n_rules, odd = 0;

    AVStream *st;

    /**

     * The ASMRuleBook contains a list of comma-separated strings per rule,

     * and each rule is separated by a ;. The last one also has a ; at the

     * end so we can use it as delimiter.

     * Every rule occurs twice, once for when the RTSP packet header marker

     * is set and once for if it isn't. We only read the first because we

     * don't care much (that's what the "odd" variable is for).

     * Each rule contains a set of one or more statements, optionally

     * preceeded by a single condition. If there's a condition, the rule

     * starts with a '#'. Multiple conditions are merged between brackets,

     * so there are never multiple conditions spread out over separate

     * statements. Generally, these conditions are bitrate limits (min/max)

     * for multi-bitrate streams.

     */

    if (*p == '\"') p++;

    for (n_rules = 0; s->nb_streams < MAX_STREAMS;) {

        if (!(end = strchr(p, ';')))

            break;

        if (!odd && end != p) {

            if (n_rules > 0)

                st = add_dstream(s, orig_st);

            else

                st = orig_st;

            real_parse_asm_rule(st, p, end);

            n_rules++;

        }

        p = end + 1;

        odd ^= 1;

    }

}


int ff_get_cpu_flags_ppc(void)

{

#if HAVE_ALTIVEC

#ifdef __AMIGAOS4__

    ULONG result = 0;

    extern struct ExecIFace *IExec;

    IExec->GetCPUInfoTags(GCIT_VectorUnit, &result, TAG_DONE);

    if (result == VECTORTYPE_ALTIVEC)

        return AV_CPU_FLAG_ALTIVEC;

    return 0;

#elif defined(__APPLE__) || defined(__OpenBSD__)

#ifdef __OpenBSD__

    int sels[2] = {CTL_MACHDEP, CPU_ALTIVEC};

#else

    int sels[2] = {CTL_HW, HW_VECTORUNIT};

#endif

    int has_vu = 0;

    size_t len = sizeof(has_vu);

    int err;

    err = sysctl(sels, 2, &has_vu, &len, NULL, 0);

    if (err == 0)

        return has_vu ? AV_CPU_FLAG_ALTIVEC : 0;

    return 0;

#elif defined(__linux__)

    // The linux kernel could have the altivec support disabled

    // even if the cpu has it.

    int i, ret = 0;

    int fd = open("/proc/self/auxv", O_RDONLY);

    unsigned long buf[64] = { 0 };

    ssize_t count;

    if (fd < 0)

        return 0;

    while ((count = read(fd, buf, sizeof(buf))) > 0) {

        for (i = 0; i < count / sizeof(*buf); i += 2) {

            if (buf[i] == AT_NULL)

                goto out;

            if (buf[i] == AT_HWCAP) {

                if (buf[i + 1] & PPC_FEATURE_HAS_ALTIVEC)

                    ret = AV_CPU_FLAG_ALTIVEC;

                goto out;

            }

        }

    }

out:

    close(fd);

    return ret;

#elif CONFIG_RUNTIME_CPUDETECT

    int proc_ver;

    // Support of mfspr PVR emulation added in Linux 2.6.17.

    __asm__ volatile("mfspr %0, 287" : "=r" (proc_ver));

    proc_ver >>= 16;

    if (proc_ver  & 0x8000 ||

        proc_ver == 0x000c ||

        proc_ver == 0x0039 || proc_ver == 0x003c ||

        proc_ver == 0x0044 || proc_ver == 0x0045 ||

        proc_ver == 0x0070)

        return AV_CPU_FLAG_ALTIVEC;

    return 0;

#else

    // Since we were compiled for AltiVec, just assume we have it

    // until someone comes up with a proper way (not involving signal hacks).

    return AV_CPU_FLAG_ALTIVEC;

#endif /* __AMIGAOS4__ */

#endif /* HAVE_ALTIVEC */

    return 0;

}


static void decode_delta_j(uint8_t *dst,

                           const uint8_t *buf, const uint8_t *buf_end,

                           int w, int h, int bpp, int dst_size)

{

    int32_t pitch;

    uint8_t *ptr;

    uint32_t type, flag, cols, groups, rows, bytes;

    uint32_t offset;

    int planepitch_byte = (w + 7) / 8;

    int planepitch = ((w + 15) / 16) * 2;

    int kludge_j, b, g, r, d;

    GetByteContext gb;

    pitch = planepitch * bpp;

    kludge_j = w < 320 ? (320 - w) / 8 / 2 : 0;

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

    while (bytestream2_get_bytes_left(&gb) >= 2) {

        type = bytestream2_get_be16(&gb);

        switch (type) {

        case 0:

            return;

        case 1:

            flag   = bytestream2_get_be16(&gb);

            cols   = bytestream2_get_be16(&gb);

            groups = bytestream2_get_be16(&gb);

            for (g = 0; g < groups; g++) {

                offset = bytestream2_get_be16(&gb);

                if (bytestream2_get_bytes_left(&gb) < 1)

                    return;

                if (kludge_j)

                    offset = ((offset / (320 / 8)) * pitch) + (offset % (320 / 8)) - kludge_j;

                else

                    offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);

                for (b = 0; b < cols; b++) {

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

                        uint8_t value = bytestream2_get_byte(&gb);

                        if (offset >= dst_size)

                            return;

                        ptr = dst + offset;

                        if (flag)

                            ptr[0] ^= value;

                        else

                            ptr[0]  = value;

                        offset += planepitch;

                    }

                }

                if ((cols * bpp) & 1)

                    bytestream2_skip(&gb, 1);

            }

            break;

        case 2:

            flag   = bytestream2_get_be16(&gb);

            rows   = bytestream2_get_be16(&gb);

            bytes  = bytestream2_get_be16(&gb);

            groups = bytestream2_get_be16(&gb);

            for (g = 0; g < groups; g++) {

                offset = bytestream2_get_be16(&gb);

                if (kludge_j)

                    offset = ((offset / (320 / 8)) * pitch) + (offset % (320/ 8)) - kludge_j;

                else

                    offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);

                for (r = 0; r < rows; r++) {

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

                        unsigned noffset = offset + (r * pitch) + d * planepitch;

                        if (bytestream2_get_bytes_left(&gb) < 1)

                            return;

                        for (b = 0; b < bytes; b++) {

                            uint8_t value = bytestream2_get_byte(&gb);

                            if (noffset >= dst_size)

                                return;

                            ptr = dst + noffset;

                            if (flag)

                                ptr[0] ^= value;

                            else

                                ptr[0]  = value;

                            noffset++;

                        }

                    }

                }

                if ((rows * bytes * bpp) & 1)

                    bytestream2_skip(&gb, 1);

            }

            break;

        default:

            return;

        }

    }

}


static int dshow_read_header(AVFormatContext *avctx)

{

    struct dshow_ctx *ctx = avctx->priv_data;

    IGraphBuilder *graph = NULL;

    ICreateDevEnum *devenum = NULL;

    IMediaControl *control = NULL;

    int ret = AVERROR(EIO);

    int r;

    if (!ctx->list_devices && !parse_device_name(avctx)) {

        av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n");

        goto error;

    }

    ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id

                                                : AV_CODEC_ID_RAWVIDEO;

    if (ctx->pixel_format != AV_PIX_FMT_NONE) {

        if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) {

            av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when "

                              "video codec is not set or set to rawvideo\n");

            ret = AVERROR(EINVAL);

            goto error;

        }

    }

    if (ctx->framerate) {

        r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate);

        if (r < 0) {

            av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate);

            goto error;

        }

    }

    CoInitialize(0);

    r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,

                         &IID_IGraphBuilder, (void **) &graph);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n");

        goto error;

    }

    ctx->graph = graph;

    r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,

                         &IID_ICreateDevEnum, (void **) &devenum);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n");

        goto error;

    }

    if (ctx->list_devices) {

        av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n");

        dshow_cycle_devices(avctx, devenum, VideoDevice, NULL);

        av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n");

        dshow_cycle_devices(avctx, devenum, AudioDevice, NULL);

        ret = AVERROR_EXIT;

        goto error;

    }

    if (ctx->list_options) {

        if (ctx->device_name[VideoDevice])

            dshow_list_device_options(avctx, devenum, VideoDevice);

        if (ctx->device_name[AudioDevice])

            dshow_list_device_options(avctx, devenum, AudioDevice);

        ret = AVERROR_EXIT;

        goto error;

    }

    if (ctx->device_name[VideoDevice]) {

        if ((r = dshow_open_device(avctx, devenum, VideoDevice)) < 0 ||

            (r = dshow_add_device(avctx, VideoDevice)) < 0) {

            ret = r;

            goto error;

        }

    }

    if (ctx->device_name[AudioDevice]) {

        if ((r = dshow_open_device(avctx, devenum, AudioDevice)) < 0 ||

            (r = dshow_add_device(avctx, AudioDevice)) < 0) {

            ret = r;

            goto error;

        }

    }

    ctx->mutex = CreateMutex(NULL, 0, NULL);

    if (!ctx->mutex) {

        av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n");

        goto error;

    }

    ctx->event = CreateEvent(NULL, 1, 0, NULL);

    if (!ctx->event) {

        av_log(avctx, AV_LOG_ERROR, "Could not create Event\n");

        goto error;

    }

    r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control);

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n");

        goto error;

    }

    ctx->control = control;

    r = IMediaControl_Run(control);

    if (r == S_FALSE) {

        OAFilterState pfs;

        r = IMediaControl_GetState(control, 0, &pfs);

    }

    if (r != S_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not run filter\n");

        goto error;

    }

    ret = 0;

error:

    if (ret < 0)

        dshow_read_close(avctx);

    if (devenum)

        ICreateDevEnum_Release(devenum);

    return ret;

}


static void init_timetables( FM_OPL *OPL , int ARRATE , int DRRATE )

{

	int i;

	double rate;

	/* make attack rate & decay rate tables */

	for (i = 0;i < 4;i++) OPL->AR_TABLE[i] = OPL->DR_TABLE[i] = 0;

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

		rate  = OPL->freqbase;						/* frequency rate */

		if( i < 60 ) rate *= 1.0+(i&3)*0.25;		/* b0-1 : x1 , x1.25 , x1.5 , x1.75 */

		rate *= 1<<((i>>2)-1);						/* b2-5 : shift bit */

		rate *= (double)(EG_ENT<<ENV_BITS);

		OPL->AR_TABLE[i] = rate / ARRATE;

		OPL->DR_TABLE[i] = rate / DRRATE;

	}

	for (i = 60;i < 76;i++)

	{

		OPL->AR_TABLE[i] = EG_AED-1;

		OPL->DR_TABLE[i] = OPL->DR_TABLE[60];

	}

#if 0

	for (i = 0;i < 64 ;i++){	/* make for overflow area */

		LOG(LOG_WAR,("rate %2d , ar %f ms , dr %f ms \n",i,

			((double)(EG_ENT<<ENV_BITS) / OPL->AR_TABLE[i]) * (1000.0 / OPL->rate),

			((double)(EG_ENT<<ENV_BITS) / OPL->DR_TABLE[i]) * (1000.0 / OPL->rate) ));

	}

#endif

}


static void dwt_decode97_float(DWTContext *s, float *t)

{

    int lev;

    int w       = s->linelen[s->ndeclevels - 1][0];

    float *line = s->f_linebuf;

    float *data = t;

    /* position at index O of line range [0-5,w+5] cf. extend function */

    line += 5;

    for (lev = 0; lev < s->ndeclevels; lev++) {

        int lh = s->linelen[lev][0],

            lv = s->linelen[lev][1],

            mh = s->mod[lev][0],

            mv = s->mod[lev][1],

            lp;

        float *l;

        // HOR_SD

        l = line + mh;

        for (lp = 0; lp < lv; lp++) {

            int i, j = 0;

            // copy with interleaving

            for (i = mh; i < lh; i += 2, j++)

                l[i] = data[w * lp + j] * F_LFTG_K;

            for (i = 1 - mh; i < lh; i += 2, j++)

                l[i] = data[w * lp + j];

            sr_1d97_float(line, mh, mh + lh);

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

                data[w * lp + i] = l[i];

        }

        // VER_SD

        l = line + mv;

        for (lp = 0; lp < lh; lp++) {

            int i, j = 0;

            // copy with interleaving

            for (i = mv; i < lv; i += 2, j++)

                l[i] = data[w * j + lp] * F_LFTG_K;

            for (i = 1 - mv; i < lv; i += 2, j++)

                l[i] = data[w * j + lp];

            sr_1d97_float(line, mv, mv + lv);

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

                data[w * i + lp] = l[i];

        }

    }

}


void FUNCC(ff_h264_idct8_add)(uint8_t *_dst, int16_t *_block, int stride){

    int i;

    pixel *dst = (pixel*)_dst;

    dctcoef *block = (dctcoef*)_block;

    stride >>= sizeof(pixel)-1;

    block[0] += 32;

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

    {

        const int a0 =  block[i+0*8] + block[i+4*8];

        const int a2 =  block[i+0*8] - block[i+4*8];

        const int a4 = (block[i+2*8]>>1) - block[i+6*8];

        const int a6 = (block[i+6*8]>>1) + block[i+2*8];

        const int b0 = a0 + a6;

        const int b2 = a2 + a4;

        const int b4 = a2 - a4;

        const int b6 = a0 - a6;

        const int a1 = -block[i+3*8] + block[i+5*8] - block[i+7*8] - (block[i+7*8]>>1);

        const int a3 =  block[i+1*8] + block[i+7*8] - block[i+3*8] - (block[i+3*8]>>1);

        const int a5 = -block[i+1*8] + block[i+7*8] + block[i+5*8] + (block[i+5*8]>>1);

        const int a7 =  block[i+3*8] + block[i+5*8] + block[i+1*8] + (block[i+1*8]>>1);

        const int b1 = (a7>>2) + a1;

        const int b3 =  a3 + (a5>>2);

        const int b5 = (a3>>2) - a5;

        const int b7 =  a7 - (a1>>2);

        block[i+0*8] = b0 + b7;

        block[i+7*8] = b0 - b7;

        block[i+1*8] = b2 + b5;

        block[i+6*8] = b2 - b5;

        block[i+2*8] = b4 + b3;

        block[i+5*8] = b4 - b3;

        block[i+3*8] = b6 + b1;

        block[i+4*8] = b6 - b1;

    }

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

    {

        const int a0 =  block[0+i*8] + block[4+i*8];

        const int a2 =  block[0+i*8] - block[4+i*8];

        const int a4 = (block[2+i*8]>>1) - block[6+i*8];

        const int a6 = (block[6+i*8]>>1) + block[2+i*8];

        const int b0 = a0 + a6;

        const int b2 = a2 + a4;

        const int b4 = a2 - a4;

        const int b6 = a0 - a6;

        const int a1 = -block[3+i*8] + block[5+i*8] - block[7+i*8] - (block[7+i*8]>>1);

        const int a3 =  block[1+i*8] + block[7+i*8] - block[3+i*8] - (block[3+i*8]>>1);

        const int a5 = -block[1+i*8] + block[7+i*8] + block[5+i*8] + (block[5+i*8]>>1);

        const int a7 =  block[3+i*8] + block[5+i*8] + block[1+i*8] + (block[1+i*8]>>1);

        const int b1 = (a7>>2) + a1;

        const int b3 =  a3 + (a5>>2);

        const int b5 = (a3>>2) - a5;

        const int b7 =  a7 - (a1>>2);

        dst[i + 0*stride] = av_clip_pixel( dst[i + 0*stride] + ((b0 + b7) >> 6) );

        dst[i + 1*stride] = av_clip_pixel( dst[i + 1*stride] + ((b2 + b5) >> 6) );

        dst[i + 2*stride] = av_clip_pixel( dst[i + 2*stride] + ((b4 + b3) >> 6) );

        dst[i + 3*stride] = av_clip_pixel( dst[i + 3*stride] + ((b6 + b1) >> 6) );

        dst[i + 4*stride] = av_clip_pixel( dst[i + 4*stride] + ((b6 - b1) >> 6) );

        dst[i + 5*stride] = av_clip_pixel( dst[i + 5*stride] + ((b4 - b3) >> 6) );

        dst[i + 6*stride] = av_clip_pixel( dst[i + 6*stride] + ((b2 - b5) >> 6) );

        dst[i + 7*stride] = av_clip_pixel( dst[i + 7*stride] + ((b0 - b7) >> 6) );

    }

    memset(block, 0, 64 * sizeof(dctcoef));

}


void hmp_info_migrate(Monitor *mon, const QDict *qdict)

{

    MigrationInfo *info;

    MigrationCapabilityStatusList *caps, *cap;

    info = qmp_query_migrate(NULL);

    caps = qmp_query_migrate_capabilities(NULL);

    /* do not display parameters during setup */

    if (info->has_status && caps) {

        monitor_printf(mon, "capabilities: ");

        for (cap = caps; cap; cap = cap->next) {

            monitor_printf(mon, "%s: %s ",

                           MigrationCapability_lookup[cap->value->capability],

                           cap->value->state ? "on" : "off");

        }

        monitor_printf(mon, "\n");

    }

    if (info->has_status) {

        monitor_printf(mon, "Migration status: %s\n",

                       MigrationStatus_lookup[info->status]);

        monitor_printf(mon, "total time: %" PRIu64 " milliseconds\n",

                       info->total_time);

        if (info->has_expected_downtime) {

            monitor_printf(mon, "expected downtime: %" PRIu64 " milliseconds\n",

                           info->expected_downtime);

        }

        if (info->has_downtime) {

            monitor_printf(mon, "downtime: %" PRIu64 " milliseconds\n",

                           info->downtime);

        }

        if (info->has_setup_time) {

            monitor_printf(mon, "setup: %" PRIu64 " milliseconds\n",

                           info->setup_time);

        }

    }

    if (info->has_ram) {

        monitor_printf(mon, "transferred ram: %" PRIu64 " kbytes\n",

                       info->ram->transferred >> 10);

        monitor_printf(mon, "throughput: %0.2f mbps\n",

                       info->ram->mbps);

        monitor_printf(mon, "remaining ram: %" PRIu64 " kbytes\n",

                       info->ram->remaining >> 10);

        monitor_printf(mon, "total ram: %" PRIu64 " kbytes\n",

                       info->ram->total >> 10);

        monitor_printf(mon, "duplicate: %" PRIu64 " pages\n",

                       info->ram->duplicate);

        monitor_printf(mon, "skipped: %" PRIu64 " pages\n",

                       info->ram->skipped);

        monitor_printf(mon, "normal: %" PRIu64 " pages\n",

                       info->ram->normal);

        monitor_printf(mon, "normal bytes: %" PRIu64 " kbytes\n",

                       info->ram->normal_bytes >> 10);

        monitor_printf(mon, "dirty sync count: %" PRIu64 "\n",

                       info->ram->dirty_sync_count);

        if (info->ram->dirty_pages_rate) {

            monitor_printf(mon, "dirty pages rate: %" PRIu64 " pages\n",

                           info->ram->dirty_pages_rate);

        }

    }

    if (info->has_disk) {

        monitor_printf(mon, "transferred disk: %" PRIu64 " kbytes\n",

                       info->disk->transferred >> 10);

        monitor_printf(mon, "remaining disk: %" PRIu64 " kbytes\n",

                       info->disk->remaining >> 10);

        monitor_printf(mon, "total disk: %" PRIu64 " kbytes\n",

                       info->disk->total >> 10);

    }

    if (info->has_xbzrle_cache) {

        monitor_printf(mon, "cache size: %" PRIu64 " bytes\n",

                       info->xbzrle_cache->cache_size);

        monitor_printf(mon, "xbzrle transferred: %" PRIu64 " kbytes\n",

                       info->xbzrle_cache->bytes >> 10);

        monitor_printf(mon, "xbzrle pages: %" PRIu64 " pages\n",

                       info->xbzrle_cache->pages);

        monitor_printf(mon, "xbzrle cache miss: %" PRIu64 "\n",

                       info->xbzrle_cache->cache_miss);

        monitor_printf(mon, "xbzrle cache miss rate: %0.2f\n",

                       info->xbzrle_cache->cache_miss_rate);

        monitor_printf(mon, "xbzrle overflow : %" PRIu64 "\n",

                       info->xbzrle_cache->overflow);

    }

    if (info->has_cpu_throttle_percentage) {

        monitor_printf(mon, "cpu throttle percentage: %" PRIu64 "\n",

                       info->cpu_throttle_percentage);

    }

    qapi_free_MigrationInfo(info);

    qapi_free_MigrationCapabilityStatusList(caps);

}


static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,

                                     const float *in, int size, int scale_idx,

                                     int cb, const float lambda)

{

    const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    const float  Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float CLIPPED_ESCAPE = 165140.0f*IQ;

    const int dim = (cb < FIRST_PAIR_BT) ? 4 : 2;

    int i, j, k;

#ifndef USE_REALLY_FULL_SEARCH

    const float  Q34 = sqrtf(Q * sqrtf(Q));

    const int range  = aac_cb_range[cb];

    const int maxval = aac_cb_maxval[cb];

    int offs[4];

    float *scaled = s->scoefs;

#endif /* USE_REALLY_FULL_SEARCH */

//START_TIMER

    if (!cb)

        return;

#ifndef USE_REALLY_FULL_SEARCH

    offs[0] = 1;

    for (i = 1; i < dim; i++)

        offs[i] = offs[i-1]*range;

    abs_pow34_v(scaled, in, size);

    quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);

#endif /* USE_REALLY_FULL_SEARCH */

    for (i = 0; i < size; i += dim) {

        float mincost;

        int minidx  = 0;

        int minbits = 0;

        const float *vec;

#ifndef USE_REALLY_FULL_SEARCH

        int (*quants)[2] = &s->qcoefs[i];

        mincost = 0.0f;

        for (j = 0; j < dim; j++)

            mincost += in[i+j]*in[i+j];

        minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;

        minbits = ff_aac_spectral_bits[cb-1][minidx];

        mincost = mincost * lambda + minbits;

        for (j = 0; j < (1<<dim); j++) {

            float rd = 0.0f;

            int curbits;

            int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;

            int same   = 0;

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

                if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {

                    same = 1;

                    break;

                }

            }

            if (same)

                continue;

            for (k = 0; k < dim; k++)

                curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];

            curbits =  ff_aac_spectral_bits[cb-1][curidx];

            vec     = &ff_aac_codebook_vectors[cb-1][curidx*dim];

#else

        vec = ff_aac_codebook_vectors[cb-1];

        mincost = INFINITY;

        for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {

            float rd = 0.0f;

            int curbits = ff_aac_spectral_bits[cb-1][j];

            int curidx  = j;

#endif /* USE_REALLY_FULL_SEARCH */

            if (IS_CODEBOOK_UNSIGNED(cb)) {

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

                    float t = fabsf(in[i+k]);

                    float di;

                    if (vec[k] == 64.0f) { //FIXME: slow

                        //do not code with escape sequence small values

                        if (t < 39.0f*IQ) {

                            rd = INFINITY;

                            break;

                        }

                        if (t >= CLIPPED_ESCAPE) {

                            di = t - CLIPPED_ESCAPE;

                            curbits += 21;

                        } else {

                            int c = av_clip(quant(t, Q), 0, 8191);

                            di = t - c*cbrtf(c)*IQ;

                            curbits += av_log2(c)*2 - 4 + 1;

                        }

                    } else {

                        di = t - vec[k]*IQ;

                    }

                    if (vec[k] != 0.0f)

                        curbits++;

                    rd += di*di;

                }

            } else {

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

                    float di = in[i+k] - vec[k]*IQ;

                    rd += di*di;

                }

            }

            rd = rd * lambda + curbits;

            if (rd < mincost) {

                mincost = rd;

                minidx  = curidx;

                minbits = curbits;

            }

        }

        put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]);

        if (IS_CODEBOOK_UNSIGNED(cb))

            for (j = 0; j < dim; j++)

                if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f)

                    put_bits(pb, 1, in[i+j] < 0.0f);

        if (cb == ESC_BT) {

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

                if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) {

                    int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);

                    int len = av_log2(coef);

                    put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);

                    put_bits(pb, len, coef & ((1 << len) - 1));

                }

            }

        }

    }

//STOP_TIMER("quantize_and_encode")

}


int ff_vc1_parse_frame_header_adv(VC1Context *v, GetBitContext* gb)

{

    int pqindex, lowquant;

    int status;

    int mbmodetab, imvtab, icbptab, twomvbptab, fourmvbptab; /* useful only for debugging */

    int field_mode, fcm;

    v->numref          = 0;

    v->p_frame_skipped = 0;

    if (v->second_field) {

        v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;

        if (v->fptype & 4)

            v->s.pict_type = (v->fptype & 1) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;

        v->s.current_picture_ptr->f.pict_type = v->s.pict_type;

        if (!v->pic_header_flag)

            goto parse_common_info;

    }

    field_mode = 0;

    if (v->interlace) {

        fcm = decode012(gb);

        if (fcm) {

            if (fcm == ILACE_FIELD)

                field_mode = 1;

        }

    } else {

        fcm = PROGRESSIVE;

    }

    if (!v->first_pic_header_flag && v->field_mode != field_mode)

        return AVERROR_INVALIDDATA;

    v->field_mode = field_mode;

    v->fcm = fcm;

    if (v->field_mode) {

        v->s.mb_height = FFALIGN(v->s.height + 15 >> 4, 2);

        v->fptype = get_bits(gb, 3);

        v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;

        if (v->fptype & 4) // B-picture

            v->s.pict_type = (v->fptype & 2) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B;

    } else {

        v->s.mb_height = v->s.height + 15 >> 4;

        switch (get_unary(gb, 0, 4)) {

        case 0:

            v->s.pict_type = AV_PICTURE_TYPE_P;

            break;

        case 1:

            v->s.pict_type = AV_PICTURE_TYPE_B;

            break;

        case 2:

            v->s.pict_type = AV_PICTURE_TYPE_I;

            break;

        case 3:

            v->s.pict_type = AV_PICTURE_TYPE_BI;

            break;

        case 4:

            v->s.pict_type = AV_PICTURE_TYPE_P; // skipped pic

            v->p_frame_skipped = 1;

            break;

        }

    }

    if (v->tfcntrflag)

        skip_bits(gb, 8);

    if (v->broadcast) {

        if (!v->interlace || v->psf) {

            v->rptfrm = get_bits(gb, 2);

        } else {

            v->tff = get_bits1(gb);

            v->rff = get_bits1(gb);

        }

    }

    if (v->panscanflag) {

        avpriv_report_missing_feature(v->s.avctx, "Pan-scan");

        //...

    }

    if (v->p_frame_skipped) {

        return 0;

    }

    v->rnd = get_bits1(gb);

    if (v->interlace)

        v->uvsamp = get_bits1(gb);

    if (v->field_mode) {

        if (!v->refdist_flag)

            v->refdist = 0;

        else if ((v->s.pict_type != AV_PICTURE_TYPE_B) && (v->s.pict_type != AV_PICTURE_TYPE_BI)) {

            v->refdist = get_bits(gb, 2);

            if (v->refdist == 3)

                v->refdist += get_unary(gb, 0, 16);

        }

        if ((v->s.pict_type == AV_PICTURE_TYPE_B) || (v->s.pict_type == AV_PICTURE_TYPE_BI)) {

            v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

            v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

            v->frfd = (v->bfraction * v->refdist) >> 8;

            v->brfd = v->refdist - v->frfd - 1;

            if (v->brfd < 0)

                v->brfd = 0;

        }

        goto parse_common_info;

    }

    if (v->fcm == PROGRESSIVE) {

        if (v->finterpflag)

            v->interpfrm = get_bits1(gb);

        if (v->s.pict_type == AV_PICTURE_TYPE_B) {

            v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

            v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

            if (v->bfraction == 0) {

                v->s.pict_type = AV_PICTURE_TYPE_BI; /* XXX: should not happen here */

            }

        }

    }

    parse_common_info:

    if (v->field_mode)

        v->cur_field_type = !(v->tff ^ v->second_field);

    pqindex = get_bits(gb, 5);

    if (!pqindex)

        return -1;

    v->pqindex = pqindex;

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pq = ff_vc1_pquant_table[0][pqindex];

    else

        v->pq = ff_vc1_pquant_table[1][pqindex];

    v->pquantizer = 1;

    if (v->quantizer_mode == QUANT_FRAME_IMPLICIT)

        v->pquantizer = pqindex < 9;

    if (v->quantizer_mode == QUANT_NON_UNIFORM)

        v->pquantizer = 0;

    v->pqindex = pqindex;

    if (pqindex < 9)

        v->halfpq = get_bits1(gb);

    else

        v->halfpq = 0;

    if (v->quantizer_mode == QUANT_FRAME_EXPLICIT)

        v->pquantizer = get_bits1(gb);

    if (v->postprocflag)

        v->postproc = get_bits(gb, 2);

    if (v->parse_only)

        return 0;

    if (v->first_pic_header_flag)

        rotate_luts(v);

    switch (v->s.pict_type) {

    case AV_PICTURE_TYPE_I:

    case AV_PICTURE_TYPE_BI:

        if (v->fcm == ILACE_FRAME) { //interlace frame picture

            status = bitplane_decoding(v->fieldtx_plane, &v->fieldtx_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "FIELDTX plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

        }

        status = bitplane_decoding(v->acpred_plane, &v->acpred_is_raw, v);

        if (status < 0)

            return -1;

        av_log(v->s.avctx, AV_LOG_DEBUG, "ACPRED plane encoding: "

               "Imode: %i, Invert: %i\n", status>>1, status&1);

        v->condover = CONDOVER_NONE;

        if (v->overlap && v->pq <= 8) {

            v->condover = decode012(gb);

            if (v->condover == CONDOVER_SELECT) {

                status = bitplane_decoding(v->over_flags_plane, &v->overflg_is_raw, v);

                if (status < 0)

                    return -1;

                av_log(v->s.avctx, AV_LOG_DEBUG, "CONDOVER plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

            }

        }

        break;

    case AV_PICTURE_TYPE_P:

        if (v->field_mode) {

            v->numref = get_bits1(gb);

            if (!v->numref) {

                v->reffield          = get_bits1(gb);

                v->ref_field_type[0] = v->reffield ^ !v->cur_field_type;

            }

        }

        if (v->extended_mv)

            v->mvrange = get_unary(gb, 0, 3);

        else

            v->mvrange = 0;

        if (v->interlace) {

            if (v->extended_dmv)

                v->dmvrange = get_unary(gb, 0, 3);

            else

                v->dmvrange = 0;

            if (v->fcm == ILACE_FRAME) { // interlaced frame picture

                v->fourmvswitch = get_bits1(gb);

                v->intcomp      = get_bits1(gb);

                if (v->intcomp) {

                    v->lumscale = get_bits(gb, 6);

                    v->lumshift = get_bits(gb, 6);

                    INIT_LUT(v->lumscale, v->lumshift, v->last_luty[0], v->last_lutuv[0], 1);

                    INIT_LUT(v->lumscale, v->lumshift, v->last_luty[1], v->last_lutuv[1], 1);

                    v->last_use_ic = 1;

                }

                status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

                av_log(v->s.avctx, AV_LOG_DEBUG, "SKIPMB plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

                mbmodetab = get_bits(gb, 2);

                if (v->fourmvswitch)

                    v->mbmode_vlc = &ff_vc1_intfr_4mv_mbmode_vlc[mbmodetab];

                else

                    v->mbmode_vlc = &ff_vc1_intfr_non4mv_mbmode_vlc[mbmodetab];

                imvtab         = get_bits(gb, 2);

                v->imv_vlc     = &ff_vc1_1ref_mvdata_vlc[imvtab];

                // interlaced p-picture cbpcy range is [1, 63]

                icbptab        = get_bits(gb, 3);

                v->cbpcy_vlc   = &ff_vc1_icbpcy_vlc[icbptab];

                twomvbptab     = get_bits(gb, 2);

                v->twomvbp_vlc = &ff_vc1_2mv_block_pattern_vlc[twomvbptab];

                if (v->fourmvswitch) {

                    fourmvbptab     = get_bits(gb, 2);

                    v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

                }

            }

        }

        v->k_x = v->mvrange + 9 + (v->mvrange >> 1); //k_x can be 9 10 12 13

        v->k_y = v->mvrange + 8; //k_y can be 8 9 10 11

        v->range_x = 1 << (v->k_x - 1);

        v->range_y = 1 << (v->k_y - 1);

        if (v->pq < 5)

            v->tt_index = 0;

        else if (v->pq < 13)

            v->tt_index = 1;

        else

            v->tt_index = 2;

        if (v->fcm != ILACE_FRAME) {

            int mvmode;

            mvmode     = get_unary(gb, 1, 4);

            lowquant   = (v->pq > 12) ? 0 : 1;

            v->mv_mode = ff_vc1_mv_pmode_table[lowquant][mvmode];

            if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {

                int mvmode2;

                mvmode2 = get_unary(gb, 1, 3);

                v->mv_mode2 = ff_vc1_mv_pmode_table2[lowquant][mvmode2];

                if (v->field_mode) {

                    v->intcompfield = decode210(gb) ^ 3;

                } else

                    v->intcompfield = 3;

                v->lumscale2 = v->lumscale = 32;

                v->lumshift2 = v->lumshift =  0;

                if (v->intcompfield & 1) {

                    v->lumscale = get_bits(gb, 6);

                    v->lumshift = get_bits(gb, 6);

                }

                if ((v->intcompfield & 2) && v->field_mode) {

                    v->lumscale2 = get_bits(gb, 6);

                    v->lumshift2 = get_bits(gb, 6);

                } else if(!v->field_mode) {

                    v->lumscale2 = v->lumscale;

                    v->lumshift2 = v->lumshift;

                }

                if (v->field_mode && v->second_field) {

                    if (v->cur_field_type) {

                        INIT_LUT(v->lumscale , v->lumshift , v->curr_luty[v->cur_field_type^1], v->curr_lutuv[v->cur_field_type^1], 0);

                        INIT_LUT(v->lumscale2, v->lumshift2, v->last_luty[v->cur_field_type  ], v->last_lutuv[v->cur_field_type  ], 1);

                    } else {

                        INIT_LUT(v->lumscale2, v->lumshift2, v->curr_luty[v->cur_field_type^1], v->curr_lutuv[v->cur_field_type^1], 0);

                        INIT_LUT(v->lumscale , v->lumshift , v->last_luty[v->cur_field_type  ], v->last_lutuv[v->cur_field_type  ], 1);

                    }

                    v->next_use_ic = v->curr_use_ic = 1;

                } else {

                    INIT_LUT(v->lumscale , v->lumshift , v->last_luty[0], v->last_lutuv[0], 1);

                    INIT_LUT(v->lumscale2, v->lumshift2, v->last_luty[1], v->last_lutuv[1], 1);

                }

                v->last_use_ic = 1;

            }

            v->qs_last = v->s.quarter_sample;

            if (v->mv_mode == MV_PMODE_1MV_HPEL || v->mv_mode == MV_PMODE_1MV_HPEL_BILIN)

                v->s.quarter_sample = 0;

            else if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {

                if (v->mv_mode2 == MV_PMODE_1MV_HPEL || v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN)

                    v->s.quarter_sample = 0;

                else

                    v->s.quarter_sample = 1;

            } else

                v->s.quarter_sample = 1;

            v->s.mspel = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN

                           || (v->mv_mode == MV_PMODE_INTENSITY_COMP

                               && v->mv_mode2 == MV_PMODE_1MV_HPEL_BILIN));

        }

        if (v->fcm == PROGRESSIVE) { // progressive

            if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&

                 v->mv_mode2 == MV_PMODE_MIXED_MV)

                || v->mv_mode == MV_PMODE_MIXED_MV) {

                status = bitplane_decoding(v->mv_type_mb_plane, &v->mv_type_is_raw, v);

                if (status < 0)

                    return -1;

                av_log(v->s.avctx, AV_LOG_DEBUG, "MB MV Type plane encoding: "

                       "Imode: %i, Invert: %i\n", status>>1, status&1);

            } else {

                v->mv_type_is_raw = 0;

                memset(v->mv_type_mb_plane, 0, v->s.mb_stride * v->s.mb_height);

            }

            status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            /* Hopefully this is correct for P frames */

            v->s.mv_table_index = get_bits(gb, 2); //but using ff_vc1_ tables

            v->cbpcy_vlc        = &ff_vc1_cbpcy_p_vlc[get_bits(gb, 2)];

        } else if (v->fcm == ILACE_FRAME) { // frame interlaced

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = 1;

            v->s.mspel          = 1;

        } else {    // field interlaced

            mbmodetab = get_bits(gb, 3);

            imvtab = get_bits(gb, 2 + v->numref);

            if (!v->numref)

                v->imv_vlc = &ff_vc1_1ref_mvdata_vlc[imvtab];

            else

                v->imv_vlc = &ff_vc1_2ref_mvdata_vlc[imvtab];

            icbptab = get_bits(gb, 3);

            v->cbpcy_vlc = &ff_vc1_icbpcy_vlc[icbptab];

            if ((v->mv_mode == MV_PMODE_INTENSITY_COMP &&

                v->mv_mode2 == MV_PMODE_MIXED_MV) || v->mv_mode == MV_PMODE_MIXED_MV) {

                fourmvbptab     = get_bits(gb, 2);

                v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

                v->mbmode_vlc = &ff_vc1_if_mmv_mbmode_vlc[mbmodetab];

            } else {

                v->mbmode_vlc = &ff_vc1_if_1mv_mbmode_vlc[mbmodetab];

            }

        }

        if (v->dquant) {

            av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

            vop_dquant_decoding(v);

        }

        v->ttfrm = 0; //FIXME Is that so ?

        if (v->vstransform) {

            v->ttmbf = get_bits1(gb);

            if (v->ttmbf) {

                v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];

            }

        } else {

            v->ttmbf = 1;

            v->ttfrm = TT_8X8;

        }

        break;

    case AV_PICTURE_TYPE_B:

        if (v->fcm == ILACE_FRAME) {

            v->bfraction_lut_index = get_vlc2(gb, ff_vc1_bfraction_vlc.table, VC1_BFRACTION_VLC_BITS, 1);

            v->bfraction           = ff_vc1_bfraction_lut[v->bfraction_lut_index];

            if (v->bfraction == 0) {

                return -1;

            }

        }

        if (v->extended_mv)

            v->mvrange = get_unary(gb, 0, 3);

        else

            v->mvrange = 0;

        v->k_x     = v->mvrange + 9 + (v->mvrange >> 1); //k_x can be 9 10 12 13

        v->k_y     = v->mvrange + 8; //k_y can be 8 9 10 11

        v->range_x = 1 << (v->k_x - 1);

        v->range_y = 1 << (v->k_y - 1);

        if (v->pq < 5)

            v->tt_index = 0;

        else if (v->pq < 13)

            v->tt_index = 1;

        else

            v->tt_index = 2;

        if (v->field_mode) {

            int mvmode;

            if (v->extended_dmv)

                v->dmvrange = get_unary(gb, 0, 3);

            mvmode = get_unary(gb, 1, 3);

            lowquant = (v->pq > 12) ? 0 : 1;

            v->mv_mode          = ff_vc1_mv_pmode_table2[lowquant][mvmode];

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = (v->mv_mode == MV_PMODE_1MV || v->mv_mode == MV_PMODE_MIXED_MV);

            v->s.mspel          = !(v->mv_mode == MV_PMODE_1MV_HPEL_BILIN || v->mv_mode == MV_PMODE_1MV_HPEL);

            status = bitplane_decoding(v->forward_mb_plane, &v->fmb_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Forward Type plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            mbmodetab = get_bits(gb, 3);

            if (v->mv_mode == MV_PMODE_MIXED_MV)

                v->mbmode_vlc = &ff_vc1_if_mmv_mbmode_vlc[mbmodetab];

            else

                v->mbmode_vlc = &ff_vc1_if_1mv_mbmode_vlc[mbmodetab];

            imvtab       = get_bits(gb, 3);

            v->imv_vlc   = &ff_vc1_2ref_mvdata_vlc[imvtab];

            icbptab      = get_bits(gb, 3);

            v->cbpcy_vlc = &ff_vc1_icbpcy_vlc[icbptab];

            if (v->mv_mode == MV_PMODE_MIXED_MV) {

                fourmvbptab     = get_bits(gb, 2);

                v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

            }

            v->numref = 1; // interlaced field B pictures are always 2-ref

        } else if (v->fcm == ILACE_FRAME) {

            if (v->extended_dmv)

                v->dmvrange = get_unary(gb, 0, 3);

            if (get_bits1(gb)) /* intcomp - present but shall always be 0 */

                av_log(v->s.avctx, AV_LOG_WARNING, "Intensity compensation set for B picture\n");

            v->intcomp          = 0;

            v->mv_mode          = MV_PMODE_1MV;

            v->fourmvswitch     = 0;

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = 1;

            v->s.mspel          = 1;

            status              = bitplane_decoding(v->direct_mb_plane, &v->dmb_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Direct Type plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            mbmodetab       = get_bits(gb, 2);

            v->mbmode_vlc   = &ff_vc1_intfr_non4mv_mbmode_vlc[mbmodetab];

            imvtab          = get_bits(gb, 2);

            v->imv_vlc      = &ff_vc1_1ref_mvdata_vlc[imvtab];

            // interlaced p/b-picture cbpcy range is [1, 63]

            icbptab         = get_bits(gb, 3);

            v->cbpcy_vlc    = &ff_vc1_icbpcy_vlc[icbptab];

            twomvbptab      = get_bits(gb, 2);

            v->twomvbp_vlc  = &ff_vc1_2mv_block_pattern_vlc[twomvbptab];

            fourmvbptab     = get_bits(gb, 2);

            v->fourmvbp_vlc = &ff_vc1_4mv_block_pattern_vlc[fourmvbptab];

        } else {

            v->mv_mode          = get_bits1(gb) ? MV_PMODE_1MV : MV_PMODE_1MV_HPEL_BILIN;

            v->qs_last          = v->s.quarter_sample;

            v->s.quarter_sample = (v->mv_mode == MV_PMODE_1MV);

            v->s.mspel          = v->s.quarter_sample;

            status              = bitplane_decoding(v->direct_mb_plane, &v->dmb_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Direct Type plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            status = bitplane_decoding(v->s.mbskip_table, &v->skip_is_raw, v);

            if (status < 0)

                return -1;

            av_log(v->s.avctx, AV_LOG_DEBUG, "MB Skip plane encoding: "

                   "Imode: %i, Invert: %i\n", status>>1, status&1);

            v->s.mv_table_index = get_bits(gb, 2);

            v->cbpcy_vlc = &ff_vc1_cbpcy_p_vlc[get_bits(gb, 2)];

        }

        if (v->dquant) {

            av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

            vop_dquant_decoding(v);

        }

        v->ttfrm = 0;

        if (v->vstransform) {

            v->ttmbf = get_bits1(gb);

            if (v->ttmbf) {

                v->ttfrm = ff_vc1_ttfrm_to_tt[get_bits(gb, 2)];

            }

        } else {

            v->ttmbf = 1;

            v->ttfrm = TT_8X8;

        }

        break;

    }

    if (v->fcm != PROGRESSIVE && !v->s.quarter_sample) {

        v->range_x <<= 1;

        v->range_y <<= 1;

    }

    /* AC Syntax */

    v->c_ac_table_index = decode012(gb);

    if (v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_BI) {

        v->y_ac_table_index = decode012(gb);

    }

    /* DC Syntax */

    v->s.dc_table_index = get_bits1(gb);

    if ((v->s.pict_type == AV_PICTURE_TYPE_I || v->s.pict_type == AV_PICTURE_TYPE_BI)

        && v->dquant) {

        av_log(v->s.avctx, AV_LOG_DEBUG, "VOP DQuant info\n");

        vop_dquant_decoding(v);

    }

    v->bi_type = 0;

    if (v->s.pict_type == AV_PICTURE_TYPE_BI) {

        v->s.pict_type = AV_PICTURE_TYPE_B;

        v->bi_type = 1;

    }

    return 0;

}


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

{

    ISADevice *isadev = ISA_DEVICE(dev);

    ISACirrusVGAState *d = ISA_CIRRUS_VGA(dev);

    VGACommonState *s = &d->cirrus_vga.vga;

    vga_common_init(s, OBJECT(dev), true);

    cirrus_init_common(&d->cirrus_vga, OBJECT(dev), CIRRUS_ID_CLGD5430, 0,

                       isa_address_space(isadev),

                       isa_address_space_io(isadev));

    s->con = graphic_console_init(dev, 0, s->hw_ops, s);

    rom_add_vga(VGABIOS_CIRRUS_FILENAME);

    /* XXX ISA-LFB support */

    /* FIXME not qdev yet */


static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,

                                const uint8_t *buf, int buf_size)

{

    int cmd_pos, pos, cmd, x1, y1, x2, y2, offset1, offset2, next_cmd_pos;

    int big_offsets, offset_size, is_8bit = 0;

    const uint8_t *yuv_palette = NULL;

    uint8_t *colormap = ctx->colormap, *alpha = ctx->alpha;

    int date;

    int i;

    int is_menu = 0;

    if (buf_size < 10)

        return -1;

    if (AV_RB16(buf) == 0) {   /* HD subpicture with 4-byte offsets */

        big_offsets = 1;

        offset_size = 4;

        cmd_pos = 6;

    } else {

        big_offsets = 0;

        offset_size = 2;

        cmd_pos = 2;

    }

    cmd_pos = READ_OFFSET(buf + cmd_pos);

    if (cmd_pos < 0 || cmd_pos > buf_size - 2 - offset_size)

        return AVERROR(EAGAIN);

    while (cmd_pos > 0 && cmd_pos < buf_size - 2 - offset_size) {

        date = AV_RB16(buf + cmd_pos);

        next_cmd_pos = READ_OFFSET(buf + cmd_pos + 2);

        av_dlog(NULL, "cmd_pos=0x%04x next=0x%04x date=%d\n",

                cmd_pos, next_cmd_pos, date);

        pos = cmd_pos + 2 + offset_size;

        offset1 = -1;

        offset2 = -1;

        x1 = y1 = x2 = y2 = 0;

        while (pos < buf_size) {

            cmd = buf[pos++];

            av_dlog(NULL, "cmd=%02x\n", cmd);

            switch(cmd) {

            case 0x00:

                /* menu subpicture */

                is_menu = 1;

                break;

            case 0x01:

                /* set start date */

                sub_header->start_display_time = (date << 10) / 90;

                break;

            case 0x02:

                /* set end date */

                sub_header->end_display_time = (date << 10) / 90;

                break;

            case 0x03:

                /* set colormap */

                if ((buf_size - pos) < 2)

                    goto fail;

                colormap[3] = buf[pos] >> 4;

                colormap[2] = buf[pos] & 0x0f;

                colormap[1] = buf[pos + 1] >> 4;

                colormap[0] = buf[pos + 1] & 0x0f;

                pos += 2;

                break;

            case 0x04:

                /* set alpha */

                if ((buf_size - pos) < 2)

                    goto fail;

                alpha[3] = buf[pos] >> 4;

                alpha[2] = buf[pos] & 0x0f;

                alpha[1] = buf[pos + 1] >> 4;

                alpha[0] = buf[pos + 1] & 0x0f;

                pos += 2;

            av_dlog(NULL, "alpha=%x%x%x%x\n", alpha[0],alpha[1],alpha[2],alpha[3]);

                break;

            case 0x05:

            case 0x85:

                if ((buf_size - pos) < 6)

                    goto fail;

                x1 = (buf[pos] << 4) | (buf[pos + 1] >> 4);

                x2 = ((buf[pos + 1] & 0x0f) << 8) | buf[pos + 2];

                y1 = (buf[pos + 3] << 4) | (buf[pos + 4] >> 4);

                y2 = ((buf[pos + 4] & 0x0f) << 8) | buf[pos + 5];

                if (cmd & 0x80)

                    is_8bit = 1;

                av_dlog(NULL, "x1=%d x2=%d y1=%d y2=%d\n", x1, x2, y1, y2);

                pos += 6;

                break;

            case 0x06:

                if ((buf_size - pos) < 4)

                    goto fail;

                offset1 = AV_RB16(buf + pos);

                offset2 = AV_RB16(buf + pos + 2);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 4;

                break;

            case 0x86:

                if ((buf_size - pos) < 8)

                    goto fail;

                offset1 = AV_RB32(buf + pos);

                offset2 = AV_RB32(buf + pos + 4);

                av_dlog(NULL, "offset1=0x%04x offset2=0x%04x\n", offset1, offset2);

                pos += 8;

                break;

            case 0x83:

                /* HD set palette */

                if ((buf_size - pos) < 768)

                    goto fail;

                yuv_palette = buf + pos;

                pos += 768;

                break;

            case 0x84:

                /* HD set contrast (alpha) */

                if ((buf_size - pos) < 256)

                    goto fail;

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

                    alpha[i] = 0xFF - buf[pos+i];

                pos += 256;

                break;

            case 0xff:

                goto the_end;

            default:

                av_dlog(NULL, "unrecognised subpicture command 0x%x\n", cmd);

                goto the_end;

            }

        }

    the_end:

        if (offset1 >= 0) {

            int w, h;

            uint8_t *bitmap;

            /* decode the bitmap */

            w = x2 - x1 + 1;

            if (w < 0)

                w = 0;

            h = y2 - y1 + 1;

            if (h < 0)

                h = 0;

            if (w > 0 && h > 0) {

                reset_rects(sub_header);

                bitmap = av_malloc(w * h);

                sub_header->rects = av_mallocz(sizeof(*sub_header->rects));

                sub_header->rects[0] = av_mallocz(sizeof(AVSubtitleRect));

                sub_header->num_rects = 1;

                sub_header->rects[0]->pict.data[0] = bitmap;

                decode_rle(bitmap, w * 2, w, (h + 1) / 2,

                           buf, offset1, buf_size, is_8bit);

                decode_rle(bitmap + w, w * 2, w, h / 2,

                           buf, offset2, buf_size, is_8bit);

                sub_header->rects[0]->pict.data[1] = av_mallocz(AVPALETTE_SIZE);

                if (is_8bit) {

                    if (!yuv_palette)

                        goto fail;

                    sub_header->rects[0]->nb_colors = 256;

                    yuv_a_to_rgba(yuv_palette, alpha, (uint32_t*)sub_header->rects[0]->pict.data[1], 256);

                } else {

                    sub_header->rects[0]->nb_colors = 4;

                    guess_palette(ctx, (uint32_t*)sub_header->rects[0]->pict.data[1],

                                  0xffff00);

                }

                sub_header->rects[0]->x = x1;

                sub_header->rects[0]->y = y1;

                sub_header->rects[0]->w = w;

                sub_header->rects[0]->h = h;

                sub_header->rects[0]->type = SUBTITLE_BITMAP;

                sub_header->rects[0]->pict.linesize[0] = w;

                sub_header->rects[0]->flags = is_menu ? AV_SUBTITLE_FLAG_FORCED : 0;

            }

        }

        if (next_cmd_pos < cmd_pos) {

            av_log(NULL, AV_LOG_ERROR, "Invalid command offset\n");

            break;

        }

        if (next_cmd_pos == cmd_pos)

            break;

        cmd_pos = next_cmd_pos;

    }

    if (sub_header->num_rects > 0)

        return is_menu;

 fail:

    reset_rects(sub_header);

    return -1;

}


static void encode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])

{

    int x, y, p, i;

    const int ring_size = s->avctx->context_model ? 3 : 2;

    int16_t *sample[4][3];

    int lbd    = s->bits_per_raw_sample <= 8;

    int bits   = s->bits_per_raw_sample > 0 ? s->bits_per_raw_sample : 8;

    int offset = 1 << bits;

    s->run_index = 0;

    memset(s->sample_buffer, 0, ring_size * MAX_PLANES *

                                (w + 6) * sizeof(*s->sample_buffer));

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

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

            for (p = 0; p < MAX_PLANES; p++)

                sample[p][i]= s->sample_buffer + p*ring_size*(w+6) + ((h+i-y)%ring_size)*(w+6) + 3;

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

            int b, g, r, av_uninit(a);

            if (lbd) {

                unsigned v = *((uint32_t*)(src[0] + x*4 + stride[0]*y));

                b =  v        & 0xFF;

                g = (v >>  8) & 0xFF;

                r = (v >> 16) & 0xFF;

                a =  v >> 24;

            } else {

                b = *((uint16_t*)(src[0] + x*2 + stride[0]*y));

                g = *((uint16_t*)(src[1] + x*2 + stride[1]*y));

                r = *((uint16_t*)(src[2] + x*2 + stride[2]*y));

            }

            b -= g;

            r -= g;

            g += (b + r) >> 2;

            b += offset;

            r += offset;

            sample[0][0][x] = g;

            sample[1][0][x] = b;

            sample[2][0][x] = r;

            sample[3][0][x] = a;

        }

        for (p = 0; p < 3 + s->transparency; p++) {

            sample[p][0][-1] = sample[p][1][0  ];

            sample[p][1][ w] = sample[p][1][w-1];

            if (lbd)

                encode_line(s, w, sample[p], (p + 1) / 2, 9);

            else

                encode_line(s, w, sample[p], (p + 1) / 2, bits + 1);

        }

    }

}


static DisplayType select_display(const char *p)

{

    const char *opts;

    DisplayType display = DT_DEFAULT;

    if (strstart(p, "sdl", &opts)) {

#ifdef CONFIG_SDL

        display = DT_SDL;

        while (*opts) {

            const char *nextopt;

            if (strstart(opts, ",frame=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    no_frame = 0;

                } else if (strstart(opts, "off", &nextopt)) {

                    no_frame = 1;

                } else {

                    goto invalid_display;

                }

            } else if (strstart(opts, ",alt_grab=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    alt_grab = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    alt_grab = 0;

                } else {

                    goto invalid_display;

                }

            } else if (strstart(opts, ",ctrl_grab=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    ctrl_grab = 1;

                } else if (strstart(opts, "off", &nextopt)) {

                    ctrl_grab = 0;

                } else {

                    goto invalid_display;

                }

            } else if (strstart(opts, ",window_close=", &nextopt)) {

                opts = nextopt;

                if (strstart(opts, "on", &nextopt)) {

                    no_quit = 0;

                } else if (strstart(opts, "off", &nextopt)) {

                    no_quit = 1;

                } else {

                    goto invalid_display;

                }

            } else {

                goto invalid_display;

            }

            opts = nextopt;

        }

#else

        fprintf(stderr, "SDL support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "vnc", &opts)) {

#ifdef CONFIG_VNC

        display_remote++;

        if (*opts) {

            const char *nextopt;

            if (strstart(opts, "=", &nextopt)) {

                vnc_display = nextopt;

            }

        }

        if (!vnc_display) {

            fprintf(stderr, "VNC requires a display argument vnc=<display>\n");

            exit(1);

        }

#else

        fprintf(stderr, "VNC support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "curses", &opts)) {

#ifdef CONFIG_CURSES

        display = DT_CURSES;

#else

        fprintf(stderr, "Curses support is disabled\n");

        exit(1);

#endif

    } else if (strstart(p, "none", &opts)) {

        display = DT_NONE;

    } else {

    invalid_display:

        fprintf(stderr, "Unknown display type: %s\n", p);

        exit(1);

    }

    return display;

}


PPC_OP(subfme)

{

    T0 = ~T0 + xer_ca - 1;

    if (T0 != -1)

        xer_ca = 1;

    RETURN();

}


static int bitpacked_decode_yuv422p10(AVCodecContext *avctx, AVFrame *frame,

                                      AVPacket *avpkt)

{

    uint64_t frame_size = (uint64_t)avctx->width * (uint64_t)avctx->height * 20;

    uint64_t packet_size = avpkt->size * 8;

    GetBitContext bc;

    uint16_t *y, *u, *v;

    int ret, i;

    ret = ff_get_buffer(avctx, frame, 0);

    if (ret < 0)

        return ret;

    y = (uint16_t*)frame->data[0];

    u = (uint16_t*)frame->data[1];

    v = (uint16_t*)frame->data[2];

    if (frame_size > packet_size)

        return AVERROR_INVALIDDATA;

    if (avctx->width % 2)

        return AVERROR_PATCHWELCOME;

    ret = init_get_bits(&bc, avpkt->data, avctx->width * avctx->height * 20);

    if (ret)

        return ret;

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

        y = (uint16_t*)(frame->data[0] + i * frame->linesize[0]);

        u = (uint16_t*)(frame->data[1] + i * frame->linesize[1]);

        v = (uint16_t*)(frame->data[2] + i * frame->linesize[2]);

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

            *u++ = get_bits(&bc, 10);

            *y++ = get_bits(&bc, 10);

            *v++ = get_bits(&bc, 10);

            *y++ = get_bits(&bc, 10);

        }

    }

    return 0;

}


static void qed_read_l2_table_cb(void *opaque, int ret)

{

    QEDReadL2TableCB *read_l2_table_cb = opaque;

    QEDRequest *request = read_l2_table_cb->request;

    BDRVQEDState *s = read_l2_table_cb->s;

    CachedL2Table *l2_table = request->l2_table;

    if (ret) {

        /* can't trust loaded L2 table anymore */

        qed_unref_l2_cache_entry(l2_table);

        request->l2_table = NULL;

    } else {

        l2_table->offset = read_l2_table_cb->l2_offset;

        qed_commit_l2_cache_entry(&s->l2_cache, l2_table);

        /* This is guaranteed to succeed because we just committed the entry

         * to the cache.

         */

        request->l2_table = qed_find_l2_cache_entry(&s->l2_cache,

                                                    l2_table->offset);

        assert(request->l2_table != NULL);

    }

    gencb_complete(&read_l2_table_cb->gencb, ret);

}


void input_type_enum(Visitor *v, int *obj, const char *strings[],

                     const char *kind, const char *name,

                     Error **errp)

{

    int64_t value = 0;

    char *enum_str;

    assert(strings);

    visit_type_str(v, &enum_str, name, errp);

    if (error_is_set(errp)) {

        return;

    }

    while (strings[value] != NULL) {

        if (strcmp(strings[value], enum_str) == 0) {

            break;

        }

        value++;

    }

    if (strings[value] == NULL) {

        error_set(errp, QERR_INVALID_PARAMETER, enum_str);

        g_free(enum_str);

        return;

    }

    g_free(enum_str);

    *obj = value;

}


static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)

{

    FramePool *pool = avctx->internal->pool;

    int i, ret;

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_VIDEO: {

        AVPicture picture;

        int size[4] = { 0 };

        int w = frame->width;

        int h = frame->height;

        int tmpsize, unaligned;

        if (pool->format == frame->format &&

            pool->width == frame->width && pool->height == frame->height)

            return 0;

        avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);

        if (!(avctx->flags & CODEC_FLAG_EMU_EDGE)) {

            w += EDGE_WIDTH * 2;

            h += EDGE_WIDTH * 2;

        }

        do {

            // NOTE: do not align linesizes individually, this breaks e.g. assumptions

            // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2

            av_image_fill_linesizes(picture.linesize, avctx->pix_fmt, w);

            // increase alignment of w for next try (rhs gives the lowest bit set in w)

            w += w & ~(w - 1);

            unaligned = 0;

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

                unaligned |= picture.linesize[i] % pool->stride_align[i];

        } while (unaligned);

        tmpsize = av_image_fill_pointers(picture.data, avctx->pix_fmt, h,

                                         NULL, picture.linesize);

        if (tmpsize < 0)

            return -1;

        for (i = 0; i < 3 && picture.data[i + 1]; i++)

            size[i] = picture.data[i + 1] - picture.data[i];

        size[i] = tmpsize - (picture.data[i] - picture.data[0]);

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

            av_buffer_pool_uninit(&pool->pools[i]);

            pool->linesize[i] = picture.linesize[i];

            if (size[i]) {

                pool->pools[i] = av_buffer_pool_init(size[i] + 16, NULL);

                if (!pool->pools[i]) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

        }

        pool->format = frame->format;

        pool->width  = frame->width;

        pool->height = frame->height;

        break;

        }

    case AVMEDIA_TYPE_AUDIO: {

        int ch     = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);

        int planar = av_sample_fmt_is_planar(frame->format);

        int planes = planar ? ch : 1;

        if (pool->format == frame->format && pool->planes == planes &&

            pool->channels == ch && frame->nb_samples == pool->samples)

            return 0;

        av_buffer_pool_uninit(&pool->pools[0]);

        ret = av_samples_get_buffer_size(&pool->linesize[0], ch,

                                         frame->nb_samples, frame->format, 0);

        if (ret < 0)

            goto fail;

        pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);

        if (!pool->pools[0]) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        pool->format     = frame->format;

        pool->planes     = planes;

        pool->channels   = ch;

        pool->samples = frame->nb_samples;

        break;

        }

    default: av_assert0(0);

    }

    return 0;

fail:

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

        av_buffer_pool_uninit(&pool->pools[i]);

    pool->format = -1;

    pool->planes = pool->channels = pool->samples = 0;

    pool->width  = pool->height = 0;

    return ret;

}


static void prom_init(target_phys_addr_t addr, const char *bios_name)

{

    DeviceState *dev;

    SysBusDevice *s;

    char *filename;

    int ret;

    dev = qdev_create(NULL, "openprom");

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    sysbus_mmio_map(s, 0, addr);

    /* load boot prom */

    if (bios_name == NULL) {

        bios_name = PROM_FILENAME;

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        ret = load_elf(filename, addr - PROM_VADDR, NULL, NULL, NULL,

                       1, ELF_MACHINE, 0);

        if (ret < 0 || ret > PROM_SIZE_MAX) {

            ret = load_image_targphys(filename, addr, PROM_SIZE_MAX);

        }

        qemu_free(filename);

    } else {

        ret = -1;

    }

    if (ret < 0 || ret > PROM_SIZE_MAX) {

        fprintf(stderr, "qemu: could not load prom '%s'\n", bios_name);

        exit(1);

    }

}


static void qemu_rdma_move_header(RDMAContext *rdma, int idx,

                                  RDMAControlHeader *head)

{

    rdma->wr_data[idx].control_len = head->len;

    rdma->wr_data[idx].control_curr =

        rdma->wr_data[idx].control + sizeof(RDMAControlHeader);

}