int ff_rtsp_fetch_packet(AVFormatContext *s, AVPacket *pkt)

{

    RTSPState *rt = s->priv_data;

    int ret, len;

    RTSPStream *rtsp_st, *first_queue_st = NULL;

    int64_t wait_end = 0;

    if (rt->nb_byes == rt->nb_rtsp_streams)

        return AVERROR_EOF;

    /* get next frames from the same RTP packet */

    if (rt->cur_transport_priv) {

        if (rt->transport == RTSP_TRANSPORT_RDT) {

            ret = ff_rdt_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);

        } else if (rt->transport == RTSP_TRANSPORT_RTP) {

            ret = ff_rtp_parse_packet(rt->cur_transport_priv, pkt, NULL, 0);

        } else if (rt->ts && CONFIG_RTPDEC) {

            ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf + rt->recvbuf_pos, rt->recvbuf_len - rt->recvbuf_pos);

            if (ret >= 0) {

                rt->recvbuf_pos += ret;

                ret = rt->recvbuf_pos < rt->recvbuf_len;

            }

        } else

            ret = -1;

        if (ret == 0) {

            rt->cur_transport_priv = NULL;

            return 0;

        } else if (ret == 1) {

            return 0;

        } else

            rt->cur_transport_priv = NULL;

    }

redo:

    if (rt->transport == RTSP_TRANSPORT_RTP) {

        int i;

        int64_t first_queue_time = 0;

        for (i = 0; i < rt->nb_rtsp_streams; i++) {

            RTPDemuxContext *rtpctx = rt->rtsp_streams[i]->transport_priv;

            int64_t queue_time;

            if (!rtpctx)

                continue;

            queue_time = ff_rtp_queued_packet_time(rtpctx);

            if (queue_time && (queue_time - first_queue_time < 0 ||

                               !first_queue_time)) {

                first_queue_time = queue_time;

                first_queue_st   = rt->rtsp_streams[i];

            }

        }

        if (first_queue_time) {

            wait_end = first_queue_time + s->max_delay;

        } else {

            wait_end = 0;

            first_queue_st = NULL;

        }

    }

    /* read next RTP packet */

    if (!rt->recvbuf) {

        rt->recvbuf = av_malloc(RECVBUF_SIZE);

        if (!rt->recvbuf)

            return AVERROR(ENOMEM);

    }

    switch(rt->lower_transport) {

    default:

#if CONFIG_RTSP_DEMUXER

    case RTSP_LOWER_TRANSPORT_TCP:

        len = ff_rtsp_tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE);

        break;

#endif

    case RTSP_LOWER_TRANSPORT_UDP:

    case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:

        len = udp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE, wait_end);

        if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)

            ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, rtsp_st->rtp_handle, NULL, len);

        break;

    case RTSP_LOWER_TRANSPORT_CUSTOM:

        if (first_queue_st && rt->transport == RTSP_TRANSPORT_RTP &&

            wait_end && wait_end < av_gettime_relative())

            len = AVERROR(EAGAIN);

        else

            len = ffio_read_partial(s->pb, rt->recvbuf, RECVBUF_SIZE);

        len = pick_stream(s, &rtsp_st, rt->recvbuf, len);

        if (len > 0 && rtsp_st->transport_priv && rt->transport == RTSP_TRANSPORT_RTP)

            ff_rtp_check_and_send_back_rr(rtsp_st->transport_priv, NULL, s->pb, len);

        break;

    }

    if (len == AVERROR(EAGAIN) && first_queue_st &&

        rt->transport == RTSP_TRANSPORT_RTP) {

        rtsp_st = first_queue_st;

        ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, NULL, 0);

        goto end;

    }

    if (len < 0)

        return len;

    if (len == 0)

        return AVERROR_EOF;

    if (rt->transport == RTSP_TRANSPORT_RDT) {

        ret = ff_rdt_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);

    } else if (rt->transport == RTSP_TRANSPORT_RTP) {

        ret = ff_rtp_parse_packet(rtsp_st->transport_priv, pkt, &rt->recvbuf, len);

        if (rtsp_st->feedback) {

            AVIOContext *pb = NULL;

            if (rt->lower_transport == RTSP_LOWER_TRANSPORT_CUSTOM)

                pb = s->pb;

            ff_rtp_send_rtcp_feedback(rtsp_st->transport_priv, rtsp_st->rtp_handle, pb);

        }

        if (ret < 0) {

            /* Either bad packet, or a RTCP packet. Check if the

             * first_rtcp_ntp_time field was initialized. */

            RTPDemuxContext *rtpctx = rtsp_st->transport_priv;

            if (rtpctx->first_rtcp_ntp_time != AV_NOPTS_VALUE) {

                /* first_rtcp_ntp_time has been initialized for this stream,

                 * copy the same value to all other uninitialized streams,

                 * in order to map their timestamp origin to the same ntp time

                 * as this one. */

                int i;

                AVStream *st = NULL;

                if (rtsp_st->stream_index >= 0)

                    st = s->streams[rtsp_st->stream_index];

                for (i = 0; i < rt->nb_rtsp_streams; i++) {

                    RTPDemuxContext *rtpctx2 = rt->rtsp_streams[i]->transport_priv;

                    AVStream *st2 = NULL;

                    if (rt->rtsp_streams[i]->stream_index >= 0)

                        st2 = s->streams[rt->rtsp_streams[i]->stream_index];

                    if (rtpctx2 && st && st2 &&

                        rtpctx2->first_rtcp_ntp_time == AV_NOPTS_VALUE) {

                        rtpctx2->first_rtcp_ntp_time = rtpctx->first_rtcp_ntp_time;

                        rtpctx2->rtcp_ts_offset = av_rescale_q(

                            rtpctx->rtcp_ts_offset, st->time_base,

                            st2->time_base);

                    }

                }

            }

            if (ret == -RTCP_BYE) {

                rt->nb_byes++;

                av_log(s, AV_LOG_DEBUG, "Received BYE for stream %d (%d/%d)\n",

                       rtsp_st->stream_index, rt->nb_byes, rt->nb_rtsp_streams);

                if (rt->nb_byes == rt->nb_rtsp_streams)

                    return AVERROR_EOF;

            }

        }

    } else if (rt->ts && CONFIG_RTPDEC) {

        ret = ff_mpegts_parse_packet(rt->ts, pkt, rt->recvbuf, len);

        if (ret >= 0) {

            if (ret < len) {

                rt->recvbuf_len = len;

                rt->recvbuf_pos = ret;

                rt->cur_transport_priv = rt->ts;

                return 1;

            } else {

                ret = 0;

            }

        }

    } else {

        return AVERROR_INVALIDDATA;

    }

end:

    if (ret < 0)

        goto redo;

    if (ret == 1)

        /* more packets may follow, so we save the RTP context */

        rt->cur_transport_priv = rtsp_st->transport_priv;

    return ret;

}


static void assign_failed_examine(AssignedDevice *dev)

{

    char name[PATH_MAX], dir[PATH_MAX], driver[PATH_MAX] = {}, *ns;

    uint16_t vendor_id, device_id;

    int r;

    snprintf(dir, sizeof(dir), "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/",

            dev->host.domain, dev->host.bus, dev->host.slot,

            dev->host.function);

    snprintf(name, sizeof(name), "%sdriver", dir);

    r = readlink(name, driver, sizeof(driver));

    if ((r <= 0) || r >= sizeof(driver)) {

        goto fail;

    }

    ns = strrchr(driver, '/');

    if (!ns) {

        goto fail;

    }

    ns++;

    if (get_real_vendor_id(dir, &vendor_id) ||

        get_real_device_id(dir, &device_id)) {

        goto fail;

    }

    error_printf("*** The driver '%s' is occupying your device "

        "%04x:%02x:%02x.%x.\n"

        "***\n"

        "*** You can try the following commands to free it:\n"

        "***\n"

        "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/new_id\n"

        "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/%s/unbind\n"

        "*** $ echo \"%04x:%02x:%02x.%x\" > /sys/bus/pci/drivers/"

        "pci-stub/bind\n"

        "*** $ echo \"%04x %04x\" > /sys/bus/pci/drivers/pci-stub/remove_id\n"

        "***",

        ns, dev->host.domain, dev->host.bus, dev->host.slot,

        dev->host.function, vendor_id, device_id,

        dev->host.domain, dev->host.bus, dev->host.slot, dev->host.function,

        ns, dev->host.domain, dev->host.bus, dev->host.slot,

        dev->host.function, vendor_id, device_id);

    return;

fail:

    error_report("Couldn't find out why.");

}


av_cold void ff_h264_free_context(H264Context *h)

{

    int i;

    free_tables(h); //FIXME cleanup init stuff perhaps

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

        av_freep(h->sps_buffers + i);

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

        av_freep(h->pps_buffers + i);

}


static int nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)

{

    NBDClient *client = req->client;

    int csock = client->sock;

    int rc;

    client->recv_coroutine = qemu_coroutine_self();

    if (nbd_receive_request(csock, request) == -1) {

        rc = -EIO;

        goto out;

    }

    if (request->len > NBD_BUFFER_SIZE) {

        LOG("len (%u) is larger than max len (%u)",

            request->len, NBD_BUFFER_SIZE);

        rc = -EINVAL;

        goto out;

    }

    if ((request->from + request->len) < request->from) {

        LOG("integer overflow detected! "

            "you're probably being attacked");

        rc = -EINVAL;

        goto out;

    }

    TRACE("Decoding type");

    if ((request->type & NBD_CMD_MASK_COMMAND) == NBD_CMD_WRITE) {

        TRACE("Reading %u byte(s)", request->len);

        if (qemu_co_recv(csock, req->data, request->len) != request->len) {

            LOG("reading from socket failed");

            rc = -EIO;

            goto out;

        }

    }

    rc = 0;

out:

    client->recv_coroutine = NULL;

    return rc;

}


static inline int hpel_motion(MpegEncContext *s,

                              uint8_t *dest, uint8_t *src,

                              int src_x, int src_y,

                              op_pixels_func *pix_op,

                              int motion_x, int motion_y)

{

    int dxy = 0;

    int emu = 0;

    src_x += motion_x >> 1;

    src_y += motion_y >> 1;

    /* WARNING: do no forget half pels */

    src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu?

    if (src_x != s->width)

        dxy |= motion_x & 1;

    src_y = av_clip(src_y, -16, s->height);

    if (src_y != s->height)

        dxy |= (motion_y & 1) << 1;

    src += src_y * s->linesize + src_x;

    if (s->unrestricted_mv) {

        if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) ||

            (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) {

            s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src,

                                     s->linesize, s->linesize,

                                     9, 9,

                                     src_x, src_y, s->h_edge_pos,

                                     s->v_edge_pos);

            src = s->sc.edge_emu_buffer;

            emu = 1;

        }

    }

    pix_op[dxy](dest, src, s->linesize, 8);

    return emu;

}


static void inline xan_wc3_copy_pixel_run(XanContext *s,

    int x, int y, int pixel_count, int motion_x, int motion_y)

{

    int stride;

    int line_inc;

    int curframe_index, prevframe_index;

    int curframe_x, prevframe_x;

    int width = s->avctx->width;

    unsigned char *palette_plane, *prev_palette_plane;

    unsigned char *y_plane, *u_plane, *v_plane;

    unsigned char *prev_y_plane, *prev_u_plane, *prev_v_plane;

    unsigned char *rgb_plane, *prev_rgb_plane;

    unsigned short *rgb16_plane, *prev_rgb16_plane;

    unsigned int *rgb32_plane, *prev_rgb32_plane;

    switch (s->avctx->pix_fmt) {

    case PIX_FMT_PAL8:

        palette_plane = s->current_frame.data[0];

        prev_palette_plane = s->last_frame.data[0];

        stride = s->current_frame.linesize[0];

        line_inc = stride - width;

        curframe_index = y * stride + x;

        curframe_x = x;

        prevframe_index = (y + motion_y) * stride + x + motion_x;

        prevframe_x = x + motion_x;

        while(pixel_count--) {

            palette_plane[curframe_index++] =

                prev_palette_plane[prevframe_index++];

            ADVANCE_CURFRAME_X();

            ADVANCE_PREVFRAME_X();

        }

        break;

    case PIX_FMT_RGB555:

    case PIX_FMT_RGB565:

        rgb16_plane = (unsigned short *)s->current_frame.data[0];

        prev_rgb16_plane = (unsigned short *)s->last_frame.data[0];

        stride = s->current_frame.linesize[0] / 2;

        line_inc = stride - width;

        curframe_index = y * stride + x;

        curframe_x = x;

        prevframe_index = (y + motion_y) * stride + x + motion_x;

        prevframe_x = x + motion_x;

        while(pixel_count--) {

            rgb16_plane[curframe_index++] =

                prev_rgb16_plane[prevframe_index++];

            ADVANCE_CURFRAME_X();

            ADVANCE_PREVFRAME_X();

        }

        break;

    case PIX_FMT_RGB24:

    case PIX_FMT_BGR24:

        rgb_plane = s->current_frame.data[0];

        prev_rgb_plane = s->last_frame.data[0];

        stride = s->current_frame.linesize[0];

        line_inc = stride - width * 3;

        curframe_index = y * stride + x * 3;

        curframe_x = x;

        prevframe_index = (y + motion_y) * stride +

            (3 * (x + motion_x));

        prevframe_x = x + motion_x;

        while(pixel_count--) {

            rgb_plane[curframe_index++] = prev_rgb_plane[prevframe_index++];

            rgb_plane[curframe_index++] = prev_rgb_plane[prevframe_index++];

            rgb_plane[curframe_index++] = prev_rgb_plane[prevframe_index++];

            ADVANCE_CURFRAME_X();

            ADVANCE_PREVFRAME_X();

        }

        break;

    case PIX_FMT_RGBA32:

        rgb32_plane = (unsigned int *)s->current_frame.data[0];

        prev_rgb32_plane = (unsigned int *)s->last_frame.data[0];

        stride = s->current_frame.linesize[0] / 4;

        line_inc = stride - width;

        curframe_index = y * stride + x;

        curframe_x = x;

        prevframe_index = (y + motion_y) * stride + x + motion_x;

        prevframe_x = x + motion_x;

        while(pixel_count--) {

            rgb32_plane[curframe_index++] =

                prev_rgb32_plane[prevframe_index++];

            ADVANCE_CURFRAME_X();

            ADVANCE_PREVFRAME_X();

        }

        break;

    case PIX_FMT_YUV444P:

        y_plane = s->current_frame.data[0];

        u_plane = s->current_frame.data[1];

        v_plane = s->current_frame.data[2];

        prev_y_plane = s->last_frame.data[0];

        prev_u_plane = s->last_frame.data[1];

        prev_v_plane = s->last_frame.data[2];

        stride = s->current_frame.linesize[0];

        line_inc = stride - width;

        curframe_index = y * stride + x;

        curframe_x = x;

        prevframe_index = (y + motion_y) * stride + x + motion_x;

        prevframe_x = x + motion_x;

        while(pixel_count--) {

            y_plane[curframe_index] = prev_y_plane[prevframe_index];

            u_plane[curframe_index] = prev_u_plane[prevframe_index];

            v_plane[curframe_index] = prev_v_plane[prevframe_index];

            curframe_index++;

            ADVANCE_CURFRAME_X();

            prevframe_index++;

            ADVANCE_PREVFRAME_X();

        }

        break;

    default:

        av_log(s->avctx, AV_LOG_ERROR, " Xan WC3: Unhandled colorspace\n");

        break;

    }

}


static int set_format(void *obj, const char *name, int fmt, int search_flags,

                      enum AVOptionType type, const char *desc, int nb_fmts)

{

    void *target_obj;

    const AVOption *o = av_opt_find2(obj, name, NULL, 0,

                                     search_flags, &target_obj);

    int min, max;

    const AVClass *class = *(AVClass **)obj;

    if (!o || !target_obj)

        return AVERROR_OPTION_NOT_FOUND;

    if (o->type != type) {

        av_log(obj, AV_LOG_ERROR,

               "The value set by option '%s' is not a %s format", name, desc);

        return AVERROR(EINVAL);

    }

#if LIBAVUTIL_VERSION_MAJOR < 54

    if (class->version && class->version < AV_VERSION_INT(52, 11, 100)) {

        min = -1;

        max = nb_fmts-1;

    } else

#endif

    {

        min = FFMIN(o->min, -1);

        max = FFMAX(o->max, nb_fmts-1);

    }

    if (fmt < min || fmt > max) {

        av_log(obj, AV_LOG_ERROR,

               "Value %d for parameter '%s' out of %s format range [%d - %d]\n",

               fmt, name, desc, min, max);

        return AVERROR(ERANGE);

    }

    *(int *)(((uint8_t *)target_obj) + o->offset) = fmt;

    return 0;

}


void ff_put_h264_qpel4_mc01_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_vt_qrt_4w_msa(src - (stride * 2), stride, dst, stride, 4, 0);

}


static void dump_cook_context(COOKContext *q, COOKextradata *e)

{

    //int i=0;

#define PRINT(a,b) av_log(NULL,AV_LOG_ERROR," %s = %d\n", a, b);

    av_log(NULL,AV_LOG_ERROR,"COOKextradata\n");

    av_log(NULL,AV_LOG_ERROR,"cookversion=%x\n",e->cookversion);

    if (e->cookversion > MONO_COOK2) {

        PRINT("js_subband_start",e->js_subband_start);

        PRINT("js_vlc_bits",e->js_vlc_bits);

    }

    av_log(NULL,AV_LOG_ERROR,"COOKContext\n");

    PRINT("nb_channels",q->nb_channels);

    PRINT("bit_rate",q->bit_rate);

    PRINT("sample_rate",q->sample_rate);

    PRINT("samples_per_channel",q->samples_per_channel);

    PRINT("samples_per_frame",q->samples_per_frame);

    PRINT("subbands",q->subbands);

    PRINT("random_state",q->random_state);

    PRINT("mlt_size",q->mlt_size);

    PRINT("js_subband_start",q->js_subband_start);

    PRINT("numvector_bits",q->numvector_bits);

    PRINT("numvector_size",q->numvector_size);

    PRINT("total_subbands",q->total_subbands);

    PRINT("frame_reorder_counter",q->frame_reorder_counter);

    PRINT("frame_reorder_index_size",q->frame_reorder_index_size);

}


static void ffm_set_write_index(AVFormatContext *s, int64_t pos,

                                int64_t file_size)

{

    FFMContext *ffm = s->priv_data;

    ffm->write_index = pos;

    ffm->file_size = file_size;

}


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

{

    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);

    uc->realize = usb_msd_realize_bot;

    uc->attached_settable = true;

}


uint64_t HELPER(get_cp_reg64)(CPUARMState *env, void *rip)

{

    const ARMCPRegInfo *ri = rip;

    return ri->readfn(env, ri);

}


static USBDevice *usb_try_create_simple(USBBus *bus, const char *name,

                                        Error **errp)

{

    Error *err = NULL;

    USBDevice *dev;

    dev = USB_DEVICE(qdev_try_create(&bus->qbus, name));

    if (!dev) {

        error_setg(errp, "Failed to create USB device '%s'", name);

        return NULL;

    }

    object_property_set_bool(OBJECT(dev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        error_prepend(errp, "Failed to initialize USB device '%s': ",

                      name);

        object_unparent(OBJECT(dev));

        return NULL;

    }

    return dev;

}


static int decode_chunks(AVCodecContext *avctx,

                         AVFrame *picture, int *got_output,

                         const uint8_t *buf, int buf_size)

{

    Mpeg1Context *s = avctx->priv_data;

    MpegEncContext *s2 = &s->mpeg_enc_ctx;

    const uint8_t *buf_ptr = buf;

    const uint8_t *buf_end = buf + buf_size;

    int ret, input_size;

    int last_code = 0;

    for (;;) {

        /* find next start code */

        uint32_t start_code = -1;

        buf_ptr = avpriv_mpv_find_start_code(buf_ptr, buf_end, &start_code);

        if (start_code > 0x1ff) {

            if (s2->pict_type != AV_PICTURE_TYPE_B || avctx->skip_frame <= AVDISCARD_DEFAULT) {

                if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {

                    int i;

                    avctx->execute(avctx, slice_decode_thread,  &s2->thread_context[0], NULL, s->slice_count, sizeof(void*));

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

                        s2->error_count += s2->thread_context[i]->error_count;

                }

                if (CONFIG_MPEG_VDPAU_DECODER && avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU)

                    ff_vdpau_mpeg_picture_complete(s2, buf, buf_size, s->slice_count);

                if (slice_end(avctx, picture)) {

                    if (s2->last_picture_ptr || s2->low_delay) //FIXME merge with the stuff in mpeg_decode_slice

                        *got_output = 1;

                }

            }

            s2->pict_type = 0;

            return FFMAX(0, buf_ptr - buf - s2->parse_context.last_index);

        }

        input_size = buf_end - buf_ptr;

        if (avctx->debug & FF_DEBUG_STARTCODE) {

            av_log(avctx, AV_LOG_DEBUG, "%3X at %td left %d\n", start_code, buf_ptr-buf, input_size);

        }

        /* prepare data for next start code */

        switch (start_code) {

        case SEQ_START_CODE:

            if (last_code == 0) {

                mpeg1_decode_sequence(avctx, buf_ptr, input_size);

                s->sync=1;

            } else {

                av_log(avctx, AV_LOG_ERROR, "ignoring SEQ_START_CODE after %X\n", last_code);

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return AVERROR_INVALIDDATA;

            }

            break;

        case PICTURE_START_CODE:

            if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE) && s->slice_count) {

                int i;

                avctx->execute(avctx, slice_decode_thread,

                               s2->thread_context, NULL,

                               s->slice_count, sizeof(void*));

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

                    s2->error_count += s2->thread_context[i]->error_count;

                s->slice_count = 0;

            }

            if (last_code == 0 || last_code == SLICE_MIN_START_CODE) {

                ret = mpeg_decode_postinit(avctx);

                if (ret < 0) {

                    av_log(avctx, AV_LOG_ERROR, "mpeg_decode_postinit() failure\n");

                    return ret;

                }

                /* we have a complete image: we try to decompress it */

                if (mpeg1_decode_picture(avctx, buf_ptr, input_size) < 0)

                    s2->pict_type = 0;

                s2->first_slice = 1;

                last_code = PICTURE_START_CODE;

            } else {

                av_log(avctx, AV_LOG_ERROR, "ignoring pic after %X\n", last_code);

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return AVERROR_INVALIDDATA;

            }

            break;

        case EXT_START_CODE:

            init_get_bits(&s2->gb, buf_ptr, input_size*8);

            switch (get_bits(&s2->gb, 4)) {

            case 0x1:

                if (last_code == 0) {

                mpeg_decode_sequence_extension(s);

                } else {

                    av_log(avctx, AV_LOG_ERROR, "ignoring seq ext after %X\n", last_code);

                    if (avctx->err_recognition & AV_EF_EXPLODE)

                        return AVERROR_INVALIDDATA;

                }

                break;

            case 0x2:

                mpeg_decode_sequence_display_extension(s);

                break;

            case 0x3:

                mpeg_decode_quant_matrix_extension(s2);

                break;

            case 0x7:

                mpeg_decode_picture_display_extension(s);

                break;

            case 0x8:

                if (last_code == PICTURE_START_CODE) {

                    mpeg_decode_picture_coding_extension(s);

                } else {

                    av_log(avctx, AV_LOG_ERROR, "ignoring pic cod ext after %X\n", last_code);

                    if (avctx->err_recognition & AV_EF_EXPLODE)

                        return AVERROR_INVALIDDATA;

                }

                break;

            }

            break;

        case USER_START_CODE:

            mpeg_decode_user_data(avctx, buf_ptr, input_size);

            break;

        case GOP_START_CODE:

            if (last_code == 0) {

                s2->first_field=0;

                mpeg_decode_gop(avctx, buf_ptr, input_size);

                s->sync=1;

            } else {

                av_log(avctx, AV_LOG_ERROR, "ignoring GOP_START_CODE after %X\n", last_code);

                if (avctx->err_recognition & AV_EF_EXPLODE)

                    return AVERROR_INVALIDDATA;

            }

            break;

        default:

            if (start_code >= SLICE_MIN_START_CODE &&

                start_code <= SLICE_MAX_START_CODE && last_code != 0) {

                const int field_pic = s2->picture_structure != PICT_FRAME;

                int mb_y = (start_code - SLICE_MIN_START_CODE) << field_pic;

                last_code = SLICE_MIN_START_CODE;

                if (s2->picture_structure == PICT_BOTTOM_FIELD)

                    mb_y++;

                if (mb_y >= s2->mb_height) {

                    av_log(s2->avctx, AV_LOG_ERROR, "slice below image (%d >= %d)\n", mb_y, s2->mb_height);

                    return -1;

                }

                if (s2->last_picture_ptr == NULL) {

                /* Skip B-frames if we do not have reference frames and gop is not closed */

                    if (s2->pict_type == AV_PICTURE_TYPE_B) {

                        if (!s->closed_gop)

                            break;

                    }

                }

                if (s2->pict_type == AV_PICTURE_TYPE_I)

                    s->sync=1;

                if (s2->next_picture_ptr == NULL) {

                /* Skip P-frames if we do not have a reference frame or we have an invalid header. */

                    if (s2->pict_type == AV_PICTURE_TYPE_P && !s->sync) break;

                }

                if ((avctx->skip_frame >= AVDISCARD_NONREF && s2->pict_type == AV_PICTURE_TYPE_B) ||

                    (avctx->skip_frame >= AVDISCARD_NONKEY && s2->pict_type != AV_PICTURE_TYPE_I) ||

                     avctx->skip_frame >= AVDISCARD_ALL)

                    break;

                if (!s->mpeg_enc_ctx_allocated)

                    break;

                if (s2->codec_id == AV_CODEC_ID_MPEG2VIDEO) {

                    if (mb_y < avctx->skip_top || mb_y >= s2->mb_height - avctx->skip_bottom)

                        break;

                }

                if (!s2->pict_type) {

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

                    if (avctx->err_recognition & AV_EF_EXPLODE)

                        return AVERROR_INVALIDDATA;

                    break;

                }

                if (s2->first_slice) {

                    s2->first_slice = 0;

                    if (mpeg_field_start(s2, buf, buf_size) < 0)

                        return -1;

                }

                if (!s2->current_picture_ptr) {

                    av_log(avctx, AV_LOG_ERROR, "current_picture not initialized\n");

                    return AVERROR_INVALIDDATA;

                }

                if (avctx->codec->capabilities & CODEC_CAP_HWACCEL_VDPAU) {

                    s->slice_count++;

                    break;

                }

                if (HAVE_THREADS && (avctx->active_thread_type & FF_THREAD_SLICE)) {

                    int threshold = (s2->mb_height * s->slice_count +

                                     s2->slice_context_count / 2) /

                                    s2->slice_context_count;

                    if (threshold <= mb_y) {

                        MpegEncContext *thread_context = s2->thread_context[s->slice_count];

                        thread_context->start_mb_y = mb_y;

                        thread_context->end_mb_y   = s2->mb_height;

                        if (s->slice_count) {

                            s2->thread_context[s->slice_count-1]->end_mb_y = mb_y;

                            ff_update_duplicate_context(thread_context, s2);

                        }

                        init_get_bits(&thread_context->gb, buf_ptr, input_size*8);

                        s->slice_count++;

                    }

                    buf_ptr += 2; // FIXME add minimum number of bytes per slice

                } else {

                    ret = mpeg_decode_slice(s2, mb_y, &buf_ptr, input_size);

                    emms_c();

                    if (ret < 0) {

                        if (avctx->err_recognition & AV_EF_EXPLODE)

                            return ret;

                        if (s2->resync_mb_x >= 0 && s2->resync_mb_y >= 0)

                            ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x, s2->mb_y, ER_AC_ERROR | ER_DC_ERROR | ER_MV_ERROR);

                    } else {

                        ff_er_add_slice(s2, s2->resync_mb_x, s2->resync_mb_y, s2->mb_x-1, s2->mb_y, ER_AC_END | ER_DC_END | ER_MV_END);

                    }

                }

            }

            break;

        }

    }

}


static inline int mdec_decode_block_intra(MDECContext *a, int16_t *block, int n)

{

    int level, diff, i, j, run;

    int component;

    RLTable *rl = &ff_rl_mpeg1;

    uint8_t * const scantable = a->scantable.permutated;

    const uint16_t *quant_matrix = ff_mpeg1_default_intra_matrix;

    const int qscale = a->qscale;

    /* DC coefficient */

    if (a->version == 2) {

        block[0] = 2 * get_sbits(&a->gb, 10) + 1024;

    } else {

        component = (n <= 3 ? 0 : n - 4 + 1);

        diff = decode_dc(&a->gb, component);

        if (diff >= 0xffff)

            return AVERROR_INVALIDDATA;

        a->last_dc[component] += diff;

        block[0] = a->last_dc[component] << 3;

    }

    i = 0;

    {

        OPEN_READER(re, &a->gb);

        /* now quantify & encode AC coefficients */

        for (;;) {

            UPDATE_CACHE(re, &a->gb);

            GET_RL_VLC(level, run, re, &a->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);

            if (level == 127) {

                break;

            } else if (level != 0) {

                i += run;

                if (i > 63) {

                    av_log(a->avctx, AV_LOG_ERROR,

                           "ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);

                    return AVERROR_INVALIDDATA;

                }

                j     = scantable[i];

                level = (level * qscale * quant_matrix[j]) >> 3;

                level = (level ^ SHOW_SBITS(re, &a->gb, 1)) - SHOW_SBITS(re, &a->gb, 1);

                LAST_SKIP_BITS(re, &a->gb, 1);

            } else {

                /* escape */

                run = SHOW_UBITS(re, &a->gb, 6)+1; LAST_SKIP_BITS(re, &a->gb, 6);

                UPDATE_CACHE(re, &a->gb);

                level = SHOW_SBITS(re, &a->gb, 10); SKIP_BITS(re, &a->gb, 10);

                i += run;

                if (i > 63) {

                    av_log(a->avctx, AV_LOG_ERROR,

                           "ac-tex damaged at %d %d\n", a->mb_x, a->mb_y);

                    return AVERROR_INVALIDDATA;

                }

                j = scantable[i];

                if (level < 0) {

                    level = -level;

                    level = (level * qscale * quant_matrix[j]) >> 3;

                    level = (level - 1) | 1;

                    level = -level;

                } else {

                    level = (level * qscale * quant_matrix[j]) >> 3;

                    level = (level - 1) | 1;

                }

            }

            block[j] = level;

        }

        CLOSE_READER(re, &a->gb);

    }

    a->block_last_index[n] = i;

    return 0;

}


static int raw_open_common(BlockDriverState *bs, QDict *options,
                           int bdrv_flags, int open_flags, Error **errp)
{
    BDRVRawState *s = bs->opaque;
    QemuOpts *opts;
    Error *local_err = NULL;
    const char *filename = NULL;
    const char *str;
    BlockdevAioOptions aio, aio_default;
    int fd, ret;
    struct stat st;
    OnOffAuto locking;
    opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    filename = qemu_opt_get(opts, "filename");
    ret = raw_normalize_devicepath(&filename);
    if (ret != 0) {
        error_setg_errno(errp, -ret, "Could not normalize device path");
    aio_default = (bdrv_flags & BDRV_O_NATIVE_AIO)
                  ? BLOCKDEV_AIO_OPTIONS_NATIVE
                  : BLOCKDEV_AIO_OPTIONS_THREADS;
    aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
                          qemu_opt_get(opts, "aio"),
                          aio_default, &local_err);
    s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
    locking = qapi_enum_parse(&OnOffAuto_lookup,
                              qemu_opt_get(opts, "locking"),
                              ON_OFF_AUTO_AUTO, &local_err);
    switch (locking) {
    case ON_OFF_AUTO_ON:
        s->use_lock = true;
        if (!qemu_has_ofd_lock()) {
            fprintf(stderr,
                    "File lock requested but OFD locking syscall is "
                    "unavailable, falling back to POSIX file locks.\n"
                    "Due to the implementation, locks can be lost "
                    "unexpectedly.\n");
        break;
    case ON_OFF_AUTO_OFF:
        s->use_lock = false;
        break;
    case ON_OFF_AUTO_AUTO:
        s->use_lock = qemu_has_ofd_lock();
        break;
    default:
        abort();
    s->open_flags = open_flags;
    raw_parse_flags(bdrv_flags, &s->open_flags);
    s->fd = -1;
    fd = qemu_open(filename, s->open_flags, 0644);
    if (fd < 0) {
        ret = -errno;
        error_setg_errno(errp, errno, "Could not open '%s'", filename);
        if (ret == -EROFS) {
            ret = -EACCES;
    s->fd = fd;
    s->lock_fd = -1;
    if (s->use_lock) {
        fd = qemu_open(filename, s->open_flags);
        if (fd < 0) {
            ret = -errno;
            error_setg_errno(errp, errno, "Could not open '%s' for locking",
                             filename);
            qemu_close(s->fd);
        s->lock_fd = fd;
    s->perm = 0;
    s->shared_perm = BLK_PERM_ALL;
#ifdef CONFIG_LINUX_AIO
     /* Currently Linux does AIO only for files opened with O_DIRECT */
    if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {
        error_setg(errp, "aio=native was specified, but it requires "
                         "cache.direct=on, which was not specified.");
#else
    if (s->use_linux_aio) {
        error_setg(errp, "aio=native was specified, but is not supported "
                         "in this build.");
#endif /* !defined(CONFIG_LINUX_AIO) */
    s->has_discard = true;
    s->has_write_zeroes = true;
    bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
    if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
        s->needs_alignment = true;
    if (fstat(s->fd, &st) < 0) {
        ret = -errno;
        error_setg_errno(errp, errno, "Could not stat file");
    if (S_ISREG(st.st_mode)) {
        s->discard_zeroes = true;
        s->has_fallocate = true;
    if (S_ISBLK(st.st_mode)) {
#ifdef BLKDISCARDZEROES
        unsigned int arg;
        if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
            s->discard_zeroes = true;
#endif
#ifdef __linux__
        /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
         * not rely on the contents of discarded blocks unless using O_DIRECT.
         * Same for BLKZEROOUT.
         */
        if (!(bs->open_flags & BDRV_O_NOCACHE)) {
            s->discard_zeroes = false;
            s->has_write_zeroes = false;
#endif
#ifdef __FreeBSD__
    if (S_ISCHR(st.st_mode)) {
        /*
         * The file is a char device (disk), which on FreeBSD isn't behind
         * a pager, so force all requests to be aligned. This is needed
         * so QEMU makes sure all IO operations on the device are aligned
         * to sector size, or else FreeBSD will reject them with EINVAL.
         */
        s->needs_alignment = true;
#endif
#ifdef CONFIG_XFS
    if (platform_test_xfs_fd(s->fd)) {
        s->is_xfs = true;
#endif
    ret = 0;
fail:
    if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
        unlink(filename);
    qemu_opts_del(opts);
    return ret;


av_cold int ff_vp8_decode_init(AVCodecContext *avctx)

{

    VP8Context *s = avctx->priv_data;

    int ret;

    s->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    avctx->internal->allocate_progress = 1;

    ff_videodsp_init(&s->vdsp, 8);

    ff_h264_pred_init(&s->hpc, AV_CODEC_ID_VP8, 8, 1);

    ff_vp8dsp_init(&s->vp8dsp);

    if ((ret = vp8_init_frames(s)) < 0) {

        ff_vp8_decode_free(avctx);

        return ret;

    }

    return 0;

}


static inline void json_print_item_str(WriterContext *wctx,

                                       const char *key, const char *value,

                                       const char *indent)

{

    char *key_esc = json_escape_str(key);

    char *value_esc = json_escape_str(value);

    printf("%s\"%s\": \"%s\"", indent,

           key_esc   ? key_esc   : "",

           value_esc ? value_esc : "");

    av_free(key_esc);

    av_free(value_esc);

}


static void handle_keydown(SDL_Event *ev)
{
    int mod_state, win;
    struct sdl2_console *scon = get_scon_from_window(ev->key.windowID);
    if (alt_grab) {
        mod_state = (SDL_GetModState() & (gui_grab_code | KMOD_LSHIFT)) ==
            (gui_grab_code | KMOD_LSHIFT);
    } else if (ctrl_grab) {
        mod_state = (SDL_GetModState() & KMOD_RCTRL) == KMOD_RCTRL;
    } else {
        mod_state = (SDL_GetModState() & gui_grab_code) == gui_grab_code;
    gui_key_modifier_pressed = mod_state;
    if (gui_key_modifier_pressed) {
        switch (ev->key.keysym.scancode) {
        case SDL_SCANCODE_2:
        case SDL_SCANCODE_3:
        case SDL_SCANCODE_4:
        case SDL_SCANCODE_5:
        case SDL_SCANCODE_6:
        case SDL_SCANCODE_7:
        case SDL_SCANCODE_8:
        case SDL_SCANCODE_9:
            win = ev->key.keysym.scancode - SDL_SCANCODE_1;
            if (win < sdl2_num_outputs) {
                sdl2_console[win].hidden = !sdl2_console[win].hidden;
                if (sdl2_console[win].real_window) {
                    if (sdl2_console[win].hidden) {
                        SDL_HideWindow(sdl2_console[win].real_window);
                    } else {
                        SDL_ShowWindow(sdl2_console[win].real_window);
                gui_keysym = 1;
            break;
        case SDL_SCANCODE_F:
            toggle_full_screen(scon);
            gui_keysym = 1;
            break;
        case SDL_SCANCODE_U:
            sdl2_window_destroy(scon);
            sdl2_window_create(scon);
            if (!scon->opengl) {
                /* re-create scon->texture */
                sdl2_2d_switch(&scon->dcl, scon->surface);
            gui_keysym = 1;
            break;
#if 0
        case SDL_SCANCODE_KP_PLUS:
        case SDL_SCANCODE_KP_MINUS:
            if (!gui_fullscreen) {
                int scr_w, scr_h;
                int width, height;
                SDL_GetWindowSize(scon->real_window, &scr_w, &scr_h);
                width = MAX(scr_w + (ev->key.keysym.scancode ==
                                     SDL_SCANCODE_KP_PLUS ? 50 : -50),
                            160);
                height = (surface_height(scon->surface) * width) /
                    surface_width(scon->surface);
                fprintf(stderr, "%s: scale to %dx%d\n",
                        __func__, width, height);
                sdl_scale(scon, width, height);
                sdl2_redraw(scon);
                gui_keysym = 1;
#endif
        default:
            break;
    if (!gui_keysym) {
        sdl2_process_key(scon, &ev->key);


AVRational ff_choose_timebase(AVFormatContext *s, AVStream *st, int min_precission)

{

    AVRational q;

    int j;

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

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

    } else {

        q = st->codec->time_base;

    }

    for (j=2; j<2000; j+= 1+(j>2))

        while (q.den / q.num < min_precission && q.num % j == 0)

            q.num /= j;

    while (q.den / q.num < min_precission && q.den < (1<<24))

        q.den <<= 1;

    return q;

}


static int pcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    PCMDecode *s = avctx->priv_data;

    int c, n;

    short *samples;

    uint8_t *src, *src2[MAX_CHANNELS];

    samples = data;

    src = buf;

    n= av_get_bits_per_sample(avctx->codec_id)/8;

    if((n && buf_size % n) || avctx->channels > MAX_CHANNELS){

        av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n");

        return -1;

    }

    buf_size= FFMIN(buf_size, *data_size/2);

    *data_size=0;

    n = buf_size/avctx->channels;

    for(c=0;c<avctx->channels;c++)

        src2[c] = &src[c*n];

    switch(avctx->codec->id) {

    case CODEC_ID_PCM_S32LE:

        decode_to16(4, 1, 0, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_S32BE:

        decode_to16(4, 0, 0, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_U32LE:

        decode_to16(4, 1, 1, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_U32BE:

        decode_to16(4, 0, 1, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_S24LE:

        decode_to16(3, 1, 0, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_S24BE:

        decode_to16(3, 0, 0, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_U24LE:

        decode_to16(3, 1, 1, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_U24BE:

        decode_to16(3, 0, 1, &src, &samples, buf_size);

        break;

    case CODEC_ID_PCM_S24DAUD:

        n = buf_size / 3;

        for(;n>0;n--) {

          uint32_t v = bytestream_get_be24(&src);

          v >>= 4; // sync flags are here

          *samples++ = ff_reverse[(v >> 8) & 0xff] +

                       (ff_reverse[v & 0xff] << 8);

        }

        break;

    case CODEC_ID_PCM_S16LE:

        n = buf_size >> 1;

        for(;n>0;n--) {

            *samples++ = bytestream_get_le16(&src);

        }

        break;

    case CODEC_ID_PCM_S16LE_PLANAR:

        for(n>>=1;n>0;n--)

            for(c=0;c<avctx->channels;c++)

                *samples++ = bytestream_get_le16(&src2[c]);

        src = src2[avctx->channels-1];

        break;

    case CODEC_ID_PCM_S16BE:

        n = buf_size >> 1;

        for(;n>0;n--) {

            *samples++ = bytestream_get_be16(&src);

        }

        break;

    case CODEC_ID_PCM_U16LE:

        n = buf_size >> 1;

        for(;n>0;n--) {

            *samples++ = bytestream_get_le16(&src) - 0x8000;

        }

        break;

    case CODEC_ID_PCM_U16BE:

        n = buf_size >> 1;

        for(;n>0;n--) {

            *samples++ = bytestream_get_be16(&src) - 0x8000;

        }

        break;

    case CODEC_ID_PCM_S8:

        n = buf_size;

        for(;n>0;n--) {

            *samples++ = *src++ << 8;

        }

        break;

    case CODEC_ID_PCM_U8:

        n = buf_size;

        for(;n>0;n--) {

            *samples++ = ((int)*src++ - 128) << 8;

        }

        break;

    case CODEC_ID_PCM_ZORK:

        n = buf_size;

        for(;n>0;n--) {

            int x= *src++;

            if(x&128) x-= 128;

            else      x = -x;

            *samples++ = x << 8;

        }

        break;

    case CODEC_ID_PCM_ALAW:

    case CODEC_ID_PCM_MULAW:

        n = buf_size;

        for(;n>0;n--) {

            *samples++ = s->table[*src++];

        }

        break;

    default:

        return -1;

    }

    *data_size = (uint8_t *)samples - (uint8_t *)data;

    return src - buf;

}


static int h264_slice_init(H264Context *h, H264SliceContext *sl,

                           const H2645NAL *nal)

{

    int i, j, ret = 0;

    if (h->picture_idr && nal->type != H264_NAL_IDR_SLICE) {

        av_log(h->avctx, AV_LOG_ERROR, "Invalid mix of IDR and non-IDR slices\n");

        return AVERROR_INVALIDDATA;

    }

    av_assert1(h->mb_num == h->mb_width * h->mb_height);

    if (sl->first_mb_addr << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num ||

        sl->first_mb_addr >= h->mb_num) {

        av_log(h->avctx, AV_LOG_ERROR, "first_mb_in_slice overflow\n");

        return AVERROR_INVALIDDATA;

    }

    sl->resync_mb_x = sl->mb_x =  sl->first_mb_addr % h->mb_width;

    sl->resync_mb_y = sl->mb_y = (sl->first_mb_addr / h->mb_width) <<

                                 FIELD_OR_MBAFF_PICTURE(h);

    if (h->picture_structure == PICT_BOTTOM_FIELD)

        sl->resync_mb_y = sl->mb_y = sl->mb_y + 1;

    av_assert1(sl->mb_y < h->mb_height);

    ret = ff_h264_build_ref_list(h, sl);

    if (ret < 0)

        return ret;

    if (h->ps.pps->weighted_bipred_idc == 2 &&

        sl->slice_type_nos == AV_PICTURE_TYPE_B) {

        implicit_weight_table(h, sl, -1);

        if (FRAME_MBAFF(h)) {

            implicit_weight_table(h, sl, 0);

            implicit_weight_table(h, sl, 1);

        }

    }

    if (sl->slice_type_nos == AV_PICTURE_TYPE_B && !sl->direct_spatial_mv_pred)

        ff_h264_direct_dist_scale_factor(h, sl);

    ff_h264_direct_ref_list_init(h, sl);

    if (h->avctx->skip_loop_filter >= AVDISCARD_ALL ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY &&

         h->nal_unit_type != H264_NAL_IDR_SLICE) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONINTRA &&

         sl->slice_type_nos != AV_PICTURE_TYPE_I) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR  &&

         sl->slice_type_nos == AV_PICTURE_TYPE_B) ||

        (h->avctx->skip_loop_filter >= AVDISCARD_NONREF &&

         nal->ref_idc == 0))

        sl->deblocking_filter = 0;

    if (sl->deblocking_filter == 1 && h->nb_slice_ctx > 1) {

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

            /* Cheat slightly for speed:

             * Do not bother to deblock across slices. */

            sl->deblocking_filter = 2;

        } else {

            h->postpone_filter = 1;

        }

    }

    sl->qp_thresh = 15 -

                   FFMIN(sl->slice_alpha_c0_offset, sl->slice_beta_offset) -

                   FFMAX3(0,

                          h->ps.pps->chroma_qp_index_offset[0],

                          h->ps.pps->chroma_qp_index_offset[1]) +

                   6 * (h->ps.sps->bit_depth_luma - 8);

    sl->slice_num       = ++h->current_slice;

    if (sl->slice_num)

        h->slice_row[(sl->slice_num-1)&(MAX_SLICES-1)]= sl->resync_mb_y;

    if (   h->slice_row[sl->slice_num&(MAX_SLICES-1)] + 3 >= sl->resync_mb_y

        && h->slice_row[sl->slice_num&(MAX_SLICES-1)] <= sl->resync_mb_y

        && sl->slice_num >= MAX_SLICES) {

        //in case of ASO this check needs to be updated depending on how we decide to assign slice numbers in this case

        av_log(h->avctx, AV_LOG_WARNING, "Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\n", sl->slice_num, MAX_SLICES);

    }

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

        int id_list[16];

        int *ref2frm = h->ref2frm[sl->slice_num & (MAX_SLICES - 1)][j];

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

            id_list[i] = 60;

            if (j < sl->list_count && i < sl->ref_count[j] &&

                sl->ref_list[j][i].parent->f->buf[0]) {

                int k;

                AVBuffer *buf = sl->ref_list[j][i].parent->f->buf[0]->buffer;

                for (k = 0; k < h->short_ref_count; k++)

                    if (h->short_ref[k]->f->buf[0]->buffer == buf) {

                        id_list[i] = k;

                        break;

                    }

                for (k = 0; k < h->long_ref_count; k++)

                    if (h->long_ref[k] && h->long_ref[k]->f->buf[0]->buffer == buf) {

                        id_list[i] = h->short_ref_count + k;

                        break;

                    }

            }

        }

        ref2frm[0] =

        ref2frm[1] = -1;

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

            ref2frm[i + 2] = 4 * id_list[i] + (sl->ref_list[j][i].reference & 3);

        ref2frm[18 + 0] =

        ref2frm[18 + 1] = -1;

        for (i = 16; i < 48; i++)

            ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] +

                             (sl->ref_list[j][i].reference & 3);

    }

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

        av_log(h->avctx, AV_LOG_DEBUG,

               "slice:%d %s mb:%d %c%s%s frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\n",

               sl->slice_num,

               (h->picture_structure == PICT_FRAME ? "F" : h->picture_structure == PICT_TOP_FIELD ? "T" : "B"),

               sl->mb_y * h->mb_width + sl->mb_x,

               av_get_picture_type_char(sl->slice_type),

               sl->slice_type_fixed ? " fix" : "",

               nal->type == H264_NAL_IDR_SLICE ? " IDR" : "",

               h->poc.frame_num,

               h->cur_pic_ptr->field_poc[0],

               h->cur_pic_ptr->field_poc[1],

               sl->ref_count[0], sl->ref_count[1],

               sl->qscale,

               sl->deblocking_filter,

               sl->slice_alpha_c0_offset, sl->slice_beta_offset,

               sl->pwt.use_weight,

               sl->pwt.use_weight == 1 && sl->pwt.use_weight_chroma ? "c" : "",

               sl->slice_type == AV_PICTURE_TYPE_B ? (sl->direct_spatial_mv_pred ? "SPAT" : "TEMP") : "");

    }

    return 0;

}


RockerSwitch *qmp_query_rocker(const char *name, Error **errp)

{

    RockerSwitch *rocker = g_malloc0(sizeof(*rocker));

    Rocker *r;

    r = rocker_find(name);

    if (!r) {

        error_set(errp, ERROR_CLASS_GENERIC_ERROR,

                  "rocker %s not found", name);

        return NULL;

    }

    rocker->name = g_strdup(r->name);

    rocker->id = r->switch_id;

    rocker->ports = r->fp_ports;

    return rocker;

}


static int init_dimensions(H264Context *h)

{

    int width  = h->width  - (h->sps.crop_right + h->sps.crop_left);

    int height = h->height - (h->sps.crop_top   + h->sps.crop_bottom);

    /* handle container cropping */

    if (FFALIGN(h->avctx->width,  16) == FFALIGN(width,  16) &&

        FFALIGN(h->avctx->height, 16) == FFALIGN(height, 16)) {

        width  = h->avctx->width;

        height = h->avctx->height;

    }

    if (width <= 0 || height <= 0) {

        av_log(h->avctx, AV_LOG_ERROR, "Invalid cropped dimensions: %dx%d.\n",

               width, height);

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

            return AVERROR_INVALIDDATA;

        av_log(h->avctx, AV_LOG_WARNING, "Ignoring cropping information.\n");

        h->sps.crop_bottom =

        h->sps.crop_top    =

        h->sps.crop_right  =

        h->sps.crop_left   =

        h->sps.crop        = 0;

        width  = h->width;

        height = h->height;

    }

    h->avctx->coded_width  = h->width;

    h->avctx->coded_height = h->height;

    h->avctx->width        = width;

    h->avctx->height       = height;

    return 0;

}


static inline CopyRet copy_frame(AVCodecContext *avctx,

                                 BC_DTS_PROC_OUT *output,

                                 void *data, int *data_size,

                                 uint8_t second_field)

{

    BC_STATUS ret;

    BC_DTS_STATUS decoder_status;

    uint8_t is_paff;

    uint8_t next_frame_same;

    uint8_t interlaced;

    CHDContext *priv = avctx->priv_data;

    int64_t pkt_pts  = AV_NOPTS_VALUE;

    uint8_t pic_type = 0;

    uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==

                           VDEC_FLAG_BOTTOMFIELD;

    uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);

    int width    = output->PicInfo.width;

    int height   = output->PicInfo.height;

    int bwidth;

    uint8_t *src = output->Ybuff;

    int sStride;

    uint8_t *dst;

    int dStride;

    if (output->PicInfo.timeStamp != 0) {

        OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);

        if (node) {

            pkt_pts = node->reordered_opaque;

            pic_type = node->pic_type;

            av_free(node);

        } else {

            /*

             * We will encounter a situation where a timestamp cannot be

             * popped if a second field is being returned. In this case,

             * each field has the same timestamp and the first one will

             * cause it to be popped. To keep subsequent calculations

             * simple, pic_type should be set a FIELD value - doesn't

             * matter which, but I chose BOTTOM.

             */

            pic_type = PICT_BOTTOM_FIELD;

        }

        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",

               output->PicInfo.timeStamp);

        av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",

               pic_type);

    }

    ret = DtsGetDriverStatus(priv->dev, &decoder_status);

    if (ret != BC_STS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR,

               "CrystalHD: GetDriverStatus failed: %u\n", ret);

       return RET_ERROR;

    }

    is_paff           = ASSUME_PAFF_OVER_MBAFF ||

                        !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC);

    next_frame_same   = output->PicInfo.picture_number ==

                        (decoder_status.picNumFlags & ~0x40000000);

    interlaced        = ((output->PicInfo.flags &

                          VDEC_FLAG_INTERLACED_SRC) && is_paff) ||

                         next_frame_same || bottom_field || second_field;

    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: next_frame_same: %u | %u | %u\n",

           next_frame_same, output->PicInfo.picture_number,

           decoder_status.picNumFlags & ~0x40000000);

    if (priv->pic.data[0] && !priv->need_second_field)

        avctx->release_buffer(avctx, &priv->pic);

    priv->need_second_field = interlaced && !priv->need_second_field;

    priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |

                             FF_BUFFER_HINTS_REUSABLE;

    if (!priv->pic.data[0]) {

        if (avctx->get_buffer(avctx, &priv->pic) < 0) {

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

            return RET_ERROR;

        }

    }

    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);

    if (priv->is_70012) {

        int pStride;

        if (width <= 720)

            pStride = 720;

        else if (width <= 1280)

            pStride = 1280;

        else if (width <= 1080)

            pStride = 1080;

        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);

    } else {

        sStride = bwidth;

    }

    dStride = priv->pic.linesize[0];

    dst     = priv->pic.data[0];

    av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");

    if (interlaced) {

        int dY = 0;

        int sY = 0;

        height /= 2;

        if (bottom_field) {

            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");

            dY = 1;

        } else {

            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");

            dY = 0;

        }

        for (sY = 0; sY < height; dY++, sY++) {

            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);

            dY++;

        }

    } else {

        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);

    }

    priv->pic.interlaced_frame = interlaced;

    if (interlaced)

        priv->pic.top_field_first = !bottom_first;

    priv->pic.pkt_pts = pkt_pts;

    if (!priv->need_second_field) {

        *data_size       = sizeof(AVFrame);

        *(AVFrame *)data = priv->pic;

    }

    if (ASSUME_TWO_INPUTS_ONE_OUTPUT &&

        output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) {

        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");

        return RET_SKIP_NEXT_COPY;

    }

    /*

     * Testing has shown that in all cases where we don't want to return the

     * full frame immediately, VDEC_FLAG_UNKNOWN_SRC is set.

     */

    return priv->need_second_field &&

           !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ?

           RET_COPY_NEXT_FIELD : RET_OK;

}


static int x11grab_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    X11GrabContext *s = s1->priv_data;

    Display *dpy      = s->dpy;

    XImage *image     = s->image;

    int x_off         = s->x_off;

    int y_off         = s->y_off;

    int follow_mouse  = s->follow_mouse;

    int screen;

    Window root;

    int64_t curtime, delay;

    struct timespec ts;

    /* Calculate the time of the next frame */

    s->time_frame += INT64_C(1000000);

    /* wait based on the frame rate */

    for (;;) {

        curtime = av_gettime();

        delay   = s->time_frame * av_q2d(s->time_base) - curtime;

        if (delay <= 0) {

            if (delay < INT64_C(-1000000) * av_q2d(s->time_base))

                s->time_frame += INT64_C(1000000);

            break;

        }

        ts.tv_sec  = delay / 1000000;

        ts.tv_nsec = (delay % 1000000) * 1000;

        nanosleep(&ts, NULL);

    }

    av_init_packet(pkt);

    pkt->data = image->data;

    pkt->size = s->frame_size;

    pkt->pts  = curtime;

    screen = DefaultScreen(dpy);

    root   = RootWindow(dpy, screen);

    if (follow_mouse) {

        int screen_w, screen_h;

        int pointer_x, pointer_y, _;

        Window w;

        screen_w = DisplayWidth(dpy, screen);

        screen_h = DisplayHeight(dpy, screen);

        XQueryPointer(dpy, root, &w, &w, &pointer_x, &pointer_y, &_, &_, &_);

        if (follow_mouse == -1) {

            // follow the mouse, put it at center of grabbing region

            x_off += pointer_x - s->width / 2 - x_off;

            y_off += pointer_y - s->height / 2 - y_off;

        } else {

            // follow the mouse, but only move the grabbing region when mouse

            // reaches within certain pixels to the edge.

            if (pointer_x > x_off + s->width - follow_mouse)

                x_off += pointer_x - (x_off + s->width - follow_mouse);

            else if (pointer_x < x_off + follow_mouse)

                x_off -= (x_off + follow_mouse) - pointer_x;

            if (pointer_y > y_off + s->height - follow_mouse)

                y_off += pointer_y - (y_off + s->height - follow_mouse);

            else if (pointer_y < y_off + follow_mouse)

                y_off -= (y_off + follow_mouse) - pointer_y;

        }

        // adjust grabbing region position if it goes out of screen.

        s->x_off = x_off = FFMIN(FFMAX(x_off, 0), screen_w - s->width);

        s->y_off = y_off = FFMIN(FFMAX(y_off, 0), screen_h - s->height);

        if (s->show_region && s->region_win)

            XMoveWindow(dpy, s->region_win,

                        s->x_off - REGION_WIN_BORDER,

                        s->y_off - REGION_WIN_BORDER);

    }

    if (s->show_region) {

        if (s->region_win) {

            XEvent evt = { .type = NoEventMask };

            // Clean up the events, and do the initial draw or redraw.

            while (XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask,

                                   &evt))

                ;

            if (evt.type)

                x11grab_draw_region_win(s);

        } else {

            x11grab_region_win_init(s);

        }

    }

    if (s->use_shm) {

        if (!XShmGetImage(dpy, root, image, x_off, y_off, AllPlanes))

            av_log(s1, AV_LOG_INFO, "XShmGetImage() failed\n");

    } else {

        if (!xget_zpixmap(dpy, root, image, x_off, y_off))

            av_log(s1, AV_LOG_INFO, "XGetZPixmap() failed\n");

    }

    if (s->draw_mouse)

        paint_mouse_pointer(image, s);

    return s->frame_size;

}


void usb_ep_combine_input_packets(USBEndpoint *ep)

{

    USBPacket *p, *u, *next, *prev = NULL, *first = NULL;

    USBPort *port = ep->dev->port;

    int ret;

    assert(ep->pipeline);

    assert(ep->pid == USB_TOKEN_IN);

    QTAILQ_FOREACH_SAFE(p, &ep->queue, queue, next) {

        /* Empty the queue on a halt */

        if (ep->halted) {

            p->result = USB_RET_REMOVE_FROM_QUEUE;

            port->ops->complete(port, p);

            continue;

        }

        /* Skip packets already submitted to the device */

        if (p->state == USB_PACKET_ASYNC) {

            prev = p;

            continue;

        }

        usb_packet_check_state(p, USB_PACKET_QUEUED);

        /*

         * If the previous (combined) packet has the short_not_ok flag set

         * stop, as we must not submit packets to the device after a transfer

         * ending with short_not_ok packet.

         */

        if (prev && prev->short_not_ok) {

            break;

        }

        if (first) {

            if (first->combined == NULL) {

                USBCombinedPacket *combined = g_new0(USBCombinedPacket, 1);

                combined->first = first;

                QTAILQ_INIT(&combined->packets);

                qemu_iovec_init(&combined->iov, 2);

                usb_combined_packet_add(combined, first);

            }

            usb_combined_packet_add(first->combined, p);

        } else {

            first = p;

        }

        /* Is this packet the last one of a (combined) transfer? */

        if ((p->iov.size % ep->max_packet_size) != 0 || !p->short_not_ok ||

                next == NULL) {

            ret = usb_device_handle_data(ep->dev, first);

            assert(ret == USB_RET_ASYNC);

            if (first->combined) {

                QTAILQ_FOREACH(u, &first->combined->packets, combined_entry) {

                    usb_packet_set_state(u, USB_PACKET_ASYNC);

                }

            } else {

                usb_packet_set_state(first, USB_PACKET_ASYNC);

            }

            first = NULL;

            prev = p;

        }

    }

}


static MemoryRegionSection *address_space_lookup_region(AddressSpaceDispatch *d,

                                                        hwaddr addr,

                                                        bool resolve_subpage)

{

    MemoryRegionSection *section = atomic_read(&d->mru_section);

    subpage_t *subpage;

    bool update;

    if (section && section != &d->map.sections[PHYS_SECTION_UNASSIGNED] &&

        section_covers_addr(section, addr)) {

        update = false;

    } else {

        section = phys_page_find(d, addr);

        update = true;

    }

    if (resolve_subpage && section->mr->subpage) {

        subpage = container_of(section->mr, subpage_t, iomem);

        section = &d->map.sections[subpage->sub_section[SUBPAGE_IDX(addr)]];

    }

    if (update) {

        atomic_set(&d->mru_section, section);

    }

    return section;

}


static int asf_read_generic_value(AVFormatContext *s, uint8_t *name, uint16_t name_len,

                                  int type, AVDictionary **met)

{

    AVIOContext *pb = s->pb;

    uint64_t value;

    char buf[32];

    switch (type) {

    case ASF_BOOL:

        value = avio_rl32(pb);

        break;

    case ASF_DWORD:

        value = avio_rl32(pb);

        break;

    case ASF_QWORD:

        value = avio_rl64(pb);

        break;

    case ASF_WORD:

        value = avio_rl16(pb);

        break;

    default:

        av_freep(&name);

        return AVERROR_INVALIDDATA;

    }

    snprintf(buf, sizeof(buf), "%"PRIu64, value);

    if (av_dict_set(met, name, buf, 0) < 0)

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

    return 0;

}


int do_netdev_add(Monitor *mon, const QDict *qdict, QObject **ret_data)
{
    QemuOpts *opts;
    int res;
    opts = qemu_opts_from_qdict(&qemu_netdev_opts, qdict);
    if (!opts) {
        return -1;
    res = net_client_init(mon, opts, 1);
    return res;


static int save_zero_page(RAMState *rs, RAMBlock *block, ram_addr_t offset,

                          uint8_t *p)

{

    int pages = -1;

    if (is_zero_range(p, TARGET_PAGE_SIZE)) {

        rs->zero_pages++;

        rs->bytes_transferred +=

            save_page_header(rs, block, offset | RAM_SAVE_FLAG_COMPRESS);

        qemu_put_byte(rs->f, 0);

        rs->bytes_transferred += 1;

        pages = 1;

    }

    return pages;

}


static int movie_push_frame(AVFilterContext *ctx, unsigned out_id)

{

    MovieContext *movie = ctx->priv;

    AVPacket *pkt = &movie->pkt;

    enum AVMediaType frame_type;

    MovieStream *st;

    int ret, got_frame = 0, pkt_out_id;

    AVFilterLink *outlink;

    AVFrame *frame;

    if (!pkt->size) {

        if (movie->eof) {

            if (movie->st[out_id].done) {

                if (movie->loop_count != 1) {

                    ret = rewind_file(ctx);

                    if (ret < 0)

                        return ret;

                    movie->loop_count -= movie->loop_count > 1;

                    av_log(ctx, AV_LOG_VERBOSE, "Stream finished, looping.\n");

                    return 0; /* retry */

                }

                return AVERROR_EOF;

            }

            pkt->stream_index = movie->st[out_id].st->index;

            /* packet is already ready for flushing */

        } else {

            ret = av_read_frame(movie->format_ctx, &movie->pkt0);

            if (ret < 0) {

                av_init_packet(&movie->pkt0); /* ready for flushing */

                *pkt = movie->pkt0;

                if (ret == AVERROR_EOF) {

                    movie->eof = 1;

                    return 0; /* start flushing */

                }

                return ret;

            }

            *pkt = movie->pkt0;

        }

    }

    pkt_out_id = pkt->stream_index > movie->max_stream_index ? -1 :

                 movie->out_index[pkt->stream_index];

    if (pkt_out_id < 0) {

        av_free_packet(&movie->pkt0);

        pkt->size = 0; /* ready for next run */

        pkt->data = NULL;

        return 0;

    }

    st = &movie->st[pkt_out_id];

    outlink = ctx->outputs[pkt_out_id];

    frame = av_frame_alloc();

    if (!frame)

        return AVERROR(ENOMEM);

    frame_type = st->st->codec->codec_type;

    switch (frame_type) {

    case AVMEDIA_TYPE_VIDEO:

        ret = avcodec_decode_video2(st->st->codec, frame, &got_frame, pkt);

        break;

    case AVMEDIA_TYPE_AUDIO:

        ret = avcodec_decode_audio4(st->st->codec, frame, &got_frame, pkt);

        break;

    default:

        ret = AVERROR(ENOSYS);

        break;

    }

    if (ret < 0) {

        av_log(ctx, AV_LOG_WARNING, "Decode error: %s\n", av_err2str(ret));

        av_frame_free(&frame);

        av_free_packet(&movie->pkt0);

        movie->pkt.size = 0;

        movie->pkt.data = NULL;

        return 0;

    }

    if (!ret || st->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

        ret = pkt->size;

    pkt->data += ret;

    pkt->size -= ret;

    if (pkt->size <= 0) {

        av_free_packet(&movie->pkt0);

        pkt->size = 0; /* ready for next run */

        pkt->data = NULL;

    }

    if (!got_frame) {

        if (!ret)

            st->done = 1;

        av_frame_free(&frame);

        return 0;

    }

    frame->pts = av_frame_get_best_effort_timestamp(frame);

    av_dlog(ctx, "movie_push_frame(): file:'%s' %s\n", movie->file_name,

            describe_frame_to_str((char[1024]){0}, 1024, frame, frame_type, outlink));

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

        if (frame->format != outlink->format) {

            av_log(ctx, AV_LOG_ERROR, "Format changed %s -> %s, discarding frame\n",

                av_get_pix_fmt_name(outlink->format),

                av_get_pix_fmt_name(frame->format)

                );

            av_frame_free(&frame);

            return 0;

        }

    }

    ret = ff_filter_frame(outlink, frame);

    if (ret < 0)

        return ret;

    return pkt_out_id == out_id;

}


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

{

    const uint8_t *s = src;

    const uint8_t *end;

    const uint8_t *mm_end;

    uint16_t *d = (uint16_t *)dst;

    end = s + src_size;

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

    __asm__ volatile(

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

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

        ::"m"(red_15mask),"m"(green_15mask));

    mm_end = end - 15;

    while (s < mm_end) {

        __asm__ volatile(

            PREFETCH"   32%1            \n\t"

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

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

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

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

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

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

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

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

            "psllq        $7, %%mm0     \n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        d += 4;

        s += 12;

    }

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

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

    while (s < end) {

        const int r = *s++;

        const int g = *s++;

        const int b = *s++;

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

    }

}


static int decode_picture_timing(H264Context *h)

{

    if (h->sps.nal_hrd_parameters_present_flag ||

        h->sps.vcl_hrd_parameters_present_flag) {

        h->sei_cpb_removal_delay = get_bits(&h->gb,

                                            h->sps.cpb_removal_delay_length);

        h->sei_dpb_output_delay  = get_bits(&h->gb,

                                            h->sps.dpb_output_delay_length);

    }

    if (h->sps.pic_struct_present_flag) {

        unsigned int i, num_clock_ts;

        h->sei_pic_struct = get_bits(&h->gb, 4);

        h->sei_ct_type    = 0;

        if (h->sei_pic_struct > SEI_PIC_STRUCT_FRAME_TRIPLING)

            return AVERROR_INVALIDDATA;

        num_clock_ts = sei_num_clock_ts_table[h->sei_pic_struct];

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

            if (get_bits(&h->gb, 1)) {                /* clock_timestamp_flag */

                unsigned int full_timestamp_flag;

                h->sei_ct_type |= 1 << get_bits(&h->gb, 2);

                skip_bits(&h->gb, 1);                 /* nuit_field_based_flag */

                skip_bits(&h->gb, 5);                 /* counting_type */

                full_timestamp_flag = get_bits(&h->gb, 1);

                skip_bits(&h->gb, 1);                 /* discontinuity_flag */

                skip_bits(&h->gb, 1);                 /* cnt_dropped_flag */

                skip_bits(&h->gb, 8);                 /* n_frames */

                if (full_timestamp_flag) {

                    skip_bits(&h->gb, 6);             /* seconds_value 0..59 */

                    skip_bits(&h->gb, 6);             /* minutes_value 0..59 */

                    skip_bits(&h->gb, 5);             /* hours_value 0..23 */

                } else {

                    if (get_bits(&h->gb, 1)) {        /* seconds_flag */

                        skip_bits(&h->gb, 6);         /* seconds_value range 0..59 */

                        if (get_bits(&h->gb, 1)) {    /* minutes_flag */

                            skip_bits(&h->gb, 6);     /* minutes_value 0..59 */

                            if (get_bits(&h->gb, 1))  /* hours_flag */

                                skip_bits(&h->gb, 5); /* hours_value 0..23 */

                        }

                    }

                }

                if (h->sps.time_offset_length > 0)

                    skip_bits(&h->gb,

                              h->sps.time_offset_length); /* time_offset */

            }

        }

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

            av_log(h->avctx, AV_LOG_DEBUG, "ct_type:%X pic_struct:%d\n",

                   h->sei_ct_type, h->sei_pic_struct);

    }

    return 0;

}


static int ftp_close(URLContext *h)

{

    FTPContext *s = h->priv_data;

    av_dlog(h, "ftp protocol close\n");

    ftp_close_both_connections(s);

    av_freep(&s->user);

    av_freep(&s->password);

    av_freep(&s->hostname);

    av_freep(&s->path);

    av_freep(&s->features);

    return 0;

}


int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,

                       AVInputFormat *fmt,

                       int buf_size,

                       AVFormatParameters *ap)

{

    AVFormatContext *ic = NULL;

    int err;

    char buf[PROBE_BUF_SIZE];

    AVProbeData probe_data, *pd = &probe_data;

    ic = av_mallocz(sizeof(AVFormatContext));

    if (!ic) {

        err = AVERROR_NOMEM;

        goto fail;

    }

    pstrcpy(ic->filename, sizeof(ic->filename), filename);

    pd->filename = ic->filename;

    pd->buf = buf;

    pd->buf_size = 0;

    if (!fmt) {

        /* guess format if no file can be opened  */

        fmt = probe_input_format(pd, 0);

    }

    /* if no file needed do not try to open one */

    if (!fmt || !(fmt->flags & AVFMT_NOFILE)) {

        if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {

            err = AVERROR_IO;

            goto fail;

        }

        if (buf_size > 0) {

            url_setbufsize(&ic->pb, buf_size);

        }

        /* read probe data */

        pd->buf_size = get_buffer(&ic->pb, buf, PROBE_BUF_SIZE);

        url_fseek(&ic->pb, 0, SEEK_SET);

    }

    /* guess file format */

    if (!fmt) {

        fmt = probe_input_format(pd, 1);

    }

    /* if still no format found, error */

    if (!fmt) {

        err = AVERROR_NOFMT;

        goto fail;

    }

    ic->iformat = fmt;

    /* allocate private data */

    ic->priv_data = av_mallocz(fmt->priv_data_size);

    if (!ic->priv_data) {

        err = AVERROR_NOMEM;

        goto fail;

    }

    /* check filename in case of an image number is expected */

    if (ic->iformat->flags & AVFMT_NEEDNUMBER) {

        if (filename_number_test(ic->filename) < 0) {

            err = AVERROR_NUMEXPECTED;

            goto fail1;

        }

    }

    err = ic->iformat->read_header(ic, ap);

    if (err < 0)

        goto fail1;

    *ic_ptr = ic;

    return 0;

 fail1:

    if (!(fmt->flags & AVFMT_NOFILE)) {

        url_fclose(&ic->pb);

    }

 fail:

    if (ic) {

        av_free(ic->priv_data);

    }

    av_free(ic);

    *ic_ptr = NULL;

    return err;

}


static int dec_21154_pci_host_init(PCIDevice *d)

{

    /* PCI2PCI bridge same values as PearPC - check this */

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_DEC);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_DEC_21154);

    pci_set_byte(d->config + PCI_REVISION_ID, 0x02);

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_PCI);

    return 0;

}


static void guess_mv(MpegEncContext *s)

{

    uint8_t *fixed = av_malloc(s->mb_stride * s->mb_height);

#define MV_FROZEN    3

#define MV_CHANGED   2

#define MV_UNCHANGED 1

    const int mb_stride = s->mb_stride;

    const int mb_width  = s->mb_width;

    const int mb_height = s->mb_height;

    int i, depth, num_avail;

    int mb_x, mb_y, mot_step, mot_stride;

    set_mv_strides(s, &mot_step, &mot_stride);

    num_avail = 0;

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

        const int mb_xy = s->mb_index2xy[i];

        int f = 0;

        int error = s->error_status_table[mb_xy];

        if (IS_INTRA(s->current_picture.f.mb_type[mb_xy]))

            f = MV_FROZEN; // intra // FIXME check

        if (!(error & ER_MV_ERROR))

            f = MV_FROZEN; // inter with undamaged MV

        fixed[mb_xy] = f;

        if (f == MV_FROZEN)

            num_avail++;

        else if(s->last_picture.f.data[0] && s->last_picture.f.motion_val[0]){

            const int mb_y= mb_xy / s->mb_stride;

            const int mb_x= mb_xy % s->mb_stride;

            const int mot_index= (mb_x + mb_y*mot_stride) * mot_step;

            s->current_picture.f.motion_val[0][mot_index][0]= s->last_picture.f.motion_val[0][mot_index][0];

            s->current_picture.f.motion_val[0][mot_index][1]= s->last_picture.f.motion_val[0][mot_index][1];

            s->current_picture.f.ref_index[0][4*mb_xy]      = s->last_picture.f.ref_index[0][4*mb_xy];

        }

    }

    if ((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) ||

        num_avail <= mb_width / 2) {

        for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

            s->mb_x = 0;

            s->mb_y = mb_y;

            ff_init_block_index(s);

            for (mb_x = 0; mb_x < s->mb_width; mb_x++) {

                const int mb_xy = mb_x + mb_y * s->mb_stride;

                ff_update_block_index(s);

                if (IS_INTRA(s->current_picture.f.mb_type[mb_xy]))

                    continue;

                if (!(s->error_status_table[mb_xy] & ER_MV_ERROR))

                    continue;

                s->mv_dir     = s->last_picture.f.data[0] ? MV_DIR_FORWARD

                                                          : MV_DIR_BACKWARD;

                s->mb_intra   = 0;

                s->mv_type    = MV_TYPE_16X16;

                s->mb_skipped = 0;

                s->dsp.clear_blocks(s->block[0]);

                s->mb_x        = mb_x;

                s->mb_y        = mb_y;

                s->mv[0][0][0] = 0;

                s->mv[0][0][1] = 0;

                decode_mb(s, 0);

            }

        }

        goto end;

    }

    for (depth = 0; ; depth++) {

        int changed, pass, none_left;

        none_left = 1;

        changed   = 1;

        for (pass = 0; (changed || pass < 2) && pass < 10; pass++) {

            int mb_x, mb_y;

            int score_sum = 0;

            changed = 0;

            for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

                s->mb_x = 0;

                s->mb_y = mb_y;

                ff_init_block_index(s);

                for (mb_x = 0; mb_x < s->mb_width; mb_x++) {

                    const int mb_xy        = mb_x + mb_y * s->mb_stride;

                    int mv_predictor[8][2] = { { 0 } };

                    int ref[8]             = { 0 };

                    int pred_count         = 0;

                    int j;

                    int best_score         = 256 * 256 * 256 * 64;

                    int best_pred          = 0;

                    const int mot_index    = (mb_x + mb_y * mot_stride) * mot_step;

                    int prev_x, prev_y, prev_ref;

                    ff_update_block_index(s);

                    if ((mb_x ^ mb_y ^ pass) & 1)

                        continue;

                    if (fixed[mb_xy] == MV_FROZEN)

                        continue;

                    assert(!IS_INTRA(s->current_picture.f.mb_type[mb_xy]));

                    assert(s->last_picture_ptr && s->last_picture_ptr->f.data[0]);

                    j = 0;

                    if (mb_x > 0             && fixed[mb_xy - 1]         == MV_FROZEN)

                        j = 1;

                    if (mb_x + 1 < mb_width  && fixed[mb_xy + 1]         == MV_FROZEN)

                        j = 1;

                    if (mb_y > 0             && fixed[mb_xy - mb_stride] == MV_FROZEN)

                        j = 1;

                    if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] == MV_FROZEN)

                        j = 1;

                    if (j == 0)

                        continue;

                    j = 0;

                    if (mb_x > 0             && fixed[mb_xy - 1        ] == MV_CHANGED)

                        j = 1;

                    if (mb_x + 1 < mb_width  && fixed[mb_xy + 1        ] == MV_CHANGED)

                        j = 1;

                    if (mb_y > 0             && fixed[mb_xy - mb_stride] == MV_CHANGED)

                        j = 1;

                    if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] == MV_CHANGED)

                        j = 1;

                    if (j == 0 && pass > 1)

                        continue;

                    none_left = 0;

                    if (mb_x > 0 && fixed[mb_xy - 1]) {

                        mv_predictor[pred_count][0] =

                            s->current_picture.f.motion_val[0][mot_index - mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->current_picture.f.motion_val[0][mot_index - mot_step][1];

                        ref[pred_count] =

                            s->current_picture.f.ref_index[0][4 * (mb_xy - 1)];

                        pred_count++;

                    }

                    if (mb_x + 1 < mb_width && fixed[mb_xy + 1]) {

                        mv_predictor[pred_count][0] =

                            s->current_picture.f.motion_val[0][mot_index + mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->current_picture.f.motion_val[0][mot_index + mot_step][1];

                        ref[pred_count] =

                            s->current_picture.f.ref_index[0][4 * (mb_xy + 1)];

                        pred_count++;

                    }

                    if (mb_y > 0 && fixed[mb_xy - mb_stride]) {

                        mv_predictor[pred_count][0] =

                            s->current_picture.f.motion_val[0][mot_index - mot_stride * mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->current_picture.f.motion_val[0][mot_index - mot_stride * mot_step][1];

                        ref[pred_count] =

                            s->current_picture.f.ref_index[0][4 * (mb_xy - s->mb_stride)];

                        pred_count++;

                    }

                    if (mb_y + 1<mb_height && fixed[mb_xy + mb_stride]) {

                        mv_predictor[pred_count][0] =

                            s->current_picture.f.motion_val[0][mot_index + mot_stride * mot_step][0];

                        mv_predictor[pred_count][1] =

                            s->current_picture.f.motion_val[0][mot_index + mot_stride * mot_step][1];

                        ref[pred_count] =

                            s->current_picture.f.ref_index[0][4 * (mb_xy + s->mb_stride)];

                        pred_count++;

                    }

                    if (pred_count == 0)

                        continue;

                    if (pred_count > 1) {

                        int sum_x = 0, sum_y = 0, sum_r = 0;

                        int max_x, max_y, min_x, min_y, max_r, min_r;

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

                            sum_x += mv_predictor[j][0];

                            sum_y += mv_predictor[j][1];

                            sum_r += ref[j];

                            if (j && ref[j] != ref[j - 1])

                                goto skip_mean_and_median;

                        }

                        /* mean */

                        mv_predictor[pred_count][0] = sum_x / j;

                        mv_predictor[pred_count][1] = sum_y / j;

                                 ref[pred_count]    = sum_r / j;

                        /* median */

                        if (pred_count >= 3) {

                            min_y = min_x = min_r =  99999;

                            max_y = max_x = max_r = -99999;

                        } else {

                            min_x = min_y = max_x = max_y = min_r = max_r = 0;

                        }

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

                            max_x = FFMAX(max_x, mv_predictor[j][0]);

                            max_y = FFMAX(max_y, mv_predictor[j][1]);

                            max_r = FFMAX(max_r, ref[j]);

                            min_x = FFMIN(min_x, mv_predictor[j][0]);

                            min_y = FFMIN(min_y, mv_predictor[j][1]);

                            min_r = FFMIN(min_r, ref[j]);

                        }

                        mv_predictor[pred_count + 1][0] = sum_x - max_x - min_x;

                        mv_predictor[pred_count + 1][1] = sum_y - max_y - min_y;

                                 ref[pred_count + 1]    = sum_r - max_r - min_r;

                        if (pred_count == 4) {

                            mv_predictor[pred_count + 1][0] /= 2;

                            mv_predictor[pred_count + 1][1] /= 2;

                                     ref[pred_count + 1]    /= 2;

                        }

                        pred_count += 2;

                    }

skip_mean_and_median:

                    /* zero MV */

                    pred_count++;

                    if (!fixed[mb_xy] && 0) {

                        if (s->avctx->codec_id == CODEC_ID_H264) {

                            // FIXME

                        } else {

                            ff_thread_await_progress(&s->last_picture_ptr->f,

                                                     mb_y, 0);

                        }

                        if (!s->last_picture.f.motion_val[0] ||

                            !s->last_picture.f.ref_index[0])

                            goto skip_last_mv;

                        prev_x   = s->last_picture.f.motion_val[0][mot_index][0];

                        prev_y   = s->last_picture.f.motion_val[0][mot_index][1];

                        prev_ref = s->last_picture.f.ref_index[0][4 * mb_xy];

                    } else {

                        prev_x   = s->current_picture.f.motion_val[0][mot_index][0];

                        prev_y   = s->current_picture.f.motion_val[0][mot_index][1];

                        prev_ref = s->current_picture.f.ref_index[0][4 * mb_xy];

                    }

                    /* last MV */

                    mv_predictor[pred_count][0] = prev_x;

                    mv_predictor[pred_count][1] = prev_y;

                             ref[pred_count]    = prev_ref;

                    pred_count++;

skip_last_mv:

                    s->mv_dir     = MV_DIR_FORWARD;

                    s->mb_intra   = 0;

                    s->mv_type    = MV_TYPE_16X16;

                    s->mb_skipped = 0;

                    s->dsp.clear_blocks(s->block[0]);

                    s->mb_x = mb_x;

                    s->mb_y = mb_y;

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

                        int score = 0;

                        uint8_t *src = s->current_picture.f.data[0] +

                                       mb_x * 16 + mb_y * 16 * s->linesize;

                        s->current_picture.f.motion_val[0][mot_index][0] =

                            s->mv[0][0][0] = mv_predictor[j][0];

                        s->current_picture.f.motion_val[0][mot_index][1] =

                            s->mv[0][0][1] = mv_predictor[j][1];

                        // predictor intra or otherwise not available

                        if (ref[j] < 0)

                            continue;

                        decode_mb(s, ref[j]);

                        if (mb_x > 0 && fixed[mb_xy - 1]) {

                            int k;

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

                                score += FFABS(src[k * s->linesize - 1] -

                                               src[k * s->linesize]);

                        }

                        if (mb_x + 1 < mb_width && fixed[mb_xy + 1]) {

                            int k;

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

                                score += FFABS(src[k * s->linesize + 15] -

                                               src[k * s->linesize + 16]);

                        }

                        if (mb_y > 0 && fixed[mb_xy - mb_stride]) {

                            int k;

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

                                score += FFABS(src[k - s->linesize] - src[k]);

                        }

                        if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride]) {

                            int k;

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

                                score += FFABS(src[k + s->linesize * 15] -

                                               src[k + s->linesize * 16]);

                        }

                        if (score <= best_score) { // <= will favor the last MV

                            best_score = score;

                            best_pred  = j;

                        }

                    }

                    score_sum += best_score;

                    s->mv[0][0][0] = mv_predictor[best_pred][0];

                    s->mv[0][0][1] = mv_predictor[best_pred][1];

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

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

                            s->current_picture.f.motion_val[0][mot_index + i + j * mot_stride][0] = s->mv[0][0][0];

                            s->current_picture.f.motion_val[0][mot_index + i + j * mot_stride][1] = s->mv[0][0][1];

                        }

                    decode_mb(s, ref[best_pred]);

                    if (s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y) {

                        fixed[mb_xy] = MV_CHANGED;

                        changed++;

                    } else

                        fixed[mb_xy] = MV_UNCHANGED;

                }

            }

            // printf(".%d/%d", changed, score_sum); fflush(stdout);

        }

        if (none_left)

            goto end;

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

            int mb_xy = s->mb_index2xy[i];

            if (fixed[mb_xy])

                fixed[mb_xy] = MV_FROZEN;

        }

        // printf(":"); fflush(stdout);

    }

end:

    av_free(fixed);

}


static void audio_reset_timer (AudioState *s)

{

    if (audio_is_timer_needed ()) {

        timer_mod (s->ts,

            qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + conf.period.ticks);

    }

    else {

        timer_del (s->ts);

    }

}


int bdrv_get_translation_hint(BlockDriverState *bs)

{

    return bs->translation;

}


static int omap_validate_emifs_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return range_covers_byte(OMAP_EMIFS_BASE, OMAP_EMIFF_BASE - OMAP_EMIFS_BASE,

                             addr);

}


StringOutputVisitor *string_output_visitor_new(bool human)

{

    StringOutputVisitor *v;

    v = g_malloc0(sizeof(*v));

    v->string = g_string_new(NULL);

    v->human = human;

    v->visitor.type = VISITOR_OUTPUT;

    v->visitor.type_int64 = print_type_int64;

    v->visitor.type_uint64 = print_type_uint64;

    v->visitor.type_size = print_type_size;

    v->visitor.type_bool = print_type_bool;

    v->visitor.type_str = print_type_str;

    v->visitor.type_number = print_type_number;

    v->visitor.start_list = start_list;

    v->visitor.next_list = next_list;

    v->visitor.end_list = end_list;

    v->visitor.free = string_output_free;

    return v;

}


int qemu_input_key_value_to_number(const KeyValue *value)

{

    if (value->kind == KEY_VALUE_KIND_QCODE) {

        return qcode_to_number[value->qcode];

    } else {

        assert(value->kind == KEY_VALUE_KIND_NUMBER);

        return value->number;

    }

}


uint64_t HELPER(paired_cmpxchg64_be)(CPUARMState *env, uint64_t addr,

                                     uint64_t new_lo, uint64_t new_hi)

{

    uintptr_t ra = GETPC();

    Int128 oldv, cmpv, newv;

    bool success;

    cmpv = int128_make128(env->exclusive_val, env->exclusive_high);

    newv = int128_make128(new_lo, new_hi);

    if (parallel_cpus) {

#ifndef CONFIG_ATOMIC128

        cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

#else

        int mem_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi = make_memop_idx(MO_BEQ | MO_ALIGN_16, mem_idx);

        oldv = helper_atomic_cmpxchgo_be_mmu(env, addr, cmpv, newv, oi, ra);

        success = int128_eq(oldv, cmpv);

#endif

    } else {

        uint64_t o0, o1;

#ifdef CONFIG_USER_ONLY

        /* ??? Enforce alignment.  */

        uint64_t *haddr = g2h(addr);

        o1 = ldq_be_p(haddr + 0);

        o0 = ldq_be_p(haddr + 1);

        oldv = int128_make128(o0, o1);

        success = int128_eq(oldv, cmpv);

        if (success) {

            stq_be_p(haddr + 0, int128_gethi(newv));

            stq_be_p(haddr + 1, int128_getlo(newv));

        }

#else

        int mem_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi0 = make_memop_idx(MO_BEQ | MO_ALIGN_16, mem_idx);

        TCGMemOpIdx oi1 = make_memop_idx(MO_BEQ, mem_idx);

        o1 = helper_be_ldq_mmu(env, addr + 0, oi0, ra);

        o0 = helper_be_ldq_mmu(env, addr + 8, oi1, ra);

        oldv = int128_make128(o0, o1);

        success = int128_eq(oldv, cmpv);

        if (success) {

            helper_be_stq_mmu(env, addr + 0, int128_gethi(newv), oi1, ra);

            helper_be_stq_mmu(env, addr + 8, int128_getlo(newv), oi1, ra);

        }

#endif

    }

    return !success;

}


void ptimer_set_limit(ptimer_state *s, uint64_t limit, int reload)

{

    /*

     * Artificially limit timeout rate to something

     * achievable under QEMU.  Otherwise, QEMU spends all

     * its time generating timer interrupts, and there

     * is no forward progress.

     * About ten microseconds is the fastest that really works

     * on the current generation of host machines.

     */

    if (!use_icount && limit * s->period < 10000 && s->period) {

        limit = 10000 / s->period;

    }

    s->limit = limit;

    if (reload)

        s->delta = limit;

    if (s->enabled && reload) {

        s->next_event = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

        ptimer_reload(s);

    }

}


static inline void conv_to_int32(int32_t *loc, float *samples, int num, float norm)

{

    int i;

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

        loc[i] = ceilf((samples[i]/norm)*INT32_MAX);

}