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