Merge the development branch: decoders, watching from the channel list

Both sides kept. From the development branch: FFmpeg's decoders at
runtime (hardware first, then software, then built-in) with the settings
stream.hardware_decoding and stream.decoder_backend, applied to the
video when they change, and watching a streaming user's stream from the
channel list, their dialog and the member card.

video.rs keeps set_decoder_preference and leaves out encoder_report:
the Integrations page asks a copy of the codecs for the report on a
thread of its own (FFmpeg's probe can take a while), not on the UI
thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-04 03:33:33 +03:00
commit 87c8d6c686
37 files changed
+2839 -158

No files matched your search

+351 -41
View File
@@ -16,8 +16,11 @@
//! sink allows. [`Streamer::reconfigure`] changes frame rate, bitrate,
//! codec, layers and audio sources while streaming.
//! - [`VideoPipeline`] decodes the video of a watched stream on its own
//! thread and hands every picture to a callback. After lost frames or
//! decoder errors it skips to the next keyframe and asks for one.
//! thread with the best decoder of its codec, falling back to the next
//! one when a decoder fails, and hands every picture to a callback. After
//! lost frames it asks for a keyframe; decoders that conceal what is
//! missing (FFmpeg's H.264 and HEVC) go on decoding meanwhile, the others
//! skip to it.
//! - [`Viewer`] is a [`VideoPipeline`] fed from [`Engine::subscribe_frames`].
//! The stream's audio needs nothing here: the session plays it
//! ([`Command::SetStreamVolume`]).
@@ -59,7 +62,7 @@ use voelin_media::{
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
VideoFrame,
};
pub use voelin_media::{EncoderBackend, EncoderPreference};
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
MediaTime, PeerConfig, VideoCodec,
@@ -79,6 +82,17 @@ const OPUS_BITRATE: i32 = 128_000;
pub const MAX_QUEUED: usize = 30;
/// Keyframe requests while waiting for one are at least this far apart.
const KEYFRAME_RETRY: Duration = Duration::from_millis(500);
/// Failures in a row (errors, or [`FRAMES_WITHOUT_PICTURE`] frames that
/// gave none) after which a decoder is replaced by the next one of its
/// codec's ladder.
const DECODER_FAILURES: u32 = 3;
/// Frames a decoder may take without giving a picture before that counts
/// as a failure (and a keyframe is asked for): decoders of streams with
/// B-frames hold a few.
const FRAMES_WITHOUT_PICTURE: u32 = 10;
/// Decoded pictures a [`VideoPipeline`] recycles; while the consumer holds
/// them all, more are made.
const PICTURE_POOL: usize = 4;
/// The decoding rates of [`DecodeStats`] cover at least this long.
const RATE_WINDOW: Duration = Duration::from_millis(500);
@@ -188,6 +202,16 @@ pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media:
}
}
/// The decoder preference of the settings `stream.hardware_decoding` and
/// `stream.decoder_backend` (for `Codecs::with_decoder_preference`).
pub fn decoder_preference(settings: &crate::settings::Settings) -> DecoderPreference {
use crate::settings::{STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING};
DecoderPreference {
hardware: settings.get(&STREAM_HARDWARE_DECODING),
backend: settings.get(&STREAM_DECODER_BACKEND).parse().unwrap_or_default(),
}
}
/// The stream codec: `configured` if we can encode it, else the first codec
/// of the encoder preference (hardware first when enabled; VP8 through
/// libvpx without hardware) that every TeamSpeak client decodes
@@ -2465,6 +2489,9 @@ pub struct DecodeStats {
pub skipped: u64,
pub keyframe_requests: u64,
pub codec: Option<Codec>,
/// The decoder in use ([`Codecs::decoders_for`]: the first of the
/// codec's that works).
pub decoder: Option<DecoderBackend>,
pub width: u32,
pub height: u32,
/// The last error (no decoder for the codec, decoding failed).
@@ -2543,12 +2570,14 @@ pub struct VideoPipeline {
}
impl VideoPipeline {
/// `on_frame` gets every decoded picture on the decoding thread;
/// `request_keyframe` is called when the decoder needs one (at most
/// every half second).
/// `on_frame` gets every decoded picture on the decoding thread, from a
/// pool: a picture comes back to it once the consumer drops it, so a
/// consumer that converts and drops each one costs no allocations.
/// `request_keyframe` is called when the decoder needs one (every half
/// second until one comes).
pub fn new(
codecs: Arc<Codecs>,
on_frame: impl FnMut(VideoFrame) + Send + 'static,
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
request_keyframe: impl Fn() + Send + 'static,
) -> Self {
let queue = Arc::new(DecodeQueue::default());
@@ -2599,16 +2628,112 @@ impl Drop for VideoPipeline {
}
}
/// The decoder of a [`VideoPipeline`] and the rest of its codec's ladder.
struct ActiveDecoder {
codec: Codec,
backend: DecoderBackend,
decoder: Box<dyn voelin_media::VideoDecoder>,
/// The codec's other decoders, best first, still to try.
rest: VecDeque<DecoderBackend>,
/// Failures since the last picture.
failures: u32,
/// Frames taken since the last picture or failure.
without_picture: u32,
/// It failed with no other decoder left (logged once).
last_failed: bool,
}
impl ActiveDecoder {
/// The first decoder of `codec`'s ladder that opens.
fn start(codecs: &Codecs, codec: Codec) -> Result<Self, String> {
let mut rest: VecDeque<DecoderBackend> = codecs.decoders_for(codec).into();
let (backend, decoder) = Self::open_next(codecs, codec, &mut rest).map_err(|e| {
e.unwrap_or_else(|| {
codecs
.check_decoder(codec)
.err()
.map_or_else(|| format!("no decoder for {codec}"), |e| e.to_string())
})
})?;
Ok(Self {
codec,
backend,
decoder,
rest,
failures: 0,
without_picture: 0,
last_failed: false,
})
}
/// The next decoder of `rest` that opens; the last error if none did.
fn open_next(
codecs: &Codecs,
codec: Codec,
rest: &mut VecDeque<DecoderBackend>,
) -> Result<(DecoderBackend, Box<dyn voelin_media::VideoDecoder>), Option<String>> {
let mut error = None;
while let Some(backend) = rest.pop_front() {
match codecs.new_decoder_with(codec, backend) {
Ok(decoder) => return Ok((backend, decoder)),
Err(e) => {
warn!(%codec, %backend, "the decoder does not open: {e}");
error = Some(e.to_string());
}
}
}
Err(error)
}
/// Replace the decoder by the next one of the ladder, after `reason`;
/// `false` (keeping this one) if there is none.
fn fall_back(&mut self, codecs: &Codecs, reason: &str) -> bool {
(self.failures, self.without_picture) = (0, 0);
let (codec, failed) = (self.codec, self.backend);
match Self::open_next(codecs, codec, &mut self.rest) {
Ok((backend, decoder)) => {
warn!(%codec, %failed, %backend, "the decoder failed ({reason}); trying the next");
(self.backend, self.decoder) = (backend, decoder);
true
}
Err(_) => {
if !std::mem::replace(&mut self.last_failed, true) {
warn!(%codec, %failed, "the decoder fails ({reason}), and no other is left");
}
false
}
}
}
}
/// A pooled picture nobody else holds, to decode into: one the consumer
/// gave back, else a new one (when the pool is full, the oldest is left to
/// whoever holds it).
fn free_picture(pictures: &mut Vec<Arc<VideoFrame>>) -> usize {
if let Some(i) = pictures.iter_mut().position(|p| Arc::get_mut(p).is_some()) {
return i;
}
if pictures.len() >= PICTURE_POOL {
pictures.remove(0);
}
pictures.push(Arc::new(VideoFrame::black_i420(0, 0)));
pictures.len() - 1
}
fn decode_loop(
queue: &DecodeQueue,
codecs: &Codecs,
mut on_frame: impl FnMut(VideoFrame),
mut on_frame: impl FnMut(Arc<VideoFrame>),
request_keyframe: impl Fn(),
) {
let mut decoder: Option<(Codec, Box<dyn voelin_media::VideoDecoder>)> = None;
let mut active: Option<ActiveDecoder> = None;
// Start at a keyframe; the streamer sends one when a viewer connects.
let mut waiting = true;
// A keyframe is wanted (after a loss, or an error of a decoder that goes
// on), asked for until one decodes.
let mut wanted = false;
let mut last_request: Option<Instant> = None;
let mut pictures: Vec<Arc<VideoFrame>> = Vec::with_capacity(PICTURE_POOL);
let mut request = |stats: &Mutex<DecodeStats>| {
if last_request.is_none_or(|t| t.elapsed() >= KEYFRAME_RETRY) {
last_request = Some(Instant::now());
@@ -2618,19 +2743,22 @@ fn decode_loop(
};
let set_error = |message: String| lock(&queue.stats).error = Some(message);
loop {
let (frame, lost) = {
let next = {
let mut state = lock(&queue.state);
loop {
if state.closed {
return;
}
if let Some(frame) = state.frames.pop_front() {
break (frame, std::mem::take(&mut state.lost));
}
if state.frames.is_empty() && !state.closed {
state =
queue.cond.wait_timeout(state, POLL).unwrap_or_else(PoisonError::into_inner).0;
}
if state.closed {
return;
}
state.frames.pop_front().map(|frame| (frame, std::mem::take(&mut state.lost)))
};
// Asked for again while none comes, even while no frame does.
if (waiting || wanted) && active.is_some() {
request(&queue.stats);
}
let Some((frame, lost)) = next else { continue };
let codec = match Codec::try_from(frame.codec) {
Ok(codec) => codec,
Err(e) => {
@@ -2638,51 +2766,95 @@ fn decode_loop(
continue;
}
};
if decoder.as_ref().is_none_or(|(c, _)| *c != codec) {
match codecs.new_decoder(codec) {
Ok(d) => {
decoder = Some((codec, d));
if active.as_ref().is_none_or(|a| a.codec != codec) {
match ActiveDecoder::start(codecs, codec) {
Ok(started) => {
let mut stats = lock(&queue.stats);
(stats.codec, stats.decoder) = (Some(codec), Some(started.backend));
drop(stats);
active = Some(started);
waiting = true;
lock(&queue.stats).codec = Some(codec);
}
Err(e) => {
if decoder.is_some() || lock(&queue.stats).error.is_none() {
if active.is_some() || lock(&queue.stats).error.is_none() {
warn!("no decoder for the stream: {e}");
}
decoder = None;
set_error(e.to_string());
active = None;
set_error(e);
continue;
}
}
}
let Some(dec) = &mut active else { continue };
if lost || !frame.contiguous {
waiting = true;
// A decoder that conceals the loss goes on; the others would
// fail, or show garbage, until a keyframe.
if dec.decoder.conceals_errors() {
wanted = true;
} else {
waiting = true;
}
}
let keyframe = is_keyframe(codec, &frame.data);
if waiting {
if !is_keyframe(codec, &frame.data) {
if !keyframe {
lock(&queue.stats).skipped += 1;
request(&queue.stats);
continue;
}
waiting = false;
}
let Some((_, dec)) = &mut decoder else { continue };
match dec.decode(&frame.data) {
Ok(Some(picture)) => {
{
let mut stats = lock(&queue.stats);
stats.decoded += 1;
(stats.width, stats.height) = (picture.width, picture.height);
loop {
let slot = free_picture(&mut pictures);
let picture = Arc::get_mut(&mut pictures[slot]).expect("a free picture");
let failure = match dec.decoder.decode_into(&frame.data, picture) {
Ok(true) => {
(dec.failures, dec.without_picture) = (0, 0);
wanted &= !keyframe;
{
let mut stats = lock(&queue.stats);
stats.decoded += 1;
(stats.width, stats.height) = (picture.width, picture.height);
}
on_frame(pictures[slot].clone());
None
}
on_frame(picture);
Ok(false) => {
// Decoders with a delay (B-frames) give it a few frames
// later; one that gives nothing gets keyframes to try.
dec.without_picture += 1;
(dec.without_picture >= FRAMES_WITHOUT_PICTURE).then(|| {
dec.without_picture = 0;
wanted = true;
request(&queue.stats);
format!("no picture from {FRAMES_WITHOUT_PICTURE} frames")
})
}
Err(e) => {
debug!("decoding failed: {e}");
set_error(e.to_string());
if dec.decoder.conceals_errors() {
wanted = true;
} else {
waiting = true;
}
request(&queue.stats);
Some(e.to_string())
}
};
let Some(reason) = failure else { break };
dec.failures += 1;
if dec.failures < DECODER_FAILURES || !dec.fall_back(codecs, &reason) {
break;
}
Ok(None) => {}
Err(e) => {
debug!("decoding failed: {e}");
set_error(e.to_string());
lock(&queue.stats).decoder = Some(dec.backend);
if !keyframe {
waiting = true;
request(&queue.stats);
break;
}
// The keyframe that failed starts the next decoder at once.
waiting = false;
}
}
}
@@ -2701,7 +2873,7 @@ impl Viewer {
session: SessionId,
stream_id: &str,
codecs: Arc<Codecs>,
on_frame: impl FnMut(VideoFrame) + Send + 'static,
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
) -> Self {
let request = {
let engine = engine.clone();
@@ -2818,7 +2990,7 @@ impl LocalPreview {
pub async fn start(
codecs: Arc<Codecs>,
mut config: StreamerConfig,
on_frame: impl FnMut(VideoFrame) + Send + 'static,
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
) -> Result<Self, MediaError> {
// The audio would go nowhere.
config.audio = false;
@@ -3087,6 +3259,144 @@ mod tests {
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
}
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
/// no picture), or gives a 2x2 picture per frame; conceals losses or not.
#[derive(Clone, Copy)]
struct FakeDecoder {
errors: bool,
pictures: bool,
conceals: bool,
}
impl voelin_media::VideoDecoder for FakeDecoder {
fn codec(&self) -> Codec {
Codec::Vp8
}
fn decode(&mut self, _: &[u8]) -> voelin_media::Result<Option<VideoFrame>> {
if self.errors {
let message = "made to fail".into();
return Err(voelin_media::Error::Decoder { codec: Codec::Vp8, message });
}
Ok(self.pictures.then(|| VideoFrame::black_i420(2, 2)))
}
fn conceals_errors(&self) -> bool {
self.conceals
}
}
impl voelin_media::codec::hw::DecoderFactory for FakeDecoder {
fn backend(&self) -> DecoderBackend {
DecoderBackend::Hardware("fake")
}
fn codec(&self) -> Codec {
Codec::Vp8
}
fn api(&self) -> &'static str {
"test"
}
fn is_hardware(&self) -> bool {
true
}
fn create(&self) -> voelin_media::Result<Box<dyn voelin_media::VideoDecoder>> {
Ok(Box::new(*self))
}
}
/// A decoder that fails, with errors or by giving no picture from
/// several keyframes, is replaced by the next of its codec's ladder
/// (libvpx here) without ending the stream: pictures go on.
#[cfg(feature = "media-desktop")]
#[tokio::test(flavor = "multi_thread")]
async fn a_failing_decoder_is_replaced_by_the_next() {
for errors in [true, false] {
let fake = FakeDecoder { errors, pictures: false, conceals: false };
let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake)));
assert_eq!(codecs.decoders_for(Codec::Vp8)[0], DecoderBackend::Hardware("fake"));
assert_eq!(codecs.decoders_for(Codec::Vp8).last(), Some(&DecoderBackend::Libvpx));
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (320, 240),
..StreamerConfig::default()
};
let (tx, rx) = std_mpsc::channel();
let preview = LocalPreview::start(codecs, config, move |picture| {
let _ = tx.send(picture);
})
.await
.unwrap();
for _ in 0..10 {
let picture = rx.recv_timeout(Duration::from_secs(10)).expect("no picture");
assert_eq!((picture.width, picture.height), (320, 240));
}
let stats = preview.stats();
assert_eq!(stats.decoder, Some(DecoderBackend::Libvpx), "errors {errors}: {stats:?}");
assert!(stats.keyframe_requests > 0, "{stats:?}");
}
}
/// After a lost frame a decoder that conceals the loss goes on decoding
/// while a keyframe is asked for, again every half second until one
/// comes; one that does not skips to the keyframe.
#[test]
fn losses_ask_for_keyframes_until_one_comes() {
for conceals in [true, false] {
let fake = FakeDecoder { errors: false, pictures: true, conceals };
let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake)));
let (tx, pictures) = std_mpsc::channel();
let requests = Arc::new(AtomicU32::new(0));
let pipeline = VideoPipeline::new(
codecs,
move |_| {
let _ = tx.send(());
},
{
let requests = requests.clone();
move || {
requests.fetch_add(1, Ordering::Relaxed);
}
},
);
let frame = |keyframe: bool, contiguous: bool| MediaFrame {
kind: MediaKind::Video,
codec: voelin_stream::Codec::Vp8,
time: MediaTime::new(0, Frequency::NINETY_KHZ),
network_time: Instant::now(),
contiguous,
// VP8's frame tag: bit 0 clear on keyframes.
data: Arc::from(if keyframe { &[0x10_u8, 0][..] } else { &[0x11, 0][..] }),
};
let got =
|n: usize| (0..n).all(|_| pictures.recv_timeout(Duration::from_secs(2)).is_ok());
pipeline.push(frame(true, true));
pipeline.push(frame(false, true));
assert!(got(2), "conceals {conceals}");
pipeline.push(frame(false, false));
pipeline.push(frame(false, true));
if conceals {
assert!(got(2), "decoding goes on");
} else {
assert!(pictures.recv_timeout(Duration::from_millis(300)).is_err(), "skipped");
}
std::thread::sleep(Duration::from_millis(1200));
let asked = requests.load(Ordering::Relaxed);
assert!(asked >= 2, "conceals {conceals}: {asked} requests");
pipeline.push(frame(true, true));
assert!(got(1), "the keyframe decodes");
let asked = requests.load(Ordering::Relaxed);
std::thread::sleep(Duration::from_millis(700));
assert_eq!(requests.load(Ordering::Relaxed), asked, "no more requests");
let stats = pipeline.stats();
assert_eq!(stats.skipped, if conceals { 0 } else { 2 }, "{stats:?}");
assert_eq!(stats.decoder, Some(DecoderBackend::Hardware("fake")));
}
}
fn layer(id: LayerId, scale: f32, max_fps: Option<u32>, bitrate: u64) -> LayerSpec {
LayerSpec { id, scale, max_fps, ..LayerSpec::single(bitrate) }
}
+23 -2
View File
@@ -1031,14 +1031,31 @@ pub static STREAM_SRTP_PROFILES: Key<Vec<String>> = Key::new(
)
.validated(valid_srtp);
/// Use hardware video encoders and decoders where available.
/// Use hardware video encoders where available.
pub static STREAM_HARDWARE_ACCELERATION: Key<bool> = Key::new(
"stream.hardware_acceleration",
Kind::Bool,
"Use hardware video encoders and decoders where available.",
"Use hardware video encoders where available.",
|| true,
);
/// Use hardware video decoders where available.
pub static STREAM_HARDWARE_DECODING: Key<bool> = Key::new(
"stream.hardware_decoding",
Kind::Bool,
"Use hardware video decoders where available.",
|| true,
);
/// Video decoder: `auto`, `software`, or the name of a decoder backend.
pub static STREAM_DECODER_BACKEND: Key<String> = Key::new(
"stream.decoder_backend",
Kind::Text { suggestions: &["auto", "software"] },
"Video decoder: auto, software, or a decoder's name.",
|| "auto".into(),
)
.validated(not_empty);
/// Who may watch our stream without being asked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -1309,6 +1326,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> {
&STREAM_ENCODER_BACKEND,
&STREAM_SRTP_PROFILES,
&STREAM_HARDWARE_ACCELERATION,
&STREAM_HARDWARE_DECODING,
&STREAM_DECODER_BACKEND,
&STREAM_PERMISSIONS,
&CHAT_STORE_HISTORY,
&CHAT_HISTORY_PAGE,
@@ -1381,6 +1400,8 @@ mod tests {
);
assert!(s.get(&STREAM_HARDWARE_ACCELERATION));
assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto");
assert!(s.get(&STREAM_HARDWARE_DECODING));
assert_eq!(s.get(&STREAM_DECODER_BACKEND), "auto");
assert!(s.get(&CHAT_STORE_HISTORY));
assert_eq!(s.get(&CHAT_HISTORY_PAGE), 100);
assert_eq!(s.get(&CHAT_DEDUPE_TOLERANCE_MS), 5000);
+75 -3
View File
@@ -2,7 +2,8 @@
//! pattern, encoded by each encoder this machine has as a share encodes the
//! screen, sent by our streamer peer offering just that codec, must decode
//! at its size in headless Chromium (libwebrtc, the stack the official
//! TeamSpeak 6 client is built on).
//! TeamSpeak 6 client is built on). And the other way: what Chromium sends
//! (AV1, VP9, H.264) our viewer accepts and the engine's pipeline decodes.
//!
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
@@ -11,6 +12,8 @@
#![cfg(feature = "media-desktop")]
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
@@ -18,8 +21,8 @@ use tokio::time::timeout;
use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::{Codec, Codecs};
use voelin_core::media::{
EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec,
peer_config, preferred_codec, video_codec,
EncodedSource, EncoderPreference, Streamer, StreamerConfig, VideoPipeline, decoded_everywhere,
media_codec, peer_config, preferred_codec, video_codec,
};
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
use voelin_stream::{Peer, PeerEvent};
@@ -185,3 +188,72 @@ async fn share_offer_picks_a_codec_every_client_decodes() {
browser.quit().await;
decoded(&video).unwrap();
}
/// Headless Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in
/// turn (what it cannot send is skipped; a system Chromium sends H.264) to
/// our viewer peer, which accepts what this machine decodes
/// (`peer_config`); the engine's pipeline decodes 30 pictures at that size
/// with the first decoder of the codec's ladder (VA-API where it decodes
/// the codec), asking the browser for keyframes as a watch does.
#[tokio::test(flavor = "multi_thread")]
async fn browser_streams_decode_in_the_pipeline() {
if !enabled() {
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let mut browser = Browser::start().await;
let codecs = Arc::new(Codecs::new());
let config = peer_config(&codecs, PeerConfig::loopback());
let mut decoded = Vec::new();
for codec in [Codec::Av1, Codec::Vp9, Codec::H264] {
let offer = browser.call(json!({ "op": "offer", "codec": codec.name() })).await;
if offer.get("unsupported").is_some() {
eprintln!("{codec}: the browser cannot send it, skipped");
continue;
}
assert!(config.accept_video_codecs.contains(&video_codec(codec)), "{codec} not accepted");
let (mut peer, answer) =
Peer::answer(&config, offer["sdp"].as_str().unwrap()).await.unwrap();
browser.call(json!({ "op": "accept", "sdp": answer })).await;
let keyframe = Arc::new(AtomicBool::new(false));
let (tx, pictures) = std::sync::mpsc::channel();
let pipeline = VideoPipeline::new(
codecs.clone(),
move |picture| {
let _ = tx.send((picture.width, picture.height));
},
{
let keyframe = keyframe.clone();
move || keyframe.store(true, Ordering::Relaxed)
},
);
let mut sizes = Vec::new();
let _ = timeout(Duration::from_secs(15), async {
while let Some(event) = peer.next_event().await {
match event {
PeerEvent::Media(frame) => pipeline.push(frame),
PeerEvent::Closed => break,
_ => {}
}
if keyframe.swap(false, Ordering::Relaxed) {
peer.request_keyframe();
}
sizes.extend(pictures.try_iter());
if sizes.len() >= 30 {
break;
}
}
})
.await;
let stats = pipeline.stats();
peer.close();
eprintln!("{codec}: {} pictures, {stats:?}", sizes.len());
assert!(sizes.len() >= 30, "{codec}: {} pictures decoded, {stats:?}", sizes.len());
assert!(sizes.iter().all(|&s| s == (320, 240)), "{codec}: {sizes:?}");
assert_eq!(stats.codec, Some(codec));
assert_eq!(stats.decoder, codecs.decoders_for(codec).first().copied(), "{stats:?}");
decoded.push(codec);
}
browser.quit().await;
assert!(decoded.contains(&Codec::Av1), "the browser sent no AV1: {decoded:?}");
}
+125
View File
@@ -0,0 +1,125 @@
//! The viewer's pipeline on an H.264 stream with B-frames at 2560x1440 and
//! 60 fps, like the official client sends (AMF with B-frames, keyframes
//! rarely): frames pushed in real time into a `VideoPipeline`, every
//! picture converted to RGBA as the app shows it, with and without a lost
//! frame every second. The stream is the one `voelin-media`'s
//! `h264_with_b_frames_at_1440p60` measurement makes (in the temporary
//! directory); `VOELIN_OPENH264_LIB` adds Cisco's OpenH264 alone, the
//! decoder the app used before FFmpeg's. Run with `--release --ignored`.
#![cfg(feature = "media-desktop")]
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use voelin_core::media::voelin_media::{Codec, Codecs, convert};
use voelin_core::media::{DecodeStats, VideoPipeline};
use voelin_stream::{Frequency, MediaFrame, MediaKind, MediaTime};
/// The access units of an Annex B stream with access unit delimiters.
fn access_units(stream: &[u8]) -> Vec<&[u8]> {
let mut starts = Vec::new();
let mut i = 0;
while i + 3 < stream.len() {
if stream[i..i + 3] == [0, 0, 1] {
if stream[i + 3] & 0x1f == 9 {
starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i });
}
i += 3;
} else {
i += 1;
}
}
starts.push(stream.len());
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
}
/// `units` at 60 fps into a pipeline of `codecs`, every `loss`-th frame
/// lost; the pictures shown and the pipeline's statistics.
fn play(codecs: Codecs, units: &[&[u8]], loss: Option<usize>) -> (u64, DecodeStats) {
let shown = Arc::new(AtomicU64::new(0));
let rgba = Mutex::new(vec![0u8; 2560 * 1440 * 4]);
let pipeline = VideoPipeline::new(
Arc::new(codecs),
{
let shown = shown.clone();
move |picture| {
let stride = picture.width as usize * 4;
let mut rgba = rgba.lock().unwrap();
rgba.resize(stride * picture.height as usize, 0);
convert::to_rgba(&picture, &mut rgba, stride).unwrap();
shown.fetch_add(1, Ordering::Relaxed);
}
},
|| {},
);
let started = Instant::now();
let mut contiguous = true;
for (n, unit) in units.iter().enumerate() {
let due = started + Duration::from_micros(16_667 * n as u64);
std::thread::sleep(due.saturating_duration_since(Instant::now()));
if loss.is_some_and(|every| n % every == every - 1) {
contiguous = false;
continue;
}
pipeline.push(MediaFrame {
kind: MediaKind::Video,
codec: voelin_stream::Codec::H264,
time: MediaTime::new(1500 * n as u64, Frequency::NINETY_KHZ),
network_time: Instant::now(),
contiguous,
data: Arc::from(*unit),
});
contiguous = true;
}
std::thread::sleep(Duration::from_millis(200));
(shown.load(Ordering::Relaxed), pipeline.stats())
}
#[test]
#[ignore = "a measurement: needs the stream voelin-media's measurement makes"]
fn h264_with_b_frames_plays_at_full_rate() {
let dir = std::env::temp_dir().join("voelin-h264-bframes");
let mut played = 0;
for stream in ["h264_vaapi", "x264"] {
let Ok(data) = std::fs::read(dir.join(format!("{stream}-bframes-1440p60.h264"))) else {
eprintln!("{stream}: no stream in {}, skipped", dir.display());
continue;
};
let units = access_units(&data);
let mut setups = vec![("ladder", Codecs::new())];
if let Some(path) = std::env::var_os("VOELIN_OPENH264_LIB") {
let library =
voelin_core::media::voelin_media::codec::h264::OpenH264::load(path).unwrap();
setups.push(("openh264", Codecs::builtin().with_openh264(library)));
}
for (name, codecs) in setups {
for loss in [None, Some(60)] {
let ladder = codecs.decoders_for(Codec::H264);
let (shown, stats) = play(codecs.clone(), &units, loss);
let seconds = units.len() as f64 / 60.0;
eprintln!(
"{stream} 2560x1440@60 with B-frames, {name} {ladder:?}, {}: {shown} of {} \
pictures shown ({:.1} fps), decoder {:?}, skipped {}, keyframe requests {}, \
last error {:?}",
if loss.is_some() { "a frame lost every second" } else { "no loss" },
units.len(),
shown as f64 / seconds,
stats.decoder,
stats.skipped,
stats.keyframe_requests,
stats.error,
);
if name == "ladder" {
// Everything but the frames lost and the two the decoder
// still holds at the end.
let lost = loss.map_or(0, |every| units.len() / every);
assert!(shown + 3 + lost as u64 >= units.len() as u64, "{shown}");
}
}
}
played += 1;
}
assert!(played > 0, "no stream: run voelin-media's h264_with_b_frames_at_1440p60 first");
}
+36 -3
View File
@@ -1,13 +1,17 @@
//! Encoder factories found at runtime.
//! Encoder and decoder factories found at runtime.
//!
//! - FFmpeg (feature `ffmpeg`, desktop): VA-API, NVENC, Quick Sync, AMF,
//! Media Foundation and VideoToolbox encoders, plus software ones FFmpeg
//! wraps (x264, OpenH264, SVT-AV1, rav1e, libaom); one factory per backend
//! that passed its self-test ([`crate::ffmpeg::probe`]).
//! that passed its self-test ([`crate::ffmpeg::probe`]). Decoders likewise:
//! VA-API, NVDEC, D3D11VA, DXVA2 and VideoToolbox, then dav1d and FFmpeg's
//! own ([`crate::ffmpeg::decoder::probe`]).
//! - Android: MediaCodec ([`super::mediacodec`]).
use crate::Result;
use crate::codec::{Codec, EncoderBackend, EncoderConfig, VideoEncoder};
use crate::codec::{
Codec, DecoderBackend, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
};
/// Creates encoders of one backend.
pub trait EncoderFactory: Send + Sync {
@@ -52,3 +56,32 @@ pub fn probe() -> Vec<Box<dyn EncoderFactory>> {
}
found
}
/// Creates decoders of one backend for one codec: FFmpeg's, or one an
/// application adds ([`Codecs::with_decoder`](super::Codecs::with_decoder)).
pub trait DecoderFactory: Send + Sync {
/// The backend its decoders are (for the ladder, logs and settings).
fn backend(&self) -> DecoderBackend;
fn codec(&self) -> Codec;
/// The API or library behind it (`VA-API`, `dav1d`, ...), for the UI.
fn api(&self) -> &'static str;
/// A GPU decoder: left out when hardware decoding is off.
fn is_hardware(&self) -> bool;
fn create(&self) -> Result<Box<dyn VideoDecoder>>;
}
/// Decoder factories usable on this machine: FFmpeg's decoders that passed
/// their self-test, hardware first.
pub fn probe_decoders() -> Vec<Box<dyn DecoderFactory>> {
#[allow(unused_mut)]
let mut found: Vec<Box<dyn DecoderFactory>> = Vec::new();
#[cfg(feature = "ffmpeg")]
for factory in crate::ffmpeg::decoder::FfmpegDecoderFactory::available() {
found.push(Box::new(factory));
}
found
}
+275 -41
View File
@@ -7,11 +7,16 @@
//! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264,
//! loaded at runtime
//! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d
//! - [`hw`]: encoder factories found at runtime: FFmpeg's hardware and
//! software encoders ([`crate::ffmpeg`], feature `ffmpeg`) and, on Android,
//! MediaCodec
//! - [`hw`]: encoder and decoder factories found at runtime: FFmpeg's
//! hardware and software encoders and decoders ([`crate::ffmpeg`], feature
//! `ffmpeg`) and, on Android, MediaCodec encoders
//! - `mediacodec` (Android): the device's MediaCodec encoders and decoders
//! (hardware, or Google's software VP8 / VP9 / H.264)
//!
//! A viewer decodes each codec with the best decoder that works here and
//! falls back to the next one ([`Codecs::decoders_for`]): hardware (FFmpeg's
//! hwaccels, MediaCodec), then FFmpeg's software decoders, then the built-in
//! libvpx, OpenH264 and dav1d.
use std::fmt;
use std::str::FromStr;
@@ -110,8 +115,12 @@ impl TryFrom<str0m::format::Codec> for Codec {
}
}
/// Order in which a viewer accepts codecs: VP9 > VP8 > AV1 > H.264.
pub const VIEWER_PREFERENCE: [Codec; 4] = [Codec::Vp9, Codec::Vp8, Codec::Av1, Codec::H264];
/// Order in which a viewer accepts codecs, best first: AV1 > HEVC > VP9 >
/// H.264 > VP8 (the best compression first, the codec every client has
/// last). Answers follow the offer's order, so this ranks what a viewer
/// asks for when it chooses, and what [`Codecs::decoders`] lists.
pub const VIEWER_PREFERENCE: [Codec; 5] =
[Codec::Av1, Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8];
/// What the encoder should optimise for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -292,6 +301,23 @@ pub trait VideoDecoder: Send {
/// Decode one complete frame (a depacketized RTP frame). Returns the
/// picture if one is ready; its timestamp is zero.
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>>;
/// Like [`decode`](Self::decode), into `out`: `true` if a picture is
/// there, else `out` is unchanged. Decoders that can reuse `out`'s
/// buffers do (FFmpeg's), so a caller that keeps passing the same frame
/// gets its pictures without allocations.
fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result<bool> {
let picture = self.decode(data)?;
Ok(picture.map(|p| *out = p).is_some())
}
/// Whether frames after a lost one still decode to a picture (what is
/// missing concealed until the next keyframe), so that a viewer keeps
/// decoding instead of waiting for a keyframe: FFmpeg's H.264 and HEVC
/// decoders. The others fail, or show garbage, on a missing reference.
fn conceals_errors(&self) -> bool {
false
}
}
/// Implementations behind [`VideoEncoder`].
@@ -324,6 +350,45 @@ impl fmt::Display for EncoderBackend {
}
}
/// Implementations behind [`VideoDecoder`], as [`Codecs::decoders_for`]
/// orders them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DecoderBackend {
/// An OS / GPU decoder of its own API (Android's `mediacodec`), or one
/// an application adds ([`Codecs::with_decoder`]).
Hardware(&'static str),
/// An FFmpeg decoder by its name in `ffmpeg::DECODERS`: in hardware
/// (`h264_vaapi`, FFmpeg's names of its hwaccels) or in software
/// (`h264`, `libdav1d`).
Ffmpeg(&'static str),
Libvpx,
OpenH264,
Dav1d,
}
impl DecoderBackend {
/// The name in settings (`stream.decoder_backend`) and logs.
pub fn name(self) -> &'static str {
match self {
DecoderBackend::Hardware(name) | DecoderBackend::Ffmpeg(name) => name,
DecoderBackend::Libvpx => "libvpx",
DecoderBackend::OpenH264 => "openh264",
DecoderBackend::Dav1d => "dav1d",
}
}
}
impl fmt::Display for DecoderBackend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// Which decoders to use (settings `stream.hardware_decoding` and
/// `stream.decoder_backend`): the choices of the encoders, `hardware` for
/// GPU decoders and `backend` naming a [`DecoderBackend::name`].
pub type DecoderPreference = EncoderPreference;
/// Which encoders to use (settings `stream.hardware_acceleration` and
/// `stream.encoder_backend`).
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -390,8 +455,12 @@ pub struct EncoderInfo {
pub rank: Option<usize>,
}
/// Every encoder backend this build knows, what works here and why the
/// rest does not (for the UI and `voelinctl stream encoders`).
/// One decoder backend in [`Codecs::report`]: as [`EncoderInfo`], its
/// `rank` the position in its codec's ladder ([`Codecs::decoders_for`]).
pub type DecoderInfo = EncoderInfo;
/// Every encoder and decoder backend this build knows, what works here and
/// why the rest does not (for the UI and `voelinctl stream encoders`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderReport {
/// The FFmpeg libraries in use (release, version, path), or why none.
@@ -400,6 +469,7 @@ pub struct EncoderReport {
/// or why not.
pub zero_copy: std::result::Result<(), String>,
pub encoders: Vec<EncoderInfo>,
pub decoders: Vec<DecoderInfo>,
}
fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
@@ -430,7 +500,9 @@ impl Candidate {
/// The codecs this build and machine can use, and factories for them.
///
/// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer
/// Viewer order ([`Codecs::decoders`]): AV1 > HEVC > VP9 > H.264 > VP8, each
/// codec with its ladder of decoders ([`Codecs::decoders_for`]) under the
/// [`DecoderPreference`]. Streamer
/// order ([`Codecs::encoders`]) under the default [`EncoderPreference`]:
/// hardware (H.264, AV1, VP9, VP8, HEVC; FFmpeg's or MediaCodec) > VP8
/// (libvpx) > H.264 (x264 and OpenH264 through FFmpeg, then Cisco's
@@ -439,9 +511,11 @@ impl Candidate {
#[derive(Clone)]
pub struct Codecs {
factories: Vec<Arc<dyn hw::EncoderFactory>>,
decoder_factories: Vec<Arc<dyn hw::DecoderFactory>>,
#[cfg(feature = "openh264")]
openh264: Option<h264::OpenH264>,
preference: EncoderPreference,
decoder_preference: DecoderPreference,
}
impl Default for Codecs {
@@ -456,34 +530,67 @@ impl fmt::Debug for Codecs {
.field("decoders", &self.decoders())
.field("encoders", &self.encoders())
.field("preference", &self.preference)
.field("decoder_preference", &self.decoder_preference)
.finish()
}
}
impl Codecs {
/// Software codecs compiled in, plus the encoders [`hw::probe`] finds
/// (FFmpeg's that passed their self-test, MediaCodec). H.264 through
/// Cisco's library needs [`Codecs::with_openh264`].
/// (FFmpeg's that passed their self-test, MediaCodec) and the decoders
/// [`hw::probe_decoders`] finds (FFmpeg's), both probed at once. H.264
/// through Cisco's library needs [`Codecs::with_openh264`].
pub fn new() -> Self {
let (factories, decoder_factories) = std::thread::scope(|scope| {
let decoders = scope.spawn(hw::probe_decoders);
(hw::probe(), decoders.join().unwrap_or_default())
});
Self {
factories: hw::probe().into_iter().map(Arc::from).collect(),
factories: factories.into_iter().map(Arc::from).collect(),
decoder_factories: decoder_factories.into_iter().map(Arc::from).collect(),
#[cfg(feature = "openh264")]
openh264: None,
preference: EncoderPreference::default(),
decoder_preference: DecoderPreference::default(),
}
}
/// Only the codecs compiled into this crate (libvpx, OpenH264 once
/// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed.
/// loaded, dav1d): no FFmpeg or MediaCodec encoders, no FFmpeg decoders,
/// nothing probed.
pub fn builtin() -> Self {
Self {
factories: Vec::new(),
decoder_factories: Vec::new(),
#[cfg(feature = "openh264")]
openh264: None,
preference: EncoderPreference::default(),
decoder_preference: DecoderPreference::default(),
}
}
/// Decode `factory`'s codec with it first (a decoder of the embedding
/// application, or a test's).
pub fn with_decoder(mut self, factory: Arc<dyn hw::DecoderFactory>) -> Self {
self.decoder_factories.insert(0, factory);
self
}
/// Use `preference` for [`decoders_for`](Self::decoders_for) and
/// [`new_decoder`](Self::new_decoder).
pub fn with_decoder_preference(mut self, preference: DecoderPreference) -> Self {
self.decoder_preference = preference;
self
}
pub fn set_decoder_preference(&mut self, preference: DecoderPreference) {
self.decoder_preference = preference;
}
pub fn decoder_preference(&self) -> &DecoderPreference {
&self.decoder_preference
}
/// Enable H.264 through a loaded OpenH264 library.
#[cfg(feature = "openh264")]
pub fn with_openh264(mut self, library: h264::OpenH264) -> Self {
@@ -525,32 +632,74 @@ impl Codecs {
/// Whether `codec` can be decoded, or why not.
pub fn check_decoder(&self, codec: Codec) -> Result<()> {
#[cfg(target_os = "android")]
if mediacodec::check_decoder(codec).is_ok() {
if !self.decoders_for(codec).is_empty() {
return Ok(());
}
match codec {
Codec::Vp8 | Codec::Vp9 => {
#[cfg(feature = "vpx")]
return vpx::check(codec, false);
#[cfg(not(feature = "vpx"))]
return Err(unavailable(codec, "built without the `vpx` feature"));
}
Codec::H264 if self.has_openh264() => Ok(()),
Codec::H264 => Err(unavailable(codec, "the OpenH264 library is not loaded")),
Codec::Av1 => {
#[cfg(feature = "av1")]
return Ok(());
#[cfg(not(feature = "av1"))]
return Err(unavailable(codec, "built without the `av1` feature"));
}
Codec::H265 => Err(unavailable(codec, "no HEVC decoder")),
if !self.decoder_candidates(codec).is_empty() {
let choice = &self.decoder_preference;
return Err(unavailable(codec, format!("its decoders are not used ({choice:?})")));
}
let builtin = match codec {
Codec::Vp8 | Codec::Vp9 if cfg!(feature = "vpx") => "libvpx has no decoder for it",
Codec::Vp8 | Codec::Vp9 => "built without the `vpx` feature",
Codec::H264 => "the OpenH264 library is not loaded",
Codec::Av1 => "built without the `av1` feature (dav1d)",
Codec::H265 => "nothing built in decodes it",
};
Err(unavailable(codec, format!("no FFmpeg decoder works here, and {builtin}")))
}
/// Decodable codecs in the viewer's order of preference.
/// Decodable codecs in the viewer's order of preference
/// ([`VIEWER_PREFERENCE`]): those with at least one decoder.
pub fn decoders(&self) -> Vec<Codec> {
VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect()
VIEWER_PREFERENCE.into_iter().filter(|&c| !self.decoders_for(c).is_empty()).collect()
}
/// Every decoder of `codec` here and whether it is a GPU one: the
/// platform's (MediaCodec), the factories (an application's, then
/// FFmpeg's hardware and software decoders), then the built-in ones.
fn decoder_candidates(&self, codec: Codec) -> Vec<(DecoderBackend, bool)> {
let mut list = Vec::new();
// The device's codecs (hardware, or Google's software ones): Android
// has no others, so hardware decoding off does not leave them out.
#[cfg(target_os = "android")]
if mediacodec::check_decoder(codec).is_ok() {
list.push((DecoderBackend::Hardware("mediacodec"), false));
}
for f in self.decoder_factories.iter().filter(|f| f.codec() == codec) {
list.push((f.backend(), f.is_hardware()));
}
match codec {
#[cfg(feature = "vpx")]
Codec::Vp8 | Codec::Vp9 if vpx::check(codec, false).is_ok() => {
list.push((DecoderBackend::Libvpx, false));
}
Codec::H264 if self.has_openh264() => list.push((DecoderBackend::OpenH264, false)),
#[cfg(feature = "av1")]
Codec::Av1 => list.push((DecoderBackend::Dav1d, false)),
_ => {}
}
list
}
/// The decoders of `codec` in the order a viewer tries them, its ladder:
/// hardware first (unless the [`DecoderPreference`] turns it off), then
/// FFmpeg's software decoders, then the built-in libvpx, OpenH264 and
/// dav1d; a backend named in the preference before all of them.
pub fn decoders_for(&self, codec: Codec) -> Vec<DecoderBackend> {
let all = self.decoder_candidates(codec);
let preference = &self.decoder_preference;
let automatic = |c: &&(DecoderBackend, bool)| preference.hardware || !c.1;
let chosen: Vec<&(DecoderBackend, bool)> = match &preference.backend {
BackendChoice::Auto => all.iter().filter(automatic).collect(),
BackendChoice::Software => all.iter().filter(|c| !c.1).collect(),
BackendChoice::Named(name) => {
let named = all.iter().filter(|c| c.0.name() == name);
let rest = all.iter().filter(|c| c.0.name() != name).filter(automatic);
named.chain(rest).collect()
}
};
chosen.into_iter().map(|c| c.0).collect()
}
/// Every usable encoder in the base order, before the preference.
@@ -618,24 +767,51 @@ impl Codecs {
codecs
}
/// A decoder for `codec`: the first of its ladder
/// ([`decoders_for`](Self::decoders_for)) that opens.
pub fn new_decoder(&self, codec: Codec) -> Result<Box<dyn VideoDecoder>> {
self.check_decoder(codec)?;
let mut last_error = None;
for backend in self.decoders_for(codec) {
match self.new_decoder_with(codec, backend) {
Ok(decoder) => return Ok(decoder),
Err(e) => {
tracing::warn!(%codec, %backend, "decoder failed to open: {e}");
last_error = Some(e);
}
}
}
Err(last_error.unwrap_or_else(|| unavailable(codec, "no decoder in this build")))
}
/// A decoder from a specific backend.
pub fn new_decoder_with(
&self,
codec: Codec,
backend: DecoderBackend,
) -> Result<Box<dyn VideoDecoder>> {
#[cfg(target_os = "android")]
if mediacodec::check_decoder(codec).is_ok() {
if backend == DecoderBackend::Hardware("mediacodec") {
return Ok(Box::new(mediacodec::MediaCodecDecoder::new(codec)?));
}
self.check_decoder(codec)?;
match codec {
if let Some(factory) =
self.decoder_factories.iter().find(|f| f.backend() == backend && f.codec() == codec)
{
return factory.create();
}
match backend {
#[cfg(feature = "vpx")]
Codec::Vp8 | Codec::Vp9 => Ok(Box::new(vpx::VpxDecoder::new(codec)?)),
DecoderBackend::Libvpx if matches!(codec, Codec::Vp8 | Codec::Vp9) => {
Ok(Box::new(vpx::VpxDecoder::new(codec)?))
}
#[cfg(feature = "openh264")]
Codec::H264 => match &self.openh264 {
DecoderBackend::OpenH264 if codec == Codec::H264 => match &self.openh264 {
Some(lib) => Ok(Box::new(lib.decoder()?)),
None => Err(unavailable(codec, "the OpenH264 library is not loaded")),
},
#[cfg(feature = "av1")]
Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)),
#[allow(unreachable_patterns)]
_ => Err(unavailable(codec, "no decoder in this build")),
DecoderBackend::Dav1d if codec == Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)),
_ => Err(unavailable(codec, format!("no decoder {backend} for it here"))),
}
}
@@ -776,7 +952,65 @@ impl Codecs {
Err("built without the `ffmpeg` feature".to_owned()),
Err("built without the `ffmpeg` feature".to_owned()),
);
EncoderReport { ffmpeg, zero_copy, encoders }
EncoderReport { ffmpeg, zero_copy, encoders, decoders: self.decoder_report() }
}
/// Every decoder this build knows, with what works here and why the
/// rest does not, and each one's place in its codec's ladder.
fn decoder_report(&self) -> Vec<DecoderInfo> {
let ladders: Vec<(Codec, Vec<DecoderBackend>)> =
Codec::ALL.into_iter().map(|c| (c, self.decoders_for(c))).collect();
let mut decoders = Vec::new();
let mut add = |backend: DecoderBackend, api: &str, codec, hardware, status| {
let ladder = ladders.iter().find(|(c, _)| *c == codec).map(|(_, l)| l);
decoders.push(DecoderInfo {
name: backend.name().to_owned(),
api: api.to_owned(),
codec,
hardware,
rank: ladder.and_then(|l| l.iter().position(|b| *b == backend)),
status,
});
};
#[cfg(target_os = "android")]
for codec in Codec::ALL {
if mediacodec::check_decoder(codec).is_ok() {
add(DecoderBackend::Hardware("mediacodec"), "MediaCodec", codec, true, Ok(()));
}
}
for f in &self.decoder_factories {
if !matches!(f.backend(), DecoderBackend::Ffmpeg(_)) {
add(f.backend(), f.api(), f.codec(), f.is_hardware(), Ok(()));
}
}
#[cfg(feature = "ffmpeg")]
for status in crate::ffmpeg::decoder::probe() {
let spec = status.spec;
let backend = DecoderBackend::Ffmpeg(spec.name);
add(backend, spec.api, spec.codec, spec.is_hardware(), status.available.clone());
}
for codec in [Codec::Vp8, Codec::Vp9] {
#[cfg(feature = "vpx")]
let status = vpx::check(codec, false).map_err(|e| e.to_string());
#[cfg(not(feature = "vpx"))]
let status = Err("built without the `vpx` feature".to_owned());
add(DecoderBackend::Libvpx, "libvpx", codec, false, status);
}
let status = if self.has_openh264() {
Ok(())
} else if cfg!(feature = "openh264") {
Err("Cisco's OpenH264 library is not loaded".to_owned())
} else {
Err("built without the `openh264` feature".to_owned())
};
add(DecoderBackend::OpenH264, "OpenH264 (Cisco)", Codec::H264, false, status);
let status = if cfg!(feature = "av1") {
Ok(())
} else {
Err("built without the `av1` feature".to_owned())
};
add(DecoderBackend::Dav1d, "dav1d", Codec::Av1, false, status);
decoders
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+836
View File
@@ -0,0 +1,836 @@
//! Video decoders through FFmpeg: the platform's hardware decoders first
//! (VA-API and, with NVIDIA's driver, NVDEC on Linux; D3D11VA and DXVA2 on
//! Windows; VideoToolbox on macOS), then FFmpeg's software decoders (dav1d
//! and libaom for AV1, FFmpeg's own HEVC, VP9, H.264 and VP8), each checked
//! by a self-test.
//!
//! Hardware decoding goes through FFmpeg's hwaccel API: FFmpeg's own decoder
//! (`av1`, `h264`, ...) with `AVCodecContext.hw_device_ctx` set (located
//! at load, see [`super::layout`]), so that its default `get_format` picks
//! the device's surfaces. Pictures are copied out of the GPU
//! (`av_hwframe_transfer_data`) into a frame of our own, reused, and from
//! there into the caller's [`VideoFrame`] (NV12), whose buffers are reused
//! as well ([`VideoDecoder::decode_into`]): a running decoder allocates
//! nothing per picture on our side. Software decoders give I420 (or NV12).
//!
//! Every decoder is set up for live video: slice threads only (frame
//! threads hold one frame per thread before the first picture comes out),
//! dav1d with a frame delay of one, so each frame's picture comes out of
//! the call that decoded it.
//!
//! [`probe`] runs every decoder once per process (in parallel) on a short
//! clip of its codec: three frames of a test picture encoded by this crate's
//! own encoders (`clips/`). Each frame must give its picture at once, at its
//! size and close to the test picture (PSNR), and a hardware decoder must
//! have decoded on the GPU: FFmpeg silently decodes in software when the
//! GPU lacks the codec (VP8 on AMD), which the self-test reports as
//! unusable, since FFmpeg's software decoder follows in the ladder anyway.
#![allow(unsafe_code)]
use std::ffi::c_int;
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::{Duration, Instant};
use super::Ffmpeg;
use super::encoder::{Device, log_suffix, vaapi_device};
use super::layout;
use super::sys::{EAGAIN, EOF, FrameHead, OPTION_NOT_FOUND, PacketHead, Ptr, cstr};
use crate::codec::hw::DecoderFactory;
use crate::codec::{Codec, DecoderBackend, VideoDecoder};
use crate::convert;
use crate::frame::{FrameData, FrameRef, PixelsRef, PlaneRef, VideoFrame, chroma_size};
use crate::{Error, Result};
/// One FFmpeg decoder this crate drives.
#[derive(Debug, PartialEq, Eq)]
pub struct DecoderSpec {
/// The name in settings (`stream.decoder_backend`) and logs: FFmpeg's
/// name of the hardware acceleration (`h264_vaapi`, `av1_nvdec`), or of
/// the decoder in software (`hevc`, `libdav1d`).
pub name: &'static str,
pub codec: Codec,
/// FFmpeg's decoder.
pub decoder: &'static str,
/// For hardware decoding: FFmpeg's device type (`vaapi`, `d3d11va`, ...)
/// and the pixel format of its pictures (`vaapi`, `d3d11`, ...).
pub hardware: Option<(&'static str, &'static str)>,
/// The API or library, for the UI.
pub api: &'static str,
}
macro_rules! hardware {
($name:literal, $codec:ident, $decoder:literal, $device:literal, $format:literal, $api:literal) => {
DecoderSpec {
name: $name,
codec: Codec::$codec,
decoder: $decoder,
hardware: Some(($device, $format)),
api: $api,
}
};
}
macro_rules! software {
($name:literal, $codec:ident, $api:literal) => {
DecoderSpec { name: $name, codec: Codec::$codec, decoder: $name, hardware: None, api: $api }
};
}
/// Every decoder of this platform, best first within its codec: hardware,
/// then software. The ones FFmpeg or the machine lacks fail the probe and
/// are skipped.
pub static DECODERS: &[DecoderSpec] = &[
#[cfg(target_os = "linux")]
hardware!("av1_vaapi", Av1, "av1", "vaapi", "vaapi", "VA-API"),
#[cfg(target_os = "linux")]
hardware!("hevc_vaapi", H265, "hevc", "vaapi", "vaapi", "VA-API"),
#[cfg(target_os = "linux")]
hardware!("vp9_vaapi", Vp9, "vp9", "vaapi", "vaapi", "VA-API"),
#[cfg(target_os = "linux")]
hardware!("h264_vaapi", H264, "h264", "vaapi", "vaapi", "VA-API"),
#[cfg(target_os = "linux")]
hardware!("vp8_vaapi", Vp8, "vp8", "vaapi", "vaapi", "VA-API"),
// NVIDIA's driver has no VA-API of its own.
#[cfg(target_os = "linux")]
hardware!("av1_nvdec", Av1, "av1", "cuda", "cuda", "NVDEC"),
#[cfg(target_os = "linux")]
hardware!("hevc_nvdec", H265, "hevc", "cuda", "cuda", "NVDEC"),
#[cfg(target_os = "linux")]
hardware!("vp9_nvdec", Vp9, "vp9", "cuda", "cuda", "NVDEC"),
#[cfg(target_os = "linux")]
hardware!("h264_nvdec", H264, "h264", "cuda", "cuda", "NVDEC"),
#[cfg(target_os = "linux")]
hardware!("vp8_nvdec", Vp8, "vp8", "cuda", "cuda", "NVDEC"),
// Every GPU vendor's; DXVA2 for systems without Direct3D 11 video.
#[cfg(windows)]
hardware!("av1_d3d11va", Av1, "av1", "d3d11va", "d3d11", "D3D11VA"),
#[cfg(windows)]
hardware!("hevc_d3d11va", H265, "hevc", "d3d11va", "d3d11", "D3D11VA"),
#[cfg(windows)]
hardware!("vp9_d3d11va", Vp9, "vp9", "d3d11va", "d3d11", "D3D11VA"),
#[cfg(windows)]
hardware!("h264_d3d11va", H264, "h264", "d3d11va", "d3d11", "D3D11VA"),
#[cfg(windows)]
hardware!("av1_dxva2", Av1, "av1", "dxva2", "dxva2_vld", "DXVA2"),
#[cfg(windows)]
hardware!("hevc_dxva2", H265, "hevc", "dxva2", "dxva2_vld", "DXVA2"),
#[cfg(windows)]
hardware!("vp9_dxva2", Vp9, "vp9", "dxva2", "dxva2_vld", "DXVA2"),
#[cfg(windows)]
hardware!("h264_dxva2", H264, "h264", "dxva2", "dxva2_vld", "DXVA2"),
#[cfg(target_vendor = "apple")]
hardware!("av1_videotoolbox", Av1, "av1", "videotoolbox", "videotoolbox_vld", "VideoToolbox"),
#[cfg(target_vendor = "apple")]
hardware!(
"hevc_videotoolbox",
H265,
"hevc",
"videotoolbox",
"videotoolbox_vld",
"VideoToolbox"
),
#[cfg(target_vendor = "apple")]
hardware!("vp9_videotoolbox", Vp9, "vp9", "videotoolbox", "videotoolbox_vld", "VideoToolbox"),
#[cfg(target_vendor = "apple")]
hardware!(
"h264_videotoolbox",
H264,
"h264",
"videotoolbox",
"videotoolbox_vld",
"VideoToolbox"
),
// FFmpeg's native AV1 decoder decodes in hardware only.
software!("libdav1d", Av1, "dav1d"),
software!("libaom-av1", Av1, "libaom"),
software!("hevc", H265, "FFmpeg"),
software!("vp9", Vp9, "FFmpeg"),
software!("h264", H264, "FFmpeg"),
software!("vp8", Vp8, "FFmpeg"),
];
impl DecoderSpec {
pub fn by_name(name: &str) -> Option<&'static DecoderSpec> {
DECODERS.iter().find(|d| d.name == name)
}
pub fn is_hardware(&self) -> bool {
self.hardware.is_some()
}
}
/// The process's device of FFmpeg type `kind` (its default one), shared by
/// all decoders; VA-API's is the encoders' (`VOELIN_VAAPI_DEVICE`, or the
/// first render node).
fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result<Ptr, String> {
if kind == "vaapi" {
return vaapi_device(ffmpeg);
}
type Devices = Vec<(&'static str, std::result::Result<Device, String>)>;
static DEVICES: Mutex<Devices> = Mutex::new(Vec::new());
let mut devices = DEVICES.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, device)) = devices.iter().find(|(k, _)| *k == kind) {
return device.as_ref().map(|d| d.0).map_err(Clone::clone);
}
let api = &ffmpeg.api;
let name = cstr(kind);
// SAFETY: a C string.
let id = unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) };
let created = if id <= 0 {
Err(format!("FFmpeg has no {kind} support"))
} else {
let mut device = std::ptr::null_mut();
// SAFETY: a valid out pointer; the type's default device, no options.
let ret = unsafe {
(api.av_hwdevice_ctx_create)(&mut device, id, std::ptr::null(), std::ptr::null_mut(), 0)
};
if ret < 0 {
Err(format!("{kind} device: {}{}", api.error_text(ret), log_suffix(kind)))
} else {
Ok(Device(device))
}
};
let result = created.as_ref().map(|d| d.0).map_err(Clone::clone);
devices.push((kind, created));
result
}
/// Threads of a software decoder: slice (or dav1d's tile and row) threads,
/// which add no delay.
fn decoder_threads() -> usize {
std::thread::available_parallelism().map_or(1, |n| n.get().min(8))
}
/// A decoder of one [`DecoderSpec`]; see the [module docs](self).
pub struct FfmpegDecoder {
ffmpeg: &'static Ffmpeg,
spec: &'static DecoderSpec,
ctx: Ptr,
packet: Ptr,
/// The decoder's pictures.
frame: Ptr,
/// Hardware pictures are copied here from the GPU (reused).
download: Ptr,
/// The pixel format of the device's pictures.
hw_format: Option<c_int>,
yuvj420p: Option<c_int>,
gpu_pictures: u64,
cpu_pictures: u64,
}
// SAFETY: the FFmpeg objects belong to this decoder alone and are used from
// one thread at a time (`&mut self`); FFmpeg's decoders have no thread
// affinity.
unsafe impl Send for FfmpegDecoder {}
impl FfmpegDecoder {
/// A decoder of `spec`, opened at once (on its device for hardware
/// decoding).
pub fn new(spec: &'static DecoderSpec) -> Result<Self> {
let unavailable = |reason: String| Error::CodecUnavailable { codec: spec.codec, reason };
let ffmpeg = Ffmpeg::get().map_err(|e| unavailable(e.to_owned()))?;
let api = &ffmpeg.api;
// Filled in one by one; Drop frees what was made.
let mut this = Self {
ffmpeg,
spec,
ctx: std::ptr::null_mut(),
packet: std::ptr::null_mut(),
frame: std::ptr::null_mut(),
download: std::ptr::null_mut(),
hw_format: None,
yuvj420p: api.pix_fmt("yuvj420p"),
gpu_pictures: 0,
cpu_pictures: 0,
};
let name = cstr(spec.decoder);
// SAFETY: a C string; returns a static codec or NULL.
let codec = unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) };
if codec.is_null() {
return Err(unavailable(format!("{} is not in this FFmpeg build", spec.decoder)));
}
// SAFETY: allocates a context with the decoder's private options.
this.ctx = unsafe { (api.avcodec_alloc_context3)(codec) };
if this.ctx.is_null() {
return Err(unavailable("avcodec_alloc_context3 failed".into()));
}
// SAFETY: `ctx` is a live codec context; the first child is its
// private options object (NULL if the decoder has none).
let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) };
// A hardware decoder's work is on the GPU.
let threads = if spec.is_hardware() { 1 } else { decoder_threads() };
this.set(this.ctx, "threads", &threads.to_string());
this.set(this.ctx, "thread_type", "slice");
if spec.decoder == "libdav1d"
&& this.set(private, "max_frame_delay", "1") == OPTION_NOT_FOUND
{
// Before FFmpeg 5.0.
this.set(private, "framethreads", "1");
}
if let Some((kind, format)) = spec.hardware {
let device = hw_device(ffmpeg, kind).map_err(unavailable)?;
let offset = ffmpeg.codec_hw_device.clone().map_err(unavailable)?;
let format =
api.pix_fmt(format).ok_or_else(|| unavailable(format!("no {format} format")))?;
this.hw_format = Some(format);
// SAFETY: `device` is a live device reference; `offset` is
// AVCodecContext.hw_device_ctx (located and checked at load),
// which takes the new reference and frees it with the context.
unsafe {
let reference = (api.av_buffer_ref)(device);
if reference.is_null() {
return Err(unavailable("out of memory".into()));
}
layout::write::<Ptr>(this.ctx, offset, reference);
}
}
// SAFETY: a configured context and its codec; no options dictionary.
let ret = unsafe { (api.avcodec_open2)(this.ctx, codec, std::ptr::null_mut()) };
if ret < 0 {
return Err(this.error("open", ret));
}
// SAFETY: allocations, checked below.
unsafe {
this.packet = (api.av_packet_alloc)();
this.frame = (api.av_frame_alloc)();
this.download = (api.av_frame_alloc)();
}
if this.packet.is_null() || this.frame.is_null() || this.download.is_null() {
return Err(unavailable("out of memory".into()));
}
Ok(this)
}
pub fn spec(&self) -> &'static DecoderSpec {
self.spec
}
/// Pictures decoded on the GPU so far.
pub fn gpu_pictures(&self) -> u64 {
self.gpu_pictures
}
/// Pictures decoded in software so far (by a hardware decoder: the GPU
/// did not take the stream, and FFmpeg decoded it itself).
pub fn cpu_pictures(&self) -> u64 {
self.cpu_pictures
}
/// Set an option of `obj` (the context, or its private options) by name;
/// one this release does not know is skipped.
fn set(&self, obj: Ptr, name: &str, value: &str) -> c_int {
if obj.is_null() {
return OPTION_NOT_FOUND;
}
let (name, value) = (cstr(name), cstr(value));
// SAFETY: an AVClass-enabled object and two C strings.
unsafe { (self.ffmpeg.api.av_opt_set)(obj, name.as_ptr(), value.as_ptr(), 0) }
}
fn error(&self, what: &str, code: c_int) -> Error {
self.failed(format!(
"{what}: {}{}",
self.ffmpeg.api.error_text(code),
log_suffix(self.spec.decoder)
))
}
fn failed(&self, message: String) -> Error {
Error::Decoder { codec: self.spec.codec, message: format!("{} {message}", self.spec.name) }
}
/// Hand `data` to the decoder. The packet points at it only during the
/// call: it is not reference-counted, so FFmpeg copies the data into a
/// padded buffer of its own.
fn send(&mut self, data: &[u8], size: c_int) -> c_int {
let packet = self.packet.cast::<PacketHead>();
// SAFETY: our packet (from av_packet_alloc, so at least as large as
// its leading fields); emptied again before `data` goes away.
unsafe {
(*packet).data = data.as_ptr().cast_mut();
(*packet).size = size;
let ret = (self.ffmpeg.api.avcodec_send_packet)(self.ctx, self.packet);
(*packet).data = std::ptr::null_mut();
(*packet).size = 0;
ret
}
}
/// Take every picture that is ready; the last one ends up in `out`.
fn receive(&mut self, out: &mut VideoFrame) -> Result<bool> {
let mut got = false;
loop {
// SAFETY: a live context and our frame.
let ret = unsafe { (self.ffmpeg.api.avcodec_receive_frame)(self.ctx, self.frame) };
if ret == EAGAIN || ret == EOF {
return Ok(got);
}
if ret < 0 {
return Err(self.error("decoding", ret));
}
let copied = self.copy_picture(out);
// SAFETY: our frame; its buffers go back to the decoder.
unsafe { (self.ffmpeg.api.av_frame_unref)(self.frame) };
copied?;
got = true;
}
}
/// The decoded picture into `out`: from the GPU through the download
/// frame, or straight from FFmpeg's buffers.
fn copy_picture(&mut self, out: &mut VideoFrame) -> Result<()> {
let api = &self.ffmpeg.api;
let head = self.frame.cast::<FrameHead>();
// SAFETY: a frame the decoder just filled.
let (format, width, height) = unsafe { ((*head).format, (*head).width, (*head).height) };
let source = if Some(format) == self.hw_format {
let download = self.download.cast::<FrameHead>();
// SAFETY: the download frame is ours: its leading fields are set
// before av_frame_get_buffer as documented, and its buffers are
// referenced by nothing else, so they are writable.
unsafe {
if (*download).data[0].is_null()
|| ((*download).width, (*download).height) != (width, height)
{
(api.av_frame_unref)(self.download);
(*download).width = width;
(*download).height = height;
(*download).format = self.ffmpeg.pix.nv12;
let ret = (api.av_frame_get_buffer)(self.download, 0);
if ret < 0 {
return Err(self.error("picture buffer", ret));
}
}
let ret = (api.av_hwframe_transfer_data)(self.download, self.frame, 0);
if ret < 0 {
return Err(self.error("copy from the GPU", ret));
}
}
self.gpu_pictures += 1;
self.download
} else {
self.cpu_pictures += 1;
self.frame
};
// SAFETY: `source` holds a picture until it is unreferenced, after
// this copy.
unsafe { self.view(source) }?.copy_to(out);
Ok(())
}
/// The picture in `frame`, borrowed.
///
/// # Safety
/// `frame` must hold a picture that stays as it is while the view is
/// used.
unsafe fn view(&self, frame: Ptr) -> Result<FrameRef<'_>> {
// SAFETY: guaranteed by the caller.
let head = unsafe { &*frame.cast::<FrameHead>() };
let (Ok(width), Ok(height)) = (u32::try_from(head.width), u32::try_from(head.height))
else {
return Err(self.failed("gave a picture of no size".into()));
};
if width == 0 || height == 0 {
return Err(self.failed("gave a picture of no size".into()));
}
let (w, h) = (width as usize, height as usize);
let (cw, ch) = chroma_size(width, height);
let plane = |i: usize, bytes: usize, rows: usize| -> Result<PlaneRef<'_>> {
let stride = usize::try_from(head.linesize[i]).unwrap_or(0);
if head.data[i].is_null() || stride < bytes {
return Err(self.failed(format!("gave plane {i} with a line size of {stride}")));
}
// SAFETY: FFmpeg's planes hold `linesize` bytes for every row of
// the picture but the last, which holds at least the row.
let data =
unsafe { std::slice::from_raw_parts(head.data[i], stride * (rows - 1) + bytes) };
Ok(PlaneRef::new(data, stride))
};
let pix = self.ffmpeg.pix;
let pixels = if head.format == pix.yuv420p || Some(head.format) == self.yuvj420p {
PixelsRef::I420 { y: plane(0, w, h)?, u: plane(1, cw, ch)?, v: plane(2, cw, ch)? }
} else if head.format == pix.nv12 {
PixelsRef::Nv12 { y: plane(0, w, h)?, uv: plane(1, cw * 2, ch)? }
} else {
return Err(self.failed(format!(
"gave pictures in {} (only 8-bit 4:2:0 is supported)",
self.ffmpeg.api.pix_fmt_name(head.format)
)));
};
Ok(FrameRef { width, height, timestamp: Duration::ZERO, pixels })
}
}
impl Drop for FfmpegDecoder {
fn drop(&mut self) {
let api = &self.ffmpeg.api;
// SAFETY: each pointer is NULL or owned by this decoder; the context
// frees its device reference.
unsafe {
(api.av_packet_free)(&mut self.packet);
(api.av_frame_free)(&mut self.frame);
(api.av_frame_free)(&mut self.download);
(api.avcodec_free_context)(&mut self.ctx);
}
}
}
impl VideoDecoder for FfmpegDecoder {
fn codec(&self) -> Codec {
self.spec.codec
}
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>> {
let mut picture = VideoFrame::black_i420(0, 0);
Ok(self.decode_into(data, &mut picture)?.then_some(picture))
}
/// FFmpeg's H.264 decoder conceals what a lost frame left missing (from
/// the previous picture), and its HEVC decoder makes up missing
/// references; VP8, VP9 and AV1 fail on them or show garbage.
fn conceals_errors(&self) -> bool {
matches!(self.spec.codec, Codec::H264 | Codec::H265)
}
fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result<bool> {
if data.is_empty() {
return Ok(false);
}
let size =
c_int::try_from(data.len()).map_err(|_| self.failed("frame too large".into()))?;
let mut got = false;
let mut ret = self.send(data, size);
if ret == EAGAIN {
// Pictures have to be taken out before more data goes in.
got |= self.receive(out)?;
ret = self.send(data, size);
}
if ret < 0 {
return Err(self.error("decoding", ret));
}
got |= self.receive(out)?;
Ok(got)
}
}
/// Creates decoders of one [`DecoderSpec`] that passed its self-test.
pub struct FfmpegDecoderFactory(pub &'static DecoderSpec);
impl FfmpegDecoderFactory {
/// Factories of the decoders that passed their self-test, in
/// [`DECODERS`] order (hardware first).
pub fn available() -> Vec<FfmpegDecoderFactory> {
probe()
.iter()
.filter(|s| s.available.is_ok())
.map(|s| FfmpegDecoderFactory(s.spec))
.collect()
}
}
impl DecoderFactory for FfmpegDecoderFactory {
fn backend(&self) -> DecoderBackend {
DecoderBackend::Ffmpeg(self.0.name)
}
fn codec(&self) -> Codec {
self.0.codec
}
fn api(&self) -> &'static str {
self.0.api
}
fn is_hardware(&self) -> bool {
self.0.is_hardware()
}
fn create(&self) -> Result<Box<dyn VideoDecoder>> {
Ok(Box::new(FfmpegDecoder::new(self.0)?))
}
}
/// Size of the self-test clips: one every hardware decoder takes (NVDEC
/// wants at least 144x144 for HEVC), and a multiple of what AV1 encoders
/// pad to (64x16 on RDNA3), so that the AV1 clip declares exactly this.
pub(crate) const CLIP_SIZE: (u32, u32) = (320, 240);
/// Frames per clip: a keyframe and two that predict from it.
const CLIP_FRAMES: usize = 3;
/// How close a decoded clip picture must be to [`clip_picture`]; the clips
/// decode at well over 40 dB.
const CLIP_PSNR: f64 = 30.0;
/// The self-test clip of `codec`: [`CLIP_FRAMES`] frames of
/// [`clip_picture`] encoded by this crate's encoders (see
/// `write_self_test_clips` in the tests), each as a little-endian `u32`
/// length and the frame as a stream carries it (Annex B for H.264 and HEVC,
/// a temporal unit of OBUs for AV1).
fn clip(codec: Codec) -> &'static [u8] {
match codec {
Codec::Av1 => include_bytes!("clips/av1.bin"),
Codec::H265 => include_bytes!("clips/hevc.bin"),
Codec::Vp9 => include_bytes!("clips/vp9.bin"),
Codec::H264 => include_bytes!("clips/h264.bin"),
Codec::Vp8 => include_bytes!("clips/vp8.bin"),
}
}
fn clip_frames(codec: Codec) -> impl Iterator<Item = &'static [u8]> {
let mut rest = clip(codec);
std::iter::from_fn(move || {
let (length, tail) = rest.split_first_chunk::<4>()?;
let (frame, tail) = tail.split_at_checked(u32::from_le_bytes(*length) as usize)?;
rest = tail;
Some(frame)
})
}
/// Frame `n` of the self-test clips: a luma ramp, chroma ramps the other
/// way, and a bright square that moves 24 pixels per frame.
fn clip_picture(n: usize) -> VideoFrame {
let (width, height) = CLIP_SIZE;
let (w, h) = (width as usize, height as usize);
let mut frame = VideoFrame::black_i420(width, height);
let FrameData::I420 { y, u, v } = &mut frame.data else { unreachable!("black_i420") };
let left = 32 + 24 * n;
for row in 0..h {
for col in 0..w {
let square = (left..left + 64).contains(&col) && (64..128).contains(&row);
y.data[row * w + col] = if square { 235 } else { 16 + (col * 200 / w) as u8 };
}
}
let (cw, ch) = (w / 2, h / 2);
for row in 0..ch {
for col in 0..cw {
u.data[row * cw + col] = 64 + (row * 128 / ch) as u8;
v.data[row * cw + col] = 192 - (col * 128 / cw) as u8;
}
}
frame.with_timestamp(Duration::from_millis(33 * n as u64))
}
/// Decode `spec`'s clip: every frame's picture at once, at its size, close
/// to the test picture; on the GPU for a hardware decoder.
fn test_decoder(spec: &'static DecoderSpec) -> std::result::Result<(), String> {
let reason = |e: Error| match e {
Error::CodecUnavailable { reason, .. } => reason,
Error::Decoder { message, .. } => message,
e => e.to_string(),
};
let mut decoder = FfmpegDecoder::new(spec).map_err(reason)?;
let mut picture = VideoFrame::black_i420(0, 0);
let mut frames = 0;
for (n, data) in clip_frames(spec.codec).enumerate() {
if !decoder.decode_into(data, &mut picture).map_err(reason)? {
return Err(format!("no picture from frame {n} of the self-test clip"));
}
if (picture.width, picture.height) != CLIP_SIZE {
let (w, h) = CLIP_SIZE;
return Err(format!(
"frame {n} decoded at {}x{} instead of {w}x{h}",
picture.width, picture.height
));
}
let psnr = convert::psnr(&clip_picture(n), &picture).map_err(|e| e.to_string())?;
if psnr < CLIP_PSNR {
return Err(format!("frame {n} decoded wrong (PSNR {psnr:.1} dB)"));
}
frames += 1;
}
if frames != CLIP_FRAMES {
return Err(format!("the {} self-test clip has {frames} frames", spec.codec));
}
if spec.is_hardware() && decoder.cpu_pictures > 0 {
return Err(format!(
"the GPU does not decode {} here (FFmpeg fell back to software){}",
spec.codec,
log_suffix(spec.decoder)
));
}
Ok(())
}
/// Why `spec` cannot work here before trying it, if that is known: not in
/// this FFmpeg build, or (NVDEC) no NVIDIA GPU, whose driver would spend
/// its initialisation failing.
fn absent(ffmpeg: &Ffmpeg, spec: &DecoderSpec) -> Option<String> {
let api = &ffmpeg.api;
let name = cstr(spec.decoder);
// SAFETY: a C string; returns a static codec or NULL.
if unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) }.is_null() {
return Some(format!("{} is not in this FFmpeg build", spec.decoder));
}
let (kind, _) = spec.hardware?;
let name = cstr(kind);
// SAFETY: a C string.
if unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) } <= 0 {
return Some(format!("FFmpeg has no {kind} support"));
}
#[cfg(target_os = "linux")]
if kind == "cuda" {
use super::encoder::{drm_vendors, vendor};
let vendors = drm_vendors();
if !vendors.is_empty()
&& !vendors.contains(&vendor::NVIDIA)
&& !std::path::Path::new("/dev/nvidiactl").exists()
{
return Some("no NVIDIA GPU in this machine".into());
}
}
None
}
/// A decoder and the result of its self-test.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DecoderStatus {
pub spec: &'static DecoderSpec,
/// `Ok` if it decoded the self-test clip, else why not.
pub available: std::result::Result<(), String>,
/// How long its self-test took (they run in parallel).
pub took: Duration,
}
/// Every decoder of [`DECODERS`] with its self-test result (run once per
/// process, the decoders in parallel). Empty without FFmpeg.
pub fn probe() -> &'static [DecoderStatus] {
static PROBE: OnceLock<Vec<DecoderStatus>> = OnceLock::new();
PROBE.get_or_init(|| {
let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() };
let started = Instant::now();
let statuses: Vec<DecoderStatus> = std::thread::scope(|scope| {
let tests: Vec<_> = DECODERS
.iter()
.map(|spec| {
let absent = absent(ffmpeg, spec);
let test = absent.is_none().then(|| {
scope.spawn(move || {
let started = Instant::now();
(test_decoder(spec), started.elapsed())
})
});
(spec, absent, test)
})
.collect();
tests
.into_iter()
.map(|(spec, absent, test)| {
let (available, took) = match test {
None => (Err(absent.unwrap_or_default()), Duration::ZERO),
Some(handle) => handle.join().unwrap_or_else(|_| {
(Err("the self-test panicked".into()), Duration::ZERO)
}),
};
DecoderStatus { spec, available, took }
})
.collect()
});
for status in &statuses {
match &status.available {
Ok(()) => tracing::info!(
decoder = status.spec.name,
ms = status.took.as_millis() as u64,
"FFmpeg decoder available"
),
Err(e) => tracing::debug!(
decoder = status.spec.name,
ms = status.took.as_millis() as u64,
"FFmpeg decoder unusable: {e}"
),
}
}
tracing::info!(
ms = started.elapsed().as_millis() as u64,
tested = statuses.iter().filter(|s| !s.took.is_zero()).count(),
"FFmpeg decoders probed"
);
statuses
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codec::{Codecs, EncoderConfig};
#[test]
fn decoder_table() {
for (i, spec) in DECODERS.iter().enumerate() {
assert!(DECODERS[..i].iter().all(|d| d.name != spec.name), "{} twice", spec.name);
assert_eq!(DecoderSpec::by_name(spec.name), Some(spec));
// Hardware first within a codec, so the probe's order is the
// ladder's.
let later_hardware =
DECODERS[i..].iter().any(|d| d.codec == spec.codec && d.is_hardware());
assert!(spec.is_hardware() || !later_hardware, "{} before hardware", spec.name);
}
assert!(DecoderSpec::by_name("h264").is_some_and(|d| !d.is_hardware()));
}
/// The clips hold [`CLIP_FRAMES`] frames each, the first a keyframe.
#[test]
fn clips_are_complete() {
for codec in Codec::ALL {
let frames: Vec<&[u8]> = clip_frames(codec).collect();
assert_eq!(frames.len(), CLIP_FRAMES, "{codec}");
assert!(frames.iter().all(|f| !f.is_empty()), "{codec}");
}
}
/// libvpx, always built in on the desktop, decodes the VP8 and VP9 clips
/// to the test picture: the clips and [`clip_picture`] belong together.
#[cfg(feature = "vpx")]
#[test]
fn clips_match_the_test_picture() {
for codec in [Codec::Vp8, Codec::Vp9] {
let mut decoder = crate::codec::vpx::VpxDecoder::new(codec).unwrap();
for (n, data) in clip_frames(codec).enumerate() {
let picture = decoder.decode(data).unwrap().expect("a picture per frame");
let psnr = convert::psnr(&clip_picture(n), &picture).unwrap();
assert!(psnr > 40.0, "{codec} frame {n}: {psnr:.1} dB");
}
}
}
/// Writes the self-test clips (`src/ffmpeg/clips/*.bin`) with the best
/// encoder of each codec this machine has: run again only when
/// [`clip_picture`] changes. Needs an encoder of every codec (HEVC is
/// encoded in hardware only).
#[test]
#[ignore = "writes the decoders' self-test clips"]
fn write_self_test_clips() {
let codecs = Codecs::new();
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ffmpeg/clips");
for codec in Codec::ALL {
// A high bitrate for a high PSNR, the keyframe dominating.
let config =
EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(codec, config).unwrap();
let mut clip = Vec::new();
let mut frames = 0;
// Hardware encoders may hold a frame or two.
for n in 0..CLIP_FRAMES + 8 {
let source = clip_picture(n.min(CLIP_FRAMES - 1));
let source = source.with_timestamp(Duration::from_millis(33 * n as u64));
for packet in encoder.encode(&source, n == 0).unwrap() {
if frames < CLIP_FRAMES {
let index = (packet.pts_90khz / 2970) as usize;
assert_eq!(index, frames, "{codec}: packets out of order");
assert_eq!(packet.keyframe, frames == 0, "{codec} frame {frames}");
clip.extend_from_slice(&(packet.data.len() as u32).to_le_bytes());
clip.extend_from_slice(&packet.data);
frames += 1;
}
}
}
assert_eq!(frames, CLIP_FRAMES, "{codec}");
let name = match codec {
Codec::H265 => "hevc".to_owned(),
c => c.name().to_ascii_lowercase(),
};
std::fs::write(dir.join(format!("{name}.bin")), &clip).unwrap();
eprintln!("{codec}: {} bytes from {}", clip.len(), encoder.backend());
}
}
}
+5 -5
View File
@@ -393,7 +393,7 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec<
/// The process's VA-API device: `VOELIN_VAAPI_DEVICE`, or the first DRM
/// render node.
struct Device(Ptr);
pub(super) struct Device(pub(super) Ptr);
// SAFETY: an AVBufferRef of an AVHWDeviceContext, never freed; FFmpeg's
// VA-API device may be used from several threads (libva locks per display).
@@ -415,7 +415,7 @@ pub fn vaapi_device_path() -> Option<String> {
nodes.into_iter().next()
}
fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
pub(super) fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
static DEVICE: OnceLock<std::result::Result<Device, String>> = OnceLock::new();
DEVICE
.get_or_init(|| {
@@ -518,7 +518,7 @@ pub(crate) fn vaapi_pool(
}
/// FFmpeg's recent messages, appended to an error.
fn log_suffix(context: &str) -> String {
pub(super) fn log_suffix(context: &str) -> String {
let log = take_log(context);
if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) }
}
@@ -1618,7 +1618,7 @@ fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool {
/// PCI vendor of a GPU, as `/sys/class/drm/*/device/vendor` gives it.
#[cfg(target_os = "linux")]
mod vendor {
pub(super) mod vendor {
pub const AMD: u32 = 0x1002;
pub const NVIDIA: u32 = 0x10de;
pub const INTEL: u32 = 0x8086;
@@ -1628,7 +1628,7 @@ mod vendor {
/// `/sys/class/drm` says nothing (a container without it, say), which is
/// taken as "unknown" and skips nothing.
#[cfg(target_os = "linux")]
fn drm_vendors() -> &'static [u32] {
pub(super) fn drm_vendors() -> &'static [u32] {
static VENDORS: OnceLock<Vec<u32>> = OnceLock::new();
VENDORS.get_or_init(|| {
let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() };
+33 -14
View File
@@ -11,7 +11,7 @@
//! | Field | Why | How it is found | Check |
//! |---|---|---|---|
//! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts |
//! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context |
//! | `AVCodecContext.hw_frames_ctx`, `hw_device_ctx` | VA-API input frames; the device of hardware decoders | next to fields that have AVOptions, whose offsets `av_opt_find` reports: `hw_frames_ctx`, `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or `hw_frames_ctx` two fields before `max_pixels` and `hw_device_ctx` right after it (up to 60) | the neighbours' option offsets must match the layout, and both fields must be NULL in a new context |
//! | `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 |
@@ -168,68 +168,74 @@ struct HwFields59 {
hwaccel_flags: c_int,
}
/// Where `hw_frames_ctx` is in `AVCodecContext`, from the offsets of
/// neighbouring AVOptions, checked in a new context.
pub fn codec_hw_frames(api: &Api) -> Result<usize, String> {
/// Where `hw_frames_ctx` and `hw_device_ctx` are in `AVCodecContext`, from
/// the offsets of neighbouring AVOptions, checked in a new context: the
/// frame pool of VA-API encoders, and the device hardware decoders decode
/// on.
pub fn codec_hw_fields(api: &Api) -> Result<(usize, usize), String> {
// 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 result = locate_hw_frames(api, ctx);
let result = locate_hw_fields(api, ctx);
// SAFETY: allocated above.
unsafe { (api.avcodec_free_context)(&mut ctx) };
result
}
fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result<usize, String> {
fn locate_hw_fields(api: &Api, ctx: Ptr) -> Result<(usize, usize), String> {
let offset = |name| option_offset(api, ctx, name);
let flags = offset("hwaccel_flags").ok_or("no hwaccel_flags option")?;
let found = 'found: {
let (found, device) = 'found: {
// libavcodec 61+: anchored at err_recognition and extra_hw_frames.
if let Some(err) = offset("err_detect")
&& let Some(base) = err.checked_sub(offset_of!(HwFieldsNew, err_recognition))
&& base + offset_of!(HwFieldsNew, hwaccel_flags) == flags
&& offset("extra_hw_frames") == Some(base + offset_of!(HwFieldsNew, extra_hw_frames))
{
break 'found base + offset_of!(HwFieldsNew, hw_frames_ctx);
break 'found (
base + offset_of!(HwFieldsNew, hw_frames_ctx),
base + offset_of!(HwFieldsNew, hw_device_ctx),
);
}
// Up to 60: anchored at max_pixels. `sub_text_format` (a field up to
// 59) only matters on 32-bit targets, where the version decides.
// SAFETY: no arguments.
let major = unsafe { (api.avcodec_version)() } >> 16;
if let Some(max_pixels) = offset("max_pixels") {
let (max_off, flags_off, frames_off) = if major < 60 {
let (max_off, flags_off, frames_off, device_off) = if major < 60 {
(
offset_of!(HwFields59, max_pixels),
offset_of!(HwFields59, hwaccel_flags),
offset_of!(HwFields59, hw_frames_ctx),
offset_of!(HwFields59, hw_device_ctx),
)
} else {
(
offset_of!(HwFields60, max_pixels),
offset_of!(HwFields60, hwaccel_flags),
offset_of!(HwFields60, hw_frames_ctx),
offset_of!(HwFields60, hw_device_ctx),
)
};
if let Some(base) = max_pixels.checked_sub(max_off)
&& base + flags_off == flags
{
break 'found base + frames_off;
break 'found (base + frames_off, base + device_off);
}
}
return Err(
"unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into()
);
};
let device = found + size_of::<Ptr>();
// SAFETY: both offsets lie before `hwaccel_flags`, an option of this
// context, so inside it; pointer-aligned by construction.
let (frames, device) = unsafe { (read::<Ptr>(ctx, found), read::<Ptr>(ctx, device)) };
if !frames.is_null() || !device.is_null() {
let (frames, device_ref) = unsafe { (read::<Ptr>(ctx, found), read::<Ptr>(ctx, device)) };
if !frames.is_null() || !device_ref.is_null() {
return Err("AVCodecContext.hw_frames_ctx check failed (not NULL in a new context)".into());
}
Ok(found)
Ok((found, device))
}
/// Where `sample_fmt` is in `AVCodecContext`, from the offsets of the
@@ -578,6 +584,19 @@ mod tests {
assert_eq!(offset_of!(HwFields60, max_pixels) - offset_of!(HwFields60, hw_frames_ctx), 16);
assert_eq!(offset_of!(HwFields59, max_pixels) - offset_of!(HwFields59, hw_frames_ctx), 16);
assert_eq!(offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, max_pixels), 16);
// `hw_device_ctx` right before `hwaccel_flags` in every layout.
assert_eq!(
offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, hw_device_ctx),
8
);
assert_eq!(
offset_of!(HwFields59, hwaccel_flags) - offset_of!(HwFields59, hw_device_ctx),
8
);
assert_eq!(
offset_of!(HwFieldsNew, hwaccel_flags) - offset_of!(HwFieldsNew, hw_device_ctx),
8
);
// 7.1: err_recognition 528, hw_frames_ctx 552, hwaccel_flags 568.
assert_eq!(offset_of!(HwFieldsNew, hw_frames_ctx), 552 - 528);
assert_eq!(offset_of!(HwFieldsNew, hwaccel_flags), 568 - 528);
+22 -3
View File
@@ -1,6 +1,8 @@
//! FFmpeg, loaded at runtime (feature `ffmpeg`): hardware video encoders
//! (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox) and
//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom).
//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom); video
//! decoders, in hardware (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox) and
//! in software (dav1d, FFmpeg's own), see [`decoder`].
//!
//! FFmpeg is never linked or shipped: [`Ffmpeg::get`] finds the system's
//! (or `VOELIN_FFMPEG_DIR`'s) libavcodec and libavutil, whatever their major
@@ -11,7 +13,8 @@
//!
//! [`probe`] lists every encoder backend with the result of a self-test (one
//! small frame encoded), so a backend whose driver or GPU is missing is
//! skipped with a reason, without affecting the others.
//! skipped with a reason, without affecting the others;
//! [`decoder::probe`] does the same for decoders (a short clip decoded).
#![allow(unsafe_code)]
use std::ffi::{CStr, c_char, c_int};
@@ -20,6 +23,7 @@ use std::sync::{Mutex, OnceLock};
pub mod audio;
pub mod avio;
pub mod decoder;
pub mod encoder;
mod gpu;
mod layout;
@@ -29,6 +33,7 @@ mod vpp;
pub(crate) use gpu::Surface;
pub use gpu::{GpuConverter, GpuLayer};
pub use decoder::{DECODERS, DecoderSpec, DecoderStatus, FfmpegDecoder};
pub use encoder::{
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
};
@@ -82,6 +87,8 @@ pub struct Ffmpeg {
pub(crate) frame: FrameFields,
/// `AVCodecContext.hw_frames_ctx`.
pub(crate) codec_hw_frames: Result<usize, String>,
/// `AVCodecContext.hw_device_ctx`, for hardware decoders.
pub(crate) codec_hw_device: Result<usize, String>,
/// `AVFrame.buf[0]` / `hw_frames_ctx`.
pub(crate) frame_refs: Result<FrameRefs, String>,
/// `AVCodecContext.sample_fmt`, for the AAC encoder of RTMP output.
@@ -122,7 +129,9 @@ impl Ffmpeg {
drm_prime: api.pix_fmt("drm_prime"),
bgr0: api.pix_fmt("bgr0"),
};
let codec_hw_frames = layout::codec_hw_frames(&api);
let hw_fields = layout::codec_hw_fields(&api);
let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames);
let codec_hw_device = hw_fields.map(|(_, device)| device);
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| {
@@ -159,6 +168,7 @@ impl Ffmpeg {
_libs: libs,
frame,
codec_hw_frames,
codec_hw_device,
frame_refs,
codec_sample_fmt,
io,
@@ -292,6 +302,15 @@ mod tests {
if cfg!(target_pointer_width = "64") {
assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs);
}
// `hw_device_ctx`, where FFmpeg 9's headers put it (libavcodec 63:
// `hw_frames_ctx` 552, `hw_device_ctx` 560 on x86-64).
let (frames, device) = (ffmpeg.codec_hw_frames.clone(), ffmpeg.codec_hw_device.clone());
// SAFETY: no arguments.
if cfg!(target_pointer_width = "64")
&& unsafe { (ffmpeg.api.avcodec_version)() } >> 16 == 63
{
assert_eq!((frames, device), (Ok(552), Ok(560)));
}
}
/// `AVIOContext.error` is where the headers of the installed releases
+12
View File
@@ -226,6 +226,7 @@ api! {
fn av_opt_child_next(obj: Ptr, prev: Ptr) -> Ptr;
fn av_strerror(errnum: c_int, buf: *mut c_char, size: usize) -> c_int;
fn av_get_pix_fmt(name: *const c_char) -> c_int;
fn av_get_pix_fmt_name(fmt: c_int) -> *const c_char;
fn av_log_set_level(level: c_int);
fn av_log_set_callback(callback: Option<LogCallback>);
fn av_log_format_line2(
@@ -617,6 +618,17 @@ impl Api {
let fmt = unsafe { (self.av_get_pix_fmt)(name.as_ptr()) };
(fmt >= 0).then_some(fmt)
}
/// The name of pixel format `fmt` (for messages).
pub fn pix_fmt_name(&self, fmt: c_int) -> String {
// SAFETY: returns a static string, or NULL for an unknown format.
let name = unsafe { (self.av_get_pix_fmt_name)(fmt) };
if name.is_null() {
return format!("pixel format {fmt}");
}
// SAFETY: a NUL-terminated static string.
unsafe { CStr::from_ptr(name) }.to_string_lossy().into_owned()
}
}
#[cfg(test)]
+59 -3
View File
@@ -89,11 +89,19 @@ impl<'a> PlaneRef<'a> {
/// A tightly packed copy of `width` x `rows` bytes.
fn to_plane(self, width: usize, rows: usize) -> Plane {
let mut data = Vec::with_capacity(width * rows);
let mut plane = Plane::new(Vec::with_capacity(width * rows), width);
self.copy_into(&mut plane, width, rows);
plane
}
/// As [`to_plane`](Self::to_plane), into `dst`'s buffer (which only
/// grows).
fn copy_into(self, dst: &mut Plane, width: usize, rows: usize) {
dst.data.clear();
for y in 0..rows {
data.extend_from_slice(self.row(y, width));
dst.data.extend_from_slice(self.row(y, width));
}
Plane::new(data, width)
dst.stride = width;
}
}
@@ -179,6 +187,33 @@ impl FrameRef<'_> {
};
VideoFrame { width: self.width, height: self.height, timestamp: self.timestamp, data }
}
/// As [`to_frame`](Self::to_frame), into `out`: its buffers are reused
/// when it has this pixel format, so copying frames of one size into the
/// same `out` allocates nothing after the first.
pub fn copy_to(&self, out: &mut VideoFrame) {
let (w, h) = (self.width as usize, self.height as usize);
let (cw, ch) = chroma_size(self.width, self.height);
match (self.pixels, &mut out.data) {
(PixelsRef::I420 { y, u, v }, FrameData::I420 { y: oy, u: ou, v: ov }) => {
y.copy_into(oy, w, h);
u.copy_into(ou, cw, ch);
v.copy_into(ov, cw, ch);
}
(PixelsRef::Nv12 { y, uv }, FrameData::Nv12 { y: oy, uv: ouv }) => {
y.copy_into(oy, w, h);
uv.copy_into(ouv, cw * 2, ch);
}
(PixelsRef::Bgra(p), FrameData::Bgra(o)) | (PixelsRef::Rgba(p), FrameData::Rgba(o)) => {
p.copy_into(o, w * 4, h);
}
_ => {
*out = self.to_frame();
return;
}
}
(out.width, out.height, out.timestamp) = (self.width, self.height, self.timestamp);
}
}
/// The pixels of a [`VideoFrame`].
@@ -418,4 +453,25 @@ mod tests {
assert!(short.validate().is_err());
assert_eq!(VideoFrame::black_i420(5, 3).view().format(), PixelFormat::I420);
}
#[test]
fn copies_reuse_the_destination() {
let source = VideoFrame::black_i420(33, 17).with_timestamp(Duration::from_millis(7));
let mut out = VideoFrame::from_bgra(1, 1, 4, vec![0; 4]).unwrap();
source.view().copy_to(&mut out);
assert_eq!(out, source, "another format: replaced");
let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") };
let buffer = y.data.as_ptr();
let smaller = VideoFrame::black_i420(20, 10);
smaller.view().copy_to(&mut out);
assert_eq!(out, smaller);
let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") };
assert_eq!(y.data.as_ptr(), buffer, "the same buffer");
let nv12 = FrameRef {
pixels: PixelsRef::Nv12 { y: PlaneRef::new(&[1; 4], 2), uv: PlaneRef::new(&[2; 2], 2) },
..VideoFrame::black_i420(2, 2).view()
};
nv12.copy_to(&mut out);
assert_eq!(out, nv12.to_frame());
}
}
+3 -3
View File
@@ -44,9 +44,9 @@ pub mod workers;
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
pub use codec::{
BackendChoice, Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend,
EncoderConfig, EncoderInfo, EncoderPreference, EncoderReport, H264Profile, VideoDecoder,
VideoEncoder,
BackendChoice, Codec, Codecs, ContentHint, DecoderBackend, DecoderInfo, DecoderPreference,
EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, EncoderInfo, EncoderPreference,
EncoderReport, H264Profile, VideoDecoder, VideoEncoder,
};
pub use frame::{
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
+108
View File
@@ -0,0 +1,108 @@
//! FFmpeg's decoders allocate nothing per picture once running: every
//! decoder that passed its self-test (hardware ones included: the GPU's
//! pictures are copied through a frame of our own) decodes into the same
//! `VideoFrame` with `decode_into`, counted with a global allocator that
//! counts only on the thread that asks. FFmpeg's own buffers are malloc'd
//! by FFmpeg and pooled by it; they are not Rust allocations.
#![cfg(feature = "ffmpeg")]
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use std::time::Duration;
use voelin_media::capture::synthetic::SyntheticScreen;
use voelin_media::ffmpeg::{FfmpegDecoder, decoder};
use voelin_media::{Codecs, EncoderConfig, VideoDecoder, VideoFrame};
thread_local! {
static COUNTING: Cell<bool> = const { Cell::new(false) };
static COUNT: Cell<u64> = const { Cell::new(0) };
}
fn count() {
// `try_with`: never panics, also while the thread is torn down; const
// thread locals without destructors never allocate.
let _ = COUNTING.try_with(|on| {
if on.get() {
let _ = COUNT.try_with(|n| n.set(n.get() + 1));
}
});
}
struct Counting;
// SAFETY: every method forwards to `System` with the caller's arguments
// unchanged, so `System`'s guarantees hold; counting touches only
// thread-local cells and never allocates.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
count();
// SAFETY: forwarded unchanged (see above).
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
count();
// SAFETY: forwarded unchanged.
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
count();
// SAFETY: forwarded unchanged.
unsafe { System.realloc(ptr, layout, new_size) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
// SAFETY: forwarded unchanged.
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
/// Allocations `f` makes on this thread.
fn allocations(f: impl FnOnce()) -> u64 {
COUNT.with(|n| n.set(0));
COUNTING.with(|on| on.set(true));
f();
COUNTING.with(|on| on.set(false));
COUNT.with(Cell::get)
}
#[test]
fn decoders_allocate_nothing_per_picture() {
assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1);
let codecs = Codecs::new();
let screen = SyntheticScreen::new(640, 360);
let mut tested = Vec::new();
for status in decoder::probe().iter().filter(|s| s.available.is_ok()) {
let codec = status.spec.codec;
let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
let Ok(mut encoder) = codecs.new_encoder(codec, config) else { continue };
let mut stream = Vec::new();
for n in 0..40u64 {
let frame = screen.frame(n, 30).with_timestamp(Duration::from_millis(33 * n));
stream.extend(encoder.encode(&frame, n == 0).unwrap().into_iter().map(|f| f.data));
}
let mut decoder = FfmpegDecoder::new(status.spec).unwrap();
let mut picture = VideoFrame::black_i420(0, 0);
// The first pictures size the buffers.
for data in &stream[..10] {
decoder.decode_into(data, &mut picture).unwrap();
}
let mut decoded = 0;
let counted = allocations(|| {
for data in &stream[10..] {
decoded += usize::from(decoder.decode_into(data, &mut picture).unwrap());
}
});
eprintln!("{}: {counted} allocations for {decoded} pictures", status.spec.name);
assert!(decoded + 3 >= stream.len() - 10, "{}: {decoded} pictures", status.spec.name);
assert_eq!(counted, 0, "{}", status.spec.name);
tested.push(status.spec.name);
}
eprintln!("tested: {tested:?}");
}
@@ -0,0 +1,482 @@
//! Decoders through the system's FFmpeg (loaded at runtime): the probe, the
//! ladder of each codec, every encoder of this machine against every decoder
//! of its codec, VA-API decoding on the GPU, and the codecs a viewer accepts
//! with and without FFmpeg.
//!
//! Skipped without FFmpeg. Hardware decoders need their GPU and driver; on a
//! machine without them the self-test reports why and they are skipped.
#![cfg(feature = "ffmpeg")]
use std::time::{Duration, Instant};
use voelin_media::capture::synthetic::SyntheticScreen;
use voelin_media::ffmpeg::{DECODERS, DecoderSpec, Ffmpeg, FfmpegDecoder, decoder};
use voelin_media::{
Codec, Codecs, DecoderBackend, EncodedFrame, EncoderConfig, EncoderPreference, VideoDecoder,
VideoFrame, convert,
};
fn ffmpeg() -> Option<&'static Ffmpeg> {
match Ffmpeg::get() {
Ok(f) => Some(f),
Err(e) => {
eprintln!("FFmpeg not available ({e}), skipped");
None
}
}
}
fn available(name: &str) -> bool {
decoder::probe().iter().any(|s| s.spec.name == name && s.available.is_ok())
}
#[test]
fn probe_reports_every_decoder() {
if ffmpeg().is_none() {
return;
}
let statuses = decoder::probe();
assert_eq!(statuses.len(), DECODERS.len());
for status in statuses {
eprintln!(
"{:>18}: {:?} ({} ms)",
status.spec.name,
status.available,
status.took.as_millis()
);
if let Err(reason) = &status.available {
assert!(!reason.is_empty());
}
}
// The report lists them with the built-in ones, ranked by the ladder.
let codecs = Codecs::new();
let report = codecs.report();
assert!(report.decoders.iter().any(|d| d.name == "libvpx"));
for status in statuses {
let info = report.decoders.iter().find(|d| d.name == status.spec.name).unwrap();
assert_eq!(info.status, status.available);
assert_eq!(info.rank.is_some(), status.available.is_ok(), "{}", status.spec.name);
}
for codec in Codec::ALL {
let ladder: Vec<String> =
codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect();
eprintln!("{codec}: {}", ladder.join(" > "));
}
eprintln!("viewer accepts: {:?}", codecs.decoders());
// FFmpeg's software decoders are in every build: a viewer takes every
// codec but AV1 (which needs dav1d or libaom in FFmpeg) with them.
for (name, codec) in [("h264", Codec::H264), ("hevc", Codec::H265), ("vp9", Codec::Vp9)] {
if available(name) {
assert!(codecs.decoders().contains(&codec), "{codec}");
}
}
}
/// `frames` of the moving test pattern at `w` x `h` through `encoder`'s
/// best backend (`backend` named first), with a keyframe at the start.
fn encode(codec: Codec, backend: &str, w: u32, h: u32, frames: u64) -> Vec<(EncodedFrame, u64)> {
let codecs = Codecs::new();
let screen = SyntheticScreen::new(w, h);
let config = EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() };
let preference = EncoderPreference { hardware: true, backend: backend.parse().unwrap() };
let mut encoder = codecs.new_encoder_preferring(codec, config, &preference).unwrap();
let mut out = Vec::new();
let mut sources = Vec::new();
for n in 0..frames + 8 {
let frame = screen.frame(n.min(frames - 1), 30);
let frame = frame.with_timestamp(Duration::from_millis(33 * n));
sources.push(frame.pts_90khz());
for f in encoder.encode(&frame, n == 0).unwrap() {
let index = sources.iter().position(|&p| p == f.pts_90khz).unwrap() as u64;
if out.len() < frames as usize {
out.push((f, index.min(frames - 1)));
}
}
}
out
}
/// Decodes `stream` with `decoder`: the PSNR of every picture against the
/// pattern frame it came from, or why it failed.
fn decode(
decoder: &mut dyn VideoDecoder,
stream: &[(EncodedFrame, u64)],
screen: &SyntheticScreen,
) -> Result<(usize, f64), String> {
let mut picture = VideoFrame::black_i420(0, 0);
let mut worst = f64::INFINITY;
let mut decoded = 0;
for (frame, index) in stream {
if decoder.decode_into(&frame.data, &mut picture).map_err(|e| e.to_string())? {
let source = screen.frame(*index, 30);
let source = if (picture.width, picture.height) == (source.width, source.height) {
source
} else {
// Cropped to the encoder's alignment (AV1 in hardware).
let mut view = source.view();
(view.width, view.height) = (picture.width, picture.height);
view.to_frame()
};
worst = worst.min(convert::psnr(&source, &picture).map_err(|e| e.to_string())?);
decoded += 1;
}
}
Ok((decoded, worst))
}
/// Every encoder this machine has, through every decoder of its codec
/// (hardware, FFmpeg's software ones, the built-in ones): every frame
/// decodes, PSNR above 28 dB against the pattern, as `tests/ffmpeg.rs`
/// checks the encoders.
#[test]
fn every_encoder_decodes_with_every_decoder() {
if ffmpeg().is_none() {
return;
}
let codecs = Codecs::new();
let (w, h) = (320, 240);
let screen = SyntheticScreen::new(w, h);
let mut table = Vec::new();
let mut failed = Vec::new();
for (codec, encoder) in codecs.encoders() {
let stream = encode(codec, encoder.name(), w, h, 12);
for backend in codecs.decoders_for(codec) {
let mut decoder = codecs.new_decoder_with(codec, backend).unwrap();
match decode(&mut *decoder, &stream, &screen) {
Ok((decoded, psnr)) if decoded == stream.len() && psnr > 28.0 => {
table.push(format!("{codec:<4} {encoder:<12} -> {backend:<12} {psnr:5.1} dB"));
}
Ok((decoded, psnr)) => failed.push(format!(
"{encoder} -> {backend}: {decoded} of {} pictures, PSNR {psnr:.1} dB",
stream.len()
)),
Err(e) => failed.push(format!("{encoder} -> {backend}: {e}")),
}
}
}
eprintln!("{}", table.join("\n"));
assert!(failed.is_empty(), "{}", failed.join("\n"));
}
/// The VA-API decoders that passed their self-test decode on the GPU: every
/// picture of a stream comes out of a VA-API surface, none from FFmpeg's
/// software path; at 1920x1080 too (1088 coded rows, cropped). Skipped
/// where no VA-API decoder works.
#[cfg(target_os = "linux")]
#[test]
fn vaapi_decodes_on_the_gpu() {
if ffmpeg().is_none() {
return;
}
let names: Vec<&str> =
DECODERS.iter().map(|d| d.name).filter(|n| n.ends_with("_vaapi") && available(n)).collect();
if names.is_empty() {
eprintln!("no usable VA-API decoder, skipped");
return;
}
let codecs = Codecs::new();
for name in &names {
let spec = DecoderSpec::by_name(name).unwrap();
if codecs.encoders().iter().all(|(c, _)| *c != spec.codec) {
eprintln!("{name}: nothing here encodes {}, skipped", spec.codec);
continue;
}
for (w, h) in [(320, 240), (1920, 1080)] {
let stream = encode(spec.codec, "auto", w, h, 10);
let mut decoder = FfmpegDecoder::new(spec).unwrap();
let screen = SyntheticScreen::new(w, h);
let started = Instant::now();
let (decoded, psnr) = decode(&mut decoder, &stream, &screen).unwrap();
eprintln!(
"{name} {w}x{h}: {decoded} pictures, {} on the GPU, PSNR {psnr:.1} dB, {:.1} ms each",
decoder.gpu_pictures(),
started.elapsed().as_secs_f64() * 1000.0 / decoded.max(1) as f64
);
assert_eq!(decoded, stream.len(), "{name}");
assert_eq!(decoder.gpu_pictures(), decoded as u64, "{name}: not on the GPU");
assert_eq!(decoder.cpu_pictures(), 0, "{name}");
assert!(psnr > 28.0, "{name}: {psnr:.1} dB");
}
}
}
/// What a viewer accepts with FFmpeg and without (`VOELIN_FFMPEG=0`, in a
/// child process: FFmpeg is loaded once per process).
#[test]
fn decoders_with_and_without_ffmpeg() {
let without = std::env::var("VOELIN_FFMPEG").is_ok_and(|v| v == "0");
let codecs = Codecs::new();
let decoders = codecs.decoders();
eprintln!("VOELIN_FFMPEG={without}: {decoders:?}");
if without {
// Only the built-in decoders: libvpx (and dav1d with `av1`).
assert!(Ffmpeg::get().is_err());
assert!(decoder::probe().is_empty());
assert!(!decoders.contains(&Codec::H265) && !decoders.contains(&Codec::H264));
assert_eq!(decoders.contains(&Codec::Av1), cfg!(feature = "av1"));
#[cfg(feature = "vpx")]
assert_eq!(decoders[decoders.len() - 2..], [Codec::Vp9, Codec::Vp8]);
let ladder = codecs.decoders_for(Codec::Vp9);
assert!(ladder.iter().all(|b| !matches!(b, DecoderBackend::Ffmpeg(_))), "{ladder:?}");
return;
}
if ffmpeg().is_some() {
// The software decoders of every FFmpeg build.
for codec in [Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8] {
assert!(decoders.contains(&codec), "{codec}: {decoders:?}");
}
// The viewer's order: best first.
let order: Vec<usize> = decoders
.iter()
.map(|c| voelin_media::codec::VIEWER_PREFERENCE.iter().position(|p| p == c).unwrap())
.collect();
assert!(order.windows(2).all(|w| w[0] < w[1]), "{decoders:?}");
}
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "decoders_with_and_without_ffmpeg", "--nocapture"])
.env("VOELIN_FFMPEG", "0")
.status()
.unwrap();
assert!(child.success(), "without FFmpeg: {child}");
}
/// The access units of an Annex B H.264 stream that has access unit
/// delimiters (`aud=1` in x264, `-aud 1` in VA-API), as a stream's frames.
fn access_units(stream: &[u8]) -> Vec<&[u8]> {
let mut starts = Vec::new();
let mut i = 0;
while i + 3 < stream.len() {
if stream[i..i + 3] == [0, 0, 1] {
if stream[i + 3] & 0x1f == 9 {
starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i });
}
i += 3;
} else {
i += 1;
}
}
starts.push(stream.len());
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
}
/// A 32x18 luma thumbnail (block averages), to compare pictures cheaply.
fn thumbnail(picture: &VideoFrame) -> Vec<u8> {
let y = match &picture.data {
voelin_media::FrameData::I420 { y, .. } | voelin_media::FrameData::Nv12 { y, .. } => y,
_ => panic!("not YUV"),
};
let (w, bw, bh) =
(picture.width as usize, picture.width as usize / 32, picture.height as usize / 18);
let mut out = Vec::with_capacity(32 * 18);
for by in 0..18 {
for bx in 0..32 {
let sum: u64 = (by * bh..(by + 1) * bh)
.map(|row| {
y.row(row, w)[bx * bw..(bx + 1) * bw].iter().map(|&p| u64::from(p)).sum::<u64>()
})
.sum();
out.push((sum / (bw * bh) as u64) as u8);
}
}
out
}
/// Make `path` with the `ffmpeg` command from `args` (output options
/// last), unless it is there; whether it is.
fn ffmpeg_command(path: &std::path::Path, args: &[&str]) -> bool {
if path.exists() {
return true;
}
let made = std::process::Command::new("ffmpeg")
.args(["-hide_banner", "-loglevel", "error", "-y"])
.args(args)
.arg(path)
.status();
if !made.is_ok_and(|s| s.success()) {
let _ = std::fs::remove_file(path);
return false;
}
true
}
/// The temporal units of a low-overhead AV1 stream (`-f obu`), each
/// starting with a temporal delimiter OBU.
fn temporal_units(stream: &[u8]) -> Vec<&[u8]> {
let mut starts = Vec::new();
let mut pos = 0;
while pos < stream.len() {
let header = stream[pos];
if (header >> 3) & 0xf == 2 {
starts.push(pos);
}
// Every OBU of such a stream has its size (LEB128).
let (mut at, mut size, mut shift) = (pos + 1 + usize::from(header & 4 != 0), 0, 0);
loop {
let byte = stream[at];
at += 1;
size |= usize::from(byte & 0x7f) << shift;
shift += 7;
if byte & 0x80 == 0 {
break;
}
}
pos = at + size;
}
starts.push(stream.len());
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
}
/// Streams of ten seconds of `testsrc2` at 2560x1440 and 60 fps, made with
/// the `ffmpeg` command from each encoder's `args` (kept in the temporary
/// directory, made again only when missing).
fn streams_1440p60(
encoders: &[(&'static str, &str)],
format: &str,
) -> Vec<(&'static str, Vec<u8>)> {
let dir = std::env::temp_dir().join("voelin-h264-bframes");
std::fs::create_dir_all(&dir).unwrap();
let source = "-f lavfi -i testsrc2=size=2560x1440:rate=60 -t 10";
let mut streams = Vec::new();
for &(name, args) in encoders {
let vaapi = name.ends_with("_vaapi");
let device = if vaapi { "-vaapi_device /dev/dri/renderD128 " } else { "" };
let upload = if vaapi { "-vf format=nv12,hwupload " } else { "" };
let args = format!("{device}{source} {upload}{args} -g 600 -b:v 8M -f {format}");
let suffix = if format == "h264" { "-bframes" } else { "" };
let path = dir.join(format!("{name}{suffix}-1440p60.{format}"));
let args: Vec<&str> = args.split(' ').collect();
if ffmpeg_command(&path, &args) {
streams.push((name, std::fs::read(&path).unwrap()));
} else {
eprintln!("{name}: the ffmpeg command did not make the stream, skipped");
}
}
streams
}
/// Every decoder of `codec`'s ladder (and OpenH264 with
/// `VOELIN_OPENH264_LIB`, for H.264) on each of `streams` (frames as
/// `split` cuts them), as fast as it goes: pictures, errors, pictures per
/// second of decoding (copied into a `VideoFrame`), the slowest frame, and
/// the pictures that differ from those of `reference`, which comes first
/// in the ladder's software part. Hardware decoders must decode every
/// picture.
fn decode_rates(
codec: Codec,
what: &str,
streams: &[(&str, Vec<u8>)],
split: fn(&[u8]) -> Vec<&[u8]>,
reference: &str,
) {
let codecs = Codecs::new();
let openh264 = std::env::var_os("VOELIN_OPENH264_LIB")
.filter(|_| codec == Codec::H264)
.map(|path| voelin_media::codec::h264::OpenH264::load(path).unwrap());
let mut names: Vec<String> = codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect();
// The reference first, so that every other decoder is compared with it.
names.sort_by_key(|n| n != reference);
names.extend(openh264.as_ref().map(|_| "openh264".to_owned()));
for (stream, data) in streams {
let units = split(data);
let mut reference: Option<Vec<Vec<u8>>> = None;
for name in &names {
let mut decoder: Box<dyn VideoDecoder> = match (name.as_str(), &openh264) {
("openh264", Some(library)) => Box::new(library.decoder().unwrap()),
_ => {
let backend = codecs.decoders_for(codec).into_iter().find(|b| b.name() == name);
codecs.new_decoder_with(codec, backend.unwrap()).unwrap()
}
};
let mut picture = VideoFrame::black_i420(0, 0);
let mut thumbnails = Vec::with_capacity(units.len());
let (mut errors, mut slowest, mut busy) = (0, Duration::ZERO, Duration::ZERO);
for unit in &units {
let started = Instant::now();
let result = decoder.decode_into(unit, &mut picture);
let took = started.elapsed();
(slowest, busy) = (slowest.max(took), busy + took);
match result {
Ok(true) => {
assert_eq!((picture.width, picture.height), (2560, 1440), "{name}");
thumbnails.push(thumbnail(&picture));
}
Ok(false) => {}
Err(_) => errors += 1,
}
}
let fps = thumbnails.len() as f64 / busy.as_secs_f64();
let differing = reference.as_ref().map_or(0, |reference| {
let differs = |(a, b): &(&Vec<u8>, &Vec<u8>)| {
a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 3)
};
thumbnails.iter().zip(reference).filter(differs).count()
});
eprintln!(
"{stream} 2560x1440@60{what}, {name}: {} of {} pictures, {errors} errors, {fps:.0} \
fps, slowest frame {:.1} ms, {differing} differ from the reference decoder",
thumbnails.len(),
units.len(),
slowest.as_secs_f64() * 1000.0,
);
if reference.is_none() {
reference = Some(thumbnails);
} else if name.ends_with("_vaapi") {
assert_eq!(errors, 0, "{name}");
assert!(thumbnails.len() + 3 >= units.len(), "{name}: pictures missing");
assert_eq!(differing, 0, "{name}");
}
}
}
}
/// H.264 with B-frames at 2560x1440 and 60 fps, like the official client's
/// stream (AMF with B-frames and rare keyframes): every H.264 decoder of
/// the ladder, and Cisco's OpenH264 with `VOELIN_OPENH264_LIB`, decodes it;
/// how fast, the slowest frame, and whether every picture comes out, in
/// order (against FFmpeg's software decoder). The streams come from the
/// `ffmpeg` command: x264 with 3 B-frames, `h264_vaapi` with 2, ten
/// seconds of `testsrc2` at 8 Mbit/s, keyframes every ten seconds. Run with
/// `--release`.
#[test]
#[ignore = "a measurement: needs the ffmpeg command; run with --release"]
fn h264_with_b_frames_at_1440p60() {
if ffmpeg().is_none() {
return;
}
let streams = streams_1440p60(
&[
(
"x264",
"-c:v libx264 -preset veryfast -profile:v high -bf 3 -x264-params aud=1 -pix_fmt yuv420p -maxrate 9M -bufsize 9M",
),
("h264_vaapi", "-c:v h264_vaapi -profile:v high -bf 2 -aud 1 -maxrate 9M"),
],
"h264",
);
decode_rates(Codec::H264, " with B-frames", &streams, access_units, "h264");
// What a viewer adds per picture: the NV12 or I420 picture to RGBA.
let mut rgba = vec![0; 2560 * 1440 * 4];
let i420 = VideoFrame::black_i420(2560, 1440);
let started = Instant::now();
for _ in 0..30 {
convert::to_rgba(&i420, &mut rgba, 2560 * 4).unwrap();
}
eprintln!("to RGBA at 2560x1440: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0 / 30.0);
}
/// AV1 at 2560x1440 and 60 fps, which the official client sends from GPUs
/// that encode it: every AV1 decoder of the ladder, against dav1d. Streams
/// from `av1_vaapi` (hardware, as the official client's AMF) and SVT-AV1.
/// Run with `--release`.
#[test]
#[ignore = "a measurement: needs the ffmpeg command; run with --release"]
fn av1_at_1440p60() {
if ffmpeg().is_none() {
return;
}
let streams = streams_1440p60(
&[("av1_vaapi", "-c:v av1_vaapi"), ("libsvtav1", "-c:v libsvtav1 -preset 10")],
"obu",
);
decode_rates(Codec::Av1, "", &streams, temporal_units, "libdav1d");
}
+2 -1
View File
@@ -53,7 +53,8 @@ fn sps_profile(data: &[u8]) -> Option<u8> {
fn roundtrip(library: OpenH264) {
let codecs = Codecs::builtin().with_openh264(library.clone());
assert_eq!(codecs.decoders().last(), Some(&Codec::H264));
assert!(codecs.decoders().contains(&Codec::H264));
assert_eq!(codecs.decoders_for(Codec::H264), [voelin_media::DecoderBackend::OpenH264]);
assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));
let screen = SyntheticScreen::new(320, 240);
+12 -2
View File
@@ -17,7 +17,10 @@ use anyhow::{Context, Result};
use slint::{ComponentHandle, ModelRc, VecModel};
use tokio::runtime::Runtime;
use tracing::warn;
use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings};
use voelin_core::media::decoder_preference;
use voelin_core::settings::{
AUDIO, CRASH_REPORTS, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings,
};
use voelin_core::stream::StreamInfo;
use voelin_core::{
AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState,
@@ -414,6 +417,9 @@ pub(crate) struct App {
pub share_error: String,
/// The stream in the viewer.
pub watch: Option<Watch>,
/// A client whose stream was asked for before it was known (session,
/// client): watched when the lookup brings it.
pub pending_watch: Option<(i64, u16)>,
/// Stream volume in percent, kept between streams.
pub stream_volume: f32,
/// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream.
@@ -592,7 +598,8 @@ pub fn run(options: RunOptions) -> Result<()> {
if settings.global_ptt {
ptt.set(Some(settings.ptt_key.clone()));
}
let video = Video::new(&dir, settings.openh264);
let mut video = Video::new(&dir, settings.openh264);
video.set_decoder_preference(decoder_preference(&prefs));
let switches = crate::dev::Switches::from_env();
let app = App {
ui: ui.as_weak(),
@@ -624,6 +631,7 @@ pub fn run(options: RunOptions) -> Result<()> {
share_busy: false,
share_error: String::new(),
watch: None,
pending_watch: None,
stream_volume: 100.0,
demo: switches.demo_stream,
demo_ui: switches.demo_ui,
@@ -776,6 +784,8 @@ impl App {
} else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() {
// A running share mixes the new sources (streams.rs).
self.share_audio_changed();
} else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() {
self.video.set_decoder_preference(decoder_preference(&self.prefs));
}
self.page_setting_changed(key);
}
+5
View File
@@ -22,6 +22,11 @@ pub(super) fn wire(ui: &MainWindow) {
bridge.on_watch_stream(|id| {
with_app(|app| app.watch_stream(id.to_string()));
});
bridge.on_watch_client(|client| {
if let Ok(client) = u16::try_from(client) {
with_app(|app| app.watch_client(client));
}
});
bridge.on_show_viewer(|| {
with_app(|app| app.show_viewer(true));
});
+5
View File
@@ -70,6 +70,7 @@ impl App {
volume: playback.volume * 100.0,
muted: playback.muted,
known: uid.is_some(),
streaming: client.streaming == Some(true),
})
})
.unwrap_or_default();
@@ -91,6 +92,10 @@ impl App {
self.open_member(-1);
}
}
"watch" => {
self.open_member(-1);
self.watch_client(client_id);
}
"poke" => {
self.command(|session| Command::Poke {
session,
+1
View File
@@ -207,6 +207,7 @@ impl App {
name: info.nickname.into(),
volume: playback.volume * 100.0,
muted: playback.muted,
streaming: info.streaming == Some(true),
});
}
true
+31 -1
View File
@@ -179,10 +179,19 @@ impl App {
.iter()
.find(|s| view.state.own_client != Some(s.streamer.0))
.map(|s| s.id.clone());
// A client whose stream was asked for while it was looked up.
let pending = self
.pending_watch
.filter(|(s, _)| *s == session as i64)
.and_then(|(_, client)| streams.iter().find(|s| s.streamer.0 == client))
.map(|s| s.id.clone());
view.streams = streams;
self.refresh_streams();
self.refresh_servers();
if autowatch && let Some(id) = first {
if let Some(id) = pending {
self.pending_watch = None;
self.watch_stream(id);
} else if autowatch && let Some(id) = first {
self.watch_stream(id);
}
}
@@ -763,6 +772,27 @@ impl App {
self.refresh_tree();
}
/// Watch the stream of `client` (a click on a streaming user in the
/// channel tree or the members): at once if it is known, else as soon as
/// the lookup brings it (it may have started in another channel or
/// before we joined).
pub(crate) fn watch_client(&mut self, client: u16) {
let Some(session) = self.current else { return };
let Some(view) = self.sessions.get(&session) else { return };
if view.state.own_client == Some(client) {
return;
}
if let Some(id) = view.streams.iter().find(|s| s.streamer.0 == client).map(|s| s.id.clone())
{
self.pending_watch = None;
self.watch_stream(id);
} else if view.presence.clients.get(&client).is_some_and(|c| c.streaming == Some(true)) {
let name = view.nickname(client);
self.pending_watch = Some((session, client));
self.set_status(format!("Looking up {name}'s stream…"));
}
}
/// `VOELIN_OPEN=watch`: watch the first stream of our channel.
pub(crate) fn watch_first_stream(&mut self) {
let Some(id) = self.view().and_then(|v| {
+30 -7
View File
@@ -13,8 +13,8 @@ use tracing::warn;
use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId};
use voelin_core::media::voelin_media::{Codec, Codecs, VideoFrame, convert};
use voelin_core::media::{
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
StreamerConfigUpdate, Viewer, peer_config, preferred_codec, stream_codec,
self, AudioSourceSpec, DecoderPreference, EncoderPreference, Latest, LocalPreview, Streamer,
StreamerConfig, StreamerConfigUpdate, Viewer, peer_config, preferred_codec, stream_codec,
};
use voelin_core::stream::{LayerSpec, PeerConfig};
use voelin_core::studio::Studio;
@@ -62,6 +62,9 @@ pub(crate) struct Video {
/// automatic), from the settings.
encoder: EncoderPreference,
codec: Option<Codec>,
/// Which decoders to use (`stream.hardware_decoding`,
/// `stream.decoder_backend`).
decoder: DecoderPreference,
/// Sources of the share dialog, by index.
sources: Vec<ShareEntry>,
}
@@ -75,6 +78,7 @@ impl Video {
codecs: Arc::new(Codecs::new()),
encoder: EncoderPreference::default(),
codec: None,
decoder: DecoderPreference::default(),
#[cfg(not(target_os = "android"))]
openh264_dir: data_dir.join("openh264"),
#[cfg(not(target_os = "android"))]
@@ -107,6 +111,17 @@ impl Video {
self.codec = codec;
}
/// Decode with other decoders (`stream.hardware_decoding`,
/// `stream.decoder_backend`): streams watched from now on.
pub fn set_decoder_preference(&mut self, decoder: DecoderPreference) {
if decoder != self.decoder {
let mut codecs = (*self.codecs).clone();
codecs.set_decoder_preference(decoder.clone());
self.codecs = Arc::new(codecs);
self.decoder = decoder;
}
}
/// Whether H.264 works, and a line for the settings page.
pub fn h264_status(&self) -> (bool, String) {
#[cfg(target_os = "android")]
@@ -133,7 +148,11 @@ impl Video {
use openh264::State;
if !enabled {
self.h264 = State::Off;
self.codecs = Arc::new(Codecs::new().with_preference(self.encoder.clone()));
self.codecs = Arc::new(
Codecs::new()
.with_preference(self.encoder.clone())
.with_decoder_preference(self.decoder.clone()),
);
return;
}
if matches!(self.h264, State::Loaded(_) | State::Downloading) {
@@ -149,8 +168,12 @@ impl Video {
#[cfg(not(target_os = "android"))]
fn loaded(&mut self, library: openh264::OpenH264) {
self.h264 = openh264::State::Loaded(library.path().to_owned());
self.codecs =
Arc::new(Codecs::new().with_openh264(library).with_preference(self.encoder.clone()));
self.codecs = Arc::new(
Codecs::new()
.with_openh264(library)
.with_preference(self.encoder.clone())
.with_decoder_preference(self.decoder.clone()),
);
}
/// Download Cisco's OpenH264 (only on the user's request). `done` runs
@@ -337,8 +360,8 @@ impl Video {
fn deliver(
pictures: Arc<Latest<Picture>>,
wake: impl Fn() + Send + Sync + 'static,
) -> impl FnMut(VideoFrame) + Send + 'static {
move |frame: VideoFrame| {
) -> impl FnMut(Arc<VideoFrame>) + Send + 'static {
move |frame: Arc<VideoFrame>| {
let mut buffer = Picture::new(frame.width, frame.height);
let stride = frame.width as usize * 4;
if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) {
+7
View File
@@ -111,6 +111,8 @@ export struct MemberCard {
muted: bool,
// The client has a unique id, so contacts and private chats work.
known: bool,
// The client streams: the card offers to watch it.
streaming: bool,
}
export struct ChatTab {
@@ -307,6 +309,8 @@ export struct ClientAudio {
name: string,
volume: float,
muted: bool,
// The client streams: the dialog offers to watch it.
streaming: bool,
}
// The appearance settings (`ui.*` keys).
@@ -922,6 +926,9 @@ export global Bridge {
callback respond-viewer(int, bool);
callback kick-viewer(int);
callback watch-stream(string);
// Watch the stream of a client (a streaming user in the tree or the
// members), as soon as it is known.
callback watch-client(int);
callback show-viewer();
callback hide-viewer();
callback leave-stream();
+18 -1
View File
@@ -226,9 +226,26 @@ component TreeRow inherits Rectangle {
alignment: center;
SpeakingBars { }
}
// A click on someone's LIVE mark watches their stream.
if item.streaming: VerticalLayout {
alignment: center;
LiveBadge { }
LiveBadge {
accessible-role: AccessibleRole.button;
accessible-label: item.myself ? @tr("Your stream") : @tr("Watch {}'s stream", item.name);
accessible-action-default => {
if !item.myself {
Bridge.watch-client(item.id);
}
}
TouchArea {
mouse-cursor: item.myself ? MouseCursor.default : MouseCursor.pointer;
clicked => {
if !item.myself {
Bridge.watch-client(item.id);
}
}
}
}
}
if item.local-muted: Icon {
source: Icons.volume-x;
@@ -506,6 +506,15 @@ export component ClientAudioDialog inherits Modal {
Bridge.client-audio-changed(Bridge.client-audio);
}
}
if Bridge.client-audio.streaming: Button {
kind: ButtonKind.primary;
icon: Icons.monitor;
text: @tr("Watch {}'s stream", Bridge.client-audio.name);
clicked => {
Bridge.watch-client(Bridge.client-audio.id);
done();
}
}
Rectangle { vertical-stretch: 1; }
Footer {
Button {
@@ -308,6 +308,13 @@ export component MemberCardPopup inherits Rectangle {
}
}
Divider { }
if Bridge.member-card.streaming: Button {
small: true;
kind: ButtonKind.primary;
icon: Icons.monitor;
text: @tr("Watch stream");
clicked => { Bridge.member-action("watch"); }
}
HorizontalLayout {
spacing: Theme.space-2;
Button {