Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a5ecbed1e5dd55ddc
This commit is contained in:
commit
5dd9aa1cd0
48 files changed
+4047
-438
No files matched your search
@@ -25,6 +25,15 @@ The first release is in preparation.
|
||||
another offered codec get their own encoder. Settings:
|
||||
`stream.hardware_acceleration`, `stream.encoder_backend`, `stream.codec`;
|
||||
`voelinctl stream encoders` lists what works.
|
||||
- Video decoding through the installed FFmpeg as well: hardware first
|
||||
(VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox), then FFmpeg's software
|
||||
decoders, then the built-in ones; each decoder is tested at start, and
|
||||
one that fails while watching is replaced by the next without ending the
|
||||
stream. Viewers now take AV1, HEVC and H.264 without OpenH264, and
|
||||
H.264 with B-frames as the official client sends it (OpenH264 showed
|
||||
under 1 fps of such a stream; 60 fps now). After a lost frame H.264 and
|
||||
HEVC go on decoding while a keyframe is asked for. Settings:
|
||||
`stream.hardware_decoding`, `stream.decoder_backend`.
|
||||
- `tsgw`: companion gateway for server admins (presence, channel chat
|
||||
relay, history).
|
||||
- Chat history: messages are kept on the device and, with a gateway, what
|
||||
|
||||
Generated
+7
@@ -8638,7 +8638,11 @@ checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustls-pki-types",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tungstenite 0.30.0",
|
||||
]
|
||||
|
||||
@@ -9188,6 +9192,8 @@ dependencies = [
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.10.3",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"sha1 0.11.0",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -9472,6 +9478,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs",
|
||||
"futures",
|
||||
"hickory-resolver",
|
||||
"md5",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
|
||||
@@ -82,3 +82,21 @@ against or offered back to upstream.
|
||||
tracing setup used `init`, which panics when quickcheck (`use_logging`) has
|
||||
already installed a `log` logger; the panic poisoned the `Lazy` and failed every
|
||||
later test of the binary, depending on test order. It uses `try_init` now.
|
||||
11. **TSDNS without an SRV record, as the official client resolves**
|
||||
(`tsclientlib/src/resolver.rs`). Without an SRV record at `_tsdns._tcp.<domain>`
|
||||
the official client asks a TSDNS server directly on TCP 41144 at the address's
|
||||
parent domains (`A/AAAA DNS resolve for possible TSDNS successful, "example.com"`,
|
||||
`TSDNS found at <ip>:41144 and queried successfully` in its log); upstream went
|
||||
straight to the address on port 9987, so servers published only through TSDNS
|
||||
(on another port) could not be reached without typing the port. Now: SRV
|
||||
`_ts3._udp.<address>`, then TSDNS (the servers `_tsdns._tcp` names, else the
|
||||
ones at each parent domain down to the last two labels), then A/AAAA on 9987.
|
||||
The steps start at once and come out in that order; each is given up after
|
||||
10 s, a TSDNS server after 3 s (connect and answer), so a port a firewall drops
|
||||
does not stall connecting. A port typed with the address now overrides the port
|
||||
of every result (the `_ts3._udp` one too). The TSDNS query sends the host
|
||||
without the port, and the answer is trimmed. SRV records of weight 0, the
|
||||
common weight, were dropped by the weighted ordering; they are kept now
|
||||
(RFC 2782 order). A CNAME among the SRV answers no longer panics. The lookups
|
||||
are injectable inside the module, and the tests use a fake TSDNS server and
|
||||
fake names; the upstream tests that need DNS and the internet are `#[ignore]`d.
|
||||
@@ -4,26 +4,32 @@
|
||||
|
||||
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
|
||||
use std::str;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::future::BoxFuture;
|
||||
use futures::prelude::*;
|
||||
use hickory_net::proto::rr::RData;
|
||||
use hickory_resolver::TokioResolver;
|
||||
use hickory_resolver::config::{CLOUDFLARE, ResolverConfig, ResolverOpts};
|
||||
use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||
use itertools::Itertools;
|
||||
use rand::RngExt;
|
||||
use thiserror::Error;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{self, TcpStream};
|
||||
use tokio::time::Duration;
|
||||
use tokio::time::{Duration, timeout};
|
||||
use tracing::{debug, instrument, warn};
|
||||
|
||||
const DEFAULT_PORT: u16 = 9987;
|
||||
/// Port a TSDNS server listens on.
|
||||
const TSDNS_PORT: u16 = 41144;
|
||||
const DNS_PREFIX_TCP: &str = "_tsdns._tcp.";
|
||||
const DNS_PREFIX_UDP: &str = "_ts3._udp.";
|
||||
const NICKNAME_LOOKUP_ADDRESS: &str = "https://named.myteamspeak.com/lookup";
|
||||
/// Wait this amount of seconds before giving up.
|
||||
const TIMEOUT_SECONDS: u64 = 10;
|
||||
/// Give up on one way of resolving after this long.
|
||||
const STEP_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
/// Give up on one TSDNS server (connecting and asking) after this long, so a
|
||||
/// firewall that drops the port does not hold up connecting.
|
||||
const TSDNS_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
@@ -68,129 +74,174 @@ enum ParseIpResult<'a> {
|
||||
|
||||
/// Beware that this may be slow because it tries all available methods.
|
||||
///
|
||||
/// The following methods are tried:
|
||||
/// The methods start at once and each is given up after a while (as the
|
||||
/// official client does); their addresses come out in this order:
|
||||
/// 1. If the address is an ip, the ip is returned
|
||||
/// 1. Server nicknames are resolved by a http request to TeamSpeak
|
||||
/// 1. The SRV record at `_ts3._udp.<address>`
|
||||
/// 1. The SRV record at `_tsdns._tcp.address.tld` to get the address of a tsdns
|
||||
/// server, e.g. when the address is `ts3.subdomain.from.com`, the SRV record
|
||||
/// at `_tsdns._tcp.from.com` is requested
|
||||
/// 1. Directly resolve the address to an ip address
|
||||
/// 1. A TSDNS server: the ones the SRV records at `_tsdns._tcp.address.tld`
|
||||
/// name, e.g. when the address is `ts3.subdomain.from.com`, the SRV record
|
||||
/// at `_tsdns._tcp.from.com` is requested; without such a record, the ones
|
||||
/// on port 41144 at the address's parent domains (`subdomain.from.com`,
|
||||
/// `from.com`). The first that knows the address answers.
|
||||
/// 1. Directly resolve the address to an ip address, port 9987
|
||||
///
|
||||
/// If a port is given with `:port`, it overwrites the automatically determined
|
||||
/// port. IPv6 addresses are put in square brackets when a port is present:
|
||||
/// If a port is given with `:port`, it overwrites the port of every address
|
||||
/// found. IPv6 addresses are put in square brackets when a port is present:
|
||||
/// `[::1]:9987`
|
||||
#[instrument]
|
||||
pub fn resolve(address: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
resolve_with(address, Lookups::system())
|
||||
}
|
||||
|
||||
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Result<Vec<(String, u16)>>> + Send + Sync;
|
||||
type HostFn = dyn Fn(String, u16) -> BoxFuture<'static, Result<Vec<SocketAddr>>> + Send + Sync;
|
||||
|
||||
/// Where [`resolve`] gets its answers from; the tests put fakes in.
|
||||
#[derive(Clone)]
|
||||
struct Lookups {
|
||||
/// The targets and ports of the SRV records at a name, in the order to
|
||||
/// try them.
|
||||
srv: Arc<SrvFn>,
|
||||
/// The addresses of a host name, with this port.
|
||||
host: Arc<HostFn>,
|
||||
tsdns_port: u16,
|
||||
tsdns_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn system() -> Self {
|
||||
Self {
|
||||
srv: Arc::new(|name| srv_targets(name).boxed()),
|
||||
host: Arc::new(|host, port| {
|
||||
async move {
|
||||
Ok(net::lookup_host((host.as_str(), port))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.collect())
|
||||
}
|
||||
.boxed()
|
||||
}),
|
||||
tsdns_port: TSDNS_PORT,
|
||||
tsdns_timeout: TSDNS_TIMEOUT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_with(address: String, lookups: Lookups) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
debug!("Starting resolve");
|
||||
let addr;
|
||||
let port;
|
||||
match parse_ip(&address) {
|
||||
let (host, port) = match parse_ip(&address) {
|
||||
Ok(ParseIpResult::Addr(res)) => {
|
||||
return stream::once(future::ok(res)).left_stream();
|
||||
}
|
||||
Ok(ParseIpResult::Other(a, p)) => {
|
||||
addr = a.to_string();
|
||||
port = p;
|
||||
if let Some(port) = port {
|
||||
debug!(port, "Found port");
|
||||
}
|
||||
}
|
||||
Ok(ParseIpResult::Other(host, port)) => (host.trim_end_matches('.').to_string(), port),
|
||||
Err(res) => return stream::once(future::err(res)).left_stream(),
|
||||
};
|
||||
if let Some(port) = port {
|
||||
debug!(port, "Found port");
|
||||
}
|
||||
|
||||
// Resolve as nickname
|
||||
let res = if !address.contains('.') && addr != "localhost" {
|
||||
debug!("Resolving nickname");
|
||||
let mut steps: Vec<BoxFuture<'static, Result<Vec<SocketAddr>>>> = Vec::new();
|
||||
if !host.contains('.') && host != "localhost" {
|
||||
// Could be a server nickname
|
||||
resolve_nickname(address.clone())
|
||||
.map_ok(move |mut addr| {
|
||||
if let Some(port) = port {
|
||||
addr.set_port(port);
|
||||
}
|
||||
addr
|
||||
})
|
||||
.left_stream()
|
||||
} else {
|
||||
stream::once(future::err(Error::InvalidNickname)).right_stream()
|
||||
};
|
||||
steps.push(resolve_nickname(host.clone()).try_collect().boxed());
|
||||
}
|
||||
steps.push(srv_addresses(lookups.clone(), format!("{DNS_PREFIX_UDP}{host}.")).boxed());
|
||||
steps.push(tsdns(lookups.clone(), host.clone()).boxed());
|
||||
// Interpret as normal address
|
||||
steps.push((lookups.host)(host, DEFAULT_PORT));
|
||||
|
||||
// The system config does not yet work on android:
|
||||
// https://github.com/bluejekyll/trust-dns/issues/652
|
||||
let addr2 = addr.clone();
|
||||
// TODO Move current span into stream
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let resolver = create_resolver()?;
|
||||
|
||||
// Try to get the address by an SRV record
|
||||
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_UDP}{addr2}.")))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// Try to get the address of a tsdns server by an SRV record
|
||||
let addr2 = addr.clone();
|
||||
// TODO Move current span into stream
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let resolver = create_resolver()?;
|
||||
// Trim address to two components
|
||||
let name = if let Some(i) = addr2.rfind('.').and_then(|i| addr2[..i].rfind('.')) {
|
||||
&addr2[i + 1..]
|
||||
} else {
|
||||
&addr2
|
||||
};
|
||||
// Pick the first srv record of the first server that answers
|
||||
Result::<_>::Ok(resolve_srv(resolver, format!("{DNS_PREFIX_TCP}{name}.")).and_then(
|
||||
move |srv| {
|
||||
let address = address.clone();
|
||||
async move {
|
||||
// Got tsdns server
|
||||
let mut addr = resolve_tsdns(srv, &address).await?;
|
||||
if let Some(port) = port {
|
||||
// Overwrite port if it was specified
|
||||
addr.set_port(port);
|
||||
}
|
||||
Ok(addr)
|
||||
}
|
||||
},
|
||||
))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// Interpret as normal address and resolve with system resolver
|
||||
let res = res.chain(
|
||||
stream::once(async move {
|
||||
let res = net::lookup_host((addr.as_str(), port.unwrap_or(DEFAULT_PORT)))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>();
|
||||
Result::<_>::Ok(stream::iter(res))
|
||||
})
|
||||
.try_flatten(),
|
||||
);
|
||||
|
||||
// TODO Move current span into stream
|
||||
tokio_stream::StreamExt::timeout(res, Duration::from_secs(TIMEOUT_SECONDS))
|
||||
.filter_map(move |r: std::result::Result<Result<SocketAddr>, _>| {
|
||||
future::ready(match r {
|
||||
// Timeout
|
||||
Err(_) => None,
|
||||
// Error
|
||||
let count = steps.len();
|
||||
stream::iter(steps)
|
||||
.map(|step| timeout(STEP_TIMEOUT, step))
|
||||
// All at once, the addresses in the order of the steps.
|
||||
.buffered(count)
|
||||
.flat_map(|result| {
|
||||
stream::iter(match result {
|
||||
Ok(Ok(addresses)) => addresses,
|
||||
Ok(Err(error)) => {
|
||||
debug!(%error, "Resolver failed in one step");
|
||||
None
|
||||
Vec::new()
|
||||
}
|
||||
Err(_) => {
|
||||
debug!("Resolver step timed out");
|
||||
Vec::new()
|
||||
}
|
||||
// Success
|
||||
Ok(Ok(r)) => Some(Ok(r)),
|
||||
})
|
||||
})
|
||||
.map(move |mut addr| {
|
||||
if let Some(port) = port {
|
||||
// A port the user gave wins.
|
||||
addr.set_port(port);
|
||||
}
|
||||
Ok(addr)
|
||||
})
|
||||
.right_stream()
|
||||
}
|
||||
|
||||
/// The addresses of the targets of the SRV records at `name`, in their order.
|
||||
async fn srv_addresses(lookups: Lookups, name: String) -> Result<Vec<SocketAddr>> {
|
||||
let mut addresses = Vec::new();
|
||||
for (target, port) in (lookups.srv)(name).await? {
|
||||
match (lookups.host)(target, port).await {
|
||||
Ok(found) => addresses.extend(found),
|
||||
Err(error) => debug!(%error, "SRV target not found"),
|
||||
}
|
||||
}
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
/// Where a TSDNS server for `host` may be, most specific first: the domains
|
||||
/// above `host` down to the last two labels, or `host` itself when it has
|
||||
/// only two (`ts.sub.example.com`: `sub.example.com`, `example.com`).
|
||||
// ponytail: two labels as the floor instead of the public suffix list; under
|
||||
// a `co.uk`-style suffix this also asks the suffix.
|
||||
fn tsdns_domains(host: &str) -> Vec<&str> {
|
||||
fn parent(name: &str) -> Option<&str> { name.split_once('.').map(|(_, parent)| parent) }
|
||||
let mut domains: Vec<&str> =
|
||||
std::iter::successors(parent(host), |d| parent(d)).filter(|d| d.contains('.')).collect();
|
||||
if domains.is_empty() && host.contains('.') {
|
||||
domains.push(host);
|
||||
}
|
||||
domains
|
||||
}
|
||||
|
||||
/// The address a TSDNS server has for `host`. The servers are the ones the
|
||||
/// SRV records at `_tsdns._tcp.<domain>` name or, without such records (as
|
||||
/// the official client does), the ones on the TSDNS port at `host`'s domain
|
||||
/// and its parents. They are asked at once; the first in that order that
|
||||
/// knows `host` answers.
|
||||
async fn tsdns(lookups: Lookups, host: String) -> Result<Vec<SocketAddr>> {
|
||||
let domains = tsdns_domains(&host);
|
||||
let Some(domain) = domains.last() else { return Ok(Vec::new()) };
|
||||
let mut servers = srv_addresses(lookups.clone(), format!("{DNS_PREFIX_TCP}{domain}."))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
let found = future::join_all(
|
||||
domains.iter().map(|d| (lookups.host)(d.to_string(), lookups.tsdns_port)),
|
||||
)
|
||||
.await;
|
||||
servers = found.into_iter().filter_map(|r| r.ok()).flatten().collect();
|
||||
}
|
||||
if servers.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let count = servers.len();
|
||||
let mut answers = stream::iter(servers)
|
||||
.map(|server| timeout(lookups.tsdns_timeout, resolve_tsdns(server, &host)))
|
||||
.buffered(count);
|
||||
let mut error = Error::TsdnsAddressNotFound;
|
||||
while let Some(answer) = answers.next().await {
|
||||
match answer {
|
||||
Ok(Ok(address)) => return Ok(vec![address]),
|
||||
Ok(Err(e)) => error = e,
|
||||
Err(_) => error = Error::Io("tsdns", std::io::ErrorKind::TimedOut.into()),
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
|
||||
// Windows for some reason automatically adds a link-local address to the dns
|
||||
// resolver. These addresses are usually not reachable and should be filtered out.
|
||||
// See: https://superuser.com/questions/638566/strange-value-in-dns-shown-in-ipconfig
|
||||
@@ -330,7 +381,7 @@ pub async fn resolve_tsdns<A: net::ToSocketAddrs>(server: A, addr: &str) -> Resu
|
||||
let mut data = Vec::new();
|
||||
stream.read_to_end(&mut data).await.map_err(|e| Error::Io("tsdns", e))?;
|
||||
|
||||
let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?;
|
||||
let addr = str::from_utf8(&data).map_err(Error::TsdnsParseResponse)?.trim();
|
||||
if addr.starts_with("404") {
|
||||
return Err(Error::TsdnsAddressNotFound);
|
||||
}
|
||||
@@ -340,75 +391,45 @@ pub async fn resolve_tsdns<A: net::ToSocketAddrs>(server: A, addr: &str) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_srv(resolver: TokioResolver, addr: String) -> impl Stream<Item = Result<SocketAddr>> {
|
||||
stream::once(async {
|
||||
let lookup = resolver.srv_lookup(addr).await.map_err(Error::SrvLookup)?;
|
||||
let srvs = lookup
|
||||
.answers()
|
||||
/// The targets and ports of the SRV records at `name`, in the order to try
|
||||
/// them.
|
||||
async fn srv_targets(name: String) -> Result<Vec<(String, u16)>> {
|
||||
let lookup = create_resolver()?.srv_lookup(name).await.map_err(Error::SrvLookup)?;
|
||||
let records = lookup
|
||||
.answers()
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::SRV(srv) => Some((srv.priority, srv.weight, (srv.target.to_ascii(), srv.port))),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Ok(order_srv(records))
|
||||
}
|
||||
|
||||
/// Order SRV records `(priority, weight, record)` as RFC 2782 says: lowest
|
||||
/// priority first, and within one priority at random by weight, where weight
|
||||
/// 0 is picked only rarely before the others.
|
||||
fn order_srv<T>(mut records: Vec<(u16, u16, T)>) -> Vec<T> {
|
||||
// The weight 0 records of a priority first: only a draw of 0 picks them.
|
||||
records.sort_by_key(|(priority, weight, _)| (*priority, *weight != 0));
|
||||
let mut ordered = Vec::with_capacity(records.len());
|
||||
while let Some(&(priority, ..)) = records.first() {
|
||||
let end = records.iter().position(|r| r.0 != priority).unwrap_or(records.len());
|
||||
let total: u32 = records[..end].iter().map(|r| u32::from(r.1)).sum();
|
||||
let mut draw = rand::rng().random_range(0..=total);
|
||||
let pick = records[..end]
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let RData::SRV(srv) = &r.data else { panic!("Unexpected answer") };
|
||||
srv.clone()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let prios = srvs.iter().chunk_by(|srv| srv.priority);
|
||||
let entries = prios.into_iter().sorted_by_key(|(p, _)| *p);
|
||||
|
||||
// Select by weight
|
||||
let mut sorted_entries = Vec::new();
|
||||
for (_, es) in entries {
|
||||
let mut zero_entries = Vec::new();
|
||||
|
||||
// All non-zero entries
|
||||
let mut entries = es
|
||||
.filter_map(|e| {
|
||||
if e.weight == 0 {
|
||||
zero_entries.push(e);
|
||||
None
|
||||
} else {
|
||||
Some(e)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
while !entries.is_empty() {
|
||||
let weight: u32 = entries.iter().map(|e| e.weight as u32).sum();
|
||||
let mut w = rand::rng().random_range(0..=weight);
|
||||
if w == 0 {
|
||||
// Pick the first entry with weight 0
|
||||
if let Some(i) = entries.iter().position(|e| e.weight == 0) {
|
||||
sorted_entries.push(entries.remove(i));
|
||||
}
|
||||
.position(|r| {
|
||||
if draw <= u32::from(r.1) {
|
||||
return true;
|
||||
}
|
||||
for i in 0..entries.len() {
|
||||
let weight = entries[i].weight as u32;
|
||||
if w <= weight {
|
||||
sorted_entries.push(entries.remove(i));
|
||||
break;
|
||||
}
|
||||
w -= weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let res = sorted_entries
|
||||
.into_iter()
|
||||
.map(|e| Ok((e.target.to_ascii(), e.port)))
|
||||
.collect::<Vec<Result<(String, u16)>>>();
|
||||
drop(resolver);
|
||||
Ok(stream::iter(res)
|
||||
.and_then(|(e, port)| async move {
|
||||
let res = net::lookup_host((e.as_str(), port))
|
||||
.await
|
||||
.map_err(Error::ResolveHost)?
|
||||
.map(Ok)
|
||||
.collect::<Vec<_>>();
|
||||
Ok(stream::iter(res))
|
||||
draw -= u32::from(r.1);
|
||||
false
|
||||
})
|
||||
.try_flatten())
|
||||
})
|
||||
.try_flatten()
|
||||
.unwrap_or(0);
|
||||
ordered.push(records.remove(pick).2);
|
||||
}
|
||||
ordered
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -479,6 +500,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs DNS and the internet"]
|
||||
async fn resolve_localhost2() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("localhost".into()).map(|r| r.unwrap()).collect().await;
|
||||
@@ -486,6 +508,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs DNS and the internet"]
|
||||
async fn resolve_example() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("example.com".into()).map(|r| r.unwrap()).collect().await;
|
||||
@@ -493,6 +516,7 @@ mod test {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs DNS and the internet"]
|
||||
async fn resolve_splamy_de() {
|
||||
create_logger();
|
||||
|
||||
@@ -506,9 +530,159 @@ mod test {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "needs DNS and the internet"]
|
||||
async fn resolve_loc() {
|
||||
create_logger();
|
||||
let res: Vec<_> = resolve("loc".into()).map(|r| r.unwrap()).collect().await;
|
||||
assert!(res.contains(&format!("127.0.0.1:{}", DEFAULT_PORT).parse().unwrap()));
|
||||
}
|
||||
|
||||
/// Lookups that never leave this machine: `hosts` maps a name to an ip
|
||||
/// (with the port asked for), `srv` an SRV name to its target and port.
|
||||
fn fake(hosts: &[(&str, &str)], srv: &[(&str, &str, u16)], tsdns_port: u16) -> Lookups {
|
||||
let hosts: Vec<(String, IpAddr)> =
|
||||
hosts.iter().map(|(name, ip)| (name.to_string(), ip.parse().unwrap())).collect();
|
||||
let srv: Vec<(String, String, u16)> = srv
|
||||
.iter()
|
||||
.map(|(name, target, port)| (name.to_string(), target.to_string(), *port))
|
||||
.collect();
|
||||
let missing = || Error::Io("dns", std::io::ErrorKind::NotFound.into());
|
||||
Lookups {
|
||||
srv: Arc::new(move |name| {
|
||||
let found: Vec<_> =
|
||||
srv.iter().filter(|r| r.0 == name).map(|r| (r.1.clone(), r.2)).collect();
|
||||
future::ready(if found.is_empty() { Err(missing()) } else { Ok(found) }).boxed()
|
||||
}),
|
||||
host: Arc::new(move |name, port| {
|
||||
let found: Vec<_> = hosts
|
||||
.iter()
|
||||
.filter(|h| h.0 == name)
|
||||
.map(|h| SocketAddr::new(h.1, port))
|
||||
.collect();
|
||||
future::ready(if found.is_empty() { Err(missing()) } else { Ok(found) }).boxed()
|
||||
}),
|
||||
tsdns_port,
|
||||
tsdns_timeout: Duration::from_millis(500),
|
||||
}
|
||||
}
|
||||
|
||||
/// A TSDNS server on 127.0.0.1 that answers the names in `answers` and
|
||||
/// `404` to others, or with `silent` accepts and never answers (like a
|
||||
/// server behind a firewall that drops the port). Returns its port.
|
||||
async fn fake_tsdns(answers: &'static [(&'static str, &'static str)], silent: bool) -> u16 {
|
||||
let listener = net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
tokio::spawn(async move {
|
||||
let mut asked = [0; 256];
|
||||
let n = socket.read(&mut asked).await.unwrap();
|
||||
if silent {
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
}
|
||||
let asked = str::from_utf8(&asked[..n]).unwrap();
|
||||
let answer = answers.iter().find(|a| a.0 == asked).map_or("404", |a| a.1);
|
||||
socket.write_all(answer.as_bytes()).await.unwrap();
|
||||
});
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
async fn resolved(address: &str, lookups: Lookups) -> Vec<String> {
|
||||
create_logger();
|
||||
let found: Vec<SocketAddr> = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
resolve_with(address.into(), lookups).try_collect(),
|
||||
)
|
||||
.await
|
||||
.expect("resolving takes too long")
|
||||
.unwrap();
|
||||
found.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
/// The official client's log for such a server: `A/AAAA DNS resolve for
|
||||
/// possible TSDNS successful, "example.test"`, `TSDNS found at …:41144
|
||||
/// and queried successfully`.
|
||||
#[tokio::test]
|
||||
async fn tsdns_at_the_domain_without_srv_records() {
|
||||
let port = fake_tsdns(&[("ts.example.test", "192.0.2.10:19987")], false).await;
|
||||
let lookups =
|
||||
fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port);
|
||||
assert_eq!(resolved("ts.example.test", lookups.clone()).await, [
|
||||
"192.0.2.10:19987",
|
||||
"198.51.100.7:9987"
|
||||
]);
|
||||
// A port typed with the address wins over TSDNS and the default.
|
||||
assert_eq!(resolved("ts.example.test:4000", lookups).await, [
|
||||
"192.0.2.10:4000",
|
||||
"198.51.100.7:4000"
|
||||
]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tsdns_that_does_not_know_the_name_leaves_the_plain_address() {
|
||||
let port = fake_tsdns(&[("other.example.test", "192.0.2.10:19987")], false).await;
|
||||
let lookups =
|
||||
fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port);
|
||||
assert_eq!(resolved("ts.example.test", lookups).await, ["198.51.100.7:9987"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_silent_tsdns_server_does_not_hold_up_resolving() {
|
||||
let port = fake_tsdns(&[("ts.example.test", "192.0.2.10:19987")], true).await;
|
||||
let lookups =
|
||||
fake(&[("example.test", "127.0.0.1"), ("ts.example.test", "198.51.100.7")], &[], port);
|
||||
let start = std::time::Instant::now();
|
||||
assert_eq!(resolved("ts.example.test", lookups).await, ["198.51.100.7:9987"]);
|
||||
assert!(start.elapsed() < Duration::from_secs(2), "{:?}", start.elapsed());
|
||||
}
|
||||
|
||||
/// The official order: `_ts3._udp` SRV, then TSDNS, then the address
|
||||
/// itself; and a TSDNS server named by `_tsdns._tcp` SRV is asked instead
|
||||
/// of one at the domain.
|
||||
#[tokio::test]
|
||||
async fn srv_records_come_first_and_name_the_tsdns_server() {
|
||||
let direct = fake_tsdns(&[("ts.example.test", "192.0.2.99:1")], false).await;
|
||||
let named = fake_tsdns(&[("ts.example.test", "192.0.2.20:2000")], false).await;
|
||||
let lookups = fake(
|
||||
&[
|
||||
("example.test", "127.0.0.1"),
|
||||
("tsdns.example.test", "127.0.0.1"),
|
||||
("voice.example.test", "203.0.113.5"),
|
||||
("ts.example.test", "198.51.100.7"),
|
||||
],
|
||||
&[
|
||||
("_ts3._udp.ts.example.test.", "voice.example.test", 9999),
|
||||
("_tsdns._tcp.example.test.", "tsdns.example.test", named),
|
||||
],
|
||||
direct,
|
||||
);
|
||||
assert_eq!(resolved("ts.example.test", lookups).await, [
|
||||
"203.0.113.5:9999",
|
||||
"192.0.2.20:2000",
|
||||
"198.51.100.7:9987"
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsdns_is_looked_for_at_the_parent_domains() {
|
||||
assert_eq!(tsdns_domains("ts.example.test"), ["example.test"]);
|
||||
assert_eq!(tsdns_domains("a.b.example.test"), ["b.example.test", "example.test"]);
|
||||
assert_eq!(tsdns_domains("example.test"), ["example.test"]);
|
||||
assert!(tsdns_domains("localhost").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srv_records_are_ordered_by_priority_and_none_is_lost() {
|
||||
// Weight 0 is the usual weight; such records were dropped before.
|
||||
assert_eq!(order_srv(vec![(0, 0, "only")]), ["only"]);
|
||||
for _ in 0..50 {
|
||||
let ordered = order_srv(vec![(10, 0, "c"), (0, 0, "a"), (0, 5, "b"), (20, 1, "d")]);
|
||||
assert_eq!(ordered.len(), 4);
|
||||
assert!(ordered[..2].contains(&"a") && ordered[..2].contains(&"b"), "{:?}", ordered);
|
||||
assert_eq!(ordered[2..], ["c", "d"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ anyhow = "1"
|
||||
base64 = "0.22"
|
||||
dirs = "6"
|
||||
futures = "0.3"
|
||||
# Finding a server's gateway in DNS (the voice resolver's version).
|
||||
hickory-resolver = "0.26"
|
||||
md5 = "0.8"
|
||||
# Reading the official clients' settings.db when importing identities.
|
||||
rusqlite = { version = "0.40.2", features = ["bundled"] }
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Finding a server's `tsgw` gateway from the server's address, so nobody
|
||||
//! types the gateway's URL.
|
||||
//!
|
||||
//! Like TeamSpeak's own lookup (SRV `_ts3._udp`, then TSDNS), at the
|
||||
//! address's host and then each parent domain down to the last two labels,
|
||||
//! the most specific name first:
|
||||
//!
|
||||
//! - SRV `_tsgws._tcp.<name>`: `wss://<target>:<port><path>`,
|
||||
//! - SRV `_tsgw._tcp.<name>`: `ws://<target>:<port><path>`,
|
||||
//!
|
||||
//! TLS first at the same name; `<path>` is `path=…` from a TXT record at the
|
||||
//! SRV record's name, `/v1` without one. Without any such record, as TSDNS
|
||||
//! has its well-known port, the gateway itself is asked at tsgw's default
|
||||
//! port: `http://<name>:7788/.well-known/tsgw` answers `{"url": "…"}`. For an
|
||||
//! IP address (or `localhost`) only that is tried. What an admin publishes is
|
||||
//! in `docs/gateway-admin.md`.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::future::{BoxFuture, FutureExt, join_all};
|
||||
use hickory_resolver::TokioResolver;
|
||||
use hickory_resolver::config::{CLOUDFLARE, ResolverConfig};
|
||||
use hickory_resolver::net::runtime::TokioRuntimeProvider;
|
||||
use hickory_resolver::proto::rr::RData;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// The port tsgw listens on by default, where it is asked for its URL.
|
||||
pub const DEFAULT_PORT: u16 = 7788;
|
||||
/// Where tsgw serves its WebSocket.
|
||||
const DEFAULT_PATH: &str = "/v1";
|
||||
/// Give up on asking one name's gateway after this long.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
type SrvFn = dyn Fn(String) -> BoxFuture<'static, Vec<(u16, String, u16)>> + Send + Sync;
|
||||
type TxtFn = dyn Fn(String) -> BoxFuture<'static, Vec<String>> + Send + Sync;
|
||||
|
||||
/// Where [`gateway`] gets its answers from; the tests put fakes in.
|
||||
#[derive(Clone)]
|
||||
struct Lookups {
|
||||
/// The SRV records at a name: priority, target, port.
|
||||
srv: Arc<SrvFn>,
|
||||
/// The strings of the TXT records at a name.
|
||||
txt: Arc<TxtFn>,
|
||||
/// Where a gateway is asked for its URL.
|
||||
probe_port: u16,
|
||||
}
|
||||
|
||||
impl Lookups {
|
||||
fn system() -> Self {
|
||||
// The system's resolver, else (Android) a public one, as the voice
|
||||
// connection's resolver does.
|
||||
let resolver = TokioResolver::builder_tokio().and_then(|b| b.build()).or_else(|_| {
|
||||
TokioResolver::builder_with_config(
|
||||
ResolverConfig::udp_and_tcp(&CLOUDFLARE),
|
||||
TokioRuntimeProvider::default(),
|
||||
)
|
||||
.build()
|
||||
});
|
||||
let resolver = resolver.ok();
|
||||
let txt_resolver = resolver.clone();
|
||||
Self {
|
||||
srv: Arc::new(move |name| {
|
||||
let resolver = resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.srv_lookup(name).await.ok()?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::SRV(s) => Some((s.priority, s.target.to_ascii(), s.port)),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
.map(Option::unwrap_or_default)
|
||||
.boxed()
|
||||
}),
|
||||
txt: Arc::new(move |name| {
|
||||
let resolver = txt_resolver.clone();
|
||||
async move {
|
||||
let lookup = resolver?.txt_lookup(name).await.ok()?;
|
||||
Some(
|
||||
lookup
|
||||
.answers()
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::TXT(t) => Some(t.txt_data.iter()),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.map(|s| String::from_utf8_lossy(s).into_owned())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
.map(Option::unwrap_or_default)
|
||||
.boxed()
|
||||
}),
|
||||
probe_port: DEFAULT_PORT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The URL of the gateway of the server at `address` (as a bookmark has it:
|
||||
/// host, host:port, an IP), if one is published.
|
||||
pub async fn gateway(address: &str) -> Option<String> {
|
||||
gateway_with(address, Lookups::system()).await
|
||||
}
|
||||
|
||||
async fn gateway_with(address: &str, lookups: Lookups) -> Option<String> {
|
||||
let host = host_of(address);
|
||||
let names = names(host);
|
||||
if names.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if host.parse::<IpAddr>().is_err()
|
||||
&& host.contains('.')
|
||||
&& let Some(url) = from_srv(&names, &lookups).await
|
||||
{
|
||||
return Some(url);
|
||||
}
|
||||
from_well_known(&names, lookups.probe_port).await
|
||||
}
|
||||
|
||||
/// The host of an address: without the port, the brackets of an IPv6
|
||||
/// address and a final dot.
|
||||
fn host_of(address: &str) -> &str {
|
||||
let address = address.trim();
|
||||
let host = match address.strip_prefix('[') {
|
||||
Some(rest) => rest.split(']').next().unwrap_or(rest),
|
||||
// One colon: host and port; more: an IPv6 address.
|
||||
None if address.matches(':').count() == 1 => address.split(':').next().unwrap_or(address),
|
||||
None => address,
|
||||
};
|
||||
host.trim_end_matches('.')
|
||||
}
|
||||
|
||||
/// The names to look at, most specific first: a host name and its parent
|
||||
/// domains down to the last two labels; an IP address or `localhost` alone;
|
||||
/// nothing for a server nickname.
|
||||
// ponytail: two labels as the floor instead of the public suffix list, as
|
||||
// the voice resolver's TSDNS lookup; under `co.uk`-style suffixes this also
|
||||
// asks the suffix.
|
||||
fn names(host: &str) -> Vec<&str> {
|
||||
if host.parse::<IpAddr>().is_ok() || host == "localhost" {
|
||||
return vec![host];
|
||||
}
|
||||
std::iter::successors(Some(host), |name| name.split_once('.').map(|(_, parent)| parent))
|
||||
.take_while(|name| name.contains('.'))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The URL from SRV records, every name and service asked at once.
|
||||
async fn from_srv(names: &[&str], lookups: &Lookups) -> Option<String> {
|
||||
let queries: Vec<(&str, String)> = names
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
[("wss", format!("_tsgws._tcp.{name}.")), ("ws", format!("_tsgw._tcp.{name}."))]
|
||||
})
|
||||
.collect();
|
||||
let answers = join_all(queries.iter().map(|(_, owner)| (lookups.srv)(owner.clone()))).await;
|
||||
// The first (most specific, TLS first) name with a usable record.
|
||||
let ((scheme, owner), (_, target, port)) =
|
||||
queries.iter().zip(answers).find_map(|(q, records)| {
|
||||
// A target of "." says there is no such service there.
|
||||
let best = records.into_iter().filter(|r| r.1 != ".").min_by_key(|r| r.0)?;
|
||||
Some((q, best))
|
||||
})?;
|
||||
let mut path = (lookups.txt)(owner.clone())
|
||||
.await
|
||||
.into_iter()
|
||||
.find_map(|s| s.strip_prefix("path=").map(str::to_owned))
|
||||
.unwrap_or_else(|| DEFAULT_PATH.to_owned());
|
||||
if !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
}
|
||||
Some(format!("{scheme}://{}:{port}{path}", target.trim_end_matches('.')))
|
||||
}
|
||||
|
||||
/// The URL a gateway gives for itself at one of `names`, all asked at once;
|
||||
/// the most specific that answers wins.
|
||||
async fn from_well_known(names: &[&str], port: u16) -> Option<String> {
|
||||
let answers =
|
||||
join_all(names.iter().map(|name| timeout(PROBE_TIMEOUT, well_known(name, port)))).await;
|
||||
answers.into_iter().find_map(|answer| answer.ok().flatten())
|
||||
}
|
||||
|
||||
/// tsgw's answer at `http://<host>:<port>/.well-known/tsgw`.
|
||||
async fn well_known(host: &str, port: u16) -> Option<String> {
|
||||
let mut stream = TcpStream::connect((host, port)).await.ok()?;
|
||||
let authority =
|
||||
if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let request =
|
||||
format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {authority}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).await.ok()?;
|
||||
let mut response = Vec::new();
|
||||
stream.take(16 * 1024).read_to_end(&mut response).await.ok()?;
|
||||
let response = String::from_utf8(response).ok()?;
|
||||
let (head, body) = response.split_once("\r\n\r\n")?;
|
||||
if head.split_whitespace().nth(1) != Some("200") {
|
||||
return None;
|
||||
}
|
||||
let answer: serde_json::Value = serde_json::from_str(body).ok()?;
|
||||
let url = answer.get("url")?.as_str()?;
|
||||
(url.starts_with("ws://") || url.starts_with("wss://")).then(|| url.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// DNS answers from these lists only: SRV `(name, priority, target,
|
||||
/// port)`, TXT `(name, string)`.
|
||||
fn fake(srv: &[(&str, u16, &str, u16)], txt: &[(&str, &str)], probe_port: u16) -> Lookups {
|
||||
let srv: Vec<(String, u16, String, u16)> =
|
||||
srv.iter().map(|(n, p, t, port)| (n.to_string(), *p, t.to_string(), *port)).collect();
|
||||
let txt: Vec<(String, String)> =
|
||||
txt.iter().map(|(n, s)| (n.to_string(), s.to_string())).collect();
|
||||
Lookups {
|
||||
srv: Arc::new(move |name| {
|
||||
let found =
|
||||
srv.iter().filter(|r| r.0 == name).map(|r| (r.1, r.2.clone(), r.3)).collect();
|
||||
futures::future::ready(found).boxed()
|
||||
}),
|
||||
txt: Arc::new(move |name| {
|
||||
let found = txt.iter().filter(|r| r.0 == name).map(|r| r.1.clone()).collect();
|
||||
futures::future::ready(found).boxed()
|
||||
}),
|
||||
probe_port,
|
||||
}
|
||||
}
|
||||
|
||||
/// A port nothing listens on.
|
||||
fn closed_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn finds_the_gateway_at_the_host_or_its_domain() {
|
||||
let lookups = fake(&[("_tsgw._tcp.example.test.", 0, "gw.example.test.", 7788)], &[], 0);
|
||||
for address in ["ts.example.test", "ts.example.test:9987", "example.test"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("ws://gw.example.test:7788/v1"),
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// The parent's parent is not the domain any more.
|
||||
assert_eq!(gateway_with("example", lookups).await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_most_specific_name_wins_then_tls() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgws._tcp.example.test.", 0, "domain.example.test.", 443),
|
||||
("_tsgw._tcp.ts.example.test.", 0, "plain.example.test.", 7788),
|
||||
("_tsgws._tcp.ts.example.test.", 5, "backup.example.test.", 443),
|
||||
("_tsgws._tcp.ts.example.test.", 1, "tls.example.test.", 8443),
|
||||
],
|
||||
&[("_tsgws._tcp.ts.example.test.", "path=/tsgw/v1")],
|
||||
0,
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups.clone()).await.as_deref(),
|
||||
Some("wss://tls.example.test:8443/tsgw/v1")
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("voice.example.test", lookups).await.as_deref(),
|
||||
Some("wss://domain.example.test:443/v1")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_record_that_says_no_service_is_skipped() {
|
||||
let lookups = fake(
|
||||
&[
|
||||
("_tsgw._tcp.ts.example.test.", 0, ".", 0),
|
||||
("_tsgw._tcp.example.test.", 0, "gw.example.test.", 80),
|
||||
],
|
||||
&[("_tsgw._tcp.example.test.", "path=ws")],
|
||||
closed_port(),
|
||||
);
|
||||
assert_eq!(
|
||||
gateway_with("ts.example.test", lookups).await.as_deref(),
|
||||
Some("ws://gw.example.test:80/ws")
|
||||
);
|
||||
}
|
||||
|
||||
/// Without records the gateway next to the server answers at its port,
|
||||
/// as tsgw does (`/.well-known/tsgw`).
|
||||
#[tokio::test]
|
||||
async fn without_records_the_gateway_itself_is_asked() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0; 1024];
|
||||
let n = socket.read(&mut request).await.unwrap();
|
||||
let request = String::from_utf8_lossy(&request[..n]).into_owned();
|
||||
let response = if request.starts_with("GET /.well-known/tsgw ") {
|
||||
let body = r#"{"url":"wss://gw.example.test/v1"}"#;
|
||||
format!("HTTP/1.1 200 OK\r\ncontent-length: {}\r\n\r\n{body}", body.len())
|
||||
} else {
|
||||
"HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\n\r\n".to_owned()
|
||||
};
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
});
|
||||
let lookups = fake(&[], &[], port);
|
||||
for address in ["127.0.0.1", "127.0.0.1:9987", "localhost"] {
|
||||
assert_eq!(
|
||||
gateway_with(address, lookups.clone()).await.as_deref(),
|
||||
Some("wss://gw.example.test/v1"),
|
||||
"{address}"
|
||||
);
|
||||
}
|
||||
// Nothing there.
|
||||
assert_eq!(gateway_with("127.0.0.1", fake(&[], &[], closed_port())).await, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_walk_up_to_the_domain() {
|
||||
assert_eq!(
|
||||
names(host_of("ts.sub.example.test:9987")),
|
||||
["ts.sub.example.test", "sub.example.test", "example.test"]
|
||||
);
|
||||
assert_eq!(names(host_of("[::1]:9987")), ["::1"]);
|
||||
assert_eq!(names(host_of("::1")), ["::1"]);
|
||||
assert_eq!(names(host_of("example.test.")), ["example.test"]);
|
||||
// A server nickname is resolved by TeamSpeak, not in DNS.
|
||||
assert!(names(host_of("nickname")).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ use voelin_gateway_proto::UniqueIds;
|
||||
use voelin_store::Store;
|
||||
|
||||
/// Name given to an identity whose source kept none.
|
||||
const DEFAULT_NICKNAME: &str = "imported";
|
||||
pub const DEFAULT_NICKNAME: &str = "imported";
|
||||
|
||||
/// Item field holding the item's type; the payload is in field
|
||||
/// [`PAYLOAD_FIELD_BASE`] `+ type`.
|
||||
@@ -76,6 +76,8 @@ pub struct Found {
|
||||
pub identity: Identity,
|
||||
/// The file it came from.
|
||||
pub source: PathBuf,
|
||||
/// The identity the other client uses by default (payload field 5).
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
@@ -171,6 +173,26 @@ pub fn import(store: &Store, found: &[Found]) -> Result<Vec<Imported>, IdentityE
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Store the identities in the official clients' files at `paths` (usually
|
||||
/// [`discover`]) that the store does not have yet, as the app does when it
|
||||
/// starts. Files that cannot be read or hold no identity are skipped; none is
|
||||
/// written. The identities the clients use by default go in first, so on a
|
||||
/// store without identities the official client's default becomes ours (the
|
||||
/// first identity) and servers see the same unique id. Returns what was
|
||||
/// added.
|
||||
pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<Vec<Found>, IdentityError> {
|
||||
let mut found: Vec<Found> = paths.iter().filter_map(|path| read(path).ok()).flatten().collect();
|
||||
// Stable: TeamSpeak 6's default before TeamSpeak 3's, as `locations` lists them.
|
||||
found.sort_by_key(|f| !f.selected);
|
||||
let outcomes = import(store, &found)?;
|
||||
Ok(found
|
||||
.into_iter()
|
||||
.zip(outcomes)
|
||||
.filter(|(_, outcome)| matches!(outcome, Imported::Added(_)))
|
||||
.map(|(f, _)| f)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -326,7 +348,7 @@ fn record_identity(record: &[(String, String)], source: &Path) -> Option<Found>
|
||||
let identity = Identity::new_from_ts_str(find("identity")?).ok()?;
|
||||
let nickname = find("nickname").or_else(|| find("id")).unwrap_or_default();
|
||||
let nickname = if nickname.is_empty() { DEFAULT_NICKNAME } else { nickname }.to_owned();
|
||||
Some(Found { nickname, identity, source: source.to_owned() })
|
||||
Some(Found { nickname, identity, source: source.to_owned(), selected: false })
|
||||
}
|
||||
|
||||
/// The identity payload of a `ProtobufItems` item, or `None` if the item is
|
||||
@@ -347,22 +369,27 @@ fn identity_payload(item: &[u8]) -> Option<&[u8]> {
|
||||
payload.filter(|_| kind == Some(IDENTITY_TYPE))
|
||||
}
|
||||
|
||||
/// The export string is field 1 of the identity payload, the nickname field 2.
|
||||
/// The export string is field 1 of the identity payload, the nickname field 2,
|
||||
/// and field 5 is 1 on the identity the client uses by default.
|
||||
fn payload_identity(payload: &[u8], source: &Path) -> Option<Found> {
|
||||
let mut export = None;
|
||||
let mut nickname = None;
|
||||
let mut selected = false;
|
||||
let mut wire = Wire { rest: payload };
|
||||
while let Some((number, Field::Bytes(bytes))) = wire.next_field() {
|
||||
match number {
|
||||
1 => export = str::from_utf8(bytes).ok(),
|
||||
2 => nickname = Some(String::from_utf8_lossy(bytes).into_owned()),
|
||||
while let Some((number, field)) = wire.next_field() {
|
||||
match (number, field) {
|
||||
(1, Field::Bytes(bytes)) => export = str::from_utf8(bytes).ok(),
|
||||
(2, Field::Bytes(bytes)) => {
|
||||
nickname = Some(String::from_utf8_lossy(bytes).into_owned())
|
||||
}
|
||||
(5, Field::Var(value)) => selected = value == 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let identity = Identity::new_from_ts_str(export?).ok()?;
|
||||
let nickname =
|
||||
nickname.filter(|n| !n.is_empty()).unwrap_or_else(|| DEFAULT_NICKNAME.to_owned());
|
||||
Some(Found { nickname, identity, source: source.to_owned() })
|
||||
Some(Found { nickname, identity, source: source.to_owned(), selected })
|
||||
}
|
||||
|
||||
/// A protobuf field's value. Fixed-width fields carry nothing we read; they
|
||||
@@ -472,13 +499,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// An item of the shape both clients write, holding `identity`.
|
||||
fn protobuf_item(identity: &Identity, nickname: &str) -> Vec<u8> {
|
||||
/// An item of the shape both clients write, holding `identity`; `selected`
|
||||
/// is the client's default.
|
||||
fn protobuf_item(identity: &Identity, nickname: &str, selected: bool) -> Vec<u8> {
|
||||
let export = format!("{}V{}", identity.counter(), identity.key().to_ts_obfuscated());
|
||||
let mut payload = bytes_field(1, export.as_bytes());
|
||||
payload.extend(bytes_field(2, nickname.as_bytes()));
|
||||
payload.extend(bytes_field(3, b"a1b2c3d4"));
|
||||
payload.extend(varint_field(5, 1));
|
||||
payload.extend(varint_field(5, u64::from(selected)));
|
||||
let mut item = bytes_field(2, b"4a7b4f46-0000-4000-8000-000000000001");
|
||||
item.extend(varint_field(TYPE_FIELD, IDENTITY_TYPE));
|
||||
item.extend(varint_field(9, 1_700_000_000));
|
||||
@@ -576,7 +604,7 @@ mod tests {
|
||||
mismatched.extend(bytes_field(PAYLOAD_FIELD_BASE, b"not an identity"));
|
||||
for (key, value) in [
|
||||
("1", other),
|
||||
("2", protobuf_item(&identity, "Имя")),
|
||||
("2", protobuf_item(&identity, "Имя", true)),
|
||||
("3", mismatched),
|
||||
("Checksum", vec![0; 20]),
|
||||
] {
|
||||
@@ -588,6 +616,52 @@ mod tests {
|
||||
// A non-ASCII nickname survives.
|
||||
assert_eq!(found[0].nickname, "Имя");
|
||||
assert_eq!(found[0].uid(), identity.key().to_pub().get_uid());
|
||||
assert!(found[0].selected);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// A `settings.db` as the official clients write it, with these
|
||||
/// identities.
|
||||
fn client_database(path: &Path, items: &[(&Identity, &str, bool)]) {
|
||||
let db = Connection::open(path).unwrap();
|
||||
db.execute_batch(
|
||||
"CREATE TABLE ProtobufItems (timestamp integer unsigned NOT NULL,
|
||||
key varchar NOT NULL UNIQUE, value varchar)",
|
||||
)
|
||||
.unwrap();
|
||||
for (key, (identity, nickname, selected)) in items.iter().enumerate() {
|
||||
let item = protobuf_item(identity, nickname, *selected);
|
||||
db.execute("INSERT INTO ProtobufItems VALUES (0, ?1, ?2)", (key.to_string(), item))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_import_makes_the_clients_default_ours_and_adds_only_new_ones() {
|
||||
let dir = temp_dir("launch");
|
||||
let ts6 = dir.join("ts6.db");
|
||||
let ts3 = dir.join("ts3.db");
|
||||
let (spare, main, old) = (synthetic(), synthetic(), synthetic());
|
||||
// The default identity is not the first item.
|
||||
client_database(&ts6, &[(&spare, "Spare", false), (&main, "Main", true)]);
|
||||
let missing = dir.join("missing.db");
|
||||
let store = Store::open_in_memory().unwrap();
|
||||
|
||||
let added = import_new(&store, &[ts6.clone(), missing.clone()]).unwrap();
|
||||
let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect();
|
||||
assert_eq!(nicknames, ["Main", "Spare"]);
|
||||
// The first identity is the app's default: the client's default.
|
||||
assert_eq!(store.identities().unwrap()[0].uid, main.key().to_pub().get_uid());
|
||||
|
||||
// The next start finds only what is new.
|
||||
client_database(&ts3, &[(&old, "Old", true), (&main, "Main", true)]);
|
||||
let added = import_new(&store, &[ts6, ts3, missing]).unwrap();
|
||||
let nicknames: Vec<_> = added.iter().map(|f| f.nickname.as_str()).collect();
|
||||
assert_eq!(nicknames, ["Old"]);
|
||||
let stored = store.identities().unwrap();
|
||||
assert_eq!(stored.len(), 3);
|
||||
// A store that has identities keeps its default.
|
||||
assert_eq!(stored[0].uid, main.key().to_pub().get_uid());
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
@@ -599,6 +673,7 @@ mod tests {
|
||||
nickname: nickname.to_owned(),
|
||||
identity: identity.clone(),
|
||||
source: PathBuf::from("test.ini"),
|
||||
selected: false,
|
||||
};
|
||||
// The same unique id twice in one batch, then again in a second run.
|
||||
let outcome = import(&store, &[found("first"), found("again")]).unwrap();
|
||||
|
||||
@@ -46,6 +46,7 @@ mod audio;
|
||||
mod book;
|
||||
pub mod cache;
|
||||
pub mod contacts;
|
||||
pub mod discover;
|
||||
pub mod files;
|
||||
pub mod gateway;
|
||||
pub mod history;
|
||||
|
||||
+351
-41
@@ -16,8 +16,11 @@
|
||||
//! sink allows. [`Streamer::reconfigure`] changes frame rate, bitrate,
|
||||
//! codec, layers and audio sources while streaming.
|
||||
//! - [`VideoPipeline`] decodes the video of a watched stream on its own
|
||||
//! thread and hands every picture to a callback. After lost frames or
|
||||
//! decoder errors it skips to the next keyframe and asks for one.
|
||||
//! thread with the best decoder of its codec, falling back to the next
|
||||
//! one when a decoder fails, and hands every picture to a callback. After
|
||||
//! lost frames it asks for a keyframe; decoders that conceal what is
|
||||
//! missing (FFmpeg's H.264 and HEVC) go on decoding meanwhile, the others
|
||||
//! skip to it.
|
||||
//! - [`Viewer`] is a [`VideoPipeline`] fed from [`Engine::subscribe_frames`].
|
||||
//! The stream's audio needs nothing here: the session plays it
|
||||
//! ([`Command::SetStreamVolume`]).
|
||||
@@ -59,7 +62,7 @@ use voelin_media::{
|
||||
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
|
||||
VideoFrame,
|
||||
};
|
||||
pub use voelin_media::{EncoderBackend, EncoderPreference};
|
||||
pub use voelin_media::{DecoderBackend, DecoderPreference, EncoderBackend, EncoderPreference};
|
||||
use voelin_stream::{
|
||||
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
|
||||
MediaTime, PeerConfig, VideoCodec,
|
||||
@@ -79,6 +82,17 @@ const OPUS_BITRATE: i32 = 128_000;
|
||||
pub const MAX_QUEUED: usize = 30;
|
||||
/// Keyframe requests while waiting for one are at least this far apart.
|
||||
const KEYFRAME_RETRY: Duration = Duration::from_millis(500);
|
||||
/// Failures in a row (errors, or [`FRAMES_WITHOUT_PICTURE`] frames that
|
||||
/// gave none) after which a decoder is replaced by the next one of its
|
||||
/// codec's ladder.
|
||||
const DECODER_FAILURES: u32 = 3;
|
||||
/// Frames a decoder may take without giving a picture before that counts
|
||||
/// as a failure (and a keyframe is asked for): decoders of streams with
|
||||
/// B-frames hold a few.
|
||||
const FRAMES_WITHOUT_PICTURE: u32 = 10;
|
||||
/// Decoded pictures a [`VideoPipeline`] recycles; while the consumer holds
|
||||
/// them all, more are made.
|
||||
const PICTURE_POOL: usize = 4;
|
||||
/// The decoding rates of [`DecodeStats`] cover at least this long.
|
||||
const RATE_WINDOW: Duration = Duration::from_millis(500);
|
||||
|
||||
@@ -188,6 +202,16 @@ pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media:
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder preference of the settings `stream.hardware_decoding` and
|
||||
/// `stream.decoder_backend` (for `Codecs::with_decoder_preference`).
|
||||
pub fn decoder_preference(settings: &crate::settings::Settings) -> DecoderPreference {
|
||||
use crate::settings::{STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING};
|
||||
DecoderPreference {
|
||||
hardware: settings.get(&STREAM_HARDWARE_DECODING),
|
||||
backend: settings.get(&STREAM_DECODER_BACKEND).parse().unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stream codec: `configured` if we can encode it, else the first codec
|
||||
/// of the encoder preference (hardware first when enabled; VP8 through
|
||||
/// libvpx without hardware) that every TeamSpeak client decodes
|
||||
@@ -2530,6 +2554,9 @@ pub struct DecodeStats {
|
||||
pub skipped: u64,
|
||||
pub keyframe_requests: u64,
|
||||
pub codec: Option<Codec>,
|
||||
/// The decoder in use ([`Codecs::decoders_for`]: the first of the
|
||||
/// codec's that works).
|
||||
pub decoder: Option<DecoderBackend>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The last error (no decoder for the codec, decoding failed).
|
||||
@@ -2608,12 +2635,14 @@ pub struct VideoPipeline {
|
||||
}
|
||||
|
||||
impl VideoPipeline {
|
||||
/// `on_frame` gets every decoded picture on the decoding thread;
|
||||
/// `request_keyframe` is called when the decoder needs one (at most
|
||||
/// every half second).
|
||||
/// `on_frame` gets every decoded picture on the decoding thread, from a
|
||||
/// pool: a picture comes back to it once the consumer drops it, so a
|
||||
/// consumer that converts and drops each one costs no allocations.
|
||||
/// `request_keyframe` is called when the decoder needs one (every half
|
||||
/// second until one comes).
|
||||
pub fn new(
|
||||
codecs: Arc<Codecs>,
|
||||
on_frame: impl FnMut(VideoFrame) + Send + 'static,
|
||||
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
|
||||
request_keyframe: impl Fn() + Send + 'static,
|
||||
) -> Self {
|
||||
let queue = Arc::new(DecodeQueue::default());
|
||||
@@ -2664,16 +2693,112 @@ impl Drop for VideoPipeline {
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder of a [`VideoPipeline`] and the rest of its codec's ladder.
|
||||
struct ActiveDecoder {
|
||||
codec: Codec,
|
||||
backend: DecoderBackend,
|
||||
decoder: Box<dyn voelin_media::VideoDecoder>,
|
||||
/// The codec's other decoders, best first, still to try.
|
||||
rest: VecDeque<DecoderBackend>,
|
||||
/// Failures since the last picture.
|
||||
failures: u32,
|
||||
/// Frames taken since the last picture or failure.
|
||||
without_picture: u32,
|
||||
/// It failed with no other decoder left (logged once).
|
||||
last_failed: bool,
|
||||
}
|
||||
|
||||
impl ActiveDecoder {
|
||||
/// The first decoder of `codec`'s ladder that opens.
|
||||
fn start(codecs: &Codecs, codec: Codec) -> Result<Self, String> {
|
||||
let mut rest: VecDeque<DecoderBackend> = codecs.decoders_for(codec).into();
|
||||
let (backend, decoder) = Self::open_next(codecs, codec, &mut rest).map_err(|e| {
|
||||
e.unwrap_or_else(|| {
|
||||
codecs
|
||||
.check_decoder(codec)
|
||||
.err()
|
||||
.map_or_else(|| format!("no decoder for {codec}"), |e| e.to_string())
|
||||
})
|
||||
})?;
|
||||
Ok(Self {
|
||||
codec,
|
||||
backend,
|
||||
decoder,
|
||||
rest,
|
||||
failures: 0,
|
||||
without_picture: 0,
|
||||
last_failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The next decoder of `rest` that opens; the last error if none did.
|
||||
fn open_next(
|
||||
codecs: &Codecs,
|
||||
codec: Codec,
|
||||
rest: &mut VecDeque<DecoderBackend>,
|
||||
) -> Result<(DecoderBackend, Box<dyn voelin_media::VideoDecoder>), Option<String>> {
|
||||
let mut error = None;
|
||||
while let Some(backend) = rest.pop_front() {
|
||||
match codecs.new_decoder_with(codec, backend) {
|
||||
Ok(decoder) => return Ok((backend, decoder)),
|
||||
Err(e) => {
|
||||
warn!(%codec, %backend, "the decoder does not open: {e}");
|
||||
error = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
|
||||
/// Replace the decoder by the next one of the ladder, after `reason`;
|
||||
/// `false` (keeping this one) if there is none.
|
||||
fn fall_back(&mut self, codecs: &Codecs, reason: &str) -> bool {
|
||||
(self.failures, self.without_picture) = (0, 0);
|
||||
let (codec, failed) = (self.codec, self.backend);
|
||||
match Self::open_next(codecs, codec, &mut self.rest) {
|
||||
Ok((backend, decoder)) => {
|
||||
warn!(%codec, %failed, %backend, "the decoder failed ({reason}); trying the next");
|
||||
(self.backend, self.decoder) = (backend, decoder);
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
if !std::mem::replace(&mut self.last_failed, true) {
|
||||
warn!(%codec, %failed, "the decoder fails ({reason}), and no other is left");
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pooled picture nobody else holds, to decode into: one the consumer
|
||||
/// gave back, else a new one (when the pool is full, the oldest is left to
|
||||
/// whoever holds it).
|
||||
fn free_picture(pictures: &mut Vec<Arc<VideoFrame>>) -> usize {
|
||||
if let Some(i) = pictures.iter_mut().position(|p| Arc::get_mut(p).is_some()) {
|
||||
return i;
|
||||
}
|
||||
if pictures.len() >= PICTURE_POOL {
|
||||
pictures.remove(0);
|
||||
}
|
||||
pictures.push(Arc::new(VideoFrame::black_i420(0, 0)));
|
||||
pictures.len() - 1
|
||||
}
|
||||
|
||||
fn decode_loop(
|
||||
queue: &DecodeQueue,
|
||||
codecs: &Codecs,
|
||||
mut on_frame: impl FnMut(VideoFrame),
|
||||
mut on_frame: impl FnMut(Arc<VideoFrame>),
|
||||
request_keyframe: impl Fn(),
|
||||
) {
|
||||
let mut decoder: Option<(Codec, Box<dyn voelin_media::VideoDecoder>)> = None;
|
||||
let mut active: Option<ActiveDecoder> = None;
|
||||
// Start at a keyframe; the streamer sends one when a viewer connects.
|
||||
let mut waiting = true;
|
||||
// A keyframe is wanted (after a loss, or an error of a decoder that goes
|
||||
// on), asked for until one decodes.
|
||||
let mut wanted = false;
|
||||
let mut last_request: Option<Instant> = None;
|
||||
let mut pictures: Vec<Arc<VideoFrame>> = Vec::with_capacity(PICTURE_POOL);
|
||||
let mut request = |stats: &Mutex<DecodeStats>| {
|
||||
if last_request.is_none_or(|t| t.elapsed() >= KEYFRAME_RETRY) {
|
||||
last_request = Some(Instant::now());
|
||||
@@ -2683,19 +2808,22 @@ fn decode_loop(
|
||||
};
|
||||
let set_error = |message: String| lock(&queue.stats).error = Some(message);
|
||||
loop {
|
||||
let (frame, lost) = {
|
||||
let next = {
|
||||
let mut state = lock(&queue.state);
|
||||
loop {
|
||||
if state.closed {
|
||||
return;
|
||||
}
|
||||
if let Some(frame) = state.frames.pop_front() {
|
||||
break (frame, std::mem::take(&mut state.lost));
|
||||
}
|
||||
if state.frames.is_empty() && !state.closed {
|
||||
state =
|
||||
queue.cond.wait_timeout(state, POLL).unwrap_or_else(PoisonError::into_inner).0;
|
||||
}
|
||||
if state.closed {
|
||||
return;
|
||||
}
|
||||
state.frames.pop_front().map(|frame| (frame, std::mem::take(&mut state.lost)))
|
||||
};
|
||||
// Asked for again while none comes, even while no frame does.
|
||||
if (waiting || wanted) && active.is_some() {
|
||||
request(&queue.stats);
|
||||
}
|
||||
let Some((frame, lost)) = next else { continue };
|
||||
let codec = match Codec::try_from(frame.codec) {
|
||||
Ok(codec) => codec,
|
||||
Err(e) => {
|
||||
@@ -2703,51 +2831,95 @@ fn decode_loop(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if decoder.as_ref().is_none_or(|(c, _)| *c != codec) {
|
||||
match codecs.new_decoder(codec) {
|
||||
Ok(d) => {
|
||||
decoder = Some((codec, d));
|
||||
if active.as_ref().is_none_or(|a| a.codec != codec) {
|
||||
match ActiveDecoder::start(codecs, codec) {
|
||||
Ok(started) => {
|
||||
let mut stats = lock(&queue.stats);
|
||||
(stats.codec, stats.decoder) = (Some(codec), Some(started.backend));
|
||||
drop(stats);
|
||||
active = Some(started);
|
||||
waiting = true;
|
||||
lock(&queue.stats).codec = Some(codec);
|
||||
}
|
||||
Err(e) => {
|
||||
if decoder.is_some() || lock(&queue.stats).error.is_none() {
|
||||
if active.is_some() || lock(&queue.stats).error.is_none() {
|
||||
warn!("no decoder for the stream: {e}");
|
||||
}
|
||||
decoder = None;
|
||||
set_error(e.to_string());
|
||||
active = None;
|
||||
set_error(e);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(dec) = &mut active else { continue };
|
||||
if lost || !frame.contiguous {
|
||||
waiting = true;
|
||||
// A decoder that conceals the loss goes on; the others would
|
||||
// fail, or show garbage, until a keyframe.
|
||||
if dec.decoder.conceals_errors() {
|
||||
wanted = true;
|
||||
} else {
|
||||
waiting = true;
|
||||
}
|
||||
}
|
||||
let keyframe = is_keyframe(codec, &frame.data);
|
||||
if waiting {
|
||||
if !is_keyframe(codec, &frame.data) {
|
||||
if !keyframe {
|
||||
lock(&queue.stats).skipped += 1;
|
||||
request(&queue.stats);
|
||||
continue;
|
||||
}
|
||||
waiting = false;
|
||||
}
|
||||
let Some((_, dec)) = &mut decoder else { continue };
|
||||
match dec.decode(&frame.data) {
|
||||
Ok(Some(picture)) => {
|
||||
{
|
||||
let mut stats = lock(&queue.stats);
|
||||
stats.decoded += 1;
|
||||
(stats.width, stats.height) = (picture.width, picture.height);
|
||||
loop {
|
||||
let slot = free_picture(&mut pictures);
|
||||
let picture = Arc::get_mut(&mut pictures[slot]).expect("a free picture");
|
||||
let failure = match dec.decoder.decode_into(&frame.data, picture) {
|
||||
Ok(true) => {
|
||||
(dec.failures, dec.without_picture) = (0, 0);
|
||||
wanted &= !keyframe;
|
||||
{
|
||||
let mut stats = lock(&queue.stats);
|
||||
stats.decoded += 1;
|
||||
(stats.width, stats.height) = (picture.width, picture.height);
|
||||
}
|
||||
on_frame(pictures[slot].clone());
|
||||
None
|
||||
}
|
||||
on_frame(picture);
|
||||
Ok(false) => {
|
||||
// Decoders with a delay (B-frames) give it a few frames
|
||||
// later; one that gives nothing gets keyframes to try.
|
||||
dec.without_picture += 1;
|
||||
(dec.without_picture >= FRAMES_WITHOUT_PICTURE).then(|| {
|
||||
dec.without_picture = 0;
|
||||
wanted = true;
|
||||
request(&queue.stats);
|
||||
format!("no picture from {FRAMES_WITHOUT_PICTURE} frames")
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
debug!("decoding failed: {e}");
|
||||
set_error(e.to_string());
|
||||
if dec.decoder.conceals_errors() {
|
||||
wanted = true;
|
||||
} else {
|
||||
waiting = true;
|
||||
}
|
||||
request(&queue.stats);
|
||||
Some(e.to_string())
|
||||
}
|
||||
};
|
||||
let Some(reason) = failure else { break };
|
||||
dec.failures += 1;
|
||||
if dec.failures < DECODER_FAILURES || !dec.fall_back(codecs, &reason) {
|
||||
break;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
debug!("decoding failed: {e}");
|
||||
set_error(e.to_string());
|
||||
lock(&queue.stats).decoder = Some(dec.backend);
|
||||
if !keyframe {
|
||||
waiting = true;
|
||||
request(&queue.stats);
|
||||
break;
|
||||
}
|
||||
// The keyframe that failed starts the next decoder at once.
|
||||
waiting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2766,7 +2938,7 @@ impl Viewer {
|
||||
session: SessionId,
|
||||
stream_id: &str,
|
||||
codecs: Arc<Codecs>,
|
||||
on_frame: impl FnMut(VideoFrame) + Send + 'static,
|
||||
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
|
||||
) -> Self {
|
||||
let request = {
|
||||
let engine = engine.clone();
|
||||
@@ -2883,7 +3055,7 @@ impl LocalPreview {
|
||||
pub async fn start(
|
||||
codecs: Arc<Codecs>,
|
||||
mut config: StreamerConfig,
|
||||
on_frame: impl FnMut(VideoFrame) + Send + 'static,
|
||||
on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static,
|
||||
) -> Result<Self, MediaError> {
|
||||
// The audio would go nowhere.
|
||||
config.audio = false;
|
||||
@@ -3218,6 +3390,144 @@ mod tests {
|
||||
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
|
||||
}
|
||||
|
||||
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
|
||||
/// no picture), or gives a 2x2 picture per frame; conceals losses or not.
|
||||
#[derive(Clone, Copy)]
|
||||
struct FakeDecoder {
|
||||
errors: bool,
|
||||
pictures: bool,
|
||||
conceals: bool,
|
||||
}
|
||||
|
||||
impl voelin_media::VideoDecoder for FakeDecoder {
|
||||
fn codec(&self) -> Codec {
|
||||
Codec::Vp8
|
||||
}
|
||||
|
||||
fn decode(&mut self, _: &[u8]) -> voelin_media::Result<Option<VideoFrame>> {
|
||||
if self.errors {
|
||||
let message = "made to fail".into();
|
||||
return Err(voelin_media::Error::Decoder { codec: Codec::Vp8, message });
|
||||
}
|
||||
Ok(self.pictures.then(|| VideoFrame::black_i420(2, 2)))
|
||||
}
|
||||
|
||||
fn conceals_errors(&self) -> bool {
|
||||
self.conceals
|
||||
}
|
||||
}
|
||||
|
||||
impl voelin_media::codec::hw::DecoderFactory for FakeDecoder {
|
||||
fn backend(&self) -> DecoderBackend {
|
||||
DecoderBackend::Hardware("fake")
|
||||
}
|
||||
|
||||
fn codec(&self) -> Codec {
|
||||
Codec::Vp8
|
||||
}
|
||||
|
||||
fn api(&self) -> &'static str {
|
||||
"test"
|
||||
}
|
||||
|
||||
fn is_hardware(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn create(&self) -> voelin_media::Result<Box<dyn voelin_media::VideoDecoder>> {
|
||||
Ok(Box::new(*self))
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoder that fails, with errors or by giving no picture from
|
||||
/// several keyframes, is replaced by the next of its codec's ladder
|
||||
/// (libvpx here) without ending the stream: pictures go on.
|
||||
#[cfg(feature = "media-desktop")]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failing_decoder_is_replaced_by_the_next() {
|
||||
for errors in [true, false] {
|
||||
let fake = FakeDecoder { errors, pictures: false, conceals: false };
|
||||
let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake)));
|
||||
assert_eq!(codecs.decoders_for(Codec::Vp8)[0], DecoderBackend::Hardware("fake"));
|
||||
assert_eq!(codecs.decoders_for(Codec::Vp8).last(), Some(&DecoderBackend::Libvpx));
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (320, 240),
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let (tx, rx) = std_mpsc::channel();
|
||||
let preview = LocalPreview::start(codecs, config, move |picture| {
|
||||
let _ = tx.send(picture);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..10 {
|
||||
let picture = rx.recv_timeout(Duration::from_secs(10)).expect("no picture");
|
||||
assert_eq!((picture.width, picture.height), (320, 240));
|
||||
}
|
||||
let stats = preview.stats();
|
||||
assert_eq!(stats.decoder, Some(DecoderBackend::Libvpx), "errors {errors}: {stats:?}");
|
||||
assert!(stats.keyframe_requests > 0, "{stats:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// After a lost frame a decoder that conceals the loss goes on decoding
|
||||
/// while a keyframe is asked for, again every half second until one
|
||||
/// comes; one that does not skips to the keyframe.
|
||||
#[test]
|
||||
fn losses_ask_for_keyframes_until_one_comes() {
|
||||
for conceals in [true, false] {
|
||||
let fake = FakeDecoder { errors: false, pictures: true, conceals };
|
||||
let codecs = Arc::new(Codecs::builtin().with_decoder(Arc::new(fake)));
|
||||
let (tx, pictures) = std_mpsc::channel();
|
||||
let requests = Arc::new(AtomicU32::new(0));
|
||||
let pipeline = VideoPipeline::new(
|
||||
codecs,
|
||||
move |_| {
|
||||
let _ = tx.send(());
|
||||
},
|
||||
{
|
||||
let requests = requests.clone();
|
||||
move || {
|
||||
requests.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
},
|
||||
);
|
||||
let frame = |keyframe: bool, contiguous: bool| MediaFrame {
|
||||
kind: MediaKind::Video,
|
||||
codec: voelin_stream::Codec::Vp8,
|
||||
time: MediaTime::new(0, Frequency::NINETY_KHZ),
|
||||
network_time: Instant::now(),
|
||||
contiguous,
|
||||
// VP8's frame tag: bit 0 clear on keyframes.
|
||||
data: Arc::from(if keyframe { &[0x10_u8, 0][..] } else { &[0x11, 0][..] }),
|
||||
};
|
||||
let got =
|
||||
|n: usize| (0..n).all(|_| pictures.recv_timeout(Duration::from_secs(2)).is_ok());
|
||||
pipeline.push(frame(true, true));
|
||||
pipeline.push(frame(false, true));
|
||||
assert!(got(2), "conceals {conceals}");
|
||||
pipeline.push(frame(false, false));
|
||||
pipeline.push(frame(false, true));
|
||||
if conceals {
|
||||
assert!(got(2), "decoding goes on");
|
||||
} else {
|
||||
assert!(pictures.recv_timeout(Duration::from_millis(300)).is_err(), "skipped");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1200));
|
||||
let asked = requests.load(Ordering::Relaxed);
|
||||
assert!(asked >= 2, "conceals {conceals}: {asked} requests");
|
||||
pipeline.push(frame(true, true));
|
||||
assert!(got(1), "the keyframe decodes");
|
||||
let asked = requests.load(Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
assert_eq!(requests.load(Ordering::Relaxed), asked, "no more requests");
|
||||
let stats = pipeline.stats();
|
||||
assert_eq!(stats.skipped, if conceals { 0 } else { 2 }, "{stats:?}");
|
||||
assert_eq!(stats.decoder, Some(DecoderBackend::Hardware("fake")));
|
||||
}
|
||||
}
|
||||
|
||||
fn layer(id: LayerId, scale: f32, max_fps: Option<u32>, bitrate: u64) -> LayerSpec {
|
||||
LayerSpec { id, scale, max_fps, ..LayerSpec::single(bitrate) }
|
||||
}
|
||||
|
||||
@@ -1032,14 +1032,31 @@ pub static STREAM_SRTP_PROFILES: Key<Vec<String>> = Key::new(
|
||||
)
|
||||
.validated(valid_srtp);
|
||||
|
||||
/// Use hardware video encoders and decoders where available.
|
||||
/// Use hardware video encoders where available.
|
||||
pub static STREAM_HARDWARE_ACCELERATION: Key<bool> = Key::new(
|
||||
"stream.hardware_acceleration",
|
||||
Kind::Bool,
|
||||
"Use hardware video encoders and decoders where available.",
|
||||
"Use hardware video encoders where available.",
|
||||
|| true,
|
||||
);
|
||||
|
||||
/// Use hardware video decoders where available.
|
||||
pub static STREAM_HARDWARE_DECODING: Key<bool> = Key::new(
|
||||
"stream.hardware_decoding",
|
||||
Kind::Bool,
|
||||
"Use hardware video decoders where available.",
|
||||
|| true,
|
||||
);
|
||||
|
||||
/// Video decoder: `auto`, `software`, or the name of a decoder backend.
|
||||
pub static STREAM_DECODER_BACKEND: Key<String> = Key::new(
|
||||
"stream.decoder_backend",
|
||||
Kind::Text { suggestions: &["auto", "software"] },
|
||||
"Video decoder: auto, software, or a decoder's name.",
|
||||
|| "auto".into(),
|
||||
)
|
||||
.validated(not_empty);
|
||||
|
||||
/// Who may watch our stream without being asked.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -1116,6 +1133,15 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
|
||||
|| true,
|
||||
);
|
||||
|
||||
/// Import identities from the official TeamSpeak clients when the app
|
||||
/// starts ([`crate::identity::import_new`]; their files are only read).
|
||||
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
|
||||
"identity.import_from_teamspeak",
|
||||
Kind::Bool,
|
||||
"Import new identities from the official TeamSpeak clients on start (read only).",
|
||||
|| true,
|
||||
);
|
||||
|
||||
/// How often a file transfer reports its progress (ms); 0: after every
|
||||
/// piece received or sent.
|
||||
pub static FILES_PROGRESS_MS: Key<u32> = Key::new(
|
||||
@@ -1283,6 +1309,8 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> {
|
||||
&STREAM_ENCODER_BACKEND,
|
||||
&STREAM_SRTP_PROFILES,
|
||||
&STREAM_HARDWARE_ACCELERATION,
|
||||
&STREAM_HARDWARE_DECODING,
|
||||
&STREAM_DECODER_BACKEND,
|
||||
&STREAM_PERMISSIONS,
|
||||
&CHAT_STORE_HISTORY,
|
||||
&CHAT_HISTORY_PAGE,
|
||||
@@ -1291,6 +1319,7 @@ pub fn builtin_keys() -> Vec<&'static dyn Setting> {
|
||||
&STREAM_AUDIO_SOURCES,
|
||||
&CACHE_MAX_MB,
|
||||
&CACHE_FETCH_IMAGES,
|
||||
&IDENTITY_IMPORT,
|
||||
&FILES_PROGRESS_MS,
|
||||
&PRIVACY_BLOCK_MODE,
|
||||
#[cfg(feature = "media")]
|
||||
@@ -1353,6 +1382,8 @@ mod tests {
|
||||
);
|
||||
assert!(s.get(&STREAM_HARDWARE_ACCELERATION));
|
||||
assert_eq!(s.get(&STREAM_ENCODER_BACKEND), "auto");
|
||||
assert!(s.get(&STREAM_HARDWARE_DECODING));
|
||||
assert_eq!(s.get(&STREAM_DECODER_BACKEND), "auto");
|
||||
assert!(s.get(&CHAT_STORE_HISTORY));
|
||||
assert_eq!(s.get(&CHAT_HISTORY_PAGE), 100);
|
||||
assert_eq!(s.get(&CHAT_DEDUPE_TOLERANCE_MS), 5000);
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! pattern, encoded by each encoder this machine has as a share encodes the
|
||||
//! screen, sent by our streamer peer offering just that codec, must decode
|
||||
//! at its size in headless Chromium (libwebrtc, the stack the official
|
||||
//! TeamSpeak 6 client is built on).
|
||||
//! TeamSpeak 6 client is built on). And the other way: what Chromium sends
|
||||
//! (AV1, VP9, H.264) our viewer accepts and the engine's pipeline decodes.
|
||||
//!
|
||||
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
|
||||
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
|
||||
@@ -11,6 +12,8 @@
|
||||
|
||||
#![cfg(feature = "media-desktop")]
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -18,8 +21,8 @@ use tokio::time::timeout;
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs};
|
||||
use voelin_core::media::{
|
||||
EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec,
|
||||
peer_config, preferred_codec, video_codec,
|
||||
EncodedSource, EncoderPreference, Streamer, StreamerConfig, VideoPipeline, decoded_everywhere,
|
||||
media_codec, peer_config, preferred_codec, video_codec,
|
||||
};
|
||||
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
|
||||
use voelin_stream::{Peer, PeerEvent};
|
||||
@@ -185,3 +188,72 @@ async fn share_offer_picks_a_codec_every_client_decodes() {
|
||||
browser.quit().await;
|
||||
decoded(&video).unwrap();
|
||||
}
|
||||
|
||||
/// Headless Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in
|
||||
/// turn (what it cannot send is skipped; a system Chromium sends H.264) to
|
||||
/// our viewer peer, which accepts what this machine decodes
|
||||
/// (`peer_config`); the engine's pipeline decodes 30 pictures at that size
|
||||
/// with the first decoder of the codec's ladder (VA-API where it decodes
|
||||
/// the codec), asking the browser for keyframes as a watch does.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn browser_streams_decode_in_the_pipeline() {
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let mut browser = Browser::start().await;
|
||||
let codecs = Arc::new(Codecs::new());
|
||||
let config = peer_config(&codecs, PeerConfig::loopback());
|
||||
let mut decoded = Vec::new();
|
||||
for codec in [Codec::Av1, Codec::Vp9, Codec::H264] {
|
||||
let offer = browser.call(json!({ "op": "offer", "codec": codec.name() })).await;
|
||||
if offer.get("unsupported").is_some() {
|
||||
eprintln!("{codec}: the browser cannot send it, skipped");
|
||||
continue;
|
||||
}
|
||||
assert!(config.accept_video_codecs.contains(&video_codec(codec)), "{codec} not accepted");
|
||||
let (mut peer, answer) =
|
||||
Peer::answer(&config, offer["sdp"].as_str().unwrap()).await.unwrap();
|
||||
browser.call(json!({ "op": "accept", "sdp": answer })).await;
|
||||
let keyframe = Arc::new(AtomicBool::new(false));
|
||||
let (tx, pictures) = std::sync::mpsc::channel();
|
||||
let pipeline = VideoPipeline::new(
|
||||
codecs.clone(),
|
||||
move |picture| {
|
||||
let _ = tx.send((picture.width, picture.height));
|
||||
},
|
||||
{
|
||||
let keyframe = keyframe.clone();
|
||||
move || keyframe.store(true, Ordering::Relaxed)
|
||||
},
|
||||
);
|
||||
let mut sizes = Vec::new();
|
||||
let _ = timeout(Duration::from_secs(15), async {
|
||||
while let Some(event) = peer.next_event().await {
|
||||
match event {
|
||||
PeerEvent::Media(frame) => pipeline.push(frame),
|
||||
PeerEvent::Closed => break,
|
||||
_ => {}
|
||||
}
|
||||
if keyframe.swap(false, Ordering::Relaxed) {
|
||||
peer.request_keyframe();
|
||||
}
|
||||
sizes.extend(pictures.try_iter());
|
||||
if sizes.len() >= 30 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let stats = pipeline.stats();
|
||||
peer.close();
|
||||
eprintln!("{codec}: {} pictures, {stats:?}", sizes.len());
|
||||
assert!(sizes.len() >= 30, "{codec}: {} pictures decoded, {stats:?}", sizes.len());
|
||||
assert!(sizes.iter().all(|&s| s == (320, 240)), "{codec}: {sizes:?}");
|
||||
assert_eq!(stats.codec, Some(codec));
|
||||
assert_eq!(stats.decoder, codecs.decoders_for(codec).first().copied(), "{stats:?}");
|
||||
decoded.push(codec);
|
||||
}
|
||||
browser.quit().await;
|
||||
assert!(decoded.contains(&Codec::Av1), "the browser sent no AV1: {decoded:?}");
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! The viewer's pipeline on an H.264 stream with B-frames at 2560x1440 and
|
||||
//! 60 fps, like the official client sends (AMF with B-frames, keyframes
|
||||
//! rarely): frames pushed in real time into a `VideoPipeline`, every
|
||||
//! picture converted to RGBA as the app shows it, with and without a lost
|
||||
//! frame every second. The stream is the one `voelin-media`'s
|
||||
//! `h264_with_b_frames_at_1440p60` measurement makes (in the temporary
|
||||
//! directory); `VOELIN_OPENH264_LIB` adds Cisco's OpenH264 alone, the
|
||||
//! decoder the app used before FFmpeg's. Run with `--release --ignored`.
|
||||
|
||||
#![cfg(feature = "media-desktop")]
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, convert};
|
||||
use voelin_core::media::{DecodeStats, VideoPipeline};
|
||||
use voelin_stream::{Frequency, MediaFrame, MediaKind, MediaTime};
|
||||
|
||||
/// The access units of an Annex B stream with access unit delimiters.
|
||||
fn access_units(stream: &[u8]) -> Vec<&[u8]> {
|
||||
let mut starts = Vec::new();
|
||||
let mut i = 0;
|
||||
while i + 3 < stream.len() {
|
||||
if stream[i..i + 3] == [0, 0, 1] {
|
||||
if stream[i + 3] & 0x1f == 9 {
|
||||
starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i });
|
||||
}
|
||||
i += 3;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
starts.push(stream.len());
|
||||
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
|
||||
}
|
||||
|
||||
/// `units` at 60 fps into a pipeline of `codecs`, every `loss`-th frame
|
||||
/// lost; the pictures shown and the pipeline's statistics.
|
||||
fn play(codecs: Codecs, units: &[&[u8]], loss: Option<usize>) -> (u64, DecodeStats) {
|
||||
let shown = Arc::new(AtomicU64::new(0));
|
||||
let rgba = Mutex::new(vec![0u8; 2560 * 1440 * 4]);
|
||||
let pipeline = VideoPipeline::new(
|
||||
Arc::new(codecs),
|
||||
{
|
||||
let shown = shown.clone();
|
||||
move |picture| {
|
||||
let stride = picture.width as usize * 4;
|
||||
let mut rgba = rgba.lock().unwrap();
|
||||
rgba.resize(stride * picture.height as usize, 0);
|
||||
convert::to_rgba(&picture, &mut rgba, stride).unwrap();
|
||||
shown.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
},
|
||||
|| {},
|
||||
);
|
||||
let started = Instant::now();
|
||||
let mut contiguous = true;
|
||||
for (n, unit) in units.iter().enumerate() {
|
||||
let due = started + Duration::from_micros(16_667 * n as u64);
|
||||
std::thread::sleep(due.saturating_duration_since(Instant::now()));
|
||||
if loss.is_some_and(|every| n % every == every - 1) {
|
||||
contiguous = false;
|
||||
continue;
|
||||
}
|
||||
pipeline.push(MediaFrame {
|
||||
kind: MediaKind::Video,
|
||||
codec: voelin_stream::Codec::H264,
|
||||
time: MediaTime::new(1500 * n as u64, Frequency::NINETY_KHZ),
|
||||
network_time: Instant::now(),
|
||||
contiguous,
|
||||
data: Arc::from(*unit),
|
||||
});
|
||||
contiguous = true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
(shown.load(Ordering::Relaxed), pipeline.stats())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "a measurement: needs the stream voelin-media's measurement makes"]
|
||||
fn h264_with_b_frames_plays_at_full_rate() {
|
||||
let dir = std::env::temp_dir().join("voelin-h264-bframes");
|
||||
let mut played = 0;
|
||||
for stream in ["h264_vaapi", "x264"] {
|
||||
let Ok(data) = std::fs::read(dir.join(format!("{stream}-bframes-1440p60.h264"))) else {
|
||||
eprintln!("{stream}: no stream in {}, skipped", dir.display());
|
||||
continue;
|
||||
};
|
||||
let units = access_units(&data);
|
||||
let mut setups = vec![("ladder", Codecs::new())];
|
||||
if let Some(path) = std::env::var_os("VOELIN_OPENH264_LIB") {
|
||||
let library =
|
||||
voelin_core::media::voelin_media::codec::h264::OpenH264::load(path).unwrap();
|
||||
setups.push(("openh264", Codecs::builtin().with_openh264(library)));
|
||||
}
|
||||
for (name, codecs) in setups {
|
||||
for loss in [None, Some(60)] {
|
||||
let ladder = codecs.decoders_for(Codec::H264);
|
||||
let (shown, stats) = play(codecs.clone(), &units, loss);
|
||||
let seconds = units.len() as f64 / 60.0;
|
||||
eprintln!(
|
||||
"{stream} 2560x1440@60 with B-frames, {name} {ladder:?}, {}: {shown} of {} \
|
||||
pictures shown ({:.1} fps), decoder {:?}, skipped {}, keyframe requests {}, \
|
||||
last error {:?}",
|
||||
if loss.is_some() { "a frame lost every second" } else { "no loss" },
|
||||
units.len(),
|
||||
shown as f64 / seconds,
|
||||
stats.decoder,
|
||||
stats.skipped,
|
||||
stats.keyframe_requests,
|
||||
stats.error,
|
||||
);
|
||||
if name == "ladder" {
|
||||
// Everything but the frames lost and the two the decoder
|
||||
// still holds at the end.
|
||||
let lost = loss.map_or(0, |every| units.len() / every);
|
||||
assert!(shown + 3 + lost as u64 >= units.len() as u64, "{shown}");
|
||||
}
|
||||
}
|
||||
}
|
||||
played += 1;
|
||||
}
|
||||
assert!(played > 0, "no stream: run voelin-media's h264_with_b_frames_at_1440p60 first");
|
||||
}
|
||||
@@ -21,7 +21,9 @@ sha1 = { package = "sha-1", version = "0.10" }
|
||||
sha2 = "0.10"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt", "sync"], optional = true }
|
||||
tokio-tungstenite = { version = "0.30", optional = true }
|
||||
# TLS (`wss://`, as gateways run behind a proxy) with the system's
|
||||
# certificates; rustls and its crates are in the tree already (reqwest).
|
||||
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
|
||||
@@ -21,10 +21,11 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::Router;
|
||||
use axum::extract::{State, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, header};
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::get;
|
||||
use axum::{Json, Router};
|
||||
use clap::Parser;
|
||||
use tracing::{info, warn};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
@@ -62,7 +63,22 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
pub fn router(hub: Arc<Hub>) -> Router {
|
||||
Router::new().route("/v1", get(ws)).route("/health", get(|| async { "ok" })).with_state(hub)
|
||||
Router::new()
|
||||
.route("/v1", get(ws))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.route("/.well-known/tsgw", get(well_known))
|
||||
.with_state(hub)
|
||||
}
|
||||
|
||||
/// Where apps reach this gateway, for those that find it by asking the
|
||||
/// server's host on the default port (docs/gateway-admin.md): the
|
||||
/// configured public URL, else this listener as the request reached it.
|
||||
async fn well_known(State(hub): State<Arc<Hub>>, headers: HeaderMap) -> Json<serde_json::Value> {
|
||||
let url = hub.boot.public_url.clone().unwrap_or_else(|| {
|
||||
let host = headers.get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("localhost");
|
||||
format!("ws://{host}/v1")
|
||||
});
|
||||
Json(serde_json::json!({ "url": url }))
|
||||
}
|
||||
|
||||
async fn ws(State(hub): State<Arc<Hub>>, upgrade: WebSocketUpgrade) -> impl IntoResponse {
|
||||
|
||||
@@ -533,3 +533,37 @@ async fn admin_settings_apply_live() {
|
||||
let stored = fx.hub.db.config_values().unwrap();
|
||||
assert!(stored.iter().any(|(k, v)| k == "relay.nickname" && v == "Bridge"));
|
||||
}
|
||||
|
||||
/// The gateway's answer at `/.well-known/tsgw`, as an app asks for it.
|
||||
async fn well_known(fx: &Fixture) -> String {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let host = fx.url.trim_start_matches("ws://").trim_end_matches("/v1");
|
||||
let mut stream = tokio::net::TcpStream::connect(host).await.unwrap();
|
||||
let request =
|
||||
format!("GET /.well-known/tsgw HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
stream.write_all(request.as_bytes()).await.unwrap();
|
||||
let mut response = String::new();
|
||||
stream.read_to_string(&mut response).await.unwrap();
|
||||
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
|
||||
let body = response.split_once("\r\n\r\n").unwrap().1;
|
||||
let answer: serde_json::Value = serde_json::from_str(body).unwrap();
|
||||
answer["url"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
/// Apps that know only the server's host ask the gateway on its port where
|
||||
/// it is (`voelin_core::discover`), then log in there.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tells_apps_where_it_is() {
|
||||
let fx = Fixture::start("well-known", "").await;
|
||||
let url = well_known(&fx).await;
|
||||
assert_eq!(url, fx.url);
|
||||
let (alice, _, _) = fx.people();
|
||||
let login = Login::Identity { key: alice.key.clone(), key_offset: 0 };
|
||||
let (client, _pushes) = connect(&url, login).await.unwrap();
|
||||
assert!(client.has(feature::PRESENCE));
|
||||
|
||||
// Behind a proxy it gives the public URL instead.
|
||||
let public = "[listen]\npublic_url = \"wss://gw.example.test/v1\"\n";
|
||||
let fx = Fixture::start("well-known-public", public).await;
|
||||
assert_eq!(well_known(&fx).await, "wss://gw.example.test/v1");
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
//! Encoder factories found at runtime.
|
||||
//! Encoder and decoder factories found at runtime.
|
||||
//!
|
||||
//! - FFmpeg (feature `ffmpeg`, desktop): VA-API, NVENC, Quick Sync, AMF,
|
||||
//! Media Foundation and VideoToolbox encoders, plus software ones FFmpeg
|
||||
//! wraps (x264, OpenH264, SVT-AV1, rav1e, libaom); one factory per backend
|
||||
//! that passed its self-test ([`crate::ffmpeg::probe`]).
|
||||
//! that passed its self-test ([`crate::ffmpeg::probe`]). Decoders likewise:
|
||||
//! VA-API, NVDEC, D3D11VA, DXVA2 and VideoToolbox, then dav1d and FFmpeg's
|
||||
//! own ([`crate::ffmpeg::decoder::probe`]).
|
||||
//! - Android: MediaCodec ([`super::mediacodec`]).
|
||||
|
||||
use crate::Result;
|
||||
use crate::codec::{Codec, EncoderBackend, EncoderConfig, VideoEncoder};
|
||||
use crate::codec::{
|
||||
Codec, DecoderBackend, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder,
|
||||
};
|
||||
|
||||
/// Creates encoders of one backend.
|
||||
pub trait EncoderFactory: Send + Sync {
|
||||
@@ -52,3 +56,32 @@ pub fn probe() -> Vec<Box<dyn EncoderFactory>> {
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Creates decoders of one backend for one codec: FFmpeg's, or one an
|
||||
/// application adds ([`Codecs::with_decoder`](super::Codecs::with_decoder)).
|
||||
pub trait DecoderFactory: Send + Sync {
|
||||
/// The backend its decoders are (for the ladder, logs and settings).
|
||||
fn backend(&self) -> DecoderBackend;
|
||||
|
||||
fn codec(&self) -> Codec;
|
||||
|
||||
/// The API or library behind it (`VA-API`, `dav1d`, ...), for the UI.
|
||||
fn api(&self) -> &'static str;
|
||||
|
||||
/// A GPU decoder: left out when hardware decoding is off.
|
||||
fn is_hardware(&self) -> bool;
|
||||
|
||||
fn create(&self) -> Result<Box<dyn VideoDecoder>>;
|
||||
}
|
||||
|
||||
/// Decoder factories usable on this machine: FFmpeg's decoders that passed
|
||||
/// their self-test, hardware first.
|
||||
pub fn probe_decoders() -> Vec<Box<dyn DecoderFactory>> {
|
||||
#[allow(unused_mut)]
|
||||
let mut found: Vec<Box<dyn DecoderFactory>> = Vec::new();
|
||||
#[cfg(feature = "ffmpeg")]
|
||||
for factory in crate::ffmpeg::decoder::FfmpegDecoderFactory::available() {
|
||||
found.push(Box::new(factory));
|
||||
}
|
||||
found
|
||||
}
|
||||
@@ -7,11 +7,16 @@
|
||||
//! - [`h264`] (feature `openh264`): H.264 with Cisco's prebuilt OpenH264,
|
||||
//! loaded at runtime
|
||||
//! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d
|
||||
//! - [`hw`]: encoder factories found at runtime: FFmpeg's hardware and
|
||||
//! software encoders ([`crate::ffmpeg`], feature `ffmpeg`) and, on Android,
|
||||
//! MediaCodec
|
||||
//! - [`hw`]: encoder and decoder factories found at runtime: FFmpeg's
|
||||
//! hardware and software encoders and decoders ([`crate::ffmpeg`], feature
|
||||
//! `ffmpeg`) and, on Android, MediaCodec encoders
|
||||
//! - `mediacodec` (Android): the device's MediaCodec encoders and decoders
|
||||
//! (hardware, or Google's software VP8 / VP9 / H.264)
|
||||
//!
|
||||
//! A viewer decodes each codec with the best decoder that works here and
|
||||
//! falls back to the next one ([`Codecs::decoders_for`]): hardware (FFmpeg's
|
||||
//! hwaccels, MediaCodec), then FFmpeg's software decoders, then the built-in
|
||||
//! libvpx, OpenH264 and dav1d.
|
||||
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
@@ -110,8 +115,12 @@ impl TryFrom<str0m::format::Codec> for Codec {
|
||||
}
|
||||
}
|
||||
|
||||
/// Order in which a viewer accepts codecs: VP9 > VP8 > AV1 > H.264.
|
||||
pub const VIEWER_PREFERENCE: [Codec; 4] = [Codec::Vp9, Codec::Vp8, Codec::Av1, Codec::H264];
|
||||
/// Order in which a viewer accepts codecs, best first: AV1 > HEVC > VP9 >
|
||||
/// H.264 > VP8 (the best compression first, the codec every client has
|
||||
/// last). Answers follow the offer's order, so this ranks what a viewer
|
||||
/// asks for when it chooses, and what [`Codecs::decoders`] lists.
|
||||
pub const VIEWER_PREFERENCE: [Codec; 5] =
|
||||
[Codec::Av1, Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8];
|
||||
|
||||
/// What the encoder should optimise for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -293,6 +302,23 @@ pub trait VideoDecoder: Send {
|
||||
/// Decode one complete frame (a depacketized RTP frame). Returns the
|
||||
/// picture if one is ready; its timestamp is zero.
|
||||
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>>;
|
||||
|
||||
/// Like [`decode`](Self::decode), into `out`: `true` if a picture is
|
||||
/// there, else `out` is unchanged. Decoders that can reuse `out`'s
|
||||
/// buffers do (FFmpeg's), so a caller that keeps passing the same frame
|
||||
/// gets its pictures without allocations.
|
||||
fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result<bool> {
|
||||
let picture = self.decode(data)?;
|
||||
Ok(picture.map(|p| *out = p).is_some())
|
||||
}
|
||||
|
||||
/// Whether frames after a lost one still decode to a picture (what is
|
||||
/// missing concealed until the next keyframe), so that a viewer keeps
|
||||
/// decoding instead of waiting for a keyframe: FFmpeg's H.264 and HEVC
|
||||
/// decoders. The others fail, or show garbage, on a missing reference.
|
||||
fn conceals_errors(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementations behind [`VideoEncoder`].
|
||||
@@ -325,6 +351,45 @@ impl fmt::Display for EncoderBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementations behind [`VideoDecoder`], as [`Codecs::decoders_for`]
|
||||
/// orders them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum DecoderBackend {
|
||||
/// An OS / GPU decoder of its own API (Android's `mediacodec`), or one
|
||||
/// an application adds ([`Codecs::with_decoder`]).
|
||||
Hardware(&'static str),
|
||||
/// An FFmpeg decoder by its name in `ffmpeg::DECODERS`: in hardware
|
||||
/// (`h264_vaapi`, FFmpeg's names of its hwaccels) or in software
|
||||
/// (`h264`, `libdav1d`).
|
||||
Ffmpeg(&'static str),
|
||||
Libvpx,
|
||||
OpenH264,
|
||||
Dav1d,
|
||||
}
|
||||
|
||||
impl DecoderBackend {
|
||||
/// The name in settings (`stream.decoder_backend`) and logs.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
DecoderBackend::Hardware(name) | DecoderBackend::Ffmpeg(name) => name,
|
||||
DecoderBackend::Libvpx => "libvpx",
|
||||
DecoderBackend::OpenH264 => "openh264",
|
||||
DecoderBackend::Dav1d => "dav1d",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DecoderBackend {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
/// Which decoders to use (settings `stream.hardware_decoding` and
|
||||
/// `stream.decoder_backend`): the choices of the encoders, `hardware` for
|
||||
/// GPU decoders and `backend` naming a [`DecoderBackend::name`].
|
||||
pub type DecoderPreference = EncoderPreference;
|
||||
|
||||
/// Which encoders to use (settings `stream.hardware_acceleration` and
|
||||
/// `stream.encoder_backend`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -391,8 +456,12 @@ pub struct EncoderInfo {
|
||||
pub rank: Option<usize>,
|
||||
}
|
||||
|
||||
/// Every encoder backend this build knows, what works here and why the
|
||||
/// rest does not (for the UI and `voelinctl stream encoders`).
|
||||
/// One decoder backend in [`Codecs::report`]: as [`EncoderInfo`], its
|
||||
/// `rank` the position in its codec's ladder ([`Codecs::decoders_for`]).
|
||||
pub type DecoderInfo = EncoderInfo;
|
||||
|
||||
/// Every encoder and decoder backend this build knows, what works here and
|
||||
/// why the rest does not (for the UI and `voelinctl stream encoders`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct EncoderReport {
|
||||
/// The FFmpeg libraries in use (release, version, path), or why none.
|
||||
@@ -401,6 +470,7 @@ pub struct EncoderReport {
|
||||
/// or why not.
|
||||
pub zero_copy: std::result::Result<(), String>,
|
||||
pub encoders: Vec<EncoderInfo>,
|
||||
pub decoders: Vec<DecoderInfo>,
|
||||
}
|
||||
|
||||
fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
|
||||
@@ -431,7 +501,9 @@ impl Candidate {
|
||||
|
||||
/// The codecs this build and machine can use, and factories for them.
|
||||
///
|
||||
/// Viewer order ([`Codecs::decoders`]): VP9 > VP8 > AV1 > H.264. Streamer
|
||||
/// Viewer order ([`Codecs::decoders`]): AV1 > HEVC > VP9 > H.264 > VP8, each
|
||||
/// codec with its ladder of decoders ([`Codecs::decoders_for`]) under the
|
||||
/// [`DecoderPreference`]. Streamer
|
||||
/// order ([`Codecs::encoders`]) under the default [`EncoderPreference`]:
|
||||
/// hardware (H.264, AV1, VP9, VP8, HEVC; FFmpeg's or MediaCodec) > VP8
|
||||
/// (libvpx) > H.264 (x264 and OpenH264 through FFmpeg, then Cisco's
|
||||
@@ -440,9 +512,11 @@ impl Candidate {
|
||||
#[derive(Clone)]
|
||||
pub struct Codecs {
|
||||
factories: Vec<Arc<dyn hw::EncoderFactory>>,
|
||||
decoder_factories: Vec<Arc<dyn hw::DecoderFactory>>,
|
||||
#[cfg(feature = "openh264")]
|
||||
openh264: Option<h264::OpenH264>,
|
||||
preference: EncoderPreference,
|
||||
decoder_preference: DecoderPreference,
|
||||
}
|
||||
|
||||
impl Default for Codecs {
|
||||
@@ -457,34 +531,67 @@ impl fmt::Debug for Codecs {
|
||||
.field("decoders", &self.decoders())
|
||||
.field("encoders", &self.encoders())
|
||||
.field("preference", &self.preference)
|
||||
.field("decoder_preference", &self.decoder_preference)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Codecs {
|
||||
/// Software codecs compiled in, plus the encoders [`hw::probe`] finds
|
||||
/// (FFmpeg's that passed their self-test, MediaCodec). H.264 through
|
||||
/// Cisco's library needs [`Codecs::with_openh264`].
|
||||
/// (FFmpeg's that passed their self-test, MediaCodec) and the decoders
|
||||
/// [`hw::probe_decoders`] finds (FFmpeg's), both probed at once. H.264
|
||||
/// through Cisco's library needs [`Codecs::with_openh264`].
|
||||
pub fn new() -> Self {
|
||||
let (factories, decoder_factories) = std::thread::scope(|scope| {
|
||||
let decoders = scope.spawn(hw::probe_decoders);
|
||||
(hw::probe(), decoders.join().unwrap_or_default())
|
||||
});
|
||||
Self {
|
||||
factories: hw::probe().into_iter().map(Arc::from).collect(),
|
||||
factories: factories.into_iter().map(Arc::from).collect(),
|
||||
decoder_factories: decoder_factories.into_iter().map(Arc::from).collect(),
|
||||
#[cfg(feature = "openh264")]
|
||||
openh264: None,
|
||||
preference: EncoderPreference::default(),
|
||||
decoder_preference: DecoderPreference::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the codecs compiled into this crate (libvpx, OpenH264 once
|
||||
/// loaded, dav1d): no FFmpeg or MediaCodec, nothing probed.
|
||||
/// loaded, dav1d): no FFmpeg or MediaCodec encoders, no FFmpeg decoders,
|
||||
/// nothing probed.
|
||||
pub fn builtin() -> Self {
|
||||
Self {
|
||||
factories: Vec::new(),
|
||||
decoder_factories: Vec::new(),
|
||||
#[cfg(feature = "openh264")]
|
||||
openh264: None,
|
||||
preference: EncoderPreference::default(),
|
||||
decoder_preference: DecoderPreference::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode `factory`'s codec with it first (a decoder of the embedding
|
||||
/// application, or a test's).
|
||||
pub fn with_decoder(mut self, factory: Arc<dyn hw::DecoderFactory>) -> Self {
|
||||
self.decoder_factories.insert(0, factory);
|
||||
self
|
||||
}
|
||||
|
||||
/// Use `preference` for [`decoders_for`](Self::decoders_for) and
|
||||
/// [`new_decoder`](Self::new_decoder).
|
||||
pub fn with_decoder_preference(mut self, preference: DecoderPreference) -> Self {
|
||||
self.decoder_preference = preference;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_decoder_preference(&mut self, preference: DecoderPreference) {
|
||||
self.decoder_preference = preference;
|
||||
}
|
||||
|
||||
pub fn decoder_preference(&self) -> &DecoderPreference {
|
||||
&self.decoder_preference
|
||||
}
|
||||
|
||||
/// Enable H.264 through a loaded OpenH264 library.
|
||||
#[cfg(feature = "openh264")]
|
||||
pub fn with_openh264(mut self, library: h264::OpenH264) -> Self {
|
||||
@@ -526,32 +633,74 @@ impl Codecs {
|
||||
|
||||
/// Whether `codec` can be decoded, or why not.
|
||||
pub fn check_decoder(&self, codec: Codec) -> Result<()> {
|
||||
#[cfg(target_os = "android")]
|
||||
if mediacodec::check_decoder(codec).is_ok() {
|
||||
if !self.decoders_for(codec).is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match codec {
|
||||
Codec::Vp8 | Codec::Vp9 => {
|
||||
#[cfg(feature = "vpx")]
|
||||
return vpx::check(codec, false);
|
||||
#[cfg(not(feature = "vpx"))]
|
||||
return Err(unavailable(codec, "built without the `vpx` feature"));
|
||||
}
|
||||
Codec::H264 if self.has_openh264() => Ok(()),
|
||||
Codec::H264 => Err(unavailable(codec, "the OpenH264 library is not loaded")),
|
||||
Codec::Av1 => {
|
||||
#[cfg(feature = "av1")]
|
||||
return Ok(());
|
||||
#[cfg(not(feature = "av1"))]
|
||||
return Err(unavailable(codec, "built without the `av1` feature"));
|
||||
}
|
||||
Codec::H265 => Err(unavailable(codec, "no HEVC decoder")),
|
||||
if !self.decoder_candidates(codec).is_empty() {
|
||||
let choice = &self.decoder_preference;
|
||||
return Err(unavailable(codec, format!("its decoders are not used ({choice:?})")));
|
||||
}
|
||||
let builtin = match codec {
|
||||
Codec::Vp8 | Codec::Vp9 if cfg!(feature = "vpx") => "libvpx has no decoder for it",
|
||||
Codec::Vp8 | Codec::Vp9 => "built without the `vpx` feature",
|
||||
Codec::H264 => "the OpenH264 library is not loaded",
|
||||
Codec::Av1 => "built without the `av1` feature (dav1d)",
|
||||
Codec::H265 => "nothing built in decodes it",
|
||||
};
|
||||
Err(unavailable(codec, format!("no FFmpeg decoder works here, and {builtin}")))
|
||||
}
|
||||
|
||||
/// Decodable codecs in the viewer's order of preference.
|
||||
/// Decodable codecs in the viewer's order of preference
|
||||
/// ([`VIEWER_PREFERENCE`]): those with at least one decoder.
|
||||
pub fn decoders(&self) -> Vec<Codec> {
|
||||
VIEWER_PREFERENCE.into_iter().filter(|&c| self.check_decoder(c).is_ok()).collect()
|
||||
VIEWER_PREFERENCE.into_iter().filter(|&c| !self.decoders_for(c).is_empty()).collect()
|
||||
}
|
||||
|
||||
/// Every decoder of `codec` here and whether it is a GPU one: the
|
||||
/// platform's (MediaCodec), the factories (an application's, then
|
||||
/// FFmpeg's hardware and software decoders), then the built-in ones.
|
||||
fn decoder_candidates(&self, codec: Codec) -> Vec<(DecoderBackend, bool)> {
|
||||
let mut list = Vec::new();
|
||||
// The device's codecs (hardware, or Google's software ones): Android
|
||||
// has no others, so hardware decoding off does not leave them out.
|
||||
#[cfg(target_os = "android")]
|
||||
if mediacodec::check_decoder(codec).is_ok() {
|
||||
list.push((DecoderBackend::Hardware("mediacodec"), false));
|
||||
}
|
||||
for f in self.decoder_factories.iter().filter(|f| f.codec() == codec) {
|
||||
list.push((f.backend(), f.is_hardware()));
|
||||
}
|
||||
match codec {
|
||||
#[cfg(feature = "vpx")]
|
||||
Codec::Vp8 | Codec::Vp9 if vpx::check(codec, false).is_ok() => {
|
||||
list.push((DecoderBackend::Libvpx, false));
|
||||
}
|
||||
Codec::H264 if self.has_openh264() => list.push((DecoderBackend::OpenH264, false)),
|
||||
#[cfg(feature = "av1")]
|
||||
Codec::Av1 => list.push((DecoderBackend::Dav1d, false)),
|
||||
_ => {}
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
/// The decoders of `codec` in the order a viewer tries them, its ladder:
|
||||
/// hardware first (unless the [`DecoderPreference`] turns it off), then
|
||||
/// FFmpeg's software decoders, then the built-in libvpx, OpenH264 and
|
||||
/// dav1d; a backend named in the preference before all of them.
|
||||
pub fn decoders_for(&self, codec: Codec) -> Vec<DecoderBackend> {
|
||||
let all = self.decoder_candidates(codec);
|
||||
let preference = &self.decoder_preference;
|
||||
let automatic = |c: &&(DecoderBackend, bool)| preference.hardware || !c.1;
|
||||
let chosen: Vec<&(DecoderBackend, bool)> = match &preference.backend {
|
||||
BackendChoice::Auto => all.iter().filter(automatic).collect(),
|
||||
BackendChoice::Software => all.iter().filter(|c| !c.1).collect(),
|
||||
BackendChoice::Named(name) => {
|
||||
let named = all.iter().filter(|c| c.0.name() == name);
|
||||
let rest = all.iter().filter(|c| c.0.name() != name).filter(automatic);
|
||||
named.chain(rest).collect()
|
||||
}
|
||||
};
|
||||
chosen.into_iter().map(|c| c.0).collect()
|
||||
}
|
||||
|
||||
/// Every usable encoder in the base order, before the preference.
|
||||
@@ -619,24 +768,51 @@ impl Codecs {
|
||||
codecs
|
||||
}
|
||||
|
||||
/// A decoder for `codec`: the first of its ladder
|
||||
/// ([`decoders_for`](Self::decoders_for)) that opens.
|
||||
pub fn new_decoder(&self, codec: Codec) -> Result<Box<dyn VideoDecoder>> {
|
||||
self.check_decoder(codec)?;
|
||||
let mut last_error = None;
|
||||
for backend in self.decoders_for(codec) {
|
||||
match self.new_decoder_with(codec, backend) {
|
||||
Ok(decoder) => return Ok(decoder),
|
||||
Err(e) => {
|
||||
tracing::warn!(%codec, %backend, "decoder failed to open: {e}");
|
||||
last_error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| unavailable(codec, "no decoder in this build")))
|
||||
}
|
||||
|
||||
/// A decoder from a specific backend.
|
||||
pub fn new_decoder_with(
|
||||
&self,
|
||||
codec: Codec,
|
||||
backend: DecoderBackend,
|
||||
) -> Result<Box<dyn VideoDecoder>> {
|
||||
#[cfg(target_os = "android")]
|
||||
if mediacodec::check_decoder(codec).is_ok() {
|
||||
if backend == DecoderBackend::Hardware("mediacodec") {
|
||||
return Ok(Box::new(mediacodec::MediaCodecDecoder::new(codec)?));
|
||||
}
|
||||
self.check_decoder(codec)?;
|
||||
match codec {
|
||||
if let Some(factory) =
|
||||
self.decoder_factories.iter().find(|f| f.backend() == backend && f.codec() == codec)
|
||||
{
|
||||
return factory.create();
|
||||
}
|
||||
match backend {
|
||||
#[cfg(feature = "vpx")]
|
||||
Codec::Vp8 | Codec::Vp9 => Ok(Box::new(vpx::VpxDecoder::new(codec)?)),
|
||||
DecoderBackend::Libvpx if matches!(codec, Codec::Vp8 | Codec::Vp9) => {
|
||||
Ok(Box::new(vpx::VpxDecoder::new(codec)?))
|
||||
}
|
||||
#[cfg(feature = "openh264")]
|
||||
Codec::H264 => match &self.openh264 {
|
||||
DecoderBackend::OpenH264 if codec == Codec::H264 => match &self.openh264 {
|
||||
Some(lib) => Ok(Box::new(lib.decoder()?)),
|
||||
None => Err(unavailable(codec, "the OpenH264 library is not loaded")),
|
||||
},
|
||||
#[cfg(feature = "av1")]
|
||||
Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)),
|
||||
#[allow(unreachable_patterns)]
|
||||
_ => Err(unavailable(codec, "no decoder in this build")),
|
||||
DecoderBackend::Dav1d if codec == Codec::Av1 => Ok(Box::new(av1::Dav1dDecoder::new()?)),
|
||||
_ => Err(unavailable(codec, format!("no decoder {backend} for it here"))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -777,7 +953,65 @@ impl Codecs {
|
||||
Err("built without the `ffmpeg` feature".to_owned()),
|
||||
Err("built without the `ffmpeg` feature".to_owned()),
|
||||
);
|
||||
EncoderReport { ffmpeg, zero_copy, encoders }
|
||||
EncoderReport { ffmpeg, zero_copy, encoders, decoders: self.decoder_report() }
|
||||
}
|
||||
|
||||
/// Every decoder this build knows, with what works here and why the
|
||||
/// rest does not, and each one's place in its codec's ladder.
|
||||
fn decoder_report(&self) -> Vec<DecoderInfo> {
|
||||
let ladders: Vec<(Codec, Vec<DecoderBackend>)> =
|
||||
Codec::ALL.into_iter().map(|c| (c, self.decoders_for(c))).collect();
|
||||
let mut decoders = Vec::new();
|
||||
let mut add = |backend: DecoderBackend, api: &str, codec, hardware, status| {
|
||||
let ladder = ladders.iter().find(|(c, _)| *c == codec).map(|(_, l)| l);
|
||||
decoders.push(DecoderInfo {
|
||||
name: backend.name().to_owned(),
|
||||
api: api.to_owned(),
|
||||
codec,
|
||||
hardware,
|
||||
rank: ladder.and_then(|l| l.iter().position(|b| *b == backend)),
|
||||
status,
|
||||
});
|
||||
};
|
||||
#[cfg(target_os = "android")]
|
||||
for codec in Codec::ALL {
|
||||
if mediacodec::check_decoder(codec).is_ok() {
|
||||
add(DecoderBackend::Hardware("mediacodec"), "MediaCodec", codec, true, Ok(()));
|
||||
}
|
||||
}
|
||||
for f in &self.decoder_factories {
|
||||
if !matches!(f.backend(), DecoderBackend::Ffmpeg(_)) {
|
||||
add(f.backend(), f.api(), f.codec(), f.is_hardware(), Ok(()));
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "ffmpeg")]
|
||||
for status in crate::ffmpeg::decoder::probe() {
|
||||
let spec = status.spec;
|
||||
let backend = DecoderBackend::Ffmpeg(spec.name);
|
||||
add(backend, spec.api, spec.codec, spec.is_hardware(), status.available.clone());
|
||||
}
|
||||
for codec in [Codec::Vp8, Codec::Vp9] {
|
||||
#[cfg(feature = "vpx")]
|
||||
let status = vpx::check(codec, false).map_err(|e| e.to_string());
|
||||
#[cfg(not(feature = "vpx"))]
|
||||
let status = Err("built without the `vpx` feature".to_owned());
|
||||
add(DecoderBackend::Libvpx, "libvpx", codec, false, status);
|
||||
}
|
||||
let status = if self.has_openh264() {
|
||||
Ok(())
|
||||
} else if cfg!(feature = "openh264") {
|
||||
Err("Cisco's OpenH264 library is not loaded".to_owned())
|
||||
} else {
|
||||
Err("built without the `openh264` feature".to_owned())
|
||||
};
|
||||
add(DecoderBackend::OpenH264, "OpenH264 (Cisco)", Codec::H264, false, status);
|
||||
let status = if cfg!(feature = "av1") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("built without the `av1` feature".to_owned())
|
||||
};
|
||||
add(DecoderBackend::Dav1d, "dav1d", Codec::Av1, false, status);
|
||||
decoders
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,836 @@
|
||||
//! Video decoders through FFmpeg: the platform's hardware decoders first
|
||||
//! (VA-API and, with NVIDIA's driver, NVDEC on Linux; D3D11VA and DXVA2 on
|
||||
//! Windows; VideoToolbox on macOS), then FFmpeg's software decoders (dav1d
|
||||
//! and libaom for AV1, FFmpeg's own HEVC, VP9, H.264 and VP8), each checked
|
||||
//! by a self-test.
|
||||
//!
|
||||
//! Hardware decoding goes through FFmpeg's hwaccel API: FFmpeg's own decoder
|
||||
//! (`av1`, `h264`, ...) with `AVCodecContext.hw_device_ctx` set (located
|
||||
//! at load, see [`super::layout`]), so that its default `get_format` picks
|
||||
//! the device's surfaces. Pictures are copied out of the GPU
|
||||
//! (`av_hwframe_transfer_data`) into a frame of our own, reused, and from
|
||||
//! there into the caller's [`VideoFrame`] (NV12), whose buffers are reused
|
||||
//! as well ([`VideoDecoder::decode_into`]): a running decoder allocates
|
||||
//! nothing per picture on our side. Software decoders give I420 (or NV12).
|
||||
//!
|
||||
//! Every decoder is set up for live video: slice threads only (frame
|
||||
//! threads hold one frame per thread before the first picture comes out),
|
||||
//! dav1d with a frame delay of one, so each frame's picture comes out of
|
||||
//! the call that decoded it.
|
||||
//!
|
||||
//! [`probe`] runs every decoder once per process (in parallel) on a short
|
||||
//! clip of its codec: three frames of a test picture encoded by this crate's
|
||||
//! own encoders (`clips/`). Each frame must give its picture at once, at its
|
||||
//! size and close to the test picture (PSNR), and a hardware decoder must
|
||||
//! have decoded on the GPU: FFmpeg silently decodes in software when the
|
||||
//! GPU lacks the codec (VP8 on AMD), which the self-test reports as
|
||||
//! unusable, since FFmpeg's software decoder follows in the ladder anyway.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::c_int;
|
||||
use std::sync::{Mutex, OnceLock, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::Ffmpeg;
|
||||
use super::encoder::{Device, log_suffix, vaapi_device};
|
||||
use super::layout;
|
||||
use super::sys::{EAGAIN, EOF, FrameHead, OPTION_NOT_FOUND, PacketHead, Ptr, cstr};
|
||||
use crate::codec::hw::DecoderFactory;
|
||||
use crate::codec::{Codec, DecoderBackend, VideoDecoder};
|
||||
use crate::convert;
|
||||
use crate::frame::{FrameData, FrameRef, PixelsRef, PlaneRef, VideoFrame, chroma_size};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// One FFmpeg decoder this crate drives.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct DecoderSpec {
|
||||
/// The name in settings (`stream.decoder_backend`) and logs: FFmpeg's
|
||||
/// name of the hardware acceleration (`h264_vaapi`, `av1_nvdec`), or of
|
||||
/// the decoder in software (`hevc`, `libdav1d`).
|
||||
pub name: &'static str,
|
||||
pub codec: Codec,
|
||||
/// FFmpeg's decoder.
|
||||
pub decoder: &'static str,
|
||||
/// For hardware decoding: FFmpeg's device type (`vaapi`, `d3d11va`, ...)
|
||||
/// and the pixel format of its pictures (`vaapi`, `d3d11`, ...).
|
||||
pub hardware: Option<(&'static str, &'static str)>,
|
||||
/// The API or library, for the UI.
|
||||
pub api: &'static str,
|
||||
}
|
||||
|
||||
macro_rules! hardware {
|
||||
($name:literal, $codec:ident, $decoder:literal, $device:literal, $format:literal, $api:literal) => {
|
||||
DecoderSpec {
|
||||
name: $name,
|
||||
codec: Codec::$codec,
|
||||
decoder: $decoder,
|
||||
hardware: Some(($device, $format)),
|
||||
api: $api,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! software {
|
||||
($name:literal, $codec:ident, $api:literal) => {
|
||||
DecoderSpec { name: $name, codec: Codec::$codec, decoder: $name, hardware: None, api: $api }
|
||||
};
|
||||
}
|
||||
|
||||
/// Every decoder of this platform, best first within its codec: hardware,
|
||||
/// then software. The ones FFmpeg or the machine lacks fail the probe and
|
||||
/// are skipped.
|
||||
pub static DECODERS: &[DecoderSpec] = &[
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("av1_vaapi", Av1, "av1", "vaapi", "vaapi", "VA-API"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("hevc_vaapi", H265, "hevc", "vaapi", "vaapi", "VA-API"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("vp9_vaapi", Vp9, "vp9", "vaapi", "vaapi", "VA-API"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("h264_vaapi", H264, "h264", "vaapi", "vaapi", "VA-API"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("vp8_vaapi", Vp8, "vp8", "vaapi", "vaapi", "VA-API"),
|
||||
// NVIDIA's driver has no VA-API of its own.
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("av1_nvdec", Av1, "av1", "cuda", "cuda", "NVDEC"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("hevc_nvdec", H265, "hevc", "cuda", "cuda", "NVDEC"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("vp9_nvdec", Vp9, "vp9", "cuda", "cuda", "NVDEC"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("h264_nvdec", H264, "h264", "cuda", "cuda", "NVDEC"),
|
||||
#[cfg(target_os = "linux")]
|
||||
hardware!("vp8_nvdec", Vp8, "vp8", "cuda", "cuda", "NVDEC"),
|
||||
// Every GPU vendor's; DXVA2 for systems without Direct3D 11 video.
|
||||
#[cfg(windows)]
|
||||
hardware!("av1_d3d11va", Av1, "av1", "d3d11va", "d3d11", "D3D11VA"),
|
||||
#[cfg(windows)]
|
||||
hardware!("hevc_d3d11va", H265, "hevc", "d3d11va", "d3d11", "D3D11VA"),
|
||||
#[cfg(windows)]
|
||||
hardware!("vp9_d3d11va", Vp9, "vp9", "d3d11va", "d3d11", "D3D11VA"),
|
||||
#[cfg(windows)]
|
||||
hardware!("h264_d3d11va", H264, "h264", "d3d11va", "d3d11", "D3D11VA"),
|
||||
#[cfg(windows)]
|
||||
hardware!("av1_dxva2", Av1, "av1", "dxva2", "dxva2_vld", "DXVA2"),
|
||||
#[cfg(windows)]
|
||||
hardware!("hevc_dxva2", H265, "hevc", "dxva2", "dxva2_vld", "DXVA2"),
|
||||
#[cfg(windows)]
|
||||
hardware!("vp9_dxva2", Vp9, "vp9", "dxva2", "dxva2_vld", "DXVA2"),
|
||||
#[cfg(windows)]
|
||||
hardware!("h264_dxva2", H264, "h264", "dxva2", "dxva2_vld", "DXVA2"),
|
||||
#[cfg(target_vendor = "apple")]
|
||||
hardware!("av1_videotoolbox", Av1, "av1", "videotoolbox", "videotoolbox_vld", "VideoToolbox"),
|
||||
#[cfg(target_vendor = "apple")]
|
||||
hardware!(
|
||||
"hevc_videotoolbox",
|
||||
H265,
|
||||
"hevc",
|
||||
"videotoolbox",
|
||||
"videotoolbox_vld",
|
||||
"VideoToolbox"
|
||||
),
|
||||
#[cfg(target_vendor = "apple")]
|
||||
hardware!("vp9_videotoolbox", Vp9, "vp9", "videotoolbox", "videotoolbox_vld", "VideoToolbox"),
|
||||
#[cfg(target_vendor = "apple")]
|
||||
hardware!(
|
||||
"h264_videotoolbox",
|
||||
H264,
|
||||
"h264",
|
||||
"videotoolbox",
|
||||
"videotoolbox_vld",
|
||||
"VideoToolbox"
|
||||
),
|
||||
// FFmpeg's native AV1 decoder decodes in hardware only.
|
||||
software!("libdav1d", Av1, "dav1d"),
|
||||
software!("libaom-av1", Av1, "libaom"),
|
||||
software!("hevc", H265, "FFmpeg"),
|
||||
software!("vp9", Vp9, "FFmpeg"),
|
||||
software!("h264", H264, "FFmpeg"),
|
||||
software!("vp8", Vp8, "FFmpeg"),
|
||||
];
|
||||
|
||||
impl DecoderSpec {
|
||||
pub fn by_name(name: &str) -> Option<&'static DecoderSpec> {
|
||||
DECODERS.iter().find(|d| d.name == name)
|
||||
}
|
||||
|
||||
pub fn is_hardware(&self) -> bool {
|
||||
self.hardware.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// The process's device of FFmpeg type `kind` (its default one), shared by
|
||||
/// all decoders; VA-API's is the encoders' (`VOELIN_VAAPI_DEVICE`, or the
|
||||
/// first render node).
|
||||
fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result<Ptr, String> {
|
||||
if kind == "vaapi" {
|
||||
return vaapi_device(ffmpeg);
|
||||
}
|
||||
type Devices = Vec<(&'static str, std::result::Result<Device, String>)>;
|
||||
static DEVICES: Mutex<Devices> = Mutex::new(Vec::new());
|
||||
let mut devices = DEVICES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((_, device)) = devices.iter().find(|(k, _)| *k == kind) {
|
||||
return device.as_ref().map(|d| d.0).map_err(Clone::clone);
|
||||
}
|
||||
let api = &ffmpeg.api;
|
||||
let name = cstr(kind);
|
||||
// SAFETY: a C string.
|
||||
let id = unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) };
|
||||
let created = if id <= 0 {
|
||||
Err(format!("FFmpeg has no {kind} support"))
|
||||
} else {
|
||||
let mut device = std::ptr::null_mut();
|
||||
// SAFETY: a valid out pointer; the type's default device, no options.
|
||||
let ret = unsafe {
|
||||
(api.av_hwdevice_ctx_create)(&mut device, id, std::ptr::null(), std::ptr::null_mut(), 0)
|
||||
};
|
||||
if ret < 0 {
|
||||
Err(format!("{kind} device: {}{}", api.error_text(ret), log_suffix(kind)))
|
||||
} else {
|
||||
Ok(Device(device))
|
||||
}
|
||||
};
|
||||
let result = created.as_ref().map(|d| d.0).map_err(Clone::clone);
|
||||
devices.push((kind, created));
|
||||
result
|
||||
}
|
||||
|
||||
/// Threads of a software decoder: slice (or dav1d's tile and row) threads,
|
||||
/// which add no delay.
|
||||
fn decoder_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get().min(8))
|
||||
}
|
||||
|
||||
/// A decoder of one [`DecoderSpec`]; see the [module docs](self).
|
||||
pub struct FfmpegDecoder {
|
||||
ffmpeg: &'static Ffmpeg,
|
||||
spec: &'static DecoderSpec,
|
||||
ctx: Ptr,
|
||||
packet: Ptr,
|
||||
/// The decoder's pictures.
|
||||
frame: Ptr,
|
||||
/// Hardware pictures are copied here from the GPU (reused).
|
||||
download: Ptr,
|
||||
/// The pixel format of the device's pictures.
|
||||
hw_format: Option<c_int>,
|
||||
yuvj420p: Option<c_int>,
|
||||
gpu_pictures: u64,
|
||||
cpu_pictures: u64,
|
||||
}
|
||||
|
||||
// SAFETY: the FFmpeg objects belong to this decoder alone and are used from
|
||||
// one thread at a time (`&mut self`); FFmpeg's decoders have no thread
|
||||
// affinity.
|
||||
unsafe impl Send for FfmpegDecoder {}
|
||||
|
||||
impl FfmpegDecoder {
|
||||
/// A decoder of `spec`, opened at once (on its device for hardware
|
||||
/// decoding).
|
||||
pub fn new(spec: &'static DecoderSpec) -> Result<Self> {
|
||||
let unavailable = |reason: String| Error::CodecUnavailable { codec: spec.codec, reason };
|
||||
let ffmpeg = Ffmpeg::get().map_err(|e| unavailable(e.to_owned()))?;
|
||||
let api = &ffmpeg.api;
|
||||
// Filled in one by one; Drop frees what was made.
|
||||
let mut this = Self {
|
||||
ffmpeg,
|
||||
spec,
|
||||
ctx: std::ptr::null_mut(),
|
||||
packet: std::ptr::null_mut(),
|
||||
frame: std::ptr::null_mut(),
|
||||
download: std::ptr::null_mut(),
|
||||
hw_format: None,
|
||||
yuvj420p: api.pix_fmt("yuvj420p"),
|
||||
gpu_pictures: 0,
|
||||
cpu_pictures: 0,
|
||||
};
|
||||
let name = cstr(spec.decoder);
|
||||
// SAFETY: a C string; returns a static codec or NULL.
|
||||
let codec = unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) };
|
||||
if codec.is_null() {
|
||||
return Err(unavailable(format!("{} is not in this FFmpeg build", spec.decoder)));
|
||||
}
|
||||
// SAFETY: allocates a context with the decoder's private options.
|
||||
this.ctx = unsafe { (api.avcodec_alloc_context3)(codec) };
|
||||
if this.ctx.is_null() {
|
||||
return Err(unavailable("avcodec_alloc_context3 failed".into()));
|
||||
}
|
||||
// SAFETY: `ctx` is a live codec context; the first child is its
|
||||
// private options object (NULL if the decoder has none).
|
||||
let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) };
|
||||
// A hardware decoder's work is on the GPU.
|
||||
let threads = if spec.is_hardware() { 1 } else { decoder_threads() };
|
||||
this.set(this.ctx, "threads", &threads.to_string());
|
||||
this.set(this.ctx, "thread_type", "slice");
|
||||
if spec.decoder == "libdav1d"
|
||||
&& this.set(private, "max_frame_delay", "1") == OPTION_NOT_FOUND
|
||||
{
|
||||
// Before FFmpeg 5.0.
|
||||
this.set(private, "framethreads", "1");
|
||||
}
|
||||
if let Some((kind, format)) = spec.hardware {
|
||||
let device = hw_device(ffmpeg, kind).map_err(unavailable)?;
|
||||
let offset = ffmpeg.codec_hw_device.clone().map_err(unavailable)?;
|
||||
let format =
|
||||
api.pix_fmt(format).ok_or_else(|| unavailable(format!("no {format} format")))?;
|
||||
this.hw_format = Some(format);
|
||||
// SAFETY: `device` is a live device reference; `offset` is
|
||||
// AVCodecContext.hw_device_ctx (located and checked at load),
|
||||
// which takes the new reference and frees it with the context.
|
||||
unsafe {
|
||||
let reference = (api.av_buffer_ref)(device);
|
||||
if reference.is_null() {
|
||||
return Err(unavailable("out of memory".into()));
|
||||
}
|
||||
layout::write::<Ptr>(this.ctx, offset, reference);
|
||||
}
|
||||
}
|
||||
// SAFETY: a configured context and its codec; no options dictionary.
|
||||
let ret = unsafe { (api.avcodec_open2)(this.ctx, codec, std::ptr::null_mut()) };
|
||||
if ret < 0 {
|
||||
return Err(this.error("open", ret));
|
||||
}
|
||||
// SAFETY: allocations, checked below.
|
||||
unsafe {
|
||||
this.packet = (api.av_packet_alloc)();
|
||||
this.frame = (api.av_frame_alloc)();
|
||||
this.download = (api.av_frame_alloc)();
|
||||
}
|
||||
if this.packet.is_null() || this.frame.is_null() || this.download.is_null() {
|
||||
return Err(unavailable("out of memory".into()));
|
||||
}
|
||||
Ok(this)
|
||||
}
|
||||
|
||||
pub fn spec(&self) -> &'static DecoderSpec {
|
||||
self.spec
|
||||
}
|
||||
|
||||
/// Pictures decoded on the GPU so far.
|
||||
pub fn gpu_pictures(&self) -> u64 {
|
||||
self.gpu_pictures
|
||||
}
|
||||
|
||||
/// Pictures decoded in software so far (by a hardware decoder: the GPU
|
||||
/// did not take the stream, and FFmpeg decoded it itself).
|
||||
pub fn cpu_pictures(&self) -> u64 {
|
||||
self.cpu_pictures
|
||||
}
|
||||
|
||||
/// Set an option of `obj` (the context, or its private options) by name;
|
||||
/// one this release does not know is skipped.
|
||||
fn set(&self, obj: Ptr, name: &str, value: &str) -> c_int {
|
||||
if obj.is_null() {
|
||||
return OPTION_NOT_FOUND;
|
||||
}
|
||||
let (name, value) = (cstr(name), cstr(value));
|
||||
// SAFETY: an AVClass-enabled object and two C strings.
|
||||
unsafe { (self.ffmpeg.api.av_opt_set)(obj, name.as_ptr(), value.as_ptr(), 0) }
|
||||
}
|
||||
|
||||
fn error(&self, what: &str, code: c_int) -> Error {
|
||||
self.failed(format!(
|
||||
"{what}: {}{}",
|
||||
self.ffmpeg.api.error_text(code),
|
||||
log_suffix(self.spec.decoder)
|
||||
))
|
||||
}
|
||||
|
||||
fn failed(&self, message: String) -> Error {
|
||||
Error::Decoder { codec: self.spec.codec, message: format!("{} {message}", self.spec.name) }
|
||||
}
|
||||
|
||||
/// Hand `data` to the decoder. The packet points at it only during the
|
||||
/// call: it is not reference-counted, so FFmpeg copies the data into a
|
||||
/// padded buffer of its own.
|
||||
fn send(&mut self, data: &[u8], size: c_int) -> c_int {
|
||||
let packet = self.packet.cast::<PacketHead>();
|
||||
// SAFETY: our packet (from av_packet_alloc, so at least as large as
|
||||
// its leading fields); emptied again before `data` goes away.
|
||||
unsafe {
|
||||
(*packet).data = data.as_ptr().cast_mut();
|
||||
(*packet).size = size;
|
||||
let ret = (self.ffmpeg.api.avcodec_send_packet)(self.ctx, self.packet);
|
||||
(*packet).data = std::ptr::null_mut();
|
||||
(*packet).size = 0;
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
/// Take every picture that is ready; the last one ends up in `out`.
|
||||
fn receive(&mut self, out: &mut VideoFrame) -> Result<bool> {
|
||||
let mut got = false;
|
||||
loop {
|
||||
// SAFETY: a live context and our frame.
|
||||
let ret = unsafe { (self.ffmpeg.api.avcodec_receive_frame)(self.ctx, self.frame) };
|
||||
if ret == EAGAIN || ret == EOF {
|
||||
return Ok(got);
|
||||
}
|
||||
if ret < 0 {
|
||||
return Err(self.error("decoding", ret));
|
||||
}
|
||||
let copied = self.copy_picture(out);
|
||||
// SAFETY: our frame; its buffers go back to the decoder.
|
||||
unsafe { (self.ffmpeg.api.av_frame_unref)(self.frame) };
|
||||
copied?;
|
||||
got = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoded picture into `out`: from the GPU through the download
|
||||
/// frame, or straight from FFmpeg's buffers.
|
||||
fn copy_picture(&mut self, out: &mut VideoFrame) -> Result<()> {
|
||||
let api = &self.ffmpeg.api;
|
||||
let head = self.frame.cast::<FrameHead>();
|
||||
// SAFETY: a frame the decoder just filled.
|
||||
let (format, width, height) = unsafe { ((*head).format, (*head).width, (*head).height) };
|
||||
let source = if Some(format) == self.hw_format {
|
||||
let download = self.download.cast::<FrameHead>();
|
||||
// SAFETY: the download frame is ours: its leading fields are set
|
||||
// before av_frame_get_buffer as documented, and its buffers are
|
||||
// referenced by nothing else, so they are writable.
|
||||
unsafe {
|
||||
if (*download).data[0].is_null()
|
||||
|| ((*download).width, (*download).height) != (width, height)
|
||||
{
|
||||
(api.av_frame_unref)(self.download);
|
||||
(*download).width = width;
|
||||
(*download).height = height;
|
||||
(*download).format = self.ffmpeg.pix.nv12;
|
||||
let ret = (api.av_frame_get_buffer)(self.download, 0);
|
||||
if ret < 0 {
|
||||
return Err(self.error("picture buffer", ret));
|
||||
}
|
||||
}
|
||||
let ret = (api.av_hwframe_transfer_data)(self.download, self.frame, 0);
|
||||
if ret < 0 {
|
||||
return Err(self.error("copy from the GPU", ret));
|
||||
}
|
||||
}
|
||||
self.gpu_pictures += 1;
|
||||
self.download
|
||||
} else {
|
||||
self.cpu_pictures += 1;
|
||||
self.frame
|
||||
};
|
||||
// SAFETY: `source` holds a picture until it is unreferenced, after
|
||||
// this copy.
|
||||
unsafe { self.view(source) }?.copy_to(out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The picture in `frame`, borrowed.
|
||||
///
|
||||
/// # Safety
|
||||
/// `frame` must hold a picture that stays as it is while the view is
|
||||
/// used.
|
||||
unsafe fn view(&self, frame: Ptr) -> Result<FrameRef<'_>> {
|
||||
// SAFETY: guaranteed by the caller.
|
||||
let head = unsafe { &*frame.cast::<FrameHead>() };
|
||||
let (Ok(width), Ok(height)) = (u32::try_from(head.width), u32::try_from(head.height))
|
||||
else {
|
||||
return Err(self.failed("gave a picture of no size".into()));
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return Err(self.failed("gave a picture of no size".into()));
|
||||
}
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let (cw, ch) = chroma_size(width, height);
|
||||
let plane = |i: usize, bytes: usize, rows: usize| -> Result<PlaneRef<'_>> {
|
||||
let stride = usize::try_from(head.linesize[i]).unwrap_or(0);
|
||||
if head.data[i].is_null() || stride < bytes {
|
||||
return Err(self.failed(format!("gave plane {i} with a line size of {stride}")));
|
||||
}
|
||||
// SAFETY: FFmpeg's planes hold `linesize` bytes for every row of
|
||||
// the picture but the last, which holds at least the row.
|
||||
let data =
|
||||
unsafe { std::slice::from_raw_parts(head.data[i], stride * (rows - 1) + bytes) };
|
||||
Ok(PlaneRef::new(data, stride))
|
||||
};
|
||||
let pix = self.ffmpeg.pix;
|
||||
let pixels = if head.format == pix.yuv420p || Some(head.format) == self.yuvj420p {
|
||||
PixelsRef::I420 { y: plane(0, w, h)?, u: plane(1, cw, ch)?, v: plane(2, cw, ch)? }
|
||||
} else if head.format == pix.nv12 {
|
||||
PixelsRef::Nv12 { y: plane(0, w, h)?, uv: plane(1, cw * 2, ch)? }
|
||||
} else {
|
||||
return Err(self.failed(format!(
|
||||
"gave pictures in {} (only 8-bit 4:2:0 is supported)",
|
||||
self.ffmpeg.api.pix_fmt_name(head.format)
|
||||
)));
|
||||
};
|
||||
Ok(FrameRef { width, height, timestamp: Duration::ZERO, pixels })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FfmpegDecoder {
|
||||
fn drop(&mut self) {
|
||||
let api = &self.ffmpeg.api;
|
||||
// SAFETY: each pointer is NULL or owned by this decoder; the context
|
||||
// frees its device reference.
|
||||
unsafe {
|
||||
(api.av_packet_free)(&mut self.packet);
|
||||
(api.av_frame_free)(&mut self.frame);
|
||||
(api.av_frame_free)(&mut self.download);
|
||||
(api.avcodec_free_context)(&mut self.ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoDecoder for FfmpegDecoder {
|
||||
fn codec(&self) -> Codec {
|
||||
self.spec.codec
|
||||
}
|
||||
|
||||
fn decode(&mut self, data: &[u8]) -> Result<Option<VideoFrame>> {
|
||||
let mut picture = VideoFrame::black_i420(0, 0);
|
||||
Ok(self.decode_into(data, &mut picture)?.then_some(picture))
|
||||
}
|
||||
|
||||
/// FFmpeg's H.264 decoder conceals what a lost frame left missing (from
|
||||
/// the previous picture), and its HEVC decoder makes up missing
|
||||
/// references; VP8, VP9 and AV1 fail on them or show garbage.
|
||||
fn conceals_errors(&self) -> bool {
|
||||
matches!(self.spec.codec, Codec::H264 | Codec::H265)
|
||||
}
|
||||
|
||||
fn decode_into(&mut self, data: &[u8], out: &mut VideoFrame) -> Result<bool> {
|
||||
if data.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let size =
|
||||
c_int::try_from(data.len()).map_err(|_| self.failed("frame too large".into()))?;
|
||||
let mut got = false;
|
||||
let mut ret = self.send(data, size);
|
||||
if ret == EAGAIN {
|
||||
// Pictures have to be taken out before more data goes in.
|
||||
got |= self.receive(out)?;
|
||||
ret = self.send(data, size);
|
||||
}
|
||||
if ret < 0 {
|
||||
return Err(self.error("decoding", ret));
|
||||
}
|
||||
got |= self.receive(out)?;
|
||||
Ok(got)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates decoders of one [`DecoderSpec`] that passed its self-test.
|
||||
pub struct FfmpegDecoderFactory(pub &'static DecoderSpec);
|
||||
|
||||
impl FfmpegDecoderFactory {
|
||||
/// Factories of the decoders that passed their self-test, in
|
||||
/// [`DECODERS`] order (hardware first).
|
||||
pub fn available() -> Vec<FfmpegDecoderFactory> {
|
||||
probe()
|
||||
.iter()
|
||||
.filter(|s| s.available.is_ok())
|
||||
.map(|s| FfmpegDecoderFactory(s.spec))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl DecoderFactory for FfmpegDecoderFactory {
|
||||
fn backend(&self) -> DecoderBackend {
|
||||
DecoderBackend::Ffmpeg(self.0.name)
|
||||
}
|
||||
|
||||
fn codec(&self) -> Codec {
|
||||
self.0.codec
|
||||
}
|
||||
|
||||
fn api(&self) -> &'static str {
|
||||
self.0.api
|
||||
}
|
||||
|
||||
fn is_hardware(&self) -> bool {
|
||||
self.0.is_hardware()
|
||||
}
|
||||
|
||||
fn create(&self) -> Result<Box<dyn VideoDecoder>> {
|
||||
Ok(Box::new(FfmpegDecoder::new(self.0)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Size of the self-test clips: one every hardware decoder takes (NVDEC
|
||||
/// wants at least 144x144 for HEVC), and a multiple of what AV1 encoders
|
||||
/// pad to (64x16 on RDNA3), so that the AV1 clip declares exactly this.
|
||||
pub(crate) const CLIP_SIZE: (u32, u32) = (320, 240);
|
||||
|
||||
/// Frames per clip: a keyframe and two that predict from it.
|
||||
const CLIP_FRAMES: usize = 3;
|
||||
|
||||
/// How close a decoded clip picture must be to [`clip_picture`]; the clips
|
||||
/// decode at well over 40 dB.
|
||||
const CLIP_PSNR: f64 = 30.0;
|
||||
|
||||
/// The self-test clip of `codec`: [`CLIP_FRAMES`] frames of
|
||||
/// [`clip_picture`] encoded by this crate's encoders (see
|
||||
/// `write_self_test_clips` in the tests), each as a little-endian `u32`
|
||||
/// length and the frame as a stream carries it (Annex B for H.264 and HEVC,
|
||||
/// a temporal unit of OBUs for AV1).
|
||||
fn clip(codec: Codec) -> &'static [u8] {
|
||||
match codec {
|
||||
Codec::Av1 => include_bytes!("clips/av1.bin"),
|
||||
Codec::H265 => include_bytes!("clips/hevc.bin"),
|
||||
Codec::Vp9 => include_bytes!("clips/vp9.bin"),
|
||||
Codec::H264 => include_bytes!("clips/h264.bin"),
|
||||
Codec::Vp8 => include_bytes!("clips/vp8.bin"),
|
||||
}
|
||||
}
|
||||
|
||||
fn clip_frames(codec: Codec) -> impl Iterator<Item = &'static [u8]> {
|
||||
let mut rest = clip(codec);
|
||||
std::iter::from_fn(move || {
|
||||
let (length, tail) = rest.split_first_chunk::<4>()?;
|
||||
let (frame, tail) = tail.split_at_checked(u32::from_le_bytes(*length) as usize)?;
|
||||
rest = tail;
|
||||
Some(frame)
|
||||
})
|
||||
}
|
||||
|
||||
/// Frame `n` of the self-test clips: a luma ramp, chroma ramps the other
|
||||
/// way, and a bright square that moves 24 pixels per frame.
|
||||
fn clip_picture(n: usize) -> VideoFrame {
|
||||
let (width, height) = CLIP_SIZE;
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let mut frame = VideoFrame::black_i420(width, height);
|
||||
let FrameData::I420 { y, u, v } = &mut frame.data else { unreachable!("black_i420") };
|
||||
let left = 32 + 24 * n;
|
||||
for row in 0..h {
|
||||
for col in 0..w {
|
||||
let square = (left..left + 64).contains(&col) && (64..128).contains(&row);
|
||||
y.data[row * w + col] = if square { 235 } else { 16 + (col * 200 / w) as u8 };
|
||||
}
|
||||
}
|
||||
let (cw, ch) = (w / 2, h / 2);
|
||||
for row in 0..ch {
|
||||
for col in 0..cw {
|
||||
u.data[row * cw + col] = 64 + (row * 128 / ch) as u8;
|
||||
v.data[row * cw + col] = 192 - (col * 128 / cw) as u8;
|
||||
}
|
||||
}
|
||||
frame.with_timestamp(Duration::from_millis(33 * n as u64))
|
||||
}
|
||||
|
||||
/// Decode `spec`'s clip: every frame's picture at once, at its size, close
|
||||
/// to the test picture; on the GPU for a hardware decoder.
|
||||
fn test_decoder(spec: &'static DecoderSpec) -> std::result::Result<(), String> {
|
||||
let reason = |e: Error| match e {
|
||||
Error::CodecUnavailable { reason, .. } => reason,
|
||||
Error::Decoder { message, .. } => message,
|
||||
e => e.to_string(),
|
||||
};
|
||||
let mut decoder = FfmpegDecoder::new(spec).map_err(reason)?;
|
||||
let mut picture = VideoFrame::black_i420(0, 0);
|
||||
let mut frames = 0;
|
||||
for (n, data) in clip_frames(spec.codec).enumerate() {
|
||||
if !decoder.decode_into(data, &mut picture).map_err(reason)? {
|
||||
return Err(format!("no picture from frame {n} of the self-test clip"));
|
||||
}
|
||||
if (picture.width, picture.height) != CLIP_SIZE {
|
||||
let (w, h) = CLIP_SIZE;
|
||||
return Err(format!(
|
||||
"frame {n} decoded at {}x{} instead of {w}x{h}",
|
||||
picture.width, picture.height
|
||||
));
|
||||
}
|
||||
let psnr = convert::psnr(&clip_picture(n), &picture).map_err(|e| e.to_string())?;
|
||||
if psnr < CLIP_PSNR {
|
||||
return Err(format!("frame {n} decoded wrong (PSNR {psnr:.1} dB)"));
|
||||
}
|
||||
frames += 1;
|
||||
}
|
||||
if frames != CLIP_FRAMES {
|
||||
return Err(format!("the {} self-test clip has {frames} frames", spec.codec));
|
||||
}
|
||||
if spec.is_hardware() && decoder.cpu_pictures > 0 {
|
||||
return Err(format!(
|
||||
"the GPU does not decode {} here (FFmpeg fell back to software){}",
|
||||
spec.codec,
|
||||
log_suffix(spec.decoder)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Why `spec` cannot work here before trying it, if that is known: not in
|
||||
/// this FFmpeg build, or (NVDEC) no NVIDIA GPU, whose driver would spend
|
||||
/// its initialisation failing.
|
||||
fn absent(ffmpeg: &Ffmpeg, spec: &DecoderSpec) -> Option<String> {
|
||||
let api = &ffmpeg.api;
|
||||
let name = cstr(spec.decoder);
|
||||
// SAFETY: a C string; returns a static codec or NULL.
|
||||
if unsafe { (api.avcodec_find_decoder_by_name)(name.as_ptr()) }.is_null() {
|
||||
return Some(format!("{} is not in this FFmpeg build", spec.decoder));
|
||||
}
|
||||
let (kind, _) = spec.hardware?;
|
||||
let name = cstr(kind);
|
||||
// SAFETY: a C string.
|
||||
if unsafe { (api.av_hwdevice_find_type_by_name)(name.as_ptr()) } <= 0 {
|
||||
return Some(format!("FFmpeg has no {kind} support"));
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
if kind == "cuda" {
|
||||
use super::encoder::{drm_vendors, vendor};
|
||||
let vendors = drm_vendors();
|
||||
if !vendors.is_empty()
|
||||
&& !vendors.contains(&vendor::NVIDIA)
|
||||
&& !std::path::Path::new("/dev/nvidiactl").exists()
|
||||
{
|
||||
return Some("no NVIDIA GPU in this machine".into());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A decoder and the result of its self-test.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DecoderStatus {
|
||||
pub spec: &'static DecoderSpec,
|
||||
/// `Ok` if it decoded the self-test clip, else why not.
|
||||
pub available: std::result::Result<(), String>,
|
||||
/// How long its self-test took (they run in parallel).
|
||||
pub took: Duration,
|
||||
}
|
||||
|
||||
/// Every decoder of [`DECODERS`] with its self-test result (run once per
|
||||
/// process, the decoders in parallel). Empty without FFmpeg.
|
||||
pub fn probe() -> &'static [DecoderStatus] {
|
||||
static PROBE: OnceLock<Vec<DecoderStatus>> = OnceLock::new();
|
||||
PROBE.get_or_init(|| {
|
||||
let Ok(ffmpeg) = Ffmpeg::get() else { return Vec::new() };
|
||||
let started = Instant::now();
|
||||
let statuses: Vec<DecoderStatus> = std::thread::scope(|scope| {
|
||||
let tests: Vec<_> = DECODERS
|
||||
.iter()
|
||||
.map(|spec| {
|
||||
let absent = absent(ffmpeg, spec);
|
||||
let test = absent.is_none().then(|| {
|
||||
scope.spawn(move || {
|
||||
let started = Instant::now();
|
||||
(test_decoder(spec), started.elapsed())
|
||||
})
|
||||
});
|
||||
(spec, absent, test)
|
||||
})
|
||||
.collect();
|
||||
tests
|
||||
.into_iter()
|
||||
.map(|(spec, absent, test)| {
|
||||
let (available, took) = match test {
|
||||
None => (Err(absent.unwrap_or_default()), Duration::ZERO),
|
||||
Some(handle) => handle.join().unwrap_or_else(|_| {
|
||||
(Err("the self-test panicked".into()), Duration::ZERO)
|
||||
}),
|
||||
};
|
||||
DecoderStatus { spec, available, took }
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
for status in &statuses {
|
||||
match &status.available {
|
||||
Ok(()) => tracing::info!(
|
||||
decoder = status.spec.name,
|
||||
ms = status.took.as_millis() as u64,
|
||||
"FFmpeg decoder available"
|
||||
),
|
||||
Err(e) => tracing::debug!(
|
||||
decoder = status.spec.name,
|
||||
ms = status.took.as_millis() as u64,
|
||||
"FFmpeg decoder unusable: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
tracing::info!(
|
||||
ms = started.elapsed().as_millis() as u64,
|
||||
tested = statuses.iter().filter(|s| !s.took.is_zero()).count(),
|
||||
"FFmpeg decoders probed"
|
||||
);
|
||||
statuses
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::codec::{Codecs, EncoderConfig};
|
||||
|
||||
#[test]
|
||||
fn decoder_table() {
|
||||
for (i, spec) in DECODERS.iter().enumerate() {
|
||||
assert!(DECODERS[..i].iter().all(|d| d.name != spec.name), "{} twice", spec.name);
|
||||
assert_eq!(DecoderSpec::by_name(spec.name), Some(spec));
|
||||
// Hardware first within a codec, so the probe's order is the
|
||||
// ladder's.
|
||||
let later_hardware =
|
||||
DECODERS[i..].iter().any(|d| d.codec == spec.codec && d.is_hardware());
|
||||
assert!(spec.is_hardware() || !later_hardware, "{} before hardware", spec.name);
|
||||
}
|
||||
assert!(DecoderSpec::by_name("h264").is_some_and(|d| !d.is_hardware()));
|
||||
}
|
||||
|
||||
/// The clips hold [`CLIP_FRAMES`] frames each, the first a keyframe.
|
||||
#[test]
|
||||
fn clips_are_complete() {
|
||||
for codec in Codec::ALL {
|
||||
let frames: Vec<&[u8]> = clip_frames(codec).collect();
|
||||
assert_eq!(frames.len(), CLIP_FRAMES, "{codec}");
|
||||
assert!(frames.iter().all(|f| !f.is_empty()), "{codec}");
|
||||
}
|
||||
}
|
||||
|
||||
/// libvpx, always built in on the desktop, decodes the VP8 and VP9 clips
|
||||
/// to the test picture: the clips and [`clip_picture`] belong together.
|
||||
#[cfg(feature = "vpx")]
|
||||
#[test]
|
||||
fn clips_match_the_test_picture() {
|
||||
for codec in [Codec::Vp8, Codec::Vp9] {
|
||||
let mut decoder = crate::codec::vpx::VpxDecoder::new(codec).unwrap();
|
||||
for (n, data) in clip_frames(codec).enumerate() {
|
||||
let picture = decoder.decode(data).unwrap().expect("a picture per frame");
|
||||
let psnr = convert::psnr(&clip_picture(n), &picture).unwrap();
|
||||
assert!(psnr > 40.0, "{codec} frame {n}: {psnr:.1} dB");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the self-test clips (`src/ffmpeg/clips/*.bin`) with the best
|
||||
/// encoder of each codec this machine has: run again only when
|
||||
/// [`clip_picture`] changes. Needs an encoder of every codec (HEVC is
|
||||
/// encoded in hardware only).
|
||||
#[test]
|
||||
#[ignore = "writes the decoders' self-test clips"]
|
||||
fn write_self_test_clips() {
|
||||
let codecs = Codecs::new();
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ffmpeg/clips");
|
||||
for codec in Codec::ALL {
|
||||
// A high bitrate for a high PSNR, the keyframe dominating.
|
||||
let config =
|
||||
EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() };
|
||||
let mut encoder = codecs.new_encoder(codec, config).unwrap();
|
||||
let mut clip = Vec::new();
|
||||
let mut frames = 0;
|
||||
// Hardware encoders may hold a frame or two.
|
||||
for n in 0..CLIP_FRAMES + 8 {
|
||||
let source = clip_picture(n.min(CLIP_FRAMES - 1));
|
||||
let source = source.with_timestamp(Duration::from_millis(33 * n as u64));
|
||||
for packet in encoder.encode(&source, n == 0).unwrap() {
|
||||
if frames < CLIP_FRAMES {
|
||||
let index = (packet.pts_90khz / 2970) as usize;
|
||||
assert_eq!(index, frames, "{codec}: packets out of order");
|
||||
assert_eq!(packet.keyframe, frames == 0, "{codec} frame {frames}");
|
||||
clip.extend_from_slice(&(packet.data.len() as u32).to_le_bytes());
|
||||
clip.extend_from_slice(&packet.data);
|
||||
frames += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(frames, CLIP_FRAMES, "{codec}");
|
||||
let name = match codec {
|
||||
Codec::H265 => "hevc".to_owned(),
|
||||
c => c.name().to_ascii_lowercase(),
|
||||
};
|
||||
std::fs::write(dir.join(format!("{name}.bin")), &clip).unwrap();
|
||||
eprintln!("{codec}: {} bytes from {}", clip.len(), encoder.backend());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,7 +485,7 @@ fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec<
|
||||
|
||||
/// The process's VA-API device: `VOELIN_VAAPI_DEVICE`, or the first DRM
|
||||
/// render node.
|
||||
struct Device(Ptr);
|
||||
pub(super) struct Device(pub(super) Ptr);
|
||||
|
||||
// SAFETY: an AVBufferRef of an AVHWDeviceContext, never freed; FFmpeg's
|
||||
// VA-API device may be used from several threads (libva locks per display).
|
||||
@@ -507,7 +507,7 @@ pub fn vaapi_device_path() -> Option<String> {
|
||||
nodes.into_iter().next()
|
||||
}
|
||||
|
||||
fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
|
||||
pub(super) fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
|
||||
static DEVICE: OnceLock<std::result::Result<Device, String>> = OnceLock::new();
|
||||
DEVICE
|
||||
.get_or_init(|| {
|
||||
@@ -610,7 +610,7 @@ pub(crate) fn vaapi_pool(
|
||||
}
|
||||
|
||||
/// FFmpeg's recent messages, appended to an error.
|
||||
fn log_suffix(context: &str) -> String {
|
||||
pub(super) fn log_suffix(context: &str) -> String {
|
||||
let log = take_log(context);
|
||||
if log.is_empty() { String::new() } else { format!(" ({})", log.join("; ")) }
|
||||
}
|
||||
@@ -1728,7 +1728,7 @@ fn in_build(ffmpeg: &Ffmpeg, name: &str) -> bool {
|
||||
|
||||
/// PCI vendor of a GPU, as `/sys/class/drm/*/device/vendor` gives it.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod vendor {
|
||||
pub(super) mod vendor {
|
||||
pub const AMD: u32 = 0x1002;
|
||||
pub const NVIDIA: u32 = 0x10de;
|
||||
pub const INTEL: u32 = 0x8086;
|
||||
@@ -1738,7 +1738,7 @@ mod vendor {
|
||||
/// `/sys/class/drm` says nothing (a container without it, say), which is
|
||||
/// taken as "unknown" and skips nothing.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn drm_vendors() -> &'static [u32] {
|
||||
pub(super) fn drm_vendors() -> &'static [u32] {
|
||||
static VENDORS: OnceLock<Vec<u32>> = OnceLock::new();
|
||||
VENDORS.get_or_init(|| {
|
||||
let Ok(entries) = std::fs::read_dir("/sys/class/drm") else { return Vec::new() };
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//! | Field | Why | How it is found | Check |
|
||||
//! |---|---|---|---|
|
||||
//! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts |
|
||||
//! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context |
|
||||
//! | `AVCodecContext.hw_frames_ctx`, `hw_device_ctx` | VA-API input frames; the device of hardware decoders | next to fields that have AVOptions, whose offsets `av_opt_find` reports: `hw_frames_ctx`, `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or `hw_frames_ctx` two fields before `max_pixels` and `hw_device_ctx` right after it (up to 60) | the neighbours' option offsets must match the layout, and both fields must be NULL in a new context |
|
||||
//! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context |
|
||||
//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool |
|
||||
//! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout |
|
||||
@@ -168,68 +168,74 @@ struct HwFields59 {
|
||||
hwaccel_flags: c_int,
|
||||
}
|
||||
|
||||
/// Where `hw_frames_ctx` is in `AVCodecContext`, from the offsets of
|
||||
/// neighbouring AVOptions, checked in a new context.
|
||||
pub fn codec_hw_frames(api: &Api) -> Result<usize, String> {
|
||||
/// Where `hw_frames_ctx` and `hw_device_ctx` are in `AVCodecContext`, from
|
||||
/// the offsets of neighbouring AVOptions, checked in a new context: the
|
||||
/// frame pool of VA-API encoders, and the device hardware decoders decode
|
||||
/// on.
|
||||
pub fn codec_hw_fields(api: &Api) -> Result<(usize, usize), String> {
|
||||
// SAFETY: a generic context (no codec); freed below.
|
||||
let mut ctx = unsafe { (api.avcodec_alloc_context3)(std::ptr::null_mut()) };
|
||||
if ctx.is_null() {
|
||||
return Err("avcodec_alloc_context3 failed".into());
|
||||
}
|
||||
let result = locate_hw_frames(api, ctx);
|
||||
let result = locate_hw_fields(api, ctx);
|
||||
// SAFETY: allocated above.
|
||||
unsafe { (api.avcodec_free_context)(&mut ctx) };
|
||||
result
|
||||
}
|
||||
|
||||
fn locate_hw_frames(api: &Api, ctx: Ptr) -> Result<usize, String> {
|
||||
fn locate_hw_fields(api: &Api, ctx: Ptr) -> Result<(usize, usize), String> {
|
||||
let offset = |name| option_offset(api, ctx, name);
|
||||
let flags = offset("hwaccel_flags").ok_or("no hwaccel_flags option")?;
|
||||
let found = 'found: {
|
||||
let (found, device) = 'found: {
|
||||
// libavcodec 61+: anchored at err_recognition and extra_hw_frames.
|
||||
if let Some(err) = offset("err_detect")
|
||||
&& let Some(base) = err.checked_sub(offset_of!(HwFieldsNew, err_recognition))
|
||||
&& base + offset_of!(HwFieldsNew, hwaccel_flags) == flags
|
||||
&& offset("extra_hw_frames") == Some(base + offset_of!(HwFieldsNew, extra_hw_frames))
|
||||
{
|
||||
break 'found base + offset_of!(HwFieldsNew, hw_frames_ctx);
|
||||
break 'found (
|
||||
base + offset_of!(HwFieldsNew, hw_frames_ctx),
|
||||
base + offset_of!(HwFieldsNew, hw_device_ctx),
|
||||
);
|
||||
}
|
||||
// Up to 60: anchored at max_pixels. `sub_text_format` (a field up to
|
||||
// 59) only matters on 32-bit targets, where the version decides.
|
||||
// SAFETY: no arguments.
|
||||
let major = unsafe { (api.avcodec_version)() } >> 16;
|
||||
if let Some(max_pixels) = offset("max_pixels") {
|
||||
let (max_off, flags_off, frames_off) = if major < 60 {
|
||||
let (max_off, flags_off, frames_off, device_off) = if major < 60 {
|
||||
(
|
||||
offset_of!(HwFields59, max_pixels),
|
||||
offset_of!(HwFields59, hwaccel_flags),
|
||||
offset_of!(HwFields59, hw_frames_ctx),
|
||||
offset_of!(HwFields59, hw_device_ctx),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
offset_of!(HwFields60, max_pixels),
|
||||
offset_of!(HwFields60, hwaccel_flags),
|
||||
offset_of!(HwFields60, hw_frames_ctx),
|
||||
offset_of!(HwFields60, hw_device_ctx),
|
||||
)
|
||||
};
|
||||
if let Some(base) = max_pixels.checked_sub(max_off)
|
||||
&& base + flags_off == flags
|
||||
{
|
||||
break 'found base + frames_off;
|
||||
break 'found (base + frames_off, base + device_off);
|
||||
}
|
||||
}
|
||||
return Err(
|
||||
"unknown AVCodecContext layout (hw_frames_ctx not next to hwaccel_flags)".into()
|
||||
);
|
||||
};
|
||||
let device = found + size_of::<Ptr>();
|
||||
// SAFETY: both offsets lie before `hwaccel_flags`, an option of this
|
||||
// context, so inside it; pointer-aligned by construction.
|
||||
let (frames, device) = unsafe { (read::<Ptr>(ctx, found), read::<Ptr>(ctx, device)) };
|
||||
if !frames.is_null() || !device.is_null() {
|
||||
let (frames, device_ref) = unsafe { (read::<Ptr>(ctx, found), read::<Ptr>(ctx, device)) };
|
||||
if !frames.is_null() || !device_ref.is_null() {
|
||||
return Err("AVCodecContext.hw_frames_ctx check failed (not NULL in a new context)".into());
|
||||
}
|
||||
Ok(found)
|
||||
Ok((found, device))
|
||||
}
|
||||
|
||||
/// Where `sample_fmt` is in `AVCodecContext`, from the offsets of the
|
||||
@@ -578,6 +584,19 @@ mod tests {
|
||||
assert_eq!(offset_of!(HwFields60, max_pixels) - offset_of!(HwFields60, hw_frames_ctx), 16);
|
||||
assert_eq!(offset_of!(HwFields59, max_pixels) - offset_of!(HwFields59, hw_frames_ctx), 16);
|
||||
assert_eq!(offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, max_pixels), 16);
|
||||
// `hw_device_ctx` right before `hwaccel_flags` in every layout.
|
||||
assert_eq!(
|
||||
offset_of!(HwFields60, hwaccel_flags) - offset_of!(HwFields60, hw_device_ctx),
|
||||
8
|
||||
);
|
||||
assert_eq!(
|
||||
offset_of!(HwFields59, hwaccel_flags) - offset_of!(HwFields59, hw_device_ctx),
|
||||
8
|
||||
);
|
||||
assert_eq!(
|
||||
offset_of!(HwFieldsNew, hwaccel_flags) - offset_of!(HwFieldsNew, hw_device_ctx),
|
||||
8
|
||||
);
|
||||
// 7.1: err_recognition 528, hw_frames_ctx 552, hwaccel_flags 568.
|
||||
assert_eq!(offset_of!(HwFieldsNew, hw_frames_ctx), 552 - 528);
|
||||
assert_eq!(offset_of!(HwFieldsNew, hwaccel_flags), 568 - 528);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! FFmpeg, loaded at runtime (feature `ffmpeg`): hardware video encoders
|
||||
//! (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox) and
|
||||
//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom).
|
||||
//! more software encoders (x264, OpenH264, SVT-AV1, rav1e, libaom); video
|
||||
//! decoders, in hardware (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox) and
|
||||
//! in software (dav1d, FFmpeg's own), see [`decoder`].
|
||||
//!
|
||||
//! FFmpeg is never linked or shipped: [`Ffmpeg::get`] finds the system's
|
||||
//! (or `VOELIN_FFMPEG_DIR`'s) libavcodec and libavutil, whatever their major
|
||||
@@ -11,7 +13,8 @@
|
||||
//!
|
||||
//! [`probe`] lists every encoder backend with the result of a self-test (one
|
||||
//! small frame encoded), so a backend whose driver or GPU is missing is
|
||||
//! skipped with a reason, without affecting the others.
|
||||
//! skipped with a reason, without affecting the others;
|
||||
//! [`decoder::probe`] does the same for decoders (a short clip decoded).
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_int};
|
||||
@@ -20,6 +23,7 @@ use std::sync::{Mutex, OnceLock};
|
||||
|
||||
pub mod audio;
|
||||
pub mod avio;
|
||||
pub mod decoder;
|
||||
pub mod encoder;
|
||||
mod gpu;
|
||||
mod layout;
|
||||
@@ -29,6 +33,7 @@ mod vpp;
|
||||
pub(crate) use gpu::Surface;
|
||||
pub use gpu::{GpuConverter, GpuLayer};
|
||||
|
||||
pub use decoder::{DECODERS, DecoderSpec, DecoderStatus, FfmpegDecoder};
|
||||
pub use encoder::{
|
||||
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
|
||||
};
|
||||
@@ -82,6 +87,8 @@ pub struct Ffmpeg {
|
||||
pub(crate) frame: FrameFields,
|
||||
/// `AVCodecContext.hw_frames_ctx`.
|
||||
pub(crate) codec_hw_frames: Result<usize, String>,
|
||||
/// `AVCodecContext.hw_device_ctx`, for hardware decoders.
|
||||
pub(crate) codec_hw_device: Result<usize, String>,
|
||||
/// `AVFrame.buf[0]` / `hw_frames_ctx`.
|
||||
pub(crate) frame_refs: Result<FrameRefs, String>,
|
||||
/// `AVCodecContext.sample_fmt`, for the AAC encoder of RTMP output.
|
||||
@@ -122,7 +129,9 @@ impl Ffmpeg {
|
||||
drm_prime: api.pix_fmt("drm_prime"),
|
||||
bgr0: api.pix_fmt("bgr0"),
|
||||
};
|
||||
let codec_hw_frames = layout::codec_hw_frames(&api);
|
||||
let hw_fields = layout::codec_hw_fields(&api);
|
||||
let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames);
|
||||
let codec_hw_device = hw_fields.map(|(_, device)| device);
|
||||
let frame_refs = layout::frame_refs(&api, yuv420p);
|
||||
let codec_sample_fmt = layout::codec_sample_fmt(&api);
|
||||
let io = libs.format_api().and_then(|format| {
|
||||
@@ -159,6 +168,7 @@ impl Ffmpeg {
|
||||
_libs: libs,
|
||||
frame,
|
||||
codec_hw_frames,
|
||||
codec_hw_device,
|
||||
frame_refs,
|
||||
codec_sample_fmt,
|
||||
io,
|
||||
@@ -292,6 +302,15 @@ mod tests {
|
||||
if cfg!(target_pointer_width = "64") {
|
||||
assert!(ffmpeg.frame_refs.is_ok(), "{:?}", ffmpeg.frame_refs);
|
||||
}
|
||||
// `hw_device_ctx`, where FFmpeg 9's headers put it (libavcodec 63:
|
||||
// `hw_frames_ctx` 552, `hw_device_ctx` 560 on x86-64).
|
||||
let (frames, device) = (ffmpeg.codec_hw_frames.clone(), ffmpeg.codec_hw_device.clone());
|
||||
// SAFETY: no arguments.
|
||||
if cfg!(target_pointer_width = "64")
|
||||
&& unsafe { (ffmpeg.api.avcodec_version)() } >> 16 == 63
|
||||
{
|
||||
assert_eq!((frames, device), (Ok(552), Ok(560)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `AVIOContext.error` is where the headers of the installed releases
|
||||
|
||||
@@ -226,6 +226,7 @@ api! {
|
||||
fn av_opt_child_next(obj: Ptr, prev: Ptr) -> Ptr;
|
||||
fn av_strerror(errnum: c_int, buf: *mut c_char, size: usize) -> c_int;
|
||||
fn av_get_pix_fmt(name: *const c_char) -> c_int;
|
||||
fn av_get_pix_fmt_name(fmt: c_int) -> *const c_char;
|
||||
fn av_log_set_level(level: c_int);
|
||||
fn av_log_set_callback(callback: Option<LogCallback>);
|
||||
fn av_log_format_line2(
|
||||
@@ -617,6 +618,17 @@ impl Api {
|
||||
let fmt = unsafe { (self.av_get_pix_fmt)(name.as_ptr()) };
|
||||
(fmt >= 0).then_some(fmt)
|
||||
}
|
||||
|
||||
/// The name of pixel format `fmt` (for messages).
|
||||
pub fn pix_fmt_name(&self, fmt: c_int) -> String {
|
||||
// SAFETY: returns a static string, or NULL for an unknown format.
|
||||
let name = unsafe { (self.av_get_pix_fmt_name)(fmt) };
|
||||
if name.is_null() {
|
||||
return format!("pixel format {fmt}");
|
||||
}
|
||||
// SAFETY: a NUL-terminated static string.
|
||||
unsafe { CStr::from_ptr(name) }.to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -89,11 +89,19 @@ impl<'a> PlaneRef<'a> {
|
||||
|
||||
/// A tightly packed copy of `width` x `rows` bytes.
|
||||
fn to_plane(self, width: usize, rows: usize) -> Plane {
|
||||
let mut data = Vec::with_capacity(width * rows);
|
||||
let mut plane = Plane::new(Vec::with_capacity(width * rows), width);
|
||||
self.copy_into(&mut plane, width, rows);
|
||||
plane
|
||||
}
|
||||
|
||||
/// As [`to_plane`](Self::to_plane), into `dst`'s buffer (which only
|
||||
/// grows).
|
||||
fn copy_into(self, dst: &mut Plane, width: usize, rows: usize) {
|
||||
dst.data.clear();
|
||||
for y in 0..rows {
|
||||
data.extend_from_slice(self.row(y, width));
|
||||
dst.data.extend_from_slice(self.row(y, width));
|
||||
}
|
||||
Plane::new(data, width)
|
||||
dst.stride = width;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,6 +187,33 @@ impl FrameRef<'_> {
|
||||
};
|
||||
VideoFrame { width: self.width, height: self.height, timestamp: self.timestamp, data }
|
||||
}
|
||||
|
||||
/// As [`to_frame`](Self::to_frame), into `out`: its buffers are reused
|
||||
/// when it has this pixel format, so copying frames of one size into the
|
||||
/// same `out` allocates nothing after the first.
|
||||
pub fn copy_to(&self, out: &mut VideoFrame) {
|
||||
let (w, h) = (self.width as usize, self.height as usize);
|
||||
let (cw, ch) = chroma_size(self.width, self.height);
|
||||
match (self.pixels, &mut out.data) {
|
||||
(PixelsRef::I420 { y, u, v }, FrameData::I420 { y: oy, u: ou, v: ov }) => {
|
||||
y.copy_into(oy, w, h);
|
||||
u.copy_into(ou, cw, ch);
|
||||
v.copy_into(ov, cw, ch);
|
||||
}
|
||||
(PixelsRef::Nv12 { y, uv }, FrameData::Nv12 { y: oy, uv: ouv }) => {
|
||||
y.copy_into(oy, w, h);
|
||||
uv.copy_into(ouv, cw * 2, ch);
|
||||
}
|
||||
(PixelsRef::Bgra(p), FrameData::Bgra(o)) | (PixelsRef::Rgba(p), FrameData::Rgba(o)) => {
|
||||
p.copy_into(o, w * 4, h);
|
||||
}
|
||||
_ => {
|
||||
*out = self.to_frame();
|
||||
return;
|
||||
}
|
||||
}
|
||||
(out.width, out.height, out.timestamp) = (self.width, self.height, self.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels of a [`VideoFrame`].
|
||||
@@ -418,4 +453,25 @@ mod tests {
|
||||
assert!(short.validate().is_err());
|
||||
assert_eq!(VideoFrame::black_i420(5, 3).view().format(), PixelFormat::I420);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_reuse_the_destination() {
|
||||
let source = VideoFrame::black_i420(33, 17).with_timestamp(Duration::from_millis(7));
|
||||
let mut out = VideoFrame::from_bgra(1, 1, 4, vec![0; 4]).unwrap();
|
||||
source.view().copy_to(&mut out);
|
||||
assert_eq!(out, source, "another format: replaced");
|
||||
let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") };
|
||||
let buffer = y.data.as_ptr();
|
||||
let smaller = VideoFrame::black_i420(20, 10);
|
||||
smaller.view().copy_to(&mut out);
|
||||
assert_eq!(out, smaller);
|
||||
let FrameData::I420 { y, .. } = &out.data else { panic!("not I420") };
|
||||
assert_eq!(y.data.as_ptr(), buffer, "the same buffer");
|
||||
let nv12 = FrameRef {
|
||||
pixels: PixelsRef::Nv12 { y: PlaneRef::new(&[1; 4], 2), uv: PlaneRef::new(&[2; 2], 2) },
|
||||
..VideoFrame::black_i420(2, 2).view()
|
||||
};
|
||||
nv12.copy_to(&mut out);
|
||||
assert_eq!(out, nv12.to_frame());
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,9 @@ pub mod workers;
|
||||
|
||||
pub use capture::{AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId};
|
||||
pub use codec::{
|
||||
BackendChoice, Codec, Codecs, ContentHint, EncodedChunk, EncodedFrame, EncoderBackend,
|
||||
EncoderConfig, EncoderInfo, EncoderPreference, EncoderReport, H264Profile, VideoDecoder,
|
||||
VideoEncoder,
|
||||
BackendChoice, Codec, Codecs, ContentHint, DecoderBackend, DecoderInfo, DecoderPreference,
|
||||
EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, EncoderInfo, EncoderPreference,
|
||||
EncoderReport, H264Profile, VideoDecoder, VideoEncoder,
|
||||
};
|
||||
pub use frame::{
|
||||
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! FFmpeg's decoders allocate nothing per picture once running: every
|
||||
//! decoder that passed its self-test (hardware ones included: the GPU's
|
||||
//! pictures are copied through a frame of our own) decodes into the same
|
||||
//! `VideoFrame` with `decode_into`, counted with a global allocator that
|
||||
//! counts only on the thread that asks. FFmpeg's own buffers are malloc'd
|
||||
//! by FFmpeg and pooled by it; they are not Rust allocations.
|
||||
#![cfg(feature = "ffmpeg")]
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::Cell;
|
||||
use std::time::Duration;
|
||||
|
||||
use voelin_media::capture::synthetic::SyntheticScreen;
|
||||
use voelin_media::ffmpeg::{FfmpegDecoder, decoder};
|
||||
use voelin_media::{Codecs, EncoderConfig, VideoDecoder, VideoFrame};
|
||||
|
||||
thread_local! {
|
||||
static COUNTING: Cell<bool> = const { Cell::new(false) };
|
||||
static COUNT: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
fn count() {
|
||||
// `try_with`: never panics, also while the thread is torn down; const
|
||||
// thread locals without destructors never allocate.
|
||||
let _ = COUNTING.try_with(|on| {
|
||||
if on.get() {
|
||||
let _ = COUNT.try_with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
struct Counting;
|
||||
|
||||
// SAFETY: every method forwards to `System` with the caller's arguments
|
||||
// unchanged, so `System`'s guarantees hold; counting touches only
|
||||
// thread-local cells and never allocates.
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
count();
|
||||
// SAFETY: forwarded unchanged (see above).
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
|
||||
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
||||
count();
|
||||
// SAFETY: forwarded unchanged.
|
||||
unsafe { System.alloc_zeroed(layout) }
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
count();
|
||||
// SAFETY: forwarded unchanged.
|
||||
unsafe { System.realloc(ptr, layout, new_size) }
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
// SAFETY: forwarded unchanged.
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: Counting = Counting;
|
||||
|
||||
/// Allocations `f` makes on this thread.
|
||||
fn allocations(f: impl FnOnce()) -> u64 {
|
||||
COUNT.with(|n| n.set(0));
|
||||
COUNTING.with(|on| on.set(true));
|
||||
f();
|
||||
COUNTING.with(|on| on.set(false));
|
||||
COUNT.with(Cell::get)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoders_allocate_nothing_per_picture() {
|
||||
assert_eq!(allocations(|| drop(std::hint::black_box(vec![0u8; 16]))), 1);
|
||||
let codecs = Codecs::new();
|
||||
let screen = SyntheticScreen::new(640, 360);
|
||||
let mut tested = Vec::new();
|
||||
for status in decoder::probe().iter().filter(|s| s.available.is_ok()) {
|
||||
let codec = status.spec.codec;
|
||||
let config = EncoderConfig { fps: 30, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
|
||||
let Ok(mut encoder) = codecs.new_encoder(codec, config) else { continue };
|
||||
let mut stream = Vec::new();
|
||||
for n in 0..40u64 {
|
||||
let frame = screen.frame(n, 30).with_timestamp(Duration::from_millis(33 * n));
|
||||
stream.extend(encoder.encode(&frame, n == 0).unwrap().into_iter().map(|f| f.data));
|
||||
}
|
||||
let mut decoder = FfmpegDecoder::new(status.spec).unwrap();
|
||||
let mut picture = VideoFrame::black_i420(0, 0);
|
||||
// The first pictures size the buffers.
|
||||
for data in &stream[..10] {
|
||||
decoder.decode_into(data, &mut picture).unwrap();
|
||||
}
|
||||
let mut decoded = 0;
|
||||
let counted = allocations(|| {
|
||||
for data in &stream[10..] {
|
||||
decoded += usize::from(decoder.decode_into(data, &mut picture).unwrap());
|
||||
}
|
||||
});
|
||||
eprintln!("{}: {counted} allocations for {decoded} pictures", status.spec.name);
|
||||
assert!(decoded + 3 >= stream.len() - 10, "{}: {decoded} pictures", status.spec.name);
|
||||
assert_eq!(counted, 0, "{}", status.spec.name);
|
||||
tested.push(status.spec.name);
|
||||
}
|
||||
eprintln!("tested: {tested:?}");
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! Decoders through the system's FFmpeg (loaded at runtime): the probe, the
|
||||
//! ladder of each codec, every encoder of this machine against every decoder
|
||||
//! of its codec, VA-API decoding on the GPU, and the codecs a viewer accepts
|
||||
//! with and without FFmpeg.
|
||||
//!
|
||||
//! Skipped without FFmpeg. Hardware decoders need their GPU and driver; on a
|
||||
//! machine without them the self-test reports why and they are skipped.
|
||||
#![cfg(feature = "ffmpeg")]
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use voelin_media::capture::synthetic::SyntheticScreen;
|
||||
use voelin_media::ffmpeg::{DECODERS, DecoderSpec, Ffmpeg, FfmpegDecoder, decoder};
|
||||
use voelin_media::{
|
||||
Codec, Codecs, DecoderBackend, EncodedFrame, EncoderConfig, EncoderPreference, VideoDecoder,
|
||||
VideoFrame, convert,
|
||||
};
|
||||
|
||||
fn ffmpeg() -> Option<&'static Ffmpeg> {
|
||||
match Ffmpeg::get() {
|
||||
Ok(f) => Some(f),
|
||||
Err(e) => {
|
||||
eprintln!("FFmpeg not available ({e}), skipped");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn available(name: &str) -> bool {
|
||||
decoder::probe().iter().any(|s| s.spec.name == name && s.available.is_ok())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_reports_every_decoder() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let statuses = decoder::probe();
|
||||
assert_eq!(statuses.len(), DECODERS.len());
|
||||
for status in statuses {
|
||||
eprintln!(
|
||||
"{:>18}: {:?} ({} ms)",
|
||||
status.spec.name,
|
||||
status.available,
|
||||
status.took.as_millis()
|
||||
);
|
||||
if let Err(reason) = &status.available {
|
||||
assert!(!reason.is_empty());
|
||||
}
|
||||
}
|
||||
// The report lists them with the built-in ones, ranked by the ladder.
|
||||
let codecs = Codecs::new();
|
||||
let report = codecs.report();
|
||||
assert!(report.decoders.iter().any(|d| d.name == "libvpx"));
|
||||
for status in statuses {
|
||||
let info = report.decoders.iter().find(|d| d.name == status.spec.name).unwrap();
|
||||
assert_eq!(info.status, status.available);
|
||||
assert_eq!(info.rank.is_some(), status.available.is_ok(), "{}", status.spec.name);
|
||||
}
|
||||
for codec in Codec::ALL {
|
||||
let ladder: Vec<String> =
|
||||
codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect();
|
||||
eprintln!("{codec}: {}", ladder.join(" > "));
|
||||
}
|
||||
eprintln!("viewer accepts: {:?}", codecs.decoders());
|
||||
// FFmpeg's software decoders are in every build: a viewer takes every
|
||||
// codec but AV1 (which needs dav1d or libaom in FFmpeg) with them.
|
||||
for (name, codec) in [("h264", Codec::H264), ("hevc", Codec::H265), ("vp9", Codec::Vp9)] {
|
||||
if available(name) {
|
||||
assert!(codecs.decoders().contains(&codec), "{codec}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `frames` of the moving test pattern at `w` x `h` through `encoder`'s
|
||||
/// best backend (`backend` named first), with a keyframe at the start.
|
||||
fn encode(codec: Codec, backend: &str, w: u32, h: u32, frames: u64) -> Vec<(EncodedFrame, u64)> {
|
||||
let codecs = Codecs::new();
|
||||
let screen = SyntheticScreen::new(w, h);
|
||||
let config = EncoderConfig { fps: 30, bitrate_bps: 2_000_000, ..EncoderConfig::default() };
|
||||
let preference = EncoderPreference { hardware: true, backend: backend.parse().unwrap() };
|
||||
let mut encoder = codecs.new_encoder_preferring(codec, config, &preference).unwrap();
|
||||
let mut out = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
for n in 0..frames + 8 {
|
||||
let frame = screen.frame(n.min(frames - 1), 30);
|
||||
let frame = frame.with_timestamp(Duration::from_millis(33 * n));
|
||||
sources.push(frame.pts_90khz());
|
||||
for f in encoder.encode(&frame, n == 0).unwrap() {
|
||||
let index = sources.iter().position(|&p| p == f.pts_90khz).unwrap() as u64;
|
||||
if out.len() < frames as usize {
|
||||
out.push((f, index.min(frames - 1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Decodes `stream` with `decoder`: the PSNR of every picture against the
|
||||
/// pattern frame it came from, or why it failed.
|
||||
fn decode(
|
||||
decoder: &mut dyn VideoDecoder,
|
||||
stream: &[(EncodedFrame, u64)],
|
||||
screen: &SyntheticScreen,
|
||||
) -> Result<(usize, f64), String> {
|
||||
let mut picture = VideoFrame::black_i420(0, 0);
|
||||
let mut worst = f64::INFINITY;
|
||||
let mut decoded = 0;
|
||||
for (frame, index) in stream {
|
||||
if decoder.decode_into(&frame.data, &mut picture).map_err(|e| e.to_string())? {
|
||||
let source = screen.frame(*index, 30);
|
||||
let source = if (picture.width, picture.height) == (source.width, source.height) {
|
||||
source
|
||||
} else {
|
||||
// Cropped to the encoder's alignment (AV1 in hardware).
|
||||
let mut view = source.view();
|
||||
(view.width, view.height) = (picture.width, picture.height);
|
||||
view.to_frame()
|
||||
};
|
||||
worst = worst.min(convert::psnr(&source, &picture).map_err(|e| e.to_string())?);
|
||||
decoded += 1;
|
||||
}
|
||||
}
|
||||
Ok((decoded, worst))
|
||||
}
|
||||
|
||||
/// Every encoder this machine has, through every decoder of its codec
|
||||
/// (hardware, FFmpeg's software ones, the built-in ones): every frame
|
||||
/// decodes, PSNR above 28 dB against the pattern, as `tests/ffmpeg.rs`
|
||||
/// checks the encoders.
|
||||
#[test]
|
||||
fn every_encoder_decodes_with_every_decoder() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let codecs = Codecs::new();
|
||||
let (w, h) = (320, 240);
|
||||
let screen = SyntheticScreen::new(w, h);
|
||||
let mut table = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
for (codec, encoder) in codecs.encoders() {
|
||||
let stream = encode(codec, encoder.name(), w, h, 12);
|
||||
for backend in codecs.decoders_for(codec) {
|
||||
let mut decoder = codecs.new_decoder_with(codec, backend).unwrap();
|
||||
match decode(&mut *decoder, &stream, &screen) {
|
||||
Ok((decoded, psnr)) if decoded == stream.len() && psnr > 28.0 => {
|
||||
table.push(format!("{codec:<4} {encoder:<12} -> {backend:<12} {psnr:5.1} dB"));
|
||||
}
|
||||
Ok((decoded, psnr)) => failed.push(format!(
|
||||
"{encoder} -> {backend}: {decoded} of {} pictures, PSNR {psnr:.1} dB",
|
||||
stream.len()
|
||||
)),
|
||||
Err(e) => failed.push(format!("{encoder} -> {backend}: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("{}", table.join("\n"));
|
||||
assert!(failed.is_empty(), "{}", failed.join("\n"));
|
||||
}
|
||||
|
||||
/// The VA-API decoders that passed their self-test decode on the GPU: every
|
||||
/// picture of a stream comes out of a VA-API surface, none from FFmpeg's
|
||||
/// software path; at 1920x1080 too (1088 coded rows, cropped). Skipped
|
||||
/// where no VA-API decoder works.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn vaapi_decodes_on_the_gpu() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let names: Vec<&str> =
|
||||
DECODERS.iter().map(|d| d.name).filter(|n| n.ends_with("_vaapi") && available(n)).collect();
|
||||
if names.is_empty() {
|
||||
eprintln!("no usable VA-API decoder, skipped");
|
||||
return;
|
||||
}
|
||||
let codecs = Codecs::new();
|
||||
for name in &names {
|
||||
let spec = DecoderSpec::by_name(name).unwrap();
|
||||
if codecs.encoders().iter().all(|(c, _)| *c != spec.codec) {
|
||||
eprintln!("{name}: nothing here encodes {}, skipped", spec.codec);
|
||||
continue;
|
||||
}
|
||||
for (w, h) in [(320, 240), (1920, 1080)] {
|
||||
let stream = encode(spec.codec, "auto", w, h, 10);
|
||||
let mut decoder = FfmpegDecoder::new(spec).unwrap();
|
||||
let screen = SyntheticScreen::new(w, h);
|
||||
let started = Instant::now();
|
||||
let (decoded, psnr) = decode(&mut decoder, &stream, &screen).unwrap();
|
||||
eprintln!(
|
||||
"{name} {w}x{h}: {decoded} pictures, {} on the GPU, PSNR {psnr:.1} dB, {:.1} ms each",
|
||||
decoder.gpu_pictures(),
|
||||
started.elapsed().as_secs_f64() * 1000.0 / decoded.max(1) as f64
|
||||
);
|
||||
assert_eq!(decoded, stream.len(), "{name}");
|
||||
assert_eq!(decoder.gpu_pictures(), decoded as u64, "{name}: not on the GPU");
|
||||
assert_eq!(decoder.cpu_pictures(), 0, "{name}");
|
||||
assert!(psnr > 28.0, "{name}: {psnr:.1} dB");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a viewer accepts with FFmpeg and without (`VOELIN_FFMPEG=0`, in a
|
||||
/// child process: FFmpeg is loaded once per process).
|
||||
#[test]
|
||||
fn decoders_with_and_without_ffmpeg() {
|
||||
let without = std::env::var("VOELIN_FFMPEG").is_ok_and(|v| v == "0");
|
||||
let codecs = Codecs::new();
|
||||
let decoders = codecs.decoders();
|
||||
eprintln!("VOELIN_FFMPEG={without}: {decoders:?}");
|
||||
if without {
|
||||
// Only the built-in decoders: libvpx (and dav1d with `av1`).
|
||||
assert!(Ffmpeg::get().is_err());
|
||||
assert!(decoder::probe().is_empty());
|
||||
assert!(!decoders.contains(&Codec::H265) && !decoders.contains(&Codec::H264));
|
||||
assert_eq!(decoders.contains(&Codec::Av1), cfg!(feature = "av1"));
|
||||
#[cfg(feature = "vpx")]
|
||||
assert_eq!(decoders[decoders.len() - 2..], [Codec::Vp9, Codec::Vp8]);
|
||||
let ladder = codecs.decoders_for(Codec::Vp9);
|
||||
assert!(ladder.iter().all(|b| !matches!(b, DecoderBackend::Ffmpeg(_))), "{ladder:?}");
|
||||
return;
|
||||
}
|
||||
if ffmpeg().is_some() {
|
||||
// The software decoders of every FFmpeg build.
|
||||
for codec in [Codec::H265, Codec::Vp9, Codec::H264, Codec::Vp8] {
|
||||
assert!(decoders.contains(&codec), "{codec}: {decoders:?}");
|
||||
}
|
||||
// The viewer's order: best first.
|
||||
let order: Vec<usize> = decoders
|
||||
.iter()
|
||||
.map(|c| voelin_media::codec::VIEWER_PREFERENCE.iter().position(|p| p == c).unwrap())
|
||||
.collect();
|
||||
assert!(order.windows(2).all(|w| w[0] < w[1]), "{decoders:?}");
|
||||
}
|
||||
let child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "decoders_with_and_without_ffmpeg", "--nocapture"])
|
||||
.env("VOELIN_FFMPEG", "0")
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(child.success(), "without FFmpeg: {child}");
|
||||
}
|
||||
|
||||
/// The access units of an Annex B H.264 stream that has access unit
|
||||
/// delimiters (`aud=1` in x264, `-aud 1` in VA-API), as a stream's frames.
|
||||
fn access_units(stream: &[u8]) -> Vec<&[u8]> {
|
||||
let mut starts = Vec::new();
|
||||
let mut i = 0;
|
||||
while i + 3 < stream.len() {
|
||||
if stream[i..i + 3] == [0, 0, 1] {
|
||||
if stream[i + 3] & 0x1f == 9 {
|
||||
starts.push(if i > 0 && stream[i - 1] == 0 { i - 1 } else { i });
|
||||
}
|
||||
i += 3;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
starts.push(stream.len());
|
||||
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
|
||||
}
|
||||
|
||||
/// A 32x18 luma thumbnail (block averages), to compare pictures cheaply.
|
||||
fn thumbnail(picture: &VideoFrame) -> Vec<u8> {
|
||||
let y = match &picture.data {
|
||||
voelin_media::FrameData::I420 { y, .. } | voelin_media::FrameData::Nv12 { y, .. } => y,
|
||||
_ => panic!("not YUV"),
|
||||
};
|
||||
let (w, bw, bh) =
|
||||
(picture.width as usize, picture.width as usize / 32, picture.height as usize / 18);
|
||||
let mut out = Vec::with_capacity(32 * 18);
|
||||
for by in 0..18 {
|
||||
for bx in 0..32 {
|
||||
let sum: u64 = (by * bh..(by + 1) * bh)
|
||||
.map(|row| {
|
||||
y.row(row, w)[bx * bw..(bx + 1) * bw].iter().map(|&p| u64::from(p)).sum::<u64>()
|
||||
})
|
||||
.sum();
|
||||
out.push((sum / (bw * bh) as u64) as u8);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Make `path` with the `ffmpeg` command from `args` (output options
|
||||
/// last), unless it is there; whether it is.
|
||||
fn ffmpeg_command(path: &std::path::Path, args: &[&str]) -> bool {
|
||||
if path.exists() {
|
||||
return true;
|
||||
}
|
||||
let made = std::process::Command::new("ffmpeg")
|
||||
.args(["-hide_banner", "-loglevel", "error", "-y"])
|
||||
.args(args)
|
||||
.arg(path)
|
||||
.status();
|
||||
if !made.is_ok_and(|s| s.success()) {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The temporal units of a low-overhead AV1 stream (`-f obu`), each
|
||||
/// starting with a temporal delimiter OBU.
|
||||
fn temporal_units(stream: &[u8]) -> Vec<&[u8]> {
|
||||
let mut starts = Vec::new();
|
||||
let mut pos = 0;
|
||||
while pos < stream.len() {
|
||||
let header = stream[pos];
|
||||
if (header >> 3) & 0xf == 2 {
|
||||
starts.push(pos);
|
||||
}
|
||||
// Every OBU of such a stream has its size (LEB128).
|
||||
let (mut at, mut size, mut shift) = (pos + 1 + usize::from(header & 4 != 0), 0, 0);
|
||||
loop {
|
||||
let byte = stream[at];
|
||||
at += 1;
|
||||
size |= usize::from(byte & 0x7f) << shift;
|
||||
shift += 7;
|
||||
if byte & 0x80 == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
pos = at + size;
|
||||
}
|
||||
starts.push(stream.len());
|
||||
starts.windows(2).map(|w| &stream[w[0]..w[1]]).collect()
|
||||
}
|
||||
|
||||
/// Streams of ten seconds of `testsrc2` at 2560x1440 and 60 fps, made with
|
||||
/// the `ffmpeg` command from each encoder's `args` (kept in the temporary
|
||||
/// directory, made again only when missing).
|
||||
fn streams_1440p60(
|
||||
encoders: &[(&'static str, &str)],
|
||||
format: &str,
|
||||
) -> Vec<(&'static str, Vec<u8>)> {
|
||||
let dir = std::env::temp_dir().join("voelin-h264-bframes");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = "-f lavfi -i testsrc2=size=2560x1440:rate=60 -t 10";
|
||||
let mut streams = Vec::new();
|
||||
for &(name, args) in encoders {
|
||||
let vaapi = name.ends_with("_vaapi");
|
||||
let device = if vaapi { "-vaapi_device /dev/dri/renderD128 " } else { "" };
|
||||
let upload = if vaapi { "-vf format=nv12,hwupload " } else { "" };
|
||||
let args = format!("{device}{source} {upload}{args} -g 600 -b:v 8M -f {format}");
|
||||
let suffix = if format == "h264" { "-bframes" } else { "" };
|
||||
let path = dir.join(format!("{name}{suffix}-1440p60.{format}"));
|
||||
let args: Vec<&str> = args.split(' ').collect();
|
||||
if ffmpeg_command(&path, &args) {
|
||||
streams.push((name, std::fs::read(&path).unwrap()));
|
||||
} else {
|
||||
eprintln!("{name}: the ffmpeg command did not make the stream, skipped");
|
||||
}
|
||||
}
|
||||
streams
|
||||
}
|
||||
|
||||
/// Every decoder of `codec`'s ladder (and OpenH264 with
|
||||
/// `VOELIN_OPENH264_LIB`, for H.264) on each of `streams` (frames as
|
||||
/// `split` cuts them), as fast as it goes: pictures, errors, pictures per
|
||||
/// second of decoding (copied into a `VideoFrame`), the slowest frame, and
|
||||
/// the pictures that differ from those of `reference`, which comes first
|
||||
/// in the ladder's software part. Hardware decoders must decode every
|
||||
/// picture.
|
||||
fn decode_rates(
|
||||
codec: Codec,
|
||||
what: &str,
|
||||
streams: &[(&str, Vec<u8>)],
|
||||
split: fn(&[u8]) -> Vec<&[u8]>,
|
||||
reference: &str,
|
||||
) {
|
||||
let codecs = Codecs::new();
|
||||
let openh264 = std::env::var_os("VOELIN_OPENH264_LIB")
|
||||
.filter(|_| codec == Codec::H264)
|
||||
.map(|path| voelin_media::codec::h264::OpenH264::load(path).unwrap());
|
||||
let mut names: Vec<String> = codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect();
|
||||
// The reference first, so that every other decoder is compared with it.
|
||||
names.sort_by_key(|n| n != reference);
|
||||
names.extend(openh264.as_ref().map(|_| "openh264".to_owned()));
|
||||
for (stream, data) in streams {
|
||||
let units = split(data);
|
||||
let mut reference: Option<Vec<Vec<u8>>> = None;
|
||||
for name in &names {
|
||||
let mut decoder: Box<dyn VideoDecoder> = match (name.as_str(), &openh264) {
|
||||
("openh264", Some(library)) => Box::new(library.decoder().unwrap()),
|
||||
_ => {
|
||||
let backend = codecs.decoders_for(codec).into_iter().find(|b| b.name() == name);
|
||||
codecs.new_decoder_with(codec, backend.unwrap()).unwrap()
|
||||
}
|
||||
};
|
||||
let mut picture = VideoFrame::black_i420(0, 0);
|
||||
let mut thumbnails = Vec::with_capacity(units.len());
|
||||
let (mut errors, mut slowest, mut busy) = (0, Duration::ZERO, Duration::ZERO);
|
||||
for unit in &units {
|
||||
let started = Instant::now();
|
||||
let result = decoder.decode_into(unit, &mut picture);
|
||||
let took = started.elapsed();
|
||||
(slowest, busy) = (slowest.max(took), busy + took);
|
||||
match result {
|
||||
Ok(true) => {
|
||||
assert_eq!((picture.width, picture.height), (2560, 1440), "{name}");
|
||||
thumbnails.push(thumbnail(&picture));
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(_) => errors += 1,
|
||||
}
|
||||
}
|
||||
let fps = thumbnails.len() as f64 / busy.as_secs_f64();
|
||||
let differing = reference.as_ref().map_or(0, |reference| {
|
||||
let differs = |(a, b): &(&Vec<u8>, &Vec<u8>)| {
|
||||
a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 3)
|
||||
};
|
||||
thumbnails.iter().zip(reference).filter(differs).count()
|
||||
});
|
||||
eprintln!(
|
||||
"{stream} 2560x1440@60{what}, {name}: {} of {} pictures, {errors} errors, {fps:.0} \
|
||||
fps, slowest frame {:.1} ms, {differing} differ from the reference decoder",
|
||||
thumbnails.len(),
|
||||
units.len(),
|
||||
slowest.as_secs_f64() * 1000.0,
|
||||
);
|
||||
if reference.is_none() {
|
||||
reference = Some(thumbnails);
|
||||
} else if name.ends_with("_vaapi") {
|
||||
assert_eq!(errors, 0, "{name}");
|
||||
assert!(thumbnails.len() + 3 >= units.len(), "{name}: pictures missing");
|
||||
assert_eq!(differing, 0, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// H.264 with B-frames at 2560x1440 and 60 fps, like the official client's
|
||||
/// stream (AMF with B-frames and rare keyframes): every H.264 decoder of
|
||||
/// the ladder, and Cisco's OpenH264 with `VOELIN_OPENH264_LIB`, decodes it;
|
||||
/// how fast, the slowest frame, and whether every picture comes out, in
|
||||
/// order (against FFmpeg's software decoder). The streams come from the
|
||||
/// `ffmpeg` command: x264 with 3 B-frames, `h264_vaapi` with 2, ten
|
||||
/// seconds of `testsrc2` at 8 Mbit/s, keyframes every ten seconds. Run with
|
||||
/// `--release`.
|
||||
#[test]
|
||||
#[ignore = "a measurement: needs the ffmpeg command; run with --release"]
|
||||
fn h264_with_b_frames_at_1440p60() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let streams = streams_1440p60(
|
||||
&[
|
||||
(
|
||||
"x264",
|
||||
"-c:v libx264 -preset veryfast -profile:v high -bf 3 -x264-params aud=1 -pix_fmt yuv420p -maxrate 9M -bufsize 9M",
|
||||
),
|
||||
("h264_vaapi", "-c:v h264_vaapi -profile:v high -bf 2 -aud 1 -maxrate 9M"),
|
||||
],
|
||||
"h264",
|
||||
);
|
||||
decode_rates(Codec::H264, " with B-frames", &streams, access_units, "h264");
|
||||
// What a viewer adds per picture: the NV12 or I420 picture to RGBA.
|
||||
let mut rgba = vec![0; 2560 * 1440 * 4];
|
||||
let i420 = VideoFrame::black_i420(2560, 1440);
|
||||
let started = Instant::now();
|
||||
for _ in 0..30 {
|
||||
convert::to_rgba(&i420, &mut rgba, 2560 * 4).unwrap();
|
||||
}
|
||||
eprintln!("to RGBA at 2560x1440: {:.1} ms", started.elapsed().as_secs_f64() * 1000.0 / 30.0);
|
||||
}
|
||||
|
||||
/// AV1 at 2560x1440 and 60 fps, which the official client sends from GPUs
|
||||
/// that encode it: every AV1 decoder of the ladder, against dav1d. Streams
|
||||
/// from `av1_vaapi` (hardware, as the official client's AMF) and SVT-AV1.
|
||||
/// Run with `--release`.
|
||||
#[test]
|
||||
#[ignore = "a measurement: needs the ffmpeg command; run with --release"]
|
||||
fn av1_at_1440p60() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let streams = streams_1440p60(
|
||||
&[("av1_vaapi", "-c:v av1_vaapi"), ("libsvtav1", "-c:v libsvtav1 -preset 10")],
|
||||
"obu",
|
||||
);
|
||||
decode_rates(Codec::Av1, "", &streams, temporal_units, "libdav1d");
|
||||
}
|
||||
@@ -53,7 +53,8 @@ fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
|
||||
fn roundtrip(library: OpenH264) {
|
||||
let codecs = Codecs::builtin().with_openh264(library.clone());
|
||||
assert_eq!(codecs.decoders().last(), Some(&Codec::H264));
|
||||
assert!(codecs.decoders().contains(&Codec::H264));
|
||||
assert_eq!(codecs.decoders_for(Codec::H264), [voelin_media::DecoderBackend::OpenH264]);
|
||||
assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));
|
||||
|
||||
let screen = SyntheticScreen::new(320, 240);
|
||||
|
||||
@@ -17,7 +17,11 @@ use anyhow::{Context, Result};
|
||||
use slint::{ComponentHandle, ModelRc, VecModel};
|
||||
use tokio::runtime::Runtime;
|
||||
use tracing::warn;
|
||||
use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings};
|
||||
use voelin_core::media::decoder_preference;
|
||||
use voelin_core::settings::{
|
||||
AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING,
|
||||
Settings,
|
||||
};
|
||||
use voelin_core::stream::StreamInfo;
|
||||
use voelin_core::{
|
||||
AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState,
|
||||
@@ -527,16 +531,30 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
Ok(history) => engine.send(Command::AttachHistory(history)),
|
||||
Err(e) => warn!(%e, "chat history is not stored this time"),
|
||||
}
|
||||
let prefs = open_settings(&dir, &options.setting_overrides);
|
||||
let switches = crate::dev::Switches::from_env();
|
||||
// New identities of the official TeamSpeak clients, on every start (not
|
||||
// with the sample data of VOELIN_DEMO_UI); with none of our own yet, the
|
||||
// client's default identity becomes ours.
|
||||
let had_identity = !store.identities()?.is_empty();
|
||||
let imported = if prefs.get(&IDENTITY_IMPORT) && !switches.demo_ui {
|
||||
voelin_core::identity::import_new(&store, &voelin_core::identity::discover())
|
||||
.unwrap_or_else(|e| {
|
||||
warn!(%e, "could not import TeamSpeak identities");
|
||||
Vec::new()
|
||||
})
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let identity = match store.identities()?.first() {
|
||||
Some(entry) => store.identity(entry.id)?,
|
||||
None => {
|
||||
// Creating an identity takes a moment (security level 8).
|
||||
let identity = tsclientlib::Identity::create();
|
||||
store.add_identity("Default", &identity)?;
|
||||
store.add_identity(crate::servers::CREATED_IDENTITY, &identity)?;
|
||||
identity
|
||||
}
|
||||
};
|
||||
let prefs = open_settings(&dir, &options.setting_overrides);
|
||||
engine.send(Command::AttachSettings(prefs.clone()));
|
||||
let mut settings: UiSettings = (*prefs.get_arc(&UI)).clone();
|
||||
settings.crash_reports = prefs.get(&CRASH_REPORTS);
|
||||
@@ -565,8 +583,8 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
if settings.global_ptt {
|
||||
ptt.set(Some(settings.ptt_key.clone()));
|
||||
}
|
||||
let video = Video::new(&dir, settings.openh264);
|
||||
let switches = crate::dev::Switches::from_env();
|
||||
let mut video = Video::new(&dir, settings.openh264);
|
||||
video.set_decoder_preference(decoder_preference(&prefs));
|
||||
let app = App {
|
||||
ui: ui.as_weak(),
|
||||
store,
|
||||
@@ -618,6 +636,9 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
if app.demo {
|
||||
app.start_demo();
|
||||
}
|
||||
if let Some(text) = crate::servers::imported_status(&imported, had_identity) {
|
||||
app.set_status(text);
|
||||
}
|
||||
});
|
||||
|
||||
// Engine events -> UI thread, until the event loop is gone.
|
||||
@@ -742,6 +763,8 @@ impl App {
|
||||
} else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() {
|
||||
// A running share mixes the new sources (streams.rs).
|
||||
self.share_audio_changed();
|
||||
} else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() {
|
||||
self.video.set_decoder_preference(decoder_preference(&self.prefs));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -782,6 +805,7 @@ impl App {
|
||||
}
|
||||
Event::ServerInfo { session, name, flavor, capabilities } => {
|
||||
self.sessions.entry(session as i64).or_default().capabilities = capabilities;
|
||||
self.adopt_server_name(session as i64, &name);
|
||||
if self.current == Some(session as i64) {
|
||||
let kind = match flavor {
|
||||
voelin_model::ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"),
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
//! - `VOELIN_DEMO_STREAM=1`: a local test stream in the viewer.
|
||||
//! - `VOELIN_OPEN=<what>[,<what>...]`: open screens on start: `home`,
|
||||
//! `server`, `settings[:<section>]` (voice, keybinds, streaming, privacy,
|
||||
//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server),
|
||||
//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server;
|
||||
//! `bookmark:edit` the current one, Advanced open),
|
||||
//! `emoji` (the picker), `client` (the volume dialog of the first other
|
||||
//! client once connected), `panel` / `no-panel` (the members panel),
|
||||
//! `voice` (the voice channel view; on the phone its own screen),
|
||||
@@ -159,6 +160,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
with_app(|app| app.demo_share());
|
||||
}
|
||||
}
|
||||
// The current server's dialog, Advanced open.
|
||||
"bookmark" if arg == "edit" => {
|
||||
if let Some(id) = with_app(|app| app.current).flatten() {
|
||||
nav.invoke_edit_server(id as i32);
|
||||
}
|
||||
}
|
||||
"bookmark" => nav.invoke_add_server(),
|
||||
"emoji" => nav.set_emoji_open(true),
|
||||
"panel" => nav.set_right_panel_open(true),
|
||||
|
||||
+233
-46
@@ -3,12 +3,87 @@
|
||||
|
||||
use slint::{ComponentHandle, SharedString};
|
||||
use tracing::warn;
|
||||
use voelin_core::identity::Found;
|
||||
use voelin_core::{Command, ObserveState, Source, VoiceOptions, VoiceState};
|
||||
use voelin_store::{Bookmark, QueryConfig, QueryTransport};
|
||||
|
||||
use crate::app::{App, BookmarkForm, Bridge};
|
||||
use crate::app::{App, BookmarkForm, Bridge, later};
|
||||
use crate::vm;
|
||||
|
||||
/// The name of the identity the app creates when it has none.
|
||||
pub(crate) const CREATED_IDENTITY: &str = "Default";
|
||||
|
||||
/// What to tell the user about the identities imported from the official
|
||||
/// clients at start ([`voelin_core::identity::import_new`]), if any.
|
||||
/// `had_identity`: we had one before, so it stays the default.
|
||||
pub(crate) fn imported_status(imported: &[Found], had_identity: bool) -> Option<String> {
|
||||
let first = imported.first()?;
|
||||
let n = imported.len();
|
||||
let names = imported.iter().map(|f| f.nickname.as_str()).collect::<Vec<_>>().join(", ");
|
||||
Some(match (had_identity, n) {
|
||||
(true, 1) => format!("Imported the identity \u{201c}{names}\u{201d} from TeamSpeak"),
|
||||
(true, _) => format!("Imported {n} identities from TeamSpeak: {names}"),
|
||||
(false, 1) => format!("Using your TeamSpeak identity \u{201c}{names}\u{201d}"),
|
||||
(false, _) => format!(
|
||||
"Using your TeamSpeak identity \u{201c}{}\u{201d} ({n} imported: {names})",
|
||||
first.nickname
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
/// The bookmark the form describes, over `old` (what the form does not show,
|
||||
/// like the identity, the default channel or the client version, stays; a
|
||||
/// new server has none of it). Only the address is needed: the name is the
|
||||
/// address until the server tells its own (`adopt_server_name`), the
|
||||
/// nickname `default_nickname`, the gateway is looked up later.
|
||||
fn bookmark_from_form(
|
||||
old: Option<&Bookmark>,
|
||||
form: &BookmarkForm,
|
||||
default_nickname: impl FnOnce() -> String,
|
||||
) -> Bookmark {
|
||||
let mut bookmark = old.cloned().unwrap_or_default();
|
||||
bookmark.id = form.id as i64;
|
||||
bookmark.address = form.address.trim().to_string();
|
||||
bookmark.name = match form.name.trim() {
|
||||
"" => bookmark.address.clone(),
|
||||
name => name.to_string(),
|
||||
};
|
||||
bookmark.nickname = match form.nickname.trim() {
|
||||
"" => default_nickname(),
|
||||
nickname => nickname.to_string(),
|
||||
};
|
||||
bookmark.gateway_url = Some(form.gateway_url.trim().to_string()).filter(|u| !u.is_empty());
|
||||
bookmark.query = match form.query_transport.as_str() {
|
||||
"none" | "" => None,
|
||||
t => {
|
||||
let (host, port) = form
|
||||
.query_addr
|
||||
.rsplit_once(':')
|
||||
.map_or((form.query_addr.to_string(), None), |(h, p)| {
|
||||
(h.to_string(), p.parse().ok())
|
||||
});
|
||||
let transport = match t {
|
||||
"raw" => QueryTransport::Raw,
|
||||
"http" => QueryTransport::Http,
|
||||
_ => QueryTransport::Ssh,
|
||||
};
|
||||
let default_port = match transport {
|
||||
QueryTransport::Raw => 10011,
|
||||
QueryTransport::Ssh => 10022,
|
||||
QueryTransport::Http => 10080,
|
||||
};
|
||||
Some(QueryConfig {
|
||||
transport,
|
||||
host,
|
||||
port: port.unwrap_or(default_port),
|
||||
user: form.query_user.to_string(),
|
||||
server_port: bookmark.query.as_ref().and_then(|q| q.server_port),
|
||||
})
|
||||
}
|
||||
};
|
||||
bookmark
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn connect_voice(&mut self) {
|
||||
let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return };
|
||||
@@ -21,6 +96,77 @@ impl App {
|
||||
self.engine
|
||||
.send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) });
|
||||
self.set_status(format!("Connecting to {}…", b.address));
|
||||
// The admin may have published the gateway since it was added.
|
||||
self.discover_gateway(b.id);
|
||||
}
|
||||
|
||||
/// The nickname a new server gets: the default identity's (one imported
|
||||
/// from TeamSpeak keeps the nickname used there), else the system user's.
|
||||
pub(crate) fn default_nickname(&self) -> String {
|
||||
self.store
|
||||
.identities()
|
||||
.ok()
|
||||
.and_then(|identities| identities.into_iter().next())
|
||||
.map(|identity| identity.name)
|
||||
.filter(|name| {
|
||||
![CREATED_IDENTITY, voelin_core::identity::DEFAULT_NICKNAME]
|
||||
.contains(&name.as_str())
|
||||
})
|
||||
.or_else(|| std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok())
|
||||
// Servers refuse an empty nickname (Android has no user name).
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.unwrap_or_else(|| "Voelin user".to_owned())
|
||||
}
|
||||
|
||||
/// Look up the gateway of a server that has none in DNS
|
||||
/// ([`voelin_core::discover`]); one found is kept as if typed.
|
||||
pub(crate) fn discover_gateway(&self, id: i64) {
|
||||
let Some(b) = self.bookmark(id).filter(|b| b.gateway_url.is_none() && !self.demo_ui) else {
|
||||
return;
|
||||
};
|
||||
let address = b.address.clone();
|
||||
self.engine.runtime().spawn(async move {
|
||||
if let Some(url) = voelin_core::discover::gateway(&address).await {
|
||||
later(move |app| app.gateway_found(id, &address, url));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A gateway was found for the server at `address`; it is kept unless
|
||||
/// the server changed meanwhile.
|
||||
fn gateway_found(&mut self, id: i64, address: &str, url: String) {
|
||||
let Some(b) = self
|
||||
.bookmarks
|
||||
.iter_mut()
|
||||
.find(|b| b.id == id && b.address == address && b.gateway_url.is_none())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
b.gateway_url = Some(url.clone());
|
||||
let name = b.name.clone();
|
||||
if let Err(e) = self.store.update_bookmark(b) {
|
||||
warn!(%e, "could not keep the gateway found");
|
||||
return;
|
||||
}
|
||||
self.set_status(format!("Found the gateway of {name}: {url}"));
|
||||
self.refresh_toolbar();
|
||||
}
|
||||
|
||||
/// The server told its name: a server still named by its address takes
|
||||
/// it, so the address is all a user has to type.
|
||||
pub(crate) fn adopt_server_name(&mut self, id: i64, name: &str) {
|
||||
let Some(b) = self.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else {
|
||||
return;
|
||||
};
|
||||
if name.trim().is_empty() || self.demo_ui {
|
||||
return;
|
||||
}
|
||||
b.name = name.trim().to_owned();
|
||||
if let Err(e) = self.store.update_bookmark(b) {
|
||||
warn!(%e, "could not name the server");
|
||||
}
|
||||
self.refresh_servers();
|
||||
self.refresh_toolbar();
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_observe(&mut self) {
|
||||
@@ -68,7 +214,7 @@ impl App {
|
||||
let Some(b) = self.bookmark(id) else {
|
||||
return BookmarkForm {
|
||||
id: -1,
|
||||
nickname: std::env::var("USER").unwrap_or_default().into(),
|
||||
nickname: self.default_nickname().into(),
|
||||
query_transport: "none".into(),
|
||||
query_user: "serveradmin".into(),
|
||||
..Default::default()
|
||||
@@ -91,7 +237,8 @@ impl App {
|
||||
};
|
||||
BookmarkForm {
|
||||
id: b.id as i32,
|
||||
name: b.name.clone().into(),
|
||||
// Named by its address: empty, so a new address names it again.
|
||||
name: if b.name == b.address { SharedString::new() } else { b.name.clone().into() },
|
||||
address: b.address.clone().into(),
|
||||
nickname: b.nickname.clone().into(),
|
||||
server_password: secret(b.server_password_key()),
|
||||
@@ -104,49 +251,8 @@ impl App {
|
||||
}
|
||||
|
||||
pub(crate) fn save_bookmark(&mut self, form: BookmarkForm) {
|
||||
let query = match form.query_transport.as_str() {
|
||||
"none" | "" => None,
|
||||
t => {
|
||||
let (host, port) = form
|
||||
.query_addr
|
||||
.rsplit_once(':')
|
||||
.map_or((form.query_addr.to_string(), None), |(h, p)| {
|
||||
(h.to_string(), p.parse().ok())
|
||||
});
|
||||
let transport = match t {
|
||||
"raw" => QueryTransport::Raw,
|
||||
"http" => QueryTransport::Http,
|
||||
_ => QueryTransport::Ssh,
|
||||
};
|
||||
let default_port = match transport {
|
||||
QueryTransport::Raw => 10011,
|
||||
QueryTransport::Ssh => 10022,
|
||||
QueryTransport::Http => 10080,
|
||||
};
|
||||
Some(QueryConfig {
|
||||
transport,
|
||||
host,
|
||||
port: port.unwrap_or(default_port),
|
||||
user: form.query_user.to_string(),
|
||||
server_port: None,
|
||||
})
|
||||
}
|
||||
};
|
||||
let mut bookmark = Bookmark {
|
||||
id: form.id as i64,
|
||||
name: if form.name.is_empty() {
|
||||
form.address.to_string()
|
||||
} else {
|
||||
form.name.to_string()
|
||||
},
|
||||
address: form.address.to_string(),
|
||||
nickname: form.nickname.to_string(),
|
||||
identity: None,
|
||||
default_channel: None,
|
||||
gateway_url: Some(form.gateway_url.to_string()).filter(|u| !u.is_empty()),
|
||||
query,
|
||||
client_version: None,
|
||||
};
|
||||
let mut bookmark =
|
||||
bookmark_from_form(self.bookmark(form.id as i64), &form, || self.default_nickname());
|
||||
let result = if bookmark.id < 0 {
|
||||
self.store.add_bookmark(&bookmark).map(|id| bookmark.id = id)
|
||||
} else {
|
||||
@@ -172,6 +278,7 @@ impl App {
|
||||
self.current = Some(bookmark.id);
|
||||
self.bookmarks = self.store.bookmarks().unwrap_or_default();
|
||||
self.refresh_all();
|
||||
self.discover_gateway(bookmark.id);
|
||||
}
|
||||
|
||||
pub(crate) fn delete_bookmark(&mut self, id: i64) {
|
||||
@@ -360,3 +467,83 @@ impl App {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_address_alone_makes_a_server() {
|
||||
let form = BookmarkForm {
|
||||
id: -1,
|
||||
address: " ts.example.test ".into(),
|
||||
query_transport: "none".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let b = bookmark_from_form(None, &form, || "Nick".into());
|
||||
assert_eq!((b.address.as_str(), b.name.as_str()), ("ts.example.test", "ts.example.test"));
|
||||
assert_eq!(b.nickname, "Nick");
|
||||
assert_eq!(
|
||||
(b.gateway_url, b.query, b.identity, b.default_channel),
|
||||
(None, None, None, None)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_keeps_what_the_form_does_not_show() {
|
||||
let old = Bookmark {
|
||||
id: 7,
|
||||
name: "Old".into(),
|
||||
address: "old.example.test".into(),
|
||||
nickname: "Me".into(),
|
||||
identity: Some(2),
|
||||
default_channel: Some("Lobby/Sub".into()),
|
||||
gateway_url: Some("ws://gw.example.test:7788/v1".into()),
|
||||
query: Some(QueryConfig { server_port: Some(9988), ..Default::default() }),
|
||||
client_version: Some("linux".into()),
|
||||
};
|
||||
let form = BookmarkForm {
|
||||
id: 7,
|
||||
name: "Mine".into(),
|
||||
address: "new.example.test:9988".into(),
|
||||
nickname: "Other".into(),
|
||||
// Cleared: looked up again.
|
||||
gateway_url: "".into(),
|
||||
query_transport: "raw".into(),
|
||||
query_addr: "q.example.test".into(),
|
||||
query_user: "serveradmin".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let b = bookmark_from_form(Some(&old), &form, || unreachable!("a nickname was given"));
|
||||
assert_eq!((b.id, b.name.as_str(), b.nickname.as_str()), (7, "Mine", "Other"));
|
||||
assert_eq!(b.address, "new.example.test:9988");
|
||||
assert_eq!((b.identity, b.default_channel), (Some(2), Some("Lobby/Sub".into())));
|
||||
assert_eq!(b.client_version.as_deref(), Some("linux"));
|
||||
assert_eq!(b.gateway_url, None);
|
||||
let q = b.query.unwrap();
|
||||
assert_eq!(
|
||||
(q.transport, q.host.as_str(), q.port),
|
||||
(QueryTransport::Raw, "q.example.test", 10011)
|
||||
);
|
||||
assert_eq!(q.server_port, Some(9988));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_import_is_told_by_nickname() {
|
||||
let found = |nickname: &str| Found {
|
||||
nickname: nickname.into(),
|
||||
identity: tsclientlib::Identity::create(),
|
||||
source: "settings.db".into(),
|
||||
selected: false,
|
||||
};
|
||||
assert_eq!(imported_status(&[], false), None);
|
||||
assert_eq!(
|
||||
imported_status(&[found("Main")], false).unwrap(),
|
||||
"Using your TeamSpeak identity \u{201c}Main\u{201d}"
|
||||
);
|
||||
assert_eq!(
|
||||
imported_status(&[found("Main"), found("Alt")], true).unwrap(),
|
||||
"Imported 2 identities from TeamSpeak: Main, Alt"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,8 @@ use tracing::warn;
|
||||
use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId};
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
|
||||
StreamerConfigUpdate, Viewer, peer_config, preferred_codec, stream_codec,
|
||||
self, AudioSourceSpec, DecoderPreference, EncoderPreference, Latest, LocalPreview, Streamer,
|
||||
StreamerConfig, StreamerConfigUpdate, Viewer, peer_config, preferred_codec, stream_codec,
|
||||
};
|
||||
use voelin_core::stream::{LayerSpec, PeerConfig};
|
||||
use voelin_core::studio::Studio;
|
||||
@@ -62,6 +62,9 @@ pub(crate) struct Video {
|
||||
/// automatic), from the settings.
|
||||
encoder: EncoderPreference,
|
||||
codec: Option<Codec>,
|
||||
/// Which decoders to use (`stream.hardware_decoding`,
|
||||
/// `stream.decoder_backend`).
|
||||
decoder: DecoderPreference,
|
||||
/// Sources of the share dialog, by index.
|
||||
sources: Vec<ShareEntry>,
|
||||
}
|
||||
@@ -75,6 +78,7 @@ impl Video {
|
||||
codecs: Arc::new(Codecs::new()),
|
||||
encoder: EncoderPreference::default(),
|
||||
codec: None,
|
||||
decoder: DecoderPreference::default(),
|
||||
#[cfg(not(target_os = "android"))]
|
||||
openh264_dir: data_dir.join("openh264"),
|
||||
#[cfg(not(target_os = "android"))]
|
||||
@@ -108,7 +112,19 @@ impl Video {
|
||||
self.codec = codec;
|
||||
}
|
||||
|
||||
/// Every encoder backend, what works and why the rest does not.
|
||||
/// Decode with other decoders (`stream.hardware_decoding`,
|
||||
/// `stream.decoder_backend`): streams watched from now on.
|
||||
pub fn set_decoder_preference(&mut self, decoder: DecoderPreference) {
|
||||
if decoder != self.decoder {
|
||||
let mut codecs = (*self.codecs).clone();
|
||||
codecs.set_decoder_preference(decoder.clone());
|
||||
self.codecs = Arc::new(codecs);
|
||||
self.decoder = decoder;
|
||||
}
|
||||
}
|
||||
|
||||
/// Every encoder and decoder backend, what works and why the rest does
|
||||
/// not.
|
||||
#[allow(dead_code, reason = "for the integrations page")]
|
||||
pub fn encoder_report(&self) -> EncoderReport {
|
||||
self.codecs.report()
|
||||
@@ -140,7 +156,11 @@ impl Video {
|
||||
use openh264::State;
|
||||
if !enabled {
|
||||
self.h264 = State::Off;
|
||||
self.codecs = Arc::new(Codecs::new().with_preference(self.encoder.clone()));
|
||||
self.codecs = Arc::new(
|
||||
Codecs::new()
|
||||
.with_preference(self.encoder.clone())
|
||||
.with_decoder_preference(self.decoder.clone()),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if matches!(self.h264, State::Loaded(_) | State::Downloading) {
|
||||
@@ -156,8 +176,12 @@ impl Video {
|
||||
#[cfg(not(target_os = "android"))]
|
||||
fn loaded(&mut self, library: openh264::OpenH264) {
|
||||
self.h264 = openh264::State::Loaded(library.path().to_owned());
|
||||
self.codecs =
|
||||
Arc::new(Codecs::new().with_openh264(library).with_preference(self.encoder.clone()));
|
||||
self.codecs = Arc::new(
|
||||
Codecs::new()
|
||||
.with_openh264(library)
|
||||
.with_preference(self.encoder.clone())
|
||||
.with_decoder_preference(self.decoder.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Download Cisco's OpenH264 (only on the user's request). `done` runs
|
||||
@@ -344,8 +368,8 @@ impl Video {
|
||||
fn deliver(
|
||||
pictures: Arc<Latest<Picture>>,
|
||||
wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> impl FnMut(VideoFrame) + Send + 'static {
|
||||
move |frame: VideoFrame| {
|
||||
) -> impl FnMut(Arc<VideoFrame>) + Send + 'static {
|
||||
move |frame: Arc<VideoFrame>| {
|
||||
let mut buffer = Picture::new(frame.width, frame.height);
|
||||
let stride = frame.width as usize * 4;
|
||||
if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) {
|
||||
|
||||
@@ -15,74 +15,103 @@ component Footer inherits HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
}
|
||||
|
||||
// Add or edit a server: its address and, if it has one, its password; the
|
||||
// rest under Advanced (name, nickname, gateway, ServerQuery), which Voelin
|
||||
// fills in itself when left empty.
|
||||
export component BookmarkDialog inherits Modal {
|
||||
in-out property <BookmarkForm> form;
|
||||
callback done();
|
||||
// The fields beyond address and password: shown when editing.
|
||||
property <bool> advanced: form.id >= 0;
|
||||
title: form.id < 0 ? @tr("Add server") : @tr("Edit server");
|
||||
subtitle: @tr("TeamSpeak 3 or 6 server address and your nickname there.");
|
||||
subtitle: @tr("Only the address is needed; Voelin finds the rest.");
|
||||
icon: Icons.server;
|
||||
card-width: 560px;
|
||||
card-height: 640px;
|
||||
// Fits the address and password (two lines more on a phone).
|
||||
card-height: advanced ? 720px : Nav.narrow ? 360px : 330px;
|
||||
dismissed => { done(); }
|
||||
ScrollView {
|
||||
vertical-stretch: 1;
|
||||
VerticalLayout {
|
||||
alignment: start;
|
||||
spacing: Theme.space-4;
|
||||
padding-right: Theme.space-3;
|
||||
Field {
|
||||
label: @tr("Name");
|
||||
TextField { text <=> form.name; placeholder: @tr("My server"); label: @tr("Name"); }
|
||||
label: @tr("Address");
|
||||
hint: @tr("Host name, IP address or server nickname; a port only if the server needs one.");
|
||||
TextField { text <=> form.address; placeholder: "ts.example.org"; label: @tr("Address"); icon: Icons.globe; }
|
||||
}
|
||||
Field {
|
||||
label: @tr("Address");
|
||||
TextField { text <=> form.address; placeholder: "ts.example.org:9987"; label: @tr("Address"); icon: Icons.globe; }
|
||||
label: @tr("Server password (optional)");
|
||||
TextField { text <=> form.server-password; input-type: InputType.password; label: @tr("Server password"); icon: Icons.lock; }
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
Button {
|
||||
kind: ButtonKind.ghost;
|
||||
small: true;
|
||||
icon: root.advanced ? Icons.chevron-down : Icons.chevron-right;
|
||||
text: @tr("Advanced");
|
||||
clicked => { root.advanced = !root.advanced; }
|
||||
}
|
||||
Text {
|
||||
text: @tr("Name, nickname, gateway, ServerQuery");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
}
|
||||
if root.advanced: VerticalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Field {
|
||||
label: @tr("Name");
|
||||
hint: @tr("Empty: the address, then the server's own name once connected.");
|
||||
TextField { text <=> form.name; placeholder: @tr("The server's name"); label: @tr("Name"); }
|
||||
}
|
||||
Field {
|
||||
label: @tr("Nickname");
|
||||
hint: @tr("Empty: the nickname of your identity.");
|
||||
TextField { text <=> form.nickname; label: @tr("Nickname"); icon: Icons.user; }
|
||||
}
|
||||
Field {
|
||||
label: @tr("Server password");
|
||||
TextField { text <=> form.server-password; input-type: InputType.password; label: @tr("Server password"); icon: Icons.lock; }
|
||||
Text {
|
||||
text: @tr("Invisible presence and chat without joining");
|
||||
font-weight: Theme.weight-semibold;
|
||||
color: Theme.text;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: @tr("Invisible presence and chat without joining (optional)");
|
||||
font-weight: Theme.weight-semibold;
|
||||
color: Theme.text;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
Field {
|
||||
label: @tr("Gateway URL");
|
||||
TextField { text <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; label: @tr("Gateway URL"); }
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Field {
|
||||
label: @tr("Query transport");
|
||||
Select {
|
||||
model: ["none", "ssh", "raw", "http"];
|
||||
current-value <=> form.query-transport;
|
||||
current-index: form.query-transport == "ssh" ? 1 : form.query-transport == "raw" ? 2 : form.query-transport == "http" ? 3 : 0;
|
||||
label: @tr("Gateway URL");
|
||||
hint: @tr("Empty: looked up in DNS, as published by the server's admin.");
|
||||
TextField { text <=> form.gateway-url; placeholder: @tr("Found automatically"); label: @tr("Gateway URL"); }
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Field {
|
||||
label: @tr("Query transport");
|
||||
Select {
|
||||
model: ["none", "ssh", "raw", "http"];
|
||||
current-value <=> form.query-transport;
|
||||
current-index: form.query-transport == "ssh" ? 1 : form.query-transport == "raw" ? 2 : form.query-transport == "http" ? 3 : 0;
|
||||
label: @tr("Query transport");
|
||||
}
|
||||
}
|
||||
Field {
|
||||
label: @tr("Query address");
|
||||
TextField { text <=> form.query-addr; placeholder: "ts.example.org:10022"; label: @tr("Query address"); }
|
||||
}
|
||||
}
|
||||
Field {
|
||||
label: @tr("Query address");
|
||||
TextField { text <=> form.query-addr; placeholder: "ts.example.org:10022"; label: @tr("Query address"); }
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Field {
|
||||
label: @tr("Query login");
|
||||
TextField { text <=> form.query-user; label: @tr("Query login"); }
|
||||
}
|
||||
Field {
|
||||
label: @tr("Query password");
|
||||
TextField { text <=> form.query-password; input-type: InputType.password; label: @tr("Query password"); }
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Field {
|
||||
label: @tr("Query login");
|
||||
TextField { text <=> form.query-user; label: @tr("Query login"); }
|
||||
}
|
||||
Field {
|
||||
label: @tr("Query password");
|
||||
TextField { text <=> form.query-password; input-type: InputType.password; label: @tr("Query password"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,8 +133,8 @@ export component BookmarkDialog inherits Modal {
|
||||
}
|
||||
Button {
|
||||
kind: ButtonKind.primary;
|
||||
text: @tr("Save");
|
||||
enabled: form.address != "" && form.nickname != "";
|
||||
text: form.id < 0 ? @tr("Add") : @tr("Save");
|
||||
enabled: form.address != "";
|
||||
clicked => {
|
||||
Bridge.save-bookmark(form);
|
||||
done();
|
||||
|
||||
+59
-1
@@ -80,7 +80,65 @@ Every login, post and settings change is written to the audit table.
|
||||
5. Install tsgw ([below](#install)), copy the example config to
|
||||
`/etc/tsgw/tsgw.toml` and set the query address and credentials
|
||||
(`TSGW_QUERY_PASSWORD` or `password_file`).
|
||||
6. Run it behind TLS (Caddy, nginx) and give users the `wss://…/v1` URL.
|
||||
6. Run it behind TLS (Caddy, nginx) and publish it in DNS
|
||||
([below](#letting-voelin-find-the-gateway)), so users only add the
|
||||
server's address; or give them the `wss://…/v1` URL.
|
||||
|
||||
## Letting Voelin find the gateway
|
||||
|
||||
When a user adds a server by its address (`ts.example.org`), Voelin looks
|
||||
for its gateway the way TeamSpeak looks for the voice server (SRV
|
||||
`_ts3._udp`, then TSDNS), and uses what it finds as if the user had typed
|
||||
the URL (the field stays editable under *Advanced*). It asks at the
|
||||
server's host name and then at each parent domain down to the registered
|
||||
domain, the most specific name first; for `ts.example.org` that is
|
||||
`ts.example.org`, then `example.org`. It looks again when the server is
|
||||
saved with an empty gateway URL and when it connects with voice.
|
||||
|
||||
**DNS records** (preferred). An SRV record names the gateway's host and
|
||||
port, the service name says whether it speaks TLS:
|
||||
|
||||
| Record | Gives |
|
||||
|---|---|
|
||||
| `_tsgws._tcp.<name> SRV <prio> <weight> <port> <host>` | `wss://<host>:<port>/v1` (TLS, e.g. behind Caddy or nginx) |
|
||||
| `_tsgw._tcp.<name> SRV <prio> <weight> <port> <host>` | `ws://<host>:<port>/v1` (plain, e.g. tsgw itself on 7788) |
|
||||
| `_tsgws._tcp.<name> TXT "path=/<path>"` (optional, same for `_tsgw`) | another path than `/v1`, e.g. behind a reverse proxy |
|
||||
|
||||
At the same name TLS wins; among several records of one name the lowest
|
||||
priority. A target of `.` means "no gateway here" and the search goes on at
|
||||
the parent domain. Examples (zone of `example.org`):
|
||||
|
||||
```dns
|
||||
; Behind a TLS proxy at gw.example.org that forwards /tsgw/v1 to tsgw:
|
||||
_tsgws._tcp.example.org. 3600 IN SRV 0 0 443 gw.example.org.
|
||||
_tsgws._tcp.example.org. 3600 IN TXT "path=/tsgw/v1"
|
||||
; -> wss://gw.example.org:443/tsgw/v1 for ts.example.org, voice.example.org, …
|
||||
|
||||
; tsgw itself, without TLS, next to the server ts.example.org:
|
||||
_tsgw._tcp.ts.example.org. 3600 IN SRV 0 0 7788 ts.example.org.
|
||||
; -> ws://ts.example.org:7788/v1, only for ts.example.org
|
||||
```
|
||||
|
||||
One domain with several servers and several gateways: publish one record
|
||||
per server host (`_tsgws._tcp.ts1.example.org`, `_tsgws._tcp.ts2.example.org`);
|
||||
a record at the domain itself applies to every host below it that has none
|
||||
of its own.
|
||||
|
||||
**Without DNS records** (like TSDNS on port 41144): Voelin asks
|
||||
`http://<name>:7788/.well-known/tsgw` at the same names (and at an IP
|
||||
address the server was added by). tsgw answers there with its URL,
|
||||
`{"url": "…"}`: `listen.public_url` if set, else the address the request
|
||||
came in on (`ws://<host>:7788/v1`). So a tsgw that listens on the default
|
||||
port on the server's host is found with no setup at all; behind a proxy,
|
||||
set `listen.public_url` so the answer points at the proxy.
|
||||
|
||||
Discovery is as trustworthy as DNS and the network, like TSDNS: prefer a
|
||||
`_tsgws` record, so TLS proves the gateway is yours. Voelin checks a
|
||||
`wss://` gateway's certificate against the system's certificate store, so
|
||||
use one from a public CA (Caddy's automatic Let's Encrypt certificates
|
||||
work); the Android app cannot reach `wss://` gateways yet (it has no
|
||||
system store to read). A user logs in with
|
||||
their own identity, and only when they choose to observe the server.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -19,6 +19,11 @@ frame:
|
||||
{"v":1,"id":7,"type":"send_chat","data":{"target":{"kind":"channel","id":5},"text":"hi"}}
|
||||
```
|
||||
|
||||
Next to it, `GET /.well-known/tsgw` answers `{"url": "…"}`, the URL apps
|
||||
should use (`listen.public_url`, else the one the request came in on); apps
|
||||
that find no DNS record ask there ([gateway-admin.md](gateway-admin.md#letting-voelin-find-the-gateway),
|
||||
`voelin_core::discover`).
|
||||
|
||||
The client picks `id` for requests; the answer carries the same `id`.
|
||||
Pushes have no `id`. Version 1 only grows: new message types and optional
|
||||
fields. Both sides ignore unknown fields. The gateway answers a type it does
|
||||
|
||||
+13
-1
@@ -92,7 +92,7 @@ field carries the body. **Type 1, payload field 17, is an identity:**
|
||||
| 4 | bytes | empty in every row seen |
|
||||
| 5 | varint | 1 on exactly one identity: the selected one |
|
||||
|
||||
Voelin reads field 1 and field 2 and ignores the rest. The other item types
|
||||
Voelin reads fields 1, 2 and 5 and ignores the rest. The other item types
|
||||
(0, 2, 3, 4, 5 — connection profiles, bookmarks, server lists and such) are
|
||||
**not** decoded; they are skipped by their type, not by guessing at their
|
||||
contents.
|
||||
@@ -168,6 +168,18 @@ voelinctl identity export <id> <path> [--store <db>]
|
||||
`--store` defaults to the desktop app's client database,
|
||||
`<data dir>/voelin/client.db`, so the CLI and the app share identities.
|
||||
|
||||
**On every start** the app does the same as `import --auto`
|
||||
(`voelin_core::identity::import_new`): identities found in the default
|
||||
locations that the client database does not have yet are added, the files
|
||||
are only read. The identity the official client uses by default (field 5 of
|
||||
its payload, below) goes in first, so when Voelin has no identity of its own
|
||||
yet, that one becomes Voelin's default (the first identity) and servers see
|
||||
the same unique id; otherwise Voelin's default stays. What was imported is
|
||||
shown once, in the status line (the toast on desktop), by nickname. The
|
||||
runtime setting `identity.import_from_teamspeak` (default on) turns it off,
|
||||
e.g. `--set identity.import_from_teamspeak=false`. The sample data of
|
||||
`VOELIN_DEMO_UI` never imports.
|
||||
|
||||
- **Import** prints what it found as nickname, unique id and security level —
|
||||
all three are public, everything else in an identity is the private key —
|
||||
and stores each one through `voelin-store` under its nickname. An identity
|
||||
|
||||
+186
-21
@@ -24,11 +24,14 @@ described in [studio.md](studio.md).
|
||||
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API; MediaCodec's surface path on Android) |
|
||||
| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time). On Android `rendered(width, height, timestamp)`: a screen picture the virtual display renders straight into MediaCodec's input surface, only its size and time travel |
|
||||
| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` |
|
||||
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) |
|
||||
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time); `decode_into(&[u8], &mut VideoFrame) -> bool` reuses the frame's buffers (FFmpeg's decoders: no allocation per picture); `conceals_errors()` (FFmpeg's H.264 and HEVC: frames after a lost one still decode) |
|
||||
| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time |
|
||||
| `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone |
|
||||
| `Codecs` | `new()` (probes FFmpeg / MediaCodec once per process), `builtin()` (compiled-in codecs only), `with_openh264(lib)`, `with_preference(EncoderPreference)` / `set_preference`, `decoders()` (viewer order: every codec one decoder here decodes), `decoders_for(codec)` (that codec's decoders, best first: the ladder), `with_decoder_preference(DecoderPreference)` / `set_decoder_preference`, `with_decoder(factory)` (an application's decoder, first), `encoders()` / `encoder_codecs()` (streamer order under the preference), `encoders_for(&pref)`, `new_decoder(codec)` (the first of the ladder that opens), `new_decoder_with(codec, DecoderBackend)`, `new_encoder(codec, config)`, `new_encoder_preferring(codec, config, &pref)`, `new_encoder_with(codec, backend, config)`, `pick_encoder(&accepted)`, `is_hardware(backend)`, `report()`; cheap to clone |
|
||||
| `EncoderPreference { hardware, backend: BackendChoice }` | settings `stream.hardware_acceleration` and `stream.encoder_backend` (`auto`, `software`, or a backend name such as `h264_vaapi`, `libx264`, `libvpx`, `openh264`) |
|
||||
| `EncoderReport { ffmpeg, zero_copy, encoders: Vec<EncoderInfo> }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference |
|
||||
| `EncoderReport { ffmpeg, zero_copy, encoders: Vec<EncoderInfo>, decoders: Vec<DecoderInfo> }` | for the UI: FFmpeg's release and path (or why none), whether DMA-BUF import works, and per backend `name`, `api`, `codec`, `hardware`, `status` (self-test result or why it cannot be used) and `rank` under the current preference (for a decoder: its place in its codec's ladder) |
|
||||
| `DecoderBackend` | `Ffmpeg("h264_vaapi")`, `Ffmpeg("libdav1d")`, `Libvpx`, `OpenH264`, `Dav1d`, `Hardware("mediacodec")`; `name()` is the settings spelling |
|
||||
| `DecoderPreference` | the `EncoderPreference` type for decoders: settings `stream.hardware_decoding` and `stream.decoder_backend` (`auto`, `software`, or a decoder's name such as `h264_vaapi`, `h264`, `libdav1d`, `libvpx`, `openh264`) |
|
||||
| `ffmpeg::{FfmpegDecoder, DECODERS, decoder::probe}` | FFmpeg's decoders, see [FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime) |
|
||||
| `EncoderBackend` | `Libvpx`, `OpenH264`, `Ffmpeg("h264_vaapi")`, `Hardware("mediacodec")`; `name()` is the settings spelling |
|
||||
| `ffmpeg::{Ffmpeg, probe, FfmpegEncoder, BACKENDS}` | FFmpeg loaded at runtime (feature `ffmpeg`), see [FFmpeg encoders](#ffmpeg-encoders-loaded-at-runtime) |
|
||||
| `ffmpeg::avio::Connection`, `ffmpeg::audio::AacEncoder` | bytes written through libavformat's protocols (`rtmp://`, `rtmps://`) with their write errors and an abort flag; the studio's Opus as AAC through FFmpeg's own codecs. See [RTMP output](#rtmp-output) |
|
||||
@@ -202,18 +205,33 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
never below 3.1, the level offered before); str0m's other H.264 variants
|
||||
are only accepted, never offered, so a viewer cannot answer a profile we
|
||||
do not send.
|
||||
- `VideoPipeline` decodes on its own thread. It starts at a keyframe, and
|
||||
after a lost frame (`contiguous == false`, a lagging frame bus, a queue
|
||||
longer than 30 frames) or a decoder error it skips to the next keyframe,
|
||||
asking for one at most every 500 ms. Keyframes are recognised from the
|
||||
- `VideoPipeline` decodes on its own thread, with the first decoder of the
|
||||
stream codec's ladder that opens (`Codecs::decoders_for`, see
|
||||
[FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime)). It starts at a
|
||||
keyframe. After a lost frame (`contiguous == false`, a lagging frame
|
||||
bus, a queue longer than 30 frames) a decoder that conceals losses
|
||||
(`conceals_errors`: FFmpeg's H.264 and HEVC) goes on decoding while a
|
||||
keyframe is asked for; the others skip to the next keyframe, as they do
|
||||
after a decoder error. A keyframe that is wanted is asked for again every
|
||||
500 ms until one decodes, also while no frame arrives. A decoder that
|
||||
fails three times in a row (an error, or ten frames without a picture,
|
||||
which also asks for a keyframe; decoders of streams with B-frames hold a
|
||||
few) is replaced by the next of the ladder without ending the watch: the
|
||||
keyframe that failed starts the next one at once, otherwise it waits for
|
||||
the next keyframe, and the switch is logged with its reason. The last
|
||||
decoder of the ladder stays. Keyframes are recognised from the
|
||||
bitstream (VP8 frame tag, VP9 header, H.264 IDR/SPS NAL units, AV1
|
||||
sequence header OBU). `stats()` (`DecodeStats`) tells the codec, the
|
||||
picture's size, pictures decoded and skipped, the video bytes received,
|
||||
and the decoded frame rate and received bitrate since the previous call
|
||||
(at least half a second); the watch screen shows codec, size, rate and
|
||||
bitrate over the player and in Stream Info, refreshed once a second.
|
||||
These are read from the pipeline, which runs in the app, not sent as
|
||||
engine events: the engine never sees the decoded pictures.
|
||||
sequence header OBU). Pictures go to the callback as `Arc<VideoFrame>`
|
||||
from a pool of four: the decoder writes into one nobody holds
|
||||
(`decode_into`), so a consumer that converts and drops each picture, as
|
||||
the app does, costs no allocations. `stats()` (`DecodeStats`) tells the
|
||||
codec, the decoder in use, the picture's size, pictures decoded and
|
||||
skipped, the video bytes received, and the decoded frame rate and
|
||||
received bitrate since the previous call (at least half a second); the
|
||||
watch screen shows codec, size, rate and bitrate over the player and in
|
||||
Stream Info, refreshed once a second. These are read from the pipeline,
|
||||
which runs in the app, not sent as engine events: the engine never sees
|
||||
the decoded pictures.
|
||||
- `Viewer` feeds a `VideoPipeline` from the engine and sends
|
||||
`RequestStreamKeyframe`; `LocalPreview` runs capture → encoder → decoder
|
||||
without a server (the desktop app's `VOELIN_DEMO_STREAM`).
|
||||
@@ -317,7 +335,10 @@ e.g. calls).
|
||||
|
||||
## Codecs
|
||||
|
||||
Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with
|
||||
Preference: a viewer accepts AV1 > HEVC > VP9 > H.264 > VP8, each with the
|
||||
best decoder that works here (hardware, then FFmpeg's software decoders,
|
||||
then the built-in ones; see [FFmpeg decoders](#ffmpeg-decoders-loaded-at-runtime));
|
||||
a streamer encodes with
|
||||
hardware (H.264 > AV1 > VP9 > VP8 > HEVC) > VP8 (libvpx) > H.264 (x264 and
|
||||
OpenH264 through FFmpeg, then Cisco's OpenH264) > VP9 (libvpx, expensive in
|
||||
software) > AV1 (SVT-AV1, libaom through FFmpeg). `Codecs` filters both lists
|
||||
@@ -332,13 +353,14 @@ off), the automatic order after it.
|
||||
| libvpx | `vpx` (default) | VP8, VP9 | VP8, VP9 | system libvpx (1.14 tested), dynamically linked; bindings from `libvpx-native-sys` (pre-generated, no bindgen) |
|
||||
| OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime |
|
||||
| dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) |
|
||||
| FFmpeg | `ffmpeg` (default; off on Android) | H.264, HEVC, AV1, VP9, VP8 in hardware; H.264 (x264, OpenH264), AV1 (SVT-AV1, libaom, rav1e) in software | – | the system's (or `VOELIN_FFMPEG_DIR`'s) libavcodec / libavutil, any major version, loaded at runtime; see below |
|
||||
| FFmpeg | `ffmpeg` (default; off on Android) | H.264, HEVC, AV1, VP9, VP8 in hardware; H.264 (x264, OpenH264), AV1 (SVT-AV1, libaom, rav1e) in software | AV1, HEVC, VP9, H.264, VP8 in hardware (VA-API, NVDEC, D3D11VA, DXVA2, VideoToolbox) and in software (dav1d, libaom, FFmpeg's own) | the system's (or `VOELIN_FFMPEG_DIR`'s) libavcodec / libavutil, any major version, loaded at runtime; see below |
|
||||
| MediaCodec (Android) | – | H.264, VP8, VP9 | VP8, VP9, H.264, AV1 | the device's default codec per type through the NDK (`ndk` crate); an encoder factory named `mediacodec` |
|
||||
|
||||
HEVC (`Codec::H265`): str0m packetizes and depacketizes H.265, so it can be
|
||||
negotiated; it is offered last and only when a hardware encoder has it, i.e.
|
||||
used only by a peer that takes none of the other codecs. There is no HEVC
|
||||
decoder, so viewers never accept it.
|
||||
used only by a peer that takes none of the other codecs. Viewers accept it
|
||||
where FFmpeg decodes it (in hardware, or with FFmpeg's own decoder, which
|
||||
every build has).
|
||||
|
||||
### FFmpeg encoders, loaded at runtime
|
||||
|
||||
@@ -372,7 +394,8 @@ the software encoders above are used as before.
|
||||
{0, 1}, `AV_NOPTS_VALUE` in exactly one layout), `AVCodecContext.hw_frames_ctx`
|
||||
(for VA-API; located from the offsets `av_opt_find` reports for its
|
||||
neighbours `hwaccel_flags` and `err_detect` / `extra_hw_frames` (libavcodec
|
||||
61+) or `max_pixels` (up to 60), and NULL in a new context),
|
||||
61+) or `max_pixels` (up to 60), and NULL in a new context), and
|
||||
`hw_device_ctx` beside it (the device of hardware decoders),
|
||||
`AVHWFramesContext` `format`, `sw_format`, `width`, `height`,
|
||||
`initial_pool_size` (with or without `internal`, which libavutil 59
|
||||
removed; `device_ctx` and both formats checked in a new context), and for
|
||||
@@ -547,6 +570,87 @@ the software encoders above are used as before.
|
||||
(no compression metadata); the portal offers it ahead of LINEAR (see
|
||||
[Capture](#capture)). See [the measurements](#zero-copy-measured).
|
||||
|
||||
### FFmpeg decoders, loaded at runtime
|
||||
|
||||
The same runtime-loaded FFmpeg decodes (`ffmpeg/decoder.rs`). Every codec a
|
||||
viewer may get has a ladder of decoders, tried best first
|
||||
(`Codecs::decoders_for`), and a viewer accepts every codec one of them
|
||||
decodes (`Codecs::decoders`, which `peer_config` puts in
|
||||
`accept_video_codecs`):
|
||||
|
||||
1. hardware, through FFmpeg's hwaccel API (`ffmpeg::DECODERS`; the names are
|
||||
FFmpeg's names of its hwaccels): `av1_vaapi`, `hevc_vaapi`, `vp9_vaapi`,
|
||||
`h264_vaapi`, `vp8_vaapi` and, for NVIDIA's driver, which has no VA-API
|
||||
of its own, `*_nvdec` (Linux); `*_d3d11va`, then `*_dxva2` (Windows; AV1,
|
||||
HEVC, VP9, H.264); `*_videotoolbox` (macOS; the same four). On Android
|
||||
MediaCodec instead, which hardware decoding off does not leave out
|
||||
(Android has no other decoders);
|
||||
2. FFmpeg's software decoders: `libdav1d`, then `libaom-av1` (AV1; FFmpeg's
|
||||
own `av1` decoder decodes only in hardware), `hevc`, `vp9`, `h264`, `vp8`;
|
||||
3. the built-in ones: `libvpx` (VP8, VP9), `openh264` (H.264, once Cisco's
|
||||
library is loaded), `dav1d` (AV1, feature `av1`).
|
||||
|
||||
The settings choose like the encoders' (`DecoderPreference`):
|
||||
`stream.hardware_decoding` (on by default) leaves the first group out, and
|
||||
`stream.decoder_backend` is `auto`, `software`, or a decoder's name, which
|
||||
then comes first for its codec (even in hardware with hardware decoding
|
||||
off). The app applies them when they change, to streams watched from then
|
||||
on (`Video::set_decoder_preference`); a running watch keeps its decoder.
|
||||
|
||||
- Hardware decoding: FFmpeg's own decoder (`av1`, `hevc`, `vp9`, `h264`,
|
||||
`vp8`) gets the process's device in `AVCodecContext.hw_device_ctx`, a
|
||||
field without an AVOption, located like `hw_frames_ctx` (right before
|
||||
`hwaccel_flags` in every layout from libavcodec 58; checked to be NULL in
|
||||
a new context; 560 in FFmpeg 9's headers, as the test compares). FFmpeg's
|
||||
default `get_format` then picks the device's surfaces, so no callback is
|
||||
installed. The devices are shared: VA-API's is the encoders' (the first
|
||||
render node, or `VOELIN_VAAPI_DEVICE`), the others the type's default.
|
||||
Pictures are copied out of the GPU with `av_hwframe_transfer_data` into
|
||||
an NV12 frame of the decoder's own, reused while the size stays, and
|
||||
from there into the caller's `VideoFrame` (`decode_into` reuses its
|
||||
buffers): no Rust allocation per picture for any decoder
|
||||
(`tests/decoder_alloc.rs`). Zero-copy display was not the goal; both
|
||||
copies are part of the 2.4-3.3 ms per 1440p picture measured in
|
||||
[Decoders, measured](#decoders-measured).
|
||||
- Packets are handed over without a reference, so FFmpeg copies them into
|
||||
its own padded buffer; pictures come out as `yuv420p` (or `yuvj420p`)
|
||||
and are taken as I420, or as NV12; anything else (10-bit, 4:4:4) is an
|
||||
error, and the ladder moves on.
|
||||
- Latency: slice threads only (frame threads would hold a picture per
|
||||
thread before the first comes out), `threads` up to 8 in software and 1
|
||||
in hardware, dav1d's `max_frame_delay` 1 (`framethreads` 1 before FFmpeg
|
||||
5.0). Every frame's picture comes out of the call that decoded it, except
|
||||
what B-frames reorder.
|
||||
- The self-test (`ffmpeg::decoder::probe()`, once per process, every decoder
|
||||
on a thread of its own, at the same time as the encoders' probe in
|
||||
`Codecs::new()`): each decoder decodes a three-frame clip of its codec
|
||||
(`src/ffmpeg/clips/`, a keyframe and two frames that predict from it, of a
|
||||
test picture at 320x240 made by our own encoders: `h264_vaapi`,
|
||||
`hevc_vaapi`, `av1_vaapi` and libvpx; `write_self_test_clips`, ignored,
|
||||
writes them again). Every frame must give its picture at once, at its
|
||||
size, above 30 dB against the test picture, and a hardware decoder must
|
||||
have decoded on the GPU: when the GPU lacks the codec, FFmpeg silently
|
||||
decodes in software (VP8 on AMD), which the self-test reports as
|
||||
unusable with FFmpeg's reason, since FFmpeg's software decoder follows
|
||||
in the ladder anyway. NVDEC is not tried without an NVIDIA GPU (the
|
||||
encoders' vendor check). Here the probe takes about 50 ms.
|
||||
- At runtime, when the GPU does not take a stream (a profile or a size it
|
||||
lacks), FFmpeg decodes it in software through the same decoder
|
||||
(`FfmpegDecoder::cpu_pictures`), except AV1, which FFmpeg decodes only in
|
||||
hardware: that is an error, and the pipeline's ladder moves on to dav1d.
|
||||
|
||||
`voelinctl stream encoders` lists the decoders with their self-test
|
||||
results and each codec's ladder. On the Radeon RX 7900 GRE with FFmpeg
|
||||
9.0.1:
|
||||
|
||||
| Codec | Ladder | Not used |
|
||||
|---|---|---|
|
||||
| AV1 | `av1_vaapi` > `libdav1d` > `libaom-av1` | `av1_nvdec` (no NVIDIA GPU), `dav1d` (built without `av1`) |
|
||||
| HEVC | `hevc_vaapi` > `hevc` | `hevc_nvdec` |
|
||||
| VP9 | `vp9_vaapi` > `vp9` > `libvpx` | `vp9_nvdec` |
|
||||
| H.264 | `h264_vaapi` > `h264` (> `openh264` once loaded) | `h264_nvdec` |
|
||||
| VP8 | `vp8` > `libvpx` | `vp8_vaapi` (the GPU has no VP8 decoder: "No support for codec vp8 profile"), `vp8_nvdec` |
|
||||
|
||||
### RTMP output
|
||||
|
||||
The studio's RTMP output ([studio.md](studio.md#outputs-studiooutput))
|
||||
@@ -927,6 +1031,56 @@ self-test: 1920x1080 is sent as 1920x1072, 1366x768 as 1344x768. H.264 has
|
||||
no such problem; its SPS crops whatever the hardware pads (exact at all 12
|
||||
sizes tried, 320x240 to 3440x1440).
|
||||
|
||||
### Decoders, measured
|
||||
|
||||
An H.264 stream with B-frames at 2560x1440 and 60 fps, as the official
|
||||
client sends it (AMF on an AMD GPU: B-frames, a lookahead, keyframes
|
||||
rarely), made with the `ffmpeg` command (x264 `veryfast` with 3 B-frames,
|
||||
`h264_vaapi` with 2; `testsrc2`, 8 Mbit/s, a keyframe every 10 s). Release
|
||||
build, Radeon RX 7900 GRE, FFmpeg 9.0.1, Cisco's OpenH264 2.6.0.
|
||||
|
||||
Decoding as fast as it goes (`tests/ffmpeg_decoders.rs`
|
||||
`h264_with_b_frames_at_1440p60`, `--ignored`): pictures out of 600 frames,
|
||||
pictures per second of decoding (copied into a `VideoFrame`; two runs on
|
||||
a desktop in use), the slowest frame. Both FFmpeg decoders give the same
|
||||
pictures, in order.
|
||||
|
||||
| Decoder | x264 stream | `h264_vaapi` stream |
|
||||
|---|---|---|
|
||||
| `h264_vaapi` | 598, 368-424 fps, 6.8-9.0 ms | 599, 355-398 fps, 4.0-8.8 ms |
|
||||
| `h264` (software) | 598, 276-283 fps, 4.9-8.0 ms | 599, 268-302 fps, 6.6-8.7 ms |
|
||||
| OpenH264 | 8, 592 errors | 8, 592 errors |
|
||||
|
||||
Played in real time into a `VideoPipeline` whose consumer converts every
|
||||
picture to RGBA as the app does (`voelin-core/tests/decode_rate.rs`,
|
||||
`--ignored`), both streams alike:
|
||||
|
||||
| Decoders | No loss | A frame lost every second |
|
||||
|---|---|---|
|
||||
| the ladder (`h264_vaapi`) | 59.9 fps | 58.9 fps (concealed; a keyframe asked for every 500 ms meanwhile) |
|
||||
| OpenH264 alone (the app before FFmpeg's decoders) | 0.8 fps | 0.8 fps |
|
||||
|
||||
OpenH264 does not decode B-frames: every B-frame is an error, and the
|
||||
pipeline then waited for keyframes the encoder sends every few seconds at
|
||||
most. That was the "very bad frame rate" of an official client's stream in
|
||||
the app.
|
||||
|
||||
AV1 at 2560x1440 and 60 fps, which the official client sends from GPUs that
|
||||
encode it (`av1_at_1440p60`, `--ignored`; streams from `av1_vaapi` and
|
||||
SVT-AV1 preset 10, 8 Mbit/s): every decoder gave all 600 pictures, the same
|
||||
as dav1d's.
|
||||
|
||||
| Decoder | `av1_vaapi` stream | SVT-AV1 stream |
|
||||
|---|---|---|
|
||||
| `av1_vaapi` | 309 fps, 11.4 ms | 301 fps, 15.4 ms |
|
||||
| `libdav1d` (8 threads) | 412 fps, 8.6 ms | 426 fps, 31.2 ms |
|
||||
| `libaom-av1` | 240 fps, 24.7 ms | 286 fps, 49.6 ms |
|
||||
|
||||
dav1d on 8 of the 32 cores outruns the GPU here, whose pictures also have to
|
||||
be copied out of it; the ladder still takes the GPU first, for the CPU it
|
||||
leaves free (the rule of the whole project: the best first, the others as
|
||||
fallbacks). Every decoder has 4-7 times the 60 fps it needs.
|
||||
|
||||
### Wayland screen capture, measured
|
||||
|
||||
Same machine, a 2560x1440 Wayland desktop through the ScreenCast portal,
|
||||
@@ -1032,7 +1186,9 @@ test -p voelin-media` (skipped without `DISPLAY`). FFmpeg needs nothing at
|
||||
build time (feature `ffmpeg` only adds `libloading`); its tests run with the
|
||||
runtime libraries installed (`libavcodec60` on Ubuntu 24.04) and are
|
||||
skipped without them; `VOELIN_OPENH264_LIB` lets them decode x264's output
|
||||
with Cisco's OpenH264, `--features av1` AV1 with dav1d.
|
||||
with Cisco's OpenH264, `--features av1` AV1 with dav1d. The decoder tests
|
||||
(`tests/ffmpeg_decoders.rs`, `tests/decoder_alloc.rs`) need the same and an
|
||||
encoder per codec they check (each is skipped without one).
|
||||
|
||||
Windows: libvpx is not found through pkg-config there. Install it (e.g.
|
||||
`vcpkg install libvpx:x64-windows`) and set `VPX_LIB_DIR`, `VPX_INCLUDE_DIR`
|
||||
@@ -1073,6 +1229,15 @@ has not run on Windows yet.
|
||||
| OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) |
|
||||
| H.264 library missing / unknown file | unit + integration tests | tested |
|
||||
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; streams of SVT-AV1, rav1e, libaom, `av1_vaapi` and `av1_amf` decoded (rows below) |
|
||||
| FFmpeg decoders' self-test: every decoder of the build, the clips and the test picture, a GPU decoder that falls back to software reported as unusable | `ffmpeg::decoder::tests`, `tests/ffmpeg_decoders.rs` `probe_reports_every_decoder` | tested on the Radeon RX 7900 GRE: VA-API decodes AV1, HEVC, VP9 and H.264; `vp8_vaapi` reported unusable (the GPU has no VP8 decoder); NVDEC skipped (no NVIDIA GPU) |
|
||||
| Every encoder of the machine → every decoder of its codec (PSNR > 28 dB, every frame a picture) | `tests/ffmpeg_decoders.rs` `every_encoder_decodes_with_every_decoder` | tested: 20 pairs (`av1_vaapi`, SVT-AV1, libaom → `av1_vaapi`, `libdav1d`, `libaom-av1`; `h264_vaapi`, x264 → `h264_vaapi`, `h264`; `hevc_vaapi` → `hevc_vaapi`, `hevc`; libvpx → `vp9_vaapi`, `vp9`, `vp8`, `libvpx`), 36.4-38.1 dB |
|
||||
| VA-API decoding on the GPU (every picture from a VA-API surface, none from FFmpeg's software path), 320x240 and 1920x1080 | `tests/ffmpeg_decoders.rs` `vaapi_decodes_on_the_gpu` | tested: `av1_vaapi`, `hevc_vaapi`, `vp9_vaapi`, `h264_vaapi`; skipped where no VA-API decoder works |
|
||||
| No allocation per picture in any FFmpeg decoder | `tests/decoder_alloc.rs` (counting allocator) | tested: 0 allocations over 30 pictures for each of the ten decoders that work here |
|
||||
| What a viewer accepts with and without FFmpeg (`VOELIN_FFMPEG=0`) | `tests/ffmpeg_decoders.rs` `decoders_with_and_without_ffmpeg` (the second half in a child process) | tested: AV1, HEVC, VP9, H.264, VP8 with FFmpeg; VP9, VP8 (libvpx) without |
|
||||
| A failing decoder replaced by the next of the ladder (errors, or no pictures), pictures going on; after a loss a concealing decoder goes on and one that does not skips to the keyframe, keyframes asked for every 500 ms until one comes | `voelin-core` `media::tests::a_failing_decoder_is_replaced_by_the_next`, `losses_ask_for_keyframes_until_one_comes` | tested (a decoder made to fail ahead of libvpx) |
|
||||
| H.264 with B-frames and AV1 at 1440p60: every decoder, and (H.264) the pipeline in real time with and without losses | `tests/ffmpeg_decoders.rs` `h264_with_b_frames_at_1440p60`, `av1_at_1440p60`, `voelin-core/tests/decode_rate.rs` (all `--ignored`, `--release`) | measured, see [Decoders, measured](#decoders-measured) |
|
||||
| Chromium's AV1, VP9 and H.264 → our viewer → the pipeline, at their size | `voelin-core/tests/browser_codecs.rs` `browser_streams_decode_in_the_pipeline` (`VOELIN_INTEROP=1`, system Chromium 152) | tested: decoded by `av1_vaapi`, `vp9_vaapi`, `h264_vaapi` |
|
||||
| Hardware decoders NVDEC, D3D11VA, DXVA2, VideoToolbox | – | not tested (no such hardware here); NVDEC is skipped by the vendor check, the Windows table type-checks for `x86_64-pc-windows-gnu`, the macOS one is not compiled here |
|
||||
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested |
|
||||
| wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) |
|
||||
| Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested |
|
||||
@@ -1091,7 +1256,7 @@ has not run on Windows yet.
|
||||
| Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) |
|
||||
| x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame |
|
||||
| Hardware encoders VA-API and AMF (H.264, HEVC, AV1) in the streamer pipeline | `voelinctl stream bench` on a Radeon RX 7900 GRE, 1080p60 / 1440p60 / simulcast | tested: full frame rate, 0.20-0.52 cores against 1.16-2.55 for software, 1.02 allocations per encoded frame, every backend within 2 % of the target bitrate once `av1_vaapi` got a two-second buffer (it overshot by 3.5-8 %; see the tables above) |
|
||||
| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is not decoded (no decoder here) |
|
||||
| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is decoded by FFmpeg's decoders in `tests/ffmpeg_decoders.rs` |
|
||||
| The alignment an AV1 encoder pads to, from the sequence header it writes | `ffmpeg::encoder::tests::av1_declared_size_and_alignment` (every optional header field), the self-test on the GPU | tested: (64, 16) for `av1_vaapi` and `av1_amf`, (2, 2) for SVT-AV1, rav1e and libaom |
|
||||
| Hardware encoders NVENC, Quick Sync, Media Foundation, VideoToolbox | – | not tested (no such hardware here); NVENC and Quick Sync are skipped by the vendor check and the Windows code type-checks for `x86_64-pc-windows-gnu` |
|
||||
| H.264 SPS against the offered `profile-level-id` (`profile_idc`, `level_idc`) for every usable backend, two sizes, both profiles | `tests/ffmpeg.rs` `sps_carries_the_offered_profile_and_level` | tested: it found `h264_amf` emitting level 4.2 where the offer said 3.1; with the level now set, all backends emit the offered level |
|
||||
|
||||
@@ -337,6 +337,33 @@ with a new peer, so the connection broke and nothing was shown. Now
|
||||
against Chromium: `browser_renegotiates_with_rust` (VP8, then a re-offer of
|
||||
VP9 on the same connection; VP9 frames arrive).
|
||||
|
||||
### What Voelin accepts from official streamers (2026-10-03)
|
||||
|
||||
The re-offer above came from our answer lacking AV1, and the H.264 the
|
||||
official client then sent decoded badly: its encoder (AMF on the user's
|
||||
AMD GPU, 2560x1440 at 60 fps, 6-9 Mbit/s) uses B-frames and a lookahead
|
||||
(its log prints QP for "IDR / P / B-frames") although the negotiated
|
||||
profile is Constrained High, and asked for a keyframe only twice in the
|
||||
session. Voelin decoded H.264 with Cisco's OpenH264 2.6.0, which does not
|
||||
decode B-frames: in a 1440p60 test stream with B-frames it gave 8 pictures
|
||||
of 600, every B-frame an error, and the viewer then waited for keyframes.
|
||||
|
||||
A Voelin viewer now decodes with FFmpeg first ([media.md](../media.md#ffmpeg-decoders-loaded-at-runtime)):
|
||||
hardware (VA-API on Linux, D3D11VA / DXVA2 on Windows, VideoToolbox on
|
||||
macOS, NVDEC), then FFmpeg's software decoders, then the built-in libvpx,
|
||||
OpenH264 and dav1d. It accepts AV1, HEVC, VP9, H.264 and VP8 wherever one
|
||||
of them works (any FFmpeg build has software HEVC, VP9, H.264 and VP8;
|
||||
AV1 needs dav1d or libaom in it, or a GPU), and answers in the offer's
|
||||
order, so an official client that offers AV1 first gets AV1 back and no
|
||||
longer re-aligns. H.264 no longer depends on OpenH264, and B-frames
|
||||
decode: the same 1440p60 stream plays at 59.9 fps through VA-API, 58.9
|
||||
fps with a frame lost every second (FFmpeg's H.264 decoder conceals the
|
||||
loss while a keyframe is asked for, every half second until one comes),
|
||||
against 0.8 fps with OpenH264. Headless Chromium 152's AV1, VP9 and H.264
|
||||
streams decode in the pipeline at their size (`browser_codecs.rs`
|
||||
`browser_streams_decode_in_the_pipeline`). Watching the official client
|
||||
itself with these decoders is still to be confirmed.
|
||||
|
||||
## Open questions
|
||||
|
||||
- [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above).
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 105 KiB After Width: | Height: | Size: 98 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
+18
-1
@@ -211,6 +211,22 @@ goes to the running capture at once (`Capture::follow_audio`, which calls
|
||||
to add sources to. With sample data `share:live` shares the test pattern
|
||||
with the sample studio's sources, live at once with sample viewers.
|
||||
|
||||
## Adding a server
|
||||
|
||||
The add-server dialog (`BookmarkDialog` in `screens/dialogs.slint`, logic in
|
||||
`servers.rs`) asks for the address (host, host:port, IP or server
|
||||
nickname; the resolver finds the port through SRV records and TSDNS) and
|
||||
an optional server password. *Advanced* (open when editing) has the rest,
|
||||
and empty fields there are filled in: the name is the address until the
|
||||
first connection, then the server's own name (`adopt_server_name`); the
|
||||
nickname is the default identity's (one imported from TeamSpeak keeps its
|
||||
nickname there), else the system user's, else "Voelin user"; the identity is the default one,
|
||||
there is no default channel; the gateway is looked up in DNS when the
|
||||
server is saved without one and when it connects
|
||||
([gateway-admin.md](gateway-admin.md#letting-voelin-find-the-gateway)),
|
||||
and one found is stored as if typed. `bookmark` and `bookmark:edit` open
|
||||
it (below).
|
||||
|
||||
## Adding a screen
|
||||
|
||||
1. Write the screen in `ui/screens/<name>.slint` from the components
|
||||
@@ -273,7 +289,7 @@ Environment variables (see `src/dev.rs`):
|
||||
- `VOELIN_DEMO_UI=1`: sample servers, channels, members, chat with emoji and
|
||||
a stream, without a server (nothing is stored).
|
||||
- `VOELIN_OPEN=<what>[,<what>...]`: `home`, `server`, `settings[:voice|keybinds|streaming|privacy|appearance]`,
|
||||
`about`, `share[:live]`, `bookmark`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`about`, `share[:live]`, `bookmark[:edit]`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`voice`, `pins`, `topics`, `topic:<id>`, `member`, `watch`, `popout`
|
||||
(the server page, above), `tab:<home|servers|chat|activity|you>` (phone
|
||||
layout). With sample data, `watch` plays the local test pattern in the
|
||||
@@ -333,6 +349,7 @@ the window's size so the pointer is not over the window, and passes
|
||||
|---|---|---|---|---|
|
||||
|  |  |  |  |  |
|
||||
|  |  |  |  |  |
|
||||
|  | | | | |
|
||||
|
||||
## Limits
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ TeamSpeak server is involved.
|
||||
| `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus, over `AES_CM_128_HMAC_SHA1_80`. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe |
|
||||
| `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as Constrained Baseline, see below); the browser must decode at least 60 frames at 1280x720 in 3 s. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped |
|
||||
| `share_offer_picks_a_codec_every_client_decodes` (voelin-core) | The offer a share makes on this machine (`preferred_codec`, `peer_config`): the browser, answering with the first codec of the offer it lists as the official client does, must pick one every TeamSpeak client decodes (`decoded_everywhere`), and decode it |
|
||||
| `browser_streams_decode_in_the_pipeline` (voelin-core) | The other way: Chromium sends its canvas (320x240) in AV1, VP9 and H.264 in turn (skipping what it cannot send) to our viewer peer, which accepts what this machine decodes (`peer_config`); the engine's `VideoPipeline` must decode 30 pictures at 320x240 with the first decoder of the codec's ladder (`Codecs::decoders_for`), keyframe requests going to the browser as PLIs |
|
||||
| `browser_renegotiates_with_rust` | Chromium streams VP8, then sends a new offer on the same connection with VP9 first (as the official client re-offers when it does not encode the codec we chose); `Peer::renegotiate` answers on the same peer, in the new offer's codec order; VP9 frames must arrive |
|
||||
| `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` |
|
||||
|
||||
@@ -72,6 +73,9 @@ may do the same; see `docs/protocol-notes/ts6-streaming.md`.
|
||||
0 and 1): it does not answer an offer of Constrained High alone
|
||||
(`640c1f`, what our streamers offer), yet decodes High profile streams
|
||||
when it negotiated another profile (its decoder is FFmpeg's).
|
||||
- Chromium 152 (Arch Linux build, `VOELIN_CHROMIUM=/usr/bin/chromium`) sends
|
||||
AV1, VP9 and H.264; our pipeline decodes all three on the GPU here (AMD,
|
||||
VA-API: `av1_vaapi`, `vp9_vaapi`, `h264_vaapi`), at the canvas's size.
|
||||
- With str0m's bandwidth estimation and pacer on our streamer peer, Chromium's
|
||||
transport-cc feedback yields estimates within the first second (about
|
||||
640 kbit/s rising towards the desired bitrate with the 720 kbit/s synthetic
|
||||
|
||||
@@ -12,7 +12,9 @@ use clap::{Args, Subcommand};
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::capture::synthetic::Pattern;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs};
|
||||
use voelin_core::media::{EncoderPreference, MediaSink, Streamer, StreamerConfig, preferred_codec};
|
||||
use voelin_core::media::{
|
||||
DecoderPreference, EncoderPreference, MediaSink, Streamer, StreamerConfig, preferred_codec,
|
||||
};
|
||||
use voelin_stream::{EncodedFrame, LayerId, LayerSet, LayerSpec, MediaKind};
|
||||
|
||||
use crate::alloc;
|
||||
@@ -29,9 +31,10 @@ enum StreamTool {
|
||||
/// test pattern without a server; print per-stage and per-layer numbers
|
||||
/// and heap allocations per frame.
|
||||
Bench(BenchArgs),
|
||||
/// List the video encoders: the FFmpeg libraries found, every backend
|
||||
/// with its self-test result (or why it cannot be used), and the order
|
||||
/// the streamer would use them in.
|
||||
/// List the video encoders and decoders: the FFmpeg libraries found,
|
||||
/// every backend with its self-test result (or why it cannot be used),
|
||||
/// the order the streamer would use the encoders in, and each codec's
|
||||
/// decoders in the order a viewer tries them.
|
||||
Encoders(EncodersArgs),
|
||||
}
|
||||
|
||||
@@ -44,6 +47,12 @@ struct EncodersArgs {
|
||||
/// Rank without hardware encoders (`stream.hardware_acceleration` off).
|
||||
#[arg(long)]
|
||||
no_hardware: bool,
|
||||
/// Decoder choice to rank by (as the setting `stream.decoder_backend`).
|
||||
#[arg(long, default_value = "auto")]
|
||||
decoder: String,
|
||||
/// Rank without hardware decoders (`stream.hardware_decoding` off).
|
||||
#[arg(long)]
|
||||
no_hardware_decoding: bool,
|
||||
/// Cisco's OpenH264 library, to list it as well.
|
||||
#[arg(long)]
|
||||
openh264: Option<PathBuf>,
|
||||
@@ -128,7 +137,11 @@ fn codecs_for(encoder: &str, no_hardware: bool, openh264: Option<&PathBuf>) -> R
|
||||
}
|
||||
|
||||
fn encoders(args: EncodersArgs) -> Result<()> {
|
||||
let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())?;
|
||||
let codecs = codecs_for(&args.encoder, args.no_hardware, args.openh264.as_ref())?
|
||||
.with_decoder_preference(DecoderPreference {
|
||||
hardware: !args.no_hardware_decoding,
|
||||
backend: args.decoder.parse().unwrap_or_default(),
|
||||
});
|
||||
let report = codecs.report();
|
||||
match &report.ffmpeg {
|
||||
Ok(text) => println!("{text}"),
|
||||
@@ -161,6 +174,27 @@ fn encoders(args: EncodersArgs) -> Result<()> {
|
||||
let order: Vec<String> =
|
||||
codecs.encoders().iter().map(|(codec, backend)| format!("{codec} {backend}")).collect();
|
||||
println!("\nstreamer order: {}", order.join(", "));
|
||||
println!();
|
||||
println!("{:<18} {:<5} {:<17} {:<8} {:<5} status", "decoder", "codec", "api", "kind", "rank");
|
||||
let mut list = report.decoders.clone();
|
||||
list.sort_by_key(|d| (d.status.is_err(), d.codec.name(), d.rank.unwrap_or(usize::MAX)));
|
||||
for d in &list {
|
||||
println!(
|
||||
"{:<18} {:<5} {:<17} {:<8} {:<5} {}",
|
||||
d.name,
|
||||
d.codec.name(),
|
||||
d.api,
|
||||
if d.hardware { "hardware" } else { "software" },
|
||||
d.rank.map_or("-".to_owned(), |r| r.to_string()),
|
||||
d.status.as_ref().err().map_or("ok", String::as_str),
|
||||
);
|
||||
}
|
||||
println!("\nviewer order (each codec's decoders, best first):");
|
||||
for codec in codecs.decoders() {
|
||||
let ladder: Vec<String> =
|
||||
codecs.decoders_for(codec).iter().map(|b| b.to_string()).collect();
|
||||
println!(" {codec}: {}", ladder.join(" > "));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -835,7 +835,7 @@ async fn watch(
|
||||
);
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(100));
|
||||
let mut first_picture = true;
|
||||
let mut last_picture: Option<VideoFrame> = None;
|
||||
let mut last_picture: Option<Arc<VideoFrame>> = None;
|
||||
let summary = |video: u64, audio: u64, decoder: &VideoPipeline| {
|
||||
let stats = decoder.stats();
|
||||
println!(
|
||||
@@ -844,7 +844,7 @@ async fn watch(
|
||||
stats.error.map(|e| format!(" (last error: {e})")).unwrap_or_default()
|
||||
);
|
||||
};
|
||||
let save_last = |last: &Option<VideoFrame>| -> Result<()> {
|
||||
let save_last = |last: &Option<Arc<VideoFrame>>| -> Result<()> {
|
||||
match (save, last) {
|
||||
(Some(path), Some(picture)) => {
|
||||
save_png(picture, path)?;
|
||||
|
||||
Reference in new issue
Block a user