Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a5ecbed1e5dd55ddc
This commit is contained in:
commit
a2333c8223
48 files changed
+4047
-438
No files matched your search
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user