voelin-media: load FFmpeg at runtime for more video encoders (WIP)
Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox) and more software ones (x264, OpenH264, SVT-AV1, rav1e, libaom) through whatever FFmpeg is installed, found with libloading and never linked. Codec settings go through AVOptions only; the few struct fields without an accessor are located and checked at runtime, so any major version with a matching layout works. Each backend encodes one test frame at startup and is skipped with a reason if that fails. Codecs gains an encoder preference (hardware on/off, auto / software / a named backend) and a report of every backend for the UI. Codec gets H265 for peers that negotiate HEVC. Work in progress: committed early so it cannot be lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
10 files changed
+2773
-128
No files matched your search
@@ -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(),
|
||||
};
|
||||
|
||||
@@ -1,38 +1,44 @@
|
||||
//! 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
|
||||
}
|
||||
|
||||
/// 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 +46,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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! - [`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)
|
||||
|
||||
@@ -28,17 +30,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 +51,7 @@ impl Codec {
|
||||
Codec::Vp9 => "VP9",
|
||||
Codec::H264 => "H264",
|
||||
Codec::Av1 => "AV1",
|
||||
Codec::H265 => "H265",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,6 +74,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 +88,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 +103,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 +122,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 +149,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 +166,7 @@ impl Default for EncoderConfig {
|
||||
content: ContentHint::Screen,
|
||||
threads: 0,
|
||||
speed: None,
|
||||
h264_profile: H264Profile::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,29 +267,143 @@ 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,
|
||||
}
|
||||
|
||||
/// 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).
|
||||
pub struct Codecs {
|
||||
hardware: Vec<Box<dyn hw::HardwareEncoderFactory>>,
|
||||
factories: Vec<Box<dyn hw::EncoderFactory>>,
|
||||
#[cfg(feature = "openh264")]
|
||||
openh264: Option<h264::OpenH264>,
|
||||
preference: EncoderPreference,
|
||||
}
|
||||
|
||||
impl Default for Codecs {
|
||||
@@ -280,18 +417,21 @@ 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(),
|
||||
#[cfg(feature = "openh264")]
|
||||
openh264: None,
|
||||
preference: EncoderPreference::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +447,21 @@ 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
|
||||
}
|
||||
|
||||
fn has_openh264(&self) -> bool {
|
||||
#[cfg(feature = "openh264")]
|
||||
return self.openh264.is_some();
|
||||
@@ -335,6 +490,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 +499,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) {
|
||||
list.push(Candidate { codec, backend: f.backend(), hardware });
|
||||
}
|
||||
}
|
||||
};
|
||||
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 { codec: Codec::Vp8, backend: EncoderBackend::Libvpx, hardware: false });
|
||||
}
|
||||
factories(Codec::H264, false, &mut list);
|
||||
if self.has_openh264() {
|
||||
list.push((Codec::H264, EncoderBackend::OpenH264));
|
||||
let backend = EncoderBackend::OpenH264;
|
||||
list.push(Candidate { codec: Codec::H264, backend, hardware: false });
|
||||
}
|
||||
#[cfg(feature = "vpx")]
|
||||
if vpx::check(Codec::Vp9, true).is_ok() {
|
||||
list.push((Codec::Vp9, EncoderBackend::Libvpx));
|
||||
list.push(Candidate { codec: Codec::Vp9, backend: EncoderBackend::Libvpx, hardware: false });
|
||||
}
|
||||
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| 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.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 +590,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 +625,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 +641,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 +649,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)]
|
||||
|
||||
Reference in new issue
Block a user