]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec.c
lavf: move ff_codec_get_tag() and ff_codec_get_id() definitions to internal.h
[ffmpeg] / libavformat / rtpdec.c
1 /*
2  * RTP input format
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/mathematics.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/time.h"
25 #include "libavcodec/get_bits.h"
26 #include "avformat.h"
27 #include "mpegts.h"
28 #include "url.h"
29
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          'ffio_open_dyn_packet_buf')
44 */
45
46 static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
47     .enc_name           = "X-MP3-draft-00",
48     .codec_type         = AVMEDIA_TYPE_AUDIO,
49     .codec_id           = AV_CODEC_ID_MP3ADU,
50 };
51
52 static RTPDynamicProtocolHandler speex_dynamic_handler = {
53     .enc_name         = "speex",
54     .codec_type       = AVMEDIA_TYPE_AUDIO,
55     .codec_id         = AV_CODEC_ID_SPEEX,
56 };
57
58 static RTPDynamicProtocolHandler opus_dynamic_handler = {
59     .enc_name         = "opus",
60     .codec_type       = AVMEDIA_TYPE_AUDIO,
61     .codec_id         = AV_CODEC_ID_OPUS,
62 };
63
64 /* statistics functions */
65 static RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
66
67 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
68 {
69     handler->next= RTPFirstDynamicPayloadHandler;
70     RTPFirstDynamicPayloadHandler= handler;
71 }
72
73 void av_register_rtp_dynamic_payload_handlers(void)
74 {
75     ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
76     ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
77     ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
78     ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
79     ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
80     ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
81     ff_register_dynamic_payload_handler(&ff_h263_rfc2190_dynamic_handler);
82     ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
83     ff_register_dynamic_payload_handler(&ff_ilbc_dynamic_handler);
84     ff_register_dynamic_payload_handler(&ff_jpeg_dynamic_handler);
85     ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
86     ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
87     ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
88     ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
89     ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
90     ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
91     ff_register_dynamic_payload_handler(&ff_qcelp_dynamic_handler);
92     ff_register_dynamic_payload_handler(&realmedia_mp3_dynamic_handler);
93     ff_register_dynamic_payload_handler(&speex_dynamic_handler);
94     ff_register_dynamic_payload_handler(&opus_dynamic_handler);
95
96     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
97     ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
98
99     ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
100     ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
101     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
102     ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
103
104     ff_register_dynamic_payload_handler(&ff_g726_16_dynamic_handler);
105     ff_register_dynamic_payload_handler(&ff_g726_24_dynamic_handler);
106     ff_register_dynamic_payload_handler(&ff_g726_32_dynamic_handler);
107     ff_register_dynamic_payload_handler(&ff_g726_40_dynamic_handler);
108 }
109
110 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
111                                                   enum AVMediaType codec_type)
112 {
113     RTPDynamicProtocolHandler *handler;
114     for (handler = RTPFirstDynamicPayloadHandler;
115          handler; handler = handler->next)
116         if (!av_strcasecmp(name, handler->enc_name) &&
117             codec_type == handler->codec_type)
118             return handler;
119     return NULL;
120 }
121
122 RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
123                                                 enum AVMediaType codec_type)
124 {
125     RTPDynamicProtocolHandler *handler;
126     for (handler = RTPFirstDynamicPayloadHandler;
127          handler; handler = handler->next)
128         if (handler->static_payload_id && handler->static_payload_id == id &&
129             codec_type == handler->codec_type)
130             return handler;
131     return NULL;
132 }
133
134 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
135 {
136     int payload_len;
137     while (len >= 4) {
138         payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
139
140         switch (buf[1]) {
141         case RTCP_SR:
142             if (payload_len < 20) {
143                 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
144                 return AVERROR_INVALIDDATA;
145             }
146
147             s->last_rtcp_ntp_time = AV_RB64(buf + 8);
148             s->last_rtcp_timestamp = AV_RB32(buf + 16);
149             if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
150                 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
151                 if (!s->base_timestamp)
152                     s->base_timestamp = s->last_rtcp_timestamp;
153                 s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;
154             }
155
156             break;
157         case RTCP_BYE:
158             return -RTCP_BYE;
159         }
160
161         buf += payload_len;
162         len -= payload_len;
163     }
164     return -1;
165 }
166
167 #define RTP_SEQ_MOD (1<<16)
168
169 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
170 {
171     memset(s, 0, sizeof(RTPStatistics));
172     s->max_seq   = base_sequence;
173     s->probation = 1;
174 }
175
176 /*
177 * called whenever there is a large jump in sequence numbers, or when they get out of probation...
178 */
179 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
180 {
181     s->max_seq        = seq;
182     s->cycles         = 0;
183     s->base_seq       = seq - 1;
184     s->bad_seq        = RTP_SEQ_MOD + 1;
185     s->received       = 0;
186     s->expected_prior = 0;
187     s->received_prior = 0;
188     s->jitter         = 0;
189     s->transit        = 0;
190 }
191
192 /*
193 * returns 1 if we should handle this packet.
194 */
195 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
196 {
197     uint16_t udelta = seq - s->max_seq;
198     const int MAX_DROPOUT    = 3000;
199     const int MAX_MISORDER   = 100;
200     const int MIN_SEQUENTIAL = 2;
201
202     /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
203     if (s->probation) {
204         if (seq == s->max_seq + 1) {
205             s->probation--;
206             s->max_seq = seq;
207             if (s->probation == 0) {
208                 rtp_init_sequence(s, seq);
209                 s->received++;
210                 return 1;
211             }
212         } else {
213             s->probation = MIN_SEQUENTIAL - 1;
214             s->max_seq = seq;
215         }
216     } else if (udelta < MAX_DROPOUT) {
217         // in order, with permissible gap
218         if (seq < s->max_seq) {
219             // sequence number wrapped; count another 64k cycles
220             s->cycles += RTP_SEQ_MOD;
221         }
222         s->max_seq = seq;
223     } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
224         // sequence made a large jump...
225         if (seq == s->bad_seq) {
226             // two sequential packets-- assume that the other side restarted without telling us; just resync.
227             rtp_init_sequence(s, seq);
228         } else {
229             s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
230             return 0;
231         }
232     } else {
233         // duplicate or reordered packet...
234     }
235     s->received++;
236     return 1;
237 }
238
239 int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
240 {
241     AVIOContext *pb;
242     uint8_t *buf;
243     int len;
244     int rtcp_bytes;
245     RTPStatistics *stats = &s->statistics;
246     uint32_t lost;
247     uint32_t extended_max;
248     uint32_t expected_interval;
249     uint32_t received_interval;
250     uint32_t lost_interval;
251     uint32_t expected;
252     uint32_t fraction;
253     uint64_t ntp_time = s->last_rtcp_ntp_time; // TODO: Get local ntp time?
254
255     if (!s->rtp_ctx || (count < 1))
256         return -1;
257
258     /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
259     /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
260     s->octet_count += count;
261     rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
262         RTCP_TX_RATIO_DEN;
263     rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
264     if (rtcp_bytes < 28)
265         return -1;
266     s->last_octet_count = s->octet_count;
267
268     if (avio_open_dyn_buf(&pb) < 0)
269         return -1;
270
271     // Receiver Report
272     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
273     avio_w8(pb, RTCP_RR);
274     avio_wb16(pb, 7); /* length in words - 1 */
275     // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
276     avio_wb32(pb, s->ssrc + 1);
277     avio_wb32(pb, s->ssrc); // server SSRC
278     // some placeholders we should really fill...
279     // RFC 1889/p64
280     extended_max = stats->cycles + stats->max_seq;
281     expected = extended_max - stats->base_seq + 1;
282     lost = expected - stats->received;
283     lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
284     expected_interval = expected - stats->expected_prior;
285     stats->expected_prior = expected;
286     received_interval = stats->received - stats->received_prior;
287     stats->received_prior = stats->received;
288     lost_interval = expected_interval - received_interval;
289     if (expected_interval == 0 || lost_interval <= 0)
290         fraction = 0;
291     else
292         fraction = (lost_interval << 8) / expected_interval;
293
294     fraction = (fraction << 24) | lost;
295
296     avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
297     avio_wb32(pb, extended_max); /* max sequence received */
298     avio_wb32(pb, stats->jitter >> 4); /* jitter */
299
300     if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
301         avio_wb32(pb, 0); /* last SR timestamp */
302         avio_wb32(pb, 0); /* delay since last SR */
303     } else {
304         uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
305         uint32_t delay_since_last = ntp_time - s->last_rtcp_ntp_time;
306
307         avio_wb32(pb, middle_32_bits); /* last SR timestamp */
308         avio_wb32(pb, delay_since_last); /* delay since last SR */
309     }
310
311     // CNAME
312     avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
313     avio_w8(pb, RTCP_SDES);
314     len = strlen(s->hostname);
315     avio_wb16(pb, (6 + len + 3) / 4); /* length in words - 1 */
316     avio_wb32(pb, s->ssrc + 1);
317     avio_w8(pb, 0x01);
318     avio_w8(pb, len);
319     avio_write(pb, s->hostname, len);
320     // padding
321     for (len = (6 + len) % 4; len % 4; len++) {
322         avio_w8(pb, 0);
323     }
324
325     avio_flush(pb);
326     len = avio_close_dyn_buf(pb, &buf);
327     if ((len > 0) && buf) {
328         int av_unused result;
329         av_dlog(s->ic, "sending %d bytes of RR\n", len);
330         result= ffurl_write(s->rtp_ctx, buf, len);
331         av_dlog(s->ic, "result from ffurl_write: %d\n", result);
332         av_free(buf);
333     }
334     return 0;
335 }
336
337 void ff_rtp_send_punch_packets(URLContext* rtp_handle)
338 {
339     AVIOContext *pb;
340     uint8_t *buf;
341     int len;
342
343     /* Send a small RTP packet */
344     if (avio_open_dyn_buf(&pb) < 0)
345         return;
346
347     avio_w8(pb, (RTP_VERSION << 6));
348     avio_w8(pb, 0); /* Payload type */
349     avio_wb16(pb, 0); /* Seq */
350     avio_wb32(pb, 0); /* Timestamp */
351     avio_wb32(pb, 0); /* SSRC */
352
353     avio_flush(pb);
354     len = avio_close_dyn_buf(pb, &buf);
355     if ((len > 0) && buf)
356         ffurl_write(rtp_handle, buf, len);
357     av_free(buf);
358
359     /* Send a minimal RTCP RR */
360     if (avio_open_dyn_buf(&pb) < 0)
361         return;
362
363     avio_w8(pb, (RTP_VERSION << 6));
364     avio_w8(pb, RTCP_RR); /* receiver report */
365     avio_wb16(pb, 1); /* length in words - 1 */
366     avio_wb32(pb, 0); /* our own SSRC */
367
368     avio_flush(pb);
369     len = avio_close_dyn_buf(pb, &buf);
370     if ((len > 0) && buf)
371         ffurl_write(rtp_handle, buf, len);
372     av_free(buf);
373 }
374
375
376 /**
377  * open a new RTP parse context for stream 'st'. 'st' can be NULL for
378  * MPEG2TS streams to indicate that they should be demuxed inside the
379  * rtp demux (otherwise AV_CODEC_ID_MPEG2TS packets are returned)
380  */
381 RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
382 {
383     RTPDemuxContext *s;
384
385     s = av_mallocz(sizeof(RTPDemuxContext));
386     if (!s)
387         return NULL;
388     s->payload_type = payload_type;
389     s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
390     s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
391     s->ic = s1;
392     s->st = st;
393     s->queue_size = queue_size;
394     rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
395     if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
396         s->ts = ff_mpegts_parse_open(s->ic);
397         if (s->ts == NULL) {
398             av_free(s);
399             return NULL;
400         }
401     } else if (st) {
402         switch(st->codec->codec_id) {
403         case AV_CODEC_ID_MPEG1VIDEO:
404         case AV_CODEC_ID_MPEG2VIDEO:
405         case AV_CODEC_ID_MP2:
406         case AV_CODEC_ID_MP3:
407         case AV_CODEC_ID_MPEG4:
408         case AV_CODEC_ID_H263:
409         case AV_CODEC_ID_H264:
410             st->need_parsing = AVSTREAM_PARSE_FULL;
411             break;
412         case AV_CODEC_ID_VORBIS:
413             st->need_parsing = AVSTREAM_PARSE_HEADERS;
414             break;
415         case AV_CODEC_ID_ADPCM_G722:
416             /* According to RFC 3551, the stream clock rate is 8000
417              * even if the sample rate is 16000. */
418             if (st->codec->sample_rate == 8000)
419                 st->codec->sample_rate = 16000;
420             break;
421         default:
422             break;
423         }
424     }
425     // needed to send back RTCP RR in RTSP sessions
426     s->rtp_ctx = rtpc;
427     gethostname(s->hostname, sizeof(s->hostname));
428     return s;
429 }
430
431 void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
432                                        RTPDynamicProtocolHandler *handler)
433 {
434     s->dynamic_protocol_context = ctx;
435     s->parse_packet = handler->parse_packet;
436 }
437
438 /**
439  * This was the second switch in rtp_parse packet.  Normalizes time, if required, sets stream_index, etc.
440  */
441 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
442 {
443     if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
444         return; /* Timestamp already set by depacketizer */
445     if (timestamp == RTP_NOTS_VALUE)
446         return;
447
448     if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
449         int64_t addend;
450         int delta_timestamp;
451
452         /* compute pts from timestamp with received ntp_time */
453         delta_timestamp = timestamp - s->last_rtcp_timestamp;
454         /* convert to the PTS timebase */
455         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);
456         pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
457                    delta_timestamp;
458         return;
459     }
460
461     if (!s->base_timestamp)
462         s->base_timestamp = timestamp;
463     /* assume that the difference is INT32_MIN < x < INT32_MAX, but allow the first timestamp to exceed INT32_MAX */
464     if (!s->timestamp)
465         s->unwrapped_timestamp += timestamp;
466     else
467         s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
468     s->timestamp = timestamp;
469     pkt->pts = s->unwrapped_timestamp + s->range_start_offset - s->base_timestamp;
470 }
471
472 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
473                                      const uint8_t *buf, int len)
474 {
475     unsigned int ssrc, h;
476     int payload_type, seq, ret, flags = 0;
477     int ext;
478     AVStream *st;
479     uint32_t timestamp;
480     int rv= 0;
481
482     ext = buf[0] & 0x10;
483     payload_type = buf[1] & 0x7f;
484     if (buf[1] & 0x80)
485         flags |= RTP_FLAG_MARKER;
486     seq  = AV_RB16(buf + 2);
487     timestamp = AV_RB32(buf + 4);
488     ssrc = AV_RB32(buf + 8);
489     /* store the ssrc in the RTPDemuxContext */
490     s->ssrc = ssrc;
491
492     /* NOTE: we can handle only one payload type */
493     if (s->payload_type != payload_type)
494         return -1;
495
496     st = s->st;
497     // only do something with this if all the rtp checks pass...
498     if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
499     {
500         av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
501                payload_type, seq, ((s->seq + 1) & 0xffff));
502         return -1;
503     }
504
505     if (buf[0] & 0x20) {
506         int padding = buf[len - 1];
507         if (len >= 12 + padding)
508             len -= padding;
509     }
510
511     s->seq = seq;
512     len -= 12;
513     buf += 12;
514
515     /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
516     if (ext) {
517         if (len < 4)
518             return -1;
519         /* calculate the header extension length (stored as number
520          * of 32-bit words) */
521         ext = (AV_RB16(buf + 2) + 1) << 2;
522
523         if (len < ext)
524             return -1;
525         // skip past RTP header extension
526         len -= ext;
527         buf += ext;
528     }
529
530     if (!st) {
531         /* specific MPEG2TS demux support */
532         ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
533         /* The only error that can be returned from ff_mpegts_parse_packet
534          * is "no more data to return from the provided buffer", so return
535          * AVERROR(EAGAIN) for all errors */
536         if (ret < 0)
537             return AVERROR(EAGAIN);
538         if (ret < len) {
539             s->read_buf_size = len - ret;
540             memcpy(s->buf, buf + ret, s->read_buf_size);
541             s->read_buf_index = 0;
542             return 1;
543         }
544         return 0;
545     } else if (s->parse_packet) {
546         rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
547                              s->st, pkt, &timestamp, buf, len, flags);
548     } else {
549         // at this point, the RTP header has been stripped;  This is ASSUMING that there is only 1 CSRC, which in't wise.
550         switch(st->codec->codec_id) {
551         case AV_CODEC_ID_MP2:
552         case AV_CODEC_ID_MP3:
553             /* better than nothing: skip mpeg audio RTP header */
554             if (len <= 4)
555                 return -1;
556             h = AV_RB32(buf);
557             len -= 4;
558             buf += 4;
559             av_new_packet(pkt, len);
560             memcpy(pkt->data, buf, len);
561             break;
562         case AV_CODEC_ID_MPEG1VIDEO:
563         case AV_CODEC_ID_MPEG2VIDEO:
564             /* better than nothing: skip mpeg video RTP header */
565             if (len <= 4)
566                 return -1;
567             h = AV_RB32(buf);
568             buf += 4;
569             len -= 4;
570             if (h & (1 << 26)) {
571                 /* mpeg2 */
572                 if (len <= 4)
573                     return -1;
574                 buf += 4;
575                 len -= 4;
576             }
577             av_new_packet(pkt, len);
578             memcpy(pkt->data, buf, len);
579             break;
580         default:
581             av_new_packet(pkt, len);
582             memcpy(pkt->data, buf, len);
583             break;
584         }
585
586         pkt->stream_index = st->index;
587     }
588
589     // now perform timestamp things....
590     finalize_packet(s, pkt, timestamp);
591
592     return rv;
593 }
594
595 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
596 {
597     while (s->queue) {
598         RTPPacket *next = s->queue->next;
599         av_free(s->queue->buf);
600         av_free(s->queue);
601         s->queue = next;
602     }
603     s->seq       = 0;
604     s->queue_len = 0;
605     s->prev_ret  = 0;
606 }
607
608 static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
609 {
610     uint16_t seq = AV_RB16(buf + 2);
611     RTPPacket *cur = s->queue, *prev = NULL, *packet;
612
613     /* Find the correct place in the queue to insert the packet */
614     while (cur) {
615         int16_t diff = seq - cur->seq;
616         if (diff < 0)
617             break;
618         prev = cur;
619         cur = cur->next;
620     }
621
622     packet = av_mallocz(sizeof(*packet));
623     if (!packet)
624         return;
625     packet->recvtime = av_gettime();
626     packet->seq = seq;
627     packet->len = len;
628     packet->buf = buf;
629     packet->next = cur;
630     if (prev)
631         prev->next = packet;
632     else
633         s->queue = packet;
634     s->queue_len++;
635 }
636
637 static int has_next_packet(RTPDemuxContext *s)
638 {
639     return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
640 }
641
642 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
643 {
644     return s->queue ? s->queue->recvtime : 0;
645 }
646
647 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
648 {
649     int rv;
650     RTPPacket *next;
651
652     if (s->queue_len <= 0)
653         return -1;
654
655     if (!has_next_packet(s))
656         av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
657                "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
658
659     /* Parse the first packet in the queue, and dequeue it */
660     rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
661     next = s->queue->next;
662     av_free(s->queue->buf);
663     av_free(s->queue);
664     s->queue = next;
665     s->queue_len--;
666     return rv;
667 }
668
669 static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
670                                 uint8_t **bufptr, int len)
671 {
672     uint8_t* buf = bufptr ? *bufptr : NULL;
673     int ret, flags = 0;
674     uint32_t timestamp;
675     int rv= 0;
676
677     if (!buf) {
678         /* If parsing of the previous packet actually returned 0 or an error,
679          * there's nothing more to be parsed from that packet, but we may have
680          * indicated that we can return the next enqueued packet. */
681         if (s->prev_ret <= 0)
682             return rtp_parse_queued_packet(s, pkt);
683         /* return the next packets, if any */
684         if(s->st && s->parse_packet) {
685             /* timestamp should be overwritten by parse_packet, if not,
686              * the packet is left with pts == AV_NOPTS_VALUE */
687             timestamp = RTP_NOTS_VALUE;
688             rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
689                                 s->st, pkt, &timestamp, NULL, 0, flags);
690             finalize_packet(s, pkt, timestamp);
691             return rv;
692         } else {
693             // TODO: Move to a dynamic packet handler (like above)
694             if (s->read_buf_index >= s->read_buf_size)
695                 return AVERROR(EAGAIN);
696             ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
697                                       s->read_buf_size - s->read_buf_index);
698             if (ret < 0)
699                 return AVERROR(EAGAIN);
700             s->read_buf_index += ret;
701             if (s->read_buf_index < s->read_buf_size)
702                 return 1;
703             else
704                 return 0;
705         }
706     }
707
708     if (len < 12)
709         return -1;
710
711     if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
712         return -1;
713     if (RTP_PT_IS_RTCP(buf[1])) {
714         return rtcp_parse_packet(s, buf, len);
715     }
716
717     if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
718         /* First packet, or no reordering */
719         return rtp_parse_packet_internal(s, pkt, buf, len);
720     } else {
721         uint16_t seq = AV_RB16(buf + 2);
722         int16_t diff = seq - s->seq;
723         if (diff < 0) {
724             /* Packet older than the previously emitted one, drop */
725             av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
726                    "RTP: dropping old packet received too late\n");
727             return -1;
728         } else if (diff <= 1) {
729             /* Correct packet */
730             rv = rtp_parse_packet_internal(s, pkt, buf, len);
731             return rv;
732         } else {
733             /* Still missing some packet, enqueue this one. */
734             enqueue_packet(s, buf, len);
735             *bufptr = NULL;
736             /* Return the first enqueued packet if the queue is full,
737              * even if we're missing something */
738             if (s->queue_len >= s->queue_size)
739                 return rtp_parse_queued_packet(s, pkt);
740             return -1;
741         }
742     }
743 }
744
745 /**
746  * Parse an RTP or RTCP packet directly sent as a buffer.
747  * @param s RTP parse context.
748  * @param pkt returned packet
749  * @param bufptr pointer to the input buffer or NULL to read the next packets
750  * @param len buffer len
751  * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
752  * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
753  */
754 int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
755                         uint8_t **bufptr, int len)
756 {
757     int rv = rtp_parse_one_packet(s, pkt, bufptr, len);
758     s->prev_ret = rv;
759     while (rv == AVERROR(EAGAIN) && has_next_packet(s))
760         rv = rtp_parse_queued_packet(s, pkt);
761     return rv ? rv : has_next_packet(s);
762 }
763
764 void ff_rtp_parse_close(RTPDemuxContext *s)
765 {
766     ff_rtp_reset_packet_queue(s);
767     if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
768         ff_mpegts_parse_close(s->ts);
769     }
770     av_free(s);
771 }
772
773 int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
774                   int (*parse_fmtp)(AVStream *stream,
775                                     PayloadContext *data,
776                                     char *attr, char *value))
777 {
778     char attr[256];
779     char *value;
780     int res;
781     int value_size = strlen(p) + 1;
782
783     if (!(value = av_malloc(value_size))) {
784         av_log(NULL, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
785         return AVERROR(ENOMEM);
786     }
787
788     // remove protocol identifier
789     while (*p && *p == ' ') p++; // strip spaces
790     while (*p && *p != ' ') p++; // eat protocol identifier
791     while (*p && *p == ' ') p++; // strip trailing spaces
792
793     while (ff_rtsp_next_attr_and_value(&p,
794                                        attr, sizeof(attr),
795                                        value, value_size)) {
796
797         res = parse_fmtp(stream, data, attr, value);
798         if (res < 0 && res != AVERROR_PATCHWELCOME) {
799             av_free(value);
800             return res;
801         }
802     }
803     av_free(value);
804     return 0;
805 }
806
807 int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
808 {
809     av_init_packet(pkt);
810
811     pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
812     pkt->stream_index = stream_idx;
813     pkt->destruct     = av_destruct_packet;
814     *dyn_buf = NULL;
815     return pkt->size;
816 }