Merge the fix for AMF crashing the app during the encoder probe
AMD's AMF runtime is not safe to open on several threads at once; the probe did exactly that and crashed the app inside avcodec_open2. AMF opens are serialised, and on Linux AMF is used only on request (VOELIN_FFMPEG_AMF=1): VA-API drives the same encoder there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
92f49cdffd
3 files changed
+132
-2
No files matched your search
@@ -529,12 +529,29 @@ struct Session {
|
||||
nv12: bool,
|
||||
/// RGB DMA-BUFs: made on the first one; why not, if they cannot be.
|
||||
rgb: Option<std::result::Result<RgbImport, String>>,
|
||||
/// 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::<Ptr>(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<Vec<BackendStatus>> = 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();
|
||||
|
||||
@@ -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") {
|
||||
|
||||
Reference in new issue
Block a user