3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/mathematics.h"
23 #include "libavutil/avstring.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/time.h"
27 #include "libavcodec/bytestream.h"
34 #include "rtpdec_formats.h"
37 #define MIN_FEEDBACK_INTERVAL 200000 /* 200 ms in us */
39 static RTPDynamicProtocolHandler l24_dynamic_handler = {
41 .codec_type = AVMEDIA_TYPE_AUDIO,
42 .codec_id = AV_CODEC_ID_PCM_S24BE,
45 static RTPDynamicProtocolHandler gsm_dynamic_handler = {
47 .codec_type = AVMEDIA_TYPE_AUDIO,
48 .codec_id = AV_CODEC_ID_GSM,
51 static RTPDynamicProtocolHandler realmedia_mp3_dynamic_handler = {
52 .enc_name = "X-MP3-draft-00",
53 .codec_type = AVMEDIA_TYPE_AUDIO,
54 .codec_id = AV_CODEC_ID_MP3ADU,
57 static RTPDynamicProtocolHandler speex_dynamic_handler = {
59 .codec_type = AVMEDIA_TYPE_AUDIO,
60 .codec_id = AV_CODEC_ID_SPEEX,
63 static RTPDynamicProtocolHandler opus_dynamic_handler = {
65 .codec_type = AVMEDIA_TYPE_AUDIO,
66 .codec_id = AV_CODEC_ID_OPUS,
69 static RTPDynamicProtocolHandler t140_dynamic_handler = { /* RFC 4103 */
71 .codec_type = AVMEDIA_TYPE_SUBTITLE,
72 .codec_id = AV_CODEC_ID_TEXT,
75 extern RTPDynamicProtocolHandler ff_rdt_video_handler;
76 extern RTPDynamicProtocolHandler ff_rdt_audio_handler;
77 extern RTPDynamicProtocolHandler ff_rdt_live_video_handler;
78 extern RTPDynamicProtocolHandler ff_rdt_live_audio_handler;
80 static const RTPDynamicProtocolHandler *rtp_dynamic_protocol_handler_list[] = {
82 &ff_ac3_dynamic_handler,
83 &ff_amr_nb_dynamic_handler,
84 &ff_amr_wb_dynamic_handler,
85 &ff_dv_dynamic_handler,
86 &ff_g726_16_dynamic_handler,
87 &ff_g726_24_dynamic_handler,
88 &ff_g726_32_dynamic_handler,
89 &ff_g726_40_dynamic_handler,
90 &ff_g726le_16_dynamic_handler,
91 &ff_g726le_24_dynamic_handler,
92 &ff_g726le_32_dynamic_handler,
93 &ff_g726le_40_dynamic_handler,
94 &ff_h261_dynamic_handler,
95 &ff_h263_1998_dynamic_handler,
96 &ff_h263_2000_dynamic_handler,
97 &ff_h263_rfc2190_dynamic_handler,
98 &ff_h264_dynamic_handler,
99 &ff_hevc_dynamic_handler,
100 &ff_ilbc_dynamic_handler,
101 &ff_jpeg_dynamic_handler,
102 &ff_mp4a_latm_dynamic_handler,
103 &ff_mp4v_es_dynamic_handler,
104 &ff_mpeg_audio_dynamic_handler,
105 &ff_mpeg_audio_robust_dynamic_handler,
106 &ff_mpeg_video_dynamic_handler,
107 &ff_mpeg4_generic_dynamic_handler,
108 &ff_mpegts_dynamic_handler,
109 &ff_ms_rtp_asf_pfa_handler,
110 &ff_ms_rtp_asf_pfv_handler,
111 &ff_qcelp_dynamic_handler,
112 &ff_qdm2_dynamic_handler,
113 &ff_qt_rtp_aud_handler,
114 &ff_qt_rtp_vid_handler,
115 &ff_quicktime_rtp_aud_handler,
116 &ff_quicktime_rtp_vid_handler,
117 &ff_rfc4175_rtp_handler,
118 &ff_svq3_dynamic_handler,
119 &ff_theora_dynamic_handler,
120 &ff_vc2hq_dynamic_handler,
121 &ff_vorbis_dynamic_handler,
122 &ff_vp8_dynamic_handler,
123 &ff_vp9_dynamic_handler,
124 &gsm_dynamic_handler,
125 &l24_dynamic_handler,
126 &opus_dynamic_handler,
127 &realmedia_mp3_dynamic_handler,
128 &speex_dynamic_handler,
129 &t140_dynamic_handler,
131 &ff_rdt_video_handler,
132 &ff_rdt_audio_handler,
133 &ff_rdt_live_video_handler,
134 &ff_rdt_live_audio_handler,
138 const RTPDynamicProtocolHandler *ff_rtp_handler_iterate(void **opaque)
140 uintptr_t i = (uintptr_t)*opaque;
141 const RTPDynamicProtocolHandler *r = rtp_dynamic_protocol_handler_list[i];
144 *opaque = (void*)(i + 1);
149 const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_name(const char *name,
150 enum AVMediaType codec_type)
153 const RTPDynamicProtocolHandler *handler;
154 while (handler = ff_rtp_handler_iterate(&i)) {
155 if (handler->enc_name &&
156 !av_strcasecmp(name, handler->enc_name) &&
157 codec_type == handler->codec_type)
163 const RTPDynamicProtocolHandler *ff_rtp_handler_find_by_id(int id,
164 enum AVMediaType codec_type)
167 const RTPDynamicProtocolHandler *handler;
168 while (handler = ff_rtp_handler_iterate(&i)) {
169 if (handler->static_payload_id && handler->static_payload_id == id &&
170 codec_type == handler->codec_type)
176 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,
181 payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);
185 if (payload_len < 20) {
186 av_log(s->ic, AV_LOG_ERROR, "Invalid RTCP SR packet length\n");
187 return AVERROR_INVALIDDATA;
190 s->last_rtcp_reception_time = av_gettime_relative();
191 s->last_rtcp_ntp_time = AV_RB64(buf + 8);
192 s->last_rtcp_timestamp = AV_RB32(buf + 16);
193 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {
194 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
195 if (!s->base_timestamp)
196 s->base_timestamp = s->last_rtcp_timestamp;
197 s->rtcp_ts_offset = (int32_t)(s->last_rtcp_timestamp - s->base_timestamp);
211 #define RTP_SEQ_MOD (1 << 16)
213 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence)
215 memset(s, 0, sizeof(RTPStatistics));
216 s->max_seq = base_sequence;
221 * Called whenever there is a large jump in sequence numbers,
222 * or when they get out of probation...
224 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
228 s->base_seq = seq - 1;
229 s->bad_seq = RTP_SEQ_MOD + 1;
231 s->expected_prior = 0;
232 s->received_prior = 0;
237 /* Returns 1 if we should handle this packet. */
238 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
240 uint16_t udelta = seq - s->max_seq;
241 const int MAX_DROPOUT = 3000;
242 const int MAX_MISORDER = 100;
243 const int MIN_SEQUENTIAL = 2;
245 /* source not valid until MIN_SEQUENTIAL packets with sequence
246 * seq. numbers have been received */
248 if (seq == s->max_seq + 1) {
251 if (s->probation == 0) {
252 rtp_init_sequence(s, seq);
257 s->probation = MIN_SEQUENTIAL - 1;
260 } else if (udelta < MAX_DROPOUT) {
261 // in order, with permissible gap
262 if (seq < s->max_seq) {
263 // sequence number wrapped; count another 64k cycles
264 s->cycles += RTP_SEQ_MOD;
267 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
268 // sequence made a large jump...
269 if (seq == s->bad_seq) {
270 /* two sequential packets -- assume that the other side
271 * restarted without telling us; just resync. */
272 rtp_init_sequence(s, seq);
274 s->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
278 // duplicate or reordered packet...
284 static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp,
285 uint32_t arrival_timestamp)
287 // Most of this is pretty straight from RFC 3550 appendix A.8
288 uint32_t transit = arrival_timestamp - sent_timestamp;
289 uint32_t prev_transit = s->transit;
290 int32_t d = transit - prev_transit;
291 // Doing the FFABS() call directly on the "transit - prev_transit"
292 // expression doesn't work, since it's an unsigned expression. Doing the
293 // transit calculation in unsigned is desired though, since it most
294 // probably will need to wrap around.
296 s->transit = transit;
299 s->jitter += d - (int32_t) ((s->jitter + 8) >> 4);
302 int ff_rtp_check_and_send_back_rr(RTPDemuxContext *s, URLContext *fd,
303 AVIOContext *avio, int count)
309 RTPStatistics *stats = &s->statistics;
311 uint32_t extended_max;
312 uint32_t expected_interval;
313 uint32_t received_interval;
314 int32_t lost_interval;
318 if ((!fd && !avio) || (count < 1))
321 /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
322 /* XXX: MPEG pts hardcoded. RTCP send every 0.5 seconds */
323 s->octet_count += count;
324 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
326 rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
329 s->last_octet_count = s->octet_count;
333 else if (avio_open_dyn_buf(&pb) < 0)
337 avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
338 avio_w8(pb, RTCP_RR);
339 avio_wb16(pb, 7); /* length in words - 1 */
340 // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
341 avio_wb32(pb, s->ssrc + 1);
342 avio_wb32(pb, s->ssrc); // server SSRC
343 // some placeholders we should really fill...
345 extended_max = stats->cycles + stats->max_seq;
346 expected = extended_max - stats->base_seq;
347 lost = expected - stats->received;
348 lost = FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
349 expected_interval = expected - stats->expected_prior;
350 stats->expected_prior = expected;
351 received_interval = stats->received - stats->received_prior;
352 stats->received_prior = stats->received;
353 lost_interval = expected_interval - received_interval;
354 if (expected_interval == 0 || lost_interval <= 0)
357 fraction = (lost_interval << 8) / expected_interval;
359 fraction = (fraction << 24) | lost;
361 avio_wb32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
362 avio_wb32(pb, extended_max); /* max sequence received */
363 avio_wb32(pb, stats->jitter >> 4); /* jitter */
365 if (s->last_rtcp_ntp_time == AV_NOPTS_VALUE) {
366 avio_wb32(pb, 0); /* last SR timestamp */
367 avio_wb32(pb, 0); /* delay since last SR */
369 uint32_t middle_32_bits = s->last_rtcp_ntp_time >> 16; // this is valid, right? do we need to handle 64 bit values special?
370 uint32_t delay_since_last = av_rescale(av_gettime_relative() - s->last_rtcp_reception_time,
371 65536, AV_TIME_BASE);
373 avio_wb32(pb, middle_32_bits); /* last SR timestamp */
374 avio_wb32(pb, delay_since_last); /* delay since last SR */
378 avio_w8(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
379 avio_w8(pb, RTCP_SDES);
380 len = strlen(s->hostname);
381 avio_wb16(pb, (7 + len + 3) / 4); /* length in words - 1 */
382 avio_wb32(pb, s->ssrc + 1);
385 avio_write(pb, s->hostname, len);
386 avio_w8(pb, 0); /* END */
388 for (len = (7 + len) % 4; len % 4; len++)
394 len = avio_close_dyn_buf(pb, &buf);
395 if ((len > 0) && buf) {
396 int av_unused result;
397 av_log(s->ic, AV_LOG_TRACE, "sending %d bytes of RR\n", len);
398 result = ffurl_write(fd, buf, len);
399 av_log(s->ic, AV_LOG_TRACE, "result from ffurl_write: %d\n", result);
405 void ff_rtp_send_punch_packets(URLContext *rtp_handle)
411 /* Send a small RTP packet */
412 if (avio_open_dyn_buf(&pb) < 0)
415 avio_w8(pb, (RTP_VERSION << 6));
416 avio_w8(pb, 0); /* Payload type */
417 avio_wb16(pb, 0); /* Seq */
418 avio_wb32(pb, 0); /* Timestamp */
419 avio_wb32(pb, 0); /* SSRC */
421 len = avio_close_dyn_buf(pb, &buf);
422 if ((len > 0) && buf)
423 ffurl_write(rtp_handle, buf, len);
426 /* Send a minimal RTCP RR */
427 if (avio_open_dyn_buf(&pb) < 0)
430 avio_w8(pb, (RTP_VERSION << 6));
431 avio_w8(pb, RTCP_RR); /* receiver report */
432 avio_wb16(pb, 1); /* length in words - 1 */
433 avio_wb32(pb, 0); /* our own SSRC */
435 len = avio_close_dyn_buf(pb, &buf);
436 if ((len > 0) && buf)
437 ffurl_write(rtp_handle, buf, len);
441 static int find_missing_packets(RTPDemuxContext *s, uint16_t *first_missing,
442 uint16_t *missing_mask)
445 uint16_t next_seq = s->seq + 1;
446 RTPPacket *pkt = s->queue;
448 if (!pkt || pkt->seq == next_seq)
452 for (i = 1; i <= 16; i++) {
453 uint16_t missing_seq = next_seq + i;
455 int16_t diff = pkt->seq - missing_seq;
462 if (pkt->seq == missing_seq)
464 *missing_mask |= 1 << (i - 1);
467 *first_missing = next_seq;
471 int ff_rtp_send_rtcp_feedback(RTPDemuxContext *s, URLContext *fd,
474 int len, need_keyframe, missing_packets;
478 uint16_t first_missing = 0, missing_mask = 0;
483 need_keyframe = s->handler && s->handler->need_keyframe &&
484 s->handler->need_keyframe(s->dynamic_protocol_context);
485 missing_packets = find_missing_packets(s, &first_missing, &missing_mask);
487 if (!need_keyframe && !missing_packets)
490 /* Send new feedback if enough time has elapsed since the last
491 * feedback packet. */
493 now = av_gettime_relative();
494 if (s->last_feedback_time &&
495 (now - s->last_feedback_time) < MIN_FEEDBACK_INTERVAL)
497 s->last_feedback_time = now;
501 else if (avio_open_dyn_buf(&pb) < 0)
505 avio_w8(pb, (RTP_VERSION << 6) | 1); /* PLI */
506 avio_w8(pb, RTCP_PSFB);
507 avio_wb16(pb, 2); /* length in words - 1 */
508 // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
509 avio_wb32(pb, s->ssrc + 1);
510 avio_wb32(pb, s->ssrc); // server SSRC
513 if (missing_packets) {
514 avio_w8(pb, (RTP_VERSION << 6) | 1); /* NACK */
515 avio_w8(pb, RTCP_RTPFB);
516 avio_wb16(pb, 3); /* length in words - 1 */
517 avio_wb32(pb, s->ssrc + 1);
518 avio_wb32(pb, s->ssrc); // server SSRC
520 avio_wb16(pb, first_missing);
521 avio_wb16(pb, missing_mask);
527 len = avio_close_dyn_buf(pb, &buf);
528 if (len > 0 && buf) {
529 ffurl_write(fd, buf, len);
535 static int opus_write_extradata(AVCodecParameters *codecpar)
540 /* This function writes an extradata with a channel mapping family of 0.
541 * This mapping family only supports mono and stereo layouts. And RFC7587
542 * specifies that the number of channels in the SDP must be 2.
544 if (codecpar->channels > 2) {
545 return AVERROR_INVALIDDATA;
548 ret = ff_alloc_extradata(codecpar, 19);
552 bs = (uint8_t *)codecpar->extradata;
555 bytestream_put_buffer(&bs, "OpusHead", 8);
557 bytestream_put_byte (&bs, 0x1);
559 bytestream_put_byte (&bs, codecpar->channels);
561 bytestream_put_le16 (&bs, 0);
562 /* Input sample rate */
563 bytestream_put_le32 (&bs, 48000);
565 bytestream_put_le16 (&bs, 0x0);
567 bytestream_put_byte (&bs, 0x0);
573 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
576 RTPDemuxContext *ff_rtp_parse_open(AVFormatContext *s1, AVStream *st,
577 int payload_type, int queue_size)
582 s = av_mallocz(sizeof(RTPDemuxContext));
585 s->payload_type = payload_type;
586 s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
587 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
590 s->queue_size = queue_size;
592 av_log(s->ic, AV_LOG_VERBOSE, "setting jitter buffer size to %d\n",
595 rtp_init_statistics(&s->statistics, 0);
597 switch (st->codecpar->codec_id) {
598 case AV_CODEC_ID_ADPCM_G722:
599 /* According to RFC 3551, the stream clock rate is 8000
600 * even if the sample rate is 16000. */
601 if (st->codecpar->sample_rate == 8000)
602 st->codecpar->sample_rate = 16000;
604 case AV_CODEC_ID_OPUS:
605 ret = opus_write_extradata(st->codecpar);
607 av_log(s1, AV_LOG_ERROR,
608 "Error creating opus extradata: %s\n",
618 // needed to send back RTCP RR in RTSP sessions
619 gethostname(s->hostname, sizeof(s->hostname));
623 void ff_rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
624 const RTPDynamicProtocolHandler *handler)
626 s->dynamic_protocol_context = ctx;
627 s->handler = handler;
630 void ff_rtp_parse_set_crypto(RTPDemuxContext *s, const char *suite,
633 if (!ff_srtp_set_crypto(&s->srtp, suite, params))
638 * This was the second switch in rtp_parse packet.
639 * Normalizes time, if required, sets stream_index, etc.
641 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
643 if (pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE)
644 return; /* Timestamp already set by depacketizer */
645 if (timestamp == RTP_NOTS_VALUE)
648 if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && s->ic->nb_streams > 1) {
652 /* compute pts from timestamp with received ntp_time */
653 delta_timestamp = timestamp - s->last_rtcp_timestamp;
654 /* convert to the PTS timebase */
655 addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time,
656 s->st->time_base.den,
657 (uint64_t) s->st->time_base.num << 32);
658 pkt->pts = s->range_start_offset + s->rtcp_ts_offset + addend +
663 if (!s->base_timestamp)
664 s->base_timestamp = timestamp;
665 /* assume that the difference is INT32_MIN < x < INT32_MAX,
666 * but allow the first timestamp to exceed INT32_MAX */
668 s->unwrapped_timestamp += timestamp;
670 s->unwrapped_timestamp += (int32_t)(timestamp - s->timestamp);
671 s->timestamp = timestamp;
672 pkt->pts = s->unwrapped_timestamp + s->range_start_offset -
676 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
677 const uint8_t *buf, int len)
680 int payload_type, seq, flags = 0;
686 csrc = buf[0] & 0x0f;
688 payload_type = buf[1] & 0x7f;
690 flags |= RTP_FLAG_MARKER;
691 seq = AV_RB16(buf + 2);
692 timestamp = AV_RB32(buf + 4);
693 ssrc = AV_RB32(buf + 8);
694 /* store the ssrc in the RTPDemuxContext */
697 /* NOTE: we can handle only one payload type */
698 if (s->payload_type != payload_type)
702 // only do something with this if all the rtp checks pass...
703 if (!rtp_valid_packet_in_sequence(&s->statistics, seq)) {
704 av_log(s->ic, AV_LOG_ERROR,
705 "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
706 payload_type, seq, ((s->seq + 1) & 0xffff));
711 int padding = buf[len - 1];
712 if (len >= 12 + padding)
723 return AVERROR_INVALIDDATA;
725 /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
729 /* calculate the header extension length (stored as number
730 * of 32-bit words) */
731 ext = (AV_RB16(buf + 2) + 1) << 2;
735 // skip past RTP header extension
740 if (s->handler && s->handler->parse_packet) {
741 rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
742 s->st, pkt, ×tamp, buf, len, seq,
745 if ((rv = av_new_packet(pkt, len)) < 0)
747 memcpy(pkt->data, buf, len);
748 pkt->stream_index = st->index;
750 return AVERROR(EINVAL);
753 // now perform timestamp things....
754 finalize_packet(s, pkt, timestamp);
759 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
762 RTPPacket *next = s->queue->next;
763 av_freep(&s->queue->buf);
772 static int enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
774 uint16_t seq = AV_RB16(buf + 2);
775 RTPPacket **cur = &s->queue, *packet;
777 /* Find the correct place in the queue to insert the packet */
779 int16_t diff = seq - (*cur)->seq;
785 packet = av_mallocz(sizeof(*packet));
787 return AVERROR(ENOMEM);
788 packet->recvtime = av_gettime_relative();
799 static int has_next_packet(RTPDemuxContext *s)
801 return s->queue && s->queue->seq == (uint16_t) (s->seq + 1);
804 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
806 return s->queue ? s->queue->recvtime : 0;
809 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
814 if (s->queue_len <= 0)
817 if (!has_next_packet(s))
818 av_log(s->ic, AV_LOG_WARNING,
819 "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
821 /* Parse the first packet in the queue, and dequeue it */
822 rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
823 next = s->queue->next;
824 av_freep(&s->queue->buf);
831 static int rtp_parse_one_packet(RTPDemuxContext *s, AVPacket *pkt,
832 uint8_t **bufptr, int len)
834 uint8_t *buf = bufptr ? *bufptr : NULL;
840 /* If parsing of the previous packet actually returned 0 or an error,
841 * there's nothing more to be parsed from that packet, but we may have
842 * indicated that we can return the next enqueued packet. */
843 if (s->prev_ret <= 0)
844 return rtp_parse_queued_packet(s, pkt);
845 /* return the next packets, if any */
846 if (s->handler && s->handler->parse_packet) {
847 /* timestamp should be overwritten by parse_packet, if not,
848 * the packet is left with pts == AV_NOPTS_VALUE */
849 timestamp = RTP_NOTS_VALUE;
850 rv = s->handler->parse_packet(s->ic, s->dynamic_protocol_context,
851 s->st, pkt, ×tamp, NULL, 0, 0,
853 finalize_packet(s, pkt, timestamp);
861 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
863 if (RTP_PT_IS_RTCP(buf[1])) {
864 return rtcp_parse_packet(s, buf, len);
868 int64_t received = av_gettime_relative();
869 uint32_t arrival_ts = av_rescale_q(received, AV_TIME_BASE_Q,
871 timestamp = AV_RB32(buf + 4);
872 // Calculate the jitter immediately, before queueing the packet
873 // into the reordering queue.
874 rtcp_update_jitter(&s->statistics, timestamp, arrival_ts);
877 if ((s->seq == 0 && !s->queue) || s->queue_size <= 1) {
878 /* First packet, or no reordering */
879 return rtp_parse_packet_internal(s, pkt, buf, len);
881 uint16_t seq = AV_RB16(buf + 2);
882 int16_t diff = seq - s->seq;
884 /* Packet older than the previously emitted one, drop */
885 av_log(s->ic, AV_LOG_WARNING,
886 "RTP: dropping old packet received too late\n");
888 } else if (diff <= 1) {
890 rv = rtp_parse_packet_internal(s, pkt, buf, len);
893 /* Still missing some packet, enqueue this one. */
894 rv = enqueue_packet(s, buf, len);
898 /* Return the first enqueued packet if the queue is full,
899 * even if we're missing something */
900 if (s->queue_len >= s->queue_size) {
901 av_log(s->ic, AV_LOG_WARNING, "jitter buffer full\n");
902 return rtp_parse_queued_packet(s, pkt);
910 * Parse an RTP or RTCP packet directly sent as a buffer.
911 * @param s RTP parse context.
912 * @param pkt returned packet
913 * @param bufptr pointer to the input buffer or NULL to read the next packets
914 * @param len buffer len
915 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
916 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
918 int ff_rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
919 uint8_t **bufptr, int len)
922 if (s->srtp_enabled && bufptr && ff_srtp_decrypt(&s->srtp, *bufptr, &len) < 0)
924 rv = rtp_parse_one_packet(s, pkt, bufptr, len);
926 while (rv < 0 && has_next_packet(s))
927 rv = rtp_parse_queued_packet(s, pkt);
928 return rv ? rv : has_next_packet(s);
931 void ff_rtp_parse_close(RTPDemuxContext *s)
933 ff_rtp_reset_packet_queue(s);
934 ff_srtp_free(&s->srtp);
938 int ff_parse_fmtp(AVFormatContext *s,
939 AVStream *stream, PayloadContext *data, const char *p,
940 int (*parse_fmtp)(AVFormatContext *s,
942 PayloadContext *data,
943 const char *attr, const char *value))
948 int value_size = strlen(p) + 1;
950 if (!(value = av_malloc(value_size))) {
951 av_log(s, AV_LOG_ERROR, "Failed to allocate data for FMTP.\n");
952 return AVERROR(ENOMEM);
955 // remove protocol identifier
956 while (*p && *p == ' ')
958 while (*p && *p != ' ')
959 p++; // eat protocol identifier
960 while (*p && *p == ' ')
961 p++; // strip trailing spaces
963 while (ff_rtsp_next_attr_and_value(&p,
965 value, value_size)) {
966 res = parse_fmtp(s, stream, data, attr, value);
967 if (res < 0 && res != AVERROR_PATCHWELCOME) {
976 int ff_rtp_finalize_packet(AVPacket *pkt, AVIOContext **dyn_buf, int stream_idx)
981 pkt->size = avio_close_dyn_buf(*dyn_buf, &pkt->data);
982 pkt->stream_index = stream_idx;
984 if ((ret = av_packet_from_data(pkt, pkt->data, pkt->size)) < 0) {
985 av_freep(&pkt->data);