FFmpeg
Loading...
Searching...
No Matches
whip.c
Go to the documentation of this file.
1/*
2 * WebRTC-HTTP ingestion protocol (WHIP) muxer
3 * Copyright (c) 2023 The FFmpeg Project
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
22#include "libavcodec/h264.h"
24
26#include "libavutil/avassert.h"
27#include "libavutil/bprint.h"
29#include "libavutil/lfg.h"
30#include "libavutil/opt.h"
31#include "libavutil/mem.h"
32#include "libavutil/time.h"
33#include "avc.h"
34#include "nal.h"
35#include "avio_internal.h"
36#include "internal.h"
37#include "mux.h"
38#include "rtc.h"
39#include "rtp.h"
40#include "srtp.h"
41#include "tls.h"
42
43/* Referring to Chrome's definition of RTP payload types. */
44#define WHIP_RTP_PAYLOAD_TYPE_H264 106
45#define WHIP_RTP_PAYLOAD_TYPE_OPUS 111
46#define WHIP_RTP_PAYLOAD_TYPE_VIDEO_RTX 105
47
48/**
49 * In the case of ICE-LITE, these fields are not used; instead, they are defined
50 * as constant values.
51 */
52#define WHIP_SDP_SESSION_ID "4489045141692799359"
53#define WHIP_SDP_CREATOR_IP "127.0.0.1"
54
55/**
56 * RTP history packet size.
57 * Target is buffering 1000ms of RTP history packets.
58 *
59 * bandwidth_bps = (RTP payload bytes) * (RTP history size) * 8
60 * Assumes average RTP payload is 1184 bytes (MTU - SRTP_CHECKSUM_LEN).
61 */
62#define WHIP_RTP_HISTORY_MIN 64 /* around 0.61 Mbps */
63#define WHIP_RTP_HISTORY_DEFAULT 512 /* around 4.85 Mbps */
64#define WHIP_RTP_HISTORY_MAX 2048 /* around 19.40 Mbps */
65
66typedef struct RtpHistoryItem {
67 uint16_t seq;
68 int size;
69 uint8_t *buf;
71
72typedef struct WHIPContext {
75
76 /* Parameters for the input audio and video codecs. */
79
80 /**
81 * The h264_mp4toannexb Bitstream Filter (BSF) bypasses the AnnexB packet;
82 * therefore, it is essential to insert the SPS and PPS before each IDR frame
83 * in such cases.
84 */
86
87 /* The SSRC of the audio and video stream, generated by the muxer. */
88 uint32_t audio_ssrc;
89 uint32_t video_ssrc;
91
94
95 uint16_t video_rtx_seq;
96 /* The PT(Payload Type) of stream, generated by the muxer. */
100
101 /* The SRTP send context, to encrypt outgoing packets. */
106 /* The SRTP receive context, to decrypt incoming packets. */
108
111 uint8_t *hist_pool;
114
115/**
116 * Initialize and check the options for the WebRTC muxer.
117 */
119{
120 int ret, ideal_pkt_size = 532;
121 WHIPContext *whip = s->priv_data;
122 RTCContext *rtc = &whip->rtc;
123
124 rtc->ctx = s;
125
126 if ((ret = ff_rtc_initialize(rtc)) < 0)
127 return ret;
128
129 whip->audio_first_seq = av_lfg_get(&rtc->rnd) & 0x0fff;
130 whip->video_first_seq = whip->audio_first_seq + 1;
131
132 if (rtc->pkt_size < ideal_pkt_size)
133 av_log(whip, AV_LOG_WARNING, "pkt_size=%d(<%d) is too small, may cause packet loss\n",
134 rtc->pkt_size, ideal_pkt_size);
135
136 whip->hist = av_calloc(whip->hist_sz, sizeof(*whip->hist));
137 if (!whip->hist)
138 return AVERROR(ENOMEM);
139
141 if (!whip->hist_pool)
142 return AVERROR(ENOMEM);
143
144 for (int i = 0; i < whip->hist_sz; i++)
145 whip->hist[i].buf = whip->hist_pool + i * (rtc->pkt_size - RTC_DTLS_SRTP_CHECKSUM_LEN);
146
147 return 0;
148}
149
150/**
151 * When duplicating a stream, the demuxer has already set the extradata, profile, and
152 * level of the par. Keep in mind that this function will not be invoked since the
153 * profile and level are set.
154 *
155 * When utilizing an encoder, such as libx264, to encode a stream, the extradata in
156 * par->extradata contains the SPS, which includes profile and level information.
157 * However, the profile and level of par remain unspecified. Therefore, it is necessary
158 * to extract the profile and level data from the extradata and assign it to the par's
159 * profile and level. Keep in mind that AVFMT_GLOBALHEADER must be enabled; otherwise,
160 * the extradata will remain empty.
161 */
163{
164 int ret = 0;
165 const uint8_t *r = par->extradata, *r1, *end = par->extradata + par->extradata_size;
166 H264SPS seq, *const sps = &seq;
167 uint32_t state;
168 WHIPContext *whip = s->priv_data;
169
170 if (par->codec_id != AV_CODEC_ID_H264)
171 return ret;
172
173 if (par->profile != AV_PROFILE_UNKNOWN && par->level != AV_LEVEL_UNKNOWN)
174 return ret;
175
176 if (!par->extradata || par->extradata_size <= 0) {
177 av_log(whip, AV_LOG_ERROR, "Unable to parse profile from empty extradata=%p, size=%d\n",
178 par->extradata, par->extradata_size);
179 return AVERROR(EINVAL);
180 }
181
182 while (1) {
184 if (r >= end)
185 break;
186
187 r1 = ff_nal_find_startcode(r, end);
188 if ((state & 0x1f) == H264_NAL_SPS) {
189 ret = ff_avc_decode_sps(sps, r, r1 - r);
190 if (ret < 0) {
191 av_log(whip, AV_LOG_ERROR, "Failed to decode SPS, state=%x, size=%d\n",
192 state, (int)(r1 - r));
193 return ret;
194 }
195
196 av_log(whip, AV_LOG_VERBOSE, "Parse profile=%d, level=%d from SPS\n",
197 sps->profile_idc, sps->level_idc);
198 par->profile = sps->profile_idc;
199 par->level = sps->level_idc;
200 }
201
202 r = r1;
203 }
204
205 return ret;
206}
207
208/**
209 * Parses video SPS/PPS from the extradata of codecpar and checks the codec.
210 * Currently only supports video(h264) and audio(opus). Note that only baseline
211 * and constrained baseline profiles of h264 are supported.
212 *
213 * If the profile is less than 0, the function considers the profile as baseline.
214 * It may need to parse the profile from SPS/PPS. This situation occurs when ingesting
215 * desktop and transcoding.
216 *
217 * @param s Pointer to the AVFormatContext
218 * @returns Returns 0 if successful or AVERROR_xxx in case of an error.
219 *
220 * TODO: FIXME: There is an issue with the timestamp of OPUS audio, especially when
221 * the input is an MP4 file. The timestamp deviates from the expected value of 960,
222 * causing Chrome to play the audio stream with noise. This problem can be replicated
223 * by transcoding a specific file into MP4 format and publishing it using the WHIP
224 * muxer. However, when directly transcoding and publishing through the WHIP muxer,
225 * the issue is not present, and the audio timestamp remains consistent. The root
226 * cause is still unknown, and this comment has been added to address this issue
227 * in the future. Further research is needed to resolve the problem.
228 */
230{
231 int i, ret = 0;
232 WHIPContext *whip = s->priv_data;
233
234 for (i = 0; i < s->nb_streams; i++) {
235 AVCodecParameters *par = s->streams[i]->codecpar;
236 switch (par->codec_type) {
238 whip->video_par = par;
239
240 if (par->video_delay > 0) {
241 av_log(whip, AV_LOG_ERROR, "Unsupported B frames by RTC\n");
243 }
244
245 if ((ret = parse_profile_level(s, par)) < 0) {
246 av_log(whip, AV_LOG_ERROR, "Failed to parse SPS/PPS from extradata\n");
247 return AVERROR(EINVAL);
248 }
249
250 if (par->profile == AV_PROFILE_UNKNOWN) {
251 av_log(whip, AV_LOG_WARNING, "No profile found in extradata, consider baseline\n");
252 return AVERROR(EINVAL);
253 }
254 if (par->level == AV_LEVEL_UNKNOWN) {
255 av_log(whip, AV_LOG_WARNING, "No level found in extradata, consider 3.1\n");
256 return AVERROR(EINVAL);
257 }
258 break;
260 whip->audio_par = par;
261
262 if (par->ch_layout.nb_channels != 2) {
263 av_log(whip, AV_LOG_ERROR, "Unsupported audio channels %d by RTC, choose stereo\n",
266 }
267
268 if (par->sample_rate != 48000) {
269 av_log(whip, AV_LOG_ERROR, "Unsupported audio sample rate %d by RTC, choose 48000\n", par->sample_rate);
271 }
272 break;
273 default:
274 av_unreachable("already checked via FF_OFMT flags");
275 }
276 }
277
278 return ret;
279}
280
281/**
282 * Generate SDP offer according to the codec parameters, DTLS and ICE information.
283 *
284 * Note that we don't use av_sdp_create to generate SDP offer because it doesn't
285 * support DTLS and ICE information.
286 *
287 * @return 0 if OK, AVERROR_xxx on error
288 */
290{
291 int ret = 0, profile_idc = 0, level, profile_iop = 0;
292 const char *acodec_name = NULL, *vcodec_name = NULL;
293 char bundle[4];
294 int bundle_index = 0;
295 AVBPrint bp;
296 WHIPContext *whip = s->priv_data;
297 RTCContext *rtc = &whip->rtc;
298 int is_dtls_active = rtc->flags & RTC_DTLS_ACTIVE;
299
300 /* To prevent a crash during cleanup, always initialize it. */
302
303 if (rtc->sdp_offer) {
304 av_log(whip, AV_LOG_ERROR, "SDP offer is already set\n");
305 ret = AVERROR(EINVAL);
306 goto end;
307 }
308
309 snprintf(rtc->ice_ufrag_local, sizeof(rtc->ice_ufrag_local), "%08x",
310 av_lfg_get(&rtc->rnd));
311 snprintf(rtc->ice_pwd_local, sizeof(rtc->ice_pwd_local), "%08x%08x%08x%08x",
312 av_lfg_get(&rtc->rnd), av_lfg_get(&rtc->rnd), av_lfg_get(&rtc->rnd),
313 av_lfg_get(&rtc->rnd));
314
315 whip->audio_ssrc = av_lfg_get(&rtc->rnd);
316 whip->video_ssrc = whip->audio_ssrc + 1;
317 whip->video_rtx_ssrc = whip->video_ssrc + 1;
318
322
323 if (whip->audio_par) {
324 bundle[bundle_index++] = '0';
325 bundle[bundle_index++] = ' ';
326 }
327 if (whip->video_par) {
328 bundle[bundle_index++] = '1';
329 bundle[bundle_index++] = ' ';
330 }
331 bundle[bundle_index - 1] = '\0';
332
333 av_bprintf(&bp, ""
334 "v=0\r\n"
335 "o=FFmpeg %s 2 IN IP4 %s\r\n"
336 "s=FFmpegPublishSession\r\n"
337 "t=0 0\r\n"
338 "a=group:BUNDLE %s\r\n"
339 "a=extmap-allow-mixed\r\n"
340 "a=msid-semantic: WMS\r\n",
343 bundle);
344
345 if (whip->audio_par) {
346 if (whip->audio_par->codec_id == AV_CODEC_ID_OPUS)
347 acodec_name = "opus";
348
349 av_bprintf(&bp, ""
350 "m=audio 9 UDP/TLS/RTP/SAVPF %u\r\n"
351 "c=IN IP4 0.0.0.0\r\n"
352 "a=ice-ufrag:%s\r\n"
353 "a=ice-pwd:%s\r\n"
354 "a=fingerprint:sha-256 %s\r\n"
355 "a=setup:%s\r\n"
356 "a=mid:0\r\n"
357 "a=sendonly\r\n"
358 "a=msid:FFmpeg audio\r\n"
359 "a=rtcp-mux\r\n"
360 "a=rtpmap:%u %s/%d/%d\r\n"
361 "a=ssrc:%u cname:FFmpeg\r\n"
362 "a=ssrc:%u msid:FFmpeg audio\r\n",
363 whip->audio_payload_type,
364 rtc->ice_ufrag_local,
365 rtc->ice_pwd_local,
366 rtc->dtls_fingerprint,
367 is_dtls_active ? "active" : "passive",
368 whip->audio_payload_type,
369 acodec_name,
370 whip->audio_par->sample_rate,
372 whip->audio_ssrc,
373 whip->audio_ssrc);
374 }
375
376 if (whip->video_par) {
377 level = whip->video_par->level;
378 if (whip->video_par->codec_id == AV_CODEC_ID_H264) {
379 vcodec_name = "H264";
380 profile_iop |= whip->video_par->profile & AV_PROFILE_H264_CONSTRAINED ? 1 << 6 : 0;
381 profile_iop |= whip->video_par->profile & AV_PROFILE_H264_INTRA ? 1 << 4 : 0;
382 profile_idc = whip->video_par->profile & 0x00ff;
383 }
384
385 av_bprintf(&bp, ""
386 "m=video 9 UDP/TLS/RTP/SAVPF %u %u\r\n"
387 "c=IN IP4 0.0.0.0\r\n"
388 "a=ice-ufrag:%s\r\n"
389 "a=ice-pwd:%s\r\n"
390 "a=fingerprint:sha-256 %s\r\n"
391 "a=setup:%s\r\n"
392 "a=mid:1\r\n"
393 "a=sendonly\r\n"
394 "a=msid:FFmpeg video\r\n"
395 "a=rtcp-mux\r\n"
396 "a=rtcp-rsize\r\n"
397 "a=rtpmap:%u %s/90000\r\n"
398 "a=fmtp:%u level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=%02x%02x%02x\r\n"
399 "a=rtcp-fb:%u nack\r\n"
400 "a=rtpmap:%u rtx/90000\r\n"
401 "a=fmtp:%u apt=%u\r\n"
402 "a=ssrc-group:FID %u %u\r\n"
403 "a=ssrc:%u cname:FFmpeg\r\n"
404 "a=ssrc:%u msid:FFmpeg video\r\n",
405 whip->video_payload_type,
407 rtc->ice_ufrag_local,
408 rtc->ice_pwd_local,
409 rtc->dtls_fingerprint,
410 is_dtls_active ? "active" : "passive",
411 whip->video_payload_type,
412 vcodec_name,
413 whip->video_payload_type,
415 profile_iop,
416 level,
417 whip->video_payload_type,
420 whip->video_payload_type,
421 whip->video_ssrc,
422 whip->video_rtx_ssrc,
423 whip->video_ssrc,
424 whip->video_ssrc);
425 }
426
427 if (!av_bprint_is_complete(&bp)) {
428 av_log(whip, AV_LOG_ERROR, "Offer exceed max %d, %s\n", RTC_MAX_SDP_SIZE, bp.str);
429 ret = AVERROR(EIO);
430 goto end;
431 }
432
433 rtc->sdp_offer = av_strdup(bp.str);
434 if (!rtc->sdp_offer) {
435 ret = AVERROR(ENOMEM);
436 goto end;
437 }
438
439 if (rtc->state < RTC_STATE_OFFER)
440 rtc->state = RTC_STATE_OFFER;
442 av_log(whip, AV_LOG_VERBOSE, "Generated state=%d, offer: %s\n", rtc->state, rtc->sdp_offer);
443
444end:
446 return ret;
447}
448
449/**
450 * Establish the SRTP context using the keying material exported from DTLS.
451 *
452 * Create separate SRTP contexts for sending video and audio, as their sequences differ
453 * and should not share a single context. Generate a single SRTP context for receiving
454 * RTCP only.
455 *
456 * @return 0 if OK, AVERROR_xxx on error
457 */
459{
460 int ret;
461 WHIPContext *whip = s->priv_data;
462 RTCContext *rtc = &whip->rtc;
463
465 if (ret < 0)
466 goto end;
467
468 /* Setup SRTP context for outgoing packets */
470 if (ret < 0) {
471 av_log(whip, AV_LOG_ERROR, "Failed to set crypto for audio send\n");
472 goto end;
473 }
474
476 if (ret < 0) {
477 av_log(whip, AV_LOG_ERROR, "Failed to set crypto for video send\n");
478 goto end;
479 }
480
482 if (ret < 0) {
483 av_log(whip, AV_LOG_ERROR, "Failed to set crypto for video rtx send\n");
484 goto end;
485 }
486
488 if (ret < 0) {
489 av_log(whip, AV_LOG_ERROR, "Failed to set crypto for rtcp send\n");
490 goto end;
491 }
492
493 /* Setup SRTP context for incoming packets */
495 if (ret < 0) {
496 av_log(whip, AV_LOG_ERROR, "Failed to set crypto for recv\n");
497 goto end;
498 }
499
503 av_log(whip, AV_LOG_VERBOSE, "SRTP setup done, state=%d, suite=%s, key=%dB, elapsed=%.2fms\n",
506
507end:
508 return ret;
509}
510
511static int rtp_history_store(WHIPContext *whip, const uint8_t *buf, int size)
512{
513 RTCContext *rtc = &whip->rtc;
514 uint16_t seq = AV_RB16(buf + 2);
515 uint32_t pos = ((uint32_t)seq - (uint32_t)whip->video_first_seq) % (uint32_t)whip->hist_sz;
516 RtpHistoryItem *it = &whip->hist[pos];
518 return AVERROR_INVALIDDATA;
519 memcpy(it->buf, buf, size);
520 it->size = size;
521 it->seq = seq;
522
523 whip->hist_head = ++pos;
524 return 0;
525}
526
527static const RtpHistoryItem *rtp_history_find(WHIPContext *whip, uint16_t seq)
528{
529 uint32_t pos = ((uint32_t)seq - (uint32_t)whip->video_first_seq) % (uint32_t)whip->hist_sz;
530 const RtpHistoryItem *it = &whip->hist[pos];
531 return it->seq == seq ? it : NULL;
532}
533
534/**
535 * Callback triggered by the RTP muxer when it creates and sends out an RTP packet.
536 *
537 * This function modifies the video STAP packet, removing the markers, and updating the
538 * NRI of the first NALU. Additionally, it uses the corresponding SRTP context to encrypt
539 * the RTP packet, where the video packet is handled by the video SRTP context.
540 */
541static int on_rtp_write_packet(void *opaque, const uint8_t *buf, int buf_size)
542{
543 int ret, cipher_size, is_rtcp, is_video;
544 uint8_t payload_type;
545 AVFormatContext *s = opaque;
546 WHIPContext *whip = s->priv_data;
547 RTCContext *rtc = &whip->rtc;
548 SRTPContext *srtp;
549
550 /* Ignore if not RTP or RTCP packet. */
551 if (!ff_rtc_media_is_rtp_rtcp(buf, buf_size))
552 return 0;
553
554 /* Only support audio, video and rtcp. */
555 is_rtcp = ff_rtc_media_is_rtcp(buf, buf_size);
556 payload_type = buf[1] & 0x7f;
557 is_video = payload_type == whip->video_payload_type;
558 if (!is_rtcp && payload_type != whip->video_payload_type && payload_type != whip->audio_payload_type)
559 return 0;
560
561 /* Get the corresponding SRTP context. */
562 srtp = is_rtcp ? &whip->srtp_rtcp_send : (is_video? &whip->srtp_video_send : &whip->srtp_audio_send);
563
564 /* Encrypt by SRTP and send out. */
565 cipher_size = ff_srtp_encrypt(srtp, buf, buf_size, rtc->buf, sizeof(rtc->buf));
566 if (cipher_size <= 0 || cipher_size < buf_size) {
567 av_log(whip, AV_LOG_WARNING, "Failed to encrypt packet=%dB, cipher=%dB\n", buf_size, cipher_size);
568 return 0;
569 }
570
571 if (is_video) {
572 ret = rtp_history_store(whip, buf, buf_size);
573 if (ret < 0)
574 return ret;
575 }
576
577 ret = ffurl_write(rtc->udp, rtc->buf, cipher_size);
578 if (ret < 0) {
579 av_log(whip, AV_LOG_ERROR, "Failed to write packet=%dB, ret=%d\n", cipher_size, ret);
580 return ret;
581 }
582
583 return ret;
584}
585
586/**
587 * Creates dedicated RTP muxers for each stream in the AVFormatContext to build RTP
588 * packets from the encoded frames.
589 *
590 * The corresponding SRTP context is utilized to encrypt each stream's RTP packets. For
591 * example, a video SRTP context is used for the video stream. Additionally, the
592 * "on_rtp_write_packet" callback function is set as the write function for each RTP
593 * muxer to send out encrypted RTP packets.
594 *
595 * @return 0 if OK, AVERROR_xxx on error
596 */
598{
599 int ret, i, is_video, buffer_size, max_packet_size;
600 AVFormatContext *rtp_ctx = NULL;
602 uint8_t *buffer = NULL;
603 WHIPContext *whip = s->priv_data;
604 RTCContext *rtc = &whip->rtc;
606
607
608 /* The UDP buffer size, may greater than MTU. */
609 buffer_size = RTC_MAX_UDP_BUFFER_SIZE;
610 /* The RTP payload max size. Reserved some bytes for SRTP checksum and padding. */
611 max_packet_size = rtc->pkt_size - RTC_DTLS_SRTP_CHECKSUM_LEN;
612
613 for (i = 0; i < s->nb_streams; i++) {
614 rtp_ctx = avformat_alloc_context();
615 if (!rtp_ctx) {
616 ret = AVERROR(ENOMEM);
617 goto end;
618 }
619
621 rtp_ctx->oformat = &ff_rtp_muxer.p;
622 if (!avformat_new_stream(rtp_ctx, NULL)) {
623 ret = AVERROR(ENOMEM);
624 goto end;
625 }
626 /* Pass the interrupt callback on */
627 rtp_ctx->interrupt_callback = s->interrupt_callback;
628 /* Copy the max delay setting; the rtp muxer reads this. */
629 rtp_ctx->max_delay = s->max_delay;
630 /* Copy other stream parameters. */
631 rtp_ctx->streams[0]->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
632 rtp_ctx->flags |= s->flags & AVFMT_FLAG_BITEXACT;
633 rtp_ctx->strict_std_compliance = s->strict_std_compliance;
634
635 /* Set the synchronized start time. */
636 rtp_ctx->start_time_realtime = s->start_time_realtime;
637
638 avcodec_parameters_copy(rtp_ctx->streams[0]->codecpar, s->streams[i]->codecpar);
639 rtp_ctx->streams[0]->time_base = s->streams[i]->time_base;
640
641 /**
642 * For H.264, consistently utilize the annexb format through the Bitstream Filter (BSF);
643 * therefore, we deactivate the extradata detection for the RTP muxer.
644 */
645 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_H264) {
646 av_freep(&rtp_ctx->streams[0]->codecpar->extradata);
647 rtp_ctx->streams[0]->codecpar->extradata_size = 0;
648 }
649
650 buffer = av_malloc(buffer_size);
651 if (!buffer) {
652 ret = AVERROR(ENOMEM);
653 goto end;
654 }
655
656 rtp_ctx->pb = avio_alloc_context(buffer, buffer_size, 1, s, NULL, on_rtp_write_packet, NULL);
657 if (!rtp_ctx->pb) {
658 ret = AVERROR(ENOMEM);
659 goto end;
660 }
661 rtp_ctx->pb->max_packet_size = max_packet_size;
662 rtp_ctx->pb->av_class = &ff_avio_class;
663
664 is_video = s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
665 av_dict_set_int(&opts, "payload_type", is_video ? whip->video_payload_type : whip->audio_payload_type, 0);
666 av_dict_set_int(&opts, "ssrc", is_video ? whip->video_ssrc : whip->audio_ssrc, 0);
667 av_dict_set_int(&opts, "seq", is_video ? whip->video_first_seq : whip->audio_first_seq, 0);
668
669 ret = avformat_write_header(rtp_ctx, &opts);
670 if (ret < 0) {
671 av_log(whip, AV_LOG_ERROR, "Failed to write rtp header\n");
672 goto end;
673 }
674
675 ff_format_set_url(rtp_ctx, av_strdup(s->url));
676 s->streams[i]->time_base = rtp_ctx->streams[0]->time_base;
677 s->streams[i]->priv_data = rtp_ctx;
678 rtp_ctx = NULL;
679 }
680
681 if (rtc->state < RTC_STATE_READY)
682 rtc->state = RTC_STATE_READY;
683 av_log(whip, AV_LOG_INFO, "Muxer state=%d, buffer_size=%d, max_packet_size=%d, "
684 "elapsed=%.2fms(init:%.2f,offer:%.2f,answer:%.2f,udp:%.2f,ice:%.2f,dtls:%.2f,srtp:%.2f)\n",
685 rtc->state, buffer_size, max_packet_size, RTC_ELAPSED(rtc->starttime, av_gettime_relative()),
686 RTC_ELAPSED(rtc->starttime, rtc->init_time),
687 RTC_ELAPSED(rtc->init_time, rtc->offer_time),
689 RTC_ELAPSED(rtc->answer_time, rtc->udp_time),
690 RTC_ELAPSED(rtc->udp_time, rtc->ice_time),
691 RTC_ELAPSED(rtc->ice_time, rtc->dtls_time),
692 RTC_ELAPSED(rtc->dtls_time, rtc->srtp_time));
693
694end:
695 if (rtp_ctx) {
696 if (!rtp_ctx->pb)
698 avio_context_free(&rtp_ctx->pb);
699 }
700 avformat_free_context(rtp_ctx);
702 return ret;
703}
704
705/**
706 * Since the h264_mp4toannexb filter only processes the MP4 ISOM format and bypasses
707 * the annexb format, it is necessary to manually insert encoder metadata before each
708 * IDR when dealing with annexb format packets. For instance, in the case of H.264,
709 * we must insert SPS and PPS before the IDR frame.
710 */
712{
713 int ret = 0;
714 AVPacket *in = NULL;
715 AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
716 uint32_t nal_size = 0, out_size = par ? par->extradata_size : 0;
717 uint8_t unit_type, sps_seen = 0, pps_seen = 0, idr_seen = 0, *out;
718 const uint8_t *buf, *buf_end, *r1;
719
720 if (!par || !par->extradata || par->extradata_size <= 0)
721 return ret;
722
723 /* Discover NALU type from packet. */
724 buf_end = pkt->data + pkt->size;
725 for (buf = ff_nal_find_startcode(pkt->data, buf_end); buf < buf_end; buf += nal_size) {
726 while (!*(buf++));
727 r1 = ff_nal_find_startcode(buf, buf_end);
728 if ((nal_size = r1 - buf) > 0) {
729 unit_type = *buf & 0x1f;
730 if (unit_type == H264_NAL_SPS) {
731 sps_seen = 1;
732 } else if (unit_type == H264_NAL_PPS) {
733 pps_seen = 1;
734 } else if (unit_type == H264_NAL_IDR_SLICE) {
735 idr_seen = 1;
736 }
737
738 out_size += 3 + nal_size;
739 }
740 }
741
742 if (!idr_seen || (sps_seen && pps_seen))
743 return ret;
744
745 /* See av_bsf_send_packet */
746 in = av_packet_alloc();
747 if (!in)
748 return AVERROR(ENOMEM);
749
751 if (ret < 0)
752 goto fail;
753
755
756 /* Create a new packet with sps/pps inserted. */
758 if (ret < 0)
759 goto fail;
760
762 if (ret < 0)
763 goto fail;
764
765 memcpy(pkt->data, par->extradata, par->extradata_size);
766 out = pkt->data + par->extradata_size;
767 buf_end = in->data + in->size;
768 for (buf = ff_nal_find_startcode(in->data, buf_end); buf < buf_end; buf += nal_size) {
769 while (!*(buf++));
770 r1 = ff_nal_find_startcode(buf, buf_end);
771 if ((nal_size = r1 - buf) > 0) {
772 AV_WB24(out, 0x00001);
773 memcpy(out + 3, buf, nal_size);
774 out += 3 + nal_size;
775 }
776 }
777
778fail:
779 if (ret < 0)
781 av_packet_free(&in);
782
783 return ret;
784}
785
787{
788 int ret;
789 WHIPContext *whip = s->priv_data;
790 RTCContext *rtc = &whip->rtc;
791
792 if ((ret = initialize(s)) < 0)
793 goto end;
794
795 if ((ret = parse_codec(s)) < 0)
796 goto end;
797
798 if ((ret = generate_sdp_offer(s)) < 0)
799 goto end;
800
801 if ((ret = ff_rtc_exchange_sdp(rtc)) < 0)
802 goto end;
803
804 if ((ret = ff_rtc_parse_answer(rtc)) < 0)
805 goto end;
806
807 if ((ret = ff_rtc_udp_connect(rtc)) < 0)
808 goto end;
809
810 if ((ret = ff_rtc_ice_dtls_handshake(rtc)) < 0)
811 goto end;
812
813 if ((ret = setup_srtp(s)) < 0)
814 goto end;
815
816 if ((ret = create_rtp_muxer(s)) < 0)
817 goto end;
818
819end:
820 if (ret < 0)
821 rtc->state = RTC_STATE_FAILED;
822 return ret;
823}
824
825/**
826 * See https://datatracker.ietf.org/doc/html/rfc4588#section-4
827 * Create RTX packet and send it out.
828 */
829static void handle_rtx_packet(AVFormatContext *s, uint16_t seq)
830{
831 int ret = -1;
832 WHIPContext *whip = s->priv_data;
833 RTCContext *rtc = &whip->rtc;
834 uint8_t *ori_buf, rtx_buf[RTC_MAX_UDP_BUFFER_SIZE] = { 0 };
835 int ori_size, rtx_size, cipher_size;
836 uint16_t ori_seq;
837 const RtpHistoryItem *it = rtp_history_find(whip, seq);
838 uint16_t latest_seq = whip->hist[(whip->hist_head - 1 + whip->hist_sz) % whip->hist_sz].seq;
839
840 if (!it) {
841 av_log(whip, AV_LOG_DEBUG,
842 "RTP history packet seq=%"PRIu16" not found, latest seq=%"PRIu16"\n",
843 seq, latest_seq);
844 return;
845 }
846 av_log(whip, AV_LOG_DEBUG,
847 "Found RTP history packet for RTX, seq=%"PRIu16", latest seq=%"PRIu16"\n",
848 seq, latest_seq);
849
850 ori_buf = it->buf;
851 ori_size = it->size;
852
853 /* A valid RTP packet must have at least a RTP header. */
854 if (ori_size < RTC_RTP_HEADER_SIZE) {
855 av_log(whip, AV_LOG_WARNING, "RTX history packet too small, size=%d\n", ori_size);
856 goto end;
857 }
858
859 /* RTX packet format: header + original seq (2 bytes) + payload */
860 if (ori_size + 2 > sizeof(rtx_buf)) {
861 av_log(whip, AV_LOG_WARNING, "RTX packet is too large, size=%d\n", ori_size);
862 goto end;
863 }
864
865 memcpy(rtx_buf, ori_buf, ori_size);
866 ori_seq = AV_RB16(rtx_buf + 2);
867
868 /* rewrite RTX packet header */
869 rtx_buf[1] = (rtx_buf[1] & 0x80) | whip->video_rtx_payload_type; /* keep M bit */
870 AV_WB16(rtx_buf + 2, whip->video_rtx_seq++);
871 AV_WB32(rtx_buf + 8, whip->video_rtx_ssrc);
872
873 /* shift payload 2 bytes to write the original seq number */
874 memmove(rtx_buf + 12 + 2, rtx_buf + 12, ori_size - 12);
875 AV_WB16(rtx_buf + 12, ori_seq);
876
877 rtx_size = ori_size + 2;
878 cipher_size = ff_srtp_encrypt(&whip->srtp_video_rtx_send,
879 rtx_buf, rtx_size,
880 rtc->buf, sizeof(rtc->buf));
881 if (cipher_size <= 0) {
883 "Failed to encrypt RTX packet, size=%d, cipher_size=%d\n",
884 rtx_size, cipher_size);
885 goto end;
886 }
887 ret = ffurl_write(rtc->udp, rtc->buf, cipher_size);
888end:
889 if (ret < 0)
890 av_log(whip, AV_LOG_WARNING, "Failed to send RTX packet, skip this one\n");
891}
892
894{
895 int ret, i = 0;
896 WHIPContext *whip = s->priv_data;
897 RTCContext *rtc = &whip->rtc;
898 uint8_t *buf = NULL;
899 int rtcp_len, srtcp_len, header_len = 12/*RFC 4585 6.1*/;
900 uint32_t ssrc;
901
902 /**
903 * Refer to RFC 3550 6.4.1
904 * The length of this RTCP packet in 32 bit words minus one,
905 * including the header and any padding.
906 */
907 rtcp_len = (AV_RB16(&rtc->buf[2]) + 1) * 4;
908 if (rtcp_len <= header_len) {
909 av_log(whip, AV_LOG_WARNING, "NACK packet is broken, size: %d\n", rtcp_len);
910 goto error;
911 }
912 /* SRTCP index(4 bytes) + HMAC(SRTP_ARS128_CM_SHA1_80) 10bytes */
913 srtcp_len = rtcp_len + 4 + 10;
914 if (srtcp_len != size) {
915 av_log(whip, AV_LOG_WARNING, "NACK packet size not match, srtcp_len:%d, size:%d\n", srtcp_len, size);
916 goto error;
917 }
918 buf = av_memdup(rtc->buf, srtcp_len);
919 if (!buf)
920 goto error;
921 if ((ret = ff_srtp_decrypt(&whip->srtp_recv, buf, &srtcp_len)) < 0) {
922 av_log(whip, AV_LOG_WARNING, "NACK packet decrypt failed: %d\n", ret);
923 goto error;
924 }
925 ssrc = AV_RB32(&buf[8]);
926 if (ssrc != whip->video_ssrc) {
927 av_log(whip, AV_LOG_DEBUG,
928 "NACK packet SSRC: %"PRIu32" not match with video track SSRC: %"PRIu32"\n",
929 ssrc, whip->video_ssrc);
930 goto end;
931 }
932 while (header_len + i + 4 <= rtcp_len) {
933 /**
934 * See https://datatracker.ietf.org/doc/html/rfc4585#section-6.1
935 * Handle multi NACKs in bundled packet.
936 */
937 uint16_t pid = AV_RB16(&buf[12 + i]);
938 uint16_t blp = AV_RB16(&buf[14 + i]);
939
940 handle_rtx_packet(s, pid);
941 /* retransmit pid + any bit set in blp */
942 for (int bit = 0; bit < 16; bit++) {
943 uint16_t seq = pid + bit + 1;
944 if (!blp)
945 break;
946 if (!(blp & (1 << bit)))
947 continue;
948
949 handle_rtx_packet(s, seq);
950 }
951 i += 4;
952 }
953 goto end;
954error:
955 av_log(whip, AV_LOG_WARNING, "Failed to handle NACK and RTX, Skip...\n");
956end:
957 av_freep(&buf);
958}
959
961{
962 int ret;
963 WHIPContext *whip = s->priv_data;
964 RTCContext *rtc = &whip->rtc;
965 AVStream *st = s->streams[pkt->stream_index];
966 AVFormatContext *rtp_ctx = st->priv_data;
968 if ((ret = ff_rtc_ice_check_and_send_consent(rtc, now)) < 0)
969 goto end;
970
971 /**
972 * Receive packets from the server such as ICE binding requests, DTLS messages,
973 * and RTCP like PLI requests, then respond to them.
974 */
975 ret = ffurl_read(rtc->udp, rtc->buf, sizeof(rtc->buf));
976 if (ret < 0) {
977 if (ret == AVERROR(EAGAIN))
978 goto write_packet;
979 av_log(whip, AV_LOG_ERROR, "Failed to read from UDP socket\n");
980 goto end;
981 }
982 if (!ret) {
983 av_log(whip, AV_LOG_ERROR, "Receive EOF from UDP socket\n");
984 goto end;
985 }
987 if (ff_is_dtls_packet(rtc->buf, ret)) {
988 if ((ret = ffurl_write(rtc->dtls_uc, rtc->buf, ret)) < 0) {
989 av_log(whip, AV_LOG_ERROR, "Failed to handle DTLS message\n");
990 goto end;
991 }
992 }
993 if (ff_rtc_media_is_rtcp(rtc->buf, ret)) {
994 uint8_t fmt = rtc->buf[0] & 0x1f;
995 uint8_t pt = rtc->buf[1];
996 /**
997 * Handle RTCP NACK packet
998 * Refer to RFC 4585 6.2.1
999 * The Generic NACK message is identified by PT=RTPFB and FMT=1
1000 */
1001 if (pt != RTCP_RTPFB)
1002 goto write_packet;
1003 if (fmt == 1)
1005 }
1007 now = av_gettime_relative();
1008 if ((ret = ff_rtc_ice_check_consent(rtc, now)) < 0)
1009 goto end;
1011 if ((ret = h264_annexb_insert_sps_pps(s, pkt)) < 0) {
1012 av_log(whip, AV_LOG_ERROR, "Failed to insert SPS/PPS before IDR\n");
1013 goto end;
1014 }
1015 }
1016
1017 ret = ff_write_chained(rtp_ctx, 0, pkt, s, 0);
1018 if (ret < 0) {
1019 if (ret == AVERROR(EINVAL)) {
1020 av_log(whip, AV_LOG_WARNING, "Ignore failed to write packet=%dB, ret=%d\n", pkt->size, ret);
1021 ret = 0;
1022 } else if (ret == AVERROR(EAGAIN)) {
1023 av_log(whip, AV_LOG_ERROR, "UDP send blocked, please increase the buffer via -ts_buffer_size\n");
1024 } else
1025 av_log(whip, AV_LOG_ERROR, "Failed to write packet, size=%d, ret=%d\n", pkt->size, ret);
1026 goto end;
1027 }
1028
1029end:
1030 if (ret < 0)
1031 rtc->state = RTC_STATE_FAILED;
1032 return ret;
1033}
1034
1036{
1037 int i, ret;
1038 WHIPContext *whip = s->priv_data;
1039 RTCContext *rtc = &whip->rtc;
1040
1042 if (ret < 0)
1043 av_log(whip, AV_LOG_WARNING, "Failed to dispose resource, ret=%d\n", ret);
1044
1045 for (i = 0; i < s->nb_streams; i++) {
1046 AVFormatContext* rtp_ctx = s->streams[i]->priv_data;
1047 if (!rtp_ctx)
1048 continue;
1049
1050 av_write_trailer(rtp_ctx);
1051 /**
1052 * Keep in mind that it is necessary to free the buffer of pb since we allocate
1053 * it and pass it to pb using avio_alloc_context, while avio_context_free does
1054 * not perform this action.
1055 */
1056 av_freep(&rtp_ctx->pb->buffer);
1057 avio_context_free(&rtp_ctx->pb);
1058 avformat_free_context(rtp_ctx);
1059 s->streams[i]->priv_data = NULL;
1060 }
1061
1062 av_freep(&whip->hist_pool);
1063 av_freep(&whip->hist);
1068 ff_srtp_free(&whip->srtp_recv);
1069 ff_rtc_deinit(rtc);
1070}
1071
1073{
1074 int ret = 1, extradata_isom = 0;
1075 uint8_t *b = pkt->data;
1076 WHIPContext *whip = s->priv_data;
1077
1078 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
1079 extradata_isom = st->codecpar->extradata_size > 0 && st->codecpar->extradata[0] == 1;
1080 if (pkt->size >= 5 && AV_RB32(b) != 0x0000001 && (AV_RB24(b) != 0x000001 || extradata_isom)) {
1081 ret = ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL);
1082 av_log(whip, AV_LOG_VERBOSE, "Enable BSF h264_mp4toannexb, packet=[%x %x %x %x %x ...], extradata_isom=%d\n",
1083 b[0], b[1], b[2], b[3], b[4], extradata_isom);
1084 } else
1086 }
1087
1088 return ret;
1089}
1090
1091#define OFFSET(x) offsetof(WHIPContext, x)
1092#define ENC AV_OPT_FLAG_ENCODING_PARAM
1093static const AVOption options[] = {
1095 { "whip_flags", "Set flags affecting WHIP connection behavior", OFFSET(rtc.flags), AV_OPT_TYPE_FLAGS, { .i64 = 0}, 0, UINT_MAX, ENC, .unit = "flags" },
1096 { "rtp_history", "The number of RTP history items to store", OFFSET(hist_sz), AV_OPT_TYPE_INT, { .i64 = WHIP_RTP_HISTORY_DEFAULT }, WHIP_RTP_HISTORY_MIN, WHIP_RTP_HISTORY_MAX, ENC },
1097 { NULL },
1098};
1099
1101 .class_name = "WHIP muxer",
1102 .item_name = av_default_item_name,
1103 .option = options,
1104 .version = LIBAVUTIL_VERSION_INT,
1105};
1106
1108 .p.name = "whip",
1109 .p.long_name = NULL_IF_CONFIG_SMALL("WHIP(WebRTC-HTTP ingestion protocol) muxer"),
1110 .p.audio_codec = AV_CODEC_ID_OPUS,
1111 .p.video_codec = AV_CODEC_ID_H264,
1112 .p.subtitle_codec = AV_CODEC_ID_NONE,
1114 .p.priv_class = &whip_muxer_class,
1116 .priv_data_size = sizeof(WHIPContext),
1117 .init = whip_init,
1121};
const FFOutputFormat ff_rtp_muxer
Definition rtpenc.c:768
const FFOutputFormat ff_whip_muxer
Definition whip.c:1107
static FILE * out
static int out_size
static AVDictionary * opts
#define EXTERN
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_unreachable(msg)
Asserts that are used as compiler optimization hints depending upon ASSERT_LEVEL and NBDEBUG.
Definition avassert.h:109
int ff_avc_decode_sps(H264SPS *sps, const uint8_t *buf, int buf_size)
Definition avc.c:196
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition avformat.c:954
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition avformat.h:1570
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition avformat.h:490
#define AVFMT_EXPERIMENTAL
The muxer/demuxer is experimental and should be used with caution.
Definition avformat.h:497
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition avformat.h:499
const AVClass ff_avio_class
Definition avio.c:104
AVIOContext * avio_alloc_context(unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, const uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Allocate and initialize an AVIOContext for buffered I/O.
Definition aviobuf.c:109
void avio_context_free(AVIOContext **s)
Free the supplied IO context and everything associated with it.
Definition aviobuf.c:126
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:649
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:121
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define ENC
Definition caca.c:198
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
static int FUNC sps(CodedBitstreamContext *ctx, RWContext *rw, H264RawSPS *current)
#define bit(string, value)
Definition cbs_mpeg2.c:56
#define s(width, name)
Definition cbs_vp9.c:198
static void deinit(AVFormatContext *s)
Definition chromaprint.c:53
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Definition codec_par.c:107
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define AV_PROFILE_UNKNOWN
Definition defs.h:65
#define AV_PROFILE_H264_CONSTRAINED
Definition defs.h:121
#define AV_LEVEL_UNKNOWN
Definition defs.h:225
#define AV_PROFILE_H264_INTRA
Definition defs.h:122
static AVPacket * pkt
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:203
int ret
Definition ffplay.c:391
#define fail
Definition test.h:479
@ AV_OPT_TYPE_FLAGS
Underlying C type is unsigned int.
Definition opt.h:254
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_CODEC_ID_H264
Definition codec_id.h:77
@ AV_CODEC_ID_NONE
Definition codec_id.h:48
@ AV_CODEC_ID_OPUS
Definition codec_id.h:519
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:435
int av_packet_make_refcounted(AVPacket *pkt)
Ensure the data described by a given packet is reference counted.
Definition packet.c:498
void av_packet_move_ref(AVPacket *dst, AVPacket *src)
Move every field in src to dst and reset src.
Definition packet.c:492
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
int av_packet_copy_props(AVPacket *dst, const AVPacket *src)
Copy only "properties" fields from src to dst.
Definition packet.c:398
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
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition options.c:165
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:165
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition mux.c:512
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition mux.c:1283
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition dict.c:180
#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_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#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_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition mem.c:408
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
H.264 common definitions.
@ H264_NAL_PPS
Definition h264.h:42
@ H264_NAL_SPS
Definition h264.h:41
@ H264_NAL_IDR_SLICE
Definition h264.h:39
int profile_idc
Definition h264_levels.c:53
#define r
Definition input.c:42
#define b
Definition input.c:43
#define AV_WB24(p, d)
#define AV_WB32(p, v)
#define AV_RB32(p)
#define AV_WB16(p, v)
#define AV_RB24(x)
#define AV_RB16(p)
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition lfg.h:53
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)
Write a packet to another muxer than the one the user originally intended.
Definition mux.c:1382
static int check_bitstream(AVFormatContext *s, FFStream *sti, AVPacket *pkt)
Definition mux.c:1101
int ff_stream_add_bitstream_filter(AVStream *st, const char *name, const char *args)
Add a bitstream filter to a stream.
Definition mux.c:1339
#define av_cold
Definition attributes.h:117
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
#define FF_OFMT_FLAG_MAX_ONE_OF_EACH
If this flag is set, it indicates that for each codec type whose corresponding default codec (i....
Definition mux.h:50
#define FF_OFMT_FLAG_ONLY_DEFAULT_CODECS
If this flag is set, then the only permitted audio/video/subtitle codec ids are AVOutputFormat....
Definition mux.h:59
const uint8_t * ff_nal_find_startcode(const uint8_t *p, const uint8_t *end)
Definition nal.c:68
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
void ff_rtc_ice_check_and_update_consent(RTCContext *rtc, const uint8_t *buf, int size)
Definition rtc.c:980
int ff_rtc_parse_answer(RTCContext *rtc)
Parses the ICE ufrag, pwd, and candidates from the SDP answer.
Definition rtc.c:330
av_cold int ff_rtc_initialize(RTCContext *rtc)
Definition rtc.c:165
int ff_rtc_media_is_rtcp(const uint8_t *b, int size)
Definition rtc.c:651
int ff_rtc_ice_dtls_handshake(RTCContext *rtc)
Definition rtc.c:737
int ff_rtc_ice_check_consent(RTCContext *rtc, int64_t now)
Definition rtc.c:988
int ff_rtc_srtp_export_keys(RTCContext *rtc)
Definition rtc.c:846
int ff_rtc_dispose_session(RTCContext *rtc)
RTC is connectionless, for it's based on UDP, so it check whether sesison is timeout.
Definition rtc.c:899
int ff_rtc_media_is_rtp_rtcp(const uint8_t *b, int size)
In RTP packets, the first byte is represented as 0b10xxxxxx, where the initial two bits (0b10) indica...
Definition rtc.c:645
av_cold void ff_rtc_deinit(RTCContext *rtc)
Definition rtc.c:1000
int ff_rtc_exchange_sdp(RTCContext *rtc)
Exchange SDP offer with WebRTC peer to get the answer.
Definition rtc.c:203
int ff_rtc_ice_check_and_send_consent(RTCContext *rtc, int64_t now)
Refer to RFC 7675 Periodically send Consent Freshness STUN Binding Request.
Definition rtc.c:956
int ff_rtc_udp_connect(RTCContext *rtc)
To establish a connection with the UDP server, we utilize ICE-LITE in a Client-Server mode.
Definition rtc.c:700
#define RTC_MAX_UDP_BUFFER_SIZE
Maximum size of the buffer for sending and receiving UDP packets.
Definition rtc.h:75
#define RTC_MAX_SDP_SIZE
Maximum size limit of a Session Description Protocol (SDP), be it an offer or answer.
Definition rtc.h:39
#define RTC_DTLS_SRTP_SALT_LEN
Definition rtc.h:48
#define RTC_SRTP_SUITE
The profile for OpenSSL's SRTP is SRTP_AES128_CM_SHA1_80, see ssl/d1_srtp.c.
Definition rtc.h:56
#define RTC_RTP_HEADER_SIZE
The RTP header is 12 bytes long, comprising the Version(1B), PT(1B), SequenceNumber(2B),...
Definition rtc.h:82
#define RTC_OPTIONS(pstruct, field, flag)
Definition rtc.h:245
#define RTC_DTLS_SRTP_CHECKSUM_LEN
The maximum size of the Secure Real-time Transport Protocol (SRTP) HMAC checksum and padding that is ...
Definition rtc.h:64
@ RTC_DTLS_ACTIVE
Definition rtc.h:118
#define RTC_DTLS_SRTP_KEY_LEN
The size of the Secure Real-time Transport Protocol (SRTP) master key material that is exported by Se...
Definition rtc.h:47
#define RTC_ELAPSED(starttime, endtime)
Definition rtc.h:85
@ RTC_STATE_OFFER
Definition rtc.h:93
@ RTC_STATE_FAILED
Definition rtc.h:114
@ RTC_STATE_SRTP_FINISHED
Definition rtc.h:110
@ RTC_STATE_READY
Definition rtc.h:112
int pt
Definition rtp.c:35
@ RTCP_RTPFB
Definition rtp.h:104
unsigned int pos
Definition spdifenc.c:431
int ff_srtp_encrypt(struct SRTPContext *s, const uint8_t *in, int len, uint8_t *out, int outlen)
Definition srtp.c:239
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
Accelerated start code search function for start codes common to MPEG-1/2/4 video,...
const uint8_t * avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state)
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
int profile
Codec-specific bitstream restrictions that the stream conforms to.
Definition codec_par.h:135
int video_delay
Number of delayed frames.
Definition codec_par.h:200
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
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:1401
AVIOContext * pb
I/O context.
Definition avformat.h:1443
int flags
Flags modifying the (de)muxer behaviour.
Definition avformat.h:1553
const struct AVOutputFormat * oformat
The output container format.
Definition avformat.h:1420
int strict_std_compliance
Allow non-standard and experimental extension.
Definition avformat.h:1776
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition avformat.h:1687
int64_t start_time_realtime
Start time of the stream in real world time, in microseconds since the Unix epoch (00:00 1st January ...
Definition avformat.h:1662
AVStream ** streams
A list of all streams in the file.
Definition avformat.h:1469
const AVClass * av_class
A class for private options.
Definition avio.h:173
unsigned char * buffer
Start of the buffer.
Definition avio.h:225
int max_packet_size
Definition avio.h:241
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:587
int size
Definition packet.h:611
uint8_t * data
Definition packet.h:610
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition avformat.h:846
void * priv_data
Definition avformat.h:793
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
Definition avc.h:32
char srtp_send_key[RTC_SRTP_KEY_SIZE]
Definition rtc.h:188
int64_t init_time
Definition rtc.h:162
int64_t dtls_time
Definition rtc.h:167
int pkt_size
The size of RTP packet, should generally be set to MTU.
Definition rtc.h:207
uint32_t flags
Definition rtc.h:124
char buf[RTC_MAX_UDP_BUFFER_SIZE]
Definition rtc.h:197
int64_t srtp_time
Definition rtc.h:168
AVLFG rnd
Definition rtc.h:129
char * dtls_fingerprint
Definition rtc.h:176
char ice_ufrag_local[9]
Definition rtc.h:132
int64_t ice_time
Definition rtc.h:166
URLContext * udp
Definition rtc.h:195
char ice_pwd_local[33]
Definition rtc.h:133
int64_t starttime
Definition rtc.h:161
char * sdp_offer
This is the SDP offer generated by the local peer based on the codec parameters, DTLS,...
Definition rtc.h:139
int64_t offer_time
Definition rtc.h:163
int64_t answer_time
Definition rtc.h:164
int64_t udp_time
Definition rtc.h:165
enum RTCState state
Definition rtc.h:126
char srtp_recv_key[RTC_SRTP_KEY_SIZE]
Definition rtc.h:189
URLContext * dtls_uc
Definition rtc.h:192
AVFormatContext * ctx
Definition rtc.h:122
uint16_t seq
Definition whip.c:67
uint8_t * buf
Definition whip.c:69
int flags
Definition url.h:40
RTCContext rtc
Definition whip.c:74
SRTPContext srtp_rtcp_send
Definition whip.c:105
AVCodecParameters * audio_par
Definition whip.c:77
uint16_t audio_first_seq
Definition whip.c:92
uint8_t video_payload_type
Definition whip.c:98
uint32_t video_ssrc
Definition whip.c:89
SRTPContext srtp_recv
Definition whip.c:107
uint8_t video_rtx_payload_type
Definition whip.c:99
uint32_t audio_ssrc
Definition whip.c:88
AVClass * av_class
Definition whip.c:73
int hist_head
Definition whip.c:112
uint16_t video_rtx_seq
Definition whip.c:95
AVCodecParameters * video_par
Definition whip.c:78
SRTPContext srtp_audio_send
Definition whip.c:102
SRTPContext srtp_video_send
Definition whip.c:103
RtpHistoryItem * hist
Definition whip.c:110
int h264_annexb_insert_sps_pps
The h264_mp4toannexb Bitstream Filter (BSF) bypasses the AnnexB packet; therefore,...
Definition whip.c:85
int hist_sz
Definition whip.c:109
SRTPContext srtp_video_rtx_send
Definition whip.c:104
uint8_t * hist_pool
Definition whip.c:111
uint32_t video_rtx_ssrc
Definition whip.c:90
uint16_t video_first_seq
Definition whip.c:93
uint8_t audio_payload_type
Definition whip.c:97
uint8_t level
Definition svq3.c:208
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
static char buffer[20]
Definition seek.c:33
static struct @232240247175332074307271266321204261331170211232 state
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
int ff_is_dtls_packet(const uint8_t *buf, int size)
Whether the packet is a DTLS packet, as defined by RFC 5764 Section 5.1.2.
Definition tls.c:167
int size
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 int ffurl_read(URLContext *h, uint8_t *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf.
Definition url.h:184
static int rtp_history_store(WHIPContext *whip, const uint8_t *buf, int size)
Definition whip.c:511
static int parse_codec(AVFormatContext *s)
Parses video SPS/PPS from the extradata of codecpar and checks the codec.
Definition whip.c:229
static void handle_nack_rtx(AVFormatContext *s, int size)
Definition whip.c:893
static const RtpHistoryItem * rtp_history_find(WHIPContext *whip, uint16_t seq)
Definition whip.c:527
#define WHIP_RTP_PAYLOAD_TYPE_OPUS
Definition whip.c:45
static int whip_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition whip.c:960
static int generate_sdp_offer(AVFormatContext *s)
Generate SDP offer according to the codec parameters, DTLS and ICE information.
Definition whip.c:289
static int on_rtp_write_packet(void *opaque, const uint8_t *buf, int buf_size)
Callback triggered by the RTP muxer when it creates and sends out an RTP packet.
Definition whip.c:541
static int whip_check_bitstream(AVFormatContext *s, AVStream *st, const AVPacket *pkt)
Definition whip.c:1072
#define WHIP_SDP_CREATOR_IP
Definition whip.c:53
static av_cold int whip_init(AVFormatContext *s)
Definition whip.c:786
static av_cold int initialize(AVFormatContext *s)
Initialize and check the options for the WebRTC muxer.
Definition whip.c:118
#define WHIP_RTP_PAYLOAD_TYPE_VIDEO_RTX
Definition whip.c:46
#define WHIP_SDP_SESSION_ID
In the case of ICE-LITE, these fields are not used; instead, they are defined as constant values.
Definition whip.c:52
#define WHIP_RTP_HISTORY_MIN
RTP history packet size.
Definition whip.c:62
#define WHIP_RTP_PAYLOAD_TYPE_H264
Definition whip.c:44
#define WHIP_RTP_HISTORY_DEFAULT
Definition whip.c:63
static int setup_srtp(AVFormatContext *s)
Establish the SRTP context using the keying material exported from DTLS.
Definition whip.c:458
static av_cold void whip_deinit(AVFormatContext *s)
Definition whip.c:1035
#define WHIP_RTP_HISTORY_MAX
Definition whip.c:64
#define OFFSET(x)
Definition whip.c:1091
static int h264_annexb_insert_sps_pps(AVFormatContext *s, AVPacket *pkt)
Since the h264_mp4toannexb filter only processes the MP4 ISOM format and bypasses the annexb format,...
Definition whip.c:711
static void handle_rtx_packet(AVFormatContext *s, uint16_t seq)
See https://datatracker.ietf.org/doc/html/rfc4588#section-4 Create RTX packet and send it out.
Definition whip.c:829
static int parse_profile_level(AVFormatContext *s, AVCodecParameters *par)
When duplicating a stream, the demuxer has already set the extradata, profile, and level of the par.
Definition whip.c:162
static const AVClass whip_muxer_class
Definition whip.c:1100
static int create_rtp_muxer(AVFormatContext *s)
Creates dedicated RTP muxers for each stream in the AVFormatContext to build RTP packets from the enc...
Definition whip.c:597