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:
1 parent
5932e9e66d
commit
4b008f7650
10 files changed
+2773
-128
No files matched your search
@@ -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 }
|
||||
|
||||
@@ -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)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,411 @@
|
||||
//! 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.
|
||||
#[allow(dead_code)] // for the DMA-BUF import
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! 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`.
|
||||
#[allow(dead_code)] // for the DMA-BUF import
|
||||
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).
|
||||
pub fn take_log() -> Vec<String> {
|
||||
std::mem::take(&mut *LOG.lock().unwrap_or_else(std::sync::PoisonError::into_inner))
|
||||
}
|
||||
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
//! 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);
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -27,6 +28,8 @@
|
||||
pub mod capture;
|
||||
pub mod codec;
|
||||
pub mod convert;
|
||||
#[cfg(feature = "ffmpeg")]
|
||||
pub mod ffmpeg;
|
||||
pub mod frame;
|
||||
pub mod handoff;
|
||||
pub mod pool;
|
||||
@@ -36,8 +39,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,
|
||||
|
||||
Reference in new issue
Block a user