Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtpdec.c @ 4ffff367

History | View | Annotate | Download (23.1 KB)

1
/*
2
 * RTP input format
3
 * Copyright (c) 2002 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/* needed for gethostname() */
23
#define _XOPEN_SOURCE 600
24

    
25
#include "libavcodec/get_bits.h"
26
#include "avformat.h"
27
#include "mpegts.h"
28

    
29
#include <unistd.h>
30
#include "network.h"
31

    
32
#include "rtpdec.h"
33
#include "rtpdec_formats.h"
34

    
35
//#define DEBUG
36

    
37
/* TODO: - add RTCP statistics reporting (should be optional).
38

39
         - add support for h263/mpeg4 packetized output : IDEA: send a
40
         buffer to 'rtp_write_packet' contains all the packets for ONE
41
         frame. Each packet should have a four byte header containing
42
         the length in big endian format (same trick as
43
         'url_open_dyn_packet_buf')
44
*/
45

    
46
/* statistics functions */
47
RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
48

    
49
void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
50
{
51
    handler->next= RTPFirstDynamicPayloadHandler;
52
    RTPFirstDynamicPayloadHandler= handler;
53
}
54

    
55
void av_register_rtp_dynamic_payload_handlers(void)
56
{
57
    ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
58
    ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
59
    ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
60
    ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
61
    ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
62
    ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
63
    ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
64
    ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
65
    ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
66
    ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
67
    ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
68
    ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
69
    ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
70

    
71
    ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
72
    ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
73

    
74
    ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
75
    ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
76
    ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
77
    ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
78
}
79

    
80
static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
81
{
82
    int payload_len;
83
    while (len >= 2) {
84
        switch (buf[1]) {
85
        case RTCP_SR:
86
            if (len < 16) {
87
                av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
88
                return AVERROR_INVALIDDATA;
89
            }
90
            payload_len = (AV_RB16(buf + 2) + 1) * 4;
91

    
92
            s->last_rtcp_ntp_time = AV_RB64(buf + 8);
93
            if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
94
                s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
95
            s->last_rtcp_timestamp = AV_RB32(buf + 16);
96

    
97
            buf += payload_len;
98
            len -= payload_len;
99
            break;
100
        case RTCP_BYE:
101
            return -RTCP_BYE;
102
        default:
103
            return -1;
104
        }
105
    }
106
    return -1;
107
}
108

    
109
#define RTP_SEQ_MOD (1<<16)
110

    
111
/**
112
* called on parse open packet
113
*/
114
static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
115
{
116
    memset(s, 0, sizeof(RTPStatistics));
117
    s->max_seq= base_sequence;
118
    s->probation= 1;
119
}
120

    
121
/**
122
* called whenever there is a large jump in sequence numbers, or when they get out of probation...
123
*/
124
static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
125
{
126
    s->max_seq= seq;
127
    s->cycles= 0;
128
    s->base_seq= seq -1;
129
    s->bad_seq= RTP_SEQ_MOD + 1;
130
    s->received= 0;
131
    s->expected_prior= 0;
132
    s->received_prior= 0;
133
    s->jitter= 0;
134
    s->transit= 0;
135
}
136

    
137
/**
138
* returns 1 if we should handle this packet.
139
*/
140
static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
141
{
142
    uint16_t udelta= seq - s->max_seq;
143
    const int MAX_DROPOUT= 3000;
144
    const int MAX_MISORDER = 100;
145
    const int MIN_SEQUENTIAL = 2;
146

    
147
    /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
148
    if(s->probation)
149
    {
150
        if(seq==s->max_seq + 1) {
151
            s->probation--;
152
            s->max_seq= seq;
153
            if(s->probation==0) {
154
                rtp_init_sequence(s, seq);
155
                s->received++;
156
                return 1;
157
            }
158
        } else {
159
            s->probation= MIN_SEQUENTIAL - 1;
160
            s->max_seq = seq;
161
        }
162
    } else if (udelta < MAX_DROPOUT) {
163
        // in order, with permissible gap
164
        if(seq < s->max_seq) {
165
            //sequence number wrapped; count antother 64k cycles
166
            s->cycles += RTP_SEQ_MOD;
167
        }
168
        s->max_seq= seq;
169
    } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
170
        // sequence made a large jump...
171
        if(seq==s->bad_seq) {
172
            // two sequential packets-- assume that the other side restarted without telling us; just resync.
173
            rtp_init_sequence(s, seq);
174
        } else {
175
            s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
176
            return 0;
177
        }
178
    } else {
179
        // duplicate or reordered packet...
180
    }
181
    s->received++;
182
    return 1;
183
}
184

    
185
#if 0
186
/**
187
* This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
188
* difference between the arrival and sent timestamp.  As a result, the jitter and transit statistics values
189
* never change.  I left this in in case someone else can see a way. (rdm)
190
*/
191
static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
192
{
193
    uint32_t transit= arrival_timestamp - sent_timestamp;
194
    int d;
195
    s->transit= transit;
196
    d= FFABS(transit - s->transit);
197
    s->jitter += d - ((s->jitter + 8)>>4);
198
}
199
#endif
200

    
201
int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
202
{
203
    ByteIOContext *pb;
204
    uint8_t *buf;
205
    int len;
206
    int rtcp_bytes;
207
    RTPStatistics *stats= &s->statistics;
208
    uint32_t lost;
209
    uint32_t extended_max;
210
    uint32_t expected_interval;
211
    uint32_t received_interval;
212
    uint32_t lost_interval;
213
    uint32_t expected;
214
    uint32_t fraction;
215
    uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
216

    
217
    if (!s->rtp_ctx || (count < 1))
218
        return -1;
219

    
220
    /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
221
    /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
222
    s->octet_count += count;
223
    rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
224
        RTCP_TX_RATIO_DEN;
225
    rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
226
    if (rtcp_bytes < 28)
227
        return -1;
228
    s->last_octet_count = s->octet_count;
229

    
230
    if (url_open_dyn_buf(&pb) < 0)
231
        return -1;
232

    
233
    // Receiver Report
234
    put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
235
    put_byte(pb, RTCP_RR);
236
    put_be16(pb, 7); /* length in words - 1 */
237
    // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
238
    put_be32(pb, s->ssrc + 1);
239
    put_be32(pb, s->ssrc); // server SSRC
240
    // some placeholders we should really fill...
241
    // RFC 1889/p64
242
    extended_max= stats->cycles + stats->max_seq;
243
    expected= extended_max - stats->base_seq + 1;
244
    lost= expected - stats->received;
245
    lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
246
    expected_interval= expected - stats->expected_prior;
247
    stats->expected_prior= expected;
248
    received_interval= stats->received - stats->received_prior;
249
    stats->received_prior= stats->received;
250
    lost_interval= expected_interval - received_interval;
251
    if (expected_interval==0 || lost_interval<=0) fraction= 0;
252
    else fraction = (lost_interval<<8)/expected_interval;
253

    
254
    fraction= (fraction<<24) | lost;
255

    
256
    put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
257
    put_be32(pb, extended_max); /* max sequence received */
258
    put_be32(pb, stats->jitter>>4); /* jitter */
259

    
260
    if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
261
    {
262
        put_be32(pb, 0); /* last SR timestamp */
263
        put_be32(pb, 0); /* delay since last SR */
264
    } else {
265
        uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
266
        uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
267

    
268
        put_be32(pb, middle_32_bits); /* last SR timestamp */
269
        put_be32(pb, delay_since_last); /* delay since last SR */
270
    }
271

    
272
    // CNAME
273
    put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
274
    put_byte(pb, RTCP_SDES);
275
    len = strlen(s->hostname);
276
    put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
277
    put_be32(pb, s->ssrc);
278
    put_byte(pb, 0x01);
279
    put_byte(pb, len);
280
    put_buffer(pb, s->hostname, len);
281
    // padding
282
    for (len = (6 + len) % 4; len % 4; len++) {
283
        put_byte(pb, 0);
284
    }
285

    
286
    put_flush_packet(pb);
287
    len = url_close_dyn_buf(pb, &buf);
288
    if ((len > 0) && buf) {
289
        int result;
290
        dprintf(s->ic, "sending %d bytes of RR\n", len);
291
        result= url_write(s->rtp_ctx, buf, len);
292
        dprintf(s->ic, "result from url_write: %d\n", result);
293
        av_free(buf);
294
    }
295
    return 0;
296
}
297

    
298
void rtp_send_punch_packets(URLContext* rtp_handle)
299
{
300
    ByteIOContext *pb;
301
    uint8_t *buf;
302
    int len;
303

    
304
    /* Send a small RTP packet */
305
    if (url_open_dyn_buf(&pb) < 0)
306
        return;
307

    
308
    put_byte(pb, (RTP_VERSION << 6));
309
    put_byte(pb, 0); /* Payload type */
310
    put_be16(pb, 0); /* Seq */
311
    put_be32(pb, 0); /* Timestamp */
312
    put_be32(pb, 0); /* SSRC */
313

    
314
    put_flush_packet(pb);
315
    len = url_close_dyn_buf(pb, &buf);
316
    if ((len > 0) && buf)
317
        url_write(rtp_handle, buf, len);
318
    av_free(buf);
319

    
320
    /* Send a minimal RTCP RR */
321
    if (url_open_dyn_buf(&pb) < 0)
322
        return;
323

    
324
    put_byte(pb, (RTP_VERSION << 6));
325
    put_byte(pb, RTCP_RR); /* receiver report */
326
    put_be16(pb, 1); /* length in words - 1 */
327
    put_be32(pb, 0); /* our own SSRC */
328

    
329
    put_flush_packet(pb);
330
    len = url_close_dyn_buf(pb, &buf);
331
    if ((len > 0) && buf)
332
        url_write(rtp_handle, buf, len);
333
    av_free(buf);
334
}
335

    
336

    
337
/**
338
 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
339
 * MPEG2TS streams to indicate that they should be demuxed inside the
340
 * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
341
 */
342
RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
343
{
344
    RTPDemuxContext *s;
345

    
346
    s = av_mallocz(sizeof(RTPDemuxContext));
347
    if (!s)
348
        return NULL;
349
    s->payload_type = payload_type;
350
    s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
351
    s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
352
    s->ic = s1;
353
    s->st = st;
354
    s->queue_size = queue_size;
355
    rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
356
    if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
357
        s->ts = ff_mpegts_parse_open(s->ic);
358
        if (s->ts == NULL) {
359
            av_free(s);
360
            return NULL;
361
        }
362
    } else {
363
        av_set_pts_info(st, 32, 1, 90000);
364
        switch(st->codec->codec_id) {
365
        case CODEC_ID_MPEG1VIDEO:
366
        case CODEC_ID_MPEG2VIDEO:
367
        case CODEC_ID_MP2:
368
        case CODEC_ID_MP3:
369
        case CODEC_ID_MPEG4:
370
        case CODEC_ID_H263:
371
        case CODEC_ID_H264:
372
            st->need_parsing = AVSTREAM_PARSE_FULL;
373
            break;
374
        case CODEC_ID_ADPCM_G722:
375
            av_set_pts_info(st, 32, 1, st->codec->sample_rate);
376
            /* According to RFC 3551, the stream clock rate is 8000
377
             * even if the sample rate is 16000. */
378
            if (st->codec->sample_rate == 8000)
379
                st->codec->sample_rate = 16000;
380
            break;
381
        default:
382
            if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
383
                av_set_pts_info(st, 32, 1, st->codec->sample_rate);
384
            }
385
            break;
386
        }
387
    }
388
    // needed to send back RTCP RR in RTSP sessions
389
    s->rtp_ctx = rtpc;
390
    gethostname(s->hostname, sizeof(s->hostname));
391
    return s;
392
}
393

    
394
void
395
rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
396
                               RTPDynamicProtocolHandler *handler)
397
{
398
    s->dynamic_protocol_context = ctx;
399
    s->parse_packet = handler->parse_packet;
400
}
401

    
402
/**
403
 * This was the second switch in rtp_parse packet.  Normalizes time, if required, sets stream_index, etc.
404
 */
405
static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
406
{
407
    if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && timestamp != RTP_NOTS_VALUE) {
408
        int64_t addend;
409
        int delta_timestamp;
410

    
411
        /* compute pts from timestamp with received ntp_time */
412
        delta_timestamp = timestamp - s->last_rtcp_timestamp;
413
        /* convert to the PTS timebase */
414
        addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
415
        pkt->pts = s->range_start_offset + addend + delta_timestamp;
416
    }
417
}
418

    
419
static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
420
                                     const uint8_t *buf, int len)
421
{
422
    unsigned int ssrc, h;
423
    int payload_type, seq, ret, flags = 0;
424
    int ext;
425
    AVStream *st;
426
    uint32_t timestamp;
427
    int rv= 0;
428

    
429
    ext = buf[0] & 0x10;
430
    payload_type = buf[1] & 0x7f;
431
    if (buf[1] & 0x80)
432
        flags |= RTP_FLAG_MARKER;
433
    seq  = AV_RB16(buf + 2);
434
    timestamp = AV_RB32(buf + 4);
435
    ssrc = AV_RB32(buf + 8);
436
    /* store the ssrc in the RTPDemuxContext */
437
    s->ssrc = ssrc;
438

    
439
    /* NOTE: we can handle only one payload type */
440
    if (s->payload_type != payload_type)
441
        return -1;
442

    
443
    st = s->st;
444
    // only do something with this if all the rtp checks pass...
445
    if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
446
    {
447
        av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
448
               payload_type, seq, ((s->seq + 1) & 0xffff));
449
        return -1;
450
    }
451

    
452
    s->seq = seq;
453
    len -= 12;
454
    buf += 12;
455

    
456
    /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
457
    if (ext) {
458
        if (len < 4)
459
            return -1;
460
        /* calculate the header extension length (stored as number
461
         * of 32-bit words) */
462
        ext = (AV_RB16(buf + 2) + 1) << 2;
463

    
464
        if (len < ext)
465
            return -1;
466
        // skip past RTP header extension
467
        len -= ext;
468
        buf += ext;
469
    }
470

    
471
    if (!st) {
472
        /* specific MPEG2TS demux support */
473
        ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
474
        if (ret < 0)
475
            return -1;
476
        if (ret < len) {
477
            s->read_buf_size = len - ret;
478
            memcpy(s->buf, buf + ret, s->read_buf_size);
479
            s->read_buf_index = 0;
480
            return 1;
481
        }
482
        return 0;
483
    } else if (s->parse_packet) {
484
        rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
485
                             s->st, pkt, &timestamp, buf, len, flags);
486
    } else {
487
        // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
488
        switch(st->codec->codec_id) {
489
        case CODEC_ID_MP2:
490
        case CODEC_ID_MP3:
491
            /* better than nothing: skip mpeg audio RTP header */
492
            if (len <= 4)
493
                return -1;
494
            h = AV_RB32(buf);
495
            len -= 4;
496
            buf += 4;
497
            av_new_packet(pkt, len);
498
            memcpy(pkt->data, buf, len);
499
            break;
500
        case CODEC_ID_MPEG1VIDEO:
501
        case CODEC_ID_MPEG2VIDEO:
502
            /* better than nothing: skip mpeg video RTP header */
503
            if (len <= 4)
504
                return -1;
505
            h = AV_RB32(buf);
506
            buf += 4;
507
            len -= 4;
508
            if (h & (1 << 26)) {
509
                /* mpeg2 */
510
                if (len <= 4)
511
                    return -1;
512
                buf += 4;
513
                len -= 4;
514
            }
515
            av_new_packet(pkt, len);
516
            memcpy(pkt->data, buf, len);
517
            break;
518
        default:
519
            av_new_packet(pkt, len);
520
            memcpy(pkt->data, buf, len);
521
            break;
522
        }
523

    
524
        pkt->stream_index = st->index;
525
    }
526

    
527
    // now perform timestamp things....
528
    finalize_packet(s, pkt, timestamp);
529

    
530
    return rv;
531
}
532

    
533
void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
534
{
535
    while (s->queue) {
536
        RTPPacket *next = s->queue->next;
537
        av_free(s->queue->buf);
538
        av_free(s->queue);
539
        s->queue = next;
540
    }
541
    s->seq       = 0;
542
    s->queue_len = 0;
543
    s->prev_ret  = 0;
544
}
545

    
546
static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
547
{
548
    uint16_t seq = AV_RB16(buf + 2);
549
    RTPPacket *cur = s->queue, *prev = NULL, *packet;
550

    
551
    /* Find the correct place in the queue to insert the packet */
552
    while (cur) {
553
        int16_t diff = seq - cur->seq;
554
        if (diff < 0)
555
            break;
556
        prev = cur;
557
        cur = cur->next;
558
    }
559

    
560
    packet = av_mallocz(sizeof(*packet));
561
    if (!packet)
562
        return;
563
    packet->recvtime = av_gettime();
564
    packet->seq = seq;
565
    packet->len = len;
566
    packet->buf = buf;
567
    packet->next = cur;
568
    if (prev)
569
        prev->next = packet;
570
    else
571
        s->queue = packet;
572
    s->queue_len++;
573
}
574

    
575
static int has_next_packet(RTPDemuxContext *s)
576
{
577
    return s->queue && s->queue->seq == s->seq + 1;
578
}
579

    
580
int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
581
{
582
    return s->queue ? s->queue->recvtime : 0;
583
}
584

    
585
static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
586
{
587
    int rv;
588
    RTPPacket *next;
589

    
590
    if (s->queue_len <= 0)
591
        return -1;
592

    
593
    if (!has_next_packet(s))
594
        av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
595
               "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
596

    
597
    /* Parse the first packet in the queue, and dequeue it */
598
    rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
599
    next = s->queue->next;
600
    av_free(s->queue->buf);
601
    av_free(s->queue);
602
    s->queue = next;
603
    s->queue_len--;
604
    return rv;
605
}
606

    
607
static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
608
                     uint8_t **bufptr, int len)
609
{
610
    uint8_t* buf = bufptr ? *bufptr : NULL;
611
    int ret, flags = 0;
612
    uint32_t timestamp;
613
    int rv= 0;
614

    
615
    if (!buf) {
616
        /* If parsing of the previous packet actually returned 0, there's
617
         * nothing more to be parsed from that packet, but we may have
618
         * indicated that we can return the next enqueued packet. */
619
        if (!s->prev_ret)
620
            return rtp_parse_queued_packet(s, pkt);
621
        /* return the next packets, if any */
622
        if(s->st && s->parse_packet) {
623
            /* timestamp should be overwritten by parse_packet, if not,
624
             * the packet is left with pts == AV_NOPTS_VALUE */
625
            timestamp = RTP_NOTS_VALUE;
626
            rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
627
                                s->st, pkt, &timestamp, NULL, 0, flags);
628
            finalize_packet(s, pkt, timestamp);
629
            return rv;
630
        } else {
631
            // TODO: Move to a dynamic packet handler (like above)
632
            if (s->read_buf_index >= s->read_buf_size)
633
                return -1;
634
            ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
635
                                      s->read_buf_size - s->read_buf_index);
636
            if (ret < 0)
637
                return -1;
638
            s->read_buf_index += ret;
639
            if (s->read_buf_index < s->read_buf_size)
640
                return 1;
641
            else
642
                return 0;
643
        }
644
    }
645

    
646
    if (len < 12)
647
        return -1;
648

    
649
    if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
650
        return -1;
651
    if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
652
        return rtcp_parse_packet(s, buf, len);
653
    }
654

    
655
    if (s->seq == 0 || s->queue_size <= 1) {
656
        /* First packet, or no reordering */
657
        return rtp_parse_packet_internal(s, pkt, buf, len);
658
    } else {
659
        uint16_t seq = AV_RB16(buf + 2);
660
        int16_t diff = seq - s->seq;
661
        if (diff < 0) {
662
            /* Packet older than the previously emitted one, drop */
663
            av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
664
                   "RTP: dropping old packet received too late\n");
665
            return -1;
666
        } else if (diff <= 1) {
667
            /* Correct packet */
668
            rv = rtp_parse_packet_internal(s, pkt, buf, len);
669
            return rv;
670
        } else {
671
            /* Still missing some packet, enqueue this one. */
672
            enqueue_packet(s, buf, len);
673
            *bufptr = NULL;
674
            /* Return the first enqueued packet if the queue is full,
675
             * even if we're missing something */
676
            if (s->queue_len >= s->queue_size)
677
                return rtp_parse_queued_packet(s, pkt);
678
            return -1;
679
        }
680
    }
681
}
682

    
683
/**
684
 * Parse an RTP or RTCP packet directly sent as a buffer.
685
 * @param s RTP parse context.
686
 * @param pkt returned packet
687
 * @param bufptr pointer to the input buffer or NULL to read the next packets
688
 * @param len buffer len
689
 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
690
 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
691
 */
692
int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
693
                     uint8_t **bufptr, int len)
694
{
695
    int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
696
    s->prev_ret = rv;
697
    return rv ? rv : has_next_packet(s);
698
}
699

    
700
void rtp_parse_close(RTPDemuxContext *s)
701
{
702
    ff_rtp_reset_packet_queue(s);
703
    if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
704
        ff_mpegts_parse_close(s->ts);
705
    }
706
    av_free(s);
707
}
708

    
709
int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
710
                  int (*parse_fmtp)(AVStream *stream,
711
                                    PayloadContext *data,
712
                                    char *attr, char *value))
713
{
714
    char attr[256];
715
    char *value;
716
    int res;
717
    int value_size = strlen(p) + 1;
718

    
719
    if (!(value = av_malloc(value_size))) {
720
        av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
721
        return AVERROR(ENOMEM);
722
    }
723

    
724
    // remove protocol identifier
725
    while (*p && *p == ' ') p++; // strip spaces
726
    while (*p && *p != ' ') p++; // eat protocol identifier
727
    while (*p && *p == ' ') p++; // strip trailing spaces
728

    
729
    while (ff_rtsp_next_attr_and_value(&p,
730
                                       attr, sizeof(attr),
731
                                       value, value_size)) {
732

    
733
        res = parse_fmtp(stream, data, attr, value);
734
        if (res < 0 && res != AVERROR_PATCHWELCOME) {
735
            av_free(value);
736
            return res;
737
        }
738
    }
739
    av_free(value);
740
    return 0;
741
}