FFmpeg coverage


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