Merge video encoders through FFmpeg loaded at runtime

H.264, HEVC, AV1, VP9 and VP8 on VA-API, NVENC, Quick Sync, AMF, Media
Foundation, VideoToolbox and the software encoders the system FFmpeg
has, found at runtime without a version allow-list and self-tested per
backend. Viewers get the codec they answered, with one encoder per codec
only while someone needs it, and H.264's level follows the stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-29 06:11:26 +00:00
commit 2f19a340f7
30 files changed
+4714 -272

No files matched your search

+434 -80
View File
@@ -53,6 +53,7 @@ use voelin_media::mix::{
pub use voelin_media::mix::{Level, SourceState};
use voelin_media::scale::Pyramid;
use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame};
pub use voelin_media::{EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
MediaTime, PeerConfig, VideoCodec,
@@ -101,6 +102,7 @@ pub fn media_codec(codec: VideoCodec) -> Codec {
VideoCodec::Vp9 => Codec::Vp9,
VideoCodec::H264 => Codec::H264,
VideoCodec::Av1 => Codec::Av1,
VideoCodec::H265 => Codec::H265,
}
}
@@ -111,6 +113,7 @@ pub fn video_codec(codec: Codec) -> VideoCodec {
Codec::Vp9 => VideoCodec::Vp9,
Codec::H264 => VideoCodec::H264,
Codec::Av1 => VideoCodec::Av1,
Codec::H265 => VideoCodec::H265,
}
}
@@ -122,16 +125,77 @@ pub fn stream_codec(codecs: &Codecs, config: &PeerConfig) -> Option<Codec> {
}
/// `config` adjusted to what `codecs` can do: viewers accept only codecs we
/// decode, and a streamer offers only the codec it encodes (every viewer
/// gets the same frames, and a viewer picks from the offer).
/// decode; a streamer offers its stream codec ([`stream_codec`]) first, then
/// [`offer_codecs`]. Viewers answer with the first they decode, and the
/// [`Streamer`] encodes each layer once per codec its viewers chose.
pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig {
config.accept_video_codecs = codecs.decoders().into_iter().map(video_codec).collect();
if let Some(codec) = stream_codec(codecs, &config) {
config.video_codecs = vec![video_codec(codec)];
config.video_codecs = offer_codecs(codecs, codec).into_iter().map(video_codec).collect();
}
config
}
/// What a streamer with `primary` as its stream codec offers, in order:
/// `primary`, the codecs of hardware encoders, VP8 through libvpx (every
/// TeamSpeak client decodes it), and HEVC last (for peers that take nothing
/// else). Other software encoders are only ever the stream codec, so no
/// viewer's answer starts one of them on top of it.
pub fn offer_codecs(codecs: &Codecs, primary: Codec) -> Vec<Codec> {
let mut offer = vec![primary];
let mut hevc = false;
for (codec, backend) in codecs.encoders() {
let cheap = codecs.is_hardware(backend)
|| (codec == Codec::Vp8 && backend == voelin_media::EncoderBackend::Libvpx);
if !cheap || offer.contains(&codec) {
continue;
}
if codec == Codec::H265 {
hevc = true;
} else {
offer.push(codec);
}
}
if hevc && primary != Codec::H265 {
offer.push(Codec::H265);
}
offer
}
/// The encoder preference of the settings `stream.hardware_acceleration`
/// and `stream.encoder_backend`.
pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media::EncoderPreference {
use crate::settings::{STREAM_ENCODER_BACKEND, STREAM_HARDWARE_ACCELERATION};
voelin_media::EncoderPreference {
hardware: settings.get(&STREAM_HARDWARE_ACCELERATION),
backend: settings.get(&STREAM_ENCODER_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), never HEVC (offered last only). Put it first in
/// `PeerConfig::video_codecs` before [`peer_config`].
pub fn preferred_codec(codecs: &Codecs, configured: Option<Codec>) -> Option<Codec> {
let encodable = codecs.encoder_codecs();
configured
.filter(|c| encodable.contains(c))
.or_else(|| encodable.into_iter().find(|c| *c != Codec::H265))
}
/// The codec of the setting `stream.codec`; `None` for `auto` (see
/// [`preferred_codec`]).
pub fn configured_codec(settings: &crate::settings::Settings) -> Option<Codec> {
use crate::settings::{CodecChoice, STREAM_CODEC};
match settings.get(&STREAM_CODEC) {
CodecChoice::Auto => None,
CodecChoice::Vp8 => Some(Codec::Vp8),
CodecChoice::Vp9 => Some(Codec::Vp9),
CodecChoice::H264 => Some(Codec::H264),
CodecChoice::Av1 => Some(Codec::Av1),
}
}
/// Monitors and windows of this session's capture backend. The portal (on
/// Wayland) lists a single entry: its own dialog picks.
pub fn screen_sources() -> Result<Vec<CaptureSource>, MediaError> {
@@ -172,6 +236,19 @@ pub trait MediaSink: Send + Sync {
let _ = layer;
None
}
/// Send one video frame encoded in `codec`: it goes to the viewers whose
/// answer chose `codec`.
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
let _ = codec;
self.send(frame)
}
/// Adds to `out` the video codecs the viewers chose; none (the default)
/// means only the stream codec is sent.
fn video_codecs(&self, out: &mut Vec<Codec>) {
let _ = out;
}
}
impl MediaSink for StreamSink {
@@ -179,6 +256,18 @@ impl MediaSink for StreamSink {
StreamSink::send(self, frame)
}
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
StreamSink::send_video(self, frame, video_codec(codec))
}
fn video_codecs(&self, out: &mut Vec<Codec>) {
for codec in VideoCodec::ALL {
if self.has_video_codec(codec) {
out.push(media_codec(codec));
}
}
}
fn take_keyframe_request(&self) -> bool {
StreamSink::take_keyframe_request(self)
}
@@ -397,6 +486,8 @@ pub struct StreamerConfig {
pub bitrate_kbps: u32,
/// The codec of our offer, see [`stream_codec`].
pub codec: Codec,
/// Which encoders to use ([`encoder_preference`] of the settings).
pub encoder: EncoderPreference,
/// Send audio: [`audio_sources`](Self::audio_sources) mixed.
pub audio: bool,
/// Audio sources mixed into the stream (any number); empty: the
@@ -424,6 +515,7 @@ impl Default for StreamerConfig {
fps: 30,
bitrate_kbps: 4608,
codec: Codec::Vp8,
encoder: EncoderPreference::default(),
audio: true,
audio_sources: Vec::new(),
cursor: true,
@@ -457,6 +549,9 @@ pub struct StreamerConfigUpdate {
pub bitrate_kbps: Option<u32>,
/// Another codec: new encoders, starting with keyframes.
pub codec: Option<Codec>,
/// Other encoders (hardware on or off, another backend): new encoders
/// for every codec, starting with keyframes.
pub encoder: Option<EncoderPreference>,
/// Another set of layers (`Some(vec![])`: back to a single layer). Layers
/// keep their encoder when their id stays; new ids get new encoders.
pub layers: Option<Vec<LayerSpec>>,
@@ -489,6 +584,11 @@ pub struct LayerStats {
pub threads: u32,
/// The encoder's speed setting (libvpx `cpu-used`), if it has one.
pub speed: Option<i32>,
/// The encoder of the stream codec (`libvpx`, `h264_vaapi`, ...).
pub backend: Option<EncoderBackend>,
/// The codecs this layer is encoded in: the stream codec, and those
/// viewers chose instead (each with its own encoder).
pub codecs: Vec<Codec>,
}
/// What a [`Streamer`] has done so far. Rates are over the last second.
@@ -555,6 +655,9 @@ struct Layer {
target: AtomicU64,
/// `cpu-used`, or `i64::MIN`.
speed: AtomicI64,
/// The stream codec's encoder and every codec encoded (for stats).
backend: Mutex<Option<EncoderBackend>>,
codecs: Mutex<Vec<Codec>>,
}
impl Layer {
@@ -578,6 +681,8 @@ impl Layer {
size: AtomicU64::new(0),
target: AtomicU64::new(spec.bitrate),
speed: AtomicI64::new(i64::MIN),
backend: Mutex::new(None),
codecs: Mutex::new(Vec::new()),
}
}
@@ -603,6 +708,7 @@ struct Settings {
fps: u32,
bitrate_kbps: u32,
codec: Codec,
encoder: EncoderPreference,
layers: Vec<LayerSpec>,
}
@@ -650,6 +756,11 @@ struct Shared {
keyframes: Mutex<LayerSet>,
settings: Mutex<Option<Settings>>,
rates: Mutex<Rates>,
/// For encoders of the codecs viewers chose besides the stream codec,
/// created by the encoder threads when a viewer needs one.
encoders: Mutex<Option<(Codecs, EncoderPreference)>>,
/// Bumped when `encoders` changes: those encoders are made again.
encoders_generation: AtomicU64,
}
impl Shared {
@@ -700,21 +811,28 @@ fn cores() -> u32 {
voelin_media::codec::encoder_cpus()
}
fn new_encoder(
codecs: &Codecs,
codec: Codec,
spec: &LayerSpec,
fps: u32,
threads: u32,
) -> Result<Box<dyn VideoEncoder>, MediaError> {
let config = EncoderConfig {
fn encoder_config(spec: &LayerSpec, fps: u32, threads: u32) -> EncoderConfig {
EncoderConfig {
fps: layer_fps(spec, fps),
bitrate_bps: spec.bitrate.clamp(1, u64::from(u32::MAX)) as u32,
content: ContentHint::Screen,
threads,
..EncoderConfig::default()
};
Ok(codecs.new_encoder(codec, config)?)
}
}
fn new_encoder(
codecs: &Codecs,
codec: Codec,
preference: &EncoderPreference,
spec: &LayerSpec,
fps: u32,
threads: u32,
) -> Result<Box<dyn VideoEncoder>, MediaError> {
let config = encoder_config(spec, fps, threads);
let encoder = codecs.new_encoder_preferring(codec, config, preference)?;
debug!(layer = spec.id, %codec, backend = %encoder.backend(), "video encoder");
Ok(encoder)
}
/// Capture and encoding for our stream. Frames are captured from the start
@@ -771,9 +889,10 @@ impl Streamer {
let split = thread_split(&layers, cores());
let mut ready = Vec::new();
for (spec, threads) in layers.iter().zip(split) {
let encoder = new_encoder(codecs, config.codec, spec, fps, threads)?;
let encoder = new_encoder(codecs, config.codec, &config.encoder, spec, fps, threads)?;
ready.push((Arc::new(Layer::new(spec, fps, threads)), encoder));
}
*lock(&shared.encoders) = Some((codecs.clone(), config.encoder.clone()));
for (layer, encoder) in ready {
streamer.spawn_encoder(layer, encoder)?;
}
@@ -781,6 +900,7 @@ impl Streamer {
fps,
bitrate_kbps: config.bitrate_kbps,
codec: config.codec,
encoder: config.encoder.clone(),
layers: config.layers.clone(),
});
streamer.threads.push(spawn("voelin-stream-stats", {
@@ -847,15 +967,16 @@ impl Streamer {
Ok(())
}
/// Change frame rate, bitrate, codec, layers or audio sources while
/// streaming, without restarting the capture; applies from the next
/// frame. A new codec gets new encoders, which start with a keyframe;
/// new layers get new encoders; removed layers stop. Fails without
/// changing anything if an encoder cannot be created. Audio sources
/// that cannot capture (e.g. an application that is not running by pid)
/// do not fail the update: their [`AudioSourceStats::error`] says why.
/// Audio sources on a streamer started without audio start the audio
/// track.
/// Change frame rate, bitrate, codec, encoders, layers or audio
/// sources while streaming, without restarting the capture; applies
/// from the next frame. A new codec or encoder preference gets new
/// encoders (the stream codec's at once, those of codecs viewers chose
/// on their next frame), which start with a keyframe; new layers get
/// new encoders; removed layers stop. Fails without changing anything
/// if an encoder cannot be created. Audio sources that cannot capture
/// (e.g. an application that is not running by pid) do not fail the
/// update: their [`AudioSourceStats::error`] says why. Audio sources on
/// a streamer started without audio start the audio track.
pub fn reconfigure(
&self,
codecs: &Codecs,
@@ -868,11 +989,12 @@ impl Streamer {
fps: update.fps.unwrap_or(settings.fps).max(1),
bitrate_kbps: update.bitrate_kbps.unwrap_or(settings.bitrate_kbps),
codec: update.codec.unwrap_or(settings.codec),
encoder: update.encoder.unwrap_or_else(|| settings.encoder.clone()),
layers: update.layers.unwrap_or_else(|| settings.layers.clone()),
};
let specs = next.effective_layers();
check_layers(&specs)?;
let codec_changed = next.codec != old_codec;
let codec_changed = next.codec != old_codec || next.encoder != settings.encoder;
let current: Vec<Arc<Layer>> = lock(&self.shared.layers).clone();
// Create every encoder before changing anything.
let split = thread_split(&specs, cores());
@@ -880,9 +1002,15 @@ impl Streamer {
for (spec, &threads) in specs.iter().zip(&split) {
let existing = current.iter().any(|l| l.id == spec.id);
if !existing || codec_changed {
created.push((spec.id, new_encoder(codecs, next.codec, spec, next.fps, threads)?));
let encoder =
new_encoder(codecs, next.codec, &next.encoder, spec, next.fps, threads)?;
created.push((spec.id, encoder));
}
}
if codec_changed {
*lock(&self.shared.encoders) = Some((codecs.clone(), next.encoder.clone()));
self.shared.encoders_generation.fetch_add(1, Ordering::Relaxed);
}
self.shared.fps.store(next.fps, Ordering::Relaxed);
let mut layers = Vec::with_capacity(specs.len());
for (spec, &threads) in specs.iter().zip(&split) {
@@ -1022,6 +1150,8 @@ impl Streamer {
bitrate: l.target.load(Ordering::Relaxed),
threads: l.threads,
speed: (speed != i64::MIN).then_some(speed as i32),
backend: *lock(&l.backend),
codecs: lock(&l.codecs).clone(),
}
})
.collect();
@@ -1432,35 +1562,168 @@ impl Drop for Ingest {
}
}
/// One layer's encoder thread.
fn encode_loop(shared: &Shared, layer: &Layer, mut encoder: Box<dyn VideoEncoder>) {
// A requested keyframe the encoder has not produced yet (rate control
// may skip a frame).
let mut keyframe_due = false;
/// One encoder of a layer: its keyframe and bitrate state.
struct LayerEncoder {
codec: Codec,
/// `None`: creating it failed (not retried until it is needed anew).
encoder: Option<Box<dyn VideoEncoder>>,
/// A requested keyframe the encoder has not produced yet (rate control
/// may skip a frame).
keyframe_due: bool,
/// The bitrate and frame rate it was last set to.
bitrate: u64,
fps: u32,
}
impl LayerEncoder {
fn new(encoder: Box<dyn VideoEncoder>, fps: u32) -> Self {
Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
}
/// Encode `frame` and hand the frames to `sink`; follows the layer's
/// target bitrate and frame rate first.
fn encode(
&mut self,
shared: &Shared,
layer: &Layer,
sink: &dyn MediaSink,
frame: &VideoFrame,
requested: bool,
target: u64,
) {
let codec = self.codec;
let Some(encoder) = &mut self.encoder else { return };
if target.abs_diff(self.bitrate) * 100 > self.bitrate {
match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) {
Ok(()) => self.bitrate = target,
Err(e) => warn!(layer = layer.id, %codec, "cannot change the bitrate: {e}"),
}
}
let want_fps = layer.fps.load(Ordering::Relaxed);
if want_fps != self.fps && encoder.set_fps(want_fps).is_ok() {
self.fps = want_fps;
}
let force = requested || self.keyframe_due;
let mut produced_keyframe = false;
let result = encoder.encode_with(frame, force, &mut |chunk| {
produced_keyframe |= chunk.keyframe;
let encoded = EncodedFrame {
kind: MediaKind::Video,
time: MediaTime::from_90khz(chunk.pts_90khz),
// The one allocation per encoded frame.
data: Arc::from(chunk.data),
layer: layer.id,
keyframe: chunk.keyframe,
};
if sink.send_video(encoded, codec) {
layer.frames.fetch_add(1, Ordering::Relaxed);
layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed);
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
shared.video_frames.fetch_add(1, Ordering::Relaxed);
}
});
match result {
Ok(()) => self.keyframe_due = force && !produced_keyframe,
Err(e) => {
warn!(layer = layer.id, %codec, "video encoding failed: {e}");
self.keyframe_due = force;
shared.set_error(e);
}
}
}
}
/// An encoder of `codec` for `layer` (a codec a viewer chose), with the
/// streamer's current codecs and preference.
fn extra_encoder(shared: &Shared, layer: &Layer, codec: Codec) -> Option<Box<dyn VideoEncoder>> {
let guard = lock(&shared.encoders);
let (codecs, preference) = guard.as_ref()?;
let spec = lock(&layer.spec).clone();
let config = encoder_config(&spec, layer.fps.load(Ordering::Relaxed), layer.threads);
match codecs.new_encoder_preferring(codec, config, preference) {
Ok(encoder) => {
debug!(layer = layer.id, %codec, backend = %encoder.backend(), "encoder for viewers");
Some(encoder)
}
Err(e) => {
warn!(layer = layer.id, %codec, "no encoder for viewers of this codec: {e}");
None
}
}
}
/// One layer's encoder thread: the stream codec's encoder, plus one per
/// other codec the sink's viewers chose (created when a viewer needs it,
/// dropped when none does).
fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
let fps = layer.fps.load(Ordering::Relaxed);
let mut primary = LayerEncoder::new(encoder, fps);
// The first frame is a keyframe anyway; no need to insist.
primary.keyframe_due = false;
primary.bitrate = layer.bitrate.load(Ordering::Relaxed);
*lock(&layer.backend) = primary.encoder.as_ref().map(|e| e.backend());
let mut extra: Vec<LayerEncoder> = Vec::new();
let mut wanted: Vec<Codec> = Vec::new();
let mut generation = shared.encoders_generation.load(Ordering::Relaxed);
// Whether the stream codec was encoded for the last frame.
let mut primary_on = true;
// The last picture, and when it came: a static screen sends no frames,
// so keyframe requests are answered by encoding it again.
let mut last: Option<(Arc<VideoFrame>, Instant)> = None;
let mut bitrate = layer.bitrate.load(Ordering::Relaxed);
let mut fps = layer.fps.load(Ordering::Relaxed);
layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed);
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
);
while !shared.stopped() && !layer.stopped() {
let frame = layer.inbox.wait_timeout(POLL);
if let Some(next) = lock(&layer.next_encoder).take() {
// Another codec: its first frame is a keyframe anyway.
encoder = next;
bitrate = 0;
keyframe_due = true;
*lock(&layer.backend) = Some(next.backend());
primary = LayerEncoder::new(next, primary.fps);
}
let Some(sink) = shared.sink() else { continue };
shared.poll_keyframes(&*sink);
// The codecs viewers chose; none known: the stream codec.
wanted.clear();
sink.video_codecs(&mut wanted);
let now = shared.encoders_generation.load(Ordering::Relaxed);
if now != generation {
generation = now;
extra.clear();
}
extra.retain(|e| wanted.contains(&e.codec));
for &codec in &wanted {
if codec != primary.codec && !extra.iter().any(|e| e.codec == codec) {
let fps = layer.fps.load(Ordering::Relaxed);
extra.push(match extra_encoder(shared, layer, codec) {
Some(encoder) => LayerEncoder::new(encoder, fps),
None => {
LayerEncoder { codec, encoder: None, keyframe_due: false, bitrate: 0, fps }
}
});
}
}
let primary_wanted = wanted.is_empty() || wanted.contains(&primary.codec);
if primary_wanted && !primary_on {
// Frames were skipped: the next one must stand alone.
primary.keyframe_due = true;
}
primary_on = primary_wanted;
{
let mut codecs = lock(&layer.codecs);
codecs.clear();
codecs.extend(primary_on.then_some(primary.codec));
codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec));
}
let requested = layer.keyframe.swap(false, Ordering::Relaxed);
let force = requested || keyframe_due;
let due = primary_on && primary.keyframe_due
|| extra.iter().any(|e| e.keyframe_due && e.encoder.is_some());
let frame = match frame {
Some(frame) => {
last = Some((frame.clone(), Instant::now()));
frame
}
None if force => {
None if requested || due => {
let Some((frame, at)) = &last else {
layer.keyframe.store(requested, Ordering::Relaxed);
continue;
@@ -1477,50 +1740,21 @@ fn encode_loop(shared: &Shared, layer: &Layer, mut encoder: Box<dyn VideoEncoder
max => max,
};
let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap);
if target.abs_diff(bitrate) * 100 > bitrate {
match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) {
Ok(()) => {
bitrate = target;
layer.target.store(target, Ordering::Relaxed);
}
Err(e) => warn!(layer = layer.id, "cannot change the bitrate: {e}"),
}
}
let want_fps = layer.fps.load(Ordering::Relaxed);
if want_fps != fps && encoder.set_fps(want_fps).is_ok() {
fps = want_fps;
}
let started = Instant::now();
let mut produced_keyframe = false;
let result = encoder.encode_with(&frame, force, &mut |chunk| {
produced_keyframe |= chunk.keyframe;
let encoded = EncodedFrame {
kind: MediaKind::Video,
time: MediaTime::from_90khz(chunk.pts_90khz),
// The one allocation per encoded frame.
data: Arc::from(chunk.data),
layer: layer.id,
keyframe: chunk.keyframe,
};
if sink.send(encoded) {
layer.frames.fetch_add(1, Ordering::Relaxed);
layer.keyframes.fetch_add(u64::from(chunk.keyframe), Ordering::Relaxed);
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
shared.video_frames.fetch_add(1, Ordering::Relaxed);
}
});
if primary_on {
primary.encode(shared, layer, &*sink, &frame, requested, target);
layer.target.store(primary.bitrate, Ordering::Relaxed);
}
for encoder in &mut extra {
encoder.encode(shared, layer, &*sink, &frame, requested, target);
}
layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
layer.encoded.fetch_add(1, Ordering::Relaxed);
layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
layer.speed.store(encoder.speed().map_or(i64::MIN, i64::from), Ordering::Relaxed);
match result {
Ok(()) => keyframe_due = force && !produced_keyframe,
Err(e) => {
warn!(layer = layer.id, "video encoding failed: {e}");
keyframe_due = force;
shared.set_error(e);
}
}
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
);
}
}
@@ -1746,6 +1980,11 @@ pub fn is_keyframe(codec: Codec, data: &[u8]) -> bool {
Codec::Vp9 => vp9_is_keyframe(data),
Codec::H264 => h264_nal_types(data).any(|t| t == 5 || t == 7),
Codec::Av1 => av1_has_sequence_header(data).unwrap_or(true),
// IRAP pictures (16-23) or a VPS / SPS in front of one.
Codec::H265 => data
.windows(4)
.filter_map(|w| (w[..3] == [0, 0, 1]).then_some((w[3] >> 1) & 0x3f))
.any(|t| (16..=23).contains(&t) || t == 32 || t == 33),
}
}
@@ -2207,6 +2446,10 @@ mod tests {
assert!(is_keyframe(Codec::Av1, &[0x12, 0x00, 0x0a, 0x01, 0xff]));
assert!(!is_keyframe(Codec::Av1, &[0x12, 0x00, 0x32, 0x01, 0xff]));
assert!(is_keyframe(Codec::Av1, &[0x12, 0x05]), "truncated: let the decoder try");
// HEVC: a VPS (type 32) or an IDR (19) starts one, a trailing picture not.
assert!(is_keyframe(Codec::H265, &[0, 0, 1, 0x40, 0x01]));
assert!(is_keyframe(Codec::H265, &[0, 0, 0, 1, 0x26, 0x01]));
assert!(!is_keyframe(Codec::H265, &[0, 0, 1, 0x02, 0x01]));
}
#[test]
@@ -2222,14 +2465,125 @@ mod tests {
#[cfg(feature = "media-desktop")]
#[test]
fn peer_config_follows_codecs() {
let codecs = Codecs::new();
let codecs = Codecs::builtin();
let config = peer_config(&codecs, PeerConfig::default());
assert_eq!(config.video_codecs, [VideoCodec::Vp8]);
assert!(config.accept_video_codecs.contains(&VideoCodec::Vp8));
assert!(!config.accept_video_codecs.contains(&VideoCodec::H264), "no OpenH264 loaded");
assert_eq!(stream_codec(&codecs, &config), Some(Codec::Vp8));
let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config };
let h264_only = PeerConfig { video_codecs: vec![VideoCodec::H264], ..config.clone() };
assert_eq!(stream_codec(&codecs, &h264_only), None);
// VP9 as the stream codec: VP8 (cheap) is offered after it, nothing
// else in software.
let vp9 = PeerConfig { video_codecs: vec![VideoCodec::Vp9], ..config };
let vp9 = peer_config(&codecs, vp9);
assert_eq!(vp9.video_codecs, [VideoCodec::Vp9, VideoCodec::Vp8]);
assert_eq!(stream_codec(&codecs, &vp9), Some(Codec::Vp9));
// With FFmpeg's software encoders, still only VP8 besides the stream
// codec.
let all = Codecs::new();
let offer = offer_codecs(&all, Codec::Vp8);
for codec in &offer[1..] {
let backend = all.encoders().into_iter().find(|(c, _)| c == codec).unwrap().1;
assert!(all.is_hardware(backend), "{codec} offered in software");
}
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
}
}
/// A sink whose viewers chose `codecs`; keeps every video frame with its
/// codec.
#[derive(Default)]
struct CodecSink {
codecs: Mutex<Vec<Codec>>,
frames: Mutex<Vec<(Codec, EncodedFrame)>>,
keyframe: AtomicBool,
}
impl MediaSink for CodecSink {
fn send(&self, _: EncodedFrame) -> bool {
true
}
fn send_video(&self, frame: EncodedFrame, codec: Codec) -> bool {
lock(&self.frames).push((codec, frame));
true
}
fn take_keyframe_request(&self) -> bool {
self.keyframe.swap(false, Ordering::Relaxed)
}
fn video_codecs(&self, out: &mut Vec<Codec>) {
out.extend(lock(&self.codecs).iter());
}
}
/// Viewers that chose another codec get their own encoder per layer,
/// made when they come and dropped when they go; the stream codec is
/// skipped while nobody takes it.
#[cfg(feature = "media-desktop")]
#[tokio::test(flavor = "multi_thread")]
async fn an_encoder_per_codec_viewers_chose() {
let codecs = Codecs::builtin();
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (160, 120),
audio: false,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let sink = Arc::new(CodecSink::default());
streamer.attach(sink.clone());
let wait_for = |codec: Codec, count: usize| {
let sink = sink.clone();
async move {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let n = lock(&sink.frames).iter().filter(|(c, _)| *c == codec).count();
if n >= count {
return;
}
assert!(Instant::now() < deadline, "no {codec} frames");
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
};
// Nobody chose yet: the stream codec.
wait_for(Codec::Vp8, 3).await;
// A VP9 viewer as well.
*lock(&sink.codecs) = vec![Codec::Vp8, Codec::Vp9];
wait_for(Codec::Vp9, 5).await;
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp8, Codec::Vp9]);
let vp9: Vec<EncodedFrame> = lock(&sink.frames)
.iter()
.filter(|(c, _)| *c == Codec::Vp9)
.map(|(_, f)| f.clone())
.collect();
assert!(is_keyframe(Codec::Vp9, &vp9[0].data), "the first VP9 frame is a keyframe");
let mut decoder = codecs.new_decoder(Codec::Vp9).unwrap();
for frame in &vp9 {
let picture = decoder.decode(&frame.data).unwrap().expect("a picture");
assert_eq!((picture.width, picture.height), (160, 120));
}
// Only VP9 viewers left: VP8 stops.
*lock(&sink.codecs) = vec![Codec::Vp9];
tokio::time::sleep(Duration::from_millis(300)).await;
let before = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
wait_for(Codec::Vp9, vp9.len() + 10).await;
let after = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp8).count();
assert_eq!(before, after, "VP8 is not encoded for nobody");
assert_eq!(streamer.stats().layers[0].codecs, [Codec::Vp9]);
assert_eq!(streamer.stats().layers[0].backend, Some(EncoderBackend::Libvpx));
// Another encoder preference: new encoders, the stream goes on.
let update = StreamerConfigUpdate {
encoder: Some(EncoderPreference { hardware: false, ..EncoderPreference::default() }),
..StreamerConfigUpdate::default()
};
streamer.reconfigure(&codecs, update).unwrap();
let count = lock(&sink.frames).iter().filter(|(c, _)| *c == Codec::Vp9).count();
wait_for(Codec::Vp9, count + 5).await;
}
/// The test pattern through VP8 and back, without a network: pictures
+18
View File
@@ -85,6 +85,18 @@ impl StreamSink {
self.live.load(Ordering::Relaxed) && self.tx.send(StreamInput::Frame(frame)).is_ok()
}
/// Send one video frame encoded in `codec`: only viewers whose answer
/// chose `codec` get it.
pub fn send_video(&self, frame: EncodedFrame, codec: VideoCodec) -> bool {
self.live.load(Ordering::Relaxed)
&& self.tx.send(StreamInput::VideoFrame(frame, codec)).is_ok()
}
/// Whether a viewer's answer chose `codec`.
pub fn has_video_codec(&self, codec: VideoCodec) -> bool {
self.feedback.has_codec(codec)
}
/// Whether a viewer asked for a keyframe of any layer since the last
/// call (or [`take_layer_keyframes`](Self::take_layer_keyframes)).
pub fn take_keyframe_request(&self) -> bool {
@@ -149,6 +161,8 @@ pub(crate) enum StreamInput {
/// SRTP profile order of new connections.
SrtpProfiles(Vec<SrtpProfile>),
Frame(EncodedFrame),
/// A video frame for the viewers that chose its codec.
VideoFrame(EncodedFrame, VideoCodec),
Notification(StreamNotification),
RequestFailed(Request, String),
/// Clients on the server: channel and `client_is_streaming`.
@@ -365,6 +379,10 @@ impl StreamTask {
self.streams.write_frame(&frame);
Ok(())
}
StreamInput::VideoFrame(frame, codec) => {
self.streams.write_frame_in(&frame, Some(codec));
Ok(())
}
StreamInput::Notification(n) => {
self.streams.handle_notification(n).await;
Ok(())
+78 -1
View File
@@ -14,7 +14,7 @@ use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::capture::synthetic::RECT_COLOR;
use voelin_core::media::voelin_media::{Codec, Codecs, convert};
use voelin_core::media::{Streamer, StreamerConfig, Viewer, peer_config, stream_codec};
use voelin_core::stream::{PeerConfig, StreamSetup};
use voelin_core::stream::{PeerConfig, StreamSetup, VideoCodec};
use voelin_core::{Command, Engine, Event, StreamState, VoiceOptions, VoiceState, WatchState};
fn live() -> bool {
@@ -177,3 +177,80 @@ async fn ts6_test_pattern_decoded() {
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
/// The streamer's offer lists VP9 (its stream codec) and VP8; a viewer that
/// only decodes VP8 answers VP8 and gets VP8 pictures from an encoder made
/// for it, while the VP9 encoder, wanted by nobody, idles.
#[tokio::test(flavor = "multi_thread")]
async fn ts6_viewer_gets_the_codec_it_chose() {
if !live() {
eprintln!("skipped: set VOELIN_LIVE=1 with the dev servers running");
return;
}
let engine = Engine::start();
let mut events = engine.subscribe();
let codecs = Arc::new(Codecs::builtin());
let vp9_first = PeerConfig { video_codecs: vec![VideoCodec::Vp9], ..PeerConfig::loopback() };
let streamer_peer = peer_config(&codecs, vp9_first);
assert_eq!(streamer_peer.video_codecs, [VideoCodec::Vp9, VideoCodec::Vp8]);
let codec = stream_codec(&codecs, &streamer_peer).expect("an encoder");
assert_eq!(codec, Codec::Vp9);
let viewer_peer =
PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() };
let tag = std::process::id() % 10_000;
connect(&engine, &mut events, 1, &format!("c-streamer-{tag}"), streamer_peer).await;
connect(&engine, &mut events, 2, &format!("c-viewer-{tag}"), viewer_peer).await;
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (320, 180),
bitrate_kbps: 1000,
codec,
..StreamerConfig::default()
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let setup = StreamSetup { name: format!("codecs {tag}"), ..Default::default() };
engine.send(Command::StartStream { session: 1, setup, auto_accept: true });
let mut live = None;
let mut listed = Vec::new();
let (id, sink) = wait_for(&mut events, "stream live and in the viewer's list", |e| {
match e {
Event::StreamState { session: 1, state: StreamState::Live { id, sink } } => {
live = Some((id.clone(), sink.clone()));
}
Event::StreamsChanged { session: 2, streams } => {
listed = streams.iter().map(|s| s.id.clone()).collect();
}
_ => {}
}
live.clone().filter(|(id, _)| listed.contains(id))
})
.await;
streamer.attach(Arc::new(sink));
let (tx, pictures) = std_mpsc::channel();
let viewer = Viewer::start(&engine, 2, &id, codecs, move |picture| {
let _ = tx.send(picture);
});
engine.send(Command::WatchStream { session: 2, stream_id: id.clone() });
let decoded = tokio::task::spawn_blocking(move || {
let mut decoded = 0;
while decoded < 30 {
let picture = pictures.recv_timeout(Duration::from_secs(15)).expect("no picture");
assert_eq!((picture.width, picture.height), (320, 180));
decoded += 1;
}
decoded
})
.await
.unwrap();
let sent = streamer.stats();
eprintln!("decoded {decoded}, sent {sent:?}");
assert_eq!(sent.layers[0].codecs, [Codec::Vp8], "only the codec a viewer chose");
assert!(viewer.stats().error.is_none());
engine.send(Command::StopStream { session: 1 });
drop(viewer);
drop(streamer);
engine.send(Command::CloseSession { session: 1 });
engine.send(Command::CloseSession { session: 2 });
tokio::time::sleep(Duration::from_millis(500)).await;
}
+6 -1
View File
@@ -9,7 +9,7 @@ repository.workspace = true
publish.workspace = true
[features]
default = ["vpx", "openh264", "openh264-download", "x11", "pipewire", "wlroots"]
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots"]
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
vpx = ["dep:libvpx-native-sys"]
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
@@ -17,6 +17,10 @@ vpx = ["dep:libvpx-native-sys"]
openh264 = ["dep:openh264"]
# Download of Cisco's OpenH264 binary over HTTPS with a SHA-256 check.
openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
# Video encoders through FFmpeg loaded at runtime (never linked or shipped):
# VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264,
# SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md).
ffmpeg = ["dep:libloading"]
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
av1 = ["dep:dav1d"]
# X11 screen capture (Linux).
@@ -33,6 +37,7 @@ str0m = ["dep:str0m"]
[dependencies]
bzip2 = { version = "0.6.1", optional = true }
dav1d = { version = "0.11.1", optional = true }
libloading = { version = "0.8.9", optional = true }
libvpx-native-sys = { version = "5.0.17", optional = true }
openh264 = { version = "0.9.8", default-features = false, features = ["libloading"], optional = true }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"], optional = true }
+48
View File
@@ -110,6 +110,54 @@ pub trait FrameSink: Send {
/// One frame. Its pixels are only valid during the call. Returns
/// `false` when no more frames are wanted; the backend then stops.
fn frame(&mut self, frame: FrameRef<'_>) -> bool;
/// Whether the sink takes frames that are still in a DMA-BUF (GPU
/// memory) through [`dmabuf`](Self::dmabuf), e.g. for a VA-API encoder
/// that imports them without a copy
/// (`ffmpeg::FfmpegEncoder::encode_dmabuf`). Backends that capture into
/// DMA-BUFs (the portal) then offer the buffer before mapping it.
fn accepts_dmabuf(&self) -> bool {
false
}
/// A frame in a DMA-BUF, valid during the call. `None`: not taken, the
/// backend maps it and calls [`frame`](Self::frame); `Some(more)` as the
/// result of `frame`.
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
let _ = frame;
None
}
}
/// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`.
pub const fn drm_fourcc(code: &[u8; 4]) -> u32 {
code[0] as u32 | (code[1] as u32) << 8 | (code[2] as u32) << 16 | (code[3] as u32) << 24
}
/// `DRM_FORMAT_MOD_LINEAR`.
pub const DRM_MOD_LINEAR: u64 = 0;
/// `DRM_FORMAT_MOD_INVALID`: the driver's implicit layout.
pub const DRM_MOD_INVALID: u64 = 0x00ff_ffff_ffff_ffff;
/// A captured frame still in a DMA-BUF: one buffer object (a file
/// descriptor borrowed for the call) with one plane per `planes` entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DmaBufRef {
pub width: u32,
pub height: u32,
/// As [`VideoFrame::timestamp`].
pub timestamp: Duration,
/// DRM format (`drm_fourcc(b"XR24")` for BGRx, `b"NV12"`, ...).
pub fourcc: u32,
/// DRM format modifier (tiling); [`DRM_MOD_LINEAR`] for rows in memory
/// order.
pub modifier: u64,
pub fd: i32,
/// Size of the buffer object in bytes.
pub size: usize,
/// `(offset, stride)` of each plane in the buffer object.
pub planes: [(usize, usize); 4],
pub plane_count: usize,
}
/// Keeps frames of a source for a frame-rate cap, by their timestamps, so
+36 -3
View File
@@ -34,7 +34,8 @@ use tracing::{debug, warn};
use crate::capture::dmabuf::DmaBufMap;
use crate::capture::pw::{PwThread, pod, serialize};
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture, SourceId,
BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink,
ScreenCapture, SourceId, drm_fourcc,
};
use crate::frame::{FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::FrameReceiver;
@@ -524,8 +525,8 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
}
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some(format) = state.format else { return };
if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) {
// Tiled: the CPU cannot read it (we never offer that).
if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) && !state.sink.accepts_dmabuf() {
// Tiled: the CPU cannot read it (we only offer LINEAR).
return;
}
let timestamp = state.started.elapsed();
@@ -564,6 +565,38 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
state.logged = Some(is_dmabuf);
debug!(dmabuf = is_dmabuf, "screen capture buffers");
}
// A sink that imports DMA-BUFs (a VA-API encoder) gets the buffer as it
// is, without a mapping or copy.
if is_dmabuf && state.sink.accepts_dmabuf() {
let raw = data.as_raw();
let fourcc = match format.format {
VideoFormat::BGRx => drm_fourcc(b"XR24"),
VideoFormat::BGRA => drm_fourcc(b"AR24"),
VideoFormat::RGBx => drm_fourcc(b"XB24"),
_ => drm_fourcc(b"AB24"),
};
let frame = DmaBufRef {
width: format.width,
height: format.height,
timestamp,
fourcc,
modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64),
fd: data.fd(),
size: (raw.mapoffset + raw.maxsize) as usize,
planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
if let Some(more) = state.sink.dmabuf(&frame) {
if !more && let Some(mainloop) = state.mainloop.upgrade() {
mainloop.quit();
}
return;
}
}
if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) {
// Tiled and not taken as it is: nothing the CPU can read.
return;
}
let started = Instant::now();
let more = if is_dmabuf {
let raw = data.as_raw();
+2 -9
View File
@@ -173,14 +173,7 @@ impl OpenH264 {
}
}
/// H.264 profile of the encoder output.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum H264Profile {
/// Constrained High (what TeamSpeak clients decode).
#[default]
ConstrainedHigh,
ConstrainedBaseline,
}
pub use super::H264Profile;
/// OpenH264 encoder.
pub struct OpenH264Encoder {
@@ -196,8 +189,8 @@ impl OpenH264Encoder {
fn new(library: OpenH264, config: EncoderConfig) -> Result<Self> {
let mut encoder = Self {
library,
profile: config.h264_profile,
config,
profile: H264Profile::default(),
encoder: None,
output: Vec::new(),
};
+35 -85
View File
@@ -1,38 +1,50 @@
//! Hardware video encoders.
//! Encoder factories found at runtime.
//!
//! The streamer prefers a GPU encoder over software VP8 / OpenH264. None is
//! implemented yet; the factories below mark where they plug in:
//!
//! - Linux: VA-API (H.264 Constrained High / VP8 / VP9 on Intel and AMD), e.g.
//! through `cros-libva`. TODO.
//! - Windows: Media Foundation H.264 encoder MFT (NVENC / QuickSync / AMF
//! behind it). TODO.
//! - 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`]).
//! - Android: MediaCodec ([`super::mediacodec`]).
use crate::Result;
use crate::codec::{Codec, EncoderConfig, VideoEncoder};
use crate::codec::{Codec, EncoderBackend, EncoderConfig, VideoEncoder};
/// Creates encoders of one hardware API.
pub trait HardwareEncoderFactory: Send + Sync {
/// Short name for logs and settings (`"vaapi"`, `"mediafoundation"`).
/// Creates encoders of one backend.
pub trait EncoderFactory: Send + Sync {
/// Short name for logs and settings (`"h264_vaapi"`, `"mediacodec"`).
fn name(&self) -> &'static str;
/// Codecs this device can encode, best first.
/// Codecs this backend encodes, best first.
fn codecs(&self) -> Vec<Codec>;
fn create(&self, codec: Codec, config: &EncoderConfig) -> Result<Box<dyn VideoEncoder>>;
/// A GPU / OS encoder (the default), as opposed to a software encoder
/// reached through the same API (FFmpeg's libx264, ...).
fn is_hardware(&self) -> bool {
true
}
/// Whether the automatic choice may use it (not for encoders with a long
/// delay; those are used only when named in the settings).
fn is_automatic(&self) -> bool {
true
}
/// The backend its encoders report.
fn backend(&self) -> EncoderBackend {
EncoderBackend::Hardware(self.name())
}
}
/// Hardware encoders usable on this machine (none yet).
pub fn probe() -> Vec<Box<dyn HardwareEncoderFactory>> {
let mut found: Vec<Box<dyn HardwareEncoderFactory>> = Vec::new();
#[cfg(target_os = "linux")]
if let Some(f) = vaapi::probe() {
found.push(Box::new(f));
}
#[cfg(windows)]
if let Some(f) = media_foundation::probe() {
found.push(Box::new(f));
/// Encoder factories usable on this machine: FFmpeg's backends that passed
/// their self-test, then MediaCodec (Android).
pub fn probe() -> Vec<Box<dyn EncoderFactory>> {
#[allow(unused_mut)]
let mut found: Vec<Box<dyn EncoderFactory>> = Vec::new();
#[cfg(feature = "ffmpeg")]
for factory in crate::ffmpeg::FfmpegFactory::available() {
found.push(Box::new(factory));
}
#[cfg(target_os = "android")]
if let Some(f) = super::mediacodec::probe() {
@@ -40,65 +52,3 @@ pub fn probe() -> Vec<Box<dyn HardwareEncoderFactory>> {
}
found
}
#[cfg(target_os = "linux")]
mod vaapi {
use super::*;
use crate::Error;
pub struct Vaapi;
/// TODO: open the DRM render node, query VAProfileH264ConstrainedBaseline /
/// VAProfileH264High / VP8 / VP9 encode entrypoints.
pub fn probe() -> Option<Vaapi> {
None
}
impl HardwareEncoderFactory for Vaapi {
fn name(&self) -> &'static str {
"vaapi"
}
fn codecs(&self) -> Vec<Codec> {
Vec::new()
}
fn create(&self, codec: Codec, _: &EncoderConfig) -> Result<Box<dyn VideoEncoder>> {
Err(Error::CodecUnavailable {
codec,
reason: "VA-API encoding is not implemented".into(),
})
}
}
}
#[cfg(windows)]
mod media_foundation {
use super::*;
use crate::Error;
pub struct MediaFoundation;
/// TODO: enumerate hardware H.264 encoder MFTs (`MFTEnumEx` with
/// `MFT_ENUM_FLAG_HARDWARE`).
pub fn probe() -> Option<MediaFoundation> {
None
}
impl HardwareEncoderFactory for MediaFoundation {
fn name(&self) -> &'static str {
"mediafoundation"
}
fn codecs(&self) -> Vec<Codec> {
Vec::new()
}
fn create(&self, codec: Codec, _: &EncoderConfig) -> Result<Box<dyn VideoEncoder>> {
Err(Error::CodecUnavailable {
codec,
reason: "Media Foundation encoding is not implemented".into(),
})
}
}
}
+3 -2
View File
@@ -24,7 +24,7 @@ use ndk::media::media_codec::{
use ndk::media::media_format::MediaFormat;
use tracing::{debug, info};
use super::hw::HardwareEncoderFactory;
use super::hw::EncoderFactory;
use super::image_layout::{
COLOR_FORMAT_FLEXIBLE, COLOR_FORMAT_I420, COLOR_FORMAT_NV12, ImageLayout,
};
@@ -56,6 +56,7 @@ fn mime(codec: Codec) -> &'static str {
Codec::Vp9 => "video/x-vnd.on2.vp9",
Codec::H264 => "video/avc",
Codec::Av1 => "video/av01",
Codec::H265 => "video/hevc",
}
}
@@ -145,7 +146,7 @@ pub struct MediaCodecFactory {
codecs: Vec<Codec>,
}
impl HardwareEncoderFactory for MediaCodecFactory {
impl EncoderFactory for MediaCodecFactory {
fn name(&self) -> &'static str {
NAME
}
+393 -29
View File
@@ -7,12 +7,15 @@
//! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264,
//! loaded at runtime
//! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d
//! - [`hw`]: hardware encoders (VA-API, Media Foundation); not implemented yet
//! - [`hw`]: encoder factories found at runtime: FFmpeg's hardware and
//! software encoders ([`crate::ffmpeg`], feature `ffmpeg`) and, on Android,
//! MediaCodec
//! - `mediacodec` (Android): the device's MediaCodec encoders and decoders
//! (hardware, or Google's software VP8 / VP9 / H.264)
use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use crate::frame::VideoFrame;
use crate::{Error, Result};
@@ -28,17 +31,19 @@ pub mod mediacodec;
#[cfg(feature = "vpx")]
pub mod vpx;
/// Video codecs TeamSpeak 6 streams use.
/// Video codecs of streams: the four TeamSpeak 6 uses, and HEVC for peers
/// that negotiate it (offered last, hardware encoders only).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Codec {
Vp8,
Vp9,
H264,
Av1,
H265,
}
impl Codec {
pub const ALL: [Codec; 4] = [Codec::Vp8, Codec::Vp9, Codec::H264, Codec::Av1];
pub const ALL: [Codec; 5] = [Codec::Vp8, Codec::Vp9, Codec::H264, Codec::Av1, Codec::H265];
/// Name as in SDP (`a=rtpmap:<pt> <name>/90000`).
pub fn name(self) -> &'static str {
@@ -47,6 +52,7 @@ impl Codec {
Codec::Vp9 => "VP9",
Codec::H264 => "H264",
Codec::Av1 => "AV1",
Codec::H265 => "H265",
}
}
}
@@ -69,6 +75,7 @@ impl FromStr for Codec {
"vp9" => Ok(Codec::Vp9),
"h264" | "h.264" | "avc" => Ok(Codec::H264),
"av1" | "av1x" => Ok(Codec::Av1),
"h265" | "h.265" | "hevc" => Ok(Codec::H265),
_ => Err(Error::Convert(format!("unknown codec {s:?}"))),
}
}
@@ -82,6 +89,7 @@ impl From<Codec> for str0m::format::Codec {
Codec::Vp9 => str0m::format::Codec::Vp9,
Codec::H264 => str0m::format::Codec::H264,
Codec::Av1 => str0m::format::Codec::Av1,
Codec::H265 => str0m::format::Codec::H265,
}
}
}
@@ -96,6 +104,7 @@ impl TryFrom<str0m::format::Codec> for Codec {
str0m::format::Codec::Vp9 => Ok(Codec::Vp9),
str0m::format::Codec::H264 => Ok(Codec::H264),
str0m::format::Codec::Av1 => Ok(Codec::Av1),
str0m::format::Codec::H265 => Ok(Codec::H265),
other => Err(Error::Convert(format!("not a video codec: {other:?}"))),
}
}
@@ -114,6 +123,16 @@ pub enum ContentHint {
Motion,
}
/// H.264 profile of the encoder output.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum H264Profile {
/// Constrained High (what TeamSpeak clients decode): High without
/// B-frames.
#[default]
ConstrainedHigh,
ConstrainedBaseline,
}
/// Encoder settings. The resolution follows the frames: the first frame and
/// every size change start a new keyframe.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -131,8 +150,12 @@ pub struct EncoderConfig {
pub threads: u32,
/// A fixed speed / quality trade-off in the backend's own terms (libvpx
/// `cpu-used`); `None` lets the encoder adapt it to how long frames take
/// to encode compared to the frame interval.
/// to encode compared to the frame interval. FFmpeg backends: the x264
/// preset index (0 ultrafast .. 9 placebo), the NVENC preset `p1`..`p7`,
/// the SVT-AV1 preset, rav1e's speed, libaom's `cpu-used`.
pub speed: Option<i32>,
/// H.264 only.
pub h264_profile: H264Profile,
}
impl Default for EncoderConfig {
@@ -144,6 +167,7 @@ impl Default for EncoderConfig {
content: ContentHint::Screen,
threads: 0,
speed: None,
h264_profile: H264Profile::default(),
}
}
}
@@ -244,29 +268,152 @@ pub trait VideoDecoder: Send {
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>>;
}
/// Implementations behind [`VideoEncoder`], in the streamer's order of
/// preference.
/// Implementations behind [`VideoEncoder`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EncoderBackend {
/// An OS / GPU encoder (see [`hw`]).
/// An OS / GPU encoder of its own API (Android's `mediacodec`, see
/// [`hw`]).
Hardware(&'static str),
/// An FFmpeg encoder by its FFmpeg name (`h264_vaapi`, `libx264`, see
/// [`crate::ffmpeg`]), hardware or software.
Ffmpeg(&'static str),
Libvpx,
OpenH264,
}
impl EncoderBackend {
/// The name in settings (`stream.encoder_backend`) and logs.
pub fn name(self) -> &'static str {
match self {
EncoderBackend::Hardware(name) | EncoderBackend::Ffmpeg(name) => name,
EncoderBackend::Libvpx => "libvpx",
EncoderBackend::OpenH264 => "openh264",
}
}
}
impl fmt::Display for EncoderBackend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
/// Which encoders to use (settings `stream.hardware_acceleration` and
/// `stream.encoder_backend`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderPreference {
/// Use hardware encoders when [`backend`](Self::backend) is `Auto`.
pub hardware: bool,
pub backend: BackendChoice,
}
impl Default for EncoderPreference {
fn default() -> Self {
Self { hardware: true, backend: BackendChoice::Auto }
}
}
/// `stream.encoder_backend`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum BackendChoice {
/// Hardware first (if enabled), then software.
#[default]
Auto,
/// Software encoders only.
Software,
/// This backend ([`EncoderBackend::name`]) for the codecs it encodes;
/// the automatic order for the others and as fallback.
Named(String),
}
impl FromStr for BackendChoice {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(match s.trim() {
"" | "auto" => BackendChoice::Auto,
"software" => BackendChoice::Software,
name => BackendChoice::Named(name.to_owned()),
})
}
}
impl fmt::Display for BackendChoice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BackendChoice::Auto => f.write_str("auto"),
BackendChoice::Software => f.write_str("software"),
BackendChoice::Named(name) => f.write_str(name),
}
}
}
/// One encoder backend in [`Codecs::report`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderInfo {
/// [`EncoderBackend::name`].
pub name: String,
/// The API or library (`VA-API`, `NVENC`, `x264`, `libvpx`, ...).
pub api: String,
pub codec: Codec,
pub hardware: bool,
/// Usable (passed its self-test), or why not.
pub status: std::result::Result<(), String>,
/// Position among the encoders of its codec under the current
/// preference (0: used first); `None` if not used.
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`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncoderReport {
/// The FFmpeg libraries in use (release, version, path), or why none.
pub ffmpeg: std::result::Result<String, String>,
/// Whether captured DMA-BUFs can go to a VA-API encoder without a copy,
/// or why not.
pub zero_copy: std::result::Result<(), String>,
pub encoders: Vec<EncoderInfo>,
}
fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
Error::CodecUnavailable { codec, reason: reason.into() }
}
/// Order of codecs among hardware encoders: H.264 (every viewer decodes
/// it), AV1, VP9, VP8, and HEVC last (only for peers that take nothing
/// else).
const HARDWARE_ORDER: [Codec; 5] = [Codec::H264, Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H265];
/// An encoder backend in the base order (before the preference applies).
struct Candidate {
codec: Codec,
backend: EncoderBackend,
hardware: bool,
/// See [`hw::EncoderFactory::is_automatic`].
automatic: bool,
}
impl Candidate {
fn builtin(codec: Codec, backend: EncoderBackend) -> Self {
Self { codec, backend, hardware: false, automatic: true }
}
}
/// The codecs this build and machine can use, and factories for them.
///
/// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer
/// order ([`Codecs::encoders`]): hardware > VP8 (libvpx) > H.264 (OpenH264)
/// > VP9 (libvpx, costly in software).
/// 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
/// OpenH264) > VP9 (libvpx, costly in software) > AV1 (SVT-AV1, rav1e,
/// libaom through FFmpeg). Cheap to clone: the factories are shared.
#[derive(Clone)]
pub struct Codecs {
hardware: Vec<Box<dyn hw::HardwareEncoderFactory>>,
factories: Vec<Arc<dyn hw::EncoderFactory>>,
#[cfg(feature = "openh264")]
openh264: Option<h264::OpenH264>,
preference: EncoderPreference,
}
impl Default for Codecs {
@@ -280,18 +427,32 @@ impl fmt::Debug for Codecs {
f.debug_struct("Codecs")
.field("decoders", &self.decoders())
.field("encoders", &self.encoders())
.field("preference", &self.preference)
.finish()
}
}
impl Codecs {
/// Software codecs compiled in, plus whatever hardware encoders
/// [`hw::probe`] finds. H.264 needs [`Codecs::with_openh264`].
/// 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`].
pub fn new() -> Self {
Self {
hardware: hw::probe(),
factories: hw::probe().into_iter().map(Arc::from).collect(),
#[cfg(feature = "openh264")]
openh264: None,
preference: EncoderPreference::default(),
}
}
/// Only the codecs compiled into this crate (libvpx, OpenH264 once
/// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed.
pub fn builtin() -> Self {
Self {
factories: Vec::new(),
#[cfg(feature = "openh264")]
openh264: None,
preference: EncoderPreference::default(),
}
}
@@ -307,6 +468,26 @@ impl Codecs {
self.openh264.as_ref()
}
/// Use `preference` for [`encoders`](Self::encoders) and
/// [`new_encoder`](Self::new_encoder).
pub fn with_preference(mut self, preference: EncoderPreference) -> Self {
self.preference = preference;
self
}
pub fn set_preference(&mut self, preference: EncoderPreference) {
self.preference = preference;
}
pub fn preference(&self) -> &EncoderPreference {
&self.preference
}
/// Whether `backend` is a hardware encoder here.
pub fn is_hardware(&self, backend: EncoderBackend) -> bool {
self.factories.iter().any(|f| f.backend() == backend && f.is_hardware())
}
fn has_openh264(&self) -> bool {
#[cfg(feature = "openh264")]
return self.openh264.is_some();
@@ -335,6 +516,7 @@ impl Codecs {
#[cfg(not(feature = "av1"))]
return Err(unavailable(codec, "built without the `av1` feature"));
}
Codec::H265 => Err(unavailable(codec, "no HEVC decoder")),
}
}
@@ -343,28 +525,59 @@ impl Codecs {
VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect()
}
/// Encoders in the streamer's order of preference.
pub fn encoders(&self) -> Vec<(Codec, EncoderBackend)> {
/// Every usable encoder in the base order, before the preference.
fn candidates(&self) -> Vec<Candidate> {
let mut list = Vec::new();
for factory in &self.hardware {
for codec in factory.codecs() {
list.push((codec, EncoderBackend::Hardware(factory.name())));
let factories = |codec: Codec, hardware: bool, list: &mut Vec<Candidate>| {
for f in self.factories.iter().filter(|f| f.is_hardware() == hardware) {
if f.codecs().contains(&codec) {
let automatic = f.is_automatic();
list.push(Candidate { codec, backend: f.backend(), hardware, automatic });
}
}
};
for codec in HARDWARE_ORDER {
factories(codec, true, &mut list);
}
#[cfg(feature = "vpx")]
if vpx::check(Codec::Vp8, true).is_ok() {
list.push((Codec::Vp8, EncoderBackend::Libvpx));
list.push(Candidate::builtin(Codec::Vp8, EncoderBackend::Libvpx));
}
factories(Codec::H264, false, &mut list);
if self.has_openh264() {
list.push((Codec::H264, EncoderBackend::OpenH264));
list.push(Candidate::builtin(Codec::H264, EncoderBackend::OpenH264));
}
#[cfg(feature = "vpx")]
if vpx::check(Codec::Vp9, true).is_ok() {
list.push((Codec::Vp9, EncoderBackend::Libvpx));
list.push(Candidate::builtin(Codec::Vp9, EncoderBackend::Libvpx));
}
for codec in [Codec::Av1, Codec::H265, Codec::Vp8, Codec::Vp9] {
factories(codec, false, &mut list);
}
list
}
/// Encoders in the streamer's order of preference.
pub fn encoders(&self) -> Vec<(Codec, EncoderBackend)> {
self.encoders_for(&self.preference)
}
/// Encoders in the order `preference` gives.
pub fn encoders_for(&self, preference: &EncoderPreference) -> Vec<(Codec, EncoderBackend)> {
let all = self.candidates();
let automatic = |c: &Candidate| c.automatic && (preference.hardware || !c.hardware);
let chosen: Vec<&Candidate> = match &preference.backend {
BackendChoice::Auto => all.iter().filter(|c| automatic(c)).collect(),
BackendChoice::Software => all.iter().filter(|c| c.automatic && !c.hardware).collect(),
BackendChoice::Named(name) => {
let named = all.iter().filter(|c| c.backend.name() == name);
let rest = all.iter().filter(|c| c.backend.name() != name && automatic(c));
named.chain(rest).collect()
}
};
chosen.into_iter().map(|c| (c.codec, c.backend)).collect()
}
/// Encodable codecs in the streamer's order of preference, without
/// duplicates (for the offer).
pub fn encoder_codecs(&self) -> Vec<Codec> {
@@ -403,16 +616,26 @@ impl Codecs {
&self,
codec: Codec,
config: EncoderConfig,
) -> Result<Box<dyn VideoEncoder>> {
self.new_encoder_preferring(codec, config, &self.preference)
}
/// As [`new_encoder`](Self::new_encoder) with another preference.
pub fn new_encoder_preferring(
&self,
codec: Codec,
config: EncoderConfig,
preference: &EncoderPreference,
) -> Result<Box<dyn VideoEncoder>> {
let mut last_error = None;
for (c, backend) in self.encoders() {
for (c, backend) in self.encoders_for(preference) {
if c != codec {
continue;
}
match self.new_encoder_with(codec, backend, config.clone()) {
Ok(encoder) => return Ok(encoder),
Err(e) => {
tracing::warn!(%codec, ?backend, "encoder backend failed: {e}");
tracing::warn!(%codec, %backend, "encoder backend failed: {e}");
last_error = Some(e);
}
}
@@ -428,12 +651,12 @@ impl Codecs {
config: EncoderConfig,
) -> Result<Box<dyn VideoEncoder>> {
match backend {
EncoderBackend::Hardware(name) => {
EncoderBackend::Hardware(_) | EncoderBackend::Ffmpeg(_) => {
let factory = self
.hardware
.factories
.iter()
.find(|f| f.name() == name)
.ok_or_else(|| unavailable(codec, format!("no hardware encoder {name}")))?;
.find(|f| f.backend() == backend)
.ok_or_else(|| unavailable(codec, format!("no encoder {backend} here")))?;
factory.create(codec, &config)
}
#[cfg(feature = "vpx")]
@@ -444,7 +667,7 @@ impl Codecs {
None => Err(unavailable(codec, "the OpenH264 library is not loaded")),
},
#[allow(unreachable_patterns)]
_ => Err(unavailable(codec, format!("{backend:?} cannot encode it in this build"))),
_ => Err(unavailable(codec, format!("{backend} cannot encode it in this build"))),
}
}
@@ -452,6 +675,81 @@ impl Codecs {
pub fn pick_encoder(&self, accepted: &[Codec]) -> Option<Codec> {
self.encoder_codecs().into_iter().find(|c| accepted.contains(c))
}
/// Every encoder backend this build knows, with what works here and why
/// the rest does not, and each one's rank under the current preference.
pub fn report(&self) -> EncoderReport {
let order = self.encoders();
let rank = |codec: Codec, backend: EncoderBackend| {
order.iter().filter(|(c, _)| *c == codec).position(|(_, b)| *b == backend)
};
let mut encoders = Vec::new();
let mut add = |backend: EncoderBackend, api: &str, codec, hardware, status| {
encoders.push(EncoderInfo {
name: backend.name().to_owned(),
api: api.to_owned(),
codec,
hardware,
rank: rank(codec, backend),
status,
});
};
for f in &self.factories {
if matches!(f.backend(), EncoderBackend::Hardware(_)) {
for codec in f.codecs() {
add(f.backend(), f.name(), codec, f.is_hardware(), Ok(()));
}
}
}
#[cfg(feature = "ffmpeg")]
for status in crate::ffmpeg::probe() {
let spec = status.spec;
let backend = EncoderBackend::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, true).map_err(|e| e.to_string());
#[cfg(not(feature = "vpx"))]
let status = Err("built without the `vpx` feature".to_owned());
add(EncoderBackend::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(EncoderBackend::OpenH264, "OpenH264 (Cisco)", Codec::H264, false, status);
#[cfg(feature = "ffmpeg")]
let (ffmpeg, zero_copy) = match crate::ffmpeg::Ffmpeg::get() {
Ok(ffmpeg) => {
let info = ffmpeg.info();
let text = format!(
"FFmpeg {} (libavcodec {}, libavutil {}) from {}",
info.release,
info.avcodec,
info.avutil,
info.path.display()
);
let vaapi = encoders.iter().any(|e| e.name.ends_with("_vaapi") && e.status.is_ok());
let zero_copy = match (&info.dmabuf_import, vaapi) {
(Err(e), _) => Err(e.clone()),
(Ok(()), false) => Err("no working VA-API encoder".to_owned()),
(Ok(()), true) => Ok(()),
};
(Ok(text), zero_copy)
}
Err(e) => (Err(e.to_owned()), Err("FFmpeg is not loaded".to_owned())),
};
#[cfg(not(feature = "ffmpeg"))]
let (ffmpeg, zero_copy) = (
Err("built without the `ffmpeg` feature".to_owned()),
Err("built without the `ffmpeg` feature".to_owned()),
);
EncoderReport { ffmpeg, zero_copy, encoders }
}
}
#[cfg(test)]
@@ -481,12 +779,13 @@ mod tests {
#[test]
fn preference_order() {
let codecs = Codecs::new();
let codecs = Codecs::builtin();
// Without OpenH264, H.264 is neither offered nor accepted.
assert!(!codecs.decoders().contains(&Codec::H264));
assert!(codecs.new_decoder(Codec::H264).is_err());
let err = codecs.new_encoder(Codec::H264, EncoderConfig::default()).err().unwrap();
assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}");
assert!(codecs.new_decoder(Codec::H265).is_err());
#[cfg(feature = "vpx")]
{
assert_eq!(codecs.decoders()[..2], [Codec::Vp9, Codec::Vp8]);
@@ -505,6 +804,71 @@ mod tests {
assert!(order.windows(2).all(|w| w[0] < w[1]));
}
struct Fake(&'static str, Codec, bool);
impl hw::EncoderFactory for Fake {
fn name(&self) -> &'static str {
self.0
}
fn codecs(&self) -> Vec<Codec> {
vec![self.1]
}
fn create(&self, codec: Codec, _: &EncoderConfig) -> Result<Box<dyn VideoEncoder>> {
Err(unavailable(codec, "fake"))
}
fn is_hardware(&self) -> bool {
self.2
}
fn backend(&self) -> EncoderBackend {
EncoderBackend::Ffmpeg(self.0)
}
}
#[test]
fn encoder_preference() {
let mut codecs = Codecs::builtin();
codecs.factories = vec![
Arc::new(Fake("x264", Codec::H264, false)),
Arc::new(Fake("vp8_gpu", Codec::Vp8, true)),
Arc::new(Fake("h264_gpu", Codec::H264, true)),
Arc::new(Fake("hevc_gpu", Codec::H265, true)),
Arc::new(Fake("av1_sw", Codec::Av1, false)),
];
let names = |preference: EncoderPreference| -> Vec<&'static str> {
codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect()
};
let auto = names(EncoderPreference::default());
// Hardware in codec order (HEVC last), then software.
assert_eq!(auto[..3], ["h264_gpu", "vp8_gpu", "hevc_gpu"]);
let position = |list: &[&str], name| list.iter().position(|n| *n == name).unwrap();
assert!(position(&auto, "x264") < position(&auto, "av1_sw"));
#[cfg(feature = "vpx")]
assert!(position(&auto, "libvpx") < position(&auto, "x264"), "VP8 before software H.264");
let no_hardware = names(EncoderPreference { hardware: false, ..Default::default() });
assert!(!no_hardware.iter().any(|n| n.ends_with("_gpu")));
let software =
names(EncoderPreference { hardware: true, backend: "software".parse().unwrap() });
assert_eq!(software, no_hardware);
// A named backend comes first, even hardware with acceleration off.
let named =
names(EncoderPreference { hardware: false, backend: "hevc_gpu".parse().unwrap() });
assert_eq!(named[0], "hevc_gpu");
assert!(!named[1..].iter().any(|n| n.ends_with("_gpu")));
// The codecs follow the preference.
codecs.set_preference(EncoderPreference::default());
assert_eq!(codecs.encoder_codecs()[..3], [Codec::H264, Codec::Vp8, Codec::H265]);
// The report ranks what the preference uses.
let report = codecs.report();
let openh264 = report.encoders.iter().find(|e| e.name == "openh264").unwrap();
assert!(openh264.status.is_err() && openh264.rank.is_none());
assert_eq!("auto".parse::<BackendChoice>().unwrap(), BackendChoice::Auto);
assert_eq!(BackendChoice::Named("h264_vaapi".into()).to_string(), "h264_vaapi");
}
#[test]
fn thread_heuristic() {
let config = EncoderConfig { threads: 3, ..EncoderConfig::default() };
File diff suppressed because it is too large. Load diff
+413
View File
@@ -0,0 +1,413 @@
//! The struct fields FFmpeg offers no function or AVOption for: where they
//! are in the loaded release, found and checked at runtime.
//!
//! Everything else goes through functions and AVOptions, whose meaning does
//! not depend on the release: the codec context is configured only with
//! `av_opt_set*` (`video_size`, `pixel_format`, `time_base`, `b`, `g`, `bf`,
//! ... and the encoders' private options), frames and packets are allocated
//! by FFmpeg, and only their leading fields are read (`sys::FrameHead`,
//! `sys::PacketHead`: unchanged since FFmpeg 0.9 and 2.1). The rest:
//!
//! | 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 |
//! | `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-60, 64-bit only) | `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 |
//!
//! A check that fails disables only what needs the field (VA-API, or the
//! DMA-BUF import), with the reason in the probe results; a new major whose
//! layout matches keeps working without a change here.
#![allow(unsafe_code)]
use std::ffi::c_int;
use std::mem::{offset_of, size_of};
use super::sys::{
Api, BufferRefHead, FrameHead, NOPTS_VALUE, PICTURE_TYPE_NONE, Ptr, Rational, cstr,
};
/// Offsets of `pict_type` and `pts` in `AVFrame`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameFields {
pub pict_type: usize,
pub pts: usize,
}
/// Up to libavutil 59.
#[repr(C)]
struct FrameWithKeyFrame {
head: FrameHead,
key_frame: c_int,
pict_type: c_int,
sample_aspect_ratio: Rational,
pts: i64,
}
/// libavutil 60 and later (`key_frame` removed).
#[repr(C)]
struct FrameWithoutKeyFrame {
head: FrameHead,
pict_type: c_int,
sample_aspect_ratio: Rational,
pts: i64,
}
/// # Safety
/// `base + offset` must lie inside a live object and be aligned for `T`.
pub unsafe fn read<T: Copy>(base: Ptr, offset: usize) -> T {
// SAFETY: guaranteed by the caller.
unsafe { base.cast::<u8>().add(offset).cast::<T>().read() }
}
/// # Safety
/// As [`read`], and the object must be ours to write.
pub unsafe fn write<T: Copy>(base: Ptr, offset: usize, value: T) {
// SAFETY: guaranteed by the caller.
unsafe { base.cast::<u8>().add(offset).cast::<T>().write(value) }
}
/// Find `pict_type` and `pts` in a frame fresh from `av_frame_alloc`.
pub fn frame_fields(api: &Api) -> Result<FrameFields, String> {
// SAFETY: allocates a frame (or returns NULL).
let mut frame = unsafe { (api.av_frame_alloc)() };
if frame.is_null() {
return Err("av_frame_alloc failed".into());
}
let matches = |pict_type: usize, sar: usize, pts: usize| {
// SAFETY: both layouts end with `pts` at 136 bytes (64-bit) or less,
// inside every AVFrame (416 bytes and more); the offsets come from
// `offset_of!` of `repr(C)` structs, so they are aligned.
unsafe {
read::<c_int>(frame, pict_type) == PICTURE_TYPE_NONE
&& read::<Rational>(frame, sar) == Rational { num: 0, den: 1 }
&& read::<i64>(frame, pts) == NOPTS_VALUE
}
};
let with = matches(
offset_of!(FrameWithKeyFrame, pict_type),
offset_of!(FrameWithKeyFrame, sample_aspect_ratio),
offset_of!(FrameWithKeyFrame, pts),
);
let without = matches(
offset_of!(FrameWithoutKeyFrame, pict_type),
offset_of!(FrameWithoutKeyFrame, sample_aspect_ratio),
offset_of!(FrameWithoutKeyFrame, pts),
);
// SAFETY: the frame came from av_frame_alloc.
unsafe { (api.av_frame_free)(&mut frame) };
match (with, without) {
(true, false) => Ok(FrameFields {
pict_type: offset_of!(FrameWithKeyFrame, pict_type),
pts: offset_of!(FrameWithKeyFrame, pts),
}),
(false, true) => Ok(FrameFields {
pict_type: offset_of!(FrameWithoutKeyFrame, pict_type),
pts: offset_of!(FrameWithoutKeyFrame, pts),
}),
_ => {
Err("unknown AVFrame layout (pict_type / pts not where any known release has them)"
.into())
}
}
}
/// The offset of an AVOption's field in `obj`, if the option exists.
fn option_offset(api: &Api, obj: Ptr, name: &str) -> Option<usize> {
let name = cstr(name);
// SAFETY: `obj` is an AVClass-enabled object; the name is a C string.
let option = unsafe { (api.av_opt_find)(obj, name.as_ptr(), std::ptr::null(), 0, 0) };
if option.is_null() {
return None;
}
// SAFETY: av_opt_find returns a pointer into a static option table.
usize::try_from(unsafe { (*option).offset }).ok()
}
/// libavcodec 61 and later: `err_recognition`, `hwaccel`, `hwaccel_context`,
/// `hw_frames_ctx`, `hw_device_ctx`, `hwaccel_flags`, `extra_hw_frames`.
#[repr(C)]
struct HwFieldsNew {
err_recognition: c_int,
hwaccel: Ptr,
hwaccel_context: Ptr,
hw_frames_ctx: Ptr,
hw_device_ctx: Ptr,
hwaccel_flags: c_int,
extra_hw_frames: c_int,
}
/// libavcodec 60: `hw_frames_ctx`, `trailing_padding`, `max_pixels`,
/// `hw_device_ctx`, `hwaccel_flags`.
#[repr(C)]
struct HwFields60 {
hw_frames_ctx: Ptr,
trailing_padding: c_int,
max_pixels: i64,
hw_device_ctx: Ptr,
hwaccel_flags: c_int,
}
/// libavcodec 58 and 59: as 60 with `sub_text_format` after
/// `hw_frames_ctx`.
#[repr(C)]
struct HwFields59 {
hw_frames_ctx: Ptr,
sub_text_format: c_int,
trailing_padding: c_int,
max_pixels: i64,
hw_device_ctx: Ptr,
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> {
// 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);
// SAFETY: allocated above.
unsafe { (api.avcodec_free_context)(&mut ctx) };
result
}
fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result<usize, String> {
let offset = |name| option_offset(api, ctx, name);
let flags = offset("hwaccel_flags").ok_or("no hwaccel_flags option")?;
let found = '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);
}
// 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 {
(
offset_of!(HwFields59, max_pixels),
offset_of!(HwFields59, hwaccel_flags),
offset_of!(HwFields59, hw_frames_ctx),
)
} else {
(
offset_of!(HwFields60, max_pixels),
offset_of!(HwFields60, hwaccel_flags),
offset_of!(HwFields60, hw_frames_ctx),
)
};
if let Some(base) = max_pixels.checked_sub(max_off)
&& base + flags_off == flags
{
break 'found base + frames_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() {
return Err("AVCodecContext.hw_frames_ctx check failed (not NULL in a new context)".into());
}
Ok(found)
}
/// Offsets in `AVHWFramesContext`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct HwFramesFields {
pub initial_pool_size: usize,
pub format: usize,
pub sw_format: usize,
pub width: usize,
pub height: usize,
}
/// Up to libavutil 58.
#[repr(C)]
struct HwFramesWithInternal {
av_class: Ptr,
internal: Ptr,
device_ref: Ptr,
device_ctx: Ptr,
hwctx: Ptr,
free: Ptr,
user_opaque: Ptr,
pool: Ptr,
initial_pool_size: c_int,
format: c_int,
sw_format: c_int,
width: c_int,
height: c_int,
}
/// libavutil 59 and later.
#[repr(C)]
struct HwFramesPublic {
av_class: Ptr,
device_ref: Ptr,
device_ctx: Ptr,
hwctx: Ptr,
free: Ptr,
user_opaque: Ptr,
pool: Ptr,
initial_pool_size: c_int,
format: c_int,
sw_format: c_int,
width: c_int,
height: c_int,
}
macro_rules! hw_frames_fields {
($ty:ty) => {
HwFramesFields {
initial_pool_size: offset_of!($ty, initial_pool_size),
format: offset_of!($ty, format),
sw_format: offset_of!($ty, sw_format),
width: offset_of!($ty, width),
height: offset_of!($ty, height),
}
};
}
/// The fields of the frames context `frames` (fresh from
/// `av_hwframe_ctx_alloc(device)`; both are `AVBufferRef`s).
///
/// # Safety
/// `frames` and `device` must be live buffer references of an
/// `AVHWFramesContext` just allocated on the `AVHWDeviceContext` `device`.
pub unsafe fn hw_frames_fields(frames: Ptr, device: Ptr) -> Result<HwFramesFields, String> {
// SAFETY: guaranteed by the caller; `data` is the leading field pair.
let (ctx, device_ctx) = unsafe {
(
(*frames.cast::<BufferRefHead>()).data.cast::<std::ffi::c_void>(),
(*device.cast::<BufferRefHead>()).data.cast::<std::ffi::c_void>(),
)
};
let check = |fields: HwFramesFields, device_at: usize| {
// SAFETY: both layouts lie within the smaller one (the current
// public struct); offsets from `offset_of!` are aligned.
unsafe {
read::<Ptr>(ctx, device_at) == device_ctx
&& read::<c_int>(ctx, fields.format) == -1
&& read::<c_int>(ctx, fields.sw_format) == -1
}
};
let old = hw_frames_fields!(HwFramesWithInternal);
let new = hw_frames_fields!(HwFramesPublic);
match (
check(old, offset_of!(HwFramesWithInternal, device_ctx)),
check(new, offset_of!(HwFramesPublic, device_ctx)),
) {
(true, false) => Ok(old),
(false, true) => Ok(new),
_ => Err("unknown AVHWFramesContext layout".into()),
}
}
/// Offsets of `buf[0]` and `hw_frames_ctx` in `AVFrame`, for importing
/// DMA-BUFs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameRefs {
pub buf: usize,
pub hw_frames_ctx: usize,
}
/// The table of [`FrameRefs`] per libavutil major (64-bit targets). A newer
/// major is tried with the newest entry and must pass the checks.
fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
if size_of::<Ptr>() != 8 {
return None;
}
let (buf, hw_frames_ctx) = match avutil_major {
56 => (288, 480),
57 | 58 => (224, 392),
59 => (200, 352),
60.. => (184, 328),
_ => return None,
};
Some(FrameRefs { buf, hw_frames_ctx })
}
/// [`FrameRefs`] of this release, with `buf[0]` checked on a real frame
/// (`hw_frames_ctx` is checked once a hardware frame exists, see
/// [`check_hw_frames_ctx`]).
pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result<FrameRefs, String> {
// SAFETY: no arguments.
let major = unsafe { (api.avutil_version)() } >> 16;
let refs = frame_refs_table(major)
.ok_or_else(|| format!("AVFrame references not known for libavutil {major} here"))?;
// SAFETY: a frame of 16x16 yuv420p pixels; the head fields are set
// before av_frame_get_buffer as its documentation asks; the offsets are
// inside AVFrame for this major (the table), pointer-aligned.
unsafe {
let mut frame = (api.av_frame_alloc)();
if frame.is_null() {
return Err("av_frame_alloc failed".into());
}
let head = frame.cast::<FrameHead>();
(*head).width = 16;
(*head).height = 16;
(*head).format = yuv420p;
let ok = (api.av_frame_get_buffer)(frame, 0) >= 0 && {
let buf: Ptr = read(frame, refs.buf);
let hw: Ptr = read(frame, refs.hw_frames_ctx);
!buf.is_null() && (*buf.cast::<BufferRefHead>()).data == (*head).data[0] && hw.is_null()
};
(api.av_frame_free)(&mut frame);
if ok { Ok(refs) } else { Err(format!("AVFrame.buf check failed (libavutil {major})")) }
}
}
/// Whether `frame` (from `av_hwframe_get_buffer(pool, ...)`) references
/// `pool` at `refs.hw_frames_ctx`.
///
/// # Safety
/// `frame` must be a live AVFrame of this release, `pool` a live buffer
/// reference.
pub unsafe fn check_hw_frames_ctx(frame: Ptr, pool: Ptr, refs: FrameRefs) -> bool {
// SAFETY: guaranteed by the caller; the offset is inside AVFrame.
unsafe {
let hw: Ptr = read(frame, refs.hw_frames_ctx);
!hw.is_null() && (*hw.cast::<BufferRefHead>()).data == (*pool.cast::<BufferRefHead>()).data
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The mirrors give the offsets compiled from FFmpeg's headers
/// (x86-64): 4.4-7.1 `pict_type` 124 / `pts` 136, 8.0 120 / 136;
/// `hw_frames_ctx` 16 bytes before `max_pixels` (4.4-6.1) and 16 before
/// `hwaccel_flags` (7.1, 8.0).
#[cfg(target_pointer_width = "64")]
#[test]
fn mirrors_match_the_headers() {
assert_eq!(offset_of!(FrameWithKeyFrame, pict_type), 124);
assert_eq!(offset_of!(FrameWithKeyFrame, pts), 136);
assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120);
assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136);
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);
// 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);
assert_eq!(offset_of!(HwFramesWithInternal, format), 68);
assert_eq!(offset_of!(HwFramesPublic, format), 60);
assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 }));
assert_eq!(frame_refs_table(55), None);
}
}
+261
View File
@@ -0,0 +1,261 @@
//! 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).
//!
//! FFmpeg is never linked or shipped: [`Ffmpeg::get`] finds the system's
//! (or `VOELIN_FFMPEG_DIR`'s) libavcodec and libavutil, whatever their major
//! version, and looks up the functions it needs by name ([`sys`]). Without
//! them the software encoders of this crate are used as before. Struct
//! layouts that differ between releases are avoided (AVOptions for every
//! codec setting) or located and checked at runtime ([`layout`]).
//!
//! [`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.
#![allow(unsafe_code)]
use std::ffi::{CStr, c_char, c_int};
use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
pub mod encoder;
mod layout;
pub mod sys;
pub use encoder::{
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
};
pub use sys::Search;
use self::layout::{FrameFields, FrameRefs};
use self::sys::{Api, Libs, LogCallback, Ptr, VaList};
/// Pixel format numbers of this release (looked up by name).
#[derive(Clone, Copy, Debug)]
pub(crate) struct PixFmts {
pub yuv420p: c_int,
pub nv12: c_int,
pub vaapi: Option<c_int>,
pub drm_prime: Option<c_int>,
}
/// What was loaded, for logs and the UI.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LibraryInfo {
/// libavcodec's file.
pub path: PathBuf,
/// FFmpeg's release (`av_version_info`, e.g. `6.1.1-3ubuntu5`).
pub release: String,
/// `major.minor.micro` of libavcodec and libavutil.
pub avcodec: String,
pub avutil: String,
/// libavformat of the same release was found (for RTMP output later).
pub avformat: bool,
/// Why hardware frame pools (VA-API) cannot be used, if not.
pub hw_frames: Result<(), String>,
/// Why DMA-BUF frames cannot be imported (zero-copy), if not.
pub dmabuf_import: Result<(), String>,
}
/// Loaded FFmpeg libraries.
pub struct Ffmpeg {
pub(crate) api: Api,
_libs: Libs,
pub(crate) frame: FrameFields,
/// `AVCodecContext.hw_frames_ctx`.
pub(crate) codec_hw_frames: Result<usize, String>,
/// `AVFrame.buf[0]` / `hw_frames_ctx`.
pub(crate) frame_refs: Result<FrameRefs, String>,
pub(crate) pix: PixFmts,
info: LibraryInfo,
}
// SAFETY: `Api` holds plain function pointers and `Libs` library handles;
// FFmpeg's functions used here are thread-safe for distinct objects.
unsafe impl Send for Ffmpeg {}
unsafe impl Sync for Ffmpeg {}
impl std::fmt::Debug for Ffmpeg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Ffmpeg").field("info", &self.info).finish_non_exhaustive()
}
}
fn version_text(v: u32) -> String {
format!("{}.{}.{}", v >> 16, (v >> 8) & 0xff, v & 0xff)
}
impl Ffmpeg {
/// Load FFmpeg from `search`. Prefer [`Ffmpeg::get`], which loads once
/// per process.
pub fn load(search: &Search) -> Result<Self, String> {
let (libs, api) = sys::load(search)?;
let frame = layout::frame_fields(&api)?;
let yuv420p = api.pix_fmt("yuv420p").ok_or("no yuv420p pixel format")?;
let nv12 = api.pix_fmt("nv12").ok_or("no nv12 pixel format")?;
let pix = PixFmts {
yuv420p,
nv12,
vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")),
drm_prime: api.pix_fmt("drm_prime"),
};
let codec_hw_frames = layout::codec_hw_frames(&api);
let frame_refs = layout::frame_refs(&api, yuv420p);
// SAFETY: no arguments; returns version numbers and a static string.
let (avcodec, avutil, release) = unsafe {
(
(api.avcodec_version)(),
(api.avutil_version)(),
CStr::from_ptr((api.av_version_info)()).to_string_lossy().into_owned(),
)
};
let info = LibraryInfo {
path: libs.path.clone(),
release,
avcodec: version_text(avcodec),
avutil: version_text(avutil),
avformat: libs.avformat.is_some(),
hw_frames: codec_hw_frames.clone().map(|_| ()),
dmabuf_import: match (&codec_hw_frames, &frame_refs, pix.drm_prime) {
(Err(e), _, _) | (_, Err(e), _) => Err(e.clone()),
(_, _, None) => Err("no DRM PRIME pixel format".into()),
_ => Ok(()),
},
};
Ok(Self { api, _libs: libs, frame, codec_hw_frames, frame_refs, pix, info })
}
/// The process's FFmpeg, loaded on first use from [`Search::from_env`]
/// (`VOELIN_FFMPEG_DIR`), or why there is none. `VOELIN_FFMPEG=0`
/// disables it.
pub fn get() -> Result<&'static Ffmpeg, &'static str> {
static FFMPEG: OnceLock<Result<Ffmpeg, String>> = OnceLock::new();
FFMPEG
.get_or_init(|| {
if std::env::var("VOELIN_FFMPEG").is_ok_and(|v| matches!(v.as_str(), "0" | "off")) {
return Err("disabled by VOELIN_FFMPEG".into());
}
let loaded = Self::load(&Search::from_env());
match &loaded {
Ok(ffmpeg) => {
ffmpeg.capture_log();
tracing::info!(
path = %ffmpeg.info.path.display(),
release = ffmpeg.info.release,
avcodec = ffmpeg.info.avcodec,
"FFmpeg loaded"
);
}
Err(e) => tracing::info!("FFmpeg not used: {e}"),
}
loaded
})
.as_ref()
.map_err(String::as_str)
}
pub fn info(&self) -> &LibraryInfo {
&self.info
}
/// Route FFmpeg's warnings and errors to `tracing` (and to
/// [`take_log`] for error reports) instead of stderr.
fn capture_log(&self) {
let _ = LOG_FORMAT.set(self.api.av_log_format_line2);
// SAFETY: sets a global level and a callback that stays valid (a
// plain function).
unsafe {
(self.api.av_log_set_level)(sys::LOG_WARNING);
(self.api.av_log_set_callback)(Some(log_callback as LogCallback));
}
}
}
type FormatLine = unsafe extern "C" fn(
Ptr,
c_int,
*const c_char,
VaList,
*mut c_char,
c_int,
*mut c_int,
) -> c_int;
static LOG_FORMAT: OnceLock<FormatLine> = OnceLock::new();
/// The last FFmpeg messages (warnings and errors), for error reports.
static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// Take the FFmpeg messages logged since the last call (at most 16) that
/// are about `context` (an encoder name such as `h264_vaapi`: FFmpeg
/// prefixes its messages with `[h264_vaapi @ 0x...]`) or about nothing in
/// particular. Messages of other encoders (tested in parallel) stay.
pub fn take_log(context: &str) -> Vec<String> {
let mut log = LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let tag = format!("[{context} @");
let (mine, others): (Vec<String>, Vec<String>) =
log.drain(..).partition(|line| line.contains(&tag) || !line.contains(" @ 0x"));
*log = others;
mine
}
unsafe extern "C" fn log_callback(avcl: Ptr, level: c_int, fmt: *const c_char, vl: VaList) {
if level > sys::LOG_WARNING {
return;
}
let Some(format) = LOG_FORMAT.get() else { return };
let mut line = [0 as c_char; 512];
let mut prefix: c_int = 1;
// SAFETY: FFmpeg passes its own arguments through; the buffer and its
// size are valid, and the result is NUL-terminated.
let text = unsafe {
format(avcl, level, fmt, vl, line.as_mut_ptr(), line.len() as c_int, &mut prefix);
CStr::from_ptr(line.as_ptr())
};
let text = text.to_string_lossy().trim_end().to_owned();
if text.is_empty() {
return;
}
if level <= sys::LOG_ERROR {
tracing::debug!(target: "ffmpeg", "{text}");
} else {
tracing::trace!(target: "ffmpeg", "{text}");
}
if let Ok(mut log) = LOG.lock() {
if log.len() >= 16 {
log.remove(0);
}
log.push(text);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// With FFmpeg installed (the CI image and this machine have it), every
/// runtime check of the layout passes.
#[test]
fn loads_when_installed() {
let Ok(ffmpeg) = Ffmpeg::get() else {
eprintln!("FFmpeg not installed, skipped");
return;
};
let info = ffmpeg.info();
assert!(!info.release.is_empty());
assert!(info.avcodec.split('.').count() == 3);
assert!(info.hw_frames.is_ok(), "{info:?}");
if cfg!(target_pointer_width = "64") {
assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs);
}
}
#[test]
fn no_ffmpeg_in_an_empty_directory() {
let dir = std::env::temp_dir().join(format!("voelin-no-ffmpeg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let err = Ffmpeg::load(&Search { dirs: vec![dir.clone()], system: false }).unwrap_err();
std::fs::remove_dir_all(&dir).unwrap();
assert!(err.contains("no FFmpeg libraries"), "{err}");
}
}
+572
View File
@@ -0,0 +1,572 @@
//! The FFmpeg libraries, found and opened at runtime (`libloading`), and the
//! few functions and struct fields this crate uses.
//!
//! Nothing is linked: every function is looked up by name once, and a
//! library that lacks one is not used. Struct fields are read or written only
//! where FFmpeg offers no function or AVOption for them; see [`super::layout`]
//! for which ones and why that is safe across major versions.
#![allow(unsafe_code)]
use std::ffi::{CStr, CString, c_char, c_int, c_uint, c_void};
use std::path::{Path, PathBuf};
use libloading::Library;
/// An FFmpeg object behind an opaque pointer (`AVCodecContext *`, ...).
pub type Ptr = *mut c_void;
/// `va_list` as FFmpeg's log callback receives it and `av_log_format_line2`
/// takes it. On every ABI this crate builds for it is passed as one pointer:
/// a `char *` (Windows, Apple, 32-bit x86), an array that decays to a pointer
/// (x86-64 System V), or a struct larger than 16 bytes passed by reference
/// (AArch64 AAPCS), or a one-word struct in a register (32-bit ARM). It is
/// only ever handed back to FFmpeg, never read.
pub type VaList = *mut c_void;
/// `AVRational`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rational {
pub num: c_int,
pub den: c_int,
}
/// The leading fields of `AVPacket`, unchanged since libavcodec 55 (FFmpeg
/// 2.1): `buf`, `pts`, `dts`, `data`, `size`, `stream_index`, `flags`.
/// Packets are always allocated by `av_packet_alloc`, so the struct is at
/// least this large.
#[repr(C)]
pub struct PacketHead {
pub buf: Ptr,
pub pts: i64,
pub dts: i64,
pub data: *mut u8,
pub size: c_int,
pub stream_index: c_int,
pub flags: c_int,
}
/// `AV_PKT_FLAG_KEY`.
pub const PKT_FLAG_KEY: c_int = 1;
/// The number of data pointers of an `AVFrame` (`AV_NUM_DATA_POINTERS`,
/// 8 since libavutil 51).
pub const NUM_DATA_POINTERS: usize = 8;
/// The leading fields of `AVFrame`, unchanged since libavutil 51 (FFmpeg
/// 0.9): `data[8]`, `linesize[8]`, `extended_data`, `width`, `height`,
/// `nb_samples`, `format`. Frames are always allocated by `av_frame_alloc`.
#[repr(C)]
pub struct FrameHead {
pub data: [*mut u8; NUM_DATA_POINTERS],
pub linesize: [c_int; NUM_DATA_POINTERS],
pub extended_data: *mut *mut u8,
pub width: c_int,
pub height: c_int,
pub nb_samples: c_int,
pub format: c_int,
}
/// The leading fields of `AVOption` (`name`, `help`, `offset`, `type`),
/// unchanged since FFmpeg 0.5. Only `offset` is read, to locate fields of
/// `AVCodecContext` that have no option of their own (see
/// [`super::layout`]).
#[repr(C)]
pub struct OptionHead {
pub name: *const c_char,
pub help: *const c_char,
pub offset: c_int,
pub kind: c_int,
}
/// The leading fields of `AVBufferRef` (`buffer`, `data`); `size` changed
/// from `int` to `size_t` in libavutil 57 and is not read.
#[repr(C)]
pub struct BufferRefHead {
pub buffer: Ptr,
pub data: *mut u8,
}
/// `AVDRMObjectDescriptor` (`libavutil/hwcontext_drm.h`, unchanged since it
/// was added in libavutil 55).
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DrmObject {
pub fd: c_int,
pub size: usize,
pub format_modifier: u64,
}
/// `AVDRMPlaneDescriptor`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DrmPlane {
pub object_index: c_int,
pub offset: isize,
pub pitch: isize,
}
/// `AV_DRM_MAX_PLANES`.
pub const DRM_MAX_PLANES: usize = 4;
/// `AVDRMLayerDescriptor`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DrmLayer {
pub format: u32,
pub nb_planes: c_int,
pub planes: [DrmPlane; DRM_MAX_PLANES],
}
/// `AVDRMFrameDescriptor`: what `data[0]` of an `AV_PIX_FMT_DRM_PRIME` frame
/// points to.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DrmFrameDescriptor {
pub nb_objects: c_int,
pub objects: [DrmObject; DRM_MAX_PLANES],
pub nb_layers: c_int,
pub layers: [DrmLayer; DRM_MAX_PLANES],
}
/// `AV_PICTURE_TYPE_NONE` and `AV_PICTURE_TYPE_I`.
pub const PICTURE_TYPE_NONE: c_int = 0;
pub const PICTURE_TYPE_I: c_int = 1;
/// `AV_NOPTS_VALUE`.
pub const NOPTS_VALUE: i64 = i64::MIN;
/// `AV_LOG_*` levels.
pub const LOG_QUIET: c_int = -8;
pub const LOG_ERROR: c_int = 16;
pub const LOG_WARNING: c_int = 24;
/// `AV_HWFRAME_MAP_READ` and `AV_HWFRAME_MAP_DIRECT`.
pub const HWFRAME_MAP_READ: c_int = 1;
pub const HWFRAME_MAP_DIRECT: c_int = 8;
/// `AVERROR(EAGAIN)`: FFmpeg errors are negated `errno` values of the C
/// library it was built against.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd"))]
pub const EAGAIN: c_int = -35;
#[cfg(not(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd"
)))]
pub const EAGAIN: c_int = -11;
/// `FFERRTAG(a, b, c, d)`.
const fn err_tag(a: u8, b: u8, c: u8, d: u8) -> c_int {
-((a as c_int) | (b as c_int) << 8 | (c as c_int) << 16 | (d as c_int) << 24)
}
/// `AVERROR_EOF`.
pub const EOF: c_int = err_tag(b'E', b'O', b'F', b' ');
/// `AVERROR_OPTION_NOT_FOUND`.
pub const OPTION_NOT_FOUND: c_int = err_tag(0xF8, b'O', b'P', b'T');
/// Declares the function table: every function, its library, its C
/// signature. `resolve` looks all of them up; a missing one fails the load.
macro_rules! api {
($($lib:ident { $(fn $name:ident($($arg:ident: $ty:ty),*) $(-> $ret:ty)?;)* })*) => {
/// FFmpeg functions used by this crate.
#[allow(non_snake_case, dead_code)]
pub struct Api {
$($(pub $name: unsafe extern "C" fn($($ty),*) $(-> $ret)?,)*)*
}
impl Api {
/// # Safety
/// The libraries must be FFmpeg's, so the symbols have the
/// declared signatures.
unsafe fn resolve(libs: &Libs) -> Result<Self, String> {
Ok(Self {
$($($name: unsafe { libs.symbol(Lib::$lib, stringify!($name))? },)*)*
})
}
}
};
}
api! {
Util {
fn avutil_version() -> c_uint;
fn av_version_info() -> *const c_char;
fn av_frame_alloc() -> Ptr;
fn av_frame_free(frame: *mut Ptr);
fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int;
fn av_frame_make_writable(frame: Ptr) -> c_int;
fn av_frame_unref(frame: Ptr);
fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int;
fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int;
fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int;
fn av_opt_set_image_size(obj: Ptr, name: *const c_char, w: c_int, h: c_int, flags: c_int) -> c_int;
fn av_opt_set_pixel_fmt(obj: Ptr, name: *const c_char, fmt: c_int, flags: c_int) -> c_int;
fn av_opt_find(
obj: Ptr,
name: *const c_char,
unit: *const c_char,
opt_flags: c_int,
search_flags: c_int
) -> *const OptionHead;
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_log_set_level(level: c_int);
fn av_log_set_callback(callback: Option<LogCallback>);
fn av_log_format_line2(
avcl: Ptr,
level: c_int,
fmt: *const c_char,
vl: VaList,
line: *mut c_char,
size: c_int,
print_prefix: *mut c_int
) -> c_int;
fn av_buffer_ref(buf: Ptr) -> Ptr;
fn av_buffer_unref(buf: *mut Ptr);
// `size` is an `int` up to libavutil 56: passed in the same register.
fn av_buffer_allocz(size: usize) -> Ptr;
fn av_hwdevice_find_type_by_name(name: *const c_char) -> c_int;
fn av_hwdevice_ctx_create(
device: *mut Ptr,
kind: c_int,
name: *const c_char,
opts: Ptr,
flags: c_int
) -> c_int;
fn av_hwframe_ctx_alloc(device: Ptr) -> Ptr;
fn av_hwframe_ctx_init(frames: Ptr) -> c_int;
fn av_hwframe_get_buffer(frames: Ptr, frame: Ptr, flags: c_int) -> c_int;
fn av_hwframe_transfer_data(dst: Ptr, src: Ptr, flags: c_int) -> c_int;
fn av_hwframe_map(dst: Ptr, src: Ptr, flags: c_int) -> c_int;
}
Codec {
fn avcodec_version() -> c_uint;
fn avcodec_find_encoder_by_name(name: *const c_char) -> Ptr;
fn avcodec_alloc_context3(codec: Ptr) -> Ptr;
fn avcodec_free_context(ctx: *mut Ptr);
fn avcodec_open2(ctx: Ptr, codec: Ptr, options: *mut Ptr) -> c_int;
fn avcodec_send_frame(ctx: Ptr, frame: Ptr) -> c_int;
fn avcodec_receive_packet(ctx: Ptr, packet: Ptr) -> c_int;
fn av_packet_alloc() -> Ptr;
fn av_packet_free(packet: *mut Ptr);
fn av_packet_unref(packet: Ptr);
}
}
/// `void (*)(void *avcl, int level, const char *fmt, va_list vl)`.
pub type LogCallback = unsafe extern "C" fn(Ptr, c_int, *const c_char, VaList);
#[derive(Clone, Copy)]
enum Lib {
Util,
Codec,
}
/// The opened libraries. Never closed: FFmpeg keeps global state (codec
/// registrations, the log callback) that must outlive every object.
pub struct Libs {
avcodec: Library,
/// libavutil where symbols are not found through libavcodec's handle
/// (Windows: `GetProcAddress` does not search dependencies).
avutil: Option<Library>,
/// libavformat, if present (for later use: RTMP output).
pub avformat: Option<Library>,
/// Where libavcodec was found.
pub path: PathBuf,
}
impl Libs {
/// # Safety
/// `T` must be the symbol's actual type.
unsafe fn symbol<T: Copy>(&self, lib: Lib, name: &str) -> Result<T, String> {
let library = match lib {
Lib::Util => self.avutil.as_ref().unwrap_or(&self.avcodec),
Lib::Codec => &self.avcodec,
};
// SAFETY: the caller guarantees the type; the library stays loaded
// for the life of the process (it is never dropped, see `Libs`).
unsafe { library.get::<T>(name.as_bytes()) }
.map(|s| *s)
.map_err(|e| format!("{} lacks {name}: {e}", self.path.display()))
}
}
/// Where to look for FFmpeg.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Search {
/// Directories searched first (full paths, newest major first).
pub dirs: Vec<PathBuf>,
/// Also the system's library search path (and `ldconfig -p` on Linux,
/// Homebrew and MacPorts on macOS, the executable's directory and `PATH`
/// on Windows).
pub system: bool,
}
impl Search {
/// `VOELIN_FFMPEG_DIR` (only that directory) if set, else the system.
pub fn from_env() -> Self {
match std::env::var_os("VOELIN_FFMPEG_DIR") {
Some(dir) if !dir.is_empty() => Self { dirs: vec![dir.into()], system: false },
_ => Self { dirs: Vec::new(), system: true },
}
}
}
/// The major version in a library file name: `libavcodec.so.61` → 61,
/// `avcodec-61.dll` → 61, `libavcodec.61.dylib` → 61.
pub fn major_of(name: &str) -> Option<u32> {
let name = name.rsplit(['/', '\\']).next()?;
let rest = name.strip_prefix("lib").unwrap_or(name);
let rest = rest.split_once(['.', '-'])?.1;
rest.split(['.', '-']).find_map(|part| part.parse().ok())
}
/// Library names (not paths) of `base` to try with the system search, newest
/// first. The range of majors reaches well past today's (62) so newer
/// releases are found without a change here; `ldconfig -p` covers the rest.
fn system_names(base: &str) -> Vec<String> {
const MAJORS: std::ops::RangeInclusive<u32> = 54..=80;
let mut names = Vec::new();
if cfg!(windows) {
names.extend(MAJORS.rev().map(|n| format!("{base}-{n}.dll")));
names.push(format!("{base}.dll"));
} else if cfg!(target_vendor = "apple") {
names.extend(MAJORS.rev().map(|n| format!("lib{base}.{n}.dylib")));
names.push(format!("lib{base}.dylib"));
} else {
names.extend(MAJORS.rev().map(|n| format!("lib{base}.so.{n}")));
names.push(format!("lib{base}.so"));
}
names
}
/// Full paths of `base` in `dir`, newest major first.
fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut found: Vec<(u32, PathBuf)> = entries
.flatten()
.filter_map(|e| {
let name = e.file_name().to_string_lossy().into_owned();
let matches = (name.starts_with(&format!("lib{base}.")) && name.contains(".so"))
|| (name.starts_with(&format!("lib{base}.")) && name.ends_with(".dylib"))
|| (name.starts_with(&format!("{base}-")) && name.ends_with(".dll"))
|| name == format!("{base}.dll");
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.into_iter().map(|(_, p)| p).collect()
}
/// `ldconfig -p` entries of `base` (Linux), newest major first.
#[cfg(target_os = "linux")]
fn ldconfig(base: &str) -> Vec<PathBuf> {
let Ok(output) = std::process::Command::new("ldconfig").arg("-p").output() else {
return Vec::new();
};
let text = String::from_utf8_lossy(&output.stdout);
let prefix = format!("lib{base}.so");
let mut found: Vec<(u32, PathBuf)> = text
.lines()
.filter_map(|line| {
let (name, path) = line.trim().split_once(" => ")?;
let name = name.split_whitespace().next()?;
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.into_iter().map(|(_, p)| p).collect()
}
/// Candidates for `base` (`avcodec`, `avformat`) in search order.
fn candidates(search: &Search, base: &str) -> Vec<PathBuf> {
let mut list: Vec<PathBuf> = Vec::new();
for dir in &search.dirs {
list.extend(files_in(dir, base));
}
if search.system {
if cfg!(target_vendor = "apple") {
for dir in ["/opt/homebrew/lib", "/usr/local/lib", "/opt/local/lib"] {
list.extend(files_in(Path::new(dir), base));
}
}
if cfg!(windows)
&& let Some(dir) =
std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_owned))
{
list.extend(files_in(&dir, base));
}
list.extend(system_names(base).into_iter().map(PathBuf::from));
#[cfg(target_os = "linux")]
list.extend(ldconfig(base));
}
let mut seen = std::collections::HashSet::new();
list.retain(|p| seen.insert(p.clone()));
list
}
/// Open one library file or name.
fn open(path: &Path) -> Result<Library, libloading::Error> {
#[cfg(windows)]
if path.is_absolute() {
use libloading::os::windows::{LOAD_WITH_ALTERED_SEARCH_PATH, Library as WinLibrary};
// SAFETY: loading runs the library's initialisers; FFmpeg's have no
// preconditions.
return unsafe { WinLibrary::load_with_flags(path, LOAD_WITH_ALTERED_SEARCH_PATH) }
.map(Library::from);
}
// SAFETY: as above.
unsafe { Library::new(path.as_os_str()) }
}
/// Load libavutil files of `dir` first, so libavcodec's dependencies resolve
/// to them when `dir` is not on the system search path (each file only
/// satisfies its own soname).
fn preload_dependencies(dir: &Path, keep: &mut Vec<Library>) {
for base in ["avutil", "swresample"] {
for path in files_in(dir, base) {
if let Ok(lib) = open(&path) {
keep.push(lib);
}
}
}
}
/// On Windows, the libavutil DLL libavcodec loaded (already in the process).
#[cfg(windows)]
fn loaded_avutil(avcodec: &Path) -> Option<Library> {
use libloading::os::windows::Library as WinLibrary;
let mut names: Vec<PathBuf> = system_names("avutil").into_iter().map(PathBuf::from).collect();
if let Some(dir) = avcodec.parent() {
names.splice(0..0, files_in(dir, "avutil"));
}
names.into_iter().find_map(|name| {
let file = name.file_name()?.to_owned();
WinLibrary::open_already_loaded(file).ok().map(Library::from)
})
}
/// Find and open libavcodec (with the libavutil it depends on) and, if
/// present, libavformat, then look up every function.
pub fn load(search: &Search) -> Result<(Libs, Api), String> {
let mut errors = Vec::new();
let mut preloaded = Vec::new();
for dir in &search.dirs {
preload_dependencies(dir, &mut preloaded);
}
for path in candidates(search, "avcodec") {
let avcodec = match open(&path) {
Ok(lib) => lib,
Err(e) => {
if path.is_absolute() {
errors.push(format!("{}: {e}", path.display()));
}
continue;
}
};
#[cfg(windows)]
let avutil = loaded_avutil(&path);
#[cfg(not(windows))]
// dlsym on libavcodec's handle also searches its dependencies, so
// libavutil's functions come from the very library it was built with.
let avutil = None;
let mut libs = Libs { avcodec, avutil, avformat: None, path: path.clone() };
// SAFETY: the library is libavcodec (found by its file name), whose
// exported functions have the signatures declared in `api!`.
match unsafe { Api::resolve(&libs) } {
Ok(api) => {
// libavformat of the same release: libavformat and libavcodec
// share their major version.
// SAFETY: no arguments; returns a version number.
let major = unsafe { (api.avcodec_version)() } >> 16;
libs.avformat = candidates(search, "avformat")
.into_iter()
.filter(|p| major_of(&p.to_string_lossy()) == Some(major))
.find_map(|p| open(&p).ok());
// Keep the preloaded dependencies loaded for good.
std::mem::forget(preloaded);
return Ok((libs, api));
}
Err(e) => errors.push(e),
}
}
if errors.is_empty() {
let place = if search.system {
"on the system library path".to_owned()
} else {
search.dirs.iter().map(|d| d.display().to_string()).collect::<Vec<_>>().join(", ")
};
Err(format!("no FFmpeg libraries (libavcodec) found {place}"))
} else {
Err(errors.join("; "))
}
}
/// A C string for an FFmpeg call (names and option values never contain
/// NUL; one that does is passed as empty).
pub fn cstr(s: &str) -> CString {
CString::new(s).unwrap_or_default()
}
impl Api {
/// FFmpeg's text for an error code.
pub fn error_text(&self, code: c_int) -> String {
let mut buf = [0 as c_char; 256];
// SAFETY: the buffer and its size are valid; av_strerror always
// NUL-terminates within it.
unsafe { (self.av_strerror)(code, buf.as_mut_ptr(), buf.len()) };
// SAFETY: NUL-terminated above.
let text = unsafe { CStr::from_ptr(buf.as_ptr()) }.to_string_lossy();
format!("{text} ({code})")
}
/// `av_get_pix_fmt(name)`: pixel format numbers moved between majors, so
/// they are always looked up by name. `None` if unknown.
pub fn pix_fmt(&self, name: &str) -> Option<c_int> {
let name = cstr(name);
// SAFETY: a valid C string.
let fmt = unsafe { (self.av_get_pix_fmt)(name.as_ptr()) };
(fmt >= 0).then_some(fmt)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn majors_from_file_names() {
assert_eq!(major_of("libavcodec.so.61"), Some(61));
assert_eq!(major_of("/usr/lib/x86_64-linux-gnu/libavcodec.so.60.31.102"), Some(60));
assert_eq!(major_of("avcodec-62.dll"), Some(62));
assert_eq!(major_of("C:\\ffmpeg\\bin\\avcodec-61.dll"), Some(61));
assert_eq!(major_of("libavcodec.59.dylib"), Some(59));
assert_eq!(major_of("libavcodec.so"), None);
}
#[test]
fn system_names_are_newest_first_and_unbounded_below_today() {
let names = system_names("avcodec");
let majors: Vec<u32> = names.iter().filter_map(|n| major_of(n)).collect();
assert!(majors.windows(2).all(|w| w[0] > w[1]));
assert!(majors.contains(&58) && majors.contains(&62) && majors[0] > 62);
}
#[test]
fn error_tags() {
assert_eq!(EOF, -0x2046_4F45);
assert_eq!(OPTION_NOT_FOUND, -0x5450_4FF8);
}
#[test]
fn missing_directory_fails_cleanly() {
let search = Search { dirs: vec!["/nonexistent/voelin-ffmpeg".into()], system: false };
let err = load(&search).err().expect("nothing there");
assert!(err.contains("no FFmpeg libraries"), "{err}");
}
}
+7 -3
View File
@@ -8,7 +8,8 @@
//! - [`codec`]: [`VideoEncoder`] / [`VideoDecoder`] traits, codec preference
//! and the backends: libvpx (VP8/VP9, feature `vpx`), Cisco's OpenH264
//! loaded at runtime (H.264, feature `openh264`), dav1d (AV1 decoding,
//! feature `av1`)
//! feature `av1`), and FFmpeg loaded at runtime ([`ffmpeg`], feature
//! `ffmpeg`: hardware encoders, x264, SVT-AV1, ...)
//! - [`capture`]: [`ScreenCapture`] and [`AudioCapture`] with a synthetic
//! test source, X11 (feature `x11`), the Wayland ScreenCast portal and
//! PipeWire system audio (feature `pipewire`), and Windows Graphics Capture
@@ -30,6 +31,8 @@
pub mod capture;
pub mod codec;
pub mod convert;
#[cfg(feature = "ffmpeg")]
pub mod ffmpeg;
pub mod frame;
pub mod handoff;
pub mod mix;
@@ -40,8 +43,9 @@ pub mod workers;
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
pub use codec::{
Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig,
VideoDecoder, VideoEncoder,
BackendChoice, Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend,
EncoderConfig, EncoderInfo, EncoderPreference, EncoderReport, H264Profile, VideoDecoder,
VideoEncoder,
};
pub use frame::{
AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
+2 -2
View File
@@ -27,7 +27,7 @@ fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str)
/// Encode 30 frames of the pattern, force a keyframe midway, lower the
/// bitrate, and check every decoded frame.
fn roundtrip(codec: Codec) {
let codecs = Codecs::new();
let codecs = Codecs::builtin();
let screen = SyntheticScreen::new(W, H);
let config = EncoderConfig { fps: FPS, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = codecs.new_encoder(codec, config).unwrap();
@@ -69,7 +69,7 @@ fn vp9_synthetic_roundtrip() {
/// Frames from the capture thread go through encode / decode in order.
#[tokio::test]
async fn capture_thread_to_decoder() {
let codecs = Codecs::new();
let codecs = Codecs::builtin();
let mut screen = SyntheticScreen::new(W, H);
let options = CaptureOptions { fps: 60, cursor: false, queue: 8 };
let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap();
+283
View File
@@ -0,0 +1,283 @@
//! Encoders through the system's FFmpeg (loaded at runtime), decoded with
//! this crate's own decoders: H.264 with Cisco's OpenH264
//! (`VOELIN_OPENH264_LIB`), AV1 with dav1d (`--features av1`).
//!
//! Skipped without FFmpeg. Hardware backends 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;
use voelin_media::capture::synthetic::SyntheticScreen;
use voelin_media::ffmpeg::{BACKENDS, Ffmpeg, FfmpegEncoder, probe};
use voelin_media::{
Codec, Codecs, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, convert,
};
const W: u32 = 320;
const H: u32 = 240;
fn ffmpeg() -> Option<&'static Ffmpeg> {
match Ffmpeg::get() {
Ok(f) => Some(f),
Err(e) => {
eprintln!("FFmpeg not available ({e}), skipped");
None
}
}
}
fn decoder(codec: Codec) -> Option<Box<dyn VideoDecoder>> {
match codec {
#[cfg(feature = "openh264")]
Codec::H264 => {
let path = std::env::var_os("VOELIN_OPENH264_LIB")?;
let library = voelin_media::codec::h264::OpenH264::load(path).ok()?;
Some(Box::new(library.decoder().unwrap()))
}
#[cfg(feature = "av1")]
Codec::Av1 => Some(Box::new(voelin_media::codec::av1::Dav1dDecoder::new().unwrap())),
_ => None,
}
}
/// Twelve frames of the moving test pattern, a keyframe forced at 8, a
/// bitrate change at 5: keyframes where asked, timestamps kept, and (with a
/// decoder) every picture decodable at PSNR > 28 dB.
fn roundtrip(name: &'static str) {
let screen = SyntheticScreen::new(W, H);
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = FfmpegEncoder::new(name, config).unwrap();
assert_eq!(encoder.backend(), EncoderBackend::Ffmpeg(name));
let codec = encoder.codec();
let mut decoder = decoder(codec);
let mut keyframes = Vec::new();
let mut sent = Vec::new();
let mut decoded = 0;
let mut sources = Vec::new();
// Frames in until the first packet came out (the encoder's delay).
let mut delay = None;
// Until frame 11 came out (encoders with a delay need more input).
for n in 0..60u32 {
if sources.len() > 11 && sent.len() >= 12 {
break;
}
let frame = screen.frame(u64::from(n), 30);
if n == 5 {
encoder.set_bitrate(800_000).unwrap();
}
let out = encoder.encode(&frame, n == 8).unwrap();
sources.push(frame);
if delay.is_none() && !out.is_empty() {
delay = Some(n);
}
for f in &out {
sent.push(f.pts_90khz);
// Encoders with a delay hand out older frames: match by time.
let index = sources.iter().position(|s| s.pts_90khz() == f.pts_90khz).unwrap();
if f.keyframe {
keyframes.push(index);
}
if let Some(decoder) = &mut decoder
&& let Some(picture) = decoder.decode(&f.data).unwrap()
{
assert_eq!((picture.width, picture.height), (W, H));
let psnr = convert::psnr(&sources[index], &picture).unwrap();
assert!(psnr > 28.0, "{name} frame {index}: PSNR {psnr:.1} dB");
decoded += 1;
}
}
}
eprintln!(
"{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}",
sent.len(),
sources.len()
);
assert!(sent.len() >= 8, "{name}: only {} packets", sent.len());
assert_eq!(keyframes.first(), Some(&0), "{name}");
assert!(keyframes.contains(&8), "{name}: forced keyframe missing: {keyframes:?}");
assert!(sent.windows(2).all(|w| w[0] < w[1]), "{name}: timestamps {sent:?}");
assert_eq!(sent[0], 0);
if decoder.is_some() {
assert!(decoded >= 8, "{name}: decoded {decoded}");
}
}
fn available(name: &str) -> bool {
probe().iter().any(|s| s.spec.name == name && s.available.is_ok())
}
#[test]
fn probe_reports_every_backend() {
let Some(ffmpeg) = ffmpeg() else { return };
eprintln!("{:?}", ffmpeg.info());
let statuses = probe();
assert_eq!(statuses.len(), BACKENDS.len());
for status in statuses {
eprintln!("{:>18}: {:?}", status.spec.name, status.available);
if let Err(reason) = &status.available {
assert!(!reason.is_empty());
}
}
// The report lists them with the built-in ones.
let report = Codecs::new().report();
assert!(report.ffmpeg.is_ok(), "{report:?}");
assert!(report.encoders.iter().any(|e| e.name == "libvpx"));
for status in statuses {
let info = report.encoders.iter().find(|e| e.name == status.spec.name).unwrap();
assert_eq!(info.status, status.available);
let automatic = status.available.is_ok() && status.spec.is_automatic();
assert_eq!(info.rank.is_some(), automatic, "{}", status.spec.name);
}
}
#[test]
fn software_encoders_roundtrip() {
if ffmpeg().is_none() {
return;
}
let mut tested = Vec::new();
for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] {
if available(name) {
roundtrip(name);
tested.push(name);
} else {
eprintln!("{name} skipped: not available");
}
}
eprintln!("tested: {tested:?}");
}
#[test]
fn x264_is_constrained_high_and_changes_size() {
if ffmpeg().is_none() || !available("libx264") {
return;
}
let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
let mut encoder = FfmpegEncoder::new("libx264", config).unwrap();
let screen = SyntheticScreen::new(W, H);
let first = encoder.encode(&screen.frame(0, 30), false).unwrap();
// profile_idc 100 (High) without B-frames: what TeamSpeak decodes.
let sps =
first[0].data.windows(5).find(|w| w[..4] == [0, 0, 1, 0x67] || w[..4] == [0, 0, 0, 1]);
assert!(sps.is_some());
let profile = h264_profile(&first[0].data);
assert_eq!(profile, Some(100), "High profile");
// A new size: a new session, starting with a keyframe.
let small = SyntheticScreen::new(160, 120);
let out = encoder.encode(&small.frame(1, 30), false);
assert!(out.unwrap().iter().any(|f| f.keyframe));
// Odd sizes are cropped to even ones instead of failing.
let odd =
voelin_media::VideoFrame::black_i420(201, 151).with_timestamp(Duration::from_millis(66));
assert!(encoder.encode(&odd, false).unwrap().iter().any(|f| f.keyframe));
// Baseline on request.
let baseline = EncoderConfig {
h264_profile: voelin_media::H264Profile::ConstrainedBaseline,
..EncoderConfig::default()
};
let mut encoder = FfmpegEncoder::new("libx264", baseline).unwrap();
let out = encoder.encode(&screen.frame(0, 30), false).unwrap();
assert_eq!(h264_profile(&out[0].data), Some(66));
}
/// `profile_idc` of the first SPS in an Annex B stream.
fn h264_profile(data: &[u8]) -> Option<u8> {
let mut i = 0;
while i + 4 < data.len() {
if data[i..i + 3] == [0, 0, 1] {
if data[i + 3] & 0x1f == 7 {
return data.get(i + 4).copied();
}
i += 3;
} else {
i += 1;
}
}
None
}
#[test]
fn codecs_prefer_ffmpeg_h264_over_nothing() {
if ffmpeg().is_none() || !available("libx264") {
return;
}
let codecs = Codecs::new();
assert!(codecs.encoder_codecs().contains(&Codec::H264));
let encoder = codecs.new_encoder(Codec::H264, EncoderConfig::default()).unwrap();
assert!(matches!(encoder.backend(), EncoderBackend::Ffmpeg(_)));
let named =
voelin_media::EncoderPreference { hardware: false, backend: "libx264".parse().unwrap() };
let encoder = codecs.new_encoder_preferring(Codec::H264, EncoderConfig::default(), &named);
assert_eq!(encoder.unwrap().backend(), EncoderBackend::Ffmpeg("libx264"));
}
/// Unknown names and hardware without its device fail with a reason, not
/// a panic.
#[test]
fn unusable_backends_fail_cleanly() {
if ffmpeg().is_none() {
return;
}
assert!(FfmpegEncoder::new("no_such_encoder", EncoderConfig::default()).is_err());
for status in probe().iter().filter(|s| s.available.is_err()) {
let Ok(mut encoder) = FfmpegEncoder::new(status.spec.name, EncoderConfig::default()) else {
continue;
};
let frame = voelin_media::VideoFrame::black_i420(W, H);
assert!(encoder.encode(&frame, true).is_err(), "{} passed now", status.spec.name);
}
}
/// A backend whose wrapper cannot change the bitrate running (libaom here,
/// VA-API alike) waits for the next keyframe, but reopens at once when the
/// target falls below half.
#[test]
fn bitrate_changes_without_live_reconfiguration() {
if ffmpeg().is_none() || !available("libaom-av1") {
return;
}
let screen = SyntheticScreen::new(W, H);
let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
let mut encoder = FfmpegEncoder::new("libaom-av1", config).unwrap();
let key = |encoder: &mut FfmpegEncoder, n: u64, force: bool| {
encoder.encode(&screen.frame(n, 30), force).unwrap().iter().any(|f| f.keyframe)
};
assert!(key(&mut encoder, 0, false));
assert!(!key(&mut encoder, 1, false));
encoder.set_bitrate(800_000).unwrap();
assert!(!key(&mut encoder, 2, false), "a small change waits for a keyframe");
encoder.set_bitrate(300_000).unwrap();
assert!(key(&mut encoder, 3, false), "congestion: at once");
encoder.set_bitrate(400_000).unwrap();
assert!(!key(&mut encoder, 4, false));
assert!(key(&mut encoder, 5, true));
assert!(!key(&mut encoder, 6, false));
}
/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is
/// refused as unavailable, so the caller maps the buffer instead.
#[cfg(target_os = "linux")]
#[test]
fn dmabuf_import_is_refused_cleanly() {
use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc};
if ffmpeg().is_none() {
return;
}
let frame = DmaBufRef {
width: W,
height: H,
timestamp: Duration::ZERO,
fourcc: drm_fourcc(b"XR24"),
modifier: DRM_MOD_LINEAR,
fd: -1,
size: (W * H * 4) as usize,
planes: [(0, (W * 4) as usize), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
for name in ["libx264", "h264_vaapi"] {
let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap();
let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err();
assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}");
}
}
+2 -2
View File
@@ -21,7 +21,7 @@ fn missing_library_is_a_clear_error() {
assert!(err.to_string().contains("OpenH264 library not found"), "{err}");
// Without a library, H.264 is neither decodable nor encodable.
let codecs = Codecs::new();
let codecs = Codecs::builtin();
assert!(!codecs.decoders().contains(&Codec::H264));
assert!(!codecs.encoder_codecs().contains(&Codec::H264));
let err = codecs.new_decoder(Codec::H264).err().unwrap();
@@ -52,7 +52,7 @@ fn sps_profile(data: &[u8]) -> Option<u8> {
}
fn roundtrip(library: OpenH264) {
let codecs = Codecs::new().with_openh264(library.clone());
let codecs = Codecs::builtin().with_openh264(library.clone());
assert_eq!(codecs.decoders().last(), Some(&Codec::H264));
assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));
+34 -2
View File
@@ -1,5 +1,6 @@
//! Feedback from the stream sessions to the encoders of our stream's layers:
//! keyframe requests and bitrate targets per [`LayerId`].
//! keyframe requests and bitrate targets per [`LayerId`], and the video
//! codecs the viewers negotiated.
//!
//! [`LayerFeedback`] is shared between the stream session (which writes) and
//! encoder threads (which read every frame). Both sides only use atomics;
@@ -9,9 +10,10 @@
use std::array;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU64, Ordering};
use crate::layer::{LayerId, LayerSet};
use crate::peer::VideoCodec;
/// Words of the keyframe bitmap: one bit per layer id.
const WORDS: usize = (LayerId::MAX as usize + 1) / 64;
@@ -30,6 +32,8 @@ pub struct LayerFeedback {
top: AtomicU16,
/// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids.
bitrates: Box<[OnceLock<Box<[AtomicU64]>>]>,
/// [`VideoCodec::bit`]s of the codecs connected viewers negotiated.
codecs: AtomicU8,
}
impl Default for LayerFeedback {
@@ -51,6 +55,7 @@ impl LayerFeedback {
summary: array::from_fn(|_| AtomicU64::new(0)),
top: AtomicU16::new(0),
bitrates: (0..=LayerId::MAX as usize / CHUNK).map(|_| OnceLock::new()).collect(),
codecs: AtomicU8::new(0),
}
}
@@ -122,6 +127,22 @@ impl LayerFeedback {
let bitrate = chunk[usize::from(layer) % CHUNK].load(Ordering::Relaxed);
(bitrate != 0).then_some(bitrate)
}
/// The video codecs the viewers negotiated.
pub fn set_codecs(&self, codecs: impl IntoIterator<Item = VideoCodec>) {
let bits = codecs.into_iter().fold(0, |bits, c| bits | c.bit());
self.codecs.store(bits, Ordering::Relaxed);
}
/// Whether a viewer negotiated `codec`.
pub fn has_codec(&self, codec: VideoCodec) -> bool {
self.codecs.load(Ordering::Relaxed) & codec.bit() != 0
}
/// Whether any viewer negotiated a codec yet.
pub fn has_codecs(&self) -> bool {
self.codecs.load(Ordering::Relaxed) != 0
}
}
#[cfg(test)]
@@ -160,4 +181,15 @@ mod tests {
f.set_bitrate(3, None);
assert_eq!(f.bitrate(3), None);
}
#[test]
fn codecs() {
let f = LayerFeedback::new();
assert!(!f.has_codecs());
f.set_codecs([VideoCodec::Vp8, VideoCodec::H265, VideoCodec::Vp8]);
assert!(f.has_codec(VideoCodec::Vp8) && f.has_codec(VideoCodec::H265));
assert!(!f.has_codec(VideoCodec::H264));
f.set_codecs([]);
assert!(!f.has_codecs());
}
}
+131
View File
@@ -0,0 +1,131 @@
//! H.264 `profile-level-id` for the offer: the profile our encoders produce
//! and the level the stream's size, frame rate and bitrate need (ITU-T
//! H.264 Table A-1), instead of a fixed level.
/// Profile of our H.264 streams.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum H264Profile {
/// Constrained High (`profile_idc` 100, `constraint_set4` and `5`): what
/// TeamSpeak clients decode.
#[default]
ConstrainedHigh,
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`).
ConstrainedBaseline,
}
/// Level limits: `level_idc`, macroblocks per second, macroblocks per frame,
/// bitrate in kbit/s (Baseline; High allows 1.25 times that).
const LEVELS: [(u8, u64, u64, u64); 19] = [
(10, 1_485, 99, 64),
(11, 3_000, 396, 192),
(12, 6_000, 396, 384),
(13, 11_880, 396, 768),
(20, 11_880, 396, 2_000),
(21, 19_800, 792, 4_000),
(22, 20_250, 1_620, 4_000),
(30, 40_500, 1_620, 10_000),
(31, 108_000, 3_600, 14_000),
(32, 216_000, 5_120, 20_000),
(40, 245_760, 8_192, 20_000),
(41, 245_760, 8_192, 50_000),
(42, 522_240, 8_704, 50_000),
(50, 589_824, 22_080, 135_000),
(51, 983_040, 36_864, 240_000),
(52, 2_073_600, 36_864, 240_000),
(60, 4_177_920, 139_264, 240_000),
(61, 8_355_840, 139_264, 480_000),
(62, 16_711_680, 139_264, 800_000),
];
/// The lowest level (`level_idc`, e.g. 31 for 3.1) whose limits hold
/// `width` x `height` at `fps` and `bitrate` bit/s; the highest level
/// defined if none does (the stream is sent anyway: decoders mostly take
/// more than their level).
pub fn level_idc(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: u64) -> u8 {
let (mbs_w, mbs_h) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
let frame = mbs_w * mbs_h;
let rate = frame * u64::from(fps.max(1));
let factor = match profile {
H264Profile::ConstrainedHigh => 1250,
H264Profile::ConstrainedBaseline => 1000,
};
LEVELS
.iter()
.find(|&&(_, max_rate, max_frame, max_kbps)| {
rate <= max_rate
&& frame <= max_frame
// Neither side may exceed sqrt(8 * MaxFS) macroblocks.
&& mbs_w * mbs_w <= 8 * max_frame
&& mbs_h * mbs_h <= 8 * max_frame
&& bitrate <= max_kbps * factor
})
.map_or(LEVELS[LEVELS.len() - 1].0, |l| l.0)
}
/// `profile-level-id` (`a=fmtp`, three bytes: `profile_idc`,
/// `profile-iop`, `level_idc`) for `profile` at `level_idc`.
pub fn profile_level_id(profile: H264Profile, level_idc: u8) -> u32 {
let (profile_idc, iop) = match profile {
H264Profile::ConstrainedHigh => (0x64, 0x0c),
H264Profile::ConstrainedBaseline => (0x42, 0xe0),
};
(profile_idc << 16) | (iop << 8) | u32::from(level_idc)
}
/// The level TeamSpeak offers (3.1): our offers never go below it, so the
/// offer official clients know stays the same for small streams.
pub const MIN_OFFER_LEVEL: u8 = 31;
/// `profile-level-id` for a stream of this size, frame rate and bitrate,
/// at least level 3.1.
pub fn offer_profile_level_id(
profile: H264Profile,
width: u32,
height: u32,
fps: u32,
bitrate: u64,
) -> u32 {
let level = level_idc(profile, width, height, fps, bitrate).max(MIN_OFFER_LEVEL);
profile_level_id(profile, level)
}
#[cfg(test)]
mod tests {
use super::*;
const HIGH: H264Profile = H264Profile::ConstrainedHigh;
#[test]
fn levels_from_macroblocks_per_second() {
// 720p30: 3600 MBs per frame, 108000 per second: exactly 3.1.
assert_eq!(level_idc(HIGH, 1280, 720, 30, 4_000_000), 31);
// 720p60 needs 3.2, 1080p30 4.0, 1080p60 4.2.
assert_eq!(level_idc(HIGH, 1280, 720, 60, 4_000_000), 32);
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 8_000_000), 40);
assert_eq!(level_idc(HIGH, 1920, 1080, 60, 8_000_000), 42);
// 1440p60: 14400 MBs per frame, more than 4.2's 8704: 5.1.
assert_eq!(level_idc(HIGH, 2560, 1440, 60, 10_000_000), 51);
// 4K120 needs 6.0 (and any size or rate beyond all: the top level).
assert_eq!(level_idc(HIGH, 3840, 2160, 120, 10_000_000), 60);
assert_eq!(level_idc(HIGH, 16384, 16384, 240, 10_000_000), 62);
// Small streams: low levels.
assert_eq!(level_idc(HIGH, 320, 240, 15, 200_000), 12);
// The bitrate counts too: 1080p30 at 30 Mbit/s is beyond 4.0 (25
// Mbit/s in High).
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 30_000_000), 41);
// Baseline has the lower bitrate limit.
let baseline = H264Profile::ConstrainedBaseline;
assert_eq!(level_idc(baseline, 1920, 1080, 30, 22_000_000), 41);
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 22_000_000), 40);
// A very wide frame is limited by sqrt(8 * MaxFS).
assert_eq!(level_idc(HIGH, 4096, 64, 1, 100_000), 40);
}
#[test]
fn profile_level_ids() {
assert_eq!(profile_level_id(HIGH, 31), 0x640c1f);
assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f);
assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f);
assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a);
}
}
+2
View File
@@ -12,6 +12,7 @@
pub mod discovery;
pub mod dtls;
pub mod feedback;
pub mod h264;
pub mod layer;
pub mod peer;
pub mod proto;
@@ -23,6 +24,7 @@ pub mod stun;
pub use discovery::{ClientState, StreamLookup};
pub use dtls::SrtpProfile;
pub use feedback::LayerFeedback;
pub use h264::H264Profile;
pub use layer::{LayerId, LayerSet, LayerSpec};
pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
+89 -2
View File
@@ -32,6 +32,7 @@ use tokio::sync::{mpsc, oneshot};
use tracing::{debug, trace, warn};
use crate::dtls::{self, NegotiatedProfile, SrtpProfile};
use crate::h264::{self, H264Profile};
use crate::layer::LayerSpec;
use crate::stun;
@@ -46,10 +47,12 @@ pub enum VideoCodec {
Vp9,
H264,
Av1,
/// HEVC: offered last, for peers that take nothing else.
H265,
}
impl VideoCodec {
pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1];
pub const ALL: [Self; 5] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1, Self::H265];
pub fn from_codec(c: Codec) -> Option<Self> {
match c {
@@ -57,6 +60,7 @@ impl VideoCodec {
Codec::Vp9 => Some(Self::Vp9),
Codec::H264 => Some(Self::H264),
Codec::Av1 => Some(Self::Av1),
Codec::H265 => Some(Self::H265),
_ => None,
}
}
@@ -72,8 +76,20 @@ impl VideoCodec {
Self::Vp9 => "VP9",
Self::H264 => "H264",
Self::Av1 => "AV1",
Self::H265 => "H265",
}
}
/// Bit of this codec in a set of codecs ([`crate::LayerFeedback`]).
pub fn bit(self) -> u8 {
1 << Self::ALL.iter().position(|c| *c == self).unwrap_or(0)
}
}
impl std::fmt::Display for VideoCodec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.sdp_name())
}
}
#[derive(Clone, Debug)]
@@ -107,6 +123,10 @@ pub struct PeerConfig {
/// simulcast leaves the peer unable to send video. Official TeamSpeak
/// viewers get a plain offer and one layer at a time.
pub simulcast: bool,
/// H.264 `profile-level-id` of the offer: Constrained High at the level
/// the stream needs ([`set_h264_format`](Self::set_h264_format)); level
/// 3.1 by default.
pub h264_profile_level_id: u32,
}
impl Default for PeerConfig {
@@ -121,6 +141,7 @@ impl Default for PeerConfig {
srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(),
bandwidth_estimation: true,
simulcast: false,
h264_profile_level_id: H264_CONSTRAINED_HIGH,
}
}
}
@@ -134,6 +155,21 @@ impl PeerConfig {
..Self::default()
}
}
/// Offer H.264 in `profile` at the level a `width` x `height` stream at
/// `fps` and `bitrate` bit/s needs (at least 3.1, see
/// [`crate::h264::offer_profile_level_id`]).
pub fn set_h264_format(
&mut self,
profile: H264Profile,
width: u32,
height: u32,
fps: u32,
bitrate: u64,
) {
self.h264_profile_level_id =
h264::offer_profile_level_id(profile, width, height, fps, bitrate);
}
}
#[derive(Debug, thiserror::Error)]
@@ -190,6 +226,9 @@ pub enum PeerEvent {
/// The answer accepted RID simulcast: video goes out per layer with
/// these RIDs ([`Peer::write_rid`]).
Simulcast(Vec<Rid>),
/// The video codec the answer chose (streamer side): the viewer's first
/// one. Video written to this peer must be in it.
VideoCodec(VideoCodec),
/// The connection is gone.
Closed,
}
@@ -422,11 +461,12 @@ fn build_rtc(
112.into(),
Some(113.into()),
true,
H264_CONSTRAINED_HIGH,
config.h264_profile_level_id,
);
c
}
VideoCodec::Av1 => rtc_config.enable_av1(true),
VideoCodec::H265 => rtc_config.enable_h265(true),
};
}
dtls::build_rtc(rtc_config, &config.srtp_profiles)
@@ -798,6 +838,18 @@ impl Task {
let _ = self.events.send(PeerEvent::Simulcast(rids.clone()));
}
}
// The codec video is written in (see `find_writer`).
if let Some((mid, pt)) = self.find_writer(MediaKind::Video) {
self.writers.insert(MediaKind::Video, (mid, pt));
let codec = self.rtc.writer(mid).and_then(|w| {
let params = w.payload_params().find(|p| p.pt() == pt)?;
VideoCodec::from_codec(params.spec().codec)
});
if let Some(codec) = codec {
debug!(%codec, "the answer chose");
let _ = self.events.send(PeerEvent::VideoCodec(codec));
}
}
Ok(())
}
@@ -872,6 +924,41 @@ mod tests {
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
}
/// Several codecs offered: the streamer learns which one each viewer's
/// answer chose; H.264 carries the level the stream needs.
#[tokio::test]
async fn streamer_learns_the_answered_codec() {
let mut streamer = PeerConfig {
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264, VideoCodec::H265],
..PeerConfig::loopback()
};
streamer.set_h264_format(H264Profile::ConstrainedHigh, 1920, 1080, 60, 8_000_000);
let (mut peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c2a"), "{offer}");
assert!(offer.contains("H265/90000"), "{offer}");
let viewers = [
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoCodec::Vp8),
(vec![VideoCodec::H264], VideoCodec::H264),
(vec![VideoCodec::H265], VideoCodec::H265),
];
for (accept, expected) in viewers {
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
let config = PeerConfig { accept_video_codecs: accept, ..PeerConfig::loopback() };
let (_viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
streamer_peer.accept_answer(&answer).await.unwrap();
let codec = loop {
match streamer_peer.next_event().await.unwrap() {
PeerEvent::VideoCodec(codec) => break codec,
PeerEvent::Closed => panic!("closed"),
_ => {}
}
};
assert_eq!(codec, expected);
}
peer.close();
while peer.next_event().await.is_some() {}
}
/// The SDP lines that make up the media description (not the random ids,
/// ports, credentials and fingerprints).
fn media_lines(sdp: &str) -> Vec<&str> {
+45 -3
View File
@@ -40,7 +40,7 @@ use crate::discovery::{ClientState, Discovery, StreamLookup};
use crate::dtls::SrtpProfile;
use crate::feedback::LayerFeedback;
use crate::layer::{LayerId, LayerSet, LayerSpec};
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent};
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec};
use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup};
use crate::signal::Signal;
use crate::source::EncodedFrame;
@@ -146,6 +146,9 @@ pub struct ViewerInfo {
pub estimate: Option<u64>,
/// The SRTP profile of the connection, once DTLS is done.
pub srtp_profile: Option<SrtpProfile>,
/// The video codec the viewer's answer chose (it gets video in that
/// codec).
pub codec: Option<VideoCodec>,
}
/// What happens to our own stream.
@@ -542,6 +545,8 @@ struct ViewerSlot {
/// The latest bandwidth estimate of the connection (bit/s).
estimate: Option<u64>,
srtp_profile: Option<SrtpProfile>,
/// The video codec its answer chose.
codec: Option<VideoCodec>,
}
impl ViewerSlot {
@@ -554,6 +559,7 @@ impl ViewerSlot {
rids: None,
estimate: None,
srtp_profile: None,
codec: None,
}
}
@@ -648,6 +654,7 @@ impl StreamerSession {
layer: (v.peer.is_some() && v.rids.is_none()).then_some(v.choice.layer),
estimate: v.estimate,
srtp_profile: v.srtp_profile,
codec: v.codec,
})
.collect()
}
@@ -792,6 +799,7 @@ impl StreamerSession {
slot.peer = Some(peer);
slot.state = ViewerState::Connecting;
slot.choice = LayerChoice::new(layer);
slot.codec = None;
slot.rids = None;
slot.estimate = None;
slot.srtp_profile = None;
@@ -930,6 +938,18 @@ impl StreamerSession {
/// Send an encoded frame: audio to every connected viewer, video to the
/// viewers of its layer (with its RID to peers with RID simulcast).
pub fn write_frame(&mut self, frame: &EncodedFrame, out: &mut Outbox) {
self.write_frame_in(frame, None, out);
}
/// [`write_frame`](Self::write_frame) for video encoded in `codec`
/// (`None`: whatever the viewers negotiated): only viewers whose answer
/// chose that codec get it.
pub fn write_frame_in(
&mut self,
frame: &EncodedFrame,
codec: Option<VideoCodec>,
out: &mut Outbox,
) {
let (kind, time, layer) = (frame.kind, frame.time, frame.layer);
let rid = match kind {
MediaKind::Video => self.layers.index(layer).and_then(|i| self.layers.rids[i]),
@@ -944,6 +964,11 @@ impl StreamerSession {
peer.write(kind, time, frame.data.clone());
continue;
}
if let (Some(codec), Some(negotiated)) = (codec, slot.codec)
&& codec != negotiated
{
continue;
}
match &slot.rids {
Some(rids) => {
if let Some(rid) = rid
@@ -1062,6 +1087,11 @@ impl StreamerSession {
slot.rids = Some(rids);
}
}
PeerEvent::VideoCodec(codec) => {
debug!(viewer = viewer.0, %codec, "viewer's video codec");
slot.codec = Some(codec);
self.emit_viewers(out);
}
PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } => {}
PeerEvent::Closed => {
// The viewer may ask for a new offer (`reconnect`); it stays
@@ -1173,6 +1203,10 @@ impl StreamerSession {
}
fn emit_viewers(&mut self, out: &mut Outbox) {
// Every change of the viewers comes through here: the encoders learn
// which codecs are needed now.
self.feedback
.set_codecs(self.viewers.values().filter(|v| v.peer.is_some()).filter_map(|v| v.codec));
self.last_viewers_event = Some(Instant::now());
out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers())));
}
@@ -1409,7 +1443,8 @@ impl ViewerSession {
PeerEvent::KeyframeRequest
| PeerEvent::LayerKeyframeRequest(_)
| PeerEvent::BitrateEstimate(_)
| PeerEvent::Simulcast(_) => {}
| PeerEvent::Simulcast(_)
| PeerEvent::VideoCodec(_) => {}
PeerEvent::Closed => {
if self.peer.take().is_none() {
return;
@@ -1524,8 +1559,15 @@ impl Streams {
/// Send an encoded frame of our stream: audio to every connected viewer,
/// video to the viewers of its layer.
pub fn write_frame(&mut self, frame: &EncodedFrame) {
self.write_frame_in(frame, None);
}
/// [`write_frame`](Self::write_frame) of video encoded in `codec`: to
/// the viewers that negotiated it (see
/// [`StreamerSession::write_frame_in`]).
pub fn write_frame_in(&mut self, frame: &EncodedFrame, codec: Option<VideoCodec>) {
if let Some(s) = self.streamer.as_mut().filter(|s| !s.is_ended()) {
s.write_frame(frame, &mut self.out);
s.write_frame_in(frame, codec, &mut self.out);
}
}
+38 -7
View File
@@ -11,10 +11,10 @@ use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
use tokio::runtime::Handle;
use tracing::warn;
use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert};
use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert};
use voelin_core::media::{
self, AudioSourceSpec, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config,
stream_codec,
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
Viewer, peer_config, preferred_codec, stream_codec,
};
use voelin_core::stream::PeerConfig;
use voelin_core::{Engine, StreamSink};
@@ -57,6 +57,10 @@ pub(crate) struct Video {
openh264_dir: PathBuf,
#[cfg(not(target_os = "android"))]
h264: openh264::State,
/// Which encoders to use and the configured stream codec (`None`:
/// automatic), from the settings.
encoder: EncoderPreference,
codec: Option<Codec>,
/// Sources of the share dialog, by index.
sources: Vec<(SourceId, String)>,
}
@@ -68,6 +72,8 @@ impl Video {
#[allow(unused_mut, reason = "set_h264 does nothing on Android")]
let mut video = Self {
codecs: Arc::new(Codecs::new()),
encoder: EncoderPreference::default(),
codec: None,
#[cfg(not(target_os = "android"))]
openh264_dir: data_dir.join("openh264"),
#[cfg(not(target_os = "android"))]
@@ -79,11 +85,34 @@ impl Video {
video
}
/// `base` with the codecs this machine can encode and decode.
pub fn peer_config(&self, base: PeerConfig) -> PeerConfig {
/// `base` with the codecs this machine can encode and decode: the stream
/// codec (configured, or the encoder preference's first) offered first.
pub fn peer_config(&self, mut base: PeerConfig) -> PeerConfig {
if let Some(codec) = preferred_codec(&self.codecs, self.codec) {
base.video_codecs = vec![media::video_codec(codec)];
}
peer_config(&self.codecs, base)
}
/// Use other encoders (`stream.hardware_acceleration`,
/// `stream.encoder_backend`) and stream codec (`stream.codec`, `None`:
/// automatic). A running share follows through
/// `Streamer::reconfigure` with `StreamerConfigUpdate::encoder`.
#[allow(dead_code, reason = "for the settings page")]
pub fn set_encoder_preference(&mut self, encoder: EncoderPreference, codec: Option<Codec>) {
let mut codecs = (*self.codecs).clone();
codecs.set_preference(encoder.clone());
self.codecs = Arc::new(codecs);
self.encoder = encoder;
self.codec = codec;
}
/// Every encoder backend, what works and why the rest does not.
#[allow(dead_code, reason = "for the integrations page")]
pub fn encoder_report(&self) -> EncoderReport {
self.codecs.report()
}
/// Whether H.264 works, and a line for the settings page.
pub fn h264_status(&self) -> (bool, String) {
#[cfg(target_os = "android")]
@@ -110,7 +139,7 @@ impl Video {
use openh264::State;
if !enabled {
self.h264 = State::Off;
self.codecs = Arc::new(Codecs::new());
self.codecs = Arc::new(Codecs::new().with_preference(self.encoder.clone()));
return;
}
if matches!(self.h264, State::Loaded(_) | State::Downloading) {
@@ -126,7 +155,8 @@ 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));
self.codecs =
Arc::new(Codecs::new().with_openh264(library).with_preference(self.encoder.clone()));
}
/// Download Cisco's OpenH264 (only on the user's request). `done` runs
@@ -230,6 +260,7 @@ impl Video {
fps: options.fps,
bitrate_kbps: options.bitrate_kbps,
codec,
encoder: self.encoder.clone(),
audio: options.audio,
audio_sources: options.audio_sources,
restore_token: options.restore_token,