From d1f5dee18c27185fea4a8db428d7430c65948231 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 12:50:58 +0300 Subject: [PATCH] voelin-media: RTMP output for the Stream Studio through libavformat The RTMP output was a seam that refused every rtmp:// URL. Broadcast services (Twitch, YouTube, nginx-rtmp) take RTMP, so the studio could only reach the few that speak WHIP. The connection is libavformat's own rtmp:// and rtmps:// protocols, loaded at runtime with the rest of FFmpeg and never linked. Its RTMP writer takes an FLV byte stream and sends each tag as a message, so the FLV is ours (onMetaData, AVC and AAC sequence headers, a tag per frame) and no muxer struct (AVFormatContext, AVStream, codec parameters, which all moved between releases) is used: five avio functions and AVIOInterruptCB. Write errors only land in AVIOContext.error, which moved too (120 bytes in libavformat 58, 84 in 63); it is found at load by flushing a context whose write callback fails with a sentinel. Video is the studio's H.264 of one layer as encoded; other codecs are refused with the reason. Audio is the studio's Opus decoded and encoded as AAC-LC by FFmpeg's own codecs on the output's thread. The encoder's sample format has no AVOption, so AVCodecContext.sample_fmt is located from its neighbours' option offsets like hw_frames_ctx; its 1024-sample frames are a reference to the first decoded frame (FFmpeg filled in the channel layout, whose field moved) with only the leading fields pointed at our planes. The stream key comes from the URL or the token (sent as the play path) and never shows in the output's name. The first connection is made when the output is added, so a wrong address fails there; later failures are reconnected with backoff (1 s doubling to 30 s), each new connection starting at a keyframe it asks for, and the stats show why it is down. EndStream unpublishes; a dead network is cut off after three seconds. Tested against FFmpeg's own RTMP server (ffmpeg -listen 1): a studio stream through the hardware H.264 encoder and a 440 Hz tone arrives as h264 320x180 and aac 48 kHz stereo per ffprobe, starts at a keyframe, decodes, and comes back after the server is replaced; the unit tests also pass against FFmpeg 4.4.8. voelinctl studio run gets --rtmp. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/voelin-core/tests/studio.rs | 170 +++++ crates/voelin-media/Cargo.toml | 3 + crates/voelin-media/src/ffmpeg/audio.rs | 383 +++++++++++ crates/voelin-media/src/ffmpeg/avio.rs | 256 +++++++ crates/voelin-media/src/ffmpeg/layout.rs | 126 +++- crates/voelin-media/src/ffmpeg/mod.rs | 66 +- crates/voelin-media/src/ffmpeg/sys.rs | 95 ++- crates/voelin-media/src/lib.rs | 3 + crates/voelin-media/src/studio/mod.rs | 20 +- crates/voelin-media/src/studio/output/flv.rs | 203 ++++++ crates/voelin-media/src/studio/output/mod.rs | 10 +- crates/voelin-media/src/studio/output/rtmp.rs | 647 +++++++++++++++++- crates/voelin-media/src/studio/output/whip.rs | 6 +- docs/media.md | 56 +- docs/studio.md | 44 +- tools/voelinctl/src/studio.rs | 27 +- 17 files changed, 2038 insertions(+), 78 deletions(-) create mode 100644 crates/voelin-media/src/ffmpeg/audio.rs create mode 100644 crates/voelin-media/src/ffmpeg/avio.rs create mode 100644 crates/voelin-media/src/studio/output/flv.rs diff --git a/Cargo.lock b/Cargo.lock index fee7ebc..ea31997 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9182,6 +9182,7 @@ dependencies = [ "memmap2", "ndk 0.9.0", "openh264", + "opus2", "pipewire", "reqwest", "rtrb", diff --git a/crates/voelin-core/tests/studio.rs b/crates/voelin-core/tests/studio.rs index f68d832..8d69886 100644 --- a/crates/voelin-core/tests/studio.rs +++ b/crates/voelin-core/tests/studio.rs @@ -180,6 +180,176 @@ async fn a_studio_stream_records_and_replays_while_the_scene_switches() { std::fs::remove_dir_all(&dir).ok(); } +/// FFmpeg's own RTMP server (`ffmpeg -listen 1`) on `port`, keeping what +/// it receives in `out`; its log goes to `out` with `.log`. +fn rtmp_server(port: u16, out: &Path) -> std::process::Child { + let log = std::fs::File::create(out.with_extension("log")).unwrap(); + Process::new("ffmpeg") + .args(["-hide_banner", "-nostdin", "-loglevel", "warning", "-listen", "1", "-i"]) + .arg(format!("rtmp://127.0.0.1:{port}/live/test-key")) + .args(["-c", "copy", "-y"]) + .arg(out) + .stderr(log) + .spawn() + .unwrap() +} + +/// Wait up to `limit` for `child` to exit by itself. +fn wait_exit(child: &mut std::process::Child, limit: Duration) -> Option { + let deadline = Instant::now() + limit; + while Instant::now() < deadline { + if let Some(status) = child.try_wait().unwrap() { + return Some(status); + } + std::thread::sleep(Duration::from_millis(50)); + } + None +} + +/// ffprobe's view of the streams of `path`: codec, width, height, sample +/// rate and channels per stream. +fn probe_streams(path: &Path) -> Vec { + let out = Process::new("ffprobe") + .args(["-v", "error", "-show_entries"]) + .args(["stream=codec_name,width,height,sample_rate,channels", "-of", "csv=p=0"]) + .arg(path) + .output() + .unwrap(); + assert!(out.status.success(), "ffprobe: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| l.trim_end_matches(',').to_owned()) + .collect() +} + +/// The audio of `path`, mono, decoded by ffmpeg: its length in seconds and +/// its frequency (from the zero crossings), ignoring the first 100 ms. +fn tone(path: &Path) -> (f64, f64) { + let out = Process::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-map", "0:a", "-ac", "1", "-ar", "48000", "-f", "f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + let samples: Vec = + out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes(b.try_into().unwrap())).collect(); + let tail = &samples[samples.len().min(4800)..]; + let crossings = tail.windows(2).filter(|w| (w[0] < 0.0) != (w[1] < 0.0)).count(); + let seconds = tail.len() as f64 / 48_000.0; + (samples.len() as f64 / 48_000.0, crossings as f64 / 2.0 / seconds.max(1e-9)) +} + +/// Whether the first video frame of `path` is a keyframe. +fn starts_with_keyframe(path: &Path) -> bool { + let out = Process::new("ffprobe") + .args(["-v", "error", "-select_streams", "v", "-read_intervals", "%+#1"]) + .args(["-show_entries", "frame=key_frame", "-of", "csv=p=0"]) + .arg(path) + .output() + .unwrap(); + String::from_utf8_lossy(&out.stdout).lines().next() == Some("1") +} + +/// The studio pushed over RTMP to FFmpeg's own RTMP server: H.264 as +/// encoded and the tone as AAC arrive, with the stream key; the server goes +/// away mid-stream and a new one takes its place, which the output finds +/// again (starting at a keyframe); End Stream unpublishes cleanly, so the +/// server finishes its file and exits by itself. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did() { + use voelin_core::media::voelin_media::ffmpeg::avio::Connection; + use voelin_core::studio::OutputSpec; + + if !has("ffmpeg") || !has("ffprobe") { + eprintln!("skipped: ffmpeg and ffprobe are the RTMP server and the check"); + return; + } + if let Err(e) = Connection::available() { + eprintln!("skipped: no FFmpeg libraries with RTMP: {e}"); + return; + } + let codecs = Codecs::new(); + if !codecs.encoder_codecs().contains(&Codec::H264) { + eprintln!("skipped: no H.264 encoder"); + return; + } + let settings = Settings::in_memory(); + let mut scenes = + Scenes { width: WIDTH, height: HEIGHT, fps: 30, active: 1, ..Scenes::default() }; + scenes.scenes.push(colour_scene(1, "Red", RED)); + settings.set(&STUDIO_SCENES, scenes).unwrap(); + let studio = studio::start(&settings).await.unwrap(); + let config = StreamerConfig { + fps: 30, + bitrate_kbps: 800, + codec: Codec::H264, + audio_sources: vec![AudioSourceSpec::new(AudioSourceKind::Synthetic { hz: 440 })], + ..StreamerConfig::default() + }; + let mut streamer = Streamer::start_studio(&codecs, config, studio.clone()).await.unwrap(); + + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let dir = std::env::temp_dir().join(format!("voelin-studio-rtmp-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (first, second) = (dir.join("first.flv"), dir.join("second.flv")); + let mut server = rtmp_server(port, &first); + // The key apart from the URL, as a service gives them. + let spec = OutputSpec::Url { + url: format!("rtmp://127.0.0.1:{port}/live"), + token: Some("test-key".into()), + }; + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match studio.apply(Command::AddOutput(spec.clone())).await { + Ok(()) => break, + // The server is still starting. + Err(e) if Instant::now() < deadline => { + eprintln!("not yet: {e}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + Err(e) => panic!("the RTMP output did not connect: {e}"), + } + } + studio.apply(Command::GoLive).await.unwrap(); + tokio::time::sleep(Duration::from_secs(3)).await; + + // The server goes away (as a service restarting would); another one + // takes the address. + Process::new("kill").args(["-TERM", &server.id().to_string()]).status().unwrap(); + assert!(wait_exit(&mut server, Duration::from_secs(10)).is_some(), "the first server hangs"); + let mut server = rtmp_server(port, &second); + let deadline = Instant::now() + Duration::from_secs(20); + while std::fs::metadata(&second).map_or(0, |m| m.len()) < 20_000 { + assert!(Instant::now() < deadline, "the output did not come back"); + tokio::time::sleep(Duration::from_millis(100)).await; + } + tokio::time::sleep(Duration::from_secs(2)).await; + studio.apply(Command::EndStream).await.unwrap(); + let status = wait_exit(&mut server, Duration::from_secs(10)); + if status.is_none() { + let _ = server.kill(); + } + streamer.stop(); + assert!(status.is_some_and(|s| s.success()), "the server did not finish: {status:?}"); + + for (file, seconds) in [(&first, 2.0), (&second, 1.5)] { + let log = std::fs::read_to_string(file.with_extension("log")).unwrap_or_default(); + // The key arrived as the stream's name. + assert!(!log.contains("Unexpected stream"), "{log}"); + let streams = probe_streams(file); + assert_eq!(streams, [format!("h264,{WIDTH},{HEIGHT}"), "aac,48000,2".to_owned()], "{log}"); + assert!(starts_with_keyframe(file), "{}", file.display()); + let pictures = decode(file); + assert!(pictures.len() as f64 >= seconds * 25.0, "{} pictures", pictures.len()); + assert!(near(centre(&pictures[0]), RED), "{:?}", centre(&pictures[0])); + let (length, hz) = tone(file); + assert!(length >= seconds, "{length} s of audio in {}", file.display()); + assert!((430.0..450.0).contains(&hz), "{hz} Hz in {}", file.display()); + } + std::fs::remove_dir_all(&dir).ok(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn the_studio_source_needs_a_studio() { let codecs = Codecs::new(); diff --git a/crates/voelin-media/Cargo.toml b/crates/voelin-media/Cargo.toml index bb1cb9c..97d80ca 100644 --- a/crates/voelin-media/Cargo.toml +++ b/crates/voelin-media/Cargo.toml @@ -79,6 +79,9 @@ windows-capture = "2.0.1" [dev-dependencies] criterion = "0.8" +# Opus packets to feed the RTMP output's AAC encoder in tests (the voice +# codec's crate, already in the tree through voelin-audio). +opus2 = "0.4" serde_json = "1" # The H.264 `profile-level-id` the signalling offers, to check it against the # SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream diff --git a/crates/voelin-media/src/ffmpeg/audio.rs b/crates/voelin-media/src/ffmpeg/audio.rs new file mode 100644 index 0000000..ac75e4f --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/audio.rs @@ -0,0 +1,383 @@ +//! The studio's Opus as AAC, through FFmpeg's own codecs: RTMP services +//! take AAC, and few take anything else. +//! +//! [`AacEncoder`] decodes the Opus packets with FFmpeg's `opus` decoder and +//! encodes AAC-LC with its native `aac` encoder (both in every FFmpeg build), +//! 48 kHz stereo, configured through AVOptions like the video encoders. +//! +//! The AAC encoder takes frames of exactly 1024 samples; Opus frames have +//! 960, so the decoded samples are queued and cut into frames of our own. +//! Such a frame needs its channel layout, whose field moved between +//! releases (`AVFrame.ch_layout` since libavutil 57, `channels` and +//! `channel_layout` before), and `avcodec_send_frame` copies frames with +//! `av_frame_ref`, which refuses one without a layout unless its buffers are +//! reference-counted. So the input frame is a reference to the first frame +//! the decoder made, which FFmpeg filled in (layout, rate, format, the +//! buffer references), and only its leading fields are changed: the data +//! pointers aim at our planes, `nb_samples` is 1024 (`sys::FrameHead`, +//! unchanged since libavutil 51), plus `pts`, located at load. The +//! decoded buffers it still references are never read. +#![allow(unsafe_code)] + +use std::ffi::c_int; + +use super::Ffmpeg; +use super::layout::write; +use super::sys::{ + EAGAIN, EOF, FrameHead, NOPTS_VALUE, OPTION_NOT_FOUND, PacketHead, Ptr, Rational, cstr, +}; + +/// Samples per AAC frame (AAC-LC). +pub const FRAME: usize = 1024; +/// The sample rate of the studio's audio and of the AAC stream. +pub const RATE: u32 = 48_000; +/// The `AudioSpecificConfig` of the stream: AAC-LC (object type 2), 48 kHz +/// (sampling index 3), two channels. What an RTMP AAC sequence header +/// carries. +pub const AUDIO_SPECIFIC_CONFIG: [u8; 2] = [0x11, 0x90]; + +/// Opus packets in, AAC frames out; see the [module docs](self). +pub struct AacEncoder { + ffmpeg: &'static Ffmpeg, + decoder: Ptr, + encoder: Ptr, + /// Where the decoder puts its frames. + decoded: Ptr, + /// The encoder's input frame, made from the first decoded frame. + input: Ptr, + packet_in: Ptr, + packet_out: Ptr, + fltp: c_int, + /// Decoded samples not encoded yet, per channel. + pending: [Vec; 2], + /// The time (48 kHz samples) of the first pending sample. + pending_time: i64, + /// The planes the input frame points at. + planes: [Vec; 2], +} + +// SAFETY: the FFmpeg objects belong to this value and are only used +// through `&mut self`; FFmpeg's codecs have no thread affinity. +unsafe impl Send for AacEncoder {} + +impl AacEncoder { + /// An encoder at `bitrate` bit/s. + pub fn new(bitrate: u64) -> Result { + let ffmpeg = Ffmpeg::get()?; + let api = &ffmpeg.api; + let name = cstr("fltp"); + // SAFETY: a C string. + let fltp = unsafe { (api.av_get_sample_fmt)(name.as_ptr()) }; + if fltp < 0 { + return Err("FFmpeg has no planar float samples".into()); + } + // The fields are filled one by one; Drop frees what was made. + let mut this = Self { + ffmpeg, + decoder: std::ptr::null_mut(), + encoder: std::ptr::null_mut(), + decoded: std::ptr::null_mut(), + input: std::ptr::null_mut(), + packet_in: std::ptr::null_mut(), + packet_out: std::ptr::null_mut(), + fltp, + pending: [Vec::with_capacity(4 * FRAME), Vec::with_capacity(4 * FRAME)], + pending_time: 0, + planes: [vec![0.0; FRAME], vec![0.0; FRAME]], + }; + // SAFETY: allocations whose results are checked; contexts of the + // codecs they are opened with; options set by name on a codec + // context (an AVClass object) with C strings, and `sample_fmt` + // written at the offset located and checked at load. + unsafe { + this.decoded = (api.av_frame_alloc)(); + this.packet_in = (api.av_packet_alloc)(); + this.packet_out = (api.av_packet_alloc)(); + if this.decoded.is_null() || this.packet_in.is_null() || this.packet_out.is_null() { + return Err("out of memory".into()); + } + let opus = cstr("opus"); + let codec = (api.avcodec_find_decoder_by_name)(opus.as_ptr()); + if codec.is_null() { + return Err("this FFmpeg has no Opus decoder".into()); + } + this.decoder = (api.avcodec_alloc_context3)(codec); + if this.decoder.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + // Without extradata the decoder gives stereo at 48 kHz. + let ret = (api.avcodec_open2)(this.decoder, codec, std::ptr::null_mut()); + if ret < 0 { + return Err(format!("cannot open the Opus decoder: {}", api.error_text(ret))); + } + let aac = cstr("aac"); + let codec = (api.avcodec_find_encoder_by_name)(aac.as_ptr()); + if codec.is_null() { + return Err("this FFmpeg has no AAC encoder".into()); + } + this.encoder = (api.avcodec_alloc_context3)(codec); + if this.encoder.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + let ctx = this.encoder; + let set = |name: &str, value: &str| { + let (name, value) = (cstr(name), cstr(value)); + (api.av_opt_set)(ctx, name.as_ptr(), value.as_ptr(), 0) + }; + let set_int = |name: &str, value: i64| { + let name = cstr(name); + (api.av_opt_set_int)(ctx, name.as_ptr(), value, 0) + }; + // `sample_fmt` has no AVOption: its field, located at load. + let at = ffmpeg.codec_sample_fmt.clone()?; + write::(ctx, at, fltp); + let mut ret = set_int("ar", i64::from(RATE)); + if ret >= 0 { + // `ch_layout` since libavcodec 59.24; before, a channel mask + // (front left | front right) and a channel count. + ret = match set("ch_layout", "stereo") { + OPTION_NOT_FOUND => match set_int("channel_layout", 3) { + r if r < 0 => r, + _ => set_int("ac", 2), + }, + r => r, + }; + } + if ret >= 0 { + ret = set_int("b", i64::try_from(bitrate).unwrap_or(i64::MAX)); + } + if ret >= 0 { + let time_base = cstr("time_base"); + let tb = Rational { num: 1, den: RATE as c_int }; + ret = (api.av_opt_set_q)(ctx, time_base.as_ptr(), tb, 0); + } + if ret < 0 { + return Err(format!("cannot set up the AAC encoder: {}", api.error_text(ret))); + } + let ret = (api.avcodec_open2)(ctx, codec, std::ptr::null_mut()); + if ret < 0 { + return Err(format!("cannot open the AAC encoder: {}", api.error_text(ret))); + } + } + Ok(this) + } + + /// Decode one Opus packet of time `time` (48 kHz samples since any + /// origin) and hand every AAC frame that is complete to `out`, with its + /// time on the same clock (an AAC encoder starts 1024 samples early: + /// its first frame is the codec's priming). + /// + /// A packet that does not follow the last one (a gap in the studio's + /// audio) starts the queue again at its time. A packet that does not + /// decode is an error; the next one is decoded as usual. + pub fn push( + &mut self, + opus: &[u8], + time: i64, + out: &mut dyn FnMut(&[u8], i64), + ) -> Result<(), String> { + let api = &self.ffmpeg.api; + // SAFETY: our packet points at `opus` only during the call that + // copies it (the packet is not reference-counted), then is emptied + // again; the decoder's frames are read within their sample count and + // unreferenced after. + unsafe { + let packet = self.packet_in.cast::(); + (*packet).data = opus.as_ptr().cast_mut(); + (*packet).size = c_int::try_from(opus.len()).map_err(|_| "Opus packet too large")?; + (*packet).pts = NOPTS_VALUE; + let ret = (api.avcodec_send_packet)(self.decoder, self.packet_in); + (*packet).data = std::ptr::null_mut(); + (*packet).size = 0; + if ret < 0 && ret != EAGAIN { + return Err(format!("Opus decoding failed: {}", api.error_text(ret))); + } + let mut time = time; + loop { + let ret = (api.avcodec_receive_frame)(self.decoder, self.decoded); + if ret == EAGAIN || ret == EOF { + break; + } + if ret < 0 { + return Err(format!("Opus decoding failed: {}", api.error_text(ret))); + } + let taken = self.take_decoded(time); + let samples = i64::from((*self.decoded.cast::()).nb_samples); + (api.av_frame_unref)(self.decoded); + taken?; + time += samples; + } + } + while self.pending[0].len() >= FRAME { + self.encode_one(out)?; + } + Ok(()) + } + + /// Queue the samples of the decoded frame, which starts at `time`. + /// + /// # Safety + /// `self.decoded` must hold a frame from the decoder. + unsafe fn take_decoded(&mut self, time: i64) -> Result<(), String> { + let api = &self.ffmpeg.api; + // SAFETY: guaranteed by the caller; planar float planes hold + // `nb_samples` samples each. + unsafe { + let head = &*self.decoded.cast::(); + if head.format != self.fltp { + return Err(format!( + "the Opus decoder gives sample format {}, not planar float", + head.format + )); + } + let n = usize::try_from(head.nb_samples).unwrap_or(0); + if n == 0 || head.data[0].is_null() { + return Ok(()); + } + if self.input.is_null() { + let input = (api.av_frame_alloc)(); + if input.is_null() || (api.av_frame_ref)(input, self.decoded) < 0 { + let mut input = input; + (api.av_frame_free)(&mut input); + return Err("cannot make the AAC encoder's frame".into()); + } + self.input = input; + } + let expected = self.pending_time + self.pending[0].len() as i64; + if self.pending[0].is_empty() || (time - expected).abs() > FRAME as i64 { + self.pending[0].clear(); + self.pending[1].clear(); + self.pending_time = time; + } + let left = std::slice::from_raw_parts(head.data[0].cast::(), n); + // A mono stream gives one plane: both channels get it. + let right = if head.data[1].is_null() { + left + } else { + std::slice::from_raw_parts(head.data[1].cast::(), n) + }; + self.pending[0].extend_from_slice(left); + self.pending[1].extend_from_slice(right); + } + Ok(()) + } + + /// Encode the first [`FRAME`] pending samples. + fn encode_one(&mut self, out: &mut dyn FnMut(&[u8], i64)) -> Result<(), String> { + let api = &self.ffmpeg.api; + for (plane, pending) in self.planes.iter_mut().zip(&mut self.pending) { + plane.copy_from_slice(&pending[..FRAME]); + pending.drain(..FRAME); + } + let time = self.pending_time; + self.pending_time += FRAME as i64; + // SAFETY: `input` is a frame of ours (a reference to a decoded one, + // see the module docs) whose leading fields we point at our planes, + // which live as long as `self` and are not touched until the + // encoder has taken the frame (it copies the samples when it + // encodes, before `avcodec_receive_packet` asks for more input); + // `pts` is the field located at load. Packets are read within their + // size and unreferenced after. + unsafe { + let head = &mut *self.input.cast::(); + for (data, plane) in head.data.iter_mut().zip(&mut self.planes) { + *data = plane.as_mut_ptr().cast(); + } + head.linesize[0] = (FRAME * size_of::()) as c_int; + head.nb_samples = FRAME as c_int; + write::(self.input, self.ffmpeg.frame.pts, time); + let ret = (api.avcodec_send_frame)(self.encoder, self.input); + if ret < 0 { + return Err(format!("AAC encoding failed: {}", api.error_text(ret))); + } + loop { + let ret = (api.avcodec_receive_packet)(self.encoder, self.packet_out); + if ret == EAGAIN || ret == EOF { + break; + } + if ret < 0 { + return Err(format!("AAC encoding failed: {}", api.error_text(ret))); + } + let packet = &*self.packet_out.cast::(); + let size = usize::try_from(packet.size).unwrap_or(0); + if !packet.data.is_null() && size > 0 { + out(std::slice::from_raw_parts(packet.data, size), packet.pts); + } + (api.av_packet_unref)(self.packet_out); + } + } + Ok(()) + } +} + +impl Drop for AacEncoder { + fn drop(&mut self) { + let api = &self.ffmpeg.api; + // SAFETY: every pointer is NULL or an object of ours, freed once; + // the free functions take NULL. + unsafe { + (api.av_frame_free)(&mut self.input); + (api.av_frame_free)(&mut self.decoded); + (api.av_packet_free)(&mut self.packet_in); + (api.av_packet_free)(&mut self.packet_out); + (api.avcodec_free_context)(&mut self.decoder); + (api.avcodec_free_context)(&mut self.encoder); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_audio_specific_config_is_aac_lc_48k_stereo() { + let config = u16::from_be_bytes(AUDIO_SPECIFIC_CONFIG); + assert_eq!(config >> 11, 2, "object type"); + assert_eq!((config >> 7) & 0xF, 3, "sampling index (48 kHz)"); + assert_eq!((config >> 3) & 0xF, 2, "channels"); + } + + /// One second of a stereo tone as 20 ms Opus packets becomes AAC frames + /// of 1024 samples, back to back from the first packet's time (less the + /// encoder's 1024 samples of priming); a gap starts the clock again. + #[test] + fn opus_becomes_aac() { + if Ffmpeg::get().is_err() { + eprintln!("FFmpeg not installed, skipped"); + return; + } + let mut aac = AacEncoder::new(160_000).unwrap(); + let mut opus = + opus2::Encoder::new(RATE, opus2::Channels::Stereo, opus2::Application::Audio).unwrap(); + let mut frames: Vec<(usize, i64)> = Vec::new(); + let mut packet = [0u8; 4000]; + let start = 48_000 * 7; + let mut feed = |aac: &mut AacEncoder, from: i64, packets: i64, frames: &mut Vec<_>| { + for p in 0..packets { + let time = from + p * 960; + let pcm: Vec = (0..960) + .flat_map(|i| { + let t = (time + i) as f32 / RATE as f32; + let v = (t * 440.0 * std::f32::consts::TAU).sin() * 0.3; + [v, v] + }) + .collect(); + let n = opus.encode_float(&pcm, &mut packet).unwrap(); + aac.push(&packet[..n], time, &mut |data, at| frames.push((data.len(), at))) + .unwrap(); + } + }; + feed(&mut aac, start, 50, &mut frames); + assert!(frames.len() >= 44, "{} frames", frames.len()); + assert_eq!(frames[0].1, start - FRAME as i64, "{frames:?}"); + assert!(frames.windows(2).all(|w| w[1].1 - w[0].1 == FRAME as i64), "{frames:?}"); + assert!(frames.iter().all(|(size, _)| *size > 0)); + // Two seconds of silence nobody sent: the clock restarts. + let after = start + 50 * 960 + 96_000; + let before = frames.len(); + feed(&mut aac, after, 10, &mut frames); + let restarted = frames[before..].iter().find(|(_, at)| *at >= after - FRAME as i64); + assert!(restarted.is_some(), "{:?}", &frames[before..]); + } +} diff --git a/crates/voelin-media/src/ffmpeg/avio.rs b/crates/voelin-media/src/ffmpeg/avio.rs new file mode 100644 index 0000000..e9ee90e --- /dev/null +++ b/crates/voelin-media/src/ffmpeg/avio.rs @@ -0,0 +1,256 @@ +//! A connection that bytes are written to through libavformat's protocols +//! (`rtmp://`, `rtmps://`, and whatever else the installed FFmpeg speaks). +//! +//! `avio_write` buffers and `avio_flush` sends; neither returns an error, +//! which lands in `AVIOContext.error` instead (found at load, +//! [`super::layout::avio_error`]), so every write and flush is checked +//! there. Every blocking call (connecting, sending, closing) polls an +//! interrupt callback, so a stuck network or a stop from another thread +//! never holds the caller for longer than FFmpeg's poll interval (100 ms) +//! once the abort flag is set. +#![allow(unsafe_code)] + +use std::ffi::c_int; +use std::sync::Arc; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::layout::read; +use super::sys::{AVIO_FLAG_WRITE, InterruptCallback, Ptr, cstr}; +use super::{Ffmpeg, Io, take_log}; + +/// An open connection; closed (cleanly, as far as the abort flag lets it) +/// when dropped. +pub struct Connection { + ffmpeg: &'static Ffmpeg, + ctx: Ptr, + /// What the interrupt callback reads; kept alive as long as the context. + abort: Arc, +} + +// SAFETY: the context is only used through `&mut self` or by value, one +// thread at a time; FFmpeg's I/O contexts have no thread affinity. +unsafe impl Send for Connection {} + +unsafe extern "C" fn interrupted(opaque: Ptr) -> c_int { + // SAFETY: `opaque` is the `AtomicBool` of the `Arc` the connection + // holds for as long as FFmpeg may call this (until its context is + // closed). + c_int::from(unsafe { (*opaque.cast::()).load(Ordering::Relaxed) }) +} + +/// The FFmpeg messages about the connection since the last call, for an +/// error text. +fn messages() -> String { + let mut lines = Vec::new(); + for context in ["rtmp", "tls", "tcp"] { + lines.extend(take_log(context)); + } + lines.join("; ") +} + +impl Connection { + /// Whether this FFmpeg can open connections: libavformat's I/O was + /// loaded and its write errors can be read. + pub fn available() -> Result<(), String> { + Self::libraries().map(|_| ()) + } + + /// The process's FFmpeg and its I/O functions. + fn libraries() -> Result<(&'static Ffmpeg, &'static Io), String> { + let ffmpeg = Ffmpeg::get()?; + Ok((ffmpeg, ffmpeg.io.as_ref().map_err(Clone::clone)?)) + } + + /// Open `url` for writing, with protocol `options` (`rw_timeout`, + /// `rtmp_app`, `rtmp_playpath`, ...; options the protocol does not + /// know are ignored). Once `abort` is set, every blocking call of this + /// connection returns at once (with an error). + pub fn open( + url: &str, + options: &[(&str, &str)], + abort: Arc, + ) -> Result { + let (ffmpeg, io) = Self::libraries()?; + static NETWORK: OnceLock<()> = OnceLock::new(); + NETWORK.get_or_init(|| { + // SAFETY: no arguments; initialises the TLS libraries once. + unsafe { (io.api.avformat_network_init)() }; + }); + // Messages of an earlier connection are not about this one. + messages(); + let url = cstr(url); + let callback = InterruptCallback { + callback: Some(interrupted), + opaque: Arc::as_ptr(&abort).cast_mut().cast(), + }; + let mut ctx: Ptr = std::ptr::null_mut(); + // SAFETY: a dictionary built with av_dict_set and freed with + // av_dict_free; avio_open2 copies the callback and takes C strings + // that outlive the call. + let ret = unsafe { + let mut dict: Ptr = std::ptr::null_mut(); + for (key, value) in options { + let (key, value) = (cstr(key), cstr(value)); + (ffmpeg.api.av_dict_set)(&mut dict, key.as_ptr(), value.as_ptr(), 0); + } + let ret = + (io.api.avio_open2)(&mut ctx, url.as_ptr(), AVIO_FLAG_WRITE, &callback, &mut dict); + (ffmpeg.api.av_dict_free)(&mut dict); + ret + }; + if ret < 0 || ctx.is_null() { + return Err(failure(ffmpeg, ret)); + } + Ok(Self { ffmpeg, ctx, abort }) + } + + fn io(&self) -> &'static Io { + // Checked in `open`. + self.ffmpeg.io.as_ref().expect("a connection is only opened with libavformat's I/O") + } + + /// The write error of the context, if one happened. + fn check(&self) -> Result<(), String> { + // SAFETY: `error` is `AVIOContext.error` of this release (located and + // checked at load); the context is live. + let error: c_int = unsafe { read(self.ctx, self.io().error) }; + if error < 0 { Err(failure(self.ffmpeg, error)) } else { Ok(()) } + } + + /// Hand `data` to the connection (sent at the latest on [`flush`]). + /// + /// [`flush`]: Self::flush + pub fn write(&mut self, data: &[u8]) -> Result<(), String> { + for chunk in data.chunks(c_int::MAX as usize) { + // SAFETY: a live context; the slice is valid for its length. + unsafe { (self.io().api.avio_write)(self.ctx, chunk.as_ptr(), chunk.len() as c_int) }; + } + self.check() + } + + /// Send everything written so far. + pub fn flush(&mut self) -> Result<(), String> { + // SAFETY: a live context. + unsafe { (self.io().api.avio_flush)(self.ctx) }; + self.check() + } + + /// Close the connection (for RTMP: unpublish), reporting a write that + /// failed on the way. + pub fn close(mut self) -> Result<(), String> { + let error = self.check(); + let ret = self.close_context(); + error?; + if ret < 0 { Err(failure(self.ffmpeg, ret)) } else { Ok(()) } + } + + fn close_context(&mut self) -> c_int { + if self.ctx.is_null() { + return 0; + } + // SAFETY: a context from avio_open2; avio_closep sets it to NULL. + unsafe { (self.io().api.avio_closep)(&mut self.ctx) } + } + + /// Whether the abort flag is set. + pub fn aborted(&self) -> bool { + self.abort.load(Ordering::Relaxed) + } +} + +impl Drop for Connection { + fn drop(&mut self) { + self.close_context(); + } +} + +/// FFmpeg's text for `code` with what it logged about the connection. +fn failure(ffmpeg: &Ffmpeg, code: c_int) -> String { + let text = ffmpeg.api.error_text(code); + match messages() { + log if log.is_empty() => text, + log => format!("{log} ({text})"), + } +} + +#[cfg(test)] +mod tests { + use std::io::Read; + use std::net::TcpListener; + use std::time::{Duration, Instant}; + + use super::*; + + /// A file written through libavformat's `file:` protocol arrives whole, + /// and a write error (a connection the other side closed) is seen. + #[test] + fn writes_arrive_and_errors_are_seen() { + if Connection::available().is_err() { + eprintln!("no FFmpeg with libavformat, skipped"); + return; + } + let path = std::env::temp_dir().join(format!("voelin-avio-{}.bin", std::process::id())); + let abort = Arc::new(AtomicBool::new(false)); + let mut file = + Connection::open(&path.to_string_lossy(), &[], abort.clone()).expect("a file opens"); + file.write(b"hello ").unwrap(); + file.write(&[7; 100_000]).unwrap(); + file.flush().unwrap(); + file.close().unwrap(); + let written = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(written.len(), 100_006); + assert!(written.starts_with(b"hello ")); + + // A TCP peer that reads a little and goes away: the writes start + // failing, and the failure is reported. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let peer = std::thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + let mut buf = [0; 16]; + let _ = socket.read_exact(&mut buf); + }); + let mut tcp = Connection::open( + &format!("tcp://127.0.0.1:{port}"), + &[("rw_timeout", "2000000")], + abort, + ) + .unwrap(); + tcp.write(&[1; 16]).unwrap(); + tcp.flush().unwrap(); + peer.join().unwrap(); + let started = Instant::now(); + let error = loop { + match tcp.write(&[1; 65536]).and_then(|()| tcp.flush()) { + Ok(()) => assert!(started.elapsed() < Duration::from_secs(10), "no error"), + Err(e) => break e, + } + }; + assert!(!error.is_empty()); + assert!(tcp.close().is_err()); + } + + /// An abort flag set while connecting makes the connection give up. + #[test] + fn an_abort_stops_a_connection_attempt() { + if Connection::available().is_err() { + return; + } + // A listener that never accepts: the RTMP handshake waits forever. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let abort = Arc::new(AtomicBool::new(false)); + let stopper = abort.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + stopper.store(true, Ordering::Relaxed); + }); + let started = Instant::now(); + let result = Connection::open(&format!("rtmp://127.0.0.1:{port}/app/key"), &[], abort); + assert!(result.is_err()); + assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); + drop(listener); + } +} diff --git a/crates/voelin-media/src/ffmpeg/layout.rs b/crates/voelin-media/src/ffmpeg/layout.rs index dbf2d2b..087bca9 100644 --- a/crates/voelin-media/src/ffmpeg/layout.rs +++ b/crates/voelin-media/src/ffmpeg/layout.rs @@ -15,20 +15,24 @@ //! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context | //! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool | //! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout | +//! | `AVCodecContext.sample_fmt` | the AAC encoder of RTMP output (an audio encoder needs its sample format before it opens) | after `sample_rate` (option `ar`): directly from libavcodec 61 (then `ch_layout`), after `channels` (option `ac`) up to 60 | the neighbours' option offsets must match exactly one layout, and the field must be `AV_SAMPLE_FMT_NONE` in a new context | +//! | `AVIOContext.error` | RTMP output: a write that failed (`avio_write` and `avio_flush` return nothing) | searched: the `int` where a write callback's failure lands ([`avio_error`]) | exactly one `int` of the first 200 bytes changes to the callback's sentinel value | //! -//! A check that fails disables only what needs the field (VA-API, or the -//! DMA-BUF import), with the reason in the probe results. The first three -//! rows are found by searching, so a new major whose layout matches keeps -//! working without a change here; the last one is a table, because there is -//! nothing to anchor those offsets to, and an unlisted major turns the -//! DMA-BUF import off rather than guess (see [`frame_refs_table`]). +//! A check that fails disables only what needs the field (VA-API, the +//! DMA-BUF import, or RTMP output), with the reason in the probe results. +//! Most rows are found by searching, so a new major whose layout matches +//! keeps working without a change here; `buf[0]` / `hw_frames_ctx` is a +//! table, because there is nothing to anchor those offsets to, and an +//! unlisted major turns the DMA-BUF import off rather than guess (see +//! [`frame_refs_table`]). #![allow(unsafe_code)] use std::ffi::c_int; use std::mem::{offset_of, size_of}; use super::sys::{ - Api, BufferRefHead, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, Rational, cstr, + Api, AvioHead, BufferRefHead, FormatApi, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, + Rational, cstr, }; /// Offsets of `pict_type` and `pts` in `AVFrame`. @@ -228,6 +232,43 @@ fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result { Ok(found) } +/// Where `sample_fmt` is in `AVCodecContext`, from the offsets of the +/// AVOptions of its neighbours, checked in a new context. +/// +/// An audio encoder must be told its sample format before it opens, and +/// that field has no AVOption. It follows `sample_rate` (option `ar`): +/// directly from libavcodec 61, with `ch_layout` (option `ch_layout`) after +/// it; after `channels` (option `ac`) up to 60, where `ch_layout` sits at +/// the end of the struct. +pub fn codec_sample_fmt(api: &Api) -> Result { + // SAFETY: a generic context (no codec); freed below. + let mut ctx = unsafe { (api.avcodec_alloc_context3)(std::ptr::null_mut()) }; + if ctx.is_null() { + return Err("avcodec_alloc_context3 failed".into()); + } + let offset = |name| option_offset(api, ctx, name); + let rate = offset("ar"); + let found = rate.and_then(|rate| { + let new = offset("ch_layout") == Some(rate + 8); + let old = offset("ac") == Some(rate + 4); + match (new, old) { + (true, false) => Some(rate + 4), + (false, true) => Some(rate + 8), + _ => None, + } + }); + // SAFETY: the offset lies before an option of this context, so inside + // it, and is int-aligned (a neighbour of int fields). + let result = match found { + Some(at) if unsafe { read::(ctx, at) } == -1 => Ok(at), + Some(_) => Err("AVCodecContext.sample_fmt check failed (not NONE in a new context)".into()), + None => Err("unknown AVCodecContext layout (sample_fmt not next to sample_rate)".into()), + }; + // SAFETY: allocated above. + unsafe { (api.avcodec_free_context)(&mut ctx) }; + result +} + /// Offsets in `AVHWFramesContext`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct HwFramesFields { @@ -400,6 +441,77 @@ fn frame_refs_table(avutil_major: u32) -> Option { Some(FrameRefs { buf, hw_frames_ctx }) } +/// The bytes of an `AVIOContext` searched for `error`: inside the struct of +/// every release (208 bytes in libavformat 63, the smallest so far; 264 in +/// 58), and since libavformat 60 it lives inside the larger `FFIOContext`. +const AVIO_SPAN: usize = 200; + +/// The value [`avio_error`]'s write callback fails with: a negative number +/// no FFmpeg error code uses. +const AVIO_SENTINEL: c_int = -0x4E5F_0321; + +unsafe extern "C" fn refuse_write(_opaque: Ptr, _data: *mut u8, _size: c_int) -> c_int { + AVIO_SENTINEL +} + +/// Where `AVIOContext.error` is, found by search. +/// +/// `avio_write` and `avio_flush` return nothing; a failed write is only +/// stored in `error`, which moved between releases (120 bytes in +/// libavformat 58, after the checksum fields; 84 in 63, right after +/// `eof_reached`). A context whose write callback fails with a sentinel +/// value is written to and flushed, and the one `int` of its first +/// [`AVIO_SPAN`] bytes that changed to the sentinel is `error`. +pub fn avio_error(format: &FormatApi, api: &Api) -> Result { + const SIZE: usize = 4096; + type Snapshot = [c_int; AVIO_SPAN / 4]; + // SAFETY: a context of our own over a buffer from av_malloc, as + // avio_alloc_context documents; it is only written to through FFmpeg, + // and the snapshots read within its first AVIO_SPAN bytes (see there), + // at int-aligned offsets of an allocation FFmpeg aligns. The buffer + // (which FFmpeg may have replaced) and the context are freed as the + // documentation says: `av_freep(&ctx->buffer)`, then + // `avio_context_free`. + unsafe { + let buffer = (api.av_malloc)(SIZE).cast::(); + if buffer.is_null() { + return Err("av_malloc failed".into()); + } + let mut ctx = (format.avio_alloc_context)( + buffer, + SIZE as c_int, + 1, + std::ptr::null_mut(), + None, + Some(refuse_write), + None, + ); + if ctx.is_null() { + let mut buffer = buffer; + (api.av_freep)((&raw mut buffer).cast()); + return Err("avio_alloc_context failed".into()); + } + let snapshot = |ctx: Ptr| -> Snapshot { std::array::from_fn(|i| read(ctx, i * 4)) }; + let before = snapshot(ctx); + (format.avio_write)(ctx, b"voelin".as_ptr(), 6); + (format.avio_flush)(ctx); + let after = snapshot(ctx); + let head = ctx.cast::(); + (api.av_freep)((&raw mut (*head).buffer).cast()); + (format.avio_context_free)(&mut ctx); + let found: Vec = (0..before.len()) + .filter(|&i| before[i] != AVIO_SENTINEL && after[i] == AVIO_SENTINEL) + .map(|i| i * 4) + .collect(); + match found[..] { + [offset] => Ok(offset), + _ => Err(format!( + "unknown AVIOContext layout (write errors at {found:?}, not in exactly one place)" + )), + } + } +} + /// [`FrameRefs`] of this release, with `buf[0]` checked on a real frame /// (`hw_frames_ctx` is checked once a hardware frame exists, see /// [`check_hw_frames_ctx`]). diff --git a/crates/voelin-media/src/ffmpeg/mod.rs b/crates/voelin-media/src/ffmpeg/mod.rs index aed49f5..7839d11 100644 --- a/crates/voelin-media/src/ffmpeg/mod.rs +++ b/crates/voelin-media/src/ffmpeg/mod.rs @@ -18,6 +18,8 @@ use std::ffi::{CStr, c_char, c_int}; use std::path::PathBuf; use std::sync::{Mutex, OnceLock}; +pub mod audio; +pub mod avio; pub mod encoder; mod gpu; mod layout; @@ -33,7 +35,7 @@ pub use encoder::{ pub use sys::Search; use self::layout::{FrameFields, FrameRefs}; -use self::sys::{Api, Libs, LogCallback, Ptr, VaList}; +use self::sys::{Api, FormatApi, Libs, LogCallback, Ptr, VaList}; /// Pixel format numbers of this release (looked up by name). #[derive(Clone, Copy, Debug)] @@ -46,6 +48,13 @@ pub(crate) struct PixFmts { pub bgr0: Option, } +/// libavformat's I/O functions and where a write error lands +/// (`AVIOContext.error`, see [`layout::avio_error`]). +pub(crate) struct Io { + pub api: FormatApi, + pub error: usize, +} + /// What was loaded, for logs and the UI. #[derive(Clone, Debug, PartialEq, Eq)] pub struct LibraryInfo { @@ -56,8 +65,10 @@ pub struct LibraryInfo { /// `major.minor.micro` of libavcodec and libavutil. pub avcodec: String, pub avutil: String, - /// libavformat of the same release was found (for RTMP output later). + /// libavformat of the same release was found. pub avformat: bool, + /// Why RTMP output (libavformat's network I/O) cannot be used, if not. + pub rtmp: Result<(), String>, /// Why hardware frame pools (VA-API) cannot be used, if not. pub hw_frames: Result<(), String>, /// Why DMA-BUF frames cannot be imported (zero-copy), if not. @@ -73,6 +84,10 @@ pub struct Ffmpeg { pub(crate) codec_hw_frames: Result, /// `AVFrame.buf[0]` / `hw_frames_ctx`. pub(crate) frame_refs: Result, + /// `AVCodecContext.sample_fmt`, for the AAC encoder of RTMP output. + pub(crate) codec_sample_fmt: Result, + /// libavformat's I/O for RTMP output. + pub(crate) io: Result, pub(crate) pix: PixFmts, info: LibraryInfo, } @@ -109,6 +124,11 @@ impl Ffmpeg { }; let codec_hw_frames = layout::codec_hw_frames(&api); let frame_refs = layout::frame_refs(&api, yuv420p); + let codec_sample_fmt = layout::codec_sample_fmt(&api); + let io = libs.format_api().and_then(|format| { + let error = layout::avio_error(&format, &api)?; + Ok(Io { api: format, error }) + }); // SAFETY: no arguments; returns version numbers and a static string. let (avcodec, avutil, release) = unsafe { ( @@ -123,6 +143,10 @@ impl Ffmpeg { avcodec: version_text(avcodec), avutil: version_text(avutil), avformat: libs.avformat.is_some(), + rtmp: match (&io, &codec_sample_fmt) { + (Err(e), _) | (_, Err(e)) => Err(e.clone()), + _ => Ok(()), + }, hw_frames: codec_hw_frames.clone().map(|_| ()), dmabuf_import: match (&codec_hw_frames, &frame_refs, pix.drm_prime) { (Err(e), _, _) | (_, Err(e), _) => Err(e.clone()), @@ -130,7 +154,17 @@ impl Ffmpeg { _ => Ok(()), }, }; - Ok(Self { api, _libs: libs, frame, codec_hw_frames, frame_refs, pix, info }) + Ok(Self { + api, + _libs: libs, + frame, + codec_hw_frames, + frame_refs, + codec_sample_fmt, + io, + pix, + info, + }) } /// The process's FFmpeg, loaded on first use from [`Search::from_env`] @@ -253,11 +287,37 @@ mod tests { assert!(!info.release.is_empty()); assert!(info.avcodec.split('.').count() == 3); assert!(info.hw_frames.is_ok(), "{info:?}"); + // libavformat comes with libavcodec in every package. + assert!(info.rtmp.is_ok(), "{info:?}"); if cfg!(target_pointer_width = "64") { assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs); } } + /// `AVIOContext.error` is where the headers of the installed releases + /// put it (compiled with `offsetof`: 120 in libavformat 58, FFmpeg 4.4; + /// 84 in 63, FFmpeg 9.0). + #[cfg(target_pointer_width = "64")] + #[test] + fn write_errors_are_found_where_the_headers_put_them() { + let Ok(ffmpeg) = Ffmpeg::get() else { return }; + let io = ffmpeg.io.as_ref().expect("libavformat's I/O"); + // SAFETY: no arguments. + let major = unsafe { (io.api.avformat_version)() } >> 16; + match major { + 58 => assert_eq!(io.error, 120), + 63 => assert_eq!(io.error, 84), + _ => {} + } + // And `AVCodecContext.sample_fmt`: 408 in libavcodec 58, 348 in 63. + // SAFETY: no arguments. + match unsafe { (ffmpeg.api.avcodec_version)() } >> 16 { + 58 => assert_eq!(ffmpeg.codec_sample_fmt, Ok(408)), + 63 => assert_eq!(ffmpeg.codec_sample_fmt, Ok(348)), + _ => {} + } + } + #[test] fn no_ffmpeg_in_an_empty_directory() { let dir = std::env::temp_dir().join(format!("voelin-no-ffmpeg-{}", std::process::id())); diff --git a/crates/voelin-media/src/ffmpeg/sys.rs b/crates/voelin-media/src/ffmpeg/sys.rs index 1cadd07..d409282 100644 --- a/crates/voelin-media/src/ffmpeg/sys.rs +++ b/crates/voelin-media/src/ffmpeg/sys.rs @@ -87,6 +87,15 @@ pub struct BufferRefHead { pub data: *mut u8, } +/// The leading fields of `AVIOContext` (`av_class`, `buffer`), unchanged +/// since libavformat 53. Only `buffer` is read, to free the buffer of a +/// context made with `avio_alloc_context`. +#[repr(C)] +pub struct AvioHead { + pub av_class: Ptr, + pub buffer: *mut u8, +} + /// `AVDRMObjectDescriptor` (`libavutil/hwcontext_drm.h`, unchanged since it /// was added in libavutil 55). #[repr(C)] @@ -167,17 +176,17 @@ pub const EOF: c_int = err_tag(b'E', b'O', b'F', b' '); /// `AVERROR_OPTION_NOT_FOUND`. pub const OPTION_NOT_FOUND: c_int = err_tag(0xF8, b'O', b'P', b'T'); -/// Declares the function table: every function, its library, its C +/// Declares a function table: every function, its library, its C /// signature. `resolve` looks all of them up; a missing one fails the load. macro_rules! api { - ($($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })*) => { - /// FFmpeg functions used by this crate. + ($(#[$doc:meta])* $api:ident { $($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })* }) => { + $(#[$doc])* #[allow(non_snake_case, dead_code)] - pub struct Api { + pub struct $api { $($(pub $name: unsafe extern "C" fn($($ty),*) $(-> $ret)?,)*)* } - impl Api { + impl $api { /// # Safety /// The libraries must be FFmpeg's, so the symbols have the /// declared signatures. @@ -191,6 +200,8 @@ macro_rules! api { } api! { + /// FFmpeg functions used by this crate (libavutil and libavcodec). + Api { Util { fn avutil_version() -> c_uint; fn av_version_info() -> *const c_char; @@ -243,6 +254,11 @@ api! { fn av_hwframe_get_buffer(frames: Ptr, frame: Ptr, flags: c_int) -> c_int; fn av_hwframe_transfer_data(dst: Ptr, src: Ptr, flags: c_int) -> c_int; fn av_hwframe_map(dst: Ptr, src: Ptr, flags: c_int) -> c_int; + fn av_get_sample_fmt(name: *const c_char) -> c_int; + fn av_malloc(size: usize) -> *mut c_void; + fn av_freep(ptr: *mut c_void); + fn av_dict_set(dict: *mut Ptr, key: *const c_char, value: *const c_char, flags: c_int) -> c_int; + fn av_dict_free(dict: *mut Ptr); } Codec { @@ -256,9 +272,64 @@ api! { fn av_packet_alloc() -> Ptr; fn av_packet_free(packet: *mut Ptr); fn av_packet_unref(packet: Ptr); + fn avcodec_find_decoder_by_name(name: *const c_char) -> Ptr; + fn avcodec_send_packet(ctx: Ptr, packet: Ptr) -> c_int; + fn avcodec_receive_frame(ctx: Ptr, frame: Ptr) -> c_int; + } } } +api! { + /// libavformat's I/O functions, for RTMP output: the connection is + /// libavformat's (`rtmp://`, `rtmps://`); the FLV inside it is ours + /// (`studio::output::flv`), so no muxer struct is ever touched. + FormatApi { + Format { + fn avformat_version() -> c_uint; + fn avformat_network_init() -> c_int; + fn avio_open2( + ctx: *mut Ptr, + url: *const c_char, + flags: c_int, + interrupt: *const InterruptCallback, + options: *mut Ptr + ) -> c_int; + fn avio_write(ctx: Ptr, data: *const u8, size: c_int); + fn avio_flush(ctx: Ptr); + fn avio_closep(ctx: *mut Ptr) -> c_int; + fn avio_alloc_context( + buffer: *mut u8, + size: c_int, + write_flag: c_int, + opaque: Ptr, + read: Option, + write: Option, + seek: Option + ) -> Ptr; + fn avio_context_free(ctx: *mut Ptr); + } + } +} + +/// `int (*)(void *opaque, uint8_t *buf, int size)`: `read_packet` and +/// `write_packet` of `avio_alloc_context` (`const uint8_t *` for writing +/// since libavformat 61, the same in the ABI). +pub type IoCallback = unsafe extern "C" fn(Ptr, *mut u8, c_int) -> c_int; +/// `int64_t (*)(void *opaque, int64_t offset, int whence)`. +pub type SeekCallback = unsafe extern "C" fn(Ptr, i64, c_int) -> i64; + +/// `AVIOInterruptCB` (`int (*callback)(void *); void *opaque;`), unchanged +/// since it was added (libavformat 53). FFmpeg calls it while it waits for +/// the network; a non-zero return aborts the operation. +#[repr(C)] +pub struct InterruptCallback { + pub callback: Option c_int>, + pub opaque: Ptr, +} + +/// `AVIO_FLAG_WRITE`. +pub const AVIO_FLAG_WRITE: c_int = 2; + /// `void (*)(void *avcl, int level, const char *fmt, va_list vl)`. pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList); @@ -266,6 +337,7 @@ pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList); enum Lib { Util, Codec, + Format, } /// The opened libraries. Never closed: FFmpeg keeps global state (codec @@ -275,19 +347,30 @@ pub struct Libs { /// libavutil where symbols are not found through libavcodec's handle /// (Windows: `GetProcAddress` does not search dependencies). avutil: Option, - /// libavformat, if present (for later use: RTMP output). + /// libavformat, if present (RTMP output). pub avformat: Option, /// Where libavcodec was found. pub path: PathBuf, } impl Libs { + /// libavformat's functions, if libavformat was found and has them all. + pub fn format_api(&self) -> Result { + if self.avformat.is_none() { + return Err(format!("no libavformat of the release of {}", self.path.display())); + } + // SAFETY: the library is libavformat (found by its file name, of + // libavcodec's major), whose functions have the declared signatures. + unsafe { FormatApi::resolve(self) } + } + /// # Safety /// `T` must be the symbol's actual type. unsafe fn symbol(&self, lib: Lib, name: &str) -> Result { let library = match lib { Lib::Util => self.avutil.as_ref().unwrap_or(&self.avcodec), Lib::Codec => &self.avcodec, + Lib::Format => self.avformat.as_ref().ok_or("no libavformat")?, }; // SAFETY: the caller guarantees the type; the library stays loaded // for the life of the process (it is never dropped, see `Libs`). diff --git a/crates/voelin-media/src/lib.rs b/crates/voelin-media/src/lib.rs index 6f8c151..904653a 100644 --- a/crates/voelin-media/src/lib.rs +++ b/crates/voelin-media/src/lib.rs @@ -70,6 +70,9 @@ pub enum Error { CaptureUnavailable { backend: &'static str, reason: String }, #[error("{backend} capture: {message}")] Capture { backend: &'static str, message: String }, + /// A studio output (WHIP, RTMP) failed or was refused. + #[error("{output}: {message}")] + Output { output: &'static str, message: String }, #[error("capture source not found: {0:?}")] SourceNotFound(SourceId), #[error("the user cancelled the capture")] diff --git a/crates/voelin-media/src/studio/mod.rs b/crates/voelin-media/src/studio/mod.rs index b444c58..3941706 100644 --- a/crates/voelin-media/src/studio/mod.rs +++ b/crates/voelin-media/src/studio/mod.rs @@ -91,7 +91,8 @@ pub struct SourceChange { pub enum OutputSpec { /// Record to a file; the name decides WebM or Matroska. Record { path: PathBuf }, - /// WHIP (or RTMP, which says it is not implemented yet). + /// WHIP (`http(s)://`, `token`: the bearer token) or RTMP + /// (`rtmp(s)://`, `token`: the stream key, unless it ends the URL). Url { url: String, token: Option }, } @@ -724,11 +725,12 @@ impl Studio { OutputSpec::Record { path } => { (Box::new(output::record::Recorder::start(path, layer, 2)?), false) } + OutputSpec::Url { url, token } if output::rtmp::Rtmp::handles(url) => { + let codec = *lock(&self.shared.codec); + let rtmp = output::rtmp::Rtmp::start(url, token.as_deref(), layer, codec).await?; + (Box::new(rtmp), true) + } OutputSpec::Url { url, token } => { - if output::rtmp::Rtmp::handles(url) { - return Err(output::rtmp::Rtmp::connect(url, token.as_deref()) - .expect_err("the RTMP seam always refuses")); - } #[cfg(feature = "whip")] { let codec = self.stream_codec(); @@ -738,6 +740,7 @@ impl Studio { } #[cfg(not(feature = "whip"))] { + let _ = (url, token); return Err(Error::CaptureUnavailable { backend: "whip", reason: "this build has no WHIP output (feature `whip`)".into(), @@ -1052,7 +1055,7 @@ fn stats_loop(shared: &Shared) { name: output.sink.name().to_owned(), bytes, kbps: output.kbps, - error: output.error.clone(), + error: output.error.clone().or_else(|| output.sink.error()), }); } stats @@ -1308,7 +1311,8 @@ mod tests { assert!(outputs[0].sink.bytes() > 0); } assert!(lock(&studio.shared.replay).stats().packets > 0); - // An RTMP url is refused with its reason, not silently dropped. + // RTMP carries H.264: with VP8 as the stream codec it is refused + // with that reason, before anything connects. let e = studio .apply(Command::AddOutput(OutputSpec::Url { url: "rtmp://live.example/app".into(), @@ -1317,7 +1321,7 @@ mod tests { .await .unwrap_err() .to_string(); - assert!(e.contains("FFmpeg"), "{e}"); + assert!(e.contains("H.264") && e.contains("VP8"), "{e}"); // The studio is a capture backend the streamer can use unchanged. let mut capture = studio.capture(); diff --git a/crates/voelin-media/src/studio/output/flv.rs b/crates/voelin-media/src/studio/output/flv.rs new file mode 100644 index 0000000..81a016e --- /dev/null +++ b/crates/voelin-media/src/studio/output/flv.rs @@ -0,0 +1,203 @@ +//! FLV tags: what libavformat's RTMP protocol takes, one RTMP message per +//! tag. Its writer reads a 13-byte file header first, then per tag the +//! 11-byte tag header, the body and the 4-byte size after it, so what goes +//! into an RTMP connection is exactly an FLV file. +//! +//! Only what a live stream needs: the script tag with `onMetaData` (AMF0), +//! H.264 as AVC tags (a sequence header with the `avcC` record, then NAL +//! units with 4-byte lengths, no B-frames so composition time 0) and AAC (a +//! sequence header with the `AudioSpecificConfig`, then raw frames). + +use crate::studio::output::ebml; + +/// The file header (audio and video), and the size of the tag before the +/// first one (0). +pub const HEADER: [u8; 13] = [b'F', b'L', b'V', 1, 0x05, 0, 0, 0, 9, 0, 0, 0, 0]; + +/// Tag types. +pub const AUDIO: u8 = 8; +pub const VIDEO: u8 = 9; +pub const SCRIPT: u8 = 18; + +/// The audio tag flags of AAC: format 10, "44 kHz" (what FLV says for any +/// AAC rate; the sequence header has the real one), 16 bit, stereo. +const AAC_FLAGS: u8 = 0xAF; +/// The video tag codec id of H.264 (AVC). +const AVC: u8 = 7; + +/// Append one tag of `kind` at `ms` (milliseconds; FLV keeps 32 bits) whose +/// body `body` appends. +pub fn tag(out: &mut Vec, kind: u8, ms: u32, body: impl FnOnce(&mut Vec)) { + let start = out.len(); + out.push(kind); + out.extend_from_slice(&[0; 3]); // body size, below + out.extend_from_slice(&ms.to_be_bytes()[1..]); + out.push((ms >> 24) as u8); + out.extend_from_slice(&[0; 3]); // stream id + let body_start = out.len(); + body(out); + let size = (out.len() - body_start) as u32; + out[start + 1..start + 4].copy_from_slice(&size.to_be_bytes()[1..]); + out.extend_from_slice(&(size + 11).to_be_bytes()); +} + +/// What `onMetaData` says about the stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Metadata { + pub width: u32, + pub height: u32, + /// Audio sample rate (Hz) and channels. + pub sample_rate: u32, + pub channels: u16, +} + +/// The body of the script tag: `onMetaData` and an ECMA array. +pub fn metadata(out: &mut Vec, meta: &Metadata) { + fn string(out: &mut Vec, text: &str) { + out.extend_from_slice(&(text.len() as u16).to_be_bytes()); + out.extend_from_slice(text.as_bytes()); + } + enum Value<'a> { + Number(f64), + Bool(bool), + Text(&'a str), + } + let entries = [ + ("duration", Value::Number(0.0)), + ("width", Value::Number(f64::from(meta.width))), + ("height", Value::Number(f64::from(meta.height))), + ("videocodecid", Value::Number(f64::from(AVC))), + ("audiocodecid", Value::Number(10.0)), + ("audiosamplerate", Value::Number(f64::from(meta.sample_rate))), + ("audiosamplesize", Value::Number(16.0)), + ("stereo", Value::Bool(meta.channels > 1)), + ("encoder", Value::Text("Voelin")), + ]; + out.push(2); + string(out, "onMetaData"); + out.push(8); + out.extend_from_slice(&(entries.len() as u32).to_be_bytes()); + for (key, value) in entries { + string(out, key); + match value { + Value::Number(n) => { + out.push(0); + out.extend_from_slice(&n.to_be_bytes()); + } + Value::Bool(b) => out.extend_from_slice(&[1, u8::from(b)]), + Value::Text(t) => { + out.push(2); + string(out, t); + } + } + } + out.extend_from_slice(&[0, 0, 9]); +} + +/// The body of the AVC sequence header: the `avcC` record +/// ([`ebml::avcc`]). +pub fn avc_sequence_header(out: &mut Vec, avcc: &[u8]) { + out.extend_from_slice(&[0x10 | AVC, 0, 0, 0, 0]); + out.extend_from_slice(avcc); +} + +/// The body of one H.264 frame given in Annex B: its NAL units with 4-byte +/// lengths (access unit delimiters left out, as in a recording). +pub fn avc_frame(out: &mut Vec, keyframe: bool, annex_b: &[u8]) { + let frame_type = if keyframe { 0x10 } else { 0x20 }; + out.extend_from_slice(&[frame_type | AVC, 1, 0, 0, 0]); + for unit in ebml::annex_b_units(annex_b) { + if unit[0] & 0x1F == 9 { + continue; + } + out.extend_from_slice(&(unit.len() as u32).to_be_bytes()); + out.extend_from_slice(unit); + } +} + +/// The body of the AAC sequence header. +pub fn aac_sequence_header(out: &mut Vec, audio_specific_config: &[u8]) { + out.extend_from_slice(&[AAC_FLAGS, 0]); + out.extend_from_slice(audio_specific_config); +} + +/// The body of one raw AAC frame. +pub fn aac_frame(out: &mut Vec, data: &[u8]) { + out.extend_from_slice(&[AAC_FLAGS, 1]); + out.extend_from_slice(data); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The tags of an FLV stream: (type, time, body). + fn tags(mut data: &[u8]) -> Vec<(u8, u32, Vec)> { + let mut tags = Vec::new(); + while data.len() >= 11 { + let size = u32::from_be_bytes([0, data[1], data[2], data[3]]) as usize; + let ms = u32::from_be_bytes([data[7], data[4], data[5], data[6]]); + tags.push((data[0], ms, data[11..11 + size].to_vec())); + let previous = u32::from_be_bytes(data[11 + size..15 + size].try_into().unwrap()); + assert_eq!(previous as usize, size + 11); + data = &data[15 + size..]; + } + assert!(data.is_empty()); + tags + } + + #[test] + fn tags_have_sizes_and_times() { + let mut out = Vec::new(); + tag(&mut out, AUDIO, 21, |b| aac_frame(b, &[1, 2, 3])); + // Times past 24 bits use the extension byte. + tag(&mut out, VIDEO, 0x0123_4567, |b| avc_frame(b, false, &[0, 0, 0, 1, 0x41, 9, 9])); + let tags = tags(&out); + assert_eq!(tags[0], (AUDIO, 21, vec![0xAF, 1, 1, 2, 3])); + assert_eq!(tags[1], (VIDEO, 0x0123_4567, vec![0x27, 1, 0, 0, 0, 0, 0, 0, 3, 0x41, 9, 9])); + } + + #[test] + fn h264_becomes_length_prefixed() { + let keyframe = [ + 0, 0, 0, 1, 0x09, 0xF0, // access unit delimiter: dropped + 0, 0, 0, 1, 0x67, 0x64, 0x00, 0x1F, 0xAC, // SPS + 0, 0, 1, 0x68, 0xEE, 0x3C, // PPS + 0, 0, 0, 1, 0x65, 0x88, 0x84, // IDR slice + ]; + let mut body = Vec::new(); + avc_frame(&mut body, true, &keyframe); + assert_eq!( + body, + [ + 0x17, 1, 0, 0, 0, 0, 0, 0, 5, 0x67, 0x64, 0x00, 0x1F, 0xAC, 0, 0, 0, 3, 0x68, 0xEE, + 0x3C, 0, 0, 0, 3, 0x65, 0x88, 0x84 + ] + ); + let avcc = ebml::avcc(&keyframe).unwrap(); + let mut header = Vec::new(); + avc_sequence_header(&mut header, &avcc); + assert_eq!(&header[..5], [0x17, 0, 0, 0, 0]); + // avcC: version 1, profile 100, compatibility 0, level 31. + assert_eq!(&header[5..9], [1, 0x64, 0x00, 0x1F]); + } + + #[test] + fn metadata_is_amf0() { + let mut body = Vec::new(); + metadata( + &mut body, + &Metadata { width: 1280, height: 720, sample_rate: 48_000, channels: 2 }, + ); + assert_eq!(&body[..13], b"\x02\x00\x0aonMetaData"); + assert_eq!(body[13], 8); + assert_eq!(u32::from_be_bytes(body[14..18].try_into().unwrap()), 9); + assert!(body.ends_with(&[0, 0, 9])); + let width = body.windows(5).position(|w| w == b"width").unwrap() + 5; + assert_eq!(body[width], 0); + assert_eq!(f64::from_be_bytes(body[width + 1..width + 9].try_into().unwrap()), 1280.0); + let stereo = body.windows(6).position(|w| w == b"stereo").unwrap() + 6; + assert_eq!(&body[stereo..stereo + 2], [1, 1]); + assert_eq!(HEADER.len(), 13); + } +} diff --git a/crates/voelin-media/src/studio/output/mod.rs b/crates/voelin-media/src/studio/output/mod.rs index f9f6472..8ea9d5d 100644 --- a/crates/voelin-media/src/studio/output/mod.rs +++ b/crates/voelin-media/src/studio/output/mod.rs @@ -9,7 +9,8 @@ //! out as a clip without re-encoding //! - [`whip`]: WHIP (WebRTC-HTTP ingestion) to a broadcast service (feature //! `whip`) -//! - [`rtmp`]: the seam for RTMP, which will go through the FFmpeg loader +//! - [`rtmp`]: RTMP and RTMPS through libavformat loaded at runtime, with +//! FLV of our own ([`flv`]) and the audio as AAC //! //! A sink never stalls the encoder: [`OutputSink::write`] returns an error //! instead of blocking for long, and the studio drops the sink and reports @@ -19,6 +20,7 @@ use crate::Result; use crate::codec::Codec; pub mod ebml; +pub mod flv; pub mod record; pub mod replay; pub mod rtmp; @@ -101,6 +103,12 @@ pub trait OutputSink: Send { fn bytes(&self) -> u64 { 0 } + + /// A problem the output reports while it keeps going (a connection + /// being made again), for the stats. + fn error(&self) -> Option { + None + } } #[cfg(test)] diff --git a/crates/voelin-media/src/studio/output/rtmp.rs b/crates/voelin-media/src/studio/output/rtmp.rs index 8c8e888..77539b6 100644 --- a/crates/voelin-media/src/studio/output/rtmp.rs +++ b/crates/voelin-media/src/studio/output/rtmp.rs @@ -1,58 +1,603 @@ -//! RTMP: the seam only. +//! RTMP and RTMPS: pushing the studio to a broadcast service (Twitch, +//! YouTube, an nginx-rtmp, anything that takes what OBS sends). //! -//! RTMP will go out through the FFmpeg libraries the crate already loads at -//! runtime ([`crate::ffmpeg`]): `libavformat` speaks `rtmp://` and -//! `rtmps://`, so the studio will hand it the same encoded packets it hands -//! every other output and never link or ship an RTMP stack of its own. +//! The connection is libavformat's, loaded at runtime with the rest of +//! FFmpeg ([`crate::ffmpeg::avio`]): its `rtmp://` and `rtmps://` protocols +//! do the handshake, `connect`, `publish` and TLS, and take an FLV byte +//! stream. The FLV is ours ([`flv`]), as the recordings' Matroska is, so no +//! libavformat struct is touched; the one field read is where a failed +//! write lands, found at load. //! -//! What is missing is the muxer side of that loader (`avformat_alloc_output_ -//! context2`, `av_interleaved_write_frame` and the bitstream filters H.264 -//! and AAC need in FLV). Until then [`Rtmp::connect`] says so rather than -//! pretending, so a scene file or a `voelinctl` command that names an RTMP -//! output fails with a reason instead of silently dropping the stream. +//! - Video: the studio's H.264 packets of one layer, as they are (no second +//! encode). Another stream codec is refused with the reason: classic RTMP +//! carries H.264 only. +//! - Audio: the studio's Opus, decoded and encoded as AAC-LC by FFmpeg's own +//! codecs ([`crate::ffmpeg::audio`]) on the output's thread. +//! - The stream key: in the URL (`rtmp://host/app/key`) or given apart (the +//! output's token), then sent as the play path with the URL's path as the +//! application. The output's name never shows the key. +//! +//! A thread of its own runs the connection, fed through a bounded queue, so +//! a slow upload never holds up an encoder: a full queue drops the packet, +//! and video resumes at the next keyframe (which it asks for). A connection +//! that fails is made again, after 1, 2, 4, ... up to 30 seconds, for as +//! long as the output exists, each new one starting at a keyframe; the +//! first connection is made by [`Rtmp::start`], so a wrong address or key +//! fails right there. [`OutputSink::finish`] (End Stream) unpublishes and +//! closes, cutting a dead network off after a few seconds. +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use crate::codec::Codec; use crate::studio::output::{OutputSink, Packet, Track}; use crate::{Error, Result}; -/// An RTMP output. Not implemented yet; see the [module docs](self). -#[derive(Debug)] -pub struct Rtmp { +/// Packets waiting for the connection's thread: about two seconds of a +/// 60 fps stream with its audio. +const QUEUE: usize = 256; +/// The AAC bitrate (bit/s): what the big services recommend. +pub const AAC_BITRATE: u64 = 160_000; +/// How long a connection may wait for the network (connecting, a send) +/// before it is given up and made again. +const TIMEOUT: Duration = Duration::from_secs(10); +/// Waits between connection attempts: doubling from the first to the last. +const BACKOFF: (Duration, Duration) = (Duration::from_secs(1), Duration::from_secs(30)); +/// How long closing may take (unpublish) before the network is cut off. +const CLOSE_GRACE: Duration = Duration::from_secs(3); +/// Audio kept while waiting for the first keyframe (as a recording does). +const BACKLOG_MS: i64 = 2_000; +/// Audio waits for the video of its time at most this long (it is written in +/// time order with the video, and the video comes later: the encoders' delay). +const INTERLEAVE_MS: i64 = 1_000; + +fn error(message: impl Into) -> Error { + Error::Output { output: "RTMP", message: message.into() } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Why `codec` cannot go out over RTMP. +fn unsupported(codec: Codec) -> Error { + error(format!( + "RTMP carries H.264 video; the stream encodes {codec}. Choose H.264 as the stream codec \ + for this output" + )) +} + +/// Where to connect: the URL libavformat opens, its protocol options and a +/// name for the UI that does not show the stream key. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Target { url: String, + options: Vec<(&'static str, String)>, + name: String, +} + +impl Target { + fn new(url: &str, key: Option<&str>) -> Result { + let url = url.trim(); + let lower = url.to_ascii_lowercase(); + let rest = ["rtmp://", "rtmps://"] + .iter() + .find_map(|scheme| lower.starts_with(scheme).then(|| &url[scheme.len()..])) + .ok_or_else(|| error(format!("not an RTMP address: {url}")))?; + let (host, path) = rest.split_once('/').unwrap_or((rest, "")); + if host.is_empty() { + return Err(error(format!("no server in {url}"))); + } + let mut options = vec![ + ("rw_timeout", TIMEOUT.as_micros().to_string()), + // Small tags (audio) go out at once. + ("tcp_nodelay", "1".to_owned()), + ]; + let name = match key.map(str::trim).filter(|k| !k.is_empty()) { + Some(key) => { + let app = path.trim_matches('/'); + if !app.is_empty() { + options.push(("rtmp_app", app.to_owned())); + } + options.push(("rtmp_playpath", key.to_owned())); + url.trim_end_matches('/').to_owned() + } + // The key is the last part of the path. + None => match url.trim_end_matches('/').rsplit_once('/') { + Some((base, _)) if path.trim_matches('/').contains('/') => format!("{base}/…"), + _ => url.to_owned(), + }, + }; + Ok(Self { url: url.to_owned(), options, name }) + } +} + +/// One packet on its way to the connection's thread. +struct Queued { + video: bool, + keyframe: bool, + pts_90khz: u64, + width: u32, + height: u32, + data: Vec, +} + +/// What an RTMP output is doing. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RtmpStats { + /// Connected and publishing. + pub connected: bool, + /// Bytes sent (FLV), over all connections. + pub bytes: u64, + /// FLV tags sent. + pub tags: u64, + /// Packets dropped because the upload could not keep up, or while + /// disconnected. + pub dropped: u64, + /// Connections made again after one failed. + pub reconnects: u64, + /// The last failure, while it is not connected. + pub error: Option, +} + +#[derive(Default)] +struct Shared { + /// End the connection (cleanly). + stop: AtomicBool, + /// Interrupt whatever FFmpeg is waiting for. + abort: Arc, + /// A keyframe is wanted; taken by [`OutputSink::needs_keyframe`]. + keyframe: AtomicBool, + connected: AtomicBool, + bytes: AtomicU64, + tags: AtomicU64, + dropped: AtomicU64, + reconnects: AtomicU64, + error: Mutex>, +} + +/// An RTMP output; see the [module docs](self). Closes when dropped. +pub struct Rtmp { + name: String, + layer: u32, + queue: Option>, + thread: Option>, + shared: Arc, + /// A video packet was dropped: no more video until a keyframe. + skip_video: bool, } impl Rtmp { - /// Whether `url` is one this output would take. + /// Whether `url` is one this output takes. pub fn handles(url: &str) -> bool { + let url = url.trim_start().to_ascii_lowercase(); url.starts_with("rtmp://") || url.starts_with("rtmps://") } - /// Always fails for now, with what is missing. - pub fn connect(url: &str, _key: Option<&str>) -> Result { - Err(Error::CodecUnavailable { - codec: crate::codec::Codec::H264, - reason: format!( - "RTMP ({url}) needs the muxing side of the FFmpeg loader, which is not \ - written yet; record to a file or use WHIP" - ), - }) + /// Connect to `url` and push `layer` of the studio and its audio. The + /// stream key is the last part of the URL's path, or `key` if given. + /// `codec` is what the studio encodes, if known: anything but H.264 is + /// refused (also later, when its first packet comes). + /// + /// Fails when there is no FFmpeg with libavformat, or the first + /// connection does (a wrong address, a refused key). + pub async fn start( + url: &str, + key: Option<&str>, + layer: u32, + codec: Option, + ) -> Result { + if let Some(codec) = codec.filter(|c| *c != Codec::H264) { + return Err(unsupported(codec)); + } + let target = Target::new(url, key)?; + #[cfg(not(feature = "ffmpeg"))] + { + let _ = (target, layer); + Err(error("this build has no FFmpeg (feature `ffmpeg`), which RTMP goes through")) + } + #[cfg(feature = "ffmpeg")] + { + session::start(target, layer).await + } } - pub fn url(&self) -> &str { - &self.url + pub fn stats(&self) -> RtmpStats { + let shared = &self.shared; + let connected = shared.connected.load(Ordering::Relaxed); + RtmpStats { + connected, + bytes: shared.bytes.load(Ordering::Relaxed), + tags: shared.tags.load(Ordering::Relaxed), + dropped: shared.dropped.load(Ordering::Relaxed), + reconnects: shared.reconnects.load(Ordering::Relaxed), + error: if connected { None } else { lock(&shared.error).clone() }, + } + } + + /// Unpublish and close; a network that does not answer is cut off + /// after [`CLOSE_GRACE`]. + fn teardown(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.queue = None; + let Some(thread) = self.thread.take() else { return }; + let deadline = Instant::now() + CLOSE_GRACE; + while !thread.is_finished() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + self.shared.abort.store(true, Ordering::Relaxed); + let _ = thread.join(); + } +} + +impl Drop for Rtmp { + fn drop(&mut self) { + self.teardown(); } } impl OutputSink for Rtmp { fn name(&self) -> &str { - &self.url + &self.name } - fn wants(&self, _track: Track) -> bool { - true + fn wants(&self, track: Track) -> bool { + match track { + Track::Video { layer, .. } => layer == self.layer, + Track::Audio { .. } => true, + } } - fn write(&mut self, _packet: &Packet<'_>) -> Result<()> { - Err(Error::Capture { backend: "rtmp", message: "RTMP is not implemented".into() }) + fn needs_keyframe(&mut self) -> bool { + self.shared.keyframe.swap(false, Ordering::Relaxed) + } + + fn write(&mut self, packet: &Packet<'_>) -> Result<()> { + let Some(queue) = &self.queue else { return Ok(()) }; + if let Track::Video { codec, layer } = packet.track { + if layer != self.layer { + return Ok(()); + } + if codec != Codec::H264 { + return Err(unsupported(codec)); + } + if self.skip_video { + if !packet.keyframe { + return Ok(()); + } + self.skip_video = false; + } + } + let queued = Queued { + video: packet.track.is_video(), + keyframe: packet.keyframe, + pts_90khz: packet.pts_90khz, + width: packet.width, + height: packet.height, + data: packet.data.to_vec(), + }; + match queue.try_send(queued) { + Ok(()) => Ok(()), + Err(std::sync::mpsc::TrySendError::Full(queued)) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + if queued.video { + self.skip_video = true; + self.shared.keyframe.store(true, Ordering::Relaxed); + } + Ok(()) + } + Err(std::sync::mpsc::TrySendError::Disconnected(_)) => Err(error( + lock(&self.shared.error).clone().unwrap_or_else(|| "the RTMP output ended".into()), + )), + } + } + + fn finish(&mut self) -> Result<()> { + self.teardown(); + Ok(()) + } + + fn bytes(&self) -> u64 { + self.shared.bytes.load(Ordering::Relaxed) + } + + fn error(&self) -> Option { + self.stats().error + } +} + +/// The connection's thread. +#[cfg(feature = "ffmpeg")] +mod session { + use std::collections::VecDeque; + use std::sync::Arc; + use std::sync::atomic::Ordering; + use std::sync::mpsc::{Receiver, RecvTimeoutError, sync_channel}; + use std::time::{Duration, Instant}; + + use tracing::{debug, warn}; + + use super::{ + AAC_BITRATE, BACKLOG_MS, BACKOFF, INTERLEAVE_MS, QUEUE, Queued, Rtmp, Shared, Target, + error, lock, + }; + use crate::Result; + use crate::ffmpeg::audio::{AUDIO_SPECIFIC_CONFIG, AacEncoder, RATE}; + use crate::ffmpeg::avio::Connection; + use crate::studio::output::{ebml, flv}; + + /// How often a thread that waits checks whether to stop. + const POLL: Duration = Duration::from_millis(100); + + pub(super) async fn start(target: Target, layer: u32) -> Result { + Connection::available().map_err(error)?; + let aac = AacEncoder::new(AAC_BITRATE).map_err(error)?; + let shared = Arc::new(Shared::default()); + let (queue, packets) = sync_channel(QUEUE); + let (ready, first) = tokio::sync::oneshot::channel(); + let name = target.name.clone(); + let worker = Worker { target, shared: shared.clone(), packets, aac, buf: Vec::new() }; + let thread = std::thread::Builder::new() + .name("voelin-rtmp".into()) + .spawn(move || worker.run(ready)) + .map_err(|e| error(e.to_string()))?; + match first.await { + Ok(Ok(())) => {} + Ok(Err(e)) => { + let _ = thread.join(); + return Err(error(e)); + } + Err(_) => return Err(error("the RTMP thread ended")), + } + debug!(name, "RTMP output connected"); + Ok(Rtmp { + name, + layer, + queue: Some(queue), + thread: Some(thread), + shared, + skip_video: false, + }) + } + + struct Worker { + target: Target, + shared: Arc, + packets: Receiver, + aac: AacEncoder, + /// The tags being sent. + buf: Vec, + } + + /// What one connection has sent. + #[derive(Default)] + struct Publish { + /// The sequence headers went out (at the first keyframe), and the + /// stream's time 0 (milliseconds on the studio's clock). + base: Option, + /// AAC frames (milliseconds on the studio's clock, data) from before + /// the first keyframe. + backlog: VecDeque<(i64, Vec)>, + /// AAC frames (stream time) waiting for the video of their time. + audio: VecDeque<(i64, Vec)>, + /// The stream time of the last video tag. + video: Option, + /// When the last keyframe request went out, while waiting for one. + asked: Option, + } + + impl Worker { + fn stopped(&self) -> bool { + self.shared.stop.load(Ordering::Relaxed) + } + + fn open(&self) -> std::result::Result { + let options: Vec<(&str, &str)> = + self.target.options.iter().map(|(k, v)| (*k, v.as_str())).collect(); + Connection::open(&self.target.url, &options, self.shared.abort.clone()) + } + + fn run(mut self, ready: tokio::sync::oneshot::Sender>) { + let mut connection = match self.open() { + Ok(connection) => { + let _ = ready.send(Ok(())); + Some(connection) + } + Err(e) => { + let _ = ready.send(Err(e)); + return; + } + }; + let mut backoff = BACKOFF.0; + while !self.stopped() { + let connection = match connection.take() { + Some(connection) => connection, + None => { + if !self.wait(backoff) { + break; + } + match self.open() { + Ok(connection) => { + self.shared.reconnects.fetch_add(1, Ordering::Relaxed); + backoff = BACKOFF.0; + connection + } + Err(e) => { + self.fail(format!("cannot connect again: {e}")); + backoff = (backoff * 2).min(BACKOFF.1); + continue; + } + } + } + }; + self.shared.connected.store(true, Ordering::Relaxed); + *lock(&self.shared.error) = None; + let result = self.publish(connection); + self.shared.connected.store(false, Ordering::Relaxed); + match result { + Ok(()) => break, + Err(e) => self.fail(e), + } + } + debug!(name = self.target.name, "RTMP output closed"); + } + + /// Wait `time` while dropping what comes in; `false` once stopped. + fn wait(&self, time: Duration) -> bool { + let until = Instant::now() + time; + while !self.stopped() { + let now = Instant::now(); + if now >= until { + return true; + } + match self.packets.recv_timeout((until - now).min(POLL)) { + Ok(_) => { + self.shared.dropped.fetch_add(1, Ordering::Relaxed); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return false, + } + } + false + } + + fn fail(&self, message: String) { + warn!(name = self.target.name, "RTMP: {message}"); + *lock(&self.shared.error) = Some(message); + } + + /// Send what comes in over `connection` until stopped (`Ok`: closed + /// cleanly) or until it fails. + fn publish(&mut self, mut connection: Connection) -> std::result::Result<(), String> { + connection.write(&flv::HEADER)?; + let mut publish = Publish::default(); + self.ask_keyframe(&mut publish); + loop { + if self.stopped() { + return connection.close(); + } + match self.packets.recv_timeout(POLL) { + Ok(packet) => self.packet(&mut connection, &mut publish, packet)?, + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return connection.close(), + } + } + } + + fn ask_keyframe(&self, publish: &mut Publish) { + publish.asked = Some(Instant::now()); + self.shared.keyframe.store(true, Ordering::Relaxed); + } + + fn packet( + &mut self, + connection: &mut Connection, + publish: &mut Publish, + packet: Queued, + ) -> std::result::Result<(), String> { + self.buf.clear(); + if packet.video { + self.video(publish, &packet); + } else { + self.audio(publish, &packet); + } + if self.buf.is_empty() { + return Ok(()); + } + connection.write(&self.buf)?; + connection.flush()?; + self.shared.bytes.fetch_add(self.buf.len() as u64, Ordering::Relaxed); + Ok(()) + } + + /// Append the tags a video packet makes to `self.buf`. + fn video(&mut self, publish: &mut Publish, packet: &Queued) { + let ms = (packet.pts_90khz / 90) as i64; + let base = match publish.base { + Some(base) => base, + None => { + // The stream starts at a keyframe that carries the + // parameter sets the AVC sequence header needs. + let avcc = packet.keyframe.then(|| ebml::avcc(&packet.data)).flatten(); + let Some(avcc) = avcc else { + if publish.asked.is_none_or(|t| t.elapsed() > Duration::from_millis(500)) { + self.ask_keyframe(publish); + } + return; + }; + let meta = flv::Metadata { + width: packet.width, + height: packet.height, + sample_rate: RATE, + channels: 2, + }; + self.tag(flv::SCRIPT, 0, |b| flv::metadata(b, &meta)); + self.tag(flv::VIDEO, 0, |b| flv::avc_sequence_header(b, &avcc)); + self.tag(flv::AUDIO, 0, |b| { + flv::aac_sequence_header(b, &AUDIO_SPECIFIC_CONFIG) + }); + publish.base = Some(ms); + // The audio of the keyframe's moment came before it. + for (time, data) in publish.backlog.drain(..) { + if time >= ms { + publish.audio.push_back((time - ms, data)); + } + } + ms + } + }; + let time = (ms - base).max(publish.video.unwrap_or(0)); + while publish.audio.front().is_some_and(|(t, _)| *t <= time) { + let (t, data) = publish.audio.pop_front().expect("checked"); + self.tag(flv::AUDIO, t, |b| flv::aac_frame(b, &data)); + } + self.tag(flv::VIDEO, time, |b| flv::avc_frame(b, packet.keyframe, &packet.data)); + publish.video = Some(time); + } + + /// Encode an Opus packet as AAC and append the audio tags that are + /// due to `self.buf`. + fn audio(&mut self, publish: &mut Publish, packet: &Queued) { + let time = (packet.pts_90khz * u64::from(RATE) / 90_000) as i64; + let mut frames = Vec::new(); + let result = self.aac.push(&packet.data, time, &mut |data, at| { + frames.push((at * 1000 / i64::from(RATE), data.to_vec())); + }); + if let Err(e) = result { + debug!("RTMP audio: {e}"); + } + for (ms, data) in frames { + match publish.base { + None => { + publish.backlog.push_back((ms, data)); + while publish.backlog.front().is_some_and(|(t, _)| *t + BACKLOG_MS < ms) { + publish.backlog.pop_front(); + } + } + Some(base) if ms >= base => publish.audio.push_back((ms - base, data)), + Some(_) => {} + } + } + // Audio goes out with the video of its time, or once the video + // is late by more than INTERLEAVE_MS. + let newest = publish.audio.back().map_or(0, |(t, _)| *t); + let video = publish.video.unwrap_or(-1); + while publish + .audio + .front() + .is_some_and(|(t, _)| *t <= video || *t + INTERLEAVE_MS < newest) + { + let (t, data) = publish.audio.pop_front().expect("checked"); + self.tag(flv::AUDIO, t, |b| flv::aac_frame(b, &data)); + } + } + + fn tag(&mut self, kind: u8, ms: i64, body: impl FnOnce(&mut Vec)) { + flv::tag(&mut self.buf, kind, ms.clamp(0, i64::from(u32::MAX)) as u32, body); + self.shared.tags.fetch_add(1, Ordering::Relaxed); + } } } @@ -61,11 +606,45 @@ mod tests { use super::*; #[test] - fn rtmp_urls_are_recognised_but_refused() { + fn urls_and_keys() { assert!(Rtmp::handles("rtmp://live.example/app")); - assert!(Rtmp::handles("rtmps://live.example/app")); + assert!(Rtmp::handles("RTMPS://live.example/app")); assert!(!Rtmp::handles("https://example/whip")); - let e = Rtmp::connect("rtmp://live.example/app", Some("key")).unwrap_err().to_string(); - assert!(e.contains("FFmpeg"), "{e}"); + + // The key in the URL: FFmpeg splits it; the name hides it. + let t = Target::new("rtmp://live.example/app/secret-key", None).unwrap(); + assert_eq!(t.url, "rtmp://live.example/app/secret-key"); + assert_eq!(t.name, "rtmp://live.example/app/…"); + assert!(!t.options.iter().any(|(k, _)| k.starts_with("rtmp_"))); + + // The key apart: the play path, the URL's path the application. + let t = Target::new("rtmps://a.rtmp.example:443/live2/", Some(" key?x=1 ")).unwrap(); + assert_eq!(t.name, "rtmps://a.rtmp.example:443/live2"); + assert!(t.options.contains(&("rtmp_app", "live2".to_owned()))); + assert!(t.options.contains(&("rtmp_playpath", "key?x=1".to_owned()))); + assert!(t.options.contains(&("rw_timeout", "10000000".to_owned()))); + assert!(!t.name.contains("key")); + + assert!(Target::new("http://example/app", None).is_err()); + assert!(Target::new("rtmp:///app", None).is_err()); + } + + #[tokio::test] + async fn other_codecs_and_dead_servers_are_refused() { + let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0, Some(Codec::Vp8)) + .await + .err() + .expect("VP8 refused") + .to_string(); + assert!(e.contains("H.264"), "{e}"); + // Port 1 on loopback: nothing listens. + if crate::ffmpeg::avio::Connection::available().is_ok() { + let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0, Some(Codec::H264)) + .await + .err() + .expect("nothing listens") + .to_string(); + assert!(!e.is_empty()); + } } } diff --git a/crates/voelin-media/src/studio/output/whip.rs b/crates/voelin-media/src/studio/output/whip.rs index 13e5355..575306b 100644 --- a/crates/voelin-media/src/studio/output/whip.rs +++ b/crates/voelin-media/src/studio/output/whip.rs @@ -40,7 +40,7 @@ use crate::{Error, Result}; const QUEUE: usize = 256; fn error(message: impl Into) -> Error { - Error::Capture { backend: "whip", message: message.into() } + Error::Output { output: "WHIP", message: message.into() } } fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { @@ -292,6 +292,10 @@ impl OutputSink for Whip { fn bytes(&self) -> u64 { self.shared.bytes.load(Ordering::Relaxed) } + + fn error(&self) -> Option { + lock(&self.shared.error).clone() + } } /// An RTC that offers exactly `codec` and, if `audio`, Opus. diff --git a/docs/media.md b/docs/media.md index b121203..e058807 100644 --- a/docs/media.md +++ b/docs/media.md @@ -30,6 +30,7 @@ video, recording, a replay buffer, WHIP) is described in | `EncoderReport { ffmpeg, zero_copy, encoders: Vec }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference | | `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling | | `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | +| `ffmpeg::avio::Connection`, `ffmpeg::audio::AacEncoder` | bytes written through libavformat's protocols (`rtmp://`, `rtmps://`) with their write errors and an abort flag; the studio's Opus as AAC through FFmpeg's own codecs. See [RTMP output](#rtmp-output) | | `ffmpeg::{GpuConverter, GpuLayer}` | an RGB DMA-BUF converted to NV12 and scaled for every simulcast layer on the GPU (`convert(&DmaBufRef, &[GpuLayer], out)`), `modifiers()` it imports; see zero-copy under [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) | | `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user | | `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool`; `accepts_dmabuf()`, `dmabuf(&DmaBufRef) -> Option` (a frame still in GPU memory, offered before it is mapped) and `dmabuf_modifiers()` (tiled layouts the sink imports) | @@ -289,8 +290,8 @@ the software encoders above are used as before. `/usr/local/lib`) and MacPorts (`/opt/local/lib`) (macOS). No version is refused. libavutil's functions come from the libavutil libavcodec itself loaded (through its handle; on Windows the already loaded DLL), so the two - always match; libavformat of the same major is opened if present (for RTMP - output later). `VOELIN_FFMPEG=0` disables FFmpeg. Only functions are + always match; libavformat of the same major is opened if present (for + [RTMP output](#rtmp-output)). `VOELIN_FFMPEG=0` disables FFmpeg. Only functions are looked up by name (`sys.rs`); FFmpeg's warnings and errors go to `tracing` (target `ffmpeg`) and into the self-test's failure reasons. - ABI across major versions: every codec setting goes through AVOptions @@ -469,6 +470,56 @@ the software encoders above are used as before. (no compression metadata); the portal offers it ahead of LINEAR (see [Capture](#capture)). See [the measurements](#zero-copy-measured). +### RTMP output + +The studio's RTMP output ([studio.md](studio.md#outputs-studiooutput)) +goes through the same runtime-loaded FFmpeg, libavformat included, and +links nothing. + +- Connection (`ffmpeg/avio.rs`): `avio_open2` with libavformat's own + `rtmp://` / `rtmps://` protocols (handshake, `connect`, `publish`, TLS), + `avio_write`, `avio_flush`, `avio_closep` (unpublish). Five functions and + `AVIOInterruptCB` (two fields, unchanged since libavformat 53): every + blocking call polls an abort flag, so a stop or a stuck network never + holds a thread for longer than FFmpeg's 100 ms poll once it is set; + `rw_timeout` (10 s) bounds a connect or a send to a server that stopped + answering. Protocol options go in as an `AVDictionary` (`rtmp_app`, + `rtmp_playpath` for a key given apart, `tcp_nodelay`). +- What it sends is FLV (`studio/output/flv.rs`): libavformat's RTMP writer + reads an FLV byte stream and sends each tag as an RTMP message, so the + FLV is written by us like the recordings' Matroska and no muxer + (`AVFormatContext`, `AVStream`, codec parameters, all of which moved + between releases) is ever used. +- Write errors: `avio_write` and `avio_flush` return nothing; a failed + write is only stored in `AVIOContext.error`, which moved (120 bytes in + libavformat 58, 84 in 63). It is found at load by search + (`layout::avio_error`): a context of our own whose write callback fails + with a sentinel value is flushed, and the one `int` of its first 200 + bytes that changed to the sentinel is the field. Checked against the + `offsetof` of FFmpeg 4.4.8 and 9.0.1. +- Audio (`ffmpeg/audio.rs`): RTMP services take AAC, so the studio's Opus + is decoded by FFmpeg's `opus` decoder and encoded by its native `aac` + encoder (AAC-LC, 48 kHz stereo, 160 kbit/s; `AudioSpecificConfig` + `11 90`). An audio encoder needs its sample format before it opens, and + `AVCodecContext.sample_fmt` has no AVOption: it is located like + `hw_frames_ctx`, from the option offsets of its neighbours (after + `sample_rate` directly from libavcodec 61 with `ch_layout` after it; + after `channels` up to 60), and checked to be `NONE` in a new context. + The encoder takes 1024-sample frames and Opus gives 960, so the samples + are queued and cut into frames of our own; such a frame needs its + channel layout, whose field also moved (`ch_layout` from libavutil 57, + `channels` and `channel_layout` before), and `avcodec_send_frame` copies + frames with `av_frame_ref`, which refuses one without a layout unless its + buffers are reference-counted. So the encoder's input frame is a + reference to the first frame the decoder made (FFmpeg filled in layout, + rate, format and buffer references), with only its leading fields + (`data`, `linesize`, `nb_samples`, unchanged since libavutil 51) and + `pts` pointed at our planes; the decoded buffers it keeps are never read. + The AAC frames carry the Opus packets' clock (less the encoder's 1024 + samples of priming), and a gap in the studio's audio restarts it. +- Without libavformat, or when a check fails, `LibraryInfo::rtmp` says why + and adding an RTMP output fails with that reason. + Installing FFmpeg (runtime libraries only, no `-dev` packages): | OS | | @@ -917,6 +968,7 @@ has not run on Windows yet. | Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested | | Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | `voelinctl stream bench --source portal` on a 2560x1440 Wayland desktop | tested: it delivered no frames at all (the DMA-BUF mapping length), and the DMA-BUF path cost 19.5 cores where shared memory costs 0.41. Both fixed; 1440p60 now runs on 0.55 cores (see the table above). Portal audio is still untested | | Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only | +| RTMP through libavformat: write errors from `AVIOContext.error`, an abort ending a stuck connect, `AVCodecContext.sample_fmt`, Opus → AAC, FLV tags, a studio stream to FFmpeg's own RTMP server read back by ffprobe, a reconnect | `ffmpeg::avio`, `ffmpeg::audio`, `ffmpeg::tests`, `studio::output::{flv, rtmp}` tests, `voelin-core/tests/studio.rs` (see [studio.md](studio.md#status)) | tested with FFmpeg 9.0.1 and 4.4.8 (`VOELIN_FFMPEG_DIR`); no public service tried. FFmpeg 4.4.8 also showed that the existing `hw_frames_ctx` check refuses its layout there (VA-API off, as designed for a failed check) | | FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-9.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04; FFmpeg 9.0.1 / libavutil 61 / libavcodec 63 on Arch, every offset compared with that release's own headers) | | FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested | | Self-test failures (NVENC without CUDA, Quick Sync without a session, VA-API without a render node, encoders not in the build) | `tests/ffmpeg.rs`, `voelinctl stream encoders` | tested: each fails alone with FFmpeg's reason | diff --git a/docs/studio.md b/docs/studio.md index c6a0e9f..b74ef81 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -3,7 +3,8 @@ The Stream Studio composites scenes of sources (screens, windows, cameras, images, text, colours) into one picture that becomes the video of our stream, and keeps or forwards what the stream's encoders make: a recording, a replay -buffer to save clips from after the fact, and WHIP to a broadcast service. It +buffer to save clips from after the fact, and WHIP or RTMP to a broadcast +service. It is the engine behind the Studio screen of the UI (scenes and sources, a live preview, LIVE / timer, the audio mixer, Record Clip, Go Live / End Stream, Share Window / Share Screen, a camera with background blur); this page is @@ -21,7 +22,7 @@ sources (a thread each) ─ Feed (latest wins) ┐ Streamer::start_studio: convert → layers → encoders ─────┼─ MediaSink (the live stream, when attached) audio sources → mixer → Opus ────┘ │ every packet of the stream codec, attached or not - └─ Studio::write_packet ─ replay buffer, recording, WHIP outputs + └─ Studio::write_packet ─ replay buffer, recording, WHIP and RTMP outputs ``` Everything is changeable while it runs, and nothing is capped: any number of @@ -165,9 +166,31 @@ fails is removed and reported, and the rest go on. that reaches the service: no STUN or TURN yet. It asks for a keyframe when it starts, when ICE comes up, when the service sends a PLI and after its queue overflowed. -- **RTMP** (`rtmp::Rtmp`): the seam only. It is meant to go through the - FFmpeg libraries loaded at runtime (libavformat's muxer side is not in the - loader yet); until then adding an `rtmp://` output fails with that reason. +- **RTMP and RTMPS** (`rtmp::Rtmp`, feature `ffmpeg`): through libavformat + loaded at runtime, never linked ([media.md](media.md#rtmp-output)). Its + `rtmp://` and `rtmps://` protocols do the handshake, `connect`, `publish` + and TLS and take an FLV byte stream; the FLV is ours (`flv`: `onMetaData`, + AVC and AAC sequence headers, then one tag per frame), as the recordings' + Matroska is, so no libavformat struct is touched. Video is the studio's + H.264 of the output's layer as encoded; another stream codec is refused + with the reason (classic RTMP carries H.264; Enhanced RTMP's HEVC, AV1, + VP9 and Opus are not written). Audio is the studio's Opus decoded and + encoded as AAC-LC (160 kbit/s, 48 kHz stereo) by FFmpeg's own `opus` + decoder and `aac` encoder, on the output's thread. The stream key is the + last part of the URL's path (`rtmp://host/app/key`) or the output's token + (sent as the play path, the URL's path as the application); the output's + name never shows it. The first connection is made when the output is + added, so a wrong address or key fails there; a connection that fails + later (the service restarting, the network) is made again after 1, 2, 4, + ... up to 30 seconds for as long as the output exists, each new one + starting at a keyframe it asks for, while the stats show why it is down. + A thread of its own runs the connection behind a bounded queue (about two + seconds): a slow upload drops packets rather than holding up an encoder, + and video resumes at the next keyframe. Audio goes out in time order with + the video (it waits for the video of its time, at most a second), and the + audio of the first keyframe's moment, which comes before the keyframe, + is kept as a recording keeps it. `EndStream` unpublishes and closes; a + network that does not answer is cut off after three seconds. Recording and the replay buffer need no live stream: a studio's streamer encodes from the start (see below). @@ -191,8 +214,8 @@ channel; late subscribers miss what came before). | `SetPreview { width, height, fps }` | the preview tap's size and rate (default 480x270 at 15 fps) | | `StartRecording { path }` / `StopRecording` | `.webm` or `.mkv` | | `SetReplay { seconds, memory_mb }` / `SaveClip { path }` | the replay buffer (0 seconds: off) | -| `AddOutput(OutputSpec::Record { path } \| Url { url, token })` / `RemoveOutput { id }` | more recordings, WHIP (`http(s)://`), RTMP (refused for now) | -| `GoLive` / `EndStream` | the studio's state for the header (LIVE, timer); `EndStream` also closes the outputs that push (WHIP push from when they are added). The TeamSpeak stream itself is started and attached as usual | +| `AddOutput(OutputSpec::Record { path } \| Url { url, token })` / `RemoveOutput { id }` | more recordings, WHIP (`http(s)://`, `token`: the bearer token), RTMP (`rtmp(s)://`, `token`: the stream key unless the URL ends with it) | +| `GoLive` / `EndStream` | the studio's state for the header (LIVE, timer); `EndStream` also closes the outputs that push (WHIP and RTMP push from when they are added). The TeamSpeak stream itself is started and attached as usual | | Event | | |---|---| @@ -251,6 +274,9 @@ voelinctl studio run scenes.json --seconds 10 --switch-to 2 \ --preview preview.png --record rec.webm --clip clip.mkv --replay 30 --tone 440 --codec vp8 # Push to a WHIP endpoint (token also from VOELIN_WHIP_TOKEN). voelinctl studio run scenes.json --seconds 60 --whip https://ingest.example/whip --token ... +# Push over RTMP(S) (H.264; the key in the URL or in --token). +voelinctl studio run scenes.json --seconds 60 --codec h264 --tone 440 \ + --rtmp rtmps://live.example/app --token # The compositor alone: compose time and heap allocations per frame. voelinctl studio bench --sources 4 --res 1920x1080 --fps 60 voelinctl studio cameras @@ -292,4 +318,6 @@ two threads) takes about 3 ms at its own rate (15 fps by default). | Screen, window and portal sources | the existing capture backends ([media.md](media.md#capture)) | as tested there; not run inside the studio here | | Background blur, image and colour backdrops on the oval mask | `segment::tests` | tested; **no person segmentation model** (see above) | | Windows and Android cameras | – | not implemented: `camera::list()` has only the test pattern there | -| RTMP | – | the seam only (refuses with its reason) | +| RTMP: the FLV tags (sizes, times past 24 bits, AVC from Annex B, `onMetaData` in AMF0), URL and key handling (the name hides the key), codecs other than H.264 and dead servers refused | `flv::tests`, `rtmp::tests` | tested | +| RTMP: write errors seen (`AVIOContext.error`, found at load), an abort ends a stuck connect, the sample format field of the AAC encoder, Opus → AAC (frames back to back from the packets' clock, priming, a gap restarts the clock) | `ffmpeg::avio::tests`, `ffmpeg::audio::tests`, `ffmpeg::tests` | tested with FFmpeg 9.0.1 (libavformat 63: `error` at 84, `sample_fmt` at 348) and FFmpeg 4.4.8 (58: 120 and 408) | +| RTMP end to end: a studio stream (H.264 through the hardware encoder, a 440 Hz tone) pushed to FFmpeg's own RTMP server (`ffmpeg -listen 1`) with the key apart from the URL; the server killed and another started on its port; `EndStream` | `voelin-core/tests/studio.rs` `a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did` | tested: ffprobe reads `h264` 320x180 and `aac` 48000 Hz stereo in both servers' files, each starting at a keyframe, every picture decodes (red), the audio decodes to 440 Hz; the key arrived as the stream name; the second server finished its file and exited by itself. No public service (Twitch, YouTube) tried; RTMPS only through FFmpeg's TLS, untried here | diff --git a/tools/voelinctl/src/studio.rs b/tools/voelinctl/src/studio.rs index d019291..02f4199 100644 --- a/tools/voelinctl/src/studio.rs +++ b/tools/voelinctl/src/studio.rs @@ -32,8 +32,9 @@ pub struct StudioArgs { #[derive(Subcommand, Debug)] enum StudioCommand { /// Run a scene file for a while: composite it, encode it as a stream - /// would, and save a preview, record, save a replay clip or push to WHIP. - Run(RunArgs), + /// would, and save a preview, record, save a replay clip or push to WHIP + /// or RTMP. + Run(Box), /// Composite N sources (a screen, a camera, an image, text, ...) into the /// output size at its frame rate, without encoding; print the compose /// time and heap allocations per frame. @@ -72,7 +73,11 @@ struct RunArgs { /// Push to this WHIP endpoint. #[arg(long)] whip: Option, - /// Bearer token for --whip. + /// Push to this RTMP(S) server (`rtmp://host/app/key`, or the key in + /// --token). Needs --codec h264 unless H.264 is the first codec. + #[arg(long)] + rtmp: Option, + /// Bearer token for --whip, stream key for --rtmp. #[arg(long, env = "VOELIN_WHIP_TOKEN", hide_env_values = true)] token: Option, /// Video codec: vp8, vp9, h264, av1 [default: the first the encoders give]. @@ -112,7 +117,7 @@ struct BenchArgs { pub fn run(args: StudioArgs) -> Result<()> { match args.command { - StudioCommand::Run(args) => tokio::runtime::Runtime::new()?.block_on(run_scenes(args)), + StudioCommand::Run(args) => tokio::runtime::Runtime::new()?.block_on(run_scenes(*args)), StudioCommand::Bench(args) => bench(&args), StudioCommand::Cameras => { for camera in camera::list() { @@ -193,7 +198,10 @@ async fn run_scenes(args: RunArgs) -> Result<()> { let outputs: Vec = stats .outputs .iter() - .map(|o| format!("{} {:.0} kbit/s", o.name, o.kbps)) + .map(|o| match &o.error { + Some(e) => format!("{} {:.0} kbit/s ({e})", o.name, o.kbps), + None => format!("{} {:.0} kbit/s", o.name, o.kbps), + }) .collect(); println!( "composed {:.0} fps, {:.2} ms; sources: {}; outputs: {}; replay {:.1} s", @@ -223,9 +231,12 @@ async fn run_scenes(args: RunArgs) -> Result<()> { if let Some(path) = &args.record { studio.apply(Command::StartRecording { path: path.clone() }).await?; } - if let Some(url) = &args.whip { - let spec = OutputSpec::Url { url: url.clone(), token: args.token.clone() }; + let pushes: Vec<&String> = args.whip.iter().chain(&args.rtmp).collect(); + for url in &pushes { + let spec = OutputSpec::Url { url: (*url).clone(), token: args.token.clone() }; studio.apply(Command::AddOutput(spec)).await?; + } + if !pushes.is_empty() { studio.apply(Command::GoLive).await?; } let run = Duration::from_secs(args.seconds); @@ -248,7 +259,7 @@ async fn run_scenes(args: RunArgs) -> Result<()> { save_png(&picture, path)?; println!("preview saved: {} ({}x{})", path.display(), picture.width, picture.height); } - if args.whip.is_some() { + if !pushes.is_empty() { studio.apply(Command::EndStream).await?; } let stats = streamer.stats();