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