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
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->codecpar->codec_id)) {
101 av_log(s1, AV_LOG_ERROR, "Unsupported codec %s\n", avcodec_get_name(st->codecpar->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->codecpar, -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 != 0 && s1->start_time_realtime != AV_NOPTS_VALUE)
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 if (s1->flags & AVFMT_FLAG_BITEXACT) {
135 s->seq = av_get_random_seed() & 0x0fff;
137 s->seq &= 0xffff; // Use the given parameter, wrapped to the right interval
139 if (s1->packet_size) {
140 if (s1->pb->max_packet_size)
141 s1->packet_size = FFMIN(s1->packet_size,
142 s1->pb->max_packet_size);
144 s1->packet_size = s1->pb->max_packet_size;
145 if (s1->packet_size <= 12) {
146 av_log(s1, AV_LOG_ERROR, "Max packet size %d too low\n", s1->packet_size);
149 s->buf = av_malloc(s1->packet_size);
151 return AVERROR(ENOMEM);
153 s->max_payload_size = s1->packet_size - 12;
155 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
156 avpriv_set_pts_info(st, 32, 1, st->codecpar->sample_rate);
158 avpriv_set_pts_info(st, 32, 1, 90000);
161 switch(st->codecpar->codec_id) {
162 case AV_CODEC_ID_MP2:
163 case AV_CODEC_ID_MP3:
164 s->buf_ptr = s->buf + 4;
165 avpriv_set_pts_info(st, 32, 1, 90000);
167 case AV_CODEC_ID_MPEG1VIDEO:
168 case AV_CODEC_ID_MPEG2VIDEO:
170 case AV_CODEC_ID_MPEG2TS:
171 n = s->max_payload_size / TS_PACKET_SIZE;
174 s->max_payload_size = n * TS_PACKET_SIZE;
176 case AV_CODEC_ID_H261:
177 if (s1->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
178 av_log(s, AV_LOG_ERROR,
179 "Packetizing H261 is experimental and produces incorrect "
180 "packetization for cases where GOBs don't fit into packets "
181 "(even though most receivers may handle it just fine). "
182 "Please set -f_strict experimental in order to enable it.\n");
183 ret = AVERROR_EXPERIMENTAL;
187 case AV_CODEC_ID_H264:
188 /* check for H.264 MP4 syntax */
189 if (st->codecpar->extradata_size > 4 && st->codecpar->extradata[0] == 1) {
190 s->nal_length_size = (st->codecpar->extradata[4] & 0x03) + 1;
193 case AV_CODEC_ID_HEVC:
194 /* Only check for the standardized hvcC version of extradata, keeping
195 * things simple and similar to the avcC/H264 case above, instead
196 * of trying to handle the pre-standardization versions (as in
197 * libavcodec/hevc.c). */
198 if (st->codecpar->extradata_size > 21 && st->codecpar->extradata[0] == 1) {
199 s->nal_length_size = (st->codecpar->extradata[21] & 0x03) + 1;
202 case AV_CODEC_ID_VORBIS:
203 case AV_CODEC_ID_THEORA:
204 s->max_frames_per_packet = 15;
206 case AV_CODEC_ID_ADPCM_G722:
207 /* Due to a historical error, the clock rate for G722 in RTP is
208 * 8000, even if the sample rate is 16000. See RFC 3551. */
209 avpriv_set_pts_info(st, 32, 1, 8000);
211 case AV_CODEC_ID_OPUS:
212 if (st->codecpar->channels > 2) {
213 av_log(s1, AV_LOG_ERROR, "Multistream opus not supported in RTP\n");
216 /* The opus RTP RFC says that all opus streams should use 48000 Hz
217 * as clock rate, since all opus sample rates can be expressed in
218 * this clock rate, and sample rate changes on the fly are supported. */
219 avpriv_set_pts_info(st, 32, 1, 48000);
221 case AV_CODEC_ID_ILBC:
222 if (st->codecpar->block_align != 38 && st->codecpar->block_align != 50) {
223 av_log(s1, AV_LOG_ERROR, "Incorrect iLBC block size specified\n");
226 s->max_frames_per_packet = s->max_payload_size / st->codecpar->block_align;
228 case AV_CODEC_ID_AMR_NB:
229 case AV_CODEC_ID_AMR_WB:
230 s->max_frames_per_packet = 50;
231 if (st->codecpar->codec_id == AV_CODEC_ID_AMR_NB)
235 /* max_header_toc_size + the largest AMR payload must fit */
236 if (1 + s->max_frames_per_packet + n > s->max_payload_size) {
237 av_log(s1, AV_LOG_ERROR, "RTP max payload size too small for AMR\n");
240 if (st->codecpar->channels != 1) {
241 av_log(s1, AV_LOG_ERROR, "Only mono is supported\n");
245 case AV_CODEC_ID_AAC:
246 s->max_frames_per_packet = 50;
259 /* send an rtcp sender report packet */
260 static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time, int bye)
262 RTPMuxContext *s = s1->priv_data;
265 av_log(s1, AV_LOG_TRACE, "RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);
267 s->last_rtcp_ntp_time = ntp_time;
268 rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, (AVRational){1, 1000000},
269 s1->streams[0]->time_base) + s->base_timestamp;
270 avio_w8(s1->pb, RTP_VERSION << 6);
271 avio_w8(s1->pb, RTCP_SR);
272 avio_wb16(s1->pb, 6); /* length in words - 1 */
273 avio_wb32(s1->pb, s->ssrc);
274 avio_wb32(s1->pb, ntp_time / 1000000);
275 avio_wb32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000);
276 avio_wb32(s1->pb, rtp_ts);
277 avio_wb32(s1->pb, s->packet_count);
278 avio_wb32(s1->pb, s->octet_count);
281 int len = FFMIN(strlen(s->cname), 255);
282 avio_w8(s1->pb, (RTP_VERSION << 6) + 1);
283 avio_w8(s1->pb, RTCP_SDES);
284 avio_wb16(s1->pb, (7 + len + 3) / 4); /* length in words - 1 */
286 avio_wb32(s1->pb, s->ssrc);
287 avio_w8(s1->pb, 0x01); /* CNAME */
288 avio_w8(s1->pb, len);
289 avio_write(s1->pb, s->cname, len);
290 avio_w8(s1->pb, 0); /* END */
291 for (len = (7 + len) % 4; len % 4; len++)
296 avio_w8(s1->pb, (RTP_VERSION << 6) | 1);
297 avio_w8(s1->pb, RTCP_BYE);
298 avio_wb16(s1->pb, 1); /* length in words - 1 */
299 avio_wb32(s1->pb, s->ssrc);
305 /* send an rtp packet. sequence number is incremented, but the caller
306 must update the timestamp itself */
307 void ff_rtp_send_data(AVFormatContext *s1, const uint8_t *buf1, int len, int m)
309 RTPMuxContext *s = s1->priv_data;
311 av_log(s1, AV_LOG_TRACE, "rtp_send_data size=%d\n", len);
313 /* build the RTP header */
314 avio_w8(s1->pb, RTP_VERSION << 6);
315 avio_w8(s1->pb, (s->payload_type & 0x7f) | ((m & 0x01) << 7));
316 avio_wb16(s1->pb, s->seq);
317 avio_wb32(s1->pb, s->timestamp);
318 avio_wb32(s1->pb, s->ssrc);
320 avio_write(s1->pb, buf1, len);
323 s->seq = (s->seq + 1) & 0xffff;
324 s->octet_count += len;
328 /* send an integer number of samples and compute time stamp and fill
329 the rtp send buffer before sending. */
330 static int rtp_send_samples(AVFormatContext *s1,
331 const uint8_t *buf1, int size, int sample_size_bits)
333 RTPMuxContext *s = s1->priv_data;
334 int len, max_packet_size, n;
335 /* Calculate the number of bytes to get samples aligned on a byte border */
336 int aligned_samples_size = sample_size_bits/av_gcd(sample_size_bits, 8);
338 max_packet_size = (s->max_payload_size / aligned_samples_size) * aligned_samples_size;
339 /* Not needed, but who knows. Don't check if samples aren't an even number of bytes. */
340 if ((sample_size_bits % 8) == 0 && ((8 * size) % sample_size_bits) != 0)
341 return AVERROR(EINVAL);
345 len = FFMIN(max_packet_size, size);
348 memcpy(s->buf_ptr, buf1, len);
352 s->timestamp = s->cur_timestamp + n * 8 / sample_size_bits;
353 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
354 n += (s->buf_ptr - s->buf);
359 static void rtp_send_mpegaudio(AVFormatContext *s1,
360 const uint8_t *buf1, int size)
362 RTPMuxContext *s = s1->priv_data;
363 int len, count, max_packet_size;
365 max_packet_size = s->max_payload_size;
367 /* test if we must flush because not enough space */
368 len = (s->buf_ptr - s->buf);
369 if ((len + size) > max_packet_size) {
371 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 0);
372 s->buf_ptr = s->buf + 4;
375 if (s->buf_ptr == s->buf + 4) {
376 s->timestamp = s->cur_timestamp;
380 if (size > max_packet_size) {
381 /* big packet: fragment */
384 len = max_packet_size - 4;
387 /* build fragmented packet */
390 s->buf[2] = count >> 8;
392 memcpy(s->buf + 4, buf1, len);
393 ff_rtp_send_data(s1, s->buf, len + 4, 0);
399 if (s->buf_ptr == s->buf + 4) {
400 /* no fragmentation possible */
406 memcpy(s->buf_ptr, buf1, size);
411 static void rtp_send_raw(AVFormatContext *s1,
412 const uint8_t *buf1, int size)
414 RTPMuxContext *s = s1->priv_data;
415 int len, max_packet_size;
417 max_packet_size = s->max_payload_size;
420 len = max_packet_size;
424 s->timestamp = s->cur_timestamp;
425 ff_rtp_send_data(s1, buf1, len, (len == size));
432 /* NOTE: size is assumed to be an integer multiple of TS_PACKET_SIZE */
433 static void rtp_send_mpegts_raw(AVFormatContext *s1,
434 const uint8_t *buf1, int size)
436 RTPMuxContext *s = s1->priv_data;
439 s->timestamp = s->cur_timestamp;
440 while (size >= TS_PACKET_SIZE) {
441 len = s->max_payload_size - (s->buf_ptr - s->buf);
444 memcpy(s->buf_ptr, buf1, len);
449 out_len = s->buf_ptr - s->buf;
450 if (out_len >= s->max_payload_size) {
451 ff_rtp_send_data(s1, s->buf, out_len, 0);
457 static int rtp_send_ilbc(AVFormatContext *s1, const uint8_t *buf, int size)
459 RTPMuxContext *s = s1->priv_data;
460 AVStream *st = s1->streams[0];
461 int frame_duration = av_get_audio_frame_duration2(st->codecpar, 0);
462 int frame_size = st->codecpar->block_align;
463 int frames = size / frame_size;
466 if (s->num_frames > 0 &&
467 av_compare_ts(s->cur_timestamp - s->timestamp, st->time_base,
468 s1->max_delay, AV_TIME_BASE_Q) >= 0) {
469 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 1);
473 if (!s->num_frames) {
475 s->timestamp = s->cur_timestamp;
477 memcpy(s->buf_ptr, buf, frame_size);
480 s->buf_ptr += frame_size;
482 s->cur_timestamp += frame_duration;
484 if (s->num_frames == s->max_frames_per_packet) {
485 ff_rtp_send_data(s1, s->buf, s->buf_ptr - s->buf, 1);
492 static int rtp_write_packet(AVFormatContext *s1, AVPacket *pkt)
494 RTPMuxContext *s = s1->priv_data;
495 AVStream *st = s1->streams[0];
499 av_log(s1, AV_LOG_TRACE, "%d: write len=%d\n", pkt->stream_index, size);
501 rtcp_bytes = ((s->octet_count - s->last_octet_count) * RTCP_TX_RATIO_NUM) /
503 if ((s->first_packet || ((rtcp_bytes >= RTCP_SR_SIZE) &&
504 (ff_ntp_time() - s->last_rtcp_ntp_time > 5000000))) &&
505 !(s->flags & FF_RTP_FLAG_SKIP_RTCP)) {
506 rtcp_send_sr(s1, ff_ntp_time(), 0);
507 s->last_octet_count = s->octet_count;
510 s->cur_timestamp = s->base_timestamp + pkt->pts;
512 switch(st->codecpar->codec_id) {
513 case AV_CODEC_ID_PCM_MULAW:
514 case AV_CODEC_ID_PCM_ALAW:
515 case AV_CODEC_ID_PCM_U8:
516 case AV_CODEC_ID_PCM_S8:
517 return rtp_send_samples(s1, pkt->data, size, 8 * st->codecpar->channels);
518 case AV_CODEC_ID_PCM_U16BE:
519 case AV_CODEC_ID_PCM_U16LE:
520 case AV_CODEC_ID_PCM_S16BE:
521 case AV_CODEC_ID_PCM_S16LE:
522 return rtp_send_samples(s1, pkt->data, size, 16 * st->codecpar->channels);
523 case AV_CODEC_ID_ADPCM_G722:
524 /* The actual sample size is half a byte per sample, but since the
525 * stream clock rate is 8000 Hz while the sample rate is 16000 Hz,
526 * the correct parameter for send_samples_bits is 8 bits per stream
528 return rtp_send_samples(s1, pkt->data, size, 8 * st->codecpar->channels);
529 case AV_CODEC_ID_ADPCM_G726:
530 return rtp_send_samples(s1, pkt->data, size,
531 st->codecpar->bits_per_coded_sample * st->codecpar->channels);
532 case AV_CODEC_ID_MP2:
533 case AV_CODEC_ID_MP3:
534 rtp_send_mpegaudio(s1, pkt->data, size);
536 case AV_CODEC_ID_MPEG1VIDEO:
537 case AV_CODEC_ID_MPEG2VIDEO:
538 ff_rtp_send_mpegvideo(s1, pkt->data, size);
540 case AV_CODEC_ID_AAC:
541 if (s->flags & FF_RTP_FLAG_MP4A_LATM)
542 ff_rtp_send_latm(s1, pkt->data, size);
544 ff_rtp_send_aac(s1, pkt->data, size);
546 case AV_CODEC_ID_AMR_NB:
547 case AV_CODEC_ID_AMR_WB:
548 ff_rtp_send_amr(s1, pkt->data, size);
550 case AV_CODEC_ID_MPEG2TS:
551 rtp_send_mpegts_raw(s1, pkt->data, size);
553 case AV_CODEC_ID_H264:
554 ff_rtp_send_h264_hevc(s1, pkt->data, size);
556 case AV_CODEC_ID_H261:
557 ff_rtp_send_h261(s1, pkt->data, size);
559 case AV_CODEC_ID_H263:
560 if (s->flags & FF_RTP_FLAG_RFC2190) {
561 int mb_info_size = 0;
562 const uint8_t *mb_info =
563 av_packet_get_side_data(pkt, AV_PKT_DATA_H263_MB_INFO,
565 ff_rtp_send_h263_rfc2190(s1, pkt->data, size, mb_info, mb_info_size);
569 case AV_CODEC_ID_H263P:
570 ff_rtp_send_h263(s1, pkt->data, size);
572 case AV_CODEC_ID_HEVC:
573 ff_rtp_send_h264_hevc(s1, pkt->data, size);
575 case AV_CODEC_ID_VORBIS:
576 case AV_CODEC_ID_THEORA:
577 ff_rtp_send_xiph(s1, pkt->data, size);
579 case AV_CODEC_ID_VP8:
580 ff_rtp_send_vp8(s1, pkt->data, size);
582 case AV_CODEC_ID_ILBC:
583 rtp_send_ilbc(s1, pkt->data, size);
585 case AV_CODEC_ID_MJPEG:
586 ff_rtp_send_jpeg(s1, pkt->data, size);
588 case AV_CODEC_ID_OPUS:
589 if (size > s->max_payload_size) {
590 av_log(s1, AV_LOG_ERROR,
591 "Packet size %d too large for max RTP payload size %d\n",
592 size, s->max_payload_size);
593 return AVERROR(EINVAL);
595 /* Intentional fallthrough */
597 /* better than nothing : send the codec raw data */
598 rtp_send_raw(s1, pkt->data, size);
604 static int rtp_write_trailer(AVFormatContext *s1)
606 RTPMuxContext *s = s1->priv_data;
608 /* If the caller closes and recreates ->pb, this might actually
609 * be NULL here even if it was successfully allocated at the start. */
610 if (s1->pb && (s->flags & FF_RTP_FLAG_SEND_BYE))
611 rtcp_send_sr(s1, ff_ntp_time(), 1);
617 AVOutputFormat ff_rtp_muxer = {
619 .long_name = NULL_IF_CONFIG_SMALL("RTP output"),
620 .priv_data_size = sizeof(RTPMuxContext),
621 .audio_codec = AV_CODEC_ID_PCM_MULAW,
622 .video_codec = AV_CODEC_ID_MPEG4,
623 .write_header = rtp_write_header,
624 .write_packet = rtp_write_packet,
625 .write_trailer = rtp_write_trailer,
626 .priv_class = &rtp_muxer_class,
627 .flags = AVFMT_TS_NONSTRICT,