diff --git a/crates/voelin-media/src/ffmpeg/encoder.rs b/crates/voelin-media/src/ffmpeg/encoder.rs index d2f5757..f2e2a7b 100644 --- a/crates/voelin-media/src/ffmpeg/encoder.rs +++ b/crates/voelin-media/src/ffmpeg/encoder.rs @@ -529,12 +529,29 @@ struct Session { nv12: bool, /// RGB DMA-BUFs: made on the first one; why not, if they cannot be. rgb: Option>, + /// An AMF encoder: opened and closed under [`amf_lock`]. + amf: bool, } // SAFETY: the FFmpeg objects belong to this session alone and are used from // one thread at a time (`&mut self`). unsafe impl Send for Session {} +/// Held while an AMF encoder is opened or closed. +/// +/// AMD's AMF runtime keeps process-wide state that is not safe to use from +/// two threads at once: its factory helper loads and unloads libraries +/// (`AMFFactoryHelper::Init` / `Terminate`, `dlclose`) while it creates the +/// Vulkan device of a new encoder. Opened on several threads together, as +/// the probe and simulcast layers do, one thread's `Terminate` unloads what +/// another's `Init` uses: SIGSEGV in `libamfrt64` inside `avcodec_open2`. +/// Measured with probes under Xvfb, several processes at once: 10 crashes +/// in 420 runs before, none in 360 with opens one at a time. +fn amf_lock() -> std::sync::MutexGuard<'static, ()> { + static AMF: std::sync::Mutex<()> = std::sync::Mutex::new(()); + AMF.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// What RGB DMA-BUFs need on their way into the session's NV12 surfaces: /// a frames context of their own size to be mapped onto (FFmpeg gives an /// imported surface the size of the destination's frames context, and the @@ -584,7 +601,9 @@ impl Drop for Session { (api.av_frame_free)(&mut self.sw); (api.av_frame_free)(&mut self.hw); (api.av_packet_free)(&mut self.packet); + let amf = self.amf.then(amf_lock); (api.avcodec_free_context)(&mut self.ctx); + drop(amf); if !self.pool.is_null() { (api.av_buffer_unref)(&mut self.pool); } @@ -631,6 +650,9 @@ impl FfmpegEncoder { codec: Codec::H264, reason: format!("unknown FFmpeg encoder {name}"), })?; + if let Some(reason) = amf_refused().filter(|_| spec.family() == "amf") { + return Err(Error::CodecUnavailable { codec: spec.codec, reason: reason.into() }); + } let ffmpeg = Ffmpeg::get() .map_err(|e| Error::CodecUnavailable { codec: spec.codec, reason: e.to_owned() })?; // What the probe measured, once it is done (its own encoders run @@ -770,6 +792,7 @@ impl FfmpegEncoder { timestamps: Timestamps::new(), nv12: self.spec.input != Input::Yuv420p, rgb: None, + amf: false, }; // SAFETY: `ctx` is a live codec context; the first child is its // private options object (NULL if the codec has none). @@ -849,8 +872,12 @@ impl FfmpegEncoder { layout::write::(ctx, offset, reference); } } - // SAFETY: a configured context and its codec; no options dictionary. - let ret = unsafe { (api.avcodec_open2)(ctx, codec, std::ptr::null_mut()) }; + session.amf = self.spec.family() == "amf"; + let ret = { + let _amf = session.amf.then(amf_lock); + // SAFETY: a configured context and its codec; no options dictionary. + unsafe { (api.avcodec_open2)(ctx, codec, std::ptr::null_mut()) } + }; if ret < 0 { return Err(self.error("open", ret)); } @@ -1772,6 +1799,20 @@ fn vendor_may_be_present(spec: &BackendSpec) -> std::result::Result<(), String> Ok(()) } +/// Why AMF is not used here, if it is not. +/// +/// On Linux it is used only with `VOELIN_FFMPEG_AMF=1`: VA-API drives the +/// same AMD encoder there, measured as fast with less CPU, and only VA-API +/// takes DMA-BUFs without a copy. AMF on Linux is AMD's closed runtime on +/// top of Vulkan, and it has crashed the app inside `avcodec_open2` (see +/// [`amf_lock`]); a library that is never loaded cannot. +fn amf_refused() -> Option<&'static str> { + let opted_in = std::env::var_os("VOELIN_FFMPEG_AMF").is_some_and(|v| v != "0"); + (cfg!(target_os = "linux") && !opted_in).then_some( + "not used on Linux: VA-API drives the same AMD encoder (VOELIN_FFMPEG_AMF=1 uses it)", + ) +} + /// The result of [`probe`], once it ran. static PROBE: OnceLock> = OnceLock::new(); @@ -2498,6 +2539,29 @@ mod tests { }); } + /// On Linux an AMF encoder is not even made unless asked for, so AMF's + /// runtime is never loaded by default; other backends are made as + /// before. + #[cfg(target_os = "linux")] + #[test] + fn amf_is_opt_in_on_linux() { + if std::env::var_os("VOELIN_FFMPEG_AMF").is_some() { + eprintln!("VOELIN_FFMPEG_AMF is set, skipped"); + return; + } + for name in ["h264_amf", "hevc_amf", "av1_amf"] { + let Err(Error::CodecUnavailable { reason, .. }) = + FfmpegEncoder::new(name, EncoderConfig::default()) + else { + panic!("{name} was made"); + }; + assert!(reason.contains("VOELIN_FFMPEG_AMF=1"), "{name}: {reason}"); + } + if Ffmpeg::get().is_ok() { + assert!(FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).is_ok()); + } + } + #[test] fn settings_per_backend() { let config = EncoderConfig::default(); diff --git a/crates/voelin-media/tests/ffmpeg.rs b/crates/voelin-media/tests/ffmpeg.rs index 18d0cac..69364ea 100644 --- a/crates/voelin-media/tests/ffmpeg.rs +++ b/crates/voelin-media/tests/ffmpeg.rs @@ -141,6 +141,17 @@ fn probe_reports_every_backend() { let automatic = status.available.is_ok() && status.spec.is_automatic(); assert_eq!(info.rank.is_some(), automatic, "{}", status.spec.name); } + // On Linux, AMF's runtime is not even loaded unless asked for: the + // probe crashed in it (SIGSEGV in libamfrt64), and VA-API drives the + // same encoder there. Nothing in this process may have loaded it. + if cfg!(target_os = "linux") && std::env::var_os("VOELIN_FFMPEG_AMF").is_none() { + for status in statuses.iter().filter(|s| s.spec.api == "AMF") { + let reason = status.available.as_ref().unwrap_err(); + assert!(reason.contains("VOELIN_FFMPEG_AMF=1"), "{}: {reason}", status.spec.name); + } + let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); + assert!(!maps.contains("libamfrt"), "AMF's runtime was loaded"); + } } #[test] @@ -194,6 +205,40 @@ fn hardware_encoders_roundtrip() { eprintln!("tested: {names:?}"); } +/// AMF's runtime crashed (SIGSEGV in `AMFFactoryHelper::Init` / +/// `Terminate` in `libamfrt64`) when encoders were opened on several +/// threads at once, as the probe and simulcast layers do: 10 of 420 probes +/// with several processes probing together. Opens and closes are +/// serialised now; this opens every usable AMF encoder on parallel threads +/// again and again. On Linux it needs `VOELIN_FFMPEG_AMF=1`; ignored by +/// default because a regression takes the whole test binary down. +#[test] +#[ignore = "needs AMF; a regression crashes the process"] +fn amf_encoders_open_in_parallel() { + if ffmpeg().is_none() { + return; + } + let names: Vec<&str> = + ["h264_amf", "hevc_amf", "av1_amf"].into_iter().filter(|n| available(n)).collect(); + if names.is_empty() { + eprintln!("no usable AMF encoder, skipped"); + return; + } + let frame = voelin_media::VideoFrame::black_i420(W, H); + for _ in 0..40 { + std::thread::scope(|scope| { + for &name in &names { + let frame = &frame; + scope.spawn(move || { + let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap(); + encoder.encode(frame, true).unwrap(); + }); + } + }); + } + eprintln!("opened {names:?} together 40 times"); +} + #[test] fn x264_is_constrained_high_and_changes_size() { if ffmpeg().is_none() || !available("libx264") { diff --git a/docs/media.md b/docs/media.md index 5fb3aa4..0b73842 100644 --- a/docs/media.md +++ b/docs/media.md @@ -323,6 +323,26 @@ the software encoders above are used as before. machine below this took `voelinctl stream encoders` from 1.77 s to 0.93-1.12 s, testing 12 backends instead of 20, and the report says "no NVIDIA GPU in this machine" instead of a CUDA error code. +- AMF on Linux: not used unless `VOELIN_FFMPEG_AMF=1`. No AMF encoder is + made (`FfmpegEncoder::new` refuses it with the reason, so the probe, the + factories and direct callers alike), and AMD's runtime (`libamfrt64`) + is never loaded. VA-API drives the same VCN encoder there, as fast and + with less CPU in the measurements below, and only VA-API takes DMA-BUFs + without a copy; AMF on Linux is AMD's closed runtime running on Vulkan. + It crashed the desktop app during the startup probe: SIGSEGV in + `AMFFactoryHelper::Init` / `Terminate` (`libamfrt64`, inside + `avcodec_open2` creating AMF's Vulkan device), reproduced in 10 of 420 + probes with several processes probing at once. The runtime's + process-wide factory helper loads and unloads libraries while each new + encoder initialises, so encoders opened on parallel threads (the probe's + self-tests, simulcast layers) pull libraries from under each other. + Wherever AMF is used (Windows, or Linux with the variable), AMF encoders + are now opened and closed one at a time in the process: none of 600 + probes crashed that way, with up to eight processes probing together + (`amf_encoders_open_in_parallel`, `--ignored`, stresses it). A crash in + a vendor library still takes the process down; running the self-tests in + a child process was not done because a clean child does not reproduce + the state of the app that uses the encoder afterwards. - Third-party output: FFmpeg's own log goes to `tracing`, but the libraries behind the encoders write to standard error themselves — SVT-AV1 prints a build banner and its allocation totals, AMD's AMF runtime prints @@ -834,6 +854,7 @@ has not run on Windows yet. | 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 | +| AMF never loaded on Linux by default; AMF opens serialised | `ffmpeg::encoder::tests::amf_is_opt_in_on_linux`, `tests/ffmpeg.rs` `probe_reports_every_backend` (no `libamfrt` in `/proc/self/maps`), `amf_encoders_open_in_parallel` (`--ignored`, with `VOELIN_FFMPEG_AMF=1`) | tested: the probe crash (SIGSEGV in `libamfrt64`, 10 of 420 concurrent probes under Xvfb) reproduced, then none in 600 with serialised opens | | Encoder preference (auto, software, named, hardware off), report ranks | `codec::tests::encoder_preference` | tested | | An encoder per codec viewers chose (made, dropped, stream codec skipped, preference change) | `voelin-core` `media::tests::an_encoder_per_codec_viewers_chose` | tested | | Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) |