FFmpeg
Loading...
Searching...
No Matches
rtpdec.c
Go to the documentation of this file.
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
23#include "libavutil/avstring.h"
25#include "libavutil/mem.h"
26#include "libavutil/time.h"
27
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
41 .enc_name = "L24",
42 .codec_type = AVMEDIA_TYPE_AUDIO,
43 .codec_id = AV_CODEC_ID_PCM_S24BE,
44};
45
47 .enc_name = "GSM",
48 .codec_type = AVMEDIA_TYPE_AUDIO,
49 .codec_id = AV_CODEC_ID_GSM,
50};
51
53 .enc_name = "X-MP3-draft-00",
54 .codec_type = AVMEDIA_TYPE_AUDIO,
55 .codec_id = AV_CODEC_ID_MP3ADU,
56};
57
59 .enc_name = "speex",
60 .codec_type = AVMEDIA_TYPE_AUDIO,
61 .codec_id = AV_CODEC_ID_SPEEX,
62};
63
64static 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
74
76 /* rtp */
126 /* rdt */
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 */
144{
145 uintptr_t i = (uintptr_t)*opaque;
147
148 if (r)
149 *opaque = (void*)(i + 1);
150
151 return r;
152}
153
156{
157 void *i = 0;
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
170{
171 void *i = 0;
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
181static 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 < 28) {
191 av_log(s->ic, AV_LOG_ERROR, "Invalid RTCP SR packet length\n");
192 return AVERROR_INVALIDDATA;
193 }
194
195 s->last_sr.ssrc = AV_RB32(buf + 4);
196 s->last_sr.ntp_timestamp = AV_RB64(buf + 8);
197 s->last_sr.rtp_timestamp = AV_RB32(buf + 16);
198 s->last_sr.sender_nb_packets = AV_RB32(buf + 20);
199 s->last_sr.sender_nb_bytes = AV_RB32(buf + 24);
200
201 s->pending_sr = 1;
202 s->last_rtcp_reception_time = av_gettime_relative();
203
204 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
205 s->first_rtcp_ntp_time = s->last_sr.ntp_timestamp;
206 if (!s->base_timestamp)
207 s->base_timestamp = s->last_sr.rtp_timestamp;
208 s->rtcp_ts_offset = (int32_t)(s->last_sr.rtp_timestamp - s->base_timestamp);
209 }
210
211 break;
212 case RTCP_BYE:
213 return -RTCP_BYE;
214 }
215
216 buf += payload_len;
217 len -= payload_len;
218 }
219 return -1;
220}
221
222#define RTP_SEQ_MOD (1 << 16)
223
224static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
225{
226 memset(s, 0, sizeof(RTPStatistics));
227 s->max_seq = base_sequence;
228 s->probation = 1;
229}
230
231/*
232 * Called whenever there is a large jump in sequence numbers,
233 * or when they get out of probation...
234 */
235static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
236{
237 s->max_seq = seq;
238 s->cycles = 0;
239 s->base_seq = seq - 1;
240 s->bad_seq = RTP_SEQ_MOD + 1;
241 s->received = 0;
242 s->expected_prior = 0;
243 s->received_prior = 0;
244 s->jitter = 0;
245 s->transit = 0;
246}
247
248/* Returns 1 if we should handle this packet. */
250{
251 uint16_t udelta = seq - s->max_seq;
252 const int MAX_DROPOUT = 3000;
253 const int MAX_MISORDER = 100;
254 const int MIN_SEQUENTIAL = 2;
255
256 /* source not valid until MIN_SEQUENTIAL packets with sequence
257 * seq. numbers have been received */
258 if (s->probation) {
259 if (seq == s->max_seq + 1) {
260 s->probation--;
261 s->max_seq = seq;
262 if (s->probation == 0) {
263 rtp_init_sequence(s, seq);
264 s->received++;
265 return 1;
266 }
267 } else {
268 s->probation = MIN_SEQUENTIAL - 1;
269 s->max_seq = seq;
270 }
271 } else if (udelta < MAX_DROPOUT) {
272 // in order, with permissible gap
273 if (seq < s->max_seq) {
274 // sequence number wrapped; count another 64k cycles
275 s->cycles += RTP_SEQ_MOD;
276 }
277 s->max_seq = seq;
278 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
279 // sequence made a large jump...
280 if (seq == s->bad_seq) {
281 /* two sequential packets -- assume that the other side
282 * restarted without telling us; just resync. */
283 rtp_init_sequence(s, seq);
284 } else {
285 s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
286 return 0;
287 }
288 } else {
289 // duplicate or reordered packet...
290 }
291 s->received++;
292 return 1;
293}
294
295static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp,
296 uint32_t arrival_timestamp)
297{
298 // Most of this is pretty straight from RFC 3550 appendix A.8
299 uint32_t transit = arrival_timestamp - sent_timestamp;
300 uint32_t prev_transit = s->transit;
301 int32_t d = transit - prev_transit;
302 // Doing the FFABS() call directly on the "transit - prev_transit"
303 // expression doesn't work, since it's an unsigned expression. Doing the
304 // transit calculation in unsigned is desired though, since it most
305 // probably will need to wrap around.
306 d = FFABS(d);
307 s->transit = transit;
308 if (!prev_transit)
309 return;
310 s->jitter += d - (int32_t) ((s->jitter + 8) >> 4);
311}
312
314 AVIOContext *avio, int count)
315{
316 AVIOContext *pb;
317 uint8_t *buf;
318 int len;
319 int rtcp_bytes;
320 RTPStatistics *stats = &s->statistics;
321 uint32_t lost;
322 uint32_t extended_max;
323 uint32_t expected_interval;
324 uint32_t received_interval;
325 int32_t lost_interval;
326 uint32_t expected;
327 uint32_t fraction;
328
329 if ((!fd && !avio) || (count < 1))
330 return -1;
331
332 /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
333 /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
334 s->octet_count += count;
335 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
337 rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
338 if (rtcp_bytes < 28)
339 return -1;
340 s->last_octet_count = s->octet_count;
341
342 if (!fd)
343 pb = avio;
344 else if (avio_open_dyn_buf(&pb) < 0)
345 return -1;
346
347 // Receiver Report
348 avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
349 avio_w8(pb, RTCP_RR);
350 avio_wb16(pb, 7); /* length in words - 1 */
351 // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
352 avio_wb32(pb, s->ssrc + 1);
353 avio_wb32(pb, s->ssrc); // server SSRC
354 // some placeholders we should really fill...
355 // RFC 1889/p64
356 extended_max = stats->cycles + stats->max_seq;
357 expected = extended_max - stats->base_seq;
358 lost = av_zero_extend(av_clip_intp2(expected - stats->received, 23), 24);
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_sr.ntp_timestamp == 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_sr.ntp_timestamp >> 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 av_unused int 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
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
439static 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
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/**
534 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
535 * MPEG-2 TS streams.
536 */
538 int payload_type, int queue_size)
539{
541
542 s = av_mallocz(sizeof(RTPDemuxContext));
543 if (!s)
544 return NULL;
545 s->payload_type = payload_type;
546 s->last_sr.ntp_timestamp = AV_NOPTS_VALUE;
547 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
548 s->ic = s1;
549 s->st = st;
550 s->queue_size = queue_size;
551
552 av_log(s->ic, AV_LOG_VERBOSE, "setting jitter buffer size to %d\n",
553 s->queue_size);
554
555 rtp_init_statistics(&s->statistics, 0);
556 if (st) {
557 switch (st->codecpar->codec_id) {
559 /* According to RFC 3551, the stream clock rate is 8000
560 * even if the sample rate is 16000. */
561 if (st->codecpar->sample_rate == 8000)
562 st->codecpar->sample_rate = 16000;
563 break;
565 AVCodecParameters *par = st->codecpar;
568 par->bit_rate = par->block_align * 8LL * par->sample_rate;
569 break;
570 }
571 default:
572 break;
573 }
574 }
575 // needed to send back RTCP RR in RTSP sessions
576 gethostname(s->hostname, sizeof(s->hostname));
577 return s;
578}
579
582{
583 s->dynamic_protocol_context = ctx;
584 s->handler = handler;
585}
586
588 const char *params)
589{
590 int ret = ff_srtp_set_crypto(&s->srtp, suite, params);
591 if (ret < 0)
592 return ret;
593 s->srtp_enabled = 1;
594 return 0;
595}
596
597static int rtp_set_prft(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp) {
598 int64_t rtcp_time, delta_time;
599 int32_t delta_timestamp;
600
604 if (!prft)
605 return AVERROR(ENOMEM);
606
607 rtcp_time = ff_parse_ntp_time(s->last_sr.ntp_timestamp) - NTP_OFFSET_US;
608 /* Cast to int32_t to handle timestamp wraparound correctly */
609 delta_timestamp = (int32_t)(timestamp - s->last_sr.rtp_timestamp);
610 delta_time = av_rescale_q(delta_timestamp, s->st->time_base, AV_TIME_BASE_Q);
611
612 prft->wallclock = rtcp_time + delta_time;
613 prft->flags = 24;
614 return 0;
615}
616
621 if (!sr)
622 return AVERROR(ENOMEM);
623
624 memcpy(sr, &s->last_sr, sizeof(AVRTCPSenderReport));
625 s->pending_sr = 0;
626 return 0;
627}
628
629/**
630 * This was the second switch in rtp_parse packet.
631 * Normalizes time, if required, sets stream_index, etc.
632 */
633static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
634{
635 if (s->pending_sr) {
636 int ret = rtp_add_sr_sidedata(s, pkt);
637 if (ret < 0)
638 av_log(s->ic, AV_LOG_WARNING, "rtpdec: failed to add SR sidedata\n");
639 }
640
641 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
642 return; /* Timestamp already set by depacketizer */
643 if (timestamp == RTP_NOTS_VALUE)
644 return;
645
646 if (s->last_sr.ntp_timestamp != AV_NOPTS_VALUE) {
647 if (rtp_set_prft(s, pkt, timestamp) < 0) {
648 av_log(s->ic, AV_LOG_WARNING, "rtpdec: failed to set prft");
649 }
650 }
651
652 if (s->last_sr.ntp_timestamp != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
653 int64_t addend;
654 int32_t delta_timestamp;
655
656 /* compute pts from timestamp with received ntp_time */
657 /* Cast to int32_t to handle timestamp wraparound correctly */
658 delta_timestamp = (int32_t)(timestamp - s->last_sr.rtp_timestamp);
659 /* convert to the PTS timebase */
660 addend = av_rescale(s->last_sr.ntp_timestamp - s->first_rtcp_ntp_time,
661 s->st->time_base.den,
662 (uint64_t) s->st->time_base.num << 32);
663 pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
664 delta_timestamp;
665 return;
666 }
667
668 if (!s->base_timestamp)
669 s->base_timestamp = timestamp;
670 /* assume that the difference is INT32_MIN < x < INT32_MAX,
671 * but allow the first timestamp to exceed INT32_MAX */
672 if (!s->timestamp)
673 s->unwrapped_timestamp += timestamp;
674 else
675 s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
676 s->timestamp = timestamp;
677 pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
678 s->base_timestamp;
679}
680
682 const uint8_t *buf, int len)
683{
684 unsigned int ssrc;
685 int payload_type, seq, flags = 0;
686 int ext, csrc;
687 AVStream *st;
688 uint32_t timestamp;
689 int rv = 0;
690
691 csrc = buf[0] & 0x0f;
692 ext = buf[0] & 0x10;
693 payload_type = buf[1] & 0x7f;
694 if (buf[1] & 0x80)
696 seq = AV_RB16(buf + 2);
697 timestamp = AV_RB32(buf + 4);
698 ssrc = AV_RB32(buf + 8);
699 /* store the ssrc in the RTPDemuxContext */
700 s->ssrc = ssrc;
701
702 /* NOTE: we can handle only one payload type */
703 if (s->payload_type != payload_type)
704 return -1;
705
706 st = s->st;
707 // only do something with this if all the rtp checks pass...
708 if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
709 av_log(s->ic, AV_LOG_ERROR,
710 "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
711 payload_type, seq, ((s->seq + 1) & 0xffff));
712 return -1;
713 }
714
715 if (buf[0] & 0x20) {
716 int padding = buf[len - 1];
717 if (len >= 12 + padding)
718 len -= padding;
719 }
720
721 s->seq = seq;
722 len -= 12;
723 buf += 12;
724
725 len -= 4 * csrc;
726 buf += 4 * csrc;
727 if (len < 0)
728 return AVERROR_INVALIDDATA;
729
730 /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
731 if (ext) {
732 if (len < 4)
733 return -1;
734 /* calculate the header extension length (stored as number
735 * of 32-bit words) */
736 ext = (AV_RB16(buf + 2) + 1) << 2;
737
738 if (len < ext)
739 return -1;
740 // skip past RTP header extension
741 len -= ext;
742 buf += ext;
743 }
744
745 if (s->handler && s->handler->parse_packet) {
746 rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
747 s->st, pkt, &timestamp, buf, len, seq,
748 flags);
749 } else if (st) {
750 if ((rv = av_new_packet(pkt, len)) < 0)
751 return rv;
752 memcpy(pkt->data, buf, len);
753 pkt->stream_index = st->index;
754 } else {
755 return AVERROR(EINVAL);
756 }
757
758 // now perform timestamp things....
759 finalize_packet(s, pkt, timestamp);
760
761 return rv;
762}
763
765{
766 while (s->queue) {
767 RTPPacket *next = s->queue->next;
768 av_freep(&s->queue->buf);
769 av_freep(&s->queue);
770 s->queue = next;
771 }
772 s->seq = 0;
773 s->queue_len = 0;
774 s->prev_ret = 0;
775}
776
777static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
778{
779 uint16_t seq = AV_RB16(buf + 2);
780 RTPPacket **cur = &s->queue, *packet;
781
782 /* Find the correct place in the queue to insert the packet */
783 while (*cur) {
784 int16_t diff = seq - (*cur)->seq;
785 if (diff < 0)
786 break;
787 cur = &(*cur)->next;
788 }
789
790 packet = av_mallocz(sizeof(*packet));
791 if (!packet)
792 return AVERROR(ENOMEM);
793 packet->recvtime = av_gettime_relative();
794 packet->seq = seq;
795 packet->len = len;
796 packet->buf = buf;
797 packet->next = *cur;
798 *cur = packet;
799 s->queue_len++;
800
801 return 0;
802}
803
805{
806 return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
807}
808
810{
811 return s->queue ? s->queue->recvtime : 0;
812}
813
815{
816 int rv;
817 RTPPacket *next;
818
819 if (s->queue_len <= 0)
820 return -1;
821
822 if (!has_next_packet(s)) {
823 int pkt_missed = s->queue->seq - s->seq - 1;
824
825 if (pkt_missed < 0)
826 pkt_missed += UINT16_MAX;
828 "RTP: missed %d packets\n", pkt_missed);
829 }
830
831 /* Parse the first packet in the queue, and dequeue it */
832 rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
833 next = s->queue->next;
834 av_freep(&s->queue->buf);
835 av_freep(&s->queue);
836 s->queue = next;
837 s->queue_len--;
838 return rv;
839}
840
842 uint8_t **bufptr, int len)
843{
844 uint8_t *buf = bufptr ? *bufptr : NULL;
845 int flags = 0;
846 uint32_t timestamp;
847 int rv = 0;
848
849 if (!buf) {
850 /* If parsing of the previous packet actually returned 0 or an error,
851 * there's nothing more to be parsed from that packet, but we may have
852 * indicated that we can return the next enqueued packet. */
853 if (s->prev_ret <= 0)
855 /* return the next packets, if any */
856 if (s->handler && s->handler->parse_packet) {
857 /* timestamp should be overwritten by parse_packet, if not,
858 * the packet is left with pts == AV_NOPTS_VALUE */
859 timestamp = RTP_NOTS_VALUE;
860 rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
861 s->st, pkt, &timestamp, NULL, 0, 0,
862 flags);
863 finalize_packet(s, pkt, timestamp);
864 return rv;
865 }
866 }
867
868 if (len < 12)
869 return -1;
870
871 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
872 return -1;
873 if (RTP_PT_IS_RTCP(buf[1])) {
874 return rtcp_parse_packet(s, buf, len);
875 }
876
877 if (s->st) {
878 int64_t received = av_gettime_relative();
879 uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,
880 s->st->time_base);
881 timestamp = AV_RB32(buf + 4);
882 // Calculate the jitter immediately, before queueing the packet
883 // into the reordering queue.
884 rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);
885 }
886
887 if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
888 /* First packet, or no reordering */
889 return rtp_parse_packet_internal(s, pkt, buf, len);
890 } else {
891 uint16_t seq = AV_RB16(buf + 2);
892 int16_t diff = seq - s->seq;
893 if (diff < 0) {
894 /* Packet older than the previously emitted one, drop */
896 "RTP: dropping old packet received too late\n");
897 return -1;
898 } else if (diff <= 1) {
899 /* Correct packet */
900 rv = rtp_parse_packet_internal(s, pkt, buf, len);
901 return rv;
902 } else {
903 /* Still missing some packet, enqueue this one. */
904 rv = enqueue_packet(s, buf, len);
905 if (rv < 0)
906 return rv;
907 *bufptr = NULL;
908 /* Return the first enqueued packet if the queue is full,
909 * even if we're missing something */
910 if (s->queue_len >= s->queue_size) {
911 av_log(s->ic, AV_LOG_WARNING, "jitter buffer full\n");
913 }
914 return -1;
915 }
916 }
917}
918
919/**
920 * Parse an RTP or RTCP packet directly sent as a buffer.
921 * @param s RTP parse context.
922 * @param pkt returned packet
923 * @param bufptr pointer to the input buffer or NULL to read the next packets
924 * @param len buffer len
925 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
926 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
927 */
929 uint8_t **bufptr, int len)
930{
931 int rv;
932 if (s->srtp_enabled && bufptr && ff_srtp_decrypt(&s->srtp, *bufptr, &len) < 0)
933 return -1;
934 rv = rtp_parse_one_packet(s, pkt, bufptr, len);
935 s->prev_ret = rv;
936 while (rv < 0 && has_next_packet(s))
938 return rv ? rv : has_next_packet(s);
939}
940
947
949 AVStream *stream, PayloadContext *data, const char *p,
951 AVStream *stream,
953 const char *attr, const char *value))
954{
955 char attr[256];
956 char *value;
957 int res;
958 int value_size = strlen(p) + 1;
959
960 if (!(value = av_malloc(value_size))) {
961 av_log(s, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
962 return AVERROR(ENOMEM);
963 }
964
965 // remove protocol identifier
966 while (*p && *p == ' ')
967 p++; // strip spaces
968 while (*p && *p != ' ')
969 p++; // eat protocol identifier
970 while (*p && *p == ' ')
971 p++; // strip trailing spaces
972
974 attr, sizeof(attr),
975 value, value_size)) {
976 res = parse_fmtp(s, stream, data, attr, value);
977 if (res < 0 && res != AVERROR_PATCHWELCOME) {
978 av_free(value);
979 return res;
980 }
981 }
982 av_free(value);
983 return 0;
984}
985
986int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
987{
988 int ret;
990
991 pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
992 pkt->stream_index = stream_idx;
993 *dyn_buf = NULL;
994 if ((ret = av_packet_from_data(pkt, pkt->data, pkt->size)) < 0) {
995 av_freep(&pkt->data);
996 return ret;
997 }
998 return pkt->size;
999}
SwsAArch64OpImplParams params
Definition ops.c:51
static AVFormatContext * ctx
int32_t
Main libavformat public API header.
void avio_w8(AVIOContext *s, int b)
Definition aviobuf.c:184
void avio_wb32(AVIOContext *s, unsigned int val)
Definition aviobuf.c:368
void avio_wb16(AVIOContext *s, unsigned int val)
Definition aviobuf.c:446
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition aviobuf.c:1369
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition aviobuf.c:228
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition aviobuf.c:1324
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define av_clip_intp2
Definition common.h:121
#define av_zero_extend
Definition common.h:151
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static AVPacket * pkt
double value
Definition eval.c:102
static CheckasmStats stats
Definition checkasm.c:75
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition utils.c:556
@ AV_CODEC_ID_PCM_S24BE
Definition codec_id.h:344
@ AV_CODEC_ID_GSM
as in Berlin toast format
Definition codec_id.h:472
@ AV_CODEC_ID_ADPCM_G722
Definition codec_id.h:399
@ AV_CODEC_ID_TEXT
raw UTF-8 text
Definition codec_id.h:569
@ AV_CODEC_ID_MP3ADU
Definition codec_id.h:467
@ AV_CODEC_ID_SPEEX
Definition codec_id.h:489
@ AV_CODEC_ID_PCM_MULAW
Definition codec_id.h:337
@ AV_PKT_DATA_PRFT
Producer Reference Time data corresponding to the AVProducerReferenceTime struct, usually exported by...
Definition packet.h:265
@ AV_PKT_DATA_RTCP_SR
Contains the last received RTCP SR (Sender Report) information in the form of the AVRTCPSenderReport ...
Definition packet.h:363
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition packet.c:231
int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size)
Initialize a reference-counted packet from av_malloc()ed data.
Definition packet.c:172
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
AVMediaType
Definition avutil.h:198
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE
Internal time base represented as integer.
Definition avutil.h:253
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition avutil.h:263
#define r
Definition input.c:42
#define AV_RB32(p)
#define AV_RB64(p)
#define AV_RB16(p)
uint64_t ff_parse_ntp_time(uint64_t ntp_ts)
Parse the NTP time in microseconds (since NTP epoch).
Definition utils.c:284
#define NTP_OFFSET_US
Definition internal.h:422
#define av_unused
Definition attributes.h:164
static void handler(vbi_event *ev, void *user_data)
#define FFMIN(a, b)
Definition macros.h:49
Memory handling functions.
const char data[16]
Definition mxf.c:149
#define av_malloc(s)
Definition ops_static.c:52
const char * name
Definition qsvenc.c:142
enum AVMediaType codec_type
Definition rtp.c:37
#define RTP_VERSION
Definition rtp.h:80
#define RTP_PT_IS_RTCP(x)
Definition rtp.h:112
@ RTCP_RTPFB
Definition rtp.h:104
@ RTCP_RR
Definition rtp.h:100
@ RTCP_SR
Definition rtp.h:99
@ RTCP_PSFB
Definition rtp.h:105
@ RTCP_SDES
Definition rtp.h:101
@ RTCP_BYE
Definition rtp.h:102
#define RTCP_TX_RATIO_NUM
Definition rtp.h:84
#define RTCP_TX_RATIO_DEN
Definition rtp.h:85
static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing, uint16_t *missing_mask)
Definition rtpdec.c:439
static int rtp_set_prft(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
Definition rtpdec.c:597
int ff_parse_fmtp(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *p, int(*parse_fmtp)(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *attr, const char *value))
Definition rtpdec.c:948
const RTPDynamicProtocolHandler ff_rdt_live_audio_handler
RTPDemuxContext * ff_rtp_parse_open(AVFormatContext *s1, AVStream *st, int payload_type, int queue_size)
open a new RTP parse context for stream 'st'.
Definition rtpdec.c:537
void ff_rtp_parse_close(RTPDemuxContext *s)
Definition rtpdec.c:941
static const RTPDynamicProtocolHandler gsm_dynamic_handler
Definition rtpdec.c:46
static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
Definition rtpdec.c:181
void ff_rtp_send_punch_packets(URLContext *rtp_handle)
Send a dummy packet on both port pairs to set up the connection state in potential NAT routers,...
Definition rtpdec.c:415
static const RTPDynamicProtocolHandler *const rtp_dynamic_protocol_handler_list[]
Definition rtpdec.c:75
const RTPDynamicProtocolHandler * ff_rtp_handler_find_by_id(int id, enum AVMediaType codec_type)
Find a registered rtp dynamic protocol handler with a matching codec ID.
Definition rtpdec.c:168
static const RTPDynamicProtocolHandler * rtp_handler_iterate(void **opaque)
Iterate over all registered rtp dynamic protocol handlers.
Definition rtpdec.c:143
const RTPDynamicProtocolHandler ff_rdt_audio_handler
static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len)
Definition rtpdec.c:841
static const RTPDynamicProtocolHandler l24_dynamic_handler
Definition rtpdec.c:40
static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
Definition rtpdec.c:295
int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd, AVIOContext *avio, int count)
some rtp servers assume client is dead if they don't hear from them... so we send a Receiver Report t...
Definition rtpdec.c:313
void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx, const RTPDynamicProtocolHandler *handler)
Definition rtpdec.c:580
static int has_next_packet(RTPDemuxContext *s)
Definition rtpdec.c:804
static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
Definition rtpdec.c:777
void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
Definition rtpdec.c:764
int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd, AVIOContext *avio)
Definition rtpdec.c:469
const RTPDynamicProtocolHandler ff_rdt_live_video_handler
static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
Definition rtpdec.c:235
const RTPDynamicProtocolHandler ff_rdt_video_handler
int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt, uint8_t **bufptr, int len)
Parse an RTP or RTCP packet directly sent as a buffer.
Definition rtpdec.c:928
static const RTPDynamicProtocolHandler t140_dynamic_handler
Definition rtpdec.c:64
int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
Definition rtpdec.c:809
static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
This was the second switch in rtp_parse packet.
Definition rtpdec.c:633
static const RTPDynamicProtocolHandler speex_dynamic_handler
Definition rtpdec.c:58
static int rtp_add_sr_sidedata(RTPDemuxContext *s, AVPacket *pkt)
Definition rtpdec.c:617
static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
Definition rtpdec.c:224
static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
Definition rtpdec.c:814
static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
Definition rtpdec.c:249
const RTPDynamicProtocolHandler * ff_rtp_handler_find_by_name(const char *name, enum AVMediaType codec_type)
Find a registered rtp dynamic protocol handler with the specified name.
Definition rtpdec.c:154
static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt, const uint8_t *buf, int len)
Definition rtpdec.c:681
int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
Close the dynamic buffer and make a packet from it.
Definition rtpdec.c:986
#define MIN_FEEDBACK_INTERVAL
Definition rtpdec.c:38
int ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite, const char *params)
Definition rtpdec.c:587
#define RTP_SEQ_MOD
Definition rtpdec.c:222
static const RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler
Definition rtpdec.c:52
int ff_rtsp_next_attr_and_value(const char **p, char *attr, int attr_size, char *value, int value_size)
#define RTP_NOTS_VALUE
Definition rtpdec.h:41
#define RTP_MIN_PACKET_LENGTH
Definition rtpdec.h:36
#define RTP_FLAG_MARKER
RTP marker bit was set for this packet.
Definition rtpdec.h:94
const RTPDynamicProtocolHandler ff_ac3_dynamic_handler
Definition rtpdec_ac3.c:125
const RTPDynamicProtocolHandler ff_amr_wb_dynamic_handler
Definition rtpdec_amr.c:195
const RTPDynamicProtocolHandler ff_amr_nb_dynamic_handler
Definition rtpdec_amr.c:185
const RTPDynamicProtocolHandler ff_av1_dynamic_handler
Definition rtpdec_av1.c:446
const RTPDynamicProtocolHandler ff_dv_dynamic_handler
Definition rtpdec_dv.c:132
const RTPDynamicProtocolHandler ff_g726_40_dynamic_handler
const RTPDynamicProtocolHandler ff_hevc_dynamic_handler
const RTPDynamicProtocolHandler ff_mpeg_video_dynamic_handler
const RTPDynamicProtocolHandler ff_qdm2_dynamic_handler
const RTPDynamicProtocolHandler ff_g726le_16_dynamic_handler
const RTPDynamicProtocolHandler ff_g726le_32_dynamic_handler
const RTPDynamicProtocolHandler ff_vc2hq_dynamic_handler
const RTPDynamicProtocolHandler ff_theora_dynamic_handler
const RTPDynamicProtocolHandler ff_mpegts_dynamic_handler
const RTPDynamicProtocolHandler ff_ms_rtp_asf_pfv_handler
const RTPDynamicProtocolHandler ff_qt_rtp_aud_handler
const RTPDynamicProtocolHandler ff_h263_1998_dynamic_handler
Definition rtpdec_h263.c:92
const RTPDynamicProtocolHandler ff_g726_16_dynamic_handler
const RTPDynamicProtocolHandler ff_ilbc_dynamic_handler
Definition rtpdec_ilbc.c:69
const RTPDynamicProtocolHandler ff_vorbis_dynamic_handler
const RTPDynamicProtocolHandler ff_quicktime_rtp_vid_handler
const RTPDynamicProtocolHandler ff_h263_2000_dynamic_handler
const RTPDynamicProtocolHandler ff_qcelp_dynamic_handler
const RTPDynamicProtocolHandler ff_opus_dynamic_handler
const RTPDynamicProtocolHandler ff_g726le_24_dynamic_handler
const RTPDynamicProtocolHandler ff_ms_rtp_asf_pfa_handler
const RTPDynamicProtocolHandler ff_rfc4175_rtp_handler
const RTPDynamicProtocolHandler ff_g726_24_dynamic_handler
const RTPDynamicProtocolHandler ff_h264_dynamic_handler
const RTPDynamicProtocolHandler ff_h261_dynamic_handler
const RTPDynamicProtocolHandler ff_svq3_dynamic_handler
const RTPDynamicProtocolHandler ff_mpeg4_generic_dynamic_handler
const RTPDynamicProtocolHandler ff_qt_rtp_vid_handler
const RTPDynamicProtocolHandler ff_quicktime_rtp_aud_handler
const RTPDynamicProtocolHandler ff_vp8_dynamic_handler
Definition rtpdec_vp8.c:279
const RTPDynamicProtocolHandler ff_mpeg_audio_robust_dynamic_handler
const RTPDynamicProtocolHandler ff_h263_rfc2190_dynamic_handler
const RTPDynamicProtocolHandler ff_mpeg_audio_dynamic_handler
const RTPDynamicProtocolHandler ff_mp4a_latm_dynamic_handler
const RTPDynamicProtocolHandler ff_vp9_dynamic_handler
Definition rtpdec_vp9.c:333
const RTPDynamicProtocolHandler ff_mp4v_es_dynamic_handler
const RTPDynamicProtocolHandler ff_g726_32_dynamic_handler
const RTPDynamicProtocolHandler ff_g726le_40_dynamic_handler
const RTPDynamicProtocolHandler ff_jpeg_dynamic_handler
static int parse_fmtp(AVFormatContext *s, AVStream *stream, PayloadContext *data, const char *attr, const char *value)
int ff_srtp_set_crypto(struct SRTPContext *s, const char *suite, const char *params)
Definition srtp.c:66
int ff_srtp_decrypt(struct SRTPContext *s, uint8_t *buf, int *lenptr)
Definition srtp.c:127
void ff_srtp_free(struct SRTPContext *s)
Definition srtp.c:32
int nb_channels
Number of channels in this layout.
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
int bits_per_coded_sample
The number of bits per sample in the codedwords.
Definition codec_par.h:113
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
int block_align
The number of bytes per coded audio frame, required by some formats.
Definition codec_par.h:221
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
Format I/O context.
Definition avformat.h:1335
Bytestream IO Context.
Definition avio.h:160
This structure stores compressed data.
Definition packet.h:580
This structure supplies correlation between a packet timestamp and a wall clock production time.
Definition defs.h:340
int64_t wallclock
A UTC timestamp, in microseconds, since Unix epoch (e.g, av_gettime()).
Definition defs.h:344
RTCP SR (Sender Report) information.
Definition defs.h:354
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
int index
stream index in AVFormatContext
Definition avformat.h:774
RTP/AV1 specific private data.
Definition rdt.c:85
struct RTPPacket * next
Definition rtpdec.h:145
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
unbuffered private I/O API
static int ffurl_write(URLContext *h, const uint8_t *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition url.h:205
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
int len