3 * Copyright (c) 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavutil/mathematics.h"
26 #include "libavutil/random_seed.h"
27 #include "libavutil/opt.h"
31 static const AVOption options[] = {
32 FF_RTP_FLAG_OPTS(RTPMuxContext, flags),
33 { "payload_type", "Specify RTP payload type", offsetof(RTPMuxContext, payload_type), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, 127, AV_OPT_FLAG_ENCODING_PARAM },
34 { "ssrc", "Stream identifier", offsetof(RTPMuxContext, ssrc), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
35 { "cname", "CNAME to include in RTCP SR packets", offsetof(RTPMuxContext, cname), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
36 { "seq", "Starting sequence number", offsetof(RTPMuxContext, seq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 65535, AV_OPT_FLAG_ENCODING_PARAM },
40 static const AVClass rtp_muxer_class = {
41 .class_name = "RTP muxer",
42 .item_name = av_default_item_name,
44 .version = LIBAVUTIL_VERSION_INT,
47 #define RTCP_SR_SIZE 28
49 static int is_supported(enum AVCodecID id)
52 case AV_CODEC_ID_H261:
53 case AV_CODEC_ID_H263:
54 case AV_CODEC_ID_H263P:
55 case AV_CODEC_ID_H264:
56 case AV_CODEC_ID_HEVC:
57 case AV_CODEC_ID_MPEG1VIDEO:
58 case AV_CODEC_ID_MPEG2VIDEO:
59 case AV_CODEC_ID_MPEG4:
63 case AV_CODEC_ID_PCM_ALAW:
64 case AV_CODEC_ID_PCM_MULAW:
65 case AV_CODEC_ID_PCM_S8:
66 case AV_CODEC_ID_PCM_S16BE:
67 case AV_CODEC_ID_PCM_S16LE:
68 case AV_CODEC_ID_PCM_U16BE:
69 case AV_CODEC_ID_PCM_U16LE:
70 case AV_CODEC_ID_PCM_U8:
71 case AV_CODEC_ID_MPEG2TS:
72 case AV_CODEC_ID_AMR_NB:
73 case AV_CODEC_ID_AMR_WB:
74 case AV_CODEC_ID_VORBIS:
75 case AV_CODEC_ID_THEORA:
77 case AV_CODEC_ID_ADPCM_G722:
78 case AV_CODEC_ID_ADPCM_G726:
79 case AV_CODEC_ID_ILBC:
80 case AV_CODEC_ID_MJPEG:
81 case AV_CODEC_ID_SPEEX:
82 case AV_CODEC_ID_OPUS:
89 static int rtp_write_header(AVFormatContext *s1)
91 RTPMuxContext *s = s1->priv_data;
92 int n, ret = AVERROR(EINVAL);
95 if (s1->nb_streams != 1) {
96 av_log(s1, AV_LOG_ERROR, "Only one stream supported in the RTP muxer\n");
97 return AVERROR(EINVAL);
100 if (!is_supported(st->codec->codec_id)) {
101 av_log(s1, AV_LOG_ERROR, "Unsupported codec %x\n", st->codec->codec_id);
106 if (s->payload_type < 0) {
107 /* Re-validate non-dynamic payload types */
108 if (st->id < RTP_PT_PRIVATE)
109 st->id = ff_rtp_get_payload_type(s1, st->codec, -1);
111 s->payload_type = st->id;
113 /* private option takes priority */
114 st->id = s->payload_type;
117 s->base_timestamp = av_get_random_seed();
118 s->timestamp = s->base_timestamp;
119 s->cur_timestamp = 0;
121 s->ssrc = av_get_random_seed();
123 s->first_rtcp_ntp_time = ff_ntp_time();
124 if (s1->start_time_realtime)
125 /* Round the NTP time to whole milliseconds. */
126 s->first_rtcp_ntp_time = (s1->start_time_realtime / 1000) * 1000 +
128 // Pick a random sequence start number, but in the lower end of the
129 // available range, so that any wraparound doesn't happen immediately.
130 // (Immediate wraparound would be an issue for SRTP.)
132 s->seq = av_get_random_seed() & 0x0fff;
134 s->seq &= 0xffff; // Use the given parameter, wrapped to the right interval
136 if (s1->packet_size) {
137 if (s1->pb->max_packet_size)
138 s1->packet_size = FFMIN(s1->packet_size,
139 s1->pb->max_packet_size);
141 s1->packet_size = s1->pb->max_packet_size;
142 if (s1->packet_size <= 12) {
143 av_log(s1, AV_LOG_ERROR, "Max packet size %d too low\n", s1->packet_size);
146 s->buf = av_malloc(s1->packet_size);
148 return AVERROR(ENOMEM);
150 s->max_payload_size = s1->packet_size - 12;
152 s->max_frames_per_packet = 0;
153 if (s1->max_delay > 0) {
154 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
155 int frame_size = av_get_audio_frame_duration(st->codec, 0);
157 frame_size = st->codec->frame_size;
158 if (frame_size == 0) {
159 av_log(s1, AV_LOG_ERROR, "Cannot respect max delay: frame size = 0\n");
161 s->max_frames_per_packet =
162 av_rescale_q_rnd(s1->max_delay,
164 (AVRational){ frame_size, st->codec->sample_rate },
168 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
169 /* FIXME: We should round down here... */
170 if (st->avg_frame_rate.num > 0 && st->avg_frame_rate.den > 0) {
171 s->max_frames_per_packet = av_rescale_q(s1->max_delay,
172 (AVRational){1, 1000000},
173 av_inv_q(st->avg_frame_rate));
175 s->max_frames_per_packet = 1;
179 avpriv_set_pts_info(st, 32, 1, 90000);
180 switch(st->codec->codec_id) {
181 case AV_CODEC_ID_MP2:
182 case AV_CODEC_ID_MP3:
183 s->buf_ptr = s->buf + 4;
185 case AV_CODEC_ID_MPEG1VIDEO:
186 case AV_CODEC_ID_MPEG2VIDEO:
188 case AV_CODEC_ID_MPEG2TS:
189 n = s->max_payload_size / TS_PACKET_SIZE;
192 s->max_payload_size = n * TS_PACKET_SIZE;
195 case AV_CODEC_ID_H261:
196 if (s1->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
197 av_log(s, AV_LOG_ERROR,
198 "Packetizing H261 is experimental and produces incorrect "
199 "packetization for cases where GOBs don't fit into packets "
200 "(even though most receivers may handle it just fine). "
201 "Please set -f_strict experimental in order to enable it.\n");
202 ret = AVERROR_EXPERIMENTAL;
206 case AV_CODEC_ID_H264:
207 /* check for H.264 MP4 syntax */
208 if (st->codec->extradata_size > 4 && st->codec->extradata[0] == 1) {
209 s->nal_length_size = (st->codec->extradata[4] & 0x03) + 1;
212 case AV_CODEC_ID_HEVC:
213 /* Only check for the standardized hvcC version of extradata, keeping
214 * things simple and similar to the avcC/H264 case above, instead
215 * of trying to handle the pre-standardization versions (as in
216 * libavcodec/hevc.c). */
217 if (st->codec->extradata_size > 21 && st->codec->extradata[0] == 1) {
218 s->nal_length_size = (st->codec->extradata[21] & 0x03) + 1;
221 case AV_CODEC_ID_VORBIS:
222 case AV_CODEC_ID_THEORA:
223 if (!s->max_frames_per_packet) s->max_frames_per_packet = 15;
224 s->max_frames_per_packet = av_clip(s->max_frames_per_packet, 1, 15);
225 s->max_payload_size -= 6; // ident+frag+tdt/vdt+pkt_num+pkt_length
228 case AV_CODEC_ID_ADPCM_G722:
229 /* Due to a historical error, the clock rate for G722 in RTP is
230 * 8000, even if the sample rate is 16000. See RFC 3551. */
231 avpriv_set_pts_info(st, 32, 1, 8000);
233 case AV_CODEC_ID_OPUS:
234 if (st->codec->channels > 2) {
235 av_log(s1, AV_LOG_ERROR, "Multistream opus not supported in RTP\n");
238 /* The opus RTP RFC says that all opus streams should use 48000 Hz
239 * as clock rate, since all opus sample rates can be expressed in
240 * this clock rate, and sample rate changes on the fly are supported. */
241 avpriv_set_pts_info(st, 32, 1, 48000);
243 case AV_CODEC_ID_ILBC:
244 if (st->codec->block_align != 38 && st->codec->block_align != 50) {
245 av_log(s1, AV_LOG_ERROR, "Incorrect iLBC block size specified\n");
248 if (!s->max_frames_per_packet)
249 s->max_frames_per_packet = 1;
250 s->max_frames_per_packet = FFMIN(s->max_frames_per_packet,
251 s->max_payload_size / st->codec->block_align);
253 case AV_CODEC_ID_AMR_NB:
254 case AV_CODEC_ID_AMR_WB:
255 if (!s->max_frames_per_packet)
256 s->max_frames_per_packet = 12;
257 if (st->codec->codec_id == AV_CODEC_ID_AMR_NB)
261 /* max_header_toc_size + the largest AMR payload must fit */
262 if (1 + s->max_frames_per_packet + n > s->max_payload_size) {
263 av_log(s1, AV_LOG_ERROR, "RTP max payload size too small for AMR\n");
266 if (st->codec->channels != 1) {
267 av_log(s1, AV_LOG_ERROR, "Only mono is supported\n");
272 case AV_CODEC_ID_AAC:
277 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
278 avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);
291 /* send an rtcp sender report packet */
292 static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time, int bye)
294 RTPMuxContext *s = s1->priv_data;
297 av_dlog(s1, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);
299 s->last_rtcp_ntp_time = ntp_time;
300 rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000},
301 s1->streams[0]->time_base) + s->base_timestamp;
302 avio_w8(s1->pb, RTP_VERSION << 6);
303 avio_w8(s1->pb, RTCP_SR);
304 avio_wb16(s1->pb, 6); /* length in words - 1 */
305 avio_wb32(s1->pb, s->ssrc);
306 avio_wb64(s1->pb, NTP_TO_RTP_FORMAT(ntp_time));
307 avio_wb32(s1->pb, rtp_ts);
308 avio_wb32(s1->pb, s->packet_count);
309 avio_wb32(s1->pb, s->octet_count);
312 int len = FFMIN(strlen(s->cname), 255);
313 avio_w8(s1->pb, (RTP_VERSION << 6) + 1);
314 avio_w8(s1->pb, RTCP_SDES);
315 avio_wb16(s1->pb, (7 + len + 3) / 4); /* length in words - 1 */
317 avio_wb32(s1->pb, s->ssrc);
318 avio_w8(s1->pb, 0x01); /* CNAME */
319 avio_w8(s1->pb, len);
320 avio_write(s1->pb, s->cname, len);
321 avio_w8(s1->pb, 0); /* END */
322 for (len = (7 + len) % 4; len % 4; len++)
327 avio_w8(s1->pb, (RTP_VERSION << 6) | 1);
328 avio_w8(s1->pb, RTCP_BYE);
329 avio_wb16(s1->pb, 1); /* length in words - 1 */
330 avio_wb32(s1->pb, s->ssrc);
336 /* send an rtp packet. sequence number is incremented, but the caller
337 must update the timestamp itself */
338 void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m)
340 RTPMuxContext *s = s1->priv_data;
342 av_dlog(s1, "rtp_send_data size=%d\n", len);
344 /* build the RTP header */
345 avio_w8(s1->pb, RTP_VERSION << 6);
346 avio_w8(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7));
347 avio_wb16(s1->pb, s->seq);
348 avio_wb32(s1->pb, s->timestamp);
349 avio_wb32(s1->pb, s->ssrc);
351 avio_write(s1->pb, buf1, len);
354 s->seq = (s->seq + 1) & 0xffff;
355 s->octet_count += len;
359 /* send an integer number of samples and compute time stamp and fill
360 the rtp send buffer before sending. */
361 static int rtp_send_samples(AVFormatContext *s1,
362 const uint8_t *buf1, int size, int sample_size_bits)
364 RTPMuxContext *s = s1->priv_data;
365 int len, max_packet_size, n;
366 /* Calculate the number of bytes to get samples aligned on a byte border */
367 int aligned_samples_size = sample_size_bits/av_gcd(sample_size_bits, 8);
369 max_packet_size = (s->max_payload_size / aligned_samples_size) * aligned_samples_size;
370 /* Not needed, but who knows. Don't check if samples aren't an even number of bytes. */
371 if ((sample_size_bits % 8) == 0 && ((8 * size) % sample_size_bits) != 0)
372 return AVERROR(EINVAL);
376 len = FFMIN(max_packet_size, size);
379 memcpy(s->buf_ptr, buf1, len);
383 s->timestamp = s->cur_timestamp + n * 8 / sample_size_bits;
384 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
385 n += (s->buf_ptr - s->buf);
390 static void rtp_send_mpegaudio(AVFormatContext *s1,
391 const uint8_t *buf1, int size)
393 RTPMuxContext *s = s1->priv_data;
394 int len, count, max_packet_size;
396 max_packet_size = s->max_payload_size;
398 /* test if we must flush because not enough space */
399 len = (s->buf_ptr - s->buf);
400 if ((len + size) > max_packet_size) {
402 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
403 s->buf_ptr = s->buf + 4;
406 if (s->buf_ptr == s->buf + 4) {
407 s->timestamp = s->cur_timestamp;
411 if (size > max_packet_size) {
412 /* big packet: fragment */
415 len = max_packet_size - 4;
418 /* build fragmented packet */
421 s->buf[2] = count >> 8;
423 memcpy(s->buf + 4, buf1, len);
424 ff_rtp_send_data(s1, s->buf, len + 4, 0);
430 if (s->buf_ptr == s->buf + 4) {
431 /* no fragmentation possible */
437 memcpy(s->buf_ptr, buf1, size);
442 static void rtp_send_raw(AVFormatContext *s1,
443 const uint8_t *buf1, int size)
445 RTPMuxContext *s = s1->priv_data;
446 int len, max_packet_size;
448 max_packet_size = s->max_payload_size;
451 len = max_packet_size;
455 s->timestamp = s->cur_timestamp;
456 ff_rtp_send_data(s1, buf1, len, (len == size));
463 /* NOTE: size is assumed to be an integer multiple of TS_PACKET_SIZE */
464 static void rtp_send_mpegts_raw(AVFormatContext *s1,
465 const uint8_t *buf1, int size)
467 RTPMuxContext *s = s1->priv_data;
470 s->timestamp = s->cur_timestamp;
471 while (size >= TS_PACKET_SIZE) {
472 len = s->max_payload_size - (s->buf_ptr - s->buf);
475 memcpy(s->buf_ptr, buf1, len);
480 out_len = s->buf_ptr - s->buf;
481 if (out_len >= s->max_payload_size) {
482 ff_rtp_send_data(s1, s->buf, out_len, 0);
488 static int rtp_send_ilbc(AVFormatContext *s1, const uint8_t *buf, int size)
490 RTPMuxContext *s = s1->priv_data;
491 AVStream *st = s1->streams[0];
492 int frame_duration = av_get_audio_frame_duration(st->codec, 0);
493 int frame_size = st->codec->block_align;
494 int frames = size / frame_size;
497 int n = FFMIN(s->max_frames_per_packet - s->num_frames, frames);
499 if (!s->num_frames) {
501 s->timestamp = s->cur_timestamp;
503 memcpy(s->buf_ptr, buf, n * frame_size);
506 s->buf_ptr += n * frame_size;
507 buf += n * frame_size;
508 s->cur_timestamp += n * frame_duration;
510 if (s->num_frames == s->max_frames_per_packet) {
511 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 1);
518 static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
520 RTPMuxContext *s = s1->priv_data;
521 AVStream *st = s1->streams[0];
525 av_dlog(s1, "%d: write len=%d\n", pkt->stream_index, size);
527 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
529 if ((s->first_packet || ((rtcp_bytes >= RTCP_SR_SIZE) &&
530 (ff_ntp_time() - s->last_rtcp_ntp_time > 5000000))) &&
531 !(s->flags & FF_RTP_FLAG_SKIP_RTCP)) {
532 rtcp_send_sr(s1, ff_ntp_time(), 0);
533 s->last_octet_count = s->octet_count;
536 s->cur_timestamp = s->base_timestamp + pkt->pts;
538 switch(st->codec->codec_id) {
539 case AV_CODEC_ID_PCM_MULAW:
540 case AV_CODEC_ID_PCM_ALAW:
541 case AV_CODEC_ID_PCM_U8:
542 case AV_CODEC_ID_PCM_S8:
543 return rtp_send_samples(s1, pkt->data, size, 8 * st->codec->channels);
544 case AV_CODEC_ID_PCM_U16BE:
545 case AV_CODEC_ID_PCM_U16LE:
546 case AV_CODEC_ID_PCM_S16BE:
547 case AV_CODEC_ID_PCM_S16LE:
548 return rtp_send_samples(s1, pkt->data, size, 16 * st->codec->channels);
549 case AV_CODEC_ID_ADPCM_G722:
550 /* The actual sample size is half a byte per sample, but since the
551 * stream clock rate is 8000 Hz while the sample rate is 16000 Hz,
552 * the correct parameter for send_samples_bits is 8 bits per stream
554 return rtp_send_samples(s1, pkt->data, size, 8 * st->codec->channels);
555 case AV_CODEC_ID_ADPCM_G726:
556 return rtp_send_samples(s1, pkt->data, size,
557 st->codec->bits_per_coded_sample * st->codec->channels);
558 case AV_CODEC_ID_MP2:
559 case AV_CODEC_ID_MP3:
560 rtp_send_mpegaudio(s1, pkt->data, size);
562 case AV_CODEC_ID_MPEG1VIDEO:
563 case AV_CODEC_ID_MPEG2VIDEO:
564 ff_rtp_send_mpegvideo(s1, pkt->data, size);
566 case AV_CODEC_ID_AAC:
567 if (s->flags & FF_RTP_FLAG_MP4A_LATM)
568 ff_rtp_send_latm(s1, pkt->data, size);
570 ff_rtp_send_aac(s1, pkt->data, size);
572 case AV_CODEC_ID_AMR_NB:
573 case AV_CODEC_ID_AMR_WB:
574 ff_rtp_send_amr(s1, pkt->data, size);
576 case AV_CODEC_ID_MPEG2TS:
577 rtp_send_mpegts_raw(s1, pkt->data, size);
579 case AV_CODEC_ID_H264:
580 ff_rtp_send_h264(s1, pkt->data, size);
582 case AV_CODEC_ID_H261:
583 ff_rtp_send_h261(s1, pkt->data, size);
585 case AV_CODEC_ID_H263:
586 if (s->flags & FF_RTP_FLAG_RFC2190) {
587 int mb_info_size = 0;
588 const uint8_t *mb_info =
589 av_packet_get_side_data(pkt, AV_PKT_DATA_H263_MB_INFO,
591 ff_rtp_send_h263_rfc2190(s1, pkt->data, size, mb_info, mb_info_size);
595 case AV_CODEC_ID_H263P:
596 ff_rtp_send_h263(s1, pkt->data, size);
598 case AV_CODEC_ID_HEVC:
599 ff_rtp_send_hevc(s1, pkt->data, size);
601 case AV_CODEC_ID_VORBIS:
602 case AV_CODEC_ID_THEORA:
603 ff_rtp_send_xiph(s1, pkt->data, size);
605 case AV_CODEC_ID_VP8:
606 ff_rtp_send_vp8(s1, pkt->data, size);
608 case AV_CODEC_ID_ILBC:
609 rtp_send_ilbc(s1, pkt->data, size);
611 case AV_CODEC_ID_MJPEG:
612 ff_rtp_send_jpeg(s1, pkt->data, size);
614 case AV_CODEC_ID_OPUS:
615 if (size > s->max_payload_size) {
616 av_log(s1, AV_LOG_ERROR,
617 "Packet size %d too large for max RTP payload size %d\n",
618 size, s->max_payload_size);
619 return AVERROR(EINVAL);
621 /* Intentional fallthrough */
623 /* better than nothing : send the codec raw data */
624 rtp_send_raw(s1, pkt->data, size);
630 static int rtp_write_trailer(AVFormatContext *s1)
632 RTPMuxContext *s = s1->priv_data;
634 /* If the caller closes and recreates ->pb, this might actually
635 * be NULL here even if it was successfully allocated at the start. */
636 if (s1->pb && (s->flags & FF_RTP_FLAG_SEND_BYE))
637 rtcp_send_sr(s1, ff_ntp_time(), 1);
643 AVOutputFormat ff_rtp_muxer = {
645 .long_name = NULL_IF_CONFIG_SMALL("RTP output"),
646 .priv_data_size = sizeof(RTPMuxContext),
647 .audio_codec = AV_CODEC_ID_PCM_MULAW,
648 .video_codec = AV_CODEC_ID_MPEG4,
649 .write_header = rtp_write_header,
650 .write_packet = rtp_write_packet,
651 .write_trailer = rtp_write_trailer,
652 .priv_class = &rtp_muxer_class,
653 .flags = AVFMT_TS_NONSTRICT,