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 /* needed for gethostname() */
23 #define _XOPEN_SOURCE 600
25 #include "libavcodec/get_bits.h"
33 #include "rtpdec_formats.h"
37 /* TODO: - add RTCP statistics reporting (should be optional).
39 - add support for h263/mpeg4 packetized output : IDEA: send a
40 buffer to 'rtp_write_packet' contains all the packets for ONE
41 frame. Each packet should have a four byte header containing
42 the length in big endian format (same trick as
43 'url_open_dyn_packet_buf')
46 /* statistics functions */
47 RTPDynamicProtocolHandler *RTPFirstDynamicPayloadHandler= NULL;
49 void ff_register_dynamic_payload_handler(RTPDynamicProtocolHandler *handler)
51 handler->next= RTPFirstDynamicPayloadHandler;
52 RTPFirstDynamicPayloadHandler= handler;
55 void av_register_rtp_dynamic_payload_handlers(void)
57 ff_register_dynamic_payload_handler(&ff_mp4v_es_dynamic_handler);
58 ff_register_dynamic_payload_handler(&ff_mpeg4_generic_dynamic_handler);
59 ff_register_dynamic_payload_handler(&ff_amr_nb_dynamic_handler);
60 ff_register_dynamic_payload_handler(&ff_amr_wb_dynamic_handler);
61 ff_register_dynamic_payload_handler(&ff_h263_1998_dynamic_handler);
62 ff_register_dynamic_payload_handler(&ff_h263_2000_dynamic_handler);
63 ff_register_dynamic_payload_handler(&ff_h264_dynamic_handler);
64 ff_register_dynamic_payload_handler(&ff_vorbis_dynamic_handler);
65 ff_register_dynamic_payload_handler(&ff_theora_dynamic_handler);
66 ff_register_dynamic_payload_handler(&ff_qdm2_dynamic_handler);
67 ff_register_dynamic_payload_handler(&ff_svq3_dynamic_handler);
68 ff_register_dynamic_payload_handler(&ff_mp4a_latm_dynamic_handler);
69 ff_register_dynamic_payload_handler(&ff_vp8_dynamic_handler);
71 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfv_handler);
72 ff_register_dynamic_payload_handler(&ff_ms_rtp_asf_pfa_handler);
74 ff_register_dynamic_payload_handler(&ff_qt_rtp_aud_handler);
75 ff_register_dynamic_payload_handler(&ff_qt_rtp_vid_handler);
76 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_aud_handler);
77 ff_register_dynamic_payload_handler(&ff_quicktime_rtp_vid_handler);
80 static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf, int len)
87 av_log(NULL, AV_LOG_ERROR, "Invalid length for RTCP SR packet\n");
88 return AVERROR_INVALIDDATA;
90 payload_len = (AV_RB16(buf + 2) + 1) * 4;
92 s->last_rtcp_ntp_time = AV_RB64(buf + 8);
93 if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE)
94 s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;
95 s->last_rtcp_timestamp = AV_RB32(buf + 16);
109 #define RTP_SEQ_MOD (1<<16)
112 * called on parse open packet
114 static void rtp_init_statistics(RTPStatistics *s, uint16_t base_sequence) // called on parse open packet.
116 memset(s, 0, sizeof(RTPStatistics));
117 s->max_seq= base_sequence;
122 * called whenever there is a large jump in sequence numbers, or when they get out of probation...
124 static void rtp_init_sequence(RTPStatistics *s, uint16_t seq)
129 s->bad_seq= RTP_SEQ_MOD + 1;
131 s->expected_prior= 0;
132 s->received_prior= 0;
138 * returns 1 if we should handle this packet.
140 static int rtp_valid_packet_in_sequence(RTPStatistics *s, uint16_t seq)
142 uint16_t udelta= seq - s->max_seq;
143 const int MAX_DROPOUT= 3000;
144 const int MAX_MISORDER = 100;
145 const int MIN_SEQUENTIAL = 2;
147 /* source not valid until MIN_SEQUENTIAL packets with sequence seq. numbers have been received */
150 if(seq==s->max_seq + 1) {
153 if(s->probation==0) {
154 rtp_init_sequence(s, seq);
159 s->probation= MIN_SEQUENTIAL - 1;
162 } else if (udelta < MAX_DROPOUT) {
163 // in order, with permissible gap
164 if(seq < s->max_seq) {
165 //sequence number wrapped; count antother 64k cycles
166 s->cycles += RTP_SEQ_MOD;
169 } else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER) {
170 // sequence made a large jump...
171 if(seq==s->bad_seq) {
172 // two sequential packets-- assume that the other side restarted without telling us; just resync.
173 rtp_init_sequence(s, seq);
175 s->bad_seq= (seq + 1) & (RTP_SEQ_MOD-1);
179 // duplicate or reordered packet...
187 * This function is currently unused; without a valid local ntp time, I don't see how we could calculate the
188 * difference between the arrival and sent timestamp. As a result, the jitter and transit statistics values
189 * never change. I left this in in case someone else can see a way. (rdm)
191 static void rtcp_update_jitter(RTPStatistics *s, uint32_t sent_timestamp, uint32_t arrival_timestamp)
193 uint32_t transit= arrival_timestamp - sent_timestamp;
196 d= FFABS(transit - s->transit);
197 s->jitter += d - ((s->jitter + 8)>>4);
201 int rtp_check_and_send_back_rr(RTPDemuxContext *s, int count)
207 RTPStatistics *stats= &s->statistics;
209 uint32_t extended_max;
210 uint32_t expected_interval;
211 uint32_t received_interval;
212 uint32_t lost_interval;
215 uint64_t ntp_time= s->last_rtcp_ntp_time; // TODO: Get local ntp time?
217 if (!s->rtp_ctx || (count < 1))
220 /* TODO: I think this is way too often; RFC 1889 has algorithm for this */
221 /* XXX: mpeg pts hardcoded. RTCP send every 0.5 seconds */
222 s->octet_count += count;
223 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
225 rtcp_bytes /= 50; // mmu_man: that's enough for me... VLC sends much less btw !?
228 s->last_octet_count = s->octet_count;
230 if (url_open_dyn_buf(&pb) < 0)
234 put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
235 put_byte(pb, RTCP_RR);
236 put_be16(pb, 7); /* length in words - 1 */
237 // our own SSRC: we use the server's SSRC + 1 to avoid conflicts
238 put_be32(pb, s->ssrc + 1);
239 put_be32(pb, s->ssrc); // server SSRC
240 // some placeholders we should really fill...
242 extended_max= stats->cycles + stats->max_seq;
243 expected= extended_max - stats->base_seq + 1;
244 lost= expected - stats->received;
245 lost= FFMIN(lost, 0xffffff); // clamp it since it's only 24 bits...
246 expected_interval= expected - stats->expected_prior;
247 stats->expected_prior= expected;
248 received_interval= stats->received - stats->received_prior;
249 stats->received_prior= stats->received;
250 lost_interval= expected_interval - received_interval;
251 if (expected_interval==0 || lost_interval<=0) fraction= 0;
252 else fraction = (lost_interval<<8)/expected_interval;
254 fraction= (fraction<<24) | lost;
256 put_be32(pb, fraction); /* 8 bits of fraction, 24 bits of total packets lost */
257 put_be32(pb, extended_max); /* max sequence received */
258 put_be32(pb, stats->jitter>>4); /* jitter */
260 if(s->last_rtcp_ntp_time==AV_NOPTS_VALUE)
262 put_be32(pb, 0); /* last SR timestamp */
263 put_be32(pb, 0); /* delay since last SR */
265 uint32_t middle_32_bits= s->last_rtcp_ntp_time>>16; // this is valid, right? do we need to handle 64 bit values special?
266 uint32_t delay_since_last= ntp_time - s->last_rtcp_ntp_time;
268 put_be32(pb, middle_32_bits); /* last SR timestamp */
269 put_be32(pb, delay_since_last); /* delay since last SR */
273 put_byte(pb, (RTP_VERSION << 6) + 1); /* 1 report block */
274 put_byte(pb, RTCP_SDES);
275 len = strlen(s->hostname);
276 put_be16(pb, (6 + len + 3) / 4); /* length in words - 1 */
277 put_be32(pb, s->ssrc);
280 put_buffer(pb, s->hostname, len);
282 for (len = (6 + len) % 4; len % 4; len++) {
286 put_flush_packet(pb);
287 len = url_close_dyn_buf(pb, &buf);
288 if ((len > 0) && buf) {
290 dprintf(s->ic, "sending %d bytes of RR\n", len);
291 result= url_write(s->rtp_ctx, buf, len);
292 dprintf(s->ic, "result from url_write: %d\n", result);
298 void rtp_send_punch_packets(URLContext* rtp_handle)
304 /* Send a small RTP packet */
305 if (url_open_dyn_buf(&pb) < 0)
308 put_byte(pb, (RTP_VERSION << 6));
309 put_byte(pb, 0); /* Payload type */
310 put_be16(pb, 0); /* Seq */
311 put_be32(pb, 0); /* Timestamp */
312 put_be32(pb, 0); /* SSRC */
314 put_flush_packet(pb);
315 len = url_close_dyn_buf(pb, &buf);
316 if ((len > 0) && buf)
317 url_write(rtp_handle, buf, len);
320 /* Send a minimal RTCP RR */
321 if (url_open_dyn_buf(&pb) < 0)
324 put_byte(pb, (RTP_VERSION << 6));
325 put_byte(pb, RTCP_RR); /* receiver report */
326 put_be16(pb, 1); /* length in words - 1 */
327 put_be32(pb, 0); /* our own SSRC */
329 put_flush_packet(pb);
330 len = url_close_dyn_buf(pb, &buf);
331 if ((len > 0) && buf)
332 url_write(rtp_handle, buf, len);
338 * open a new RTP parse context for stream 'st'. 'st' can be NULL for
339 * MPEG2TS streams to indicate that they should be demuxed inside the
340 * rtp demux (otherwise CODEC_ID_MPEG2TS packets are returned)
342 RTPDemuxContext *rtp_parse_open(AVFormatContext *s1, AVStream *st, URLContext *rtpc, int payload_type, int queue_size)
346 s = av_mallocz(sizeof(RTPDemuxContext));
349 s->payload_type = payload_type;
350 s->last_rtcp_ntp_time = AV_NOPTS_VALUE;
351 s->first_rtcp_ntp_time = AV_NOPTS_VALUE;
354 s->queue_size = queue_size;
355 rtp_init_statistics(&s->statistics, 0); // do we know the initial sequence from sdp?
356 if (!strcmp(ff_rtp_enc_name(payload_type), "MP2T")) {
357 s->ts = ff_mpegts_parse_open(s->ic);
363 av_set_pts_info(st, 32, 1, 90000);
364 switch(st->codec->codec_id) {
365 case CODEC_ID_MPEG1VIDEO:
366 case CODEC_ID_MPEG2VIDEO:
372 st->need_parsing = AVSTREAM_PARSE_FULL;
374 case CODEC_ID_ADPCM_G722:
375 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
376 /* According to RFC 3551, the stream clock rate is 8000
377 * even if the sample rate is 16000. */
378 if (st->codec->sample_rate == 8000)
379 st->codec->sample_rate = 16000;
382 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
383 av_set_pts_info(st, 32, 1, st->codec->sample_rate);
388 // needed to send back RTCP RR in RTSP sessions
390 gethostname(s->hostname, sizeof(s->hostname));
395 rtp_parse_set_dynamic_protocol(RTPDemuxContext *s, PayloadContext *ctx,
396 RTPDynamicProtocolHandler *handler)
398 s->dynamic_protocol_context = ctx;
399 s->parse_packet = handler->parse_packet;
403 * This was the second switch in rtp_parse packet. Normalizes time, if required, sets stream_index, etc.
405 static void finalize_packet(RTPDemuxContext *s, AVPacket *pkt, uint32_t timestamp)
407 if (s->last_rtcp_ntp_time != AV_NOPTS_VALUE && timestamp != RTP_NOTS_VALUE) {
411 /* compute pts from timestamp with received ntp_time */
412 delta_timestamp = timestamp - s->last_rtcp_timestamp;
413 /* convert to the PTS timebase */
414 addend = av_rescale(s->last_rtcp_ntp_time - s->first_rtcp_ntp_time, s->st->time_base.den, (uint64_t)s->st->time_base.num << 32);
415 pkt->pts = s->range_start_offset + addend + delta_timestamp;
419 static int rtp_parse_packet_internal(RTPDemuxContext *s, AVPacket *pkt,
420 const uint8_t *buf, int len)
422 unsigned int ssrc, h;
423 int payload_type, seq, ret, flags = 0;
430 payload_type = buf[1] & 0x7f;
432 flags |= RTP_FLAG_MARKER;
433 seq = AV_RB16(buf + 2);
434 timestamp = AV_RB32(buf + 4);
435 ssrc = AV_RB32(buf + 8);
436 /* store the ssrc in the RTPDemuxContext */
439 /* NOTE: we can handle only one payload type */
440 if (s->payload_type != payload_type)
444 // only do something with this if all the rtp checks pass...
445 if(!rtp_valid_packet_in_sequence(&s->statistics, seq))
447 av_log(st?st->codec:NULL, AV_LOG_ERROR, "RTP: PT=%02x: bad cseq %04x expected=%04x\n",
448 payload_type, seq, ((s->seq + 1) & 0xffff));
456 /* RFC 3550 Section 5.3.1 RTP Header Extension handling */
460 /* calculate the header extension length (stored as number
461 * of 32-bit words) */
462 ext = (AV_RB16(buf + 2) + 1) << 2;
466 // skip past RTP header extension
472 /* specific MPEG2TS demux support */
473 ret = ff_mpegts_parse_packet(s->ts, pkt, buf, len);
479 s->read_buf_size = len - ret;
480 memcpy(s->buf, buf + ret, s->read_buf_size);
481 s->read_buf_index = 0;
487 } else if (s->parse_packet) {
488 rv = s->parse_packet(s->ic, s->dynamic_protocol_context,
489 s->st, pkt, ×tamp, buf, len, flags);
491 // at this point, the RTP header has been stripped; This is ASSUMING that there is only 1 CSRC, which in't wise.
492 switch(st->codec->codec_id) {
495 /* better than nothing: skip mpeg audio RTP header */
501 av_new_packet(pkt, len);
502 memcpy(pkt->data, buf, len);
504 case CODEC_ID_MPEG1VIDEO:
505 case CODEC_ID_MPEG2VIDEO:
506 /* better than nothing: skip mpeg video RTP header */
519 av_new_packet(pkt, len);
520 memcpy(pkt->data, buf, len);
523 av_new_packet(pkt, len);
524 memcpy(pkt->data, buf, len);
528 pkt->stream_index = st->index;
531 // now perform timestamp things....
532 finalize_packet(s, pkt, timestamp);
538 void ff_rtp_reset_packet_queue(RTPDemuxContext *s)
541 RTPPacket *next = s->queue->next;
542 av_free(s->queue->buf);
551 static void enqueue_packet(RTPDemuxContext *s, uint8_t *buf, int len)
553 uint16_t seq = AV_RB16(buf + 2);
554 RTPPacket *cur = s->queue, *prev = NULL, *packet;
556 /* Find the correct place in the queue to insert the packet */
558 int16_t diff = seq - cur->seq;
565 packet = av_mallocz(sizeof(*packet));
568 packet->recvtime = av_gettime();
580 static int has_next_packet(RTPDemuxContext *s)
582 return s->queue && s->queue->seq == s->seq + 1;
585 int64_t ff_rtp_queued_packet_time(RTPDemuxContext *s)
587 return s->queue ? s->queue->recvtime : 0;
590 static int rtp_parse_queued_packet(RTPDemuxContext *s, AVPacket *pkt)
595 if (s->queue_len <= 0)
598 if (!has_next_packet(s))
599 av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
600 "RTP: missed %d packets\n", s->queue->seq - s->seq - 1);
602 /* Parse the first packet in the queue, and dequeue it */
603 rv = rtp_parse_packet_internal(s, pkt, s->queue->buf, s->queue->len);
604 next = s->queue->next;
605 av_free(s->queue->buf);
609 return rv ? rv : has_next_packet(s);
613 * Parse an RTP or RTCP packet directly sent as a buffer.
614 * @param s RTP parse context.
615 * @param pkt returned packet
616 * @param bufptr pointer to the input buffer or NULL to read the next packets
617 * @param len buffer len
618 * @return 0 if a packet is returned, 1 if a packet is returned and more can follow
619 * (use buf as NULL to read the next). -1 if no packet (error or no more packet).
621 int rtp_parse_packet(RTPDemuxContext *s, AVPacket *pkt,
622 uint8_t **bufptr, int len)
624 uint8_t* buf = bufptr ? *bufptr : NULL;
630 /* If parsing of the previous packet actually returned 0, there's
631 * nothing more to be parsed from that packet, but we may have
632 * indicated that we can return the next enqueued packet. */
634 return rtp_parse_queued_packet(s, pkt);
635 /* return the next packets, if any */
636 if(s->st && s->parse_packet) {
637 /* timestamp should be overwritten by parse_packet, if not,
638 * the packet is left with pts == AV_NOPTS_VALUE */
639 timestamp = RTP_NOTS_VALUE;
640 rv= s->parse_packet(s->ic, s->dynamic_protocol_context,
641 s->st, pkt, ×tamp, NULL, 0, flags);
642 finalize_packet(s, pkt, timestamp);
644 return rv ? rv : has_next_packet(s);
646 // TODO: Move to a dynamic packet handler (like above)
647 if (s->read_buf_index >= s->read_buf_size) {
651 ret = ff_mpegts_parse_packet(s->ts, pkt, s->buf + s->read_buf_index,
652 s->read_buf_size - s->read_buf_index);
657 s->read_buf_index += ret;
658 if (s->read_buf_index < s->read_buf_size)
662 return has_next_packet(s);
670 if ((buf[0] & 0xc0) != (RTP_VERSION << 6))
672 if (buf[1] >= RTCP_SR && buf[1] <= RTCP_APP) {
673 return rtcp_parse_packet(s, buf, len);
676 if (s->seq == 0 || s->queue_size <= 1) {
677 /* First packet, or no reordering */
678 return rtp_parse_packet_internal(s, pkt, buf, len);
680 uint16_t seq = AV_RB16(buf + 2);
681 int16_t diff = seq - s->seq;
683 /* Packet older than the previously emitted one, drop */
684 av_log(s->st ? s->st->codec : NULL, AV_LOG_WARNING,
685 "RTP: dropping old packet received too late\n");
687 } else if (diff <= 1) {
689 rv = rtp_parse_packet_internal(s, pkt, buf, len);
690 return rv ? rv : has_next_packet(s);
692 /* Still missing some packet, enqueue this one. */
693 enqueue_packet(s, buf, len);
695 /* Return the first enqueued packet if the queue is full,
696 * even if we're missing something */
697 if (s->queue_len >= s->queue_size)
698 return rtp_parse_queued_packet(s, pkt);
704 void rtp_parse_close(RTPDemuxContext *s)
706 ff_rtp_reset_packet_queue(s);
707 if (!strcmp(ff_rtp_enc_name(s->payload_type), "MP2T")) {
708 ff_mpegts_parse_close(s->ts);
713 int ff_parse_fmtp(AVStream *stream, PayloadContext *data, const char *p,
714 int (*parse_fmtp)(AVStream *stream,
715 PayloadContext *data,
716 char *attr, char *value))
721 int value_size = strlen(p) + 1;
723 if (!(value = av_malloc(value_size))) {
724 av_log(stream, AV_LOG_ERROR, "Failed to allocate data for FMTP.");
725 return AVERROR(ENOMEM);
728 // remove protocol identifier
729 while (*p && *p == ' ') p++; // strip spaces
730 while (*p && *p != ' ') p++; // eat protocol identifier
731 while (*p && *p == ' ') p++; // strip trailing spaces
733 while (ff_rtsp_next_attr_and_value(&p,
735 value, value_size)) {
737 res = parse_fmtp(stream, data, attr, value);
738 if (res < 0 && res != AVERROR_PATCHWELCOME) {