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