FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/rtpdec.c
Date: 2024-04-25 15:36:26
Exec Total Coverage
Lines: 0 496 0.0%
Functions: 0 29 0.0%
Branches: 0 272 0.0%

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