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